-
Notifications
You must be signed in to change notification settings - Fork 536
/
tls_openssl.c
2400 lines (2144 loc) · 79.2 KB
/
tls_openssl.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:
Implements the TLS functions by calling OpenSSL.
--*/
#include "platform_internal.h"
#include "openssl/opensslv.h"
#if OPENSSL_VERSION_MAJOR >= 3
#define IS_OPENSSL_3
#endif
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable:4100) // Unreferenced parameter errcode in inline function
#endif
#include "openssl/bio.h"
#ifdef IS_OPENSSL_3
#include "openssl/core_names.h"
#else
#include "openssl/hmac.h"
#endif
#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
extern EVP_CIPHER *CXPLAT_AES_256_CBC_ALG_HANDLE;
uint16_t CxPlatTlsTPHeaderSize = 0;
const size_t OpenSslFilePrefixLength = sizeof("..\\..\\..\\..\\..\\..\\submodules");
#define PFX_PASSWORD_LENGTH 33
//
// The QUIC sec config object. Created once per listener on server side and
// once per connection on client side.
//
typedef struct CXPLAT_SEC_CONFIG {
//
// The SSL context associated with the sec config.
//
SSL_CTX *SSLCtx;
//
// Optional ticket key provided by the app.
//
QUIC_TICKET_KEY_CONFIG* TicketKey;
//
// Callbacks for TLS.
//
CXPLAT_TLS_CALLBACKS Callbacks;
//
// The application supplied credential flags.
//
QUIC_CREDENTIAL_FLAGS Flags;
//
// Internal TLS credential flags.
//
CXPLAT_TLS_CREDENTIAL_FLAGS TlsFlags;
} CXPLAT_SEC_CONFIG;
//
// A TLS context associated per connection.
//
typedef struct CXPLAT_TLS {
//
// The TLS configuration information and credentials.
//
CXPLAT_SEC_CONFIG* SecConfig;
//
// Labels for deriving key material.
//
const QUIC_HKDF_LABELS* HkdfLabels;
//
// Indicates if this context belongs to server side or client side
// connection.
//
BOOLEAN IsServer : 1;
//
// Indicates if the peer sent a certificate.
//
BOOLEAN PeerCertReceived : 1;
//
// Indicates whether the peer's TP has been received.
//
BOOLEAN PeerTPReceived : 1;
//
// The TLS extension type for the QUIC transport parameters.
//
uint16_t QuicTpExtType;
//
// The ALPN buffer.
//
uint16_t AlpnBufferLength;
const uint8_t* AlpnBuffer;
//
// On client side stores a NULL terminated SNI.
//
const char* SNI;
//
// Ssl - A SSL object associated with the connection.
//
SSL *Ssl;
//
// State - The TLS state associated with the connection.
// ResultFlags - Stores the result of the TLS data processing operation.
//
CXPLAT_TLS_PROCESS_STATE* State;
CXPLAT_TLS_RESULT_FLAGS ResultFlags;
//
// Callback context and handler for QUIC TP.
//
QUIC_CONNECTION* Connection;
//
// Optional struct to log TLS traffic secrets.
// Only non-null when the connection is configured to log these.
//
QUIC_TLS_SECRETS* TlsSecrets;
} CXPLAT_TLS;
//
// 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
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;
}
}
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;
}
static
int
CxPlatTlsCertificateVerifyCallback(
X509_STORE_CTX *x509_ctx,
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(x509_ctx);
SSL *Ssl = X509_STORE_CTX_get_ex_data(x509_ctx, 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(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"No certificate passed");
X509_STORE_CTX_set_error(x509_ctx, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return FALSE;
}
int OpenSSLCertLength = i2d_X509(Cert, &OpenSSLCertBuffer);
if (OpenSSLCertLength <= 0) {
QuicTraceEvent(
LibraryError,
"[ lib] ERROR, %s.",
"i2d_X509 failed");
CertificateVerified = FALSE;
} else {
CertificateVerified =
CxPlatCertVerifyRawCertificate(
OpenSSLCertBuffer,
OpenSSLCertLength,
TlsContext->SNI,
TlsContext->SecConfig->Flags,
IsDeferredValidationOrClientAuth?
(uint32_t*)&ValidationResult :
NULL);
}
if (OpenSSLCertBuffer != NULL) {
OPENSSL_free(OpenSSLCertBuffer);
}
if (!CertificateVerified) {
X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_CERT_REJECTED);
}
} else {
CertificateVerified = X509_verify_cert(x509_ctx);
if (IsDeferredValidationOrClientAuth &&
CertificateVerified <= 0) {
ValidationResult =
(int)CxPlatTlsMapOpenSSLErrorToQuicStatus(X509_STORE_CTX_get_error(x509_ctx));
}
}
} else if ((TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_INDICATE_CERTIFICATE_RECEIVED) &&
(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_PORTABLE_CERTIFICATES)) {
//
// We need to get certificates provided by peer if we going to pass them via Callbacks.CertificateReceived.
// We don't really care about validation status but without calling X509_verify_cert() x509_ctx has
// no certificates attached to it and that impacts validation of custom certificate chains.
//
// OpenSSL 3 has X509_build_chain() to build just the chain.
// We may do something similar here for OpenSsl 1.1
//
X509_verify_cert(x509_ctx);
}
if (!(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_NO_CERTIFICATE_VALIDATION) &&
!(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_DEFER_CERTIFICATE_VALIDATION) &&
!CertificateVerified) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Internal certificate validation failed");
return FALSE;
}
if (TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_PORTABLE_CERTIFICATES) {
if (Cert) {
PortableCertificate.Length = i2d_X509(Cert, &PortableCertificate.Buffer);
if (!PortableCertificate.Buffer) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Failed to serialize certificate context");
X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_OUT_OF_MEM);
return FALSE;
}
}
if (x509_ctx) {
int ChainCount;
STACK_OF(X509)* Chain = X509_STORE_CTX_get0_chain(x509_ctx);
if ((ChainCount = sk_X509_num(Chain)) > 0) {
PKCS7* p7 = PKCS7_new();
if (p7) {
PKCS7_set_type(p7, NID_pkcs7_signed);
PKCS7_content_new(p7, NID_pkcs7_data);
for (int i = 0; i < ChainCount; i++) {
PKCS7_add_certificate(p7, sk_X509_value(Chain, i));
}
PortableChain.Length = i2d_PKCS7(p7, &PortableChain.Buffer);
PKCS7_free(p7);
} else {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Failed to allocate PKCS7 context");
}
}
}
}
if ((TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_INDICATE_CERTIFICATE_RECEIVED) &&
!TlsContext->SecConfig->Callbacks.CertificateReceived(
TlsContext->Connection,
(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_PORTABLE_CERTIFICATES) ? (QUIC_CERTIFICATE*)&PortableCertificate : (QUIC_CERTIFICATE*)Cert,
(TlsContext->SecConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_PORTABLE_CERTIFICATES) ? (QUIC_CERTIFICATE_CHAIN*)&PortableChain : (QUIC_CERTIFICATE_CHAIN*)x509_ctx,
0,
ValidationResult)) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Indicate certificate received failed");
X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_CERT_REJECTED);
status = FALSE;
}
if (PortableCertificate.Buffer) {
OPENSSL_free(PortableCertificate.Buffer);
}
if (PortableChain.Buffer) {
OPENSSL_free(PortableChain.Buffer);
}
return status;
}
CXPLAT_STATIC_ASSERT((int)ssl_encryption_initial == (int)QUIC_PACKET_KEY_INITIAL, "Code assumes exact match!");
CXPLAT_STATIC_ASSERT((int)ssl_encryption_early_data == (int)QUIC_PACKET_KEY_0_RTT, "Code assumes exact match!");
CXPLAT_STATIC_ASSERT((int)ssl_encryption_handshake == (int)QUIC_PACKET_KEY_HANDSHAKE, "Code assumes exact match!");
CXPLAT_STATIC_ASSERT((int)ssl_encryption_application == (int)QUIC_PACKET_KEY_1_RTT, "Code assumes exact match!");
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);
}
}
int
CxPlatTlsSetEncryptionSecretsCallback(
_In_ SSL *Ssl,
_In_ OSSL_ENCRYPTION_LEVEL Level,
_In_reads_(SecretLen) const uint8_t* ReadSecret,
_In_reads_(SecretLen) const uint8_t* WriteSecret,
_In_ size_t SecretLen
)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
CXPLAT_TLS_PROCESS_STATE* TlsState = TlsContext->State;
QUIC_PACKET_KEY_TYPE KeyType = (QUIC_PACKET_KEY_TYPE)Level;
QUIC_STATUS Status;
QuicTraceLogConnVerbose(
OpenSslNewEncryptionSecrets,
TlsContext->Connection,
"New encryption secrets (Level = %u)",
(uint32_t)Level);
CXPLAT_SECRET Secret;
CxPlatTlsNegotiatedCiphers(TlsContext, &Secret.Aead, &Secret.Hash);
if (WriteSecret) {
CxPlatCopyMemory(Secret.Secret, WriteSecret, 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;
}
TlsState->WriteKey = KeyType;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_WRITE_KEY_UPDATED;
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;
}
}
if (ReadSecret) {
CxPlatCopyMemory(Secret.Secret, ReadSecret, SecretLen);
CXPLAT_DBG_ASSERT(TlsState->ReadKeys[KeyType] == NULL);
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;
}
}
if (TlsContext->TlsSecrets != NULL) {
TlsContext->TlsSecrets->SecretLength = (uint8_t)SecretLen;
switch (KeyType) {
case QUIC_PACKET_KEY_HANDSHAKE:
CXPLAT_FRE_ASSERT(ReadSecret != NULL && WriteSecret != NULL);
if (TlsContext->IsServer) {
memcpy(TlsContext->TlsSecrets->ClientHandshakeTrafficSecret, ReadSecret, SecretLen);
memcpy(TlsContext->TlsSecrets->ServerHandshakeTrafficSecret, WriteSecret, SecretLen);
} else {
memcpy(TlsContext->TlsSecrets->ClientHandshakeTrafficSecret, WriteSecret, SecretLen);
memcpy(TlsContext->TlsSecrets->ServerHandshakeTrafficSecret, ReadSecret, SecretLen);
}
TlsContext->TlsSecrets->IsSet.ClientHandshakeTrafficSecret = TRUE;
TlsContext->TlsSecrets->IsSet.ServerHandshakeTrafficSecret = TRUE;
break;
case QUIC_PACKET_KEY_1_RTT:
CXPLAT_FRE_ASSERT(ReadSecret != NULL && WriteSecret != NULL);
if (TlsContext->IsServer) {
memcpy(TlsContext->TlsSecrets->ClientTrafficSecret0, ReadSecret, SecretLen);
memcpy(TlsContext->TlsSecrets->ServerTrafficSecret0, WriteSecret, SecretLen);
} else {
memcpy(TlsContext->TlsSecrets->ClientTrafficSecret0, WriteSecret, SecretLen);
memcpy(TlsContext->TlsSecrets->ServerTrafficSecret0, ReadSecret, SecretLen);
}
TlsContext->TlsSecrets->IsSet.ClientTrafficSecret0 = TRUE;
TlsContext->TlsSecrets->IsSet.ServerTrafficSecret0 = TRUE;
//
// We're done with the TlsSecrets.
//
TlsContext->TlsSecrets = NULL;
break;
case QUIC_PACKET_KEY_0_RTT:
if (TlsContext->IsServer) {
CXPLAT_FRE_ASSERT(ReadSecret != NULL);
memcpy(TlsContext->TlsSecrets->ClientEarlyTrafficSecret, ReadSecret, SecretLen);
TlsContext->TlsSecrets->IsSet.ClientEarlyTrafficSecret = TRUE;
} else {
CXPLAT_FRE_ASSERT(WriteSecret != NULL);
memcpy(TlsContext->TlsSecrets->ClientEarlyTrafficSecret, WriteSecret, SecretLen);
TlsContext->TlsSecrets->IsSet.ClientEarlyTrafficSecret = TRUE;
}
break;
default:
break;
}
}
return 1;
}
int
CxPlatTlsAddHandshakeDataCallback(
_In_ SSL *Ssl,
_In_ OSSL_ENCRYPTION_LEVEL Level,
_In_reads_(Length) const uint8_t *Data,
_In_ size_t Length
)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
CXPLAT_TLS_PROCESS_STATE* TlsState = TlsContext->State;
QUIC_PACKET_KEY_TYPE KeyType = (QUIC_PACKET_KEY_TYPE)Level;
if (TlsContext->ResultFlags & CXPLAT_TLS_RESULT_ERROR) {
CXPLAT_DBG_ASSERT(CxPlatIsRandomMemoryFailureEnabled());
return -1;
}
CXPLAT_DBG_ASSERT(KeyType == 0 || TlsState->WriteKeys[KeyType] != NULL);
QuicTraceLogConnVerbose(
OpenSslAddHandshakeData,
TlsContext->Connection,
"Sending %llu handshake bytes (Level = %u)",
(uint64_t)Length,
(uint32_t)Level);
if (Length + TlsState->BufferLength > 0xF000) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Too much handshake data");
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return -1;
}
if (Length + 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 (Length + 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,
Data,
Length);
TlsState->BufferLength += (uint16_t)Length;
TlsState->BufferTotalLength += (uint16_t)Length;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_DATA;
return 1;
}
int
CxPlatTlsFlushFlightCallback(
_In_ SSL *Ssl
)
{
UNREFERENCED_PARAMETER(Ssl);
return 1;
}
int
CxPlatTlsSendAlertCallback(
_In_ SSL *Ssl,
_In_ enum ssl_encryption_level_t Level,
_In_ uint8_t Alert
)
{
UNREFERENCED_PARAMETER(Level);
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
QuicTraceLogConnError(
OpenSslAlert,
TlsContext->Connection,
"Send alert = %u (Level = %u)",
Alert,
(uint32_t)Level);
TlsContext->State->AlertCode = Alert;
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
return 1;
}
_Success_(return == SSL_CLIENT_HELLO_SUCCESS)
int
CxPlatTlsClientHelloCallback(
_In_ SSL *Ssl,
_When_(return == SSL_CLIENT_HELLO_ERROR, _Out_)
int *Alert,
_In_ void *arg
)
{
UNREFERENCED_PARAMETER(arg);
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
const uint8_t* TransportParams;
size_t TransportParamLen;
if (!SSL_client_hello_get0_ext(
Ssl,
TlsContext->QuicTpExtType,
&TransportParams,
&TransportParamLen)) {
TlsContext->ResultFlags |= CXPLAT_TLS_RESULT_ERROR;
*Alert = SSL_AD_INTERNAL_ERROR;
return SSL_CLIENT_HELLO_ERROR;
}
return SSL_CLIENT_HELLO_SUCCESS;
}
int
CxPlatTlsOnClientSessionTicketReceived(
_In_ SSL *Ssl,
_In_ SSL_SESSION *Session
)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
BIO* Bio = BIO_new(BIO_s_mem());
if (Bio) {
if (PEM_write_bio_SSL_SESSION(Bio, Session) == 1) {
uint8_t* Data = NULL;
long Length = BIO_get_mem_data(Bio, &Data);
if (Length < UINT16_MAX) {
QuicTraceLogConnInfo(
OpenSslOnRecvTicket,
TlsContext->Connection,
"Received session ticket, %u bytes",
(uint32_t)Length);
TlsContext->SecConfig->Callbacks.ReceiveTicket(
TlsContext->Connection,
(uint32_t)Length,
Data);
} else {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Session data too big");
}
} else {
QuicTraceEvent(
TlsErrorStatus,
"[ tls][%p] ERROR, %u, %s.",
TlsContext->Connection,
ERR_get_error(),
"PEM_write_bio_SSL_SESSION failed");
}
BIO_free(Bio);
} else {
QuicTraceEvent(
TlsErrorStatus,
"[ tls][%p] ERROR, %u, %s.",
TlsContext->Connection,
ERR_get_error(),
"BIO_new_mem_buf failed");
}
//
// We always return a "fail" response so that the session gets freed again
// because we haven't used the reference.
//
return 0;
}
_Success_(return > 0)
int
CxPlatTlsOnSessionTicketKeyNeeded(
_In_ SSL *Ssl,
_When_(enc, _Out_writes_bytes_(16))
_When_(!enc, _In_reads_bytes_(16))
unsigned char key_name[16],
_When_(enc, _Out_writes_bytes_(EVP_MAX_IV_LENGTH))
_When_(!enc, _In_reads_bytes_(EVP_MAX_IV_LENGTH))
unsigned char iv[EVP_MAX_IV_LENGTH],
_Inout_ EVP_CIPHER_CTX *ctx,
#ifdef IS_OPENSSL_3
_Inout_ EVP_MAC_CTX *hctx,
#else
_Inout_ HMAC_CTX *hctx,
#endif
_In_ int enc // Encryption or decryption
)
{
#ifdef IS_OPENSSL_3
OSSL_PARAM params[3];
#endif
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
QUIC_TICKET_KEY_CONFIG* TicketKey = TlsContext->SecConfig->TicketKey;
CXPLAT_DBG_ASSERT(TicketKey != NULL);
if (TicketKey == NULL) {
return -1;
}
CXPLAT_STATIC_ASSERT(
sizeof(TicketKey->Id) == 16,
"key_name and TicketKey->Id are the same size");
if (enc) {
if (QUIC_FAILED(CxPlatRandom(EVP_MAX_IV_LENGTH, iv))) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Failed to generate ticket IV");
return -1; // Insufficient random
}
CxPlatCopyMemory(key_name, TicketKey->Id, 16);
EVP_EncryptInit_ex(ctx, CXPLAT_AES_256_CBC_ALG_HANDLE, NULL, TicketKey->Material, iv);
#ifdef IS_OPENSSL_3
params[0] =
OSSL_PARAM_construct_octet_string(
OSSL_MAC_PARAM_KEY,
TicketKey->Material,
32);
params[1] =
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "sha256", 0);
params[2] =
OSSL_PARAM_construct_end();
EVP_MAC_CTX_set_params(hctx, params);
#else
HMAC_Init_ex(hctx, TicketKey->Material, 32, EVP_sha256(), NULL);
#endif
} else {
if (memcmp(key_name, TicketKey->Id, 16) != 0) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"Ticket key_name mismatch");
return 0; // No match
}
#ifdef IS_OPENSSL_3
params[0] =
OSSL_PARAM_construct_octet_string(
OSSL_MAC_PARAM_KEY,
TicketKey->Material,
32);
params[1] =
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "sha256", 0);
params[2] =
OSSL_PARAM_construct_end();
EVP_MAC_CTX_set_params(hctx, params);
#else
HMAC_Init_ex(hctx, TicketKey->Material, 32, EVP_sha256(), NULL);
#endif
EVP_DecryptInit_ex(ctx, CXPLAT_AES_256_CBC_ALG_HANDLE, NULL, TicketKey->Material, iv);
}
return 1; // This indicates that the ctx and hctx have been set and the
// session can continue on those parameters.
}
int
CxPlatTlsOnServerSessionTicketGenerated(
_In_ SSL *Ssl,
_In_ void *arg
)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
UNREFERENCED_PARAMETER(TlsContext);
UNREFERENCED_PARAMETER(arg);
return 1;
}
SSL_TICKET_RETURN
CxPlatTlsOnServerSessionTicketDecrypted(
_In_ SSL *Ssl,
_In_ SSL_SESSION *Session,
_In_ const unsigned char *keyname,
_In_ size_t keyname_length,
_In_ SSL_TICKET_STATUS status,
_In_ void *arg
)
{
CXPLAT_TLS* TlsContext = SSL_get_app_data(Ssl);
UNREFERENCED_PARAMETER(keyname);
UNREFERENCED_PARAMETER(keyname_length);
UNREFERENCED_PARAMETER(arg);
QuicTraceLogConnVerbose(
OpenSslTickedDecrypted,
TlsContext->Connection,
"Session ticket decrypted, status %u",
(uint32_t)status);
SSL_TICKET_RETURN Result;
if (status == SSL_TICKET_SUCCESS) {
Result = SSL_TICKET_RETURN_USE;
} else if (status == SSL_TICKET_SUCCESS_RENEW) {
Result = SSL_TICKET_RETURN_USE_RENEW;
} else {
Result = SSL_TICKET_RETURN_IGNORE_RENEW;
}
uint8_t* Buffer = NULL;
size_t Length = 0;
if (Session != NULL &&
SSL_SESSION_get0_ticket_appdata(Session, (void**)&Buffer, &Length)) {
QuicTraceLogConnVerbose(
OpenSslRecvTicketData,
TlsContext->Connection,
"Received ticket data, %u bytes",
(uint32_t)Length);
if (!TlsContext->SecConfig->Callbacks.ReceiveTicket(
TlsContext->Connection,
(uint32_t)Length,
Buffer)) {
QuicTraceEvent(
TlsError,
"[ tls][%p] ERROR, %s.",
TlsContext->Connection,
"ReceiveTicket failed");
if (status == SSL_TICKET_SUCCESS_RENEW) {
Result = SSL_TICKET_RETURN_IGNORE_RENEW;
} else {
Result = SSL_TICKET_RETURN_IGNORE;
}
}
}
return Result;
}
SSL_QUIC_METHOD OpenSslQuicCallbacks = {
CxPlatTlsSetEncryptionSecretsCallback,
CxPlatTlsAddHandshakeDataCallback,
CxPlatTlsFlushFlightCallback,
CxPlatTlsSendAlertCallback
};
CXPLAT_STATIC_ASSERT(
FIELD_OFFSET(QUIC_CERTIFICATE_FILE, PrivateKeyFile) == FIELD_OFFSET(QUIC_CERTIFICATE_FILE_PROTECTED, PrivateKeyFile),
"Mismatch (private key) in certificate file structs");
CXPLAT_STATIC_ASSERT(
FIELD_OFFSET(QUIC_CERTIFICATE_FILE, CertificateFile) == FIELD_OFFSET(QUIC_CERTIFICATE_FILE_PROTECTED, CertificateFile),
"Mismatch (certificate file) in certificate file structs");
_IRQL_requires_max_(DISPATCH_LEVEL)
QUIC_TLS_PROVIDER
CxPlatTlsGetProvider(
void
)
{
return QUIC_TLS_PROVIDER_OPENSSL;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
CxPlatTlsSecConfigCreate(
_In_ const QUIC_CREDENTIAL_CONFIG* CredConfig,
_In_ CXPLAT_TLS_CREDENTIAL_FLAGS TlsCredFlags,
_In_ const CXPLAT_TLS_CALLBACKS* TlsCallbacks,
_In_opt_ void* Context,
_In_ CXPLAT_SEC_CONFIG_CREATE_COMPLETE_HANDLER CompletionHandler
)
{
QUIC_CREDENTIAL_FLAGS CredConfigFlags = CredConfig->Flags;
if (CredConfigFlags & QUIC_CREDENTIAL_FLAG_LOAD_ASYNCHRONOUS &&
CredConfig->AsyncHandler == NULL) {
return QUIC_STATUS_INVALID_PARAMETER;
}
if (CredConfigFlags & QUIC_CREDENTIAL_FLAG_ENABLE_OCSP ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_USE_SUPPLIED_CREDENTIALS ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_USE_SYSTEM_MAPPER ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_INPROC_PEER_CERTIFICATE) {
return QUIC_STATUS_NOT_SUPPORTED; // Not supported by this TLS implementation
}
#ifdef CX_PLATFORM_USES_TLS_BUILTIN_CERTIFICATE
CredConfigFlags |= QUIC_CREDENTIAL_FLAG_USE_TLS_BUILTIN_CERTIFICATE_VALIDATION;
#endif
if ((CredConfigFlags & QUIC_CREDENTIAL_FLAG_DEFER_CERTIFICATE_VALIDATION) &&
!(CredConfigFlags & QUIC_CREDENTIAL_FLAG_INDICATE_CERTIFICATE_RECEIVED)) {
return QUIC_STATUS_INVALID_PARAMETER; // Defer validation without indication doesn't make sense.
}
if ((CredConfigFlags & QUIC_CREDENTIAL_FLAG_USE_TLS_BUILTIN_CERTIFICATE_VALIDATION) &&
(CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_END_CERT ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CHAIN ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_IGNORE_NO_REVOCATION_CHECK ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_IGNORE_REVOCATION_OFFLINE ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_CACHE_ONLY_URL_RETRIEVAL ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CACHE_ONLY ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_DISABLE_AIA)) {
return QUIC_STATUS_INVALID_PARAMETER;
}
#ifdef CX_PLATFORM_DARWIN
if (((CredConfigFlags & QUIC_CREDENTIAL_FLAG_USE_TLS_BUILTIN_CERTIFICATE_VALIDATION) == 0) &&
(CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_END_CERT ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_IGNORE_NO_REVOCATION_CHECK ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_IGNORE_REVOCATION_OFFLINE ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_CACHE_ONLY_URL_RETRIEVAL ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CACHE_ONLY ||
CredConfigFlags & QUIC_CREDENTIAL_FLAG_DISABLE_AIA)) {
return QUIC_STATUS_INVALID_PARAMETER;
}
#endif