-
Notifications
You must be signed in to change notification settings - Fork 546
/
Copy pathtls_schannel.c
3335 lines (2947 loc) · 119 KB
/
tls_schannel.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:
SCHANNEL TLS Implementation for QUIC
Environment:
Windows user mode or kernel mode
--*/
#ifdef QUIC_UWP_BUILD
#undef WINAPI_FAMILY
#define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP
#endif
#include "platform_internal.h"
#include <security.h>
#ifdef QUIC_CLOG
#include "tls_schannel.c.clog.h"
#endif
#ifdef _KERNEL_MODE
#include <winerror.h>
typedef enum _SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS
{
SecApplicationProtocolNegotiationStatus_None,
SecApplicationProtocolNegotiationStatus_Success,
SecApplicationProtocolNegotiationStatus_SelectedClientOnly
} SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS, *PSEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS;
#define MAX_PROTOCOL_ID_SIZE 0xff
typedef struct _SecPkgContext_ApplicationProtocol
{
SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS ProtoNegoStatus; // Application protocol negotiation status
SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT ProtoNegoExt; // Protocol negotiation extension type corresponding to this protocol ID
unsigned char ProtocolIdSize; // Size in bytes of the application protocol ID
unsigned char ProtocolId[MAX_PROTOCOL_ID_SIZE]; // Byte string representing the negotiated application protocol ID
} SecPkgContext_ApplicationProtocol, *PSecPkgContext_ApplicationProtocol;
typedef struct _SecPkgContext_CertificateValidationResult
{
DWORD dwChainErrorStatus; // Contains chain build error flags set by CertGetCertificateChain.
HRESULT hrVerifyChainStatus; // Certificate validation policy error returned by CertVerifyCertificateChainPolicy.
} SecPkgContext_CertificateValidationResult, *PSecPkgContext_CertificateValidationResult;
// Session ticket protection version definitions.
#define SESSION_TICKET_INFO_V0 0
#define SESSION_TICKET_INFO_VERSION SESSION_TICKET_INFO_V0
typedef struct _SecPkgCred_SessionTicketKey
{
DWORD TicketInfoVersion; // Set to SESSION_TICKET_INFO_VERSION for the current session ticket protection method.
BYTE KeyId[16]; // Uniquely identifies each session ticket key issued by a TLS server.
BYTE KeyingMaterial[64]; // Must be generated using a cryptographic RNG.
BYTE KeyingMaterialSize; // Size in bytes of the keying material in the KeyingMaterial array. Must be between 32 and 64.
} SecPkgCred_SessionTicketKey, *PSecPkgCred_SessionTicketKey;
typedef struct _SecPkgCred_SessionTicketKeys
{
DWORD cSessionTicketKeys; // Up to 16 keys.
PSecPkgCred_SessionTicketKey pSessionTicketKeys;
} SecPkgCred_SessionTicketKeys, *PSecPkgCred_SessionTicketKeys;
typedef struct _SEND_GENERIC_TLS_EXTENSION
{
WORD ExtensionType; // Code point of extension.
WORD HandshakeType; // Message type used to transport extension.
DWORD Flags; // Flags used to modify behavior. Must be zero.
WORD BufferSize; // Size in bytes of the extension data.
UCHAR Buffer[ANYSIZE_ARRAY]; // Extension data.
} SEND_GENERIC_TLS_EXTENSION, * PSEND_GENERIC_TLS_EXTENSION;
//
// This property returns the raw binary certificates that were received
// from the remote party. The format of the buffer that's returned is as
// follows.
//
// <4 bytes> length of certificate #1
// <n bytes> certificate #1
// <4 bytes> length of certificate #2
// <n bytes> certificate #2
// ...
//
typedef struct _SecPkgContext_Certificates
{
DWORD cCertificates;
DWORD cbCertificateChain;
PBYTE pbCertificateChain;
} SecPkgContext_Certificates, *PSecPkgContext_Certificates;
typedef struct _SecPkgCred_ClientCertPolicy
{
DWORD dwFlags;
GUID guidPolicyId;
DWORD dwCertFlags;
DWORD dwUrlRetrievalTimeout;
BOOL fCheckRevocationFreshnessTime;
DWORD dwRevocationFreshnessTime;
BOOL fOmitUsageCheck;
LPWSTR pwszSslCtlStoreName;
LPWSTR pwszSslCtlIdentifier;
} SecPkgCred_ClientCertPolicy, *PSecPkgCred_ClientCertPolicy;
// CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL - don't hit the wire to get URL based objects
#define CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL 0x00000004
// CERT_CHAIN_CACHE_END_CERT can be used here as well
// Revocation flags are in the high nibble
#define CERT_CHAIN_REVOCATION_CHECK_END_CERT 0x10000000
#define CERT_CHAIN_REVOCATION_CHECK_CHAIN 0x20000000
#define CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT 0x40000000
#define CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY 0x80000000
#define CERT_CHAIN_DISABLE_AIA 0x00002000
#define SECPKG_ATTR_REMOTE_CERTIFICATES 0x5F // returns SecPkgContext_Certificates
#define SP_PROT_TLS1_3_SERVER 0x00001000
#define SP_PROT_TLS1_3_CLIENT 0x00002000
#define SP_PROT_TLS1_3 (SP_PROT_TLS1_3_SERVER | \
SP_PROT_TLS1_3_CLIENT)
#define SCH_CRED_NO_SYSTEM_MAPPER 0x00000002
#define SCH_CRED_NO_SERVERNAME_CHECK 0x00000004
#define SCH_CRED_MANUAL_CRED_VALIDATION 0x00000008
#define SCH_CRED_NO_DEFAULT_CREDS 0x00000010
#define SCH_CRED_AUTO_CRED_VALIDATION 0x00000020
#define SCH_CRED_USE_DEFAULT_CREDS 0x00000040
#define SCH_CRED_DISABLE_RECONNECTS 0x00000080
#define SCH_CRED_REVOCATION_CHECK_END_CERT 0x00000100
#define SCH_CRED_REVOCATION_CHECK_CHAIN 0x00000200
#define SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT 0x00000400
#define SCH_CRED_IGNORE_NO_REVOCATION_CHECK 0x00000800
#define SCH_CRED_IGNORE_REVOCATION_OFFLINE 0x00001000
#define SCH_CRED_RESTRICTED_ROOTS 0x00002000
#define SCH_CRED_REVOCATION_CHECK_CACHE_ONLY 0x00004000
#define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL 0x00008000
#define SCH_CRED_MEMORY_STORE_CERT 0x00010000
#define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE 0x00020000
#define SCH_SEND_ROOT_CERT 0x00040000
#define SCH_CRED_SNI_CREDENTIAL 0x00080000
#define SCH_CRED_SNI_ENABLE_OCSP 0x00100000
#define SCH_SEND_AUX_RECORD 0x00200000
#define SCH_USE_STRONG_CRYPTO 0x00400000
#define SCH_USE_PRESHAREDKEY_ONLY 0x00800000
#define SCH_USE_DTLS_ONLY 0x01000000
#define SCH_ALLOW_NULL_ENCRYPTION 0x02000000
#define SCH_CRED_DEFERRED_CRED_VALIDATION 0x04000000
// Values for SCHANNEL_CRED dwCredFormat field.
#define SCH_CRED_FORMAT_CERT_CONTEXT 0x00000000
#define SCH_CRED_FORMAT_CERT_HASH 0x00000001
#define SCH_CRED_FORMAT_CERT_HASH_STORE 0x00000002
#define SCH_CRED_MAX_STORE_NAME_SIZE 128
#define SCH_CRED_MAX_SUPPORTED_ALGS 256
#define SCH_CRED_MAX_SUPPORTED_CERTS 100
typedef ULONG_PTR HCRYPTPROV;
typedef struct _SCHANNEL_CERT_HASH
{
DWORD dwLength;
DWORD dwFlags;
HCRYPTPROV hProv;
BYTE ShaHash[20];
} SCHANNEL_CERT_HASH, * PSCHANNEL_CERT_HASH;
typedef struct _SCHANNEL_CERT_HASH_STORE
{
DWORD dwLength;
DWORD dwFlags;
HCRYPTPROV hProv;
BYTE ShaHash[20];
WCHAR pwszStoreName[SCH_CRED_MAX_STORE_NAME_SIZE];
} SCHANNEL_CERT_HASH_STORE, * PSCHANNEL_CERT_HASH_STORE;
// Values for SCHANNEL_CERT_HASH dwFlags field.
#define SCH_MACHINE_CERT_HASH 0x00000001
typedef struct _CRYPTOAPI_BLOB {
DWORD cbData;
_Field_size_bytes_(cbData)
BYTE *pbData;
} CERT_BLOB, *PCERT_BLOB;
//
// Schannel credentials data structure.
//
#define SCH_CRED_V1 0x00000001
#define SCH_CRED_V2 0x00000002 // for legacy code
#define SCH_CRED_VERSION 0x00000002 // for legacy code
#define SCH_CRED_V3 0x00000003 // for legacy code
#define SCHANNEL_CRED_VERSION 0x00000004 // for legacy code
#define SCH_CREDENTIALS_VERSION 0x00000005
struct _HMAPPER;
typedef const struct _CERT_CONTEXT* PCCERT_CONTEXT;
typedef void* HCERTSTORE;
typedef enum _eTlsAlgorithmUsage
{
TlsParametersCngAlgUsageKeyExchange, // Key exchange algorithm. RSA, ECHDE, DHE, etc.
TlsParametersCngAlgUsageSignature, // Signature algorithm. RSA, DSA, ECDSA, etc.
TlsParametersCngAlgUsageCipher, // Encryption algorithm. AES, DES, RC4, etc.
TlsParametersCngAlgUsageDigest, // Digest of cipher suite. SHA1, SHA256, SHA384, etc.
TlsParametersCngAlgUsageCertSig // Signature and/or hash used to sign certificate. RSA, DSA, ECDSA, SHA1, SHA256, etc.
} eTlsAlgorithmUsage;
//
// SCH_CREDENTIALS structures
//
typedef struct _CRYPTO_SETTINGS
{
eTlsAlgorithmUsage eAlgorithmUsage; // How this algorithm is being used.
UNICODE_STRING strCngAlgId; // CNG algorithm identifier.
DWORD cChainingModes; // Set to 0 if CNG algorithm does not have a chaining mode.
PUNICODE_STRING rgstrChainingModes; // Set to NULL if CNG algorithm does not have a chaining mode.
DWORD dwMinBitLength; // Blacklist key sizes less than this. Set to 0 if not defined or CNG algorithm implies bit length.
DWORD dwMaxBitLength; // Blacklist key sizes greater than this. Set to 0 if not defined or CNG algorithm implies bit length.
} CRYPTO_SETTINGS, * PCRYPTO_SETTINGS;
typedef struct _TLS_PARAMETERS
{
DWORD cAlpnIds; // Valid for server applications only. Must be zero otherwise. Number of ALPN IDs in rgstrAlpnIds; set to 0 if applies to all.
PUNICODE_STRING rgstrAlpnIds; // Valid for server applications only. Must be NULL otherwise. Array of ALPN IDs that the following settings apply to; set to NULL if applies to all.
DWORD grbitDisabledProtocols; // List protocols you DO NOT want negotiated.
DWORD cDisabledCrypto; // Number of CRYPTO_SETTINGS structures; set to 0 if there are none.
PCRYPTO_SETTINGS pDisabledCrypto; // Array of CRYPTO_SETTINGS structures; set to NULL if there are none;
DWORD dwFlags; // Optional flags to pass; set to 0 if there are none.
} TLS_PARAMETERS, * PTLS_PARAMETERS;
typedef struct _SCH_CREDENTIALS
{
DWORD dwVersion; // Always SCH_CREDENTIALS_VERSION.
DWORD dwCredFormat;
DWORD cCreds;
PCCERT_CONTEXT* paCred;
HCERTSTORE hRootStore;
DWORD cMappers;
struct _HMAPPER** aphMappers;
DWORD dwSessionLifespan;
DWORD dwFlags;
DWORD cTlsParameters;
PTLS_PARAMETERS pTlsParameters;
} SCH_CREDENTIALS, * PSCH_CREDENTIALS;
typedef struct _TLS_EXTENSION_SUBSCRIPTION
{
WORD ExtensionType; // Code point of extension.
WORD HandshakeType; // Message type used to transport extension.
} TLS_EXTENSION_SUBSCRIPTION, * PTLS_EXTENSION_SUBSCRIPTION;
typedef struct _SUBSCRIBE_GENERIC_TLS_EXTENSION
{
DWORD Flags; // Flags used to modify behavior. Must be zero.
DWORD SubscriptionsCount; // Number of elements in the Subscriptions array.
TLS_EXTENSION_SUBSCRIPTION Subscriptions[ANYSIZE_ARRAY]; // Array of TLS_EXTENSION_SUBSCRIPTION structures.
} SUBSCRIBE_GENERIC_TLS_EXTENSION, * PSUBSCRIBE_GENERIC_TLS_EXTENSION;
// Flag values for SecPkgContext_SessionInfo
#define SSL_SESSION_RECONNECT 1
typedef struct _SecPkgContext_SessionInfo
{
DWORD dwFlags;
DWORD cbSessionId;
BYTE rgbSessionId[32];
} SecPkgContext_SessionInfo, * PSecPkgContext_SessionInfo;
#define SECPKG_ATTR_SESSION_INFO 0x5d // returns SecPkgContext_SessionInfo
#define SECPKG_ATTR_CERT_CHECK_RESULT_INPROC 0x72 // returns SecPkgContext_CertificateValidationResult, use only after SSPI handshake loop
#define SECPKG_ATTR_SESSION_TICKET_KEYS 0x73 // sets SecPkgCred_SessionTicketKeys
typedef unsigned int ALG_ID;
typedef struct _SecPkgContext_CipherInfo
{
DWORD dwVersion;
DWORD dwProtocol;
DWORD dwCipherSuite;
DWORD dwBaseCipherSuite;
WCHAR szCipherSuite[SZ_ALG_MAX_SIZE];
WCHAR szCipher[SZ_ALG_MAX_SIZE];
DWORD dwCipherLen;
DWORD dwCipherBlockLen; // in bytes
WCHAR szHash[SZ_ALG_MAX_SIZE];
DWORD dwHashLen;
WCHAR szExchange[SZ_ALG_MAX_SIZE];
DWORD dwMinExchangeLen;
DWORD dwMaxExchangeLen;
WCHAR szCertificate[SZ_ALG_MAX_SIZE];
DWORD dwKeyType;
} SecPkgContext_CipherInfo, * PSecPkgContext_CipherInfo;
typedef struct _SecPkgContext_ConnectionInfo
{
DWORD dwProtocol;
ALG_ID aiCipher;
DWORD dwCipherStrength;
ALG_ID aiHash;
DWORD dwHashStrength;
ALG_ID aiExch;
DWORD dwExchStrength;
} SecPkgContext_ConnectionInfo, * PSecPkgContext_ConnectionInfo;
#define SECPKG_ATTR_CIPHER_INFO 0x64 // returns new CNG SecPkgContext_CipherInfo
#define SECPKG_ATTR_CONNECTION_INFO 0x5a // returns SecPkgContext_ConnectionInfo
#else
#define SCHANNEL_USE_BLACKLISTS
#if (defined(QUIC_GAMECORE_BUILD))
#include <sdkddkver.h>
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
#endif
#include <schannel.h>
#ifndef SCH_CRED_DEFERRED_CRED_VALIDATION
#define SCH_CRED_DEFERRED_CRED_VALIDATION 0x04000000
typedef struct _SecPkgContext_CertificateValidationResult
{
DWORD dwChainErrorStatus; // Contains chain build error flags set by CertGetCertificateChain.
HRESULT hrVerifyChainStatus; // Certificate validation policy error returned by CertVerifyCertificateChainPolicy.
} SecPkgContext_CertificateValidationResult, *PSecPkgContext_CertificateValidationResult;
#define SECPKG_ATTR_CERT_CHECK_RESULT_INPROC 0x72 // returns SecPkgContext_CertificateValidationResult, use only after SSPI handshake loop
#endif // SCH_CRED_DEFERRED_CRED_VALIDATION
#ifndef SECPKG_ATTR_SESSION_TICKET_KEYS
#define SECPKG_ATTR_SESSION_TICKET_KEYS 0x73 // sets SecPkgCred_SessionTicketKeys
// Session ticket protection version definitions.
#define SESSION_TICKET_INFO_V0 0
#define SESSION_TICKET_INFO_VERSION SESSION_TICKET_INFO_V0
typedef struct _SecPkgCred_SessionTicketKey
{
DWORD TicketInfoVersion; // Set to SESSION_TICKET_INFO_VERSION for the current session ticket protection method.
BYTE KeyId[16]; // Uniquely identifies each session ticket key issued by a TLS server.
BYTE KeyingMaterial[64]; // Must be generated using a cryptographic RNG.
BYTE KeyingMaterialSize; // Size in bytes of the keying material in the KeyingMaterial array. Must be between 32 and 64.
} SecPkgCred_SessionTicketKey, *PSecPkgCred_SessionTicketKey;
typedef struct _SecPkgCred_SessionTicketKeys
{
DWORD cSessionTicketKeys; // Up to 16 keys.
PSecPkgCred_SessionTicketKey pSessionTicketKeys;
} SecPkgCred_SessionTicketKeys, *PSecPkgCred_SessionTicketKeys;
#endif // SECPKG_ATTR_SESSION_TICKET_KEYS
#endif
#ifndef SECPKG_ATTR_CLIENT_CERT_POLICY
#define SECPKG_ATTR_CLIENT_CERT_POLICY 0x60 // sets SecPkgCred_ClientCertCtlPolicy
#endif
#ifndef SECPKG_ATTR_SERIALIZED_REMOTE_CERT_CONTEXT_INPROC
#define SECPKG_ATTR_SERIALIZED_REMOTE_CERT_CONTEXT_INPROC 0x74 // returns CERT_BLOB, use only after SSPI handshake loop
#endif
//
// Defines until BCrypt.h updates
//
#ifndef BCRYPT_CHACHA20_POLY1305_ALGORITHM
#define BCRYPT_CHACHA20_POLY1305_ALGORITHM L"CHACHA20_POLY1305"
#endif
extern BCRYPT_ALG_HANDLE CXPLAT_CHACHA20_POLY1305_ALG_HANDLE;
uint16_t CxPlatTlsTPHeaderSize = FIELD_OFFSET(SEND_GENERIC_TLS_EXTENSION, Buffer);
#define SecTrafficSecret_ClientEarlyData (SecTrafficSecret_Server + 1) // Hack to have my layer support 0-RTT
#define SEC_TRAFFIC_SECRETS_COUNT 4
#define MAX_SEC_TRAFFIC_SECRET_SIZE 0x40 // Fits all known current and future algorithms
#define MAX_SEC_TRAFFIC_SECRETS_SIZE \
(sizeof(SEC_TRAFFIC_SECRETS) + MAX_SEC_TRAFFIC_SECRET_SIZE)
const WORD TlsHandshake_ClientHello = 0x01;
const WORD TlsHandshake_EncryptedExtensions = 0x08;
// {791A59D6-34C8-4ADE-9B53-D13EEA4E9F0B}
static const GUID CxPlatTlsClientCertPolicyGuid =
{
0x791a59d6,
0x34c8,
0x4ade,
{ 0x9b, 0x53, 0xd1, 0x3e, 0xea, 0x4e, 0x9f, 0xb }
};
#ifndef TLS1_ALERT_CLOSE_NOTIFY
#define TLS1_ALERT_CLOSE_NOTIFY 0
#endif
#ifndef TLS1_ALERT_CERTIFICATE_REQUIRED
#define TLS1_ALERT_CERTIFICATE_REQUIRED 116
#endif
typedef struct CXPLAT_SEC_CONFIG {
//
// Acquired credential handle.
//
CredHandle CredentialHandle;
//
// Credential flags used to acquire the handle.
//
QUIC_CREDENTIAL_FLAGS Flags;
//
// Callbacks for TLS.
//
CXPLAT_TLS_CALLBACKS Callbacks;
#ifdef _KERNEL_MODE
//
// Impersonation token from the original call to initialize.
//
PACCESS_TOKEN ImpersonationToken;
BOOLEAN IsPrimaryToken;
BOOLEAN CopyOnOpen;
BOOLEAN EffectiveOnly;
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
#endif // _KERNEL_MODE
} CXPLAT_SEC_CONFIG;
typedef struct QUIC_ACH_CONTEXT {
//
// Credential flags used to acquire the handle.
//
QUIC_CREDENTIAL_CONFIG CredConfig;
//
// Context for the completion callback.
//
void* CompletionContext;
//
// Caller-registered callback to signal credential acquisition is complete.
//
CXPLAT_SEC_CONFIG_CREATE_COMPLETE_HANDLER CompletionCallback;
#ifdef _KERNEL_MODE
//
// Async call context.
//
SspiAsyncContext* SspiContext;
//
// Principal string, stored here to ensure it's alive as long as the async
// call needs it.
//
UNICODE_STRING Principal;
//
// Used to wait on the async callback, when in synchronous mode.
//
KEVENT CompletionEvent;
//
// The status received from the completion callback.
//
NTSTATUS CompletionStatus;
#endif
//
// CredConfig certificate hash used to find the server certificate.
//
SCHANNEL_CERT_HASH_STORE CertHash;
//
// Security config to pass back to the caller.
//
CXPLAT_SEC_CONFIG* SecConfig;
//
// Holds the credentials configuration for the lifetime of the ACH call.
//
SCH_CREDENTIALS Credentials;
//
// Holds TLS configuration for the lifetime of the ACH call.
//
TLS_PARAMETERS TlsParameters;
//
// Holds the blocked algorithms for the lifetime of the ACH call.
//
CRYPTO_SETTINGS CryptoSettings[4];
//
// Holds the list of blocked chaining modes for the lifetime of the ACH call.
//
UNICODE_STRING BlockedChainingModes[1];
} QUIC_ACH_CONTEXT;
typedef struct _SEC_BUFFER_WORKSPACE {
//
// Used to pass additional flags to Schannel.
//
SEC_FLAGS InSecFlags;
//
// Space for the output traffic secrets generated by Schannel.
//
uint8_t OutTrafSecBuf[SEC_TRAFFIC_SECRETS_COUNT*MAX_SEC_TRAFFIC_SECRETS_SIZE];
//
// Input sec buffers to pass to Schannel.
//
SecBuffer InSecBuffers[7];
//
// Output sec buffers to get data produced by Schannel.
//
SecBuffer OutSecBuffers[7];
} SEC_BUFFER_WORKSPACE;
typedef struct CXPLAT_TLS {
BOOLEAN IsServer : 1;
BOOLEAN GeneratedFirstPayload : 1;
BOOLEAN PeerTransportParamsReceived : 1;
BOOLEAN HandshakeKeyRead : 1;
BOOLEAN ApplicationKeyRead : 1;
//
// The TLS extension type for the QUIC transport parameters.
//
uint16_t QuicTpExtType;
//
// Cached server name indication.
//
const char* SNI;
//
// Schannel-allocated context for use between calls.
//
CtxtHandle SchannelContext;
//
// SecurityConfig information for this TLS stream.
//
CXPLAT_SEC_CONFIG* SecConfig;
//
// Labels for deriving key material.
//
const QUIC_HKDF_LABELS* HkdfLabels;
SEC_APPLICATION_PROTOCOLS* ApplicationProtocols;
ULONG AppProtocolsSize;
//
// Schannel encoded TLS extension buffer for QUIC TP.
//
SEND_GENERIC_TLS_EXTENSION* TransportParams;
//
// Callback context and handler for QUIC TP.
//
QUIC_CONNECTION* Connection;
//
// Workspace for sec buffers pass into ISC/ASC.
//
SEC_BUFFER_WORKSPACE Workspace;
//
// Peer Transport parameters length.
//
uint32_t PeerTransportParamsLength;
//
// Peer transport parameters for when heavy fragmentation doesn't
// provide enough storage for the peer transport parameters.
//
uint8_t* PeerTransportParams;
//
// Optional struct to log TLS traffic secrets.
// Only non-null when the connection is configured to log these.
//
QUIC_TLS_SECRETS* TlsSecrets;
} CXPLAT_TLS;
typedef enum QUIC_CERT_BLOB_TYPE {
QUIC_CERT_BLOB_NONE,
QUIC_CERT_BLOB_CHAIN,
QUIC_CERT_BLOB_CONTEXT,
QUIC_CERT_BLOB_SERIALIZED
} QUIC_CERT_BLOB_TYPE;
typedef struct QUIC_CERT_BLOB {
QUIC_CERT_BLOB_TYPE Type;
union {
SecPkgContext_Certificates Chain;
PCCERT_CONTEXT Context;
CERT_BLOB Serialized;
};
} QUIC_CERT_BLOB;
_Success_(return==TRUE)
BOOLEAN
QuicPacketKeyCreate(
_Inout_ CXPLAT_TLS* TlsContext,
_In_ QUIC_PACKET_KEY_TYPE KeyType,
_In_z_ const char* const SecretName,
_In_ const SEC_TRAFFIC_SECRETS* TrafficSecrets,
_Out_ QUIC_PACKET_KEY** Key
);
#define SecStatusToQuicStatus(x) (QUIC_STATUS)(x)
#ifdef _KERNEL_MODE
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
CxPlatTlsUtf8ToUnicodeString(
_In_z_ const char* Input,
_Inout_ PUNICODE_STRING Output,
_In_ uint32_t Tag
)
{
CXPLAT_DBG_ASSERT(Input != NULL);
CXPLAT_DBG_ASSERT(Output != NULL);
QUIC_STATUS Status;
ULONG RequiredSize = 0;
PWSTR UnicodeString = NULL;
size_t InputLength = strnlen_s(Input, QUIC_MAX_SNI_LENGTH + 1);
if (InputLength == QUIC_MAX_SNI_LENGTH + 1) {
Status = QUIC_STATUS_INVALID_PARAMETER;
goto Error;
}
InputLength++;
Status =
RtlUTF8ToUnicodeN(
UnicodeString,
RequiredSize,
&RequiredSize,
Input,
(ULONG) InputLength);
if (!NT_SUCCESS(Status)) {
QuicTraceEvent(
LibraryErrorStatus,
"[ lib] ERROR, %u, %s.",
Status,
"Get unicode string size");
goto Error;
}
UnicodeString = CXPLAT_ALLOC_NONPAGED(RequiredSize, Tag);
if (UnicodeString == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"unicode string",
RequiredSize);
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
Status =
RtlUTF8ToUnicodeN(
UnicodeString,
RequiredSize,
&RequiredSize,
Input,
(ULONG) InputLength);
if (!NT_SUCCESS(Status)) {
QuicTraceEvent(
LibraryErrorStatus,
"[ lib] ERROR, %u, %s.",
Status,
"Convert string to unicode");
goto Error;
}
CXPLAT_DBG_ASSERT(Output->Buffer == NULL);
Output->Buffer = UnicodeString;
UnicodeString = NULL;
Output->MaximumLength = (USHORT)RequiredSize;
Output->Length = Output->MaximumLength - sizeof(WCHAR);
Error:
if (UnicodeString != NULL) {
CXPLAT_FREE(UnicodeString, Tag);
UnicodeString = NULL;
}
return Status;
}
#endif
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
CxPlatTlsSetClientCertPolicy(
_In_ CXPLAT_SEC_CONFIG* SecConfig
)
{
SECURITY_STATUS SecStatus = SEC_E_OK;
SecPkgCred_ClientCertPolicy ClientCertPolicy;
CXPLAT_DBG_ASSERT(!(SecConfig->Flags & QUIC_CREDENTIAL_FLAG_CLIENT));
CxPlatZeroMemory(&ClientCertPolicy, sizeof(ClientCertPolicy));
ClientCertPolicy.guidPolicyId = CxPlatTlsClientCertPolicyGuid;
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_END_CERT) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_REVOCATION_CHECK_END_CERT;
}
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CHAIN) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN;
}
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
}
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_CACHE_ONLY_URL_RETRIEVAL) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL;
}
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REVOCATION_CHECK_CACHE_ONLY) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY;
}
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_DISABLE_AIA) {
ClientCertPolicy.dwCertFlags |= CERT_CHAIN_DISABLE_AIA;
}
SecStatus =
SetCredentialsAttributesW(
&SecConfig->CredentialHandle,
SECPKG_ATTR_CLIENT_CERT_POLICY,
&ClientCertPolicy,
sizeof(ClientCertPolicy));
if (SecStatus != SEC_E_OK) {
QuicTraceEvent(
LibraryErrorStatus,
"[ lib] ERROR, %u, %s.",
SecStatus,
"SetCredentialsAttributesW(SECPKG_ATTR_CLIENT_CERT_POLICY) failed");
}
if (SecStatus == SEC_E_UNSUPPORTED_FUNCTION) {
return QUIC_STATUS_NOT_SUPPORTED;
}
return SecStatusToQuicStatus(SecStatus);
}
_IRQL_requires_max_(DISPATCH_LEVEL)
__drv_allocatesMem(Mem)
_Must_inspect_result_
_Success_(return != NULL)
QUIC_ACH_CONTEXT*
CxPlatTlsAllocateAchContext(
_In_ const QUIC_CREDENTIAL_CONFIG* CredConfig,
_In_opt_ void* Context,
_In_ CXPLAT_SEC_CONFIG_CREATE_COMPLETE_HANDLER Callback
)
{
QUIC_ACH_CONTEXT* AchContext = CXPLAT_ALLOC_NONPAGED(sizeof(QUIC_ACH_CONTEXT), QUIC_POOL_TLS_ACHCTX);
if (AchContext == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"QUIC_ACH_CONTEXT",
sizeof(QUIC_ACH_CONTEXT));
} else {
RtlZeroMemory(AchContext, sizeof(*AchContext));
AchContext->CredConfig = *CredConfig;
AchContext->CompletionContext = Context;
AchContext->CompletionCallback = Callback;
AchContext->TlsParameters.pDisabledCrypto = AchContext->CryptoSettings;
AchContext->TlsParameters.cDisabledCrypto = 2; // initialized to the basic blocked cipher suites.
AchContext->Credentials.pTlsParameters = &AchContext->TlsParameters;
AchContext->Credentials.cTlsParameters = 1;
#ifdef _KERNEL_MODE
if (!(AchContext->CredConfig.Flags & QUIC_CREDENTIAL_FLAG_LOAD_ASYNCHRONOUS)) {
KeInitializeEvent(&AchContext->CompletionEvent, NotificationEvent, FALSE);
}
#endif
}
return AchContext;
}
void
CxPlatTlsFreeAchContext(
_In_ QUIC_ACH_CONTEXT* AchContext
)
{
#ifdef _KERNEL_MODE
if (AchContext->Principal.Buffer != NULL) {
CXPLAT_FREE(AchContext->Principal.Buffer, QUIC_POOL_TLS_PRINCIPAL);
RtlZeroMemory(&AchContext->Principal, sizeof(AchContext->Principal));
}
if (AchContext->SspiContext != NULL) {
SspiFreeAsyncContext(AchContext->SspiContext);
}
#endif
if (AchContext->SecConfig != NULL) {
CxPlatTlsSecConfigDelete(AchContext->SecConfig);
}
CXPLAT_FREE(AchContext, QUIC_POOL_TLS_ACHCTX);
}
#ifdef _KERNEL_MODE
void
CxPlatTlsSspiNotifyCallback(
_In_ SspiAsyncContext* Handle,
_In_opt_ void* CallbackData
)
{
if (CallbackData == NULL) {
QuicTraceEvent(
LibraryError,
"[ lib] ERROR, %s.",
"NULL CallbackData to CxPlatTlsSspiNotifyCallback");
return;
}
QUIC_ACH_CONTEXT* AchContext = CallbackData;
BOOLEAN IsAsync = !!(AchContext->CredConfig.Flags & QUIC_CREDENTIAL_FLAG_LOAD_ASYNCHRONOUS);
CXPLAT_SEC_CONFIG_CREATE_COMPLETE_HANDLER CompletionCallback = AchContext->CompletionCallback;
void* CompletionContext = AchContext->CompletionContext;
CXPLAT_SEC_CONFIG* SecConfig = AchContext->SecConfig;
AchContext->SecConfig = NULL;
SECURITY_STATUS Status = SspiGetAsyncCallStatus(Handle);
AchContext->CompletionStatus = SecStatusToQuicStatus(Status);
QUIC_CREDENTIAL_CONFIG CredConfig = AchContext->CredConfig;
if (IsAsync) {
CxPlatTlsFreeAchContext(AchContext);
}
if (Status != SEC_E_OK) {
QuicTraceEvent(
LibraryErrorStatus,
"[ lib] ERROR, %u, %s.",
Status,
"Completion for SspiAcquireCredentialsHandleAsyncW");
CompletionCallback(&CredConfig, CompletionContext, SecStatusToQuicStatus(Status), NULL);
CxPlatTlsSecConfigDelete(SecConfig); // *MUST* be last call to prevent crash in platform cleanup.
} else {
Status = (SECURITY_STATUS)QUIC_STATUS_SUCCESS;
if (SecConfig->Flags & QUIC_CREDENTIAL_FLAG_REQUIRE_CLIENT_AUTHENTICATION) {
Status = (SECURITY_STATUS)CxPlatTlsSetClientCertPolicy(SecConfig);
}
CompletionCallback(&CredConfig, CompletionContext, (QUIC_STATUS)Status, SecConfig);
}
if (!IsAsync) {
KeSetEvent(&AchContext->CompletionEvent, IO_NO_INCREMENT, FALSE);
}
}
const static UNICODE_STRING CxPlatTlsPackageName = RTL_CONSTANT_STRING(L"Schannel");
typedef struct TLS_WORKER_CONTEXT {
NTSTATUS CompletionStatus;
QUIC_ACH_CONTEXT* AchContext;
} TLS_WORKER_CONTEXT;
_IRQL_requires_same_
void
CxPlatTlsAchHelper(
_In_ TLS_WORKER_CONTEXT* ThreadContext
)
{
QUIC_ACH_CONTEXT* AchContext = ThreadContext->AchContext;
BOOLEAN IsClient = !!(AchContext->CredConfig.Flags & QUIC_CREDENTIAL_FLAG_CLIENT);
BOOLEAN IsAsync = !!(AchContext->CredConfig.Flags & QUIC_CREDENTIAL_FLAG_LOAD_ASYNCHRONOUS);
QuicTraceLogVerbose(
SchannelAchAsync,
"[ tls] Calling SspiAcquireCredentialsHandleAsyncW");
SECURITY_STATUS SecStatus =
SspiAcquireCredentialsHandleAsyncW(
AchContext->SspiContext,
IsClient ? NULL : &AchContext->Principal,
(PSECURITY_STRING)&CxPlatTlsPackageName,
IsClient ? SECPKG_CRED_OUTBOUND : SECPKG_CRED_INBOUND,
NULL,
&AchContext->Credentials,
NULL,
NULL,
&AchContext->SecConfig->CredentialHandle,
NULL);
if (SecStatus != SEC_E_OK) {
QuicTraceEvent(
LibraryErrorStatus,
"[ lib] ERROR, %u, %s.",
SecStatus,
"SspiAcquireCredentialsHandleAsyncW");
ThreadContext->CompletionStatus = SecStatusToQuicStatus(SecStatus);
} else {
if (IsAsync) {
ThreadContext->CompletionStatus = QUIC_STATUS_PENDING;
ThreadContext->AchContext = NULL;
} else {
KeWaitForSingleObject(&AchContext->CompletionEvent, Executive, KernelMode, FALSE, NULL);
ThreadContext->CompletionStatus = AchContext->CompletionStatus;
}
}
}
_Function_class_(KSTART_ROUTINE)
_IRQL_requires_same_
void
CxPlatTlsAchWorker(
_In_ void* Context
)
{
TLS_WORKER_CONTEXT* ThreadContext = Context;
CxPlatTlsAchHelper(ThreadContext);
PsTerminateSystemThread(STATUS_SUCCESS);
}
#endif
_IRQL_requires_max_(DISPATCH_LEVEL)
QUIC_TLS_PROVIDER
CxPlatTlsGetProvider(
void
)
{
return QUIC_TLS_PROVIDER_SCHANNEL;
}
_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
)
{
CXPLAT_DBG_ASSERT(CredConfig && CompletionHandler);
SECURITY_STATUS SecStatus;
QUIC_STATUS Status = QUIC_STATUS_SUCCESS;
BOOLEAN IsClient = !!(CredConfig->Flags & QUIC_CREDENTIAL_FLAG_CLIENT);
if (CredConfig->Reserved != NULL) {
return QUIC_STATUS_INVALID_PARAMETER; // Not currently used and should be NULL.
}
#ifndef _KERNEL_MODE
PCERT_CONTEXT CertContext = NULL;
if (CredConfig->Flags & QUIC_CREDENTIAL_FLAG_LOAD_ASYNCHRONOUS) {
return QUIC_STATUS_NOT_SUPPORTED;
}
#endif
if ((CredConfig->Flags & QUIC_CREDENTIAL_FLAG_DEFER_CERTIFICATE_VALIDATION) &&
!(CredConfig->Flags & QUIC_CREDENTIAL_FLAG_INDICATE_CERTIFICATE_RECEIVED)) {
return QUIC_STATUS_INVALID_PARAMETER; // Defer validation without indication doesn't make sense.
}
if (IsClient) {
if ((CredConfig->Flags & QUIC_CREDENTIAL_FLAG_REQUIRE_CLIENT_AUTHENTICATION) ||
(CredConfig->Flags & QUIC_CREDENTIAL_FLAG_USE_SYSTEM_MAPPER)) {
return QUIC_STATUS_INVALID_PARAMETER; // Client authentication is a server-only flag.
}