forked from microsoft/msquic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.c
2498 lines (2184 loc) · 78.4 KB
/
crypto.c
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
Abstract:
This file contains all the state and logic for the cryptographic handshake.
This abstracts dealing with TLS 1.3 messages, as a multiple, serial streams
of bytes. Each stream of bytes is secured with a different encryption key.
QUIC_CRYPTO represents the multiple streams as a single contiguous buffer
internally, and keeps tracks of the offsets at which each different stream
starts (and therefore where the previous stream ends).
Many of the internals of QUIC_CRYPTO are similar to QUIC_STREAM. This
includes ACK tracking and receive buffer reassembly.
--*/
#include "precomp.h"
#ifdef QUIC_CLOG
#include "crypto.c.clog.h"
#endif
CXPLAT_TLS_RECEIVE_TP_CALLBACK QuicConnReceiveTP;
CXPLAT_TLS_RECEIVE_TICKET_CALLBACK QuicConnRecvResumptionTicket;
CXPLAT_TLS_PEER_CERTIFICATE_RECEIVED_CALLBACK QuicConnPeerCertReceived;
CXPLAT_TLS_CALLBACKS QuicTlsCallbacks = {
QuicConnReceiveTP,
QuicConnRecvResumptionTicket,
QuicConnPeerCertReceived
};
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoDumpSendState(
_In_ QUIC_CRYPTO* Crypto
)
{
if (QuicTraceLogVerboseEnabled()) {
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
QuicTraceLogConnVerbose(
CryptoDump,
Connection,
"QS:%u MAX:%u UNA:%u NXT:%u RECOV:%u-%u",
Crypto->TlsState.BufferTotalLength,
Crypto->MaxSentLength,
Crypto->UnAckedOffset,
Crypto->NextSendOffset,
Crypto->InRecovery ? Crypto->RecoveryNextOffset : 0,
Crypto->InRecovery ? Crypto->RecoveryEndOffset : 0);
uint64_t UnAcked = Crypto->UnAckedOffset;
uint32_t i = 0;
QUIC_SUBRANGE* Sack;
while ((Sack = QuicRangeGetSafe(&Crypto->SparseAckRanges, i++)) != NULL) {
QuicTraceLogConnVerbose(
CryptoDumpUnacked,
Connection,
" unACKed: [%llu, %llu]",
UnAcked,
Sack->Low);
UnAcked = Sack->Low + Sack->Count;
}
if (UnAcked < (uint64_t)Crypto->MaxSentLength) {
QuicTraceLogConnVerbose(
CryptoDumpUnacked2,
Connection,
" unACKed: [%llu, %u]",
UnAcked,
Crypto->MaxSentLength);
}
CXPLAT_DBG_ASSERT(Crypto->UnAckedOffset <= Crypto->NextSendOffset);
}
}
#if DEBUG
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoValidate(
_In_ const QUIC_CRYPTO* Crypto
)
{
CXPLAT_DBG_ASSERT(Crypto->TlsState.BufferTotalLength >= Crypto->MaxSentLength);
CXPLAT_DBG_ASSERT(Crypto->MaxSentLength >= Crypto->UnAckedOffset);
CXPLAT_DBG_ASSERT(Crypto->MaxSentLength >= Crypto->NextSendOffset);
CXPLAT_DBG_ASSERT(Crypto->MaxSentLength >= Crypto->RecoveryNextOffset);
CXPLAT_DBG_ASSERT(Crypto->MaxSentLength >= Crypto->RecoveryEndOffset);
CXPLAT_DBG_ASSERT(Crypto->NextSendOffset >= Crypto->UnAckedOffset);
CXPLAT_DBG_ASSERT(Crypto->TlsState.BufferLength + Crypto->UnAckedOffset == Crypto->TlsState.BufferTotalLength);
}
#else
#define QuicCryptoValidate(Crypto)
#endif
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
QuicCryptoInitialize(
_Inout_ QUIC_CRYPTO* Crypto
)
{
QUIC_STATUS Status;
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
uint16_t SendBufferLength =
QuicConnIsServer(Connection) ?
QUIC_MAX_TLS_SERVER_SEND_BUFFER : QUIC_MAX_TLS_CLIENT_SEND_BUFFER;
uint16_t InitialRecvBufferLength =
QuicConnIsServer(Connection) ?
QUIC_MAX_TLS_CLIENT_SEND_BUFFER : QUIC_DEFAULT_STREAM_RECV_BUFFER_SIZE;
const uint8_t* HandshakeCid;
uint8_t HandshakeCidLength;
BOOLEAN RecvBufferInitialized = FALSE;
const QUIC_VERSION_INFO* VersionInfo = &QuicSupportedVersionList[0]; // Default to latest
for (uint32_t i = 0; i < ARRAYSIZE(QuicSupportedVersionList); ++i) {
if (QuicSupportedVersionList[i].Number == Connection->Stats.QuicVersion) {
VersionInfo = &QuicSupportedVersionList[i];
break;
}
}
CXPLAT_PASSIVE_CODE();
QuicRangeInitialize(
QUIC_MAX_RANGE_ALLOC_SIZE,
&Crypto->SparseAckRanges);
Crypto->TlsState.BufferAllocLength = SendBufferLength;
Crypto->TlsState.Buffer = CXPLAT_ALLOC_NONPAGED(SendBufferLength, QUIC_POOL_TLS_BUFFER);
if (Crypto->TlsState.Buffer == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"crypto send buffer",
SendBufferLength);
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Exit;
}
QuicRangeInitialize(
QUIC_MAX_RANGE_ALLOC_SIZE,
&Crypto->SparseAckRanges);
Status =
QuicRecvBufferInitialize(
&Crypto->RecvBuffer,
InitialRecvBufferLength,
QUIC_DEFAULT_STREAM_FC_WINDOW_SIZE / 2,
TRUE,
NULL);
if (QUIC_FAILED(Status)) {
goto Exit;
}
RecvBufferInitialized = TRUE;
if (QuicConnIsServer(Connection)) {
CXPLAT_DBG_ASSERT(Connection->SourceCids.Next != NULL);
QUIC_CID_HASH_ENTRY* SourceCid =
CXPLAT_CONTAINING_RECORD(
Connection->SourceCids.Next,
QUIC_CID_HASH_ENTRY,
Link);
HandshakeCid = SourceCid->CID.Data;
HandshakeCidLength = SourceCid->CID.Length;
} else {
CXPLAT_DBG_ASSERT(!CxPlatListIsEmpty(&Connection->DestCids));
QUIC_CID_LIST_ENTRY* DestCid =
CXPLAT_CONTAINING_RECORD(
Connection->DestCids.Flink,
QUIC_CID_LIST_ENTRY,
Link);
HandshakeCid = DestCid->CID.Data;
HandshakeCidLength = DestCid->CID.Length;
}
Status =
QuicPacketKeyCreateInitial(
QuicConnIsServer(Connection),
&VersionInfo->HkdfLabels,
VersionInfo->Salt,
HandshakeCidLength,
HandshakeCid,
&Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL],
&Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL]);
if (QUIC_FAILED(Status)) {
QuicTraceEvent(
ConnErrorStatus,
"[conn][%p] ERROR, %u, %s.",
Connection,
Status,
"Creating initial keys");
goto Exit;
}
CXPLAT_DBG_ASSERT(Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL] != NULL);
CXPLAT_DBG_ASSERT(Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL] != NULL);
Crypto->Initialized = TRUE;
QuicCryptoValidate(Crypto);
Exit:
if (QUIC_FAILED(Status)) {
for (size_t i = 0; i < QUIC_PACKET_KEY_COUNT; ++i) {
QuicPacketKeyFree(Crypto->TlsState.ReadKeys[i]);
Crypto->TlsState.ReadKeys[i] = NULL;
QuicPacketKeyFree(Crypto->TlsState.WriteKeys[i]);
Crypto->TlsState.WriteKeys[i] = NULL;
}
if (RecvBufferInitialized) {
QuicRecvBufferUninitialize(&Crypto->RecvBuffer);
}
if (Crypto->TlsState.Buffer != NULL) {
CXPLAT_FREE(Crypto->TlsState.Buffer, QUIC_POOL_TLS_BUFFER);
Crypto->TlsState.Buffer = NULL;
}
}
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoUninitialize(
_In_ QUIC_CRYPTO* Crypto
)
{
for (size_t i = 0; i < QUIC_PACKET_KEY_COUNT; ++i) {
QuicPacketKeyFree(Crypto->TlsState.ReadKeys[i]);
Crypto->TlsState.ReadKeys[i] = NULL;
QuicPacketKeyFree(Crypto->TlsState.WriteKeys[i]);
Crypto->TlsState.WriteKeys[i] = NULL;
}
if (Crypto->TLS != NULL) {
CxPlatTlsUninitialize(Crypto->TLS);
Crypto->TLS = NULL;
}
if (Crypto->ResumptionTicket != NULL) {
CXPLAT_FREE(Crypto->ResumptionTicket, QUIC_POOL_CRYPTO_RESUMPTION_TICKET);
Crypto->ResumptionTicket = NULL;
}
if (Crypto->TlsState.NegotiatedAlpn != NULL &&
QuicConnIsServer(QuicCryptoGetConnection(Crypto))) {
if (Crypto->TlsState.NegotiatedAlpn != Crypto->TlsState.SmallAlpnBuffer) {
CXPLAT_FREE(Crypto->TlsState.NegotiatedAlpn, QUIC_POOL_ALPN);
}
Crypto->TlsState.NegotiatedAlpn = NULL;
}
if (Crypto->Initialized) {
QuicRecvBufferUninitialize(&Crypto->RecvBuffer);
QuicRangeUninitialize(&Crypto->SparseAckRanges);
CXPLAT_FREE(Crypto->TlsState.Buffer, QUIC_POOL_TLS_BUFFER);
Crypto->TlsState.Buffer = NULL;
Crypto->Initialized = FALSE;
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
QuicCryptoInitializeTls(
_Inout_ QUIC_CRYPTO* Crypto,
_In_ CXPLAT_SEC_CONFIG* SecConfig,
_In_ const QUIC_TRANSPORT_PARAMETERS* Params
)
{
QUIC_STATUS Status;
CXPLAT_TLS_CONFIG TlsConfig = { 0 };
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
BOOLEAN IsServer = QuicConnIsServer(Connection);
CXPLAT_DBG_ASSERT(Params != NULL);
CXPLAT_DBG_ASSERT(SecConfig != NULL);
CXPLAT_DBG_ASSERT(Connection->Configuration != NULL);
Crypto->MaxSentLength = 0;
Crypto->UnAckedOffset = 0;
Crypto->NextSendOffset = 0;
Crypto->RecoveryNextOffset = 0;
Crypto->RecoveryEndOffset = 0;
Crypto->InRecovery = FALSE;
Crypto->TlsState.BufferLength = 0;
Crypto->TlsState.BufferTotalLength = 0;
TlsConfig.IsServer = IsServer;
if (IsServer) {
TlsConfig.AlpnBuffer = Crypto->TlsState.NegotiatedAlpn;
TlsConfig.AlpnBufferLength = 1 + Crypto->TlsState.NegotiatedAlpn[0];
} else {
TlsConfig.AlpnBuffer = Connection->Configuration->AlpnList;
TlsConfig.AlpnBufferLength = Connection->Configuration->AlpnListLength;
}
TlsConfig.SecConfig = SecConfig;
TlsConfig.Connection = Connection;
TlsConfig.ResumptionTicketBuffer = Crypto->ResumptionTicket;
TlsConfig.ResumptionTicketLength = Crypto->ResumptionTicketLength;
if (QuicConnIsClient(Connection)) {
TlsConfig.ServerName = Connection->RemoteServerName;
}
TlsConfig.TlsSecrets = Connection->TlsSecrets;
TlsConfig.HkdfLabels = &QuicSupportedVersionList[0].HkdfLabels; // Default to latest
for (uint32_t i = 0; i < ARRAYSIZE(QuicSupportedVersionList); ++i) {
if (QuicSupportedVersionList[i].Number == Connection->Stats.QuicVersion) {
TlsConfig.HkdfLabels = &QuicSupportedVersionList[i].HkdfLabels;
break;
}
}
TlsConfig.TPType =
Connection->Stats.QuicVersion != QUIC_VERSION_DRAFT_29 ?
TLS_EXTENSION_TYPE_QUIC_TRANSPORT_PARAMETERS :
TLS_EXTENSION_TYPE_QUIC_TRANSPORT_PARAMETERS_DRAFT;
TlsConfig.LocalTPBuffer =
QuicCryptoTlsEncodeTransportParameters(
Connection,
QuicConnIsServer(Connection),
Params,
(Connection->State.TestTransportParameterSet ?
&Connection->TestTransportParameter : NULL),
&TlsConfig.LocalTPLength);
if (TlsConfig.LocalTPBuffer == NULL) {
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
if (Crypto->TLS != NULL) {
CxPlatTlsUninitialize(Crypto->TLS);
Crypto->TLS = NULL;
}
Status = CxPlatTlsInitialize(&TlsConfig, &Crypto->TlsState, &Crypto->TLS);
if (QUIC_FAILED(Status)) {
QuicTraceEvent(
ConnErrorStatus,
"[conn][%p] ERROR, %u, %s.",
Connection,
Status,
"CxPlatTlsInitialize");
CXPLAT_FREE(TlsConfig.LocalTPBuffer, QUIC_POOL_TLS_TRANSPARAMS);
goto Error;
}
Crypto->ResumptionTicket = NULL; // Owned by TLS now.
Crypto->ResumptionTicketLength = 0;
Status = QuicCryptoProcessData(Crypto, !IsServer);
Error:
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoReset(
_In_ QUIC_CRYPTO* Crypto
)
{
CXPLAT_DBG_ASSERT(QuicConnIsClient(QuicCryptoGetConnection(Crypto)));
CXPLAT_TEL_ASSERT(Crypto->RecvTotalConsumed == 0);
Crypto->MaxSentLength = 0;
Crypto->UnAckedOffset = 0;
Crypto->NextSendOffset = 0;
Crypto->RecoveryNextOffset = 0;
Crypto->RecoveryEndOffset = 0;
Crypto->InRecovery = FALSE;
QuicSendSetSendFlag(
&QuicCryptoGetConnection(Crypto)->Send,
QUIC_CONN_SEND_FLAG_CRYPTO);
QuicCryptoValidate(Crypto);
}
QUIC_STATUS
QuicCryptoOnVersionChange(
_In_ QUIC_CRYPTO* Crypto
)
{
QUIC_STATUS Status;
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
const uint8_t* HandshakeCid;
uint8_t HandshakeCidLength;
if (!Crypto->Initialized) {
//
// Crypto is not initialized yet, so no need to set keys.
//
return QUIC_STATUS_SUCCESS;
}
const QUIC_VERSION_INFO* VersionInfo = &QuicSupportedVersionList[0]; // Default to latest
for (uint32_t i = 0; i < ARRAYSIZE(QuicSupportedVersionList); ++i) {
if (QuicSupportedVersionList[i].Number == Connection->Stats.QuicVersion) {
VersionInfo = &QuicSupportedVersionList[i];
break;
}
}
if (QuicConnIsServer(Connection)) {
CXPLAT_DBG_ASSERT(Connection->SourceCids.Next != NULL);
QUIC_CID_HASH_ENTRY* SourceCid =
CXPLAT_CONTAINING_RECORD(
Connection->SourceCids.Next,
QUIC_CID_HASH_ENTRY,
Link);
HandshakeCid = SourceCid->CID.Data;
HandshakeCidLength = SourceCid->CID.Length;
} else {
CXPLAT_DBG_ASSERT(!CxPlatListIsEmpty(&Connection->DestCids));
QUIC_CID_LIST_ENTRY* DestCid =
CXPLAT_CONTAINING_RECORD(
Connection->DestCids.Flink,
QUIC_CID_LIST_ENTRY,
Link);
HandshakeCid = DestCid->CID.Data;
HandshakeCidLength = DestCid->CID.Length;
}
if (Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL] != NULL) {
CXPLAT_FRE_ASSERT(Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL] != NULL);
QuicPacketKeyFree(Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL]);
QuicPacketKeyFree(Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL]);
Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL] = NULL;
Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL] = NULL;
}
Status =
QuicPacketKeyCreateInitial(
QuicConnIsServer(Connection),
&VersionInfo->HkdfLabels,
VersionInfo->Salt,
HandshakeCidLength,
HandshakeCid,
&Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL],
&Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL]);
if (QUIC_FAILED(Status)) {
QuicTraceEvent(
ConnErrorStatus,
"[conn][%p] ERROR, %u, %s.",
Connection,
Status,
"Creating initial keys");
goto Exit;
}
CXPLAT_DBG_ASSERT(Crypto->TlsState.ReadKeys[QUIC_PACKET_KEY_INITIAL] != NULL);
CXPLAT_DBG_ASSERT(Crypto->TlsState.WriteKeys[QUIC_PACKET_KEY_INITIAL] != NULL);
QuicCryptoValidate(Crypto);
Exit:
if (QUIC_FAILED(Status)) {
for (size_t i = 0; i < QUIC_PACKET_KEY_COUNT; ++i) {
QuicPacketKeyFree(Crypto->TlsState.ReadKeys[i]);
Crypto->TlsState.ReadKeys[i] = NULL;
QuicPacketKeyFree(Crypto->TlsState.WriteKeys[i]);
Crypto->TlsState.WriteKeys[i] = NULL;
}
}
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoHandshakeConfirmed(
_In_ QUIC_CRYPTO* Crypto
)
{
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
Connection->State.HandshakeConfirmed = TRUE;
QUIC_PATH* Path = &Connection->Paths[0];
CXPLAT_DBG_ASSERT(Path->Binding != NULL);
QuicBindingOnConnectionHandshakeConfirmed(Path->Binding, Connection);
QuicCryptoDiscardKeys(Crypto, QUIC_PACKET_KEY_HANDSHAKE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
BOOLEAN
QuicCryptoDiscardKeys(
_In_ QUIC_CRYPTO* Crypto,
_In_ QUIC_PACKET_KEY_TYPE KeyType
)
{
if (Crypto->TlsState.WriteKeys[KeyType] == NULL &&
Crypto->TlsState.ReadKeys[KeyType] == NULL) {
//
// The keys have already been discarded.
//
return FALSE;
}
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
QuicTraceLogConnInfo(
DiscardKeyType,
Connection,
"Discarding key type = %hhu",
(uint8_t)KeyType);
QuicPacketKeyFree(Crypto->TlsState.WriteKeys[KeyType]);
QuicPacketKeyFree(Crypto->TlsState.ReadKeys[KeyType]);
Crypto->TlsState.WriteKeys[KeyType] = NULL;
Crypto->TlsState.ReadKeys[KeyType] = NULL;
QUIC_ENCRYPT_LEVEL EncryptLevel = QuicKeyTypeToEncryptLevel(KeyType);
_Analysis_assume_(EncryptLevel >= 0);
if (EncryptLevel >= QUIC_ENCRYPT_LEVEL_1_RTT) {
//
// No additional state clean up required for 1-RTT encrytion level.
//
return TRUE;
}
//
// Clean up send/recv tracking state for the encryption level.
//
CXPLAT_DBG_ASSERT(Connection->Packets[EncryptLevel] != NULL);
BOOLEAN HasAckElicitingPacketsToAcknowledge =
Connection->Packets[EncryptLevel]->AckTracker.AckElicitingPacketsToAcknowledge != 0;
QuicLossDetectionDiscardPackets(&Connection->LossDetection, KeyType);
QuicPacketSpaceUninitialize(Connection->Packets[EncryptLevel]);
Connection->Packets[EncryptLevel] = NULL;
//
// Clean up any possible left over recovery state.
//
uint32_t BufferOffset =
KeyType == QUIC_PACKET_KEY_INITIAL ?
Crypto->TlsState.BufferOffsetHandshake :
Crypto->TlsState.BufferOffset1Rtt;
CXPLAT_DBG_ASSERT(BufferOffset != 0);
CXPLAT_DBG_ASSERT(Crypto->MaxSentLength >= BufferOffset);
if (Crypto->NextSendOffset < BufferOffset) {
Crypto->NextSendOffset = BufferOffset;
}
if (Crypto->RecoveryNextOffset < BufferOffset) {
Crypto->RecoveryNextOffset = BufferOffset;
}
if (Crypto->UnAckedOffset < BufferOffset) {
uint32_t DrainLength = BufferOffset - Crypto->UnAckedOffset;
CXPLAT_DBG_ASSERT(DrainLength <= (uint32_t)Crypto->TlsState.BufferLength);
if ((uint32_t)Crypto->TlsState.BufferLength > DrainLength) {
Crypto->TlsState.BufferLength -= (uint16_t)DrainLength;
CxPlatMoveMemory(
Crypto->TlsState.Buffer,
Crypto->TlsState.Buffer + DrainLength,
Crypto->TlsState.BufferLength);
} else {
Crypto->TlsState.BufferLength = 0;
}
Crypto->UnAckedOffset = BufferOffset;
QuicRangeSetMin(&Crypto->SparseAckRanges, Crypto->UnAckedOffset);
}
if (HasAckElicitingPacketsToAcknowledge) {
QuicSendUpdateAckState(&Connection->Send);
}
QuicCryptoValidate(Crypto);
return TRUE;
}
//
// Send Interfaces
//
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_ENCRYPT_LEVEL
QuicCryptoGetNextEncryptLevel(
_In_ QUIC_CRYPTO* Crypto
)
{
uint64_t SendOffset =
RECOV_WINDOW_OPEN(Crypto) ?
Crypto->RecoveryNextOffset : Crypto->NextSendOffset;
if (Crypto->TlsState.BufferOffset1Rtt != 0 &&
SendOffset >= Crypto->TlsState.BufferOffset1Rtt) {
return QUIC_ENCRYPT_LEVEL_1_RTT;
}
if (Crypto->TlsState.BufferOffsetHandshake != 0 &&
SendOffset >= Crypto->TlsState.BufferOffsetHandshake) {
return QUIC_ENCRYPT_LEVEL_HANDSHAKE;
}
return QUIC_ENCRYPT_LEVEL_INITIAL;
}
//
// Writes data at the requested stream offset to a stream frame.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
_Success_(return != FALSE)
BOOLEAN
QuicCryptoWriteOneFrame(
_In_ QUIC_CRYPTO* Crypto,
_In_ uint32_t EncryptLevelStart,
_In_ uint32_t CryptoOffset,
_Inout_ uint16_t* FramePayloadBytes,
_Inout_ uint16_t* Offset,
_In_ uint16_t BufferLength,
_Out_writes_to_(BufferLength, *Offset) uint8_t* Buffer,
_Inout_ QUIC_SENT_PACKET_METADATA* PacketMetadata
)
{
QuicCryptoValidate(Crypto);
CXPLAT_DBG_ASSERT(*FramePayloadBytes > 0);
CXPLAT_DBG_ASSERT(CryptoOffset >= EncryptLevelStart);
CXPLAT_DBG_ASSERT(CryptoOffset <= Crypto->TlsState.BufferTotalLength);
CXPLAT_DBG_ASSERT(CryptoOffset >= (Crypto->TlsState.BufferTotalLength - Crypto->TlsState.BufferLength));
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
QUIC_CRYPTO_EX Frame = { CryptoOffset - EncryptLevelStart, 0, 0 };
Frame.Data =
Crypto->TlsState.Buffer +
(CryptoOffset - (Crypto->TlsState.BufferTotalLength - Crypto->TlsState.BufferLength));
//
// From the remaining amount of space in the packet, calculate the size of
// the CRYPTO frame header to then determine how much room is left for
// payload.
//
uint16_t HeaderLength = sizeof(uint8_t) + QuicVarIntSize(CryptoOffset);
if (BufferLength < *Offset + HeaderLength + 4) {
QuicTraceLogConnVerbose(
NoMoreRoomForCrypto,
Connection,
"No room for CRYPTO frame");
return FALSE;
}
Frame.Length = BufferLength - *Offset - HeaderLength;
uint16_t LengthFieldByteCount = QuicVarIntSize(Frame.Length);
Frame.Length -= LengthFieldByteCount;
//
// Even if there is room in the buffer, we can't write more data than is
// currently queued.
//
if (Frame.Length > *FramePayloadBytes) {
Frame.Length = *FramePayloadBytes;
}
CXPLAT_DBG_ASSERT(Frame.Length > 0);
*FramePayloadBytes = (uint16_t)Frame.Length;
QuicTraceLogConnVerbose(
AddCryptoFrame,
Connection,
"Sending %hu crypto bytes, offset=%u",
(uint16_t)Frame.Length,
CryptoOffset);
//
// We're definitely writing a frame and we know how many bytes it contains,
// so do the real call to QuicFrameEncodeStreamHeader to write the header.
//
CXPLAT_FRE_ASSERT(
QuicCryptoFrameEncode(&Frame, Offset, BufferLength, Buffer));
PacketMetadata->Flags.IsAckEliciting = TRUE;
PacketMetadata->Frames[PacketMetadata->FrameCount].Type = QUIC_FRAME_CRYPTO;
PacketMetadata->Frames[PacketMetadata->FrameCount].CRYPTO.Offset = CryptoOffset;
PacketMetadata->Frames[PacketMetadata->FrameCount].CRYPTO.Length = (uint16_t)Frame.Length;
PacketMetadata->Frames[PacketMetadata->FrameCount].Flags = 0;
PacketMetadata->FrameCount++;
return TRUE;
}
//
// Writes CRYPTO frames into a packet buffer.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicCryptoWriteCryptoFrames(
_In_ QUIC_CRYPTO* Crypto,
_Inout_ QUIC_PACKET_BUILDER* Builder,
_Inout_ uint16_t* Offset,
_In_ uint16_t BufferLength,
_Out_writes_to_(BufferLength, *Offset) uint8_t* Buffer
)
{
QuicCryptoValidate(Crypto);
//
// Write frames until we've filled the provided space.
//
while (*Offset < BufferLength &&
Builder->Metadata->FrameCount < QUIC_MAX_FRAMES_PER_PACKET) {
//
// Find the bounds of this frame. Left is the offset of the
// first byte in the frame, and Right is the offset of the
// first byte AFTER the frame.
//
uint32_t Left;
uint32_t Right;
BOOLEAN Recovery;
if (RECOV_WINDOW_OPEN(Crypto)) {
Left = Crypto->RecoveryNextOffset;
Recovery = TRUE;
} else {
Left = Crypto->NextSendOffset;
Recovery = FALSE;
}
if (Left == Crypto->TlsState.BufferTotalLength) {
//
// No more data left to send.
//
break;
}
Right = Left + BufferLength - *Offset;
if (Recovery &&
Right > Crypto->RecoveryEndOffset &&
Crypto->RecoveryEndOffset != Crypto->NextSendOffset) {
Right = Crypto->RecoveryEndOffset;
}
//
// Find the first SACK after the selected offset.
//
QUIC_SUBRANGE* Sack;
if (Left == Crypto->MaxSentLength) {
//
// Transmitting new bytes; no such SACK can exist.
//
Sack = NULL;
} else {
uint32_t i = 0;
while ((Sack = QuicRangeGetSafe(&Crypto->SparseAckRanges, i++)) != NULL &&
Sack->Low < (uint64_t)Left) {
CXPLAT_DBG_ASSERT(Sack->Low + Sack->Count <= (uint64_t)Left);
}
}
if (Sack) {
if ((uint64_t)Right > Sack->Low) {
Right = (uint32_t)Sack->Low;
}
} else {
if (Right > Crypto->TlsState.BufferTotalLength) {
Right = Crypto->TlsState.BufferTotalLength;
}
}
CXPLAT_DBG_ASSERT(Right >= Left);
uint32_t EncryptLevelStart;
uint32_t PacketTypeRight;
switch (Builder->PacketType) {
case QUIC_INITIAL:
EncryptLevelStart = 0;
if (Crypto->TlsState.BufferOffsetHandshake != 0) {
PacketTypeRight = Crypto->TlsState.BufferOffsetHandshake;
} else {
PacketTypeRight = Crypto->TlsState.BufferTotalLength;
}
break;
case QUIC_0_RTT_PROTECTED:
CXPLAT_FRE_ASSERT(FALSE);
EncryptLevelStart = 0;
PacketTypeRight = 0; // To get build to stop complaining.
break;
case QUIC_HANDSHAKE:
CXPLAT_DBG_ASSERT(Crypto->TlsState.BufferOffsetHandshake != 0);
CXPLAT_DBG_ASSERT(Left >= Crypto->TlsState.BufferOffsetHandshake);
EncryptLevelStart = Crypto->TlsState.BufferOffsetHandshake;
PacketTypeRight =
Crypto->TlsState.BufferOffset1Rtt == 0 ?
Crypto->TlsState.BufferTotalLength : Crypto->TlsState.BufferOffset1Rtt;
break;
default:
CXPLAT_DBG_ASSERT(Crypto->TlsState.BufferOffset1Rtt != 0);
CXPLAT_DBG_ASSERT(Left >= Crypto->TlsState.BufferOffset1Rtt);
EncryptLevelStart = Crypto->TlsState.BufferOffset1Rtt;
PacketTypeRight = Crypto->TlsState.BufferTotalLength;
break;
}
if (Right > PacketTypeRight) {
Right = PacketTypeRight;
}
if (Left >= Right) {
//
// No more data to write at this encryption level, though we should
// have at least written something. If not, then the logic that
// decided to call this function in the first place is wrong.
//
break;
}
CXPLAT_DBG_ASSERT(Right > Left);
uint16_t FramePayloadBytes = (uint16_t)(Right - Left);
if (!QuicCryptoWriteOneFrame(
Crypto,
EncryptLevelStart,
Left,
&FramePayloadBytes,
Offset,
BufferLength,
Buffer,
Builder->Metadata)) {
//
// No more data could be written.
//
break;
}
//
// FramePayloadBytes may have been reduced.
//
Right = Left + FramePayloadBytes;
//
// Move the "next" offset (RecoveryNextOffset if we are sending
// recovery bytes or NextSendOffset otherwise) forward by the
// number of bytes we've written. If we wrote up to the edge
// of a SACK, skip past the SACK.
//
if (Recovery) {
CXPLAT_DBG_ASSERT(Crypto->RecoveryNextOffset <= Right);
Crypto->RecoveryNextOffset = Right;
if (Sack && (uint64_t)Crypto->RecoveryNextOffset == Sack->Low) {
Crypto->RecoveryNextOffset += (uint32_t)Sack->Count;
}
}
if (Crypto->NextSendOffset < Right) {
Crypto->NextSendOffset = Right;
if (Sack && (uint64_t)Crypto->NextSendOffset == Sack->Low) {
Crypto->NextSendOffset += (uint32_t)Sack->Count;
}
}
if (Crypto->MaxSentLength < Right) {
Crypto->MaxSentLength = Right;
}
QuicCryptoValidate(Crypto);
}
QuicCryptoDumpSendState(Crypto);
QuicCryptoValidate(Crypto);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
BOOLEAN
QuicCryptoWriteFrames(
_In_ QUIC_CRYPTO* Crypto,
_Inout_ QUIC_PACKET_BUILDER* Builder
)
{
CXPLAT_DBG_ASSERT(Builder->Metadata->FrameCount < QUIC_MAX_FRAMES_PER_PACKET);
QUIC_CONNECTION* Connection = QuicCryptoGetConnection(Crypto);
if (!QuicCryptoHasPendingCryptoFrame(Crypto)) {
//
// Likely an ACK after retransmission got us into this state. Just
// remove the send flag and continue on.
//
Connection->Send.SendFlags &= ~QUIC_CONN_SEND_FLAG_CRYPTO;
return TRUE;
}
if (Builder->PacketType !=
QuicEncryptLevelToPacketType(QuicCryptoGetNextEncryptLevel(Crypto))) {
//
// Nothing to send in this packet / encryption level, just continue on.
//
return TRUE;
}
uint8_t PrevFrameCount = Builder->Metadata->FrameCount;
uint16_t AvailableBufferLength =
(uint16_t)Builder->Datagram->Length - Builder->EncryptionOverhead;
QuicCryptoWriteCryptoFrames(
Crypto,
Builder,
&Builder->DatagramLength,
AvailableBufferLength,
Builder->Datagram->Buffer);
if (!QuicCryptoHasPendingCryptoFrame(Crypto)) {
Connection->Send.SendFlags &= ~QUIC_CONN_SEND_FLAG_CRYPTO;
}
return Builder->Metadata->FrameCount > PrevFrameCount;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
BOOLEAN
QuicCryptoOnLoss(
_In_ QUIC_CRYPTO* Crypto,
_In_ QUIC_SENT_FRAME_METADATA* FrameMetadata
)
{
uint64_t Start = FrameMetadata->CRYPTO.Offset;
uint64_t End = Start + FrameMetadata->CRYPTO.Length;
//
// First check to make sure this data wasn't already acknowledged in a
// different packet.
//
if (End <= Crypto->UnAckedOffset) {
//
// Already completely acknowledged.
//
return FALSE;
}
if (Start < Crypto->UnAckedOffset) {
//
// The 'lost' range overlaps with UNA. Move Start forward.
//
Start = Crypto->UnAckedOffset;
}
QUIC_SUBRANGE* Sack;
uint32_t i = 0;
while ((Sack = QuicRangeGetSafe(&Crypto->SparseAckRanges, i++)) != NULL &&
Sack->Low < End) {
if (Start < Sack->Low + Sack->Count) {
//
// This SACK overlaps with the 'lost' range.
//
if (Start >= Sack->Low) {
//
// The SACK fully covers the Start of the 'lost' range.
//
if (End <= Sack->Low + Sack->Count) {
//
// The SACK fully covers the whole 'lost' range.
//
return FALSE;
}
//
// The SACK only covers the beginning of the 'lost'
// range. Move Start forward to the end of the SACK.
//
Start = Sack->Low + Sack->Count;
} else if (End <= Sack->Low + Sack->Count) {
//
// The SACK fully covers the End of the 'lost' range. Move
// the End backward to right before the SACK.
//
End = Sack->Low;
} else {
//
// The SACK is fully covered by the 'lost' range. Don't do
// anything special in this case, because we still have stuff
// that needs to be retransmitted in that case.
//
}
}
}
BOOLEAN UpdatedRecoveryWindow = FALSE;
//
// Expand the recovery window to encompass the crypto frame that was lost.
//
if (Start < Crypto->RecoveryNextOffset) {
Crypto->RecoveryNextOffset = (uint32_t)Start;
UpdatedRecoveryWindow = TRUE;
}