-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureSession.cpp
More file actions
438 lines (413 loc) · 17.2 KB
/
SecureSession.cpp
File metadata and controls
438 lines (413 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#include <nlohmann/json.hpp>
#include "SecureSession.h"
#include "cipher/IAuthenticationPeer.h"
#include "cipher/Spake2p.h"
#include "cipher/EcdhePsk.h"
#include "cipher/HandshakeMessage.h"
#include "schema/IServer.h"
#include "common/Base64.h"
#include "common/UniqueTypes.h"
using namespace TUI;
using namespace TUI::Network;
using namespace TUI::Application;
using namespace TUI::Application::SecureSession;
namespace
{
class EncryptionCodec : public IMessageCodec
{
public:
EncryptionCodec(
Cipher::ChaCha20Poly1305::Encryptor encryptor,
Cipher::ChaCha20Poly1305::Decryptor decryptor)
: _encryptor(std::move(encryptor)), _decryptor(std::move(decryptor))
{
}
~EncryptionCodec() override = default;
EncryptionCodec(const EncryptionCodec&) = delete;
EncryptionCodec& operator=(const EncryptionCodec&) = delete;
EncryptionCodec(EncryptionCodec&&) = delete;
EncryptionCodec& operator=(EncryptionCodec&&) = delete;
std::vector<std::uint8_t> Encode(const std::vector<std::uint8_t>& data) override
{
return _encryptor.Encrypt(data);
}
std::vector<std::uint8_t> Decode(const std::vector<std::uint8_t>& data) override
{
return _decryptor.Decrypt(data);
}
private:
Cipher::ChaCha20Poly1305::Encryptor _encryptor;
Cipher::ChaCha20Poly1305::Decryptor _decryptor;
};
}
/** Session */
Connection::Connection(
std::shared_ptr<IConnection<void>> connection,
const CallerId& callerId,
std::function<void(CallerId)> onClose,
const std::vector<std::shared_ptr<IMessageCodec>>& messageCodecs)
: _connection(std::move(connection)), _callerId(callerId), _onClose(std::move(onClose)),
_messageCodecs(messageCodecs)
{
if (_connection == nullptr)
{
throw std::invalid_argument("Connection cannot be null");
}
if (_onClose == nullptr)
{
throw std::invalid_argument("onClose callback cannot be null");
}
}
Connection::~Connection()
{
Close();
}
void Connection::Close()
{
if (_closed)
{
return;
}
_closed = true;
_connection->Close();
_onClose(_callerId);
}
bool Connection::IsClosed() const noexcept
{
return _closed;
}
void Connection::Send(std::vector<std::uint8_t> message)
{
if (IsClosed())
{
throw std::runtime_error("Connection is closed");
}
for (const auto& codec : _messageCodecs)
{
message = codec->Encode(message);
}
_connection->Send(std::move(message));
}
JS::Promise<std::optional<std::vector<std::uint8_t>>> Connection::ReceiveAsync()
{
if (IsClosed())
{
throw std::runtime_error("Connection is closed");
}
auto dataOpt = co_await _connection->ReceiveAsync();
if (!dataOpt.has_value())
{
Close();
co_return std::nullopt;
}
auto data = std::move(dataOpt.value());
for (auto it = _messageCodecs.rbegin(); it != _messageCodecs.rend(); ++it)
{
data = (*it)->Decode(data);
}
co_return std::move(data);
}
CallerId Connection::GetId() const
{
return _callerId;
}
/** Server */
std::shared_ptr<IServer<CallerId>> Server::Create(
Tev& tev,
std::shared_ptr<IServer<void>> server,
GetUserCredentialFunc getUserCredential,
const std::vector<std::shared_ptr<IMessageCodec>>& messageCodecs)
{
return std::shared_ptr<Server>(new Server(tev, server, getUserCredential, messageCodecs));
}
Server::Server(
Tev& tev,
std::shared_ptr<IServer<void>> server,
GetUserCredentialFunc getUserCredential,
const std::vector<std::shared_ptr<IMessageCodec>>& messageCodecs)
: _tev(tev), _server(server), _getUserCredential(getUserCredential), _messageCodecs(messageCodecs)
{
if (server == nullptr || getUserCredential == nullptr)
{
throw std::invalid_argument("Server and getUserCredential cannot be null");
}
/** Fire the raw connection handle loop */
HandleRawConnections();
}
Server::~Server()
{
Close();
}
void Server::Close()
{
if (_closed)
{
return;
}
_closed = true;
/** Clear all resumption timeouts */
_resumptionKeyTimeouts.clear();
/** Clear all resumption keys so the timeouts do not get set during close */
_sessionResumptionKeys.clear();
/**
* Explicitly closing all connections.
* Closeing the server should do so too.
*/
for (auto item = _connections.begin(); item != _connections.end();)
{
/** Erase first to avoid recursive callback. */
item->second->Close();
item = _connections.erase(item);
}
if (_server)
{
_server->Close();
}
_connectionGenerator.Finish();
}
bool Server::IsClosed() const noexcept
{
return _closed;
}
JS::Promise<std::optional<std::shared_ptr<IConnection<CallerId>>>> Server::AcceptAsync()
{
if (IsClosed())
{
throw std::runtime_error("Server is closed");
}
return _connectionGenerator.NextAsync();
}
JS::Promise<void> Server::HandleRawConnections()
{
while (true)
{
auto connectionOpt = co_await _server->AcceptAsync();
if (!connectionOpt.has_value())
{
break;
}
auto connection = connectionOpt.value();
/** Fire handshake session */
HandleHandshakeAsync(connection);
}
Close();
}
JS::Promise<void> Server::HandleHandshakeAsync(std::shared_ptr<IConnection<void>> connection)
{
/**
* 10s handshake timeout
* This will not leak on exit.
* As the connection will be closed when the server is closed.
* And the receive loop will break and clear the timeout.
*/
std::optional<std::string> usernameOpt;
try
{
auto handshakeTimeout = _tev.SetTimeout(
[connection]() {
connection->Close();
}, AUTH_TIMEOUT_MS);
std::shared_ptr<Cipher::IAuthenticationPeer> auth{nullptr};
/**
* This will generate both the userId and the connectionId.'
* The userId should be replaced by the real userId after authentication.
*/
CallerId callerId{};
while (true)
{
auto dataOpt = co_await connection->ReceiveAsync();
if (!dataOpt.has_value())
{
throw std::runtime_error("Connection closed before handshake completion");
}
auto data = std::move(dataOpt.value());
if (auth == nullptr || !auth->IsHandshakeComplete())
{
/** authentication messages */
auto message = Cipher::HandshakeMessage::Message::Parse(data);
if (auth == nullptr)
{
/** First message, create auth from the ProtocolType */
auto protocolTypeElementOpt = message.GetElement(Cipher::HandshakeMessage::Type::ProtocolType);
if (!protocolTypeElementOpt.has_value())
{
throw std::runtime_error("ProtocolType element is missing in the handshake message");
}
auto protocolTypeElement = std::move(protocolTypeElementOpt.value());
if (protocolTypeElement.size() != sizeof(ProtocolType))
{
throw std::runtime_error("Invalid ProtocolType element size");
}
auto protocolType = static_cast<ProtocolType>(protocolTypeElement[0]);
switch (protocolType)
{
case ProtocolType::Password:
auth = std::make_shared<Cipher::Spake2p::Server>([this, &callerId, &usernameOpt](const std::string& username) -> Cipher::Spake2p::RegistrationResult {
Cipher::Spake2p::RegistrationResult result;
auto pairOpt = _getUserCredential(username);
if (!pairOpt.has_value())
{
/** invalid username. However, we need to trick the attacker to do the computational heavy handshake. */
result = _fakeCredentialGenerator.GetFakeCredential(username);
}
else
{
/** valid username */
if (_bruteForceLimiter.IsBlocked(username))
{
/**
* The current username is under attack.
* We need to provide the correct salt to the attacker to not leaking this is a valid username.
* But the other credentials should be fake.
*/
result = _fakeCredentialGenerator.GetFakeCredential(username);
auto pair = std::move(pairOpt.value());
auto userCredential = nlohmann::json::parse(pair.first).get<Schema::IServer::UserCredential>();
result.salt = Common::Base64::Decode<sizeof(result.salt)>(userCredential.get_salt());
}
else
{
auto pair = std::move(pairOpt.value());
auto userCredential = nlohmann::json::parse(pair.first).get<Schema::IServer::UserCredential>();
result.w0 = Common::Base64::Decode<sizeof(result.w0)>(userCredential.get_w0());
result.L = Common::Base64::Decode<sizeof(result.L)>(userCredential.get_l());
result.salt = Common::Base64::Decode<sizeof(result.salt)>(userCredential.get_salt());
callerId.userId = pair.second;
}
usernameOpt = username;
}
return result;
});
break;
case ProtocolType::Psk:
auth = std::make_shared<Cipher::EcdhePsk::Server>([this, &callerId](const std::vector<uint8_t>& keyIndex) -> Cipher::EcdhePsk::Psk {
auto keyIndexStr = std::string(keyIndex.begin(), keyIndex.end());
auto timeoutItem = _resumptionKeyTimeouts.find(keyIndexStr);
if (timeoutItem != _resumptionKeyTimeouts.end())
{
_resumptionKeyTimeouts.erase(timeoutItem);
}
auto item = _sessionResumptionKeys.find(keyIndexStr);
if (item == _sessionResumptionKeys.end())
{
throw std::runtime_error("PSK not found for the given key index");
}
auto pair = std::move(item->second);
_sessionResumptionKeys.erase(item);
callerId = pair.second;
return pair.first;
});
break;
default:
throw std::runtime_error("Unknown protocol type");
}
}
auto replyOpt = auth->GetNextMessage(message);
if (replyOpt.has_value())
{
auto replyData = replyOpt->Serialize();
connection->Send(std::move(replyData));
}
}
else
{
/**
* There are cases where the caller id is not set to a valid value when the username is not valid or blocked.
* But it is almost impossible to reach here by passing the handshake with a fake credential.
* So no further checks are implemented.
*/
/** authentication pass. This message would be the protocol negotiation message */
Cipher::ChaCha20Poly1305::Decryptor decryptor{auth->GetClientKey()};
auto plainTextBytes = decryptor.Decrypt(data);
std::string plainText(plainTextBytes.begin(), plainTextBytes.end());
auto negotiationRequest = nlohmann::json::parse(plainText).get<Schema::IServer::ProtocolNegotiationRequest>();
/** Close any session with the same callerId (in case of a valid resumption) */
auto item = _connections.find(callerId);
if (item != _connections.end())
{
auto oldConnection = item->second;
_connections.erase(item);
oldConnection->Close();
}
/** Regenerate connection id */
callerId.connectionId = Common::Uuid{};
/** Generate resumption keys */
Common::Uuid resumptionKeyIndex{};
auto resumptionKey = Cipher::EcdhePsk::GeneratePsk();
Schema::IServer::ProtocolNegotiationResponse negotiationResponse;
negotiationResponse.set_session_resumption_key_index(static_cast<std::string>(resumptionKeyIndex));
negotiationResponse.set_session_resumption_key(Common::Base64::Encode(resumptionKey));
negotiationResponse.set_was_under_attack(false);
if (usernameOpt.has_value())
{
bool wasUnderAttack = _bruteForceLimiter.LogValidLogin(usernameOpt.value());
negotiationResponse.set_was_under_attack(wasUnderAttack);
/** Avoid following exceptions to trigger the invalid login log */
usernameOpt.reset();
}
_sessionResumptionKeys.emplace(
static_cast<std::string>(resumptionKeyIndex),
std::make_pair(resumptionKey, callerId));
/** Reply negotiation. This will always be encrypted no matter how turnOffEncryption is set */
auto negotiationResponseStr = static_cast<nlohmann::json>(negotiationResponse).dump();
std::vector<uint8_t> negotiationResponseBytes(negotiationResponseStr.begin(), negotiationResponseStr.end());
Cipher::ChaCha20Poly1305::Encryptor encryptor{auth->GetServerKey()};
auto negotiationResponseCipher = encryptor.Encrypt(negotiationResponseBytes);
connection->Send(std::move(negotiationResponseCipher));
/** Create the secure connection */
std::weak_ptr<Server> weakThis = shared_from_this();
std::vector<std::shared_ptr<IMessageCodec>> codecs = _messageCodecs;
if (!negotiationRequest.get_turn_off_encryption())
{
codecs.push_back(std::make_shared<EncryptionCodec>(std::move(encryptor), std::move(decryptor)));
}
auto secureConnection = std::shared_ptr<Connection>(new Connection(
std::move(connection),
callerId,
[weakThis, resumptionKeyIndex](CallerId id) {
auto self = weakThis.lock();
if (!self)
{
return;
}
self->_connections.erase(id);
/** If the resumption key exists, set a timeout */
auto resumptionKeyIndexStr = static_cast<std::string>(resumptionKeyIndex);
auto item = self->_sessionResumptionKeys.find(resumptionKeyIndexStr);
if (item == self->_sessionResumptionKeys.end())
{
return;
}
auto resumptionKeyTimeout = self->_tev.SetTimeout(
[weakThis, resumptionKeyIndexStr]() {
auto self = weakThis.lock();
if (!self)
{
return;
}
self->_resumptionKeyTimeouts.erase(resumptionKeyIndexStr);
self->_sessionResumptionKeys.erase(resumptionKeyIndexStr);
}, RESUMPTION_KEY_TIMEOUT_MS);
self->_resumptionKeyTimeouts.emplace(
resumptionKeyIndexStr,
std::move(resumptionKeyTimeout));
},
std::move(codecs)));
_connections.emplace(callerId, secureConnection);
/** Add the connection to the generator */
_connectionGenerator.Feed(secureConnection);
break;
}
}
}
catch(...)
{
if (usernameOpt.has_value())
{
/** Invalid login attempt for this username */
_bruteForceLimiter.LogInvalidLogin(usernameOpt.value());
}
/** Under any error, close the connection */
connection->Close();
}
}