Debian Codegraph @

srtcore/crypto.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 /*****************************************************************************
12 written by
13 Haivision Systems Inc.
14 *****************************************************************************/
15
16 #include "platform_sys.h"
17
18 #include <cstring>
19 #include <string>
20 #include <sstream>
21 #include <iterator>
22
23 #include "udt.h"
24 #include "utilities.h"
25 #include <haicrypt.h>
26 #include "crypto.h"
27 #include "logging.h"
28 #include "core.h"
29 #include "api.h"
30
31 using namespace srt_logging;
32
33 #define SRT_MAX_KMRETRY 10
34
35 //#define SRT_CMD_KMREQ 3 /* HaiCryptTP SRT Keying Material */
36 //#define SRT_CMD_KMRSP 4 /* HaiCryptTP SRT Keying Material ACK */
37 #define SRT_CMD_KMREQ_SZ HCRYPT_MSG_KM_MAX_SZ /* */
38 #if SRT_CMD_KMREQ_SZ > SRT_CMD_MAXSZ
39 #error SRT_CMD_MAXSZ too small
40 #endif
41 /* Key Material Request (Network Order)
42 See HaiCryptTP SRT (hcrypt_xpt_srt.c)
43 */
44
45 // 10* HAICRYPT_DEF_KM_PRE_ANNOUNCE
46 const int SRT_CRYPT_KM_PRE_ANNOUNCE SRT_ATR_UNUSED = 0x10000;
47
48 namespace srt_logging
49 {
50 std::string KmStateStr(SRT_KM_STATE state)
51 {
52 switch (state)
53 {
54 #define TAKE(val) case SRT_KM_S_##val : return #val
55 TAKE(UNSECURED);
56 TAKE(SECURED);
57 TAKE(SECURING);
58 TAKE(NOSECRET);
59 TAKE(BADSECRET);
60 #ifdef ENABLE_AEAD_API_PREVIEW
61 TAKE(BADCRYPTOMODE);
62 #endif
63 #undef TAKE
64 default:
65 {
66 char buf[256];
67 #if defined(_MSC_VER) && _MSC_VER < 1900
68 _snprintf(buf, sizeof(buf) - 1, "??? (%d)", state);
69 #else
70 snprintf(buf, sizeof(buf), "??? (%d)", state);
71 #endif
72 return buf;
73 }
74 }
75 }
76 } // namespace
77
78 using srt_logging::KmStateStr;
79
80 void srt::CCryptoControl::globalInit()
81 {
82 #ifdef SRT_ENABLE_ENCRYPTION
83 // We need to force the Cryspr to be initialized during startup to avoid the
84 // possibility of multiple threads initializing the same static data later on.
85 HaiCryptCryspr_Get_Instance();
86 #endif
87 }
88
89 bool srt::CCryptoControl::isAESGCMSupported()
90 {
91 #ifdef SRT_ENABLE_ENCRYPTION
92 return HaiCrypt_IsAESGCM_Supported() != 0;
93 #else
94 return false;
95 #endif
96 }
97
98 #if ENABLE_LOGGING
99 std::string srt::CCryptoControl::FormatKmMessage(std::string hdr, int cmd, size_t srtlen)
100 {
101 std::ostringstream os;
102 os << hdr << ": cmd=" << cmd << "(" << (cmd == SRT_CMD_KMREQ ? "KMREQ":"KMRSP") <<") len="
103 << size_t(srtlen*sizeof(int32_t)) << " KmState: SND="
104 << KmStateStr(m_SndKmState)
105 << " RCV=" << KmStateStr(m_RcvKmState);
106 return os.str();
107 }
108 #endif
109
110 void srt::CCryptoControl::updateKmState(int cmd, size_t srtlen SRT_ATR_UNUSED)
111 {
112 if (cmd == SRT_CMD_KMREQ)
113 {
114 if ( SRT_KM_S_UNSECURED == m_SndKmState)
115 {
116 m_SndKmState = SRT_KM_S_SECURING;
117 }
118 LOGP(cnlog.Note, FormatKmMessage("sendSrtMsg", cmd, srtlen));
119 }
120 else
121 {
122 LOGP(cnlog.Note, FormatKmMessage("sendSrtMsg", cmd, srtlen));
123 }
124 }
125
126 void srt::CCryptoControl::createFakeSndContext()
127 {
128 if (!m_iSndKmKeyLen)
129 m_iSndKmKeyLen = 16;
130
131 if (!createCryptoCtx((m_hSndCrypto), m_iSndKmKeyLen, HAICRYPT_CRYPTO_DIR_TX, false))
132 {
133 HLOGC(cnlog.Debug, log << "Error: Can't create fake crypto context for sending - sending will return ERROR!");
134 m_hSndCrypto = 0;
135 }
136 }
137
138 int srt::CCryptoControl::processSrtMsg_KMREQ(
139 const uint32_t* srtdata SRT_ATR_UNUSED,
140 size_t bytelen SRT_ATR_UNUSED,
141 int hsv SRT_ATR_UNUSED, unsigned srtv SRT_ATR_UNUSED,
142 uint32_t pw_srtdata_out[], size_t& w_srtlen)
143 {
144 //Receiver
145 /* All 32-bit msg fields swapped on reception
146 * But HaiCrypt expect network order message
147 * Re-swap to cancel it.
148 */
149 #ifdef SRT_ENABLE_ENCRYPTION
150 w_srtlen = bytelen/sizeof(srtdata[SRT_KMR_KMSTATE]);
151 HtoNLA((pw_srtdata_out), srtdata, w_srtlen);
152 unsigned char* kmdata = reinterpret_cast<unsigned char*>(pw_srtdata_out);
153
154 // The side that has received KMREQ is always an HSD_RESPONDER, regardless of
155 // what has called this function. The HSv5 handshake only enforces bidirectional
156 // connection.
157
158 const bool bidirectional = hsv > CUDT::HS_VERSION_UDT4;
159
160 // Local macro to return rejection appropriately.
161 // CHANGED. The first version made HSv5 reject the connection.
162 // This isn't well handled by applications, so the connection is
163 // still established, but unable to handle any transport.
164 //#define KMREQ_RESULT_REJECTION() if (bidirectional) { return SRT_CMD_NONE; } else { w_srtlen = 1; goto HSv4_ErrorReport; }
165 #define KMREQ_RESULT_REJECTION() { w_srtlen = 1; goto HSv4_ErrorReport; }
166
167 int rc = HAICRYPT_OK; // needed before 'goto' run from KMREQ_RESULT_REJECTION macro
168 bool wasb4 SRT_ATR_UNUSED = false;
169 size_t sek_len = 0;
170
171 const bool bUseGCM =
172 (m_iCryptoMode == CSrtConfig::CIPHER_MODE_AUTO && kmdata[HCRYPT_MSG_KM_OFS_CIPHER] == HCRYPT_CIPHER_AES_GCM) ||
173 (m_iCryptoMode == CSrtConfig::CIPHER_MODE_AES_GCM);
174
175 m_bUseGcm153 = srtv <= SrtVersion(1, 5, 3);
176
177 // What we have to do:
178 // If encryption is on (we know that by having m_KmSecret nonempty), create
179 // the crypto context (if bidirectional, create for both sending and receiving).
180 // Both crypto contexts should be set with the same length of the key.
181 // The problem with interpretinting this should be reported as SRT_CMD_NONE,
182 // should be appropriately handled by the caller, as it expects that this
183 // function normally return SRT_CMD_KMRSP.
184 if ( bytelen <= HCRYPT_MSG_KM_OFS_SALT ) //Sanity on message
185 {
186 LOGC(cnlog.Error, log << "processSrtMsg_KMREQ: size of the KM (" << bytelen << ") is too small, must be >" << HCRYPT_MSG_KM_OFS_SALT);
187 m_RcvKmState = SRT_KM_S_BADSECRET;
188 KMREQ_RESULT_REJECTION();
189 }
190
191 HLOGC(cnlog.Debug, log << "KMREQ: getting SEK and creating receiver crypto");
192 sek_len = hcryptMsg_KM_GetSekLen(kmdata);
193 if ( sek_len == 0 )
194 {
195 LOGC(cnlog.Error, log << "processSrtMsg_KMREQ: Received SEK is empty - REJECTING!");
196 m_RcvKmState = SRT_KM_S_BADSECRET;
197 KMREQ_RESULT_REJECTION();
198 }
199
200 // Write the key length
201 m_iRcvKmKeyLen = sek_len;
202 // Overwrite the key length anyway - it doesn't make sense to somehow
203 // keep the original setting because it will only make KMX impossible.
204 #if ENABLE_HEAVY_LOGGING
205 if (m_iSndKmKeyLen != m_iRcvKmKeyLen)
206 {
207 LOGC(cnlog.Debug, log << "processSrtMsg_KMREQ: Agent's PBKEYLEN=" << m_iSndKmKeyLen
208 << " overwritten by Peer's PBKEYLEN=" << m_iRcvKmKeyLen);
209 }
210 #endif
211 m_iSndKmKeyLen = m_iRcvKmKeyLen;
212
213 // This is checked only now so that the SRTO_PBKEYLEN return always the correct value,
214 // even if encryption is not possible because Agent didn't set a password, or supplied
215 // a wrong password.
216 if (m_KmSecret.len == 0) //We have a shared secret <==> encryption is on
217 {
218 LOGC(cnlog.Warn, log << "processSrtMsg_KMREQ: Agent does not declare encryption - won't decrypt incoming packets!");
219 m_RcvKmState = SRT_KM_S_NOSECRET;
220 KMREQ_RESULT_REJECTION();
221 }
222 wasb4 = m_hRcvCrypto;
223
224 if (!createCryptoCtx((m_hRcvCrypto), m_iRcvKmKeyLen, HAICRYPT_CRYPTO_DIR_RX, bUseGCM))
225 {
226 LOGC(cnlog.Error, log << "processSrtMsg_KMREQ: Can't create RCV CRYPTO CTX - must reject...");
227 m_RcvKmState = SRT_KM_S_NOSECRET;
228 KMREQ_RESULT_REJECTION();
229 }
230
231 // Deduce resulting mode.
232 m_iCryptoMode = bUseGCM ? CSrtConfig::CIPHER_MODE_AES_GCM : CSrtConfig::CIPHER_MODE_AES_CTR;
233
234 if (!wasb4)
235 {
236 HLOGC(cnlog.Debug, log << "processSrtMsg_KMREQ: created RX ENC with KeyLen=" << m_iRcvKmKeyLen);
237 }
238 // We have both sides set with password, so both are pending for security
239 m_RcvKmState = SRT_KM_S_SECURING;
240 // m_SndKmState is set to SECURING or UNSECURED in init(),
241 // or it might have been set to SECURED, NOSECRET or BADSECRET in the previous
242 // handshake iteration (handshakes may be sent multiple times for the same connection).
243
244 rc = HaiCrypt_Rx_Process(m_hRcvCrypto, kmdata, bytelen, NULL, NULL, 0);
245 switch(rc >= 0 ? HAICRYPT_OK : rc)
246 {
247 case HAICRYPT_OK:
248 m_RcvKmState = SRT_KM_S_SECURED;
249 HLOGC(cnlog.Debug, log << "KMREQ/rcv: (snd) Rx process successful - SECURED.");
250 //Send back the whole message to confirm
251 break;
252 case HAICRYPT_ERROR_WRONG_SECRET: //Unmatched shared secret to decrypt wrapped key
253 m_RcvKmState = m_SndKmState = SRT_KM_S_BADSECRET;
254 //Send status KMRSP message to tel error
255 w_srtlen = 1;
256 LOGC(cnlog.Warn, log << "KMREQ/rcv: (snd) Rx process failure - BADSECRET");
257 break;
258 case HAICRYPT_ERROR_CIPHER:
259 #ifdef ENABLE_AEAD_API_PREVIEW
260 m_RcvKmState = m_SndKmState = SRT_KM_S_BADCRYPTOMODE;
261 #else
262 m_RcvKmState = m_SndKmState = SRT_KM_S_BADSECRET; // Use "bad secret" as a fallback.
263 #endif
264 w_srtlen = 1;
265 LOGC(cnlog.Warn, log << "KMREQ/rcv: (snd) Rx process failure - BADCRYPTOMODE");
266 break;
267 case HAICRYPT_ERROR: //Other errors
268 default:
269 m_RcvKmState = m_SndKmState = SRT_KM_S_NOSECRET;
270 w_srtlen = 1;
271 LOGC(cnlog.Warn, log << "KMREQ/rcv: (snd) Rx process failure (IPE) - NOSECRET");
272 break;
273 }
274
275 LOGP(cnlog.Note, FormatKmMessage("processSrtMsg_KMREQ", SRT_CMD_KMREQ, bytelen));
276
277 // Since now, when CCryptoControl::decrypt() encounters an error, it will print it, ONCE,
278 // until the next KMREQ is received as a key regeneration.
279 m_bErrorReported = false;
280
281 if (w_srtlen == 1)
282 goto HSv4_ErrorReport;
283
284 // Configure the sender context also, if it succeeded to configure the
285 // receiver context and we are using bidirectional mode.
286 if (bidirectional)
287 {
288 // Note: 'bidirectional' means that we want a bidirectional key update,
289 // which happens only and exclusively with HSv5 handshake - not when the
290 // usual key update through UMSG_EXT+SRT_CMD_KMREQ was done (which is used
291 // in HSv4 versions also to initialize the first key, unlike HSv5).
292 if (m_RcvKmState == SRT_KM_S_SECURED)
293 {
294 if (m_SndKmState == SRT_KM_S_SECURING && !m_hSndCrypto)
295 {
296 m_iSndKmKeyLen = m_iRcvKmKeyLen;
297 if (HaiCrypt_Clone(m_hRcvCrypto, HAICRYPT_CRYPTO_DIR_TX, &m_hSndCrypto) != HAICRYPT_OK)
298 {
299 LOGC(cnlog.Error, log << "processSrtMsg_KMREQ: Can't create SND CRYPTO CTX - WILL NOT SEND-ENCRYPT correctly!");
300 if (hasPassphrase())
301 m_SndKmState = SRT_KM_S_BADSECRET;
302 else
303 m_SndKmState = SRT_KM_S_NOSECRET;
304 }
305 else
306 {
307 m_SndKmState = SRT_KM_S_SECURED;
308 }
309
310 LOGC(cnlog.Note, log << FormatKmMessage("processSrtMsg_KMREQ", SRT_CMD_KMREQ, bytelen)
311 << " SndKeyLen=" << m_iSndKmKeyLen
312 << " TX CRYPTO CTX CLONED FROM RX"
313 );
314
315 // Write the KM message into the field from which it will be next sent.
316 memcpy((m_SndKmMsg[0].Msg), kmdata, bytelen);
317 m_SndKmMsg[0].MsgLen = bytelen;
318 m_SndKmMsg[0].iPeerRetry = 0; // Don't start sending them upon connection :)
319 }
320 else
321 {
322 HLOGC(cnlog.Debug, log << "processSrtMsg_KMREQ: NOT cloning RX to TX crypto: already in "
323 << KmStateStr(m_SndKmState) << " state");
324 }
325 }
326 else
327 {
328 HLOGP(cnlog.Debug, "processSrtMsg_KMREQ: NOT SECURED - not replaying failed security association to TX CRYPTO CTX");
329 }
330 }
331 else
332 {
333 HLOGC(cnlog.Debug, log << "processSrtMsg_KMREQ: NOT REPLAYING the key update to TX CRYPTO CTX.");
334 }
335
336 #ifdef SRT_ENABLE_ENCRYPTION
337 if (m_hRcvCrypto != NULL)
338 HaiCrypt_UpdateGcm153(m_hRcvCrypto, m_bUseGcm153);
339 if (m_hSndCrypto != NULL)
340 HaiCrypt_UpdateGcm153(m_hSndCrypto, m_bUseGcm153);
341 #endif
342
343 return SRT_CMD_KMRSP;
344
345 HSv4_ErrorReport:
346
347 if (bidirectional && hasPassphrase())
348 {
349 // If the Forward KMX process has failed, the reverse-KMX process was not done at all.
350 // This will lead to incorrect object configuration and will fail to properly declare
351 // the transmission state.
352 // Create the "fake crypto" with the passphrsae you currently have.
353 createFakeSndContext();
354 }
355 #undef KMREQ_RESULT_REJECTION
356
357 #else
358 // It's ok that this is reported as error because this happens in a scenario,
359 // when non-encryption-enabled SRT application is contacted by encryption-enabled SRT
360 // application which tries to make a security association.
361 LOGC(cnlog.Warn, log << "processSrtMsg_KMREQ: Encryption not enabled at compile time - must reject...");
362 m_RcvKmState = SRT_KM_S_NOSECRET;
363 #endif
364
365 w_srtlen = 1;
366
367 pw_srtdata_out[SRT_KMR_KMSTATE] = m_RcvKmState;
368 return SRT_CMD_KMRSP;
369 }
370
371 int srt::CCryptoControl::processSrtMsg_KMRSP(const uint32_t* srtdata, size_t len, unsigned srtv)
372 {
373 /* All 32-bit msg fields (if present) swapped on reception
374 * But HaiCrypt expect network order message
375 * Re-swap to cancel it.
376 */
377 uint32_t srtd[SRTDATA_MAXSIZE];
378 size_t srtlen = len/sizeof(uint32_t);
379 HtoNLA(srtd, srtdata, srtlen);
380
381 int retstatus = -1;
382
383 // Since now, when CCryptoControl::decrypt() encounters an error, it will print it, ONCE,
384 // until the next KMREQ is received as a key regeneration.
385 m_bErrorReported = false;
386
387 if (srtlen == 1) // Error report. Set accordingly.
388 {
389 SRT_KM_STATE peerstate = SRT_KM_STATE(srtd[SRT_KMR_KMSTATE]); /* Bad or no passphrase */
390 m_SndKmMsg[0].iPeerRetry = 0;
391 m_SndKmMsg[1].iPeerRetry = 0;
392
393 switch (peerstate)
394 {
395 case SRT_KM_S_BADSECRET:
396 m_SndKmState = m_RcvKmState = SRT_KM_S_BADSECRET;
397 retstatus = -1;
398 break;
399
400 // Default embraces two cases:
401 // NOSECRET: this KMRSP was sent by secured Peer, but Agent supplied no password.
402 // UNSECURED: this KMRSP was sent by unsecure Peer because Agent sent KMREQ.
403
404 case SRT_KM_S_NOSECRET:
405 // This means that the peer did not set the password, while Agent did.
406 m_RcvKmState = SRT_KM_S_UNSECURED;
407 m_SndKmState = SRT_KM_S_NOSECRET;
408 retstatus = -1;
409 break;
410
411 case SRT_KM_S_UNSECURED:
412 // This means that KMRSP was sent without KMREQ, to inform the Agent,
413 // that the Peer, unlike Agent, does use password. Agent can send then,
414 // but can't decrypt what Peer would send.
415 m_RcvKmState = SRT_KM_S_NOSECRET;
416 m_SndKmState = SRT_KM_S_UNSECURED;
417 retstatus = 0;
418 break;
419 #ifdef ENABLE_AEAD_API_PREVIEW
420 case SRT_KM_S_BADCRYPTOMODE:
421 // The peer expects to use a different cryptographic mode (e.g. AES-GCM, not AES-CTR).
422 m_RcvKmState = SRT_KM_S_BADCRYPTOMODE;
423 m_SndKmState = SRT_KM_S_BADCRYPTOMODE;
424 retstatus = -1;
425 break;
426 #endif
427
428 default:
429 LOGC(cnlog.Fatal, log << "processSrtMsg_KMRSP: IPE: unknown peer error state: "
430 << KmStateStr(peerstate) << " (" << int(peerstate) << ")");
431 m_RcvKmState = SRT_KM_S_NOSECRET;
432 m_SndKmState = SRT_KM_S_NOSECRET;
433 retstatus = -1; //This is IPE
434 break;
435 }
436
437 LOGC(cnlog.Warn, log << "processSrtMsg_KMRSP: received failure report. STATE: " << KmStateStr(m_RcvKmState));
438 }
439 else
440 {
441 HLOGC(cnlog.Debug, log << "processSrtMsg_KMRSP: received key response len=" << len);
442 // XXX INSECURE << ": [" << FormatBinaryString((uint8_t*)srtd, len) << "]";
443 bool key1 = getKmMsg_acceptResponse(0, srtd, len);
444 bool key2 = true;
445 if ( !key1 )
446 key2 = getKmMsg_acceptResponse(1, srtd, len); // <--- NOTE SEQUENCING!
447
448 if (key1 || key2)
449 {
450 m_SndKmState = m_RcvKmState = SRT_KM_S_SECURED;
451 HLOGC(cnlog.Debug, log << "processSrtMsg_KMRSP: KM response matches " << (key1 ? "EVEN" : "ODD") << " key");
452 retstatus = 1;
453 }
454 else
455 {
456 retstatus = -1;
457 LOGC(cnlog.Error, log << "processSrtMsg_KMRSP: IPE??? KM response key matches no key");
458 /* XXX INSECURE
459 LOGC(cnlog.Error, log << "processSrtMsg_KMRSP: KM response: [" << FormatBinaryString((uint8_t*)srtd, len)
460 << "] matches no key 0=[" << FormatBinaryString((uint8_t*)m_SndKmMsg[0].Msg, m_SndKmMsg[0].MsgLen)
461 << "] 1=[" << FormatBinaryString((uint8_t*)m_SndKmMsg[1].Msg, m_SndKmMsg[1].MsgLen) << "]");
462 */
463
464 m_SndKmState = m_RcvKmState = SRT_KM_S_BADSECRET;
465 }
466 HLOGC(cnlog.Debug, log << "processSrtMsg_KMRSP: key[0]: len=" << m_SndKmMsg[0].MsgLen << " retry=" << m_SndKmMsg[0].iPeerRetry
467 << "; key[1]: len=" << m_SndKmMsg[1].MsgLen << " retry=" << m_SndKmMsg[1].iPeerRetry);
468
469 m_bUseGcm153 = srtv <= SrtVersion(1, 5, 3);
470 #ifdef SRT_ENABLE_ENCRYPTION
471 if (m_hRcvCrypto != NULL)
472 HaiCrypt_UpdateGcm153(m_hRcvCrypto, m_bUseGcm153);
473 if (m_hSndCrypto != NULL)
474 HaiCrypt_UpdateGcm153(m_hSndCrypto, m_bUseGcm153);
475 #endif
476 }
477
478 LOGP(cnlog.Note, FormatKmMessage("processSrtMsg_KMRSP", SRT_CMD_KMRSP, len));
479
480 return retstatus;
481 }
482
483 void srt::CCryptoControl::sendKeysToPeer(CUDT* sock SRT_ATR_UNUSED, int iSRTT SRT_ATR_UNUSED)
484 {
485 sync::ScopedLock lck(m_mtxLock);
486 if (!m_hSndCrypto || m_SndKmState == SRT_KM_S_UNSECURED)
487 {
488 HLOGC(cnlog.Debug, log << "sendKeysToPeer: NOT sending/regenerating keys: "
489 << (m_hSndCrypto ? "CONNECTION UNSECURED" : "NO TX CRYPTO CTX created"));
490 return;
491 }
492 #ifdef SRT_ENABLE_ENCRYPTION
493 srt::sync::steady_clock::time_point now = srt::sync::steady_clock::now();
494 /*
495 * Crypto Key Distribution to peer:
496 * If...
497 * - we want encryption; and
498 * - we have not tried more than CSRTCC_MAXRETRY times (peer may not be SRT); and
499 * - and did not get answer back from peer; and
500 * - last sent Keying Material req should have been replied (RTT*1.5 elapsed);
501 * then (re-)send handshake request.
502 */
503 if (((m_SndKmMsg[0].iPeerRetry > 0) || (m_SndKmMsg[1].iPeerRetry > 0))
504 && ((m_SndKmLastTime + srt::sync::microseconds_from((iSRTT * 3)/2)) <= now))
505 {
506 for (int ki = 0; ki < 2; ki++)
507 {
508 if (m_SndKmMsg[ki].iPeerRetry > 0 && m_SndKmMsg[ki].MsgLen > 0)
509 {
510 m_SndKmMsg[ki].iPeerRetry--;
511 HLOGC(cnlog.Debug, log << "sendKeysToPeer: SENDING ki=" << ki << " len=" << m_SndKmMsg[ki].MsgLen
512 << " retry(updated)=" << m_SndKmMsg[ki].iPeerRetry);
513 m_SndKmLastTime = now;
514 sock->sendSrtMsg(SRT_CMD_KMREQ, (uint32_t *)m_SndKmMsg[ki].Msg, m_SndKmMsg[ki].MsgLen / sizeof(uint32_t));
515 }
516 }
517 }
518 #endif
519 }
520
521 void srt::CCryptoControl::regenCryptoKm(CUDT* sock SRT_ATR_UNUSED, bool bidirectional SRT_ATR_UNUSED)
522 {
523 #ifdef SRT_ENABLE_ENCRYPTION
524 sync::ScopedLock lck(m_mtxLock);
525 if (!m_hSndCrypto)
526 return;
527
528 void *out_p[2];
529 size_t out_len_p[2];
530 int nbo = HaiCrypt_Tx_ManageKeys(m_hSndCrypto, out_p, out_len_p, 2);
531 int sent = 0;
532
533 HLOGC(cnlog.Debug, log << "regenCryptoKm: regenerating crypto keys nbo=" << nbo <<
534 " THEN=" << (sock ? "SEND" : "KEEP") << " DIR=" << (bidirectional ? "BOTH" : "SENDER"));
535
536 for (int i = 0; i < nbo && i < 2; i++)
537 {
538 /*
539 * New connection keying material
540 * or regenerated after crypto_cfg.km_refresh_rate_pkt packets .
541 * Send to peer
542 */
543 // XXX Need to make it clearer and less hardcoded values
544 int kix = hcryptMsg_KM_GetKeyIndex((unsigned char *)(out_p[i]));
545 int ki = kix & 0x1;
546 if ((out_len_p[i] != m_SndKmMsg[ki].MsgLen)
547 || (0 != memcmp(out_p[i], m_SndKmMsg[ki].Msg, m_SndKmMsg[ki].MsgLen)))
548 {
549
550 uint8_t* oldkey SRT_ATR_UNUSED = m_SndKmMsg[ki].Msg;
551 HLOGC(cnlog.Debug, log << "new key[" << ki << "] index=" << kix
552 << " OLD=[" << m_SndKmMsg[ki].MsgLen << "]"
553 << FormatBinaryString(m_SndKmMsg[ki].Msg, m_SndKmMsg[ki].MsgLen)
554 << " NEW=[" << out_len_p[i] << "]"
555 << FormatBinaryString((const uint8_t*)out_p[i], out_len_p[i]));
556
557 /* New Keying material, send to peer */
558 memcpy((m_SndKmMsg[ki].Msg), out_p[i], out_len_p[i]);
559 m_SndKmMsg[ki].MsgLen = out_len_p[i];
560 m_SndKmMsg[ki].iPeerRetry = SRT_MAX_KMRETRY;
561
562 if (bidirectional && !sock)
563 {
564 // "Send" this key also to myself, just to be applied to the receiver crypto,
565 // exactly the same way how this key is interpreted on the peer side into its receiver crypto
566 int rc = HaiCrypt_Rx_Process(m_hRcvCrypto, m_SndKmMsg[ki].Msg, m_SndKmMsg[ki].MsgLen, NULL, NULL, 0);
567 if ( rc < 0 )
568 {
569 LOGC(cnlog.Fatal, log << "regenCryptoKm: IPE: applying key generated in snd crypto into rcv crypto: failed code=" << rc);
570 // The party won't be able to decrypt incoming data!
571 // Not sure if anything has to be reported.
572 }
573 }
574
575 if (sock)
576 {
577 HLOGC(cnlog.Debug, log << "regenCryptoKm: SENDING ki=" << ki << " len=" << m_SndKmMsg[ki].MsgLen
578 << " retry(updated)=" << m_SndKmMsg[ki].iPeerRetry);
579 sock->sendSrtMsg(SRT_CMD_KMREQ, (uint32_t *)m_SndKmMsg[ki].Msg, m_SndKmMsg[ki].MsgLen / sizeof(uint32_t));
580 sent++;
581 }
582 }
583 else if (out_len_p[i] == 0)
584 {
585 HLOGC(cnlog.Debug, log << "no key[" << ki << "] index=" << kix << ": not generated");
586 }
587 else
588 {
589 HLOGC(cnlog.Debug, log << "no key[" << ki << "] index=" << kix << ": key unchanged");
590 }
591 }
592
593 HLOGC(cnlog.Debug, log << "regenCryptoKm: key[0]: len=" << m_SndKmMsg[0].MsgLen << " retry=" << m_SndKmMsg[0].iPeerRetry
594 << "; key[1]: len=" << m_SndKmMsg[1].MsgLen << " retry=" << m_SndKmMsg[1].iPeerRetry);
595
596 if (sent)
597 m_SndKmLastTime = srt::sync::steady_clock::now();
598 #endif
599 }
600
601 srt::CCryptoControl::CCryptoControl(SRTSOCKET id)
602 : m_SocketID(id)
603 , m_iSndKmKeyLen(0)
604 , m_iRcvKmKeyLen(0)
605 , m_SndKmState(SRT_KM_S_UNSECURED)
606 , m_RcvKmState(SRT_KM_S_UNSECURED)
607 , m_KmRefreshRatePkt(0)
608 , m_KmPreAnnouncePkt(0)
609 , m_iCryptoMode(CSrtConfig::CIPHER_MODE_AUTO)
610 , m_bUseGcm153(false)
611 , m_bErrorReported(false)
612 {
613 m_KmSecret.len = 0;
614 //send
615 m_SndKmMsg[0].MsgLen = 0;
616 m_SndKmMsg[0].iPeerRetry = 0;
617 m_SndKmMsg[1].MsgLen = 0;
618 m_SndKmMsg[1].iPeerRetry = 0;
619 m_hSndCrypto = NULL;
620 //recv
621 m_hRcvCrypto = NULL;
622 }
623
624 bool srt::CCryptoControl::init(HandshakeSide side, const CSrtConfig& cfg, bool bidirectional SRT_ATR_UNUSED, bool bUseGcm153 SRT_ATR_UNUSED)
625 {
626 // NOTE: initiator creates m_hSndCrypto. When bidirectional,
627 // it creates also m_hRcvCrypto with the same key length.
628 // Acceptor creates nothing - it will create appropriate
629 // contexts when receiving KMREQ from the initiator.
630
631 HLOGC(cnlog.Debug, log << "CCryptoControl::init: HS SIDE:"
632 << (side == HSD_INITIATOR ? "INITIATOR" : "RESPONDER")
633 << " DIRECTION:" << (bidirectional ? "BOTH" : (side == HSD_INITIATOR) ? "SENDER" : "RECEIVER"));
634
635 // Set UNSECURED state as default
636 m_RcvKmState = SRT_KM_S_UNSECURED;
637 m_iCryptoMode = cfg.iCryptoMode;
638 m_bUseGcm153 = bUseGcm153;
639
640 #ifdef SRT_ENABLE_ENCRYPTION
641 if (!cfg.bTSBPD && m_iCryptoMode == CSrtConfig::CIPHER_MODE_AUTO)
642 m_iCryptoMode = CSrtConfig::CIPHER_MODE_AES_CTR;
643 const bool bUseGCM = m_iCryptoMode == CSrtConfig::CIPHER_MODE_AES_GCM;
644
645 if (bUseGCM && !isAESGCMSupported())
646 {
647 LOGC(cnlog.Warn, log << "CCryptoControl: AES GCM is not supported by the crypto service provider.");
648 return false;
649 }
650 #endif
651
652 // Set security-pending state, if a password was set.
653 m_SndKmState = hasPassphrase() ? SRT_KM_S_SECURING : SRT_KM_S_UNSECURED;
654
655 m_KmPreAnnouncePkt = cfg.uKmPreAnnouncePkt;
656 m_KmRefreshRatePkt = cfg.uKmRefreshRatePkt;
657
658 if (side == HSD_INITIATOR)
659 {
660 if (hasPassphrase())
661 {
662 #ifdef SRT_ENABLE_ENCRYPTION
663 if (m_iSndKmKeyLen == 0)
664 {
665 HLOGC(cnlog.Debug, log << "CCryptoControl::init: PBKEYLEN still 0, setting default 16");
666 m_iSndKmKeyLen = 16;
667 }
668
669 bool ok = createCryptoCtx((m_hSndCrypto), m_iSndKmKeyLen, HAICRYPT_CRYPTO_DIR_TX, bUseGCM);
670 HLOGC(cnlog.Debug, log << "CCryptoControl::init: creating SND crypto context: " << ok);
671
672 if (ok && bidirectional)
673 {
674 m_iRcvKmKeyLen = m_iSndKmKeyLen;
675 const int st = HaiCrypt_Clone(m_hSndCrypto, HAICRYPT_CRYPTO_DIR_RX, &m_hRcvCrypto);
676 HLOGC(cnlog.Debug, log << "CCryptoControl::init: creating CLONED RCV crypto context: status=" << st);
677 ok = st == 0;
678 }
679
680 // Note: this is sanity check, it should never happen.
681 if (!ok)
682 {
683 m_SndKmState = SRT_KM_S_NOSECRET; // wanted to secure, but error occurred.
684 if (bidirectional)
685 m_RcvKmState = SRT_KM_S_NOSECRET;
686
687 return false;
688 }
689
690 regenCryptoKm(
691 NULL, // Do not send the key (the KM msg will be attached to the HSv5 handshake)
692 bidirectional // replicate the key to the receiver context, if bidirectional
693 );
694
695 m_iCryptoMode = bUseGCM ? CSrtConfig::CIPHER_MODE_AES_GCM : CSrtConfig::CIPHER_MODE_AES_CTR;
696 #else
697 // This error would be a consequence of setting the passphrase, while encryption
698 // is turned off at compile time. Setting the password itself should be not allowed
699 // so this could only happen as a consequence of an IPE.
700 LOGC(cnlog.Error, log << "CCryptoControl::init: IPE: encryption not supported");
701 return false;
702 #endif
703 }
704 else
705 {
706 HLOGC(cnlog.Debug, log << "CCryptoControl::init: CAN'T CREATE crypto: key length for SND = " << m_iSndKmKeyLen);
707 }
708 }
709 else
710 {
711 HLOGC(cnlog.Debug, log << "CCryptoControl::init: NOT creating crypto contexts - will be created upon reception of KMREQ");
712 }
713
714 return true;
715 }
716
717 void srt::CCryptoControl::close()
718 {
719 /* Wipeout secrets */
720 sync::ScopedLock lck(m_mtxLock);
721 memset(&m_KmSecret, 0, sizeof(m_KmSecret));
722 }
723
724 std::string srt::CCryptoControl::CONID() const
725 {
726 if (m_SocketID == 0)
727 return "";
728
729 std::ostringstream os;
730 os << "@" << m_SocketID << ":";
731
732 return os.str();
733 }
734
735 #ifdef SRT_ENABLE_ENCRYPTION
736
737 #if ENABLE_HEAVY_LOGGING
738 namespace srt {
739 static std::string CryptoFlags(int flg)
740 {
741 using namespace std;
742
743 vector<string> f;
744 if (flg & HAICRYPT_CFG_F_CRYPTO)
745 f.push_back("crypto");
746 if (flg & HAICRYPT_CFG_F_TX)
747 f.push_back("TX");
748 if (flg & HAICRYPT_CFG_F_FEC)
749 f.push_back("fec");
750
751 ostringstream os;
752 copy(f.begin(), f.end(), ostream_iterator<string>(os, "|"));
753 return os.str();
754 }
755 } // namespace srt
756 #endif // ENABLE_HEAVY_LOGGING
757
758 bool srt::CCryptoControl::createCryptoCtx(HaiCrypt_Handle& w_hCrypto, size_t keylen, HaiCrypt_CryptoDir cdir, bool bAESGCM)
759 {
760 if (w_hCrypto)
761 {
762 // XXX You can check here if the existing handle represents
763 // a correctly defined crypto. But this doesn't seem to be
764 // necessary - the whole CCryptoControl facility seems to be valid only
765 // within the frames of one connection.
766 return true;
767 }
768
769 if ((m_KmSecret.len <= 0) || (keylen <= 0))
770 {
771 LOGC(cnlog.Error, log << CONID() << "cryptoCtx: IPE missing secret (" << m_KmSecret.len << ") or key length (" << keylen << ")");
772 return false;
773 }
774
775 HaiCrypt_Cfg crypto_cfg;
776 memset(&crypto_cfg, 0, sizeof(crypto_cfg));
777 #if 0//test key refresh (fast rate)
778 m_KmRefreshRatePkt = 2000;
779 m_KmPreAnnouncePkt = 500;
780 #endif
781 crypto_cfg.flags = HAICRYPT_CFG_F_CRYPTO | (cdir == HAICRYPT_CRYPTO_DIR_TX ? HAICRYPT_CFG_F_TX : 0) | (bAESGCM ? HAICRYPT_CFG_F_GCM : 0);
782 crypto_cfg.xport = HAICRYPT_XPT_SRT;
783 crypto_cfg.cryspr = HaiCryptCryspr_Get_Instance();
784 crypto_cfg.key_len = (size_t)keylen;
785 crypto_cfg.data_max_len = HAICRYPT_DEF_DATA_MAX_LENGTH; //MTU
786 crypto_cfg.km_tx_period_ms = 0;//No HaiCrypt KM inject period, handled in SRT;
787 crypto_cfg.km_refresh_rate_pkt = m_KmRefreshRatePkt == 0 ? HAICRYPT_DEF_KM_REFRESH_RATE : m_KmRefreshRatePkt;
788 crypto_cfg.km_pre_announce_pkt = m_KmPreAnnouncePkt == 0 ? SRT_CRYPT_KM_PRE_ANNOUNCE : m_KmPreAnnouncePkt;
789 crypto_cfg.secret = m_KmSecret;
790
791 HLOGC(cnlog.Debug, log << "CRYPTO CFG: flags=" << CryptoFlags(crypto_cfg.flags) << " xport=" << crypto_cfg.xport << " cryspr=" << crypto_cfg.cryspr
792 << " keylen=" << crypto_cfg.key_len << " passphrase_length=" << crypto_cfg.secret.len);
793
794 if (HaiCrypt_Create(&crypto_cfg, (&w_hCrypto)) != HAICRYPT_OK)
795 {
796 LOGC(cnlog.Error, log << CONID() << "cryptoCtx: could not create " << (cdir == HAICRYPT_CRYPTO_DIR_TX ? "tx" : "rx") << " crypto ctx");
797 return false;
798 }
799
800 HLOGC(cnlog.Debug, log << CONID() << "cryptoCtx: CREATED crypto for dir=" << (cdir == HAICRYPT_CRYPTO_DIR_TX ? "tx" : "rx") << " keylen=" << keylen);
801
802 return true;
803 }
804 #else
805 bool srt::CCryptoControl::createCryptoCtx(HaiCrypt_Handle&, size_t, HaiCrypt_CryptoDir, bool)
806 {
807 return false;
808 }
809 #endif // SRT_ENABLE_ENCRYPTION
810
811
812 srt::EncryptionStatus srt::CCryptoControl::encrypt(CPacket& w_packet SRT_ATR_UNUSED)
813 {
814 #ifdef SRT_ENABLE_ENCRYPTION
815 // Encryption not enabled - do nothing.
816 if ( getSndCryptoFlags() == EK_NOENC )
817 return ENCS_CLEAR;
818
819 // Note that in case of GCM the header has to zero Retransmitted Packet Flag (R).
820 // If TSBPD is disabled, timestamp also has to be zeroed.
821 int rc = HaiCrypt_Tx_Data(m_hSndCrypto, ((uint8_t*)w_packet.getHeader()), ((uint8_t*)w_packet.m_pcData), w_packet.getLength());
822 if (rc < 0)
823 {
824 return ENCS_FAILED;
825 }
826 else if (rc > 0)
827 {
828 // XXX what happens if the encryption is said to be "succeeded",
829 // but the length is 0? Shouldn't this be treated as unwanted?
830 w_packet.setLength(rc);
831 }
832
833 return ENCS_CLEAR;
834 #else
835 return ENCS_NOTSUP;
836 #endif
837 }
838
839 srt::EncryptionStatus srt::CCryptoControl::decrypt(CPacket& w_packet SRT_ATR_UNUSED)
840 {
841 #ifdef SRT_ENABLE_ENCRYPTION
842 if (w_packet.getMsgCryptoFlags() == EK_NOENC)
843 {
844 HLOGC(cnlog.Debug, log << "CPacket::decrypt: packet not encrypted");
845 return ENCS_CLEAR; // not encrypted, no need do decrypt, no flags to be modified
846 }
847
848 if (m_RcvKmState == SRT_KM_S_UNSECURED)
849 {
850 if (m_KmSecret.len != 0)
851 {
852 // We were unaware that the peer has set password,
853 // but now here we are.
854 m_RcvKmState = SRT_KM_S_SECURING;
855 LOGC(cnlog.Note, log << "SECURITY UPDATE: Peer has surprised Agent with encryption, but KMX is pending - current packet size="
856 << w_packet.getLength() << " dropped");
857 return ENCS_FAILED;
858 }
859 else
860 {
861 // Peer has set a password, but Agent did not,
862 // which means that it will be unable to decrypt
863 // sent payloads anyway.
864 m_RcvKmState = SRT_KM_S_NOSECRET;
865 LOGP(cnlog.Warn, "SECURITY FAILURE: Agent has no PW, but Peer sender has declared one, can't decrypt");
866 // This only informs about the state change; it will be also caught by the condition below
867 }
868 }
869
870 if (m_RcvKmState != SRT_KM_S_SECURED)
871 {
872 // If not "secured", it means that it won't be able to decrypt packets,
873 // so there's no point to even try to send them to HaiCrypt_Rx_Data.
874 // Actually the current conditions concerning m_hRcvCrypto are such that this object
875 // is created in case of SRT_KM_S_BADSECRET, so it will simply fail to decrypt,
876 // but with SRT_KM_S_NOSECRET m_hRcvCrypto is not even created (is NULL), which
877 // will then cause an error to be reported, misleadingly. Simply don't try to
878 // decrypt anything as long as you are not sure that the connection is secured.
879
880 // This problem will occur every time a packet comes in, it's worth reporting,
881 // but not with every single packet arriving. Print it once and turn off the flag;
882 // it will be restored at the next attempt of KMX.
883 if (!m_bErrorReported)
884 {
885 m_bErrorReported = true;
886 LOGC(cnlog.Error, log << "SECURITY STATUS: " << KmStateStr(m_RcvKmState) << " - can't decrypt w_packet.");
887 }
888 HLOGC(cnlog.Debug, log << "Packet still not decrypted, status=" << KmStateStr(m_RcvKmState)
889 << " - dropping size=" << w_packet.getLength());
890 return ENCS_FAILED;
891 }
892
893 const int rc = HaiCrypt_Rx_Data(m_hRcvCrypto, ((uint8_t *)w_packet.getHeader()), ((uint8_t *)w_packet.m_pcData), w_packet.getLength());
894 if (rc <= 0)
895 {
896 LOGC(cnlog.Note, log << "decrypt ERROR: HaiCrypt_Rx_Data failure=" << rc << " - returning failed decryption");
897 // -1: decryption failure
898 // 0: key not received yet
899 return ENCS_FAILED;
900 }
901 // Otherwise: rc == decrypted text length.
902 w_packet.setLength(rc); /* In case clr txt size is different from cipher txt */
903
904 // Decryption succeeded. Update flags.
905 w_packet.setMsgCryptoFlags(EK_NOENC);
906
907 HLOGC(cnlog.Debug, log << "decrypt: successfully decrypted, resulting length=" << rc);
908 return ENCS_CLEAR;
909 #else
910 return ENCS_NOTSUP;
911 #endif
912 }
913
914
915 srt::CCryptoControl::~CCryptoControl()
916 {
917 #ifdef SRT_ENABLE_ENCRYPTION
918 close();
919 if (m_hSndCrypto)
920 {
921 HaiCrypt_Close(m_hSndCrypto);
922 }
923
924 if (m_hRcvCrypto)
925 {
926 HaiCrypt_Close(m_hRcvCrypto);
927 }
928 #endif
929 }