forked from microsoft/msquic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtls_openssl.c
More file actions
3564 lines (3250 loc) · 122 KB
/
Copy pathtls_openssl.c
File metadata and controls
3564 lines (3250 loc) · 122 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
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:
Implements the TLS functions by calling OpenSSL.
--*/
#include "platform_internal.h"
#include "openssl/opensslv.h"
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable:4100) // Unreferenced parameter errcode in inline function
#endif
#include "openssl/bio.h"
#include "openssl/core_names.h"
#include "openssl/err.h"
#include "openssl/kdf.h"
#include "openssl/pem.h"
#include "openssl/pkcs12.h"
#include "openssl/pkcs7.h"
#include "openssl/rsa.h"
#include "openssl/ssl.h"
#include "openssl/x509.h"
#ifdef _WIN32
#pragma warning(pop)
#endif
#ifdef QUIC_CLOG
#include "tls_openssl.c.clog.h"
#endif
//
// @struct CXPLAT_SEC_CONFIG
// @brief Represents the security configuration used for TLS.
//
// This structure encapsulates all the necessary information for
// configuring TLS security settings, including SSL context,
// ticket keying, and callback functions.
//
typedef struct CXPLAT_SEC_CONFIG {
//
// SSL context used for establishing TLS connections.
//
SSL_CTX *SSLCtx;
//
// Pointer to the ticket key configuration for session resumption.
//
QUIC_TICKET_KEY_CONFIG* TicketKey;
//
// TLS-related callbacks for handling crypto events.
//
CXPLAT_TLS_CALLBACKS Callbacks;
//
// Credential flags specifying various QUIC credential options.
//
QUIC_CREDENTIAL_FLAGS Flags;
//
// Flags that specify behavior for TLS credential handling.
//
CXPLAT_TLS_CREDENTIAL_FLAGS TlsFlags;
} CXPLAT_SEC_CONFIG;
//
// @struct CXPLAT_TLS
// @brief Represents the state and configuration of a TLS session.
//
// This structure holds information necessary to manage a TLS handshake,
// encryption state, and associated connection details for QUIC.
//
typedef struct CXPLAT_TLS {
//
// Pointer to the security configuration used for the TLS session.
//
CXPLAT_SEC_CONFIG* SecConfig;
//
// Pointer to HKDF label definitions used in the key derivation process.
//
const QUIC_HKDF_LABELS* HkdfLabels;
//
// Indicates if the endpoint is acting as a server.
//
BOOLEAN IsServer : 1;
//
// Indicates if a peer certificate has been received.
//
BOOLEAN PeerCertReceived : 1;
//
// Indicates if the peer's transport parameters have been received.
//
BOOLEAN PeerTPReceived : 1;
//
// QUIC transport parameter extension type used in the session.
//
uint16_t QuicTpExtType;
//
// Length of the ALPN buffer.
//
uint16_t AlpnBufferLength;
//
// Pointer to the ALPN buffer data.
//
const uint8_t* AlpnBuffer;
//
// Pointer to the Server Name Indication (SNI) string.
//
const char* SNI;
//
// OpenSSL SSL object used for the TLS handshake and encryption.
//
SSL *Ssl;
//
// Pointer to internal TLS processing state.
//
CXPLAT_TLS_PROCESS_STATE* State;
//
// Flags indicating the results of TLS processing.
//
CXPLAT_TLS_RESULT_FLAGS ResultFlags;
//
// Pointer to the QUIC connection associated with this TLS session.
//
QUIC_CONNECTION* Connection;
//
// Pointer to derived TLS secrets for encryption and decryption.
//
QUIC_TLS_SECRETS* TlsSecrets;
} CXPLAT_TLS;
//
// @struct RECORD_ENTRY
// @brief Represents a buffered SSL record in a linked list.
//
// This structure is used to store an SSL record along with its
// metAData and linkage in a list. It supports tracking incomplete
// records and whether the memory should be freed.
//
typedef struct RECORD_ENTRY {
//
// Linked list node for linking Entries in a list.
//
CXPLAT_LIST_ENTRY Link;
//
// Length of the SSL record.
//
size_t RecLen;
//
// Pointer to the associated SSL connection.
//
SSL *Ssl;
//
// Non-zero if the record is incomplete.
//
unsigned char Incomplete;
//
// Non-zero if the record memory should be freed.
//
unsigned char FreeMe;
//
// The raw SSL record data.
//
uint8_t Record[0];
} RECORD_ENTRY;
typedef struct SECRET_SET {
uint8_t *Secret;
size_t SecretLen;
uint8_t installed;
} SECRET_SET;
//
// @struct AUX_DATA
// @brief holds auxilliary data we need for each ssl
//
typedef struct AUX_DATA {
//
// @brief transport params for our endpoint
//
const uint8_t *Tp;
//
// @brief peer transport params
//
uint8_t *PeerTp;
//
// @brief peer transport param len
//
size_t PeerTpLen;
//
// @brief The current encryption level we are sending data for
//
uint32_t Level;
//
// @brief this SSL's receive record list
//
CXPLAT_LIST_ENTRY RecordList;
//
// @brief state tracking for 1_rtt secrets
SECRET_SET SecretSet[4][2];
} AUX_DATA;
//
// @def GetSslAuxData
// @brief Retrieves application-specific data associated with an SSL object.
//
// This macro accesses the auxiliary data stored in the BIO associated
// with the given SSL connection.
//
// @param s Pointer to an @c SSL object.
//
// @return Pointer to the application-specific data.
//
#define GetSslAuxData(s) BIO_get_app_data(SSL_get_rbio(s))
//
// @brief Determines the negotiated AEAD and hash algorithms from a TLS session.
//
// This function inspects the currently negotiated cipher suite in the given
// TLS context and maps it to corresponding internal AEAD and hash algorithm
// types used by the QUIC implementation.
//
// Supported ciphers include:
// - TLS_AES_128_GCM_SHA256
// - TLS_AES_256_GCM_SHA384
// - TLS_CHACHA20_POLY1305_SHA256
//
// If an unsupported cipher is negotiated, the function asserts.
//
// @param[in] TlsContext Pointer to the TLS context containing the SSL object.
// @param[out] AeadType Pointer to receive the negotiated AEAD algorithm type.
// @param[out] HashType Pointer to receive the negotiated hash algorithm type.
//
void
CxPlatTlsNegotiatedCiphers(
_In_ CXPLAT_TLS* TlsContext,
_Out_ CXPLAT_AEAD_TYPE *AeadType,
_Out_ CXPLAT_HASH_TYPE *HashType
)
{
switch (SSL_CIPHER_get_id(SSL_get_current_cipher(TlsContext->Ssl))) {
case 0x03001301U: // TLS_AES_128_GCM_SHA256
*AeadType = CXPLAT_AEAD_AES_128_GCM;
*HashType = CXPLAT_HASH_SHA256;
break;
case 0x03001302U: // TLS_AES_256_GCM_SHA384
*AeadType = CXPLAT_AEAD_AES_256_GCM;
*HashType = CXPLAT_HASH_SHA384;
break;
case 0x03001303U: // TLS_CHACHA20_POLY1305_SHA256
*AeadType = CXPLAT_AEAD_CHACHA20_POLY1305;
*HashType = CXPLAT_HASH_SHA256;
break;
default:
CXPLAT_FRE_ASSERT(FALSE);
}
}
//
// @brief Callback to send TLS handshake data to the QUIC stack.
//
// This function is called by OpenSSL to send handshake data over QUIC.
// It submits the provided buffer to the QUIC connection for transmission.
// If the submission fails, it sets the TLS error on the QUIC connection.
//
// @param[in] s Pointer to the SSL connection object.
// @param[in] buf Pointer to the buffer containing data to send.
// @param[in] buf_len Length of the data in @p buf.
// @param[out] consumed Number of bytes successfully consumed from @p buf.
// @param[in] arg Unused argument (typically NULL).
//
// @return 1 on success, -1 on failure.
//
static int QuicTlsSend(SSL *s, const unsigned char *Buf,
size_t BufLen, size_t *Consumed,
void *Arg)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(s);
CXPLAT_TLS_PROCESS_STATE* TlsState = TlsContext->State;
struct AUX_DATA *AData = GetSslAuxData(s);
UNREFERENCED_PARAMETER(Arg);
//
// KeyTypes in msquic map directly to our protection levels
//
QUIC_PACKET_KEY_TYPE KeyType = (QUIC_PACKET_KEY_TYPE)AData->Level;
if (TlsContext->ResultFlags & CXPLAT_TLS_RESULT_ERROR) {
return -1;
}
QuicTraceLogConnVerbose(
OpenSslAddHandshakeData,
TlsContext->Connection,
"Sending %llu handshake bytes (Level = %u)",
(uint64_t)BufLen,
(uint32_t)AData->Level);
//
// Make sure that we don't violate handshake data lengths
//
if (BufLen + TlsState->BufferLength > 0xF000) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Too much handshake data");
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return -1;
}
if (BufLen + TlsState->BufferLength > (size_t)TlsState->BufferAllocLength) {
//
// Double the allocated Buffer length until there's enough room for the
// new data.
//
uint16_t NewBufferAllocLength = TlsState->BufferAllocLength;
while (BufLen + TlsState->BufferLength > (size_t)NewBufferAllocLength) {
NewBufferAllocLength <<= 1;
}
uint8_t* NewBuffer = CXPLAT_ALLOC_NONPAGED(NewBufferAllocLength, QUIC_POOL_TLS_BUFFER);
if (NewBuffer == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"New crypto Buffer",
NewBufferAllocLength);
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return -1;
}
CxPlatCopyMemory(
NewBuffer,
TlsState->Buffer,
TlsState->BufferLength);
CXPLAT_FREE(TlsState->Buffer, QUIC_POOL_TLS_BUFFER);
TlsState->Buffer = NewBuffer;
TlsState->BufferAllocLength = NewBufferAllocLength;
}
switch (KeyType) {
case QUIC_PACKET_KEY_HANDSHAKE:
if (TlsState->BufferOffsetHandshake == 0) {
TlsState->BufferOffsetHandshake = TlsState->BufferTotalLength;
QuicTraceLogConnInfo(
OpenSslHandshakeDataStart,
TlsContext->Connection,
"Writing Handshake data starts at %u",
TlsState->BufferOffsetHandshake);
}
break;
case QUIC_PACKET_KEY_1_RTT:
if (TlsState->BufferOffset1Rtt == 0) {
TlsState->BufferOffset1Rtt = TlsState->BufferTotalLength;
QuicTraceLogConnInfo(
OpenSsl1RttDataStart,
TlsContext->Connection,
"Writing 1-RTT data starts at %u",
TlsState->BufferOffset1Rtt);
}
break;
default:
break;
}
CxPlatCopyMemory(
TlsState->Buffer + TlsState->BufferLength,
Buf,
BufLen);
TlsState->BufferLength += (uint16_t)BufLen;
TlsState->BufferTotalLength += (uint16_t)BufLen;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_DATA;
*Consumed = BufLen;
return 1;
}
//
// @brief Callback to provide a previously buffered TLS record to OpenSSL.
//
// This function is called by OpenSSL to retrieve a TLS record for further
// processing. It searches the buffered records for one matching the given
// SSL connection. If a complete record is found, it is returned via @p buf
// and @p bytes_read. If the record is incomplete, it signals OpenSSL to
// wait for more data.
//
// @param[in] s Pointer to the SSL connection object.
// @param[out] buf Pointer to the buffer containing the record data.
// If no data is available, set to NULL.
// @param[out] bytes_read Length of the record returned in @p buf.
// If no data is available, set to 0.
// @param[in] arg Unused argument (typically NULL).
//
// @return Always returns 1.
//
static int QuicTlsRcvRec(SSL *s, const unsigned char **Buf, size_t *BytesRead,
void *Arg)
{
RECORD_ENTRY *entry;
struct AUX_DATA *AData = GetSslAuxData(s);
CXPLAT_LIST_ENTRY* lentry;
UNREFERENCED_PARAMETER(Arg);
CXPLAT_DBG_ASSERT(AData != NULL);
//
// Iterate over our received record list looking
// for a complete entry to submit to the TLS
// stack
//
lentry = AData->RecordList.Flink;
while (lentry != &AData->RecordList) {
entry = CXPLAT_CONTAINING_RECORD(lentry, RECORD_ENTRY, Link);
lentry = lentry->Flink;
if (entry->Incomplete) {
return 1;
}
if (entry->FreeMe == 1) {
continue;
}
*Buf = entry->Record;
*BytesRead = entry->RecLen;
entry->FreeMe = 1;
break;
}
return 1;
}
//
// @brief Callback to release a previously buffered TLS record.
//
// This function is called by OpenSSL after a TLS record has been fully
// processed and can be safely released. It verifies the number of bytes
// read matches the expected record length, frees the associated memory,
// and resets the pointer.
//
// @param[in] bytes_read The number of bytes processed in the TLS record.
// @param[in] arg Unused argument (typically NULL).
//
// @return Always returns 1.
//
static int QuicTlsRlsRec(SSL *S, size_t BytesRead,
void *Arg)
{
struct AUX_DATA *AData = GetSslAuxData(S);
RECORD_ENTRY *entry;
CXPLAT_LIST_ENTRY* lentry;
UNREFERENCED_PARAMETER(Arg);
//
// Look for Entries that are marked for freeing
// if the record length matches, we can free it
//
lentry = AData->RecordList.Flink;
while (lentry != &AData->RecordList) {
entry = CXPLAT_CONTAINING_RECORD(lentry, RECORD_ENTRY, Link);
lentry = lentry->Flink;
if ((entry->FreeMe == 1) && (entry->RecLen == BytesRead)) {
CxPlatListEntryRemove(&entry->Link);
CXPLAT_FREE(entry, QUIC_POOL_TLS_RECORD_ENTRY);
return 1;
}
}
return 1;
}
//
// @brief Callback to yield TLS secrets to the QUIC stack.
//
// This function is invoked by OpenSSL to provide traffic secrets during
// the QUIC handshake. It installs the given secret into the msquic QUIC
// connection, either as a read (RX) key or write (TX) key depending on
// the direction.
//
// @param[in] s Pointer to the SSL connection object.
// @param[in] prot_level OpenSSL encryption level of the secret.
// @param[in] dir Direction of the key. 1 for read (RX) key,
// 0 for write (TX) key.
// @param[in] secret Pointer to the secret to be installed.
// @param[in] secret_len Length of the secret.
// @param[in] arg Unused argument (typically NULL).
//
// @return 1 on success, 0 on failure.
//
#define DIR_READ 0
#define DIR_WRITE 1
static int QuicTlsYieldSecret(SSL *S, uint32_t ProtLevel,
int Dir,
const unsigned char *NewSecret,
size_t SecretLen, void *Arg)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(S);
CXPLAT_TLS_PROCESS_STATE* TlsState = TlsContext->State;
QUIC_PACKET_KEY_TYPE KeyType = (QUIC_PACKET_KEY_TYPE)ProtLevel;
QUIC_STATUS Status;
CXPLAT_SECRET Secret;
struct AUX_DATA *AData = GetSslAuxData(S);
UNREFERENCED_PARAMETER(Arg);
QuicTraceLogConnVerbose(
OpenSslNewEncryptionSecrets,
TlsContext->Connection,
"New encryption secrets (Level = %u)",
ProtLevel);
if (AData->SecretSet[ProtLevel][Dir].Secret != NULL) {
return 1;
}
AData->SecretSet[ProtLevel][Dir].Secret = CXPLAT_ALLOC_NONPAGED(sizeof(struct AUX_DATA), QUIC_POOL_TLS_AUX_DATA);
if (AData->SecretSet[ProtLevel][Dir].Secret == NULL) {
return -1;
}
memcpy(AData->SecretSet[ProtLevel][Dir].Secret, NewSecret, SecretLen);
AData->SecretSet[ProtLevel][Dir].SecretLen = SecretLen;
//
// Install key immediately unless its a read key and we don't yet
// have the corresponding write key
// A notable exception is 0RTT keys on the server, as we only ever get
// a read key for that.
//
if (Dir == 0 && ProtLevel != QUIC_PACKET_KEY_0_RTT &&
AData->SecretSet[ProtLevel][DIR_WRITE].Secret == NULL) {
return 1;
}
CxPlatTlsNegotiatedCiphers(TlsContext, &Secret.Aead, &Secret.Hash);
//
// Tx/Write Secret
//
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL
&& TlsState->WriteKeys[KeyType] == NULL
&& AData->SecretSet[ProtLevel][DIR_WRITE].installed == 0) {
CxPlatCopyMemory(Secret.Secret, AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][DIR_WRITE].SecretLen);
CXPLAT_DBG_ASSERT(TlsState->WriteKeys[KeyType] == NULL);
Status =
QuicPacketKeyDerive(
KeyType,
TlsContext->HkdfLabels,
&Secret,
"write Secret",
TRUE,
&TlsState->WriteKeys[KeyType]);
if (QUIC_FAILED(Status)) {
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return -1;
}
if (TlsContext->IsServer && KeyType == QUIC_PACKET_KEY_0_RTT) {
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_EARLY_DATA_ACCEPT;
TlsContext->State->EarlyDataState = CXPLAT_TLS_EARLY_DATA_ACCEPTED;
}
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_WRITE_KEY_UPDATED;
TlsState->WriteKey = KeyType;
AData->SecretSet[ProtLevel][DIR_WRITE].installed = 1;
}
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL
&& TlsState->ReadKeys[KeyType] == NULL
&& AData->SecretSet[ProtLevel][DIR_READ].installed == 0) {
CxPlatCopyMemory(Secret.Secret, AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
Status =
QuicPacketKeyDerive(
KeyType,
TlsContext->HkdfLabels,
&Secret,
"read Secret",
TRUE,
&TlsState->ReadKeys[KeyType]);
if (QUIC_FAILED(Status)) {
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return -1;
}
if (TlsContext->IsServer && KeyType == QUIC_PACKET_KEY_1_RTT) {
// The 1-RTT read keys aren't actually allowed to be used until the
// handshake completes.
//
} else {
TlsState->ReadKey = KeyType;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_READ_KEY_UPDATED;
AData->SecretSet[ProtLevel][DIR_READ].installed = 1;
}
}
if (AData->SecretSet[ProtLevel][DIR_READ].installed == 1 && AData->SecretSet[ProtLevel][DIR_WRITE].installed == 1) {
AData->Level = ProtLevel;
}
//
// If we are installing initial Secrets TlsSecrets aren't allocated yet
//
if (TlsContext->TlsSecrets != NULL) {
//
// We pass our Secrets one at a time instead of together
// So we need to map which Secret we're assigning based
// on whether we are a server, what type of key we're writing
// and the Direction (1 for write, 0 for read)
//
TlsContext->TlsSecrets->SecretLength = (uint8_t)SecretLen;
switch(KeyType) {
case QUIC_PACKET_KEY_HANDSHAKE:
if (TlsContext->IsServer) {
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ServerHandshakeTrafficSecret,
AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][1].SecretLen);
TlsContext->TlsSecrets->IsSet.ServerHandshakeTrafficSecret = TRUE;
}
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientHandshakeTrafficSecret,
AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientHandshakeTrafficSecret = TRUE;
}
} else {
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientHandshakeTrafficSecret,
AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][DIR_WRITE].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientHandshakeTrafficSecret = TRUE;
}
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ServerHandshakeTrafficSecret,
AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
TlsContext->TlsSecrets->IsSet.ServerHandshakeTrafficSecret = TRUE;
}
}
break;
case QUIC_PACKET_KEY_0_RTT:
if (TlsContext->IsServer) {
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientEarlyTrafficSecret,
AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientEarlyTrafficSecret = TRUE;
}
} else {
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientEarlyTrafficSecret,
AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][DIR_WRITE].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientEarlyTrafficSecret = TRUE;
}
}
break;
case QUIC_PACKET_KEY_1_RTT:
if (TlsContext->IsServer) {
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientTrafficSecret0,
AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientTrafficSecret0 = TRUE;
}
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ServerTrafficSecret0,
AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][DIR_WRITE].SecretLen);
TlsContext->TlsSecrets->IsSet.ServerTrafficSecret0 = TRUE;
}
} else {
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ServerTrafficSecret0,
AData->SecretSet[ProtLevel][DIR_READ].Secret, AData->SecretSet[ProtLevel][DIR_READ].SecretLen);
TlsContext->TlsSecrets->IsSet.ServerTrafficSecret0 = TRUE;
}
if (AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
memcpy(TlsContext->TlsSecrets->ClientTrafficSecret0,
AData->SecretSet[ProtLevel][DIR_WRITE].Secret, AData->SecretSet[ProtLevel][DIR_WRITE].SecretLen);
TlsContext->TlsSecrets->IsSet.ClientTrafficSecret0 = TRUE;
}
}
if (AData->SecretSet[ProtLevel][DIR_READ].Secret != NULL &&
AData->SecretSet[ProtLevel][DIR_WRITE].Secret != NULL) {
/*
* We're done installing secrets
*/
TlsContext->TlsSecrets = NULL;
}
break;
default:
break;
}
}
return 1;
}
//
// @brief Callback invoked when transport parameters are received from peer.
//
// This function is called by OpenSSL when remote QUIC transport parameters
// are received during the TLS handshake. It decodes and applies these
// parameters to the QUIC connection. If decoding fails, it sets a TLS
// error on the connection.
//
// @param[in] s Pointer to the SSL connection object.
// @param[in] params Pointer to the buffer containing transport
// parameters from the peer.
// @param[in] params_len Length of the transport parameters buffer.
// @param[in] arg Unused argument (typically NULL).
//
// @return 1 on success, -1 on failure.
//
static int QuicTlsGotTp(SSL *S, const unsigned char *Params,
size_t ParamsLen, void *Arg)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(S);
struct AUX_DATA *AData = GetSslAuxData(S);
UNREFERENCED_PARAMETER(Arg);
AData->PeerTp = CXPLAT_ALLOC_NONPAGED(ParamsLen,
QUIC_POOL_TLS_TRANSPARAMS);
if (AData->PeerTp == NULL) {
return 0;
}
memcpy(AData->PeerTp, Params, ParamsLen);
AData->PeerTpLen = ParamsLen;
if (!TlsContext->IsServer && TlsContext->PeerTPReceived == FALSE) {
if (AData->PeerTp != NULL && AData->PeerTpLen != 0) {
TlsContext->PeerTPReceived = TRUE;
if (!TlsContext->SecConfig->Callbacks.ReceiveTP(
TlsContext->Connection,
(uint16_t)AData->PeerTpLen,
AData->PeerTp)) {
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return 0;
}
}
}
return 1;
}
//
// @brief Callback invoked when a TLS alert is generated or received.
//
// This function is called by OpenSSL when a TLS alert is triggered
// during the handshake or connection. It logs the alert event for
// debugging purposes.
//
// @param[in] s Pointer to the SSL connection object.
// @param[in] alert_code The TLS alert code.
// @param[in] arg Unused argument (typically NULL).
//
// @return Always returns 1.
//
static int QuicTlsAlert(SSL *S,
unsigned int AlertCode,
void *Arg)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(S);
struct AUX_DATA *AData = GetSslAuxData(S);
UNREFERENCED_PARAMETER(Arg);
QuicTraceLogConnError(
OpenSslAlert,
TlsContext->Connection,
"Send alert = %u (Level = %u)",
AlertCode,
(uint32_t)AData->Level);
TlsContext->State->AlertCode = (uint16_t)AlertCode;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return 1;
}
//
// @brief OpenSSL QUIC TLS callback dispatch table.
//
// This array defines a set of function pointers that OpenSSL uses to
// interact with the QUIC transport layer in a QUIC-enabled TLS session.
// Each entry maps a specific OpenSSL QUIC operation to its corresponding
// callback implementation.
//
// The dispatch table includes:
// - @ref QuicTlsSend: Sends handshake data to the QUIC stack.
// - @ref QuicTlsRcvRec: Provides received handshake data to OpenSSL.
// - @ref QuicTlsRlsRec: Releases processed handshake records.
// - @ref QuicTlsYieldSecret: Supplies derived secrets to the QUIC stack.
// - @ref QuicTlsGotTp: Handles received transport parameters.
// - @ref QuicTlsAlert: Processes TLS alerts.
//
// This table is registered with OpenSSL using SSL_set_quic_tls_cbs().
//
static OSSL_DISPATCH OpenSslQuicDispatch[] = {
{OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))QuicTlsSend},
{OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD, (void (*)(void))QuicTlsRcvRec},
{OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD, (void (*)(void))QuicTlsRlsRec},
{OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET, (void (*)(void))QuicTlsYieldSecret},
{OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS, (void (*)(void))QuicTlsGotTp},
{OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))QuicTlsAlert},
OSSL_DISPATCH_END
};
extern EVP_CIPHER *CXPLAT_AES_256_CBC_ALG_HANDLE;
uint16_t CxPlatTlsTPHeaderSize = 0;
const size_t OpenSslFilePrefixLength = sizeof("..\\..\\..\\..\\..\\..\\submodules");
#define PFX_PASSWORD_LENGTH 33
//
// Default list of Cipher used.
//
#define CXPLAT_TLS_DEFAULT_SSL_CIPHERS "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256"
#define CXPLAT_TLS_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256"
#define CXPLAT_TLS_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384"
#define CXPLAT_TLS_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256"
//
// Default cert verify depth.
//
#define CXPLAT_TLS_DEFAULT_VERIFY_DEPTH 10
//
// @brief Maps an OpenSSL certificate verification error to a QUIC status code.
//
// This function translates specific OpenSSL X.509 verification error codes
// into corresponding QUIC error status values used by the QUIC transport
// layer. It provides a way to surface TLS-level certificate issues through
// standardized QUIC error codes.
//
// Supported mappings:
// - @c X509_V_ERR_CERT_REJECTED → @c QUIC_STATUS_BAD_CERTIFICATE
// - @c X509_V_ERR_CERT_REVOKED → @c QUIC_STATUS_REVOKED_CERTIFICATE
// - @c X509_V_ERR_CERT_HAS_EXPIRED → @c QUIC_STATUS_CERT_EXPIRED
// - @c X509_V_ERR_CERT_UNTRUSTED,
// @c X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT → @c QUIC_STATUS_CERT_UNTRUSTED_ROOT
// - All other errors → @c QUIC_STATUS_TLS_ERROR
//
// @param[in] OpenSSLError OpenSSL error code from certificate validation.
//
// @return Corresponding @c QUIC_STATUS value.
//
static
QUIC_STATUS
CxPlatTlsMapOpenSSLErrorToQuicStatus(
_In_ int OpenSSLError
)
{
switch (OpenSSLError) {
case X509_V_ERR_CERT_REJECTED:
return QUIC_STATUS_BAD_CERTIFICATE;
case X509_V_ERR_CERT_REVOKED:
return QUIC_STATUS_REVOKED_CERTIFICATE;
case X509_V_ERR_CERT_HAS_EXPIRED:
return QUIC_STATUS_CERT_EXPIRED;
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
__fallthrough;
case X509_V_ERR_CERT_UNTRUSTED:
return QUIC_STATUS_CERT_UNTRUSTED_ROOT;
default:
return QUIC_STATUS_TLS_ERROR;
}
}
//
// @brief ALPN selection callback for OpenSSL during TLS handshake.
//
// This callback is invoked by OpenSSL during the TLS handshake to select
// the Application-Layer Protocol Negotiation (ALPN) value to be used.
//
// The selection is driven by QUIC's previously parsed and negotiated ALPN,
// which is already stored in the TLS context. This avoids needing to parse
// the client's offered ALPNs again.
//
// @param[in] Ssl Pointer to the SSL object.
// @param[out] Out On success, set to point to the selected ALPN buffer.
// @param[out] OutLen On success, set to the length of the selected ALPN.
// @param[in] In Pointer to the client's list of ALPN identifiers.
// @param[in] InLen Length in bytes of the @p In buffer.
// @param[in] Arg Application-provided argument (unused).
//
// @return @c SSL_TLSEXT_ERR_OK to indicate successful selection.
//
static
int
CxPlatTlsAlpnSelectCallback(
_In_ SSL *Ssl,
_Out_writes_bytes_(*OutLen) const unsigned char **Out,
_Out_ unsigned char *OutLen,
_In_reads_bytes_(InLen) const unsigned char *In,
_In_ unsigned int InLen,
_In_ void *Arg
)
{
UNREFERENCED_PARAMETER(In);
UNREFERENCED_PARAMETER(InLen);
UNREFERENCED_PARAMETER(Arg);
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
//
// QUIC already parsed and picked the ALPN to use and set it in the
// NegotiatedAlpn variable.
//
CXPLAT_DBG_ASSERT(TlsContext->State->NegotiatedAlpn != NULL);
*OutLen = TlsContext->State->NegotiatedAlpn[0];
*Out = TlsContext->State->NegotiatedAlpn + 1;
return SSL_TLSEXT_ERR_OK;
}
//
// @brief Custom OpenSSL certificate verification callback for OpenSSL.
//
// This function is invoked by OpenSSL during the TLS handshake to verify
// the peer certificate. It handles several QUIC-specific scenarios such as:
// - Disabling or deferring certificate validation.
// - Using QUIC callbacks for certificate verification.
// - Serializing certificates into a portable format when needed.
// - Mapping OpenSSL errors to QUIC status codes.
//
// Behavior depends on the configured credential flags in the associated
// TLS context. It may use OpenSSL’s built-in validation, a custom raw
// certificate verifier, or simply indicate that a certificate was received.
//
// If portable certificates are requested, the peer certificate and chain
// are serialized and passed to the certificate callback. If validation is
// deferred or explicitly disabled, the function ensures certificate
// information is still collected without enforcing verification.
//
// @param[in] x509_ctx
// Pointer to the OpenSSL certificate verification context.
// @param[in] param
// Application-defined parameter (unused).
//
// @return Non-zero on success (certificate accepted), zero on failure.
//
static
int
CxPlatTlsCertificateVerifyCallback(
X509_STORE_CTX *X509Ctx,
void* Param
)
{
UNREFERENCED_PARAMETER(Param);
int CertificateVerified = 0;
int status = TRUE;
unsigned char* OpenSSLCertBuffer = NULL;
QUIC_BUFFER PortableCertificate = { 0, 0 };
QUIC_BUFFER PortableChain = { 0, 0 };
X509* Cert = X509_STORE_CTX_get0_cert(X509Ctx);
SSL *Ssl = X509_STORE_CTX_get_ex_data(X509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
int ValidationResult = X509_V_OK;
BOOLEAN IsDeferredValidationOrClientAuth =
(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REQUIRE_CLIENT_AUTHENTICATION ||
TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_DEFER_CERTIFICATE_VALIDATION);
TlsContext->PeerCertReceived = (Cert != NULL);
if ((TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_CLIENT ||
IsDeferredValidationOrClientAuth) &&
!(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_NO_CERTIFICATE_VALIDATION)) {
if (!(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_TLS_BUILTIN_CERTIFICATE_VALIDATION)) {
if (Cert == NULL) {
QuicTraceEvent(