Artifactspublic-v0

curl

master
ply4 git calls37 ms313 KiB3 cachedprotocol v2
2926 lines99 KiBRaw
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 * Copyright (C) Marc Hoersken, <info@marc-hoersken.de>
10 * Copyright (C) Mark Salisbury, <mark.salisbury@hp.com>
11 *
12 * This software is licensed as described in the file COPYING, which
13 * you should have received as part of this distribution. The terms
14 * are also available at https://curl.se/docs/copyright.html.
15 *
16 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
17 * copies of the Software, and permit persons to whom the Software is
18 * furnished to do so, under the terms of the COPYING file.
19 *
20 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21 * KIND, either express or implied.
22 *
23 * SPDX-License-Identifier: curl
24 *
25 ***************************************************************************/
26/*
27 * Source file for all Schannel-specific code for the TLS/SSL layer. No code
28 * but vtls.c should ever call or use these functions.
29 */
30#include "curl_setup.h"
32#ifdef USE_SCHANNEL
34#ifndef USE_WINDOWS_SSPI
35#error "cannot compile Schannel support without SSPI."
36#endif
38#include "vtls/schannel.h"
39#include "vtls/schannel_int.h"
40#include "vtls/vtls.h"
41#include "vtls/vtls_int.h"
42#include "vtls/vtls_scache.h"
43#include "curl_trc.h"
44#include "connect.h" /* for the connect timeout */
45#include "curlx/strdup.h"
46#include "strerror.h"
47#include "select.h" /* for the socket readiness */
48#include "curlx/win32-fopen.h"
49#include "curlx/multibyte.h"
50#include "vtls/x509asn1.h"
51#include "curlx/version_win32.h"
52#include "curlx/winapi.h"
53#include "curlx/strparse.h"
54#include "progress.h"
55#include "curl_sha256.h"
57/* Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF()
58 * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These
59 * messages are extra verbose and intended for curl developers debugging
60 * Schannel recv decryption and renegotiation.
61 */
62#ifdef CURL_SCHANNEL_DEV_DEBUG
63#define SCH_DEV(x) x
64#define SCH_DEV_SHOWBOOL(x) \
65 do { \
66 infof(data, "schannel: " #x " %s", (x) ? "TRUE" : "FALSE"); \
67 } while(0)
68#else
69#define SCH_DEV(x) do {} while(0)
70#define SCH_DEV_SHOWBOOL(x) do {} while(0)
71#endif
73/* Offered by mingw-w64 v8+, MS SDK 7.0A/VS2010+ */
74#ifndef SP_PROT_TLS1_0_CLIENT
75#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
76#endif
77#ifndef SP_PROT_TLS1_1_CLIENT
78#define SP_PROT_TLS1_1_CLIENT 0x00000200
79#endif
80#ifndef SP_PROT_TLS1_2_CLIENT
81#define SP_PROT_TLS1_2_CLIENT 0x00000800
82#endif
84/* Offered by mingw-w64 v8+, MS SDK 10.0.15063.0/VS2017 15.1+ */
85#ifndef SP_PROT_TLS1_3_CLIENT
86#define SP_PROT_TLS1_3_CLIENT 0x00002000
87#endif
88/* Offered by mingw-w64 v8+, MS SDK 8.1/VS2013+ */
89#ifndef SCH_USE_STRONG_CRYPTO
90#define SCH_USE_STRONG_CRYPTO 0x00400000
91#endif
93/* Offered by mingw-w64 v10+, MS SDK 7.0A/VS2010+ */
94#ifndef SECBUFFER_ALERT
95#define SECBUFFER_ALERT 17
96#endif
98/* Both schannel buffer sizes must be > 0 */
99#define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096
100#define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024
102#define CERT_THUMBPRINT_STR_LEN 40
103#define CERT_THUMBPRINT_DATA_LEN 20
105/* Uncomment to force verbose output
106 * #define infof(x, y, ...) curl_mprintf(y, __VA_ARGS__)
107 * #define failf(x, y, ...) curl_mprintf(y, __VA_ARGS__)
108 */
110/* Offered by mingw-w64 v4+, MS SDK 6.0A/VS2008+ */
111#ifndef PKCS12_NO_PERSIST_KEY
112#define PKCS12_NO_PERSIST_KEY 0x00008000
113#endif
115/* Offered by mingw-w64 v4+, MS SDK 8.0/~VS2012+ */
116#ifndef CERT_FIND_HAS_PRIVATE_KEY
117#define CERT_FIND_HAS_PRIVATE_KEY (21 << CERT_COMPARE_SHIFT)
118#endif
120/* key to use at `multi->proto_hash` */
121#define MPROTO_SCHANNEL_CERT_SHARE_KEY "tls:schannel:cert:share"
123static bool s_win_has_alpn;
125/* Offered by mingw-w64 v9+, MS SDK 8.1/VS2013+ */
126#ifndef SECBUFFER_APPLICATION_PROTOCOLS
127#define SECBUFFER_APPLICATION_PROTOCOLS 18
128#define SECPKG_ATTR_APPLICATION_PROTOCOL 35
130typedef enum {
131 SecApplicationProtocolNegotiationExt_None,
132 SecApplicationProtocolNegotiationExt_NPN,
133 SecApplicationProtocolNegotiationExt_ALPN
134} SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT;
136typedef enum {
137 SecApplicationProtocolNegotiationStatus_None,
138 SecApplicationProtocolNegotiationStatus_Success,
139 SecApplicationProtocolNegotiationStatus_SelectedClientOnly
140} SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS;
142/* !checksrc! disable TYPEDEFSTRUCT 1 */
143typedef struct {
144 SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS ProtoNegoStatus;
145 SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT ProtoNegoExt;
146 unsigned char ProtocolIdSize;
147 unsigned char ProtocolId[0xff];
148} SecPkgContext_ApplicationProtocol;
149#endif
151static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType,
152 void *BufDataPtr, unsigned long BufByteSize)
154 buffer->cbBuffer = BufByteSize;
155 buffer->BufferType = BufType;
156 buffer->pvBuffer = BufDataPtr;
159static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr,
160 unsigned long NumArrElem)
162 desc->ulVersion = SECBUFFER_VERSION;
163 desc->pBuffers = BufArr;
164 desc->cBuffers = NumArrElem;
167static CURLcode schannel_set_ssl_version_min_max(DWORD *enabled_protocols,
168 struct Curl_cfilter *cf,
169 struct Curl_easy *data)
171 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
172 long ssl_version = conn_config->version;
173 long ssl_version_max = (long)conn_config->version_max;
174 long i = ssl_version;
176 switch(ssl_version_max) {
177 case CURL_SSLVERSION_MAX_NONE:
178 case CURL_SSLVERSION_MAX_DEFAULT:
180 /* Windows Server 2022 and newer (including Windows 11) support TLS 1.3
181 built-in. Previous builds of Windows 10 had broken TLS 1.3
182 implementations that could be enabled via registry. */
183 if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT,
184 VERSION_GREATER_THAN_EQUAL)) {
185 ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3;
186 }
187 else /* Windows 10 or older */
188 ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
190 break;
191 }
193 for(; i <= (ssl_version_max >> 16); ++i) {
194 switch(i) {
195 case CURL_SSLVERSION_TLSv1_0:
196 *enabled_protocols |= SP_PROT_TLS1_0_CLIENT;
197 break;
198 case CURL_SSLVERSION_TLSv1_1:
199 *enabled_protocols |= SP_PROT_TLS1_1_CLIENT;
200 break;
201 case CURL_SSLVERSION_TLSv1_2:
202 *enabled_protocols |= SP_PROT_TLS1_2_CLIENT;
203 break;
204 case CURL_SSLVERSION_TLSv1_3:
206 /* Windows Server 2022 or newer */
207 if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT,
208 VERSION_GREATER_THAN_EQUAL)) {
209 *enabled_protocols |= SP_PROT_TLS1_3_CLIENT;
210 break;
211 }
212 else { /* Windows 10 or older */
213 failf(data, "schannel: TLS 1.3 not supported on Windows 10 or older");
214 return CURLE_SSL_CONNECT_ERROR;
215 }
216 }
217 }
218 return CURLE_OK;
221#define CIPHEROPTION(x) { #x, x }
223struct algo {
224 const char *name;
225 int id;
226};
228static const struct algo algs[] = {
229 CIPHEROPTION(CALG_MD2),
230 CIPHEROPTION(CALG_MD4),
231 CIPHEROPTION(CALG_MD5),
232 CIPHEROPTION(CALG_SHA),
233 CIPHEROPTION(CALG_SHA1),
234 CIPHEROPTION(CALG_MAC),
235 CIPHEROPTION(CALG_RSA_SIGN),
236 CIPHEROPTION(CALG_DSS_SIGN),
237 CIPHEROPTION(CALG_NO_SIGN),
238 CIPHEROPTION(CALG_RSA_KEYX),
239 CIPHEROPTION(CALG_DES),
240 CIPHEROPTION(CALG_3DES_112),
241 CIPHEROPTION(CALG_3DES),
242 CIPHEROPTION(CALG_DESX),
243 CIPHEROPTION(CALG_RC2),
244 CIPHEROPTION(CALG_RC4),
245 CIPHEROPTION(CALG_SEAL),
246 CIPHEROPTION(CALG_DH_SF),
247 CIPHEROPTION(CALG_DH_EPHEM),
248 CIPHEROPTION(CALG_AGREEDKEY_ANY),
249 CIPHEROPTION(CALG_HUGHES_MD5),
250 CIPHEROPTION(CALG_SKIPJACK),
251 CIPHEROPTION(CALG_TEK),
252 CIPHEROPTION(CALG_CYLINK_MEK), /* spellchecker:disable-line */
253 CIPHEROPTION(CALG_SSL3_SHAMD5),
254 CIPHEROPTION(CALG_SSL3_MASTER),
255 CIPHEROPTION(CALG_SCHANNEL_MASTER_HASH),
256 CIPHEROPTION(CALG_SCHANNEL_MAC_KEY),
257 CIPHEROPTION(CALG_SCHANNEL_ENC_KEY),
258 CIPHEROPTION(CALG_PCT1_MASTER),
259 CIPHEROPTION(CALG_SSL2_MASTER),
260 CIPHEROPTION(CALG_TLS1_MASTER),
261 CIPHEROPTION(CALG_RC5),
262 CIPHEROPTION(CALG_HMAC),
263 CIPHEROPTION(CALG_TLS1PRF),
264 CIPHEROPTION(CALG_HASH_REPLACE_OWF),
265 CIPHEROPTION(CALG_AES_128),
266 CIPHEROPTION(CALG_AES_192),
267 CIPHEROPTION(CALG_AES_256),
268 CIPHEROPTION(CALG_AES),
269 CIPHEROPTION(CALG_SHA_256),
270 CIPHEROPTION(CALG_SHA_384),
271 CIPHEROPTION(CALG_SHA_512),
272 CIPHEROPTION(CALG_ECDH),
273/* Offered by mingw-w64 v4+, MS SDK 6.0A/VS2008+ */
274#ifdef CALG_ECMQV
275 CIPHEROPTION(CALG_ECMQV),
276#endif
277 CIPHEROPTION(CALG_ECDSA),
278/* Offered by mingw-w64 v7+, MS SDK 7.0A/VS2010+ */
279#ifdef CALG_ECDH_EPHEM
280 CIPHEROPTION(CALG_ECDH_EPHEM),
281#endif
282 { NULL, 0 },
283};
285static int get_alg_id_by_name(const char *name)
287 const char *nameEnd = strchr(name, ':');
288 size_t n = nameEnd ? (size_t)(nameEnd - name) : strlen(name);
289 int i;
291 for(i = 0; algs[i].name; i++) {
292 if((n == strlen(algs[i].name) && !strncmp(algs[i].name, name, n)))
293 return algs[i].id;
294 }
295 return 0; /* not found */
298#define NUM_CIPHERS 47 /* There are a maximum of 47 options listed above */
300static CURLcode set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers,
301 ALG_ID *algIds)
303 const char *startCur = ciphers;
304 int algCount = 0;
305 while(startCur && *startCur && (algCount < NUM_CIPHERS)) {
306 curl_off_t alg;
307 if(curlx_str_number(&startCur, &alg, INT_MAX) || !alg)
308 alg = get_alg_id_by_name(startCur);
310 if(alg)
311 algIds[algCount++] = (ALG_ID)alg;
312 else if(!strncmp(startCur, "USE_STRONG_CRYPTO",
313 CURL_CSTRLEN("USE_STRONG_CRYPTO")) ||
314 !strncmp(startCur, "SCH_USE_STRONG_CRYPTO",
315 CURL_CSTRLEN("SCH_USE_STRONG_CRYPTO")))
316 schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO;
317 else
318 return CURLE_SSL_CIPHER;
319 startCur = strchr(startCur, ':');
320 if(startCur)
321 startCur++;
322 }
323 schannel_cred->palgSupportedAlgs = algIds;
324 schannel_cred->cSupportedAlgs = (DWORD)algCount;
325 return CURLE_OK;
328/* Function allocates memory for store_path only if CURLE_OK is returned */
329static CURLcode get_cert_location(TCHAR *path, DWORD *store_name,
330 TCHAR **store_path, TCHAR **thumbprint)
332 TCHAR *sep;
333 TCHAR *store_path_start;
334 size_t store_name_len;
336 sep = _tcschr(path, _TEXT('\\'));
337 if(!sep)
338 return CURLE_SSL_CERTPROBLEM;
340 store_name_len = sep - path;
342 if(_tcsncmp(path, _TEXT("CurrentUser"), store_name_len) == 0)
343 *store_name = CERT_SYSTEM_STORE_CURRENT_USER;
344 else if(_tcsncmp(path, _TEXT("LocalMachine"), store_name_len) == 0)
345 *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE;
346 else if(_tcsncmp(path, _TEXT("CurrentService"), store_name_len) == 0)
347 *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE;
348 else if(_tcsncmp(path, _TEXT("Services"), store_name_len) == 0)
349 *store_name = CERT_SYSTEM_STORE_SERVICES;
350 else if(_tcsncmp(path, _TEXT("Users"), store_name_len) == 0)
351 *store_name = CERT_SYSTEM_STORE_USERS;
352 else if(_tcsncmp(path, _TEXT("CurrentUserGroupPolicy"), store_name_len) == 0)
353 *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY;
354 else if(_tcsncmp(path, _TEXT("LocalMachineGroupPolicy"), store_name_len) ==
355 0)
356 *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY;
357 else if(_tcsncmp(path, _TEXT("LocalMachineEnterprise"), store_name_len) == 0)
358 *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE;
359 else
360 return CURLE_SSL_CERTPROBLEM;
362 store_path_start = sep + 1;
364 sep = _tcschr(store_path_start, _TEXT('\\'));
365 if(!sep)
366 return CURLE_SSL_CERTPROBLEM;
368 *thumbprint = sep + 1;
369 if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN)
370 return CURLE_SSL_CERTPROBLEM;
372 *sep = _TEXT('\0');
373 *store_path = curlx_tcsdup(store_path_start);
374 *sep = _TEXT('\\');
375 if(!*store_path)
376 return CURLE_OUT_OF_MEMORY;
378 return CURLE_OK;
381static CURLcode get_client_cert(struct Curl_cfilter *cf,
382 struct Curl_easy *data,
383 HCERTSTORE *out_cert_store,
384 PCCERT_CONTEXT *out_cert_context)
386 struct ssl_filter_config *sslc = Curl_ssl_cf_get_filter_config(cf);
387 PCCERT_CONTEXT client_cert = NULL;
388 HCERTSTORE client_cert_store = NULL;
389 CURLcode result = CURLE_OK;
391 if(sslc->clientcert || sslc->cert_blob) {
392 DWORD cert_store_name = 0;
393 TCHAR *cert_store_path = NULL;
394 TCHAR *cert_thumbprint_str = NULL;
395 TCHAR cert_thumbprint_buf[CERT_THUMBPRINT_STR_LEN + 1];
396 CRYPT_HASH_BLOB cert_thumbprint;
397 BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN];
398 HCERTSTORE cert_store = NULL;
399 FILE *fInCert = NULL;
400 void *certdata = NULL;
401 size_t certsize = 0;
402 bool blob = !!sslc->cert_blob;
404 if(blob) {
405 certdata = sslc->cert_blob->data;
406 certsize = sslc->cert_blob->len;
407 }
408 else {
409 TCHAR *cert_path =
410 curlx_convert_UTF8_to_tchar(sslc->clientcert);
411 if(!cert_path)
412 return CURLE_OUT_OF_MEMORY;
414 result = get_cert_location(cert_path, &cert_store_name,
415 &cert_store_path, &cert_thumbprint_str);
417 /* 'cert_thumbprint_str' points in to the allocated 'cert_path', copy
418 the data. The string is verified to be CERT_THUMBPRINT_STR_LEN bytes
419 long within the get_cert_location() function. */
420 if(!result && cert_thumbprint_str) {
421 memcpy(cert_thumbprint_buf, cert_thumbprint_str,
422 sizeof(cert_thumbprint_buf));
423 cert_thumbprint_str = cert_thumbprint_buf;
424 }
426 curlx_free(cert_path);
427 if(result && (sslc->clientcert[0] != '\0'))
428 fInCert = curlx_fopen(sslc->clientcert, "rb");
430 if(result && !fInCert) {
431 failf(data, "schannel: Failed to get certificate location"
432 " or file for %s",
433 sslc->clientcert);
434 return result;
435 }
436 }
438 if((fInCert || blob) && sslc->cert_type &&
439 !curl_strequal(sslc->cert_type, "P12")) {
440 failf(data, "schannel: certificate format compatibility error "
441 "for %s",
442 blob ? "(memory blob)" : sslc->clientcert);
443 curlx_free(cert_store_path);
444 if(fInCert)
445 curlx_fclose(fInCert);
446 return CURLE_SSL_CERTPROBLEM;
447 }
449 if(fInCert || blob) {
450 /* Reading a .p12 or .pfx file, like the example at bottom of
451 https://learn.microsoft.com/archive/msdn-technet-forums/3e7bc95f-b21a-4bcd-bd2c-7f996718cae5
452 */
453 CRYPT_DATA_BLOB datablob;
454 WCHAR *pszPassword;
455 size_t pwd_len = 0;
456 int cert_find_flags;
457 const char *cert_showfilename_error = blob ?
458 "(memory blob)" : sslc->clientcert;
459 curlx_free(cert_store_path);
460 if(fInCert) {
461 long cert_tell = 0;
462 bool continue_reading = fseek(fInCert, 0, SEEK_END) == 0;
463 if(continue_reading) {
464 cert_tell = ftell(fInCert);
465 if(cert_tell < 0)
466 continue_reading = FALSE;
467 else
468 certsize = (size_t)cert_tell;
469 }
470 if(continue_reading)
471 continue_reading = fseek(fInCert, 0, SEEK_SET) == 0;
472 if(continue_reading && (certsize < CURL_MAX_INPUT_LENGTH))
473 certdata = curlx_malloc(certsize + 1);
474 if(!certdata || ((int)fread(certdata, certsize, 1, fInCert) != 1))
475 continue_reading = FALSE;
476 curlx_fclose(fInCert);
477 if(!continue_reading) {
478 failf(data, "schannel: Failed to read cert file %s",
479 sslc->clientcert);
480 curlx_free(certdata);
481 return CURLE_SSL_CERTPROBLEM;
482 }
483 }
485 /* Convert key-pair data to the in-memory certificate store */
486 datablob.pbData = (BYTE *)certdata;
487 datablob.cbData = (DWORD)certsize;
489 if(sslc->key_passwd)
490 pwd_len = strlen(sslc->key_passwd);
491 pszPassword = curlx_malloc(sizeof(WCHAR) * (pwd_len + 1));
492 if(pszPassword) {
493 int str_w_len = 0;
494 if(pwd_len > 0)
495 str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
496 sslc->key_passwd, (int)pwd_len,
497 pszPassword, (int)(pwd_len + 1));
499 if((str_w_len >= 0) && (str_w_len <= (int)pwd_len))
500 pszPassword[str_w_len] = 0;
501 else
502 pszPassword[0] = 0;
504 cert_store = PFXImportCertStore(&datablob, pszPassword,
505 PKCS12_NO_PERSIST_KEY);
506 curlx_memzero(pszPassword, sizeof(WCHAR) * (pwd_len + 1));
507 curlx_free(pszPassword);
508 }
509 if(!blob)
510 curlx_free(certdata);
511 if(!cert_store) {
512 DWORD errorcode = GetLastError();
513 if(errorcode == ERROR_INVALID_PASSWORD)
514 failf(data, "schannel: Failed to import cert file %s, "
515 "password is bad",
516 cert_showfilename_error);
517 else
518 failf(data, "schannel: Failed to import cert file %s, "
519 "last error is 0x%08lx",
520 cert_showfilename_error, errorcode);
521 return CURLE_SSL_CERTPROBLEM;
522 }
524 /* CERT_FIND_HAS_PRIVATE_KEY is only available in Windows 8 / Server
525 2012, (NT 6.2). For older versions we use CURL_FIND_ANY. */
526 if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT,
527 VERSION_GREATER_THAN_EQUAL))
528 cert_find_flags = CERT_FIND_HAS_PRIVATE_KEY;
529 else
530 cert_find_flags = CERT_FIND_ANY;
532 client_cert =
533 CertFindCertificateInStore(cert_store,
534 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
535 cert_find_flags, NULL, NULL);
537 if(!client_cert) {
538 failf(data, "schannel: Failed to get certificate from file %s"
539 ", last error is 0x%08lx",
540 cert_showfilename_error, GetLastError());
541 CertCloseStore(cert_store, 0);
542 return CURLE_SSL_CERTPROBLEM;
543 }
544 }
545 else {
546 cert_store =
547 CertOpenStore(
548#ifdef UNICODE
549 CERT_STORE_PROV_SYSTEM_W,
550#else
551 CERT_STORE_PROV_SYSTEM_A,
552#endif
553 0,
554 (HCRYPTPROV)NULL,
555 CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name,
556 cert_store_path);
557 if(!cert_store) {
558 char *path_utf8 =
559 curlx_convert_tchar_to_UTF8(cert_store_path);
560 failf(data, "schannel: Failed to open cert store %lx %s, "
561 "last error is 0x%08lx",
562 cert_store_name, (path_utf8 ? path_utf8 : "(unknown)"),
563 GetLastError());
564 curlx_free(cert_store_path);
565 curlx_free(path_utf8);
566 return CURLE_SSL_CERTPROBLEM;
567 }
568 curlx_free(cert_store_path);
570 cert_thumbprint.pbData = cert_thumbprint_data;
571 cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN;
573 if(!CryptStringToBinary(cert_thumbprint_str,
574 CERT_THUMBPRINT_STR_LEN,
575 CRYPT_STRING_HEX,
576 cert_thumbprint_data,
577 &cert_thumbprint.cbData,
578 NULL, NULL)) {
579 CertCloseStore(cert_store, 0);
580 return CURLE_SSL_CERTPROBLEM;
581 }
583 client_cert =
584 CertFindCertificateInStore(cert_store,
585 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
586 CERT_FIND_HASH, &cert_thumbprint, NULL);
587 if(!client_cert) {
588 /* CRYPT_E_NOT_FOUND / E_INVALIDARG */
589 CertCloseStore(cert_store, 0);
590 failf(data, "schannel: client cert not found in cert store");
591 return CURLE_SSL_CERTPROBLEM;
592 }
593 }
594 client_cert_store = cert_store;
595 }
597 *out_cert_store = client_cert_store;
598 *out_cert_context = client_cert;
600 return CURLE_OK;
603static CURLcode acquire_sspi_handle(struct Curl_cfilter *cf,
604 struct Curl_easy *data,
605 struct schannel_ssl_backend_data *backend,
606 PCCERT_CONTEXT client_cert,
607 DWORD flags,
608 DWORD enabled_protocols)
610 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
611 SECURITY_STATUS sspi_status = SEC_E_OK;
612 CURLcode result;
614 /* We support TLS 1.3 starting in Windows Server 2022 or later
615 * (OS build 20348) */
616 if(!conn_config->cipher_list &&
617 curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT,
618 VERSION_GREATER_THAN_EQUAL)) {
620 SCH_CREDENTIALS credentials = { 0 };
621 TLS_PARAMETERS tls_parameters = { 0 };
622 CRYPTO_SETTINGS crypto_settings[1];
623 PCCERT_CONTEXT client_certs[1];
625 if(client_cert)
626 client_certs[0] = client_cert;
627 else
628 client_certs[0] = NULL;
630 memset(crypto_settings, 0, sizeof(crypto_settings));
632 tls_parameters.pDisabledCrypto = crypto_settings;
634 /* The number of blocked suites */
635 tls_parameters.cDisabledCrypto = (DWORD)0;
636 credentials.pTlsParameters = &tls_parameters;
637 credentials.cTlsParameters = 1;
639 credentials.dwVersion = SCH_CREDENTIALS_VERSION;
640 credentials.dwFlags = flags | SCH_USE_STRONG_CRYPTO;
642 credentials.pTlsParameters->grbitDisabledProtocols = ~enabled_protocols;
644 if(client_certs[0]) {
645 credentials.cCreds = 1;
646 credentials.paCred = client_certs;
647 }
649 sspi_status =
650 Curl_pSecFn->AcquireCredentialsHandle(NULL, CURL_UNCONST(UNISP_NAME),
651 SECPKG_CRED_OUTBOUND, NULL,
652 &credentials, NULL, NULL,
653 &backend->cred->cred_handle, NULL);
654 }
655 else {
656 /* Pre-Windows 10 1809 or the user set a legacy algorithm list.
657 Schannel does not negotiate TLS 1.3 when SCHANNEL_CRED is used. */
658 ALG_ID algIds[NUM_CIPHERS];
659 char *ciphers = conn_config->cipher_list;
660 SCHANNEL_CRED schannel_cred = { 0 };
661 PCCERT_CONTEXT client_certs[1];
663 if(client_cert)
664 client_certs[0] = client_cert;
665 else
666 client_certs[0] = NULL;
668 schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
669 schannel_cred.dwFlags = flags;
670 schannel_cred.grbitEnabledProtocols = enabled_protocols;
672 if(ciphers) {
673 if((enabled_protocols & SP_PROT_TLS1_3_CLIENT)) {
674 if(!(enabled_protocols & ~SP_PROT_TLS1_3_CLIENT)) {
675 failf(data, "schannel: TLS 1.3 is not supported with a cipher list; "
676 "remove the cipher list or allow a lower TLS version");
677 return CURLE_SSL_CONNECT_ERROR;
678 }
679 infof(data, "schannel: WARNING: This version of Schannel "
680 "negotiates a less-secure TLS version than TLS 1.3 because the "
681 "user set an algorithm cipher list.");
682 }
683 result = set_ssl_ciphers(&schannel_cred, ciphers, algIds);
684 if(result) {
685 failf(data, "schannel: Failed setting algorithm cipher list");
686 return result;
687 }
688 }
689 else {
690 schannel_cred.dwFlags = flags | SCH_USE_STRONG_CRYPTO;
691 }
693 if(client_certs[0]) {
694 schannel_cred.cCreds = 1;
695 schannel_cred.paCred = client_certs;
696 }
698 sspi_status =
699 Curl_pSecFn->AcquireCredentialsHandle(NULL, CURL_UNCONST(UNISP_NAME),
700 SECPKG_CRED_OUTBOUND, NULL,
701 &schannel_cred, NULL, NULL,
702 &backend->cred->cred_handle, NULL);
703 }
705 if(sspi_status != SEC_E_OK) {
706 char buffer[STRERROR_LEN];
707 failf(data, "schannel: AcquireCredentialsHandle failed: %s",
708 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
709 switch(sspi_status) {
710 case SEC_E_INSUFFICIENT_MEMORY:
711 return CURLE_OUT_OF_MEMORY;
712 case SEC_E_NO_CREDENTIALS:
713 case SEC_E_SECPKG_NOT_FOUND:
714 case SEC_E_NOT_OWNER:
715 case SEC_E_UNKNOWN_CREDENTIALS:
716 case SEC_E_INTERNAL_ERROR:
717 default:
718 return CURLE_SSL_CONNECT_ERROR;
719 }
720 }
722 return CURLE_OK;
725static CURLcode schannel_acquire_credential_handle(struct Curl_cfilter *cf,
726 struct Curl_easy *data)
728 struct ssl_connect_data *connssl = cf->ctx;
729 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
731 PCCERT_CONTEXT client_cert = NULL;
732 HCERTSTORE client_cert_store = NULL;
733 CURLcode result;
735 /* setup Schannel API options */
736 DWORD flags = 0;
737 DWORD enabled_protocols = 0;
739 struct schannel_ssl_backend_data *backend =
740 (struct schannel_ssl_backend_data *)connssl->backend;
742 DEBUGASSERT(backend);
744 if(conn_config->verifypeer) {
745 if(backend->use_manual_cred_validation)
746 flags = SCH_CRED_MANUAL_CRED_VALIDATION;
747 else
748 flags = SCH_CRED_AUTO_CRED_VALIDATION;
750 if(conn_config->no_revoke) {
751 flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
752 SCH_CRED_IGNORE_REVOCATION_OFFLINE;
754 DEBUGF(infof(data, "schannel: disabled server certificate revocation "
755 "checks"));
756 }
757 else if(conn_config->revoke_best_effort) {
758 flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
759 SCH_CRED_IGNORE_REVOCATION_OFFLINE |
760 SCH_CRED_REVOCATION_CHECK_CHAIN;
762 DEBUGF(infof(data, "schannel: ignore revocation offline errors"));
763 }
764 else {
765 flags |= SCH_CRED_REVOCATION_CHECK_CHAIN;
767 DEBUGF(infof(data, "schannel: checking server certificate revocation"));
768 }
769 }
770 else {
771 flags = SCH_CRED_MANUAL_CRED_VALIDATION |
772 SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
773 SCH_CRED_IGNORE_REVOCATION_OFFLINE;
774 DEBUGF(infof(data, "schannel: disabled server cert revocation checks"));
775 }
777 if(!conn_config->verifyhost) {
778 flags |= SCH_CRED_NO_SERVERNAME_CHECK;
779 DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from "
780 "comparing the supplied target name with the subject "
781 "names in server certificates."));
782 }
784 if(!conn_config->auto_client_cert) {
785 flags &= ~(DWORD)SCH_CRED_USE_DEFAULT_CREDS;
786 flags |= SCH_CRED_NO_DEFAULT_CREDS;
787 infof(data, "schannel: disabled automatic use of client certificate");
788 }
789 else
790 infof(data, "schannel: enabled automatic use of client certificate");
792 DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT);
793 switch(conn_config->version) {
794 case CURL_SSLVERSION_TLSv1:
795 case CURL_SSLVERSION_TLSv1_0:
796 case CURL_SSLVERSION_TLSv1_1:
797 case CURL_SSLVERSION_TLSv1_2:
798 case CURL_SSLVERSION_TLSv1_3: {
799 result = schannel_set_ssl_version_min_max(&enabled_protocols, cf, data);
800 if(result)
801 return result;
802 break;
803 }
804 case CURL_SSLVERSION_SSLv3:
805 case CURL_SSLVERSION_SSLv2:
806 failf(data, "SSL versions not supported");
807 return CURLE_NOT_BUILT_IN;
808 default:
809 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
810 return CURLE_SSL_CONNECT_ERROR;
811 }
813 result = get_client_cert(cf, data, &client_cert_store, &client_cert);
814 if(result)
815 return result;
817 /* allocate memory for the reusable credential handle */
818 backend->cred = (struct Curl_schannel_cred *)
819 curlx_calloc(1, sizeof(struct Curl_schannel_cred));
820 if(!backend->cred) {
821 failf(data, "schannel: unable to allocate memory");
823 if(client_cert)
824 CertFreeCertificateContext(client_cert);
825 if(client_cert_store)
826 CertCloseStore(client_cert_store, 0);
828 return CURLE_OUT_OF_MEMORY;
829 }
830 backend->cred->refcount = 1;
832 /* Since we did not persist the key, we need to extend the store's
833 * lifetime until the end of the connection
834 */
835 backend->cred->client_cert_store = client_cert_store;
837 result = acquire_sspi_handle(cf, data, backend, client_cert,
838 flags, enabled_protocols);
840 if(client_cert)
841 CertFreeCertificateContext(client_cert);
843 return result;
846static CURLcode schannel_connect_step1(struct Curl_cfilter *cf,
847 struct Curl_easy *data)
849 size_t written = 0;
850 struct ssl_connect_data *connssl = cf->ctx;
851 struct schannel_ssl_backend_data *backend =
852 (struct schannel_ssl_backend_data *)connssl->backend;
853 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
854 SecBuffer outbuf;
855 SecBufferDesc outbuf_desc;
856 SecBuffer inbuf;
857 SecBufferDesc inbuf_desc;
858 unsigned char alpn_buffer[128];
859 SECURITY_STATUS sspi_status = SEC_E_OK;
860 CURLcode result;
862 DEBUGASSERT(backend);
863 DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 1/3)",
864 connssl->peer.origin->hostname, connssl->peer.origin->port));
866 backend->use_alpn = connssl->alpn && s_win_has_alpn;
868 if(conn_config->CAfile || conn_config->ca_info_blob) {
869 if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT,
870 VERSION_GREATER_THAN_EQUAL)) {
871 backend->use_manual_cred_validation = TRUE;
872 }
873 else {
874 failf(data, "schannel: this version of Windows is too old to support "
875 "certificate verification via CA bundle file.");
876 return CURLE_SSL_CACERT_BADFILE;
877 }
878 }
879 else
880 backend->use_manual_cred_validation = FALSE;
882 backend->cred = NULL;
884 /* check for an existing reusable credential handle */
885 if(Curl_ssl_scache_use(cf, data)) {
886 struct Curl_schannel_cred *old_cred;
887 Curl_ssl_scache_lock(data);
888 old_cred = Curl_ssl_scache_get_obj(cf, data, connssl->peer.scache_key);
889 if(old_cred) {
890 backend->cred = old_cred;
891 DEBUGF(infof(data, "schannel: reusing existing credential handle"));
893 /* increment the reference counter of the credential/session handle */
894 backend->cred->refcount++;
895 DEBUGF(infof(data,
896 "schannel: incremented credential handle refcount = %d",
897 backend->cred->refcount));
898 }
899 Curl_ssl_scache_unlock(data);
900 }
902 if(!backend->cred) {
903 char *snihost;
904 result = schannel_acquire_credential_handle(cf, data);
905 if(result || !backend->cred)
906 return result;
907 /* schannel_acquire_credential_handle() sets backend->cred accordingly or
908 it returns error otherwise. */
910 /* A hostname associated with the credential is needed by
911 InitializeSecurityContext for SNI and other reasons. */
912 snihost = connssl->peer.sni ?
913 connssl->peer.sni : connssl->peer.origin->hostname;
914 backend->cred->sni_hostname = curlx_convert_UTF8_to_tchar(snihost);
915 if(!backend->cred->sni_hostname)
916 return CURLE_OUT_OF_MEMORY;
917 }
919 /* Warn if SNI is disabled due to use of an IP address */
920 if(connssl->peer.type != CURL_SSL_PEER_DNS) {
921 infof(data, "schannel: using IP address, SNI is not supported by OS.");
922 }
924 if(backend->use_alpn) {
925 int cur = 0;
926 int list_start_index = 0;
927 unsigned int *extension_len = NULL;
928 unsigned short *list_len = NULL;
929 const unsigned int uiALPN = SecApplicationProtocolNegotiationExt_ALPN;
930 struct alpn_proto_buf proto;
932 /* The first four bytes is an unsigned int indicating number
933 of bytes of data in the rest of the buffer. */
934 extension_len = (unsigned int *)(void *)&alpn_buffer[cur];
935 cur += (int)sizeof(unsigned int);
937 /* The next four bytes are an indicator that this buffer contains
938 ALPN data, as opposed to NPN, for example. */
939 memcpy(&alpn_buffer[cur], &uiALPN, sizeof(uiALPN));
940 cur += (int)sizeof(unsigned int);
942 /* The next two bytes is an unsigned short indicating the number
943 of bytes used to list the preferred protocols. */
944 list_len = (unsigned short *)(void *)&alpn_buffer[cur];
945 cur += (int)sizeof(unsigned short);
947 list_start_index = cur;
949 result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
950 if(result) {
951 failf(data, "Error setting ALPN");
952 return CURLE_SSL_CONNECT_ERROR;
953 }
954 memcpy(&alpn_buffer[cur], proto.data, proto.len);
955 cur += proto.len;
957 *list_len = curlx_uitous(cur - list_start_index);
958 *extension_len = (unsigned int)(*list_len +
959 sizeof(unsigned int) + sizeof(unsigned short));
961 InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur);
962 InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
964 Curl_alpn_to_proto_str(&proto, connssl->alpn);
965 infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
966 }
967 else {
968 InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
969 InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
970 }
972 /* setup output buffer */
973 InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
974 InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
976 /* security request flags */
977 backend->req_flags =
978 ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
979 ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
980 ISC_REQ_STREAM |
981 (!conn_config->auto_client_cert ? ISC_REQ_USE_SUPPLIED_CREDS : 0);
983 /* allocate memory for the security context handle */
984 backend->ctxt = (struct Curl_schannel_ctxt *)
985 curlx_calloc(1, sizeof(struct Curl_schannel_ctxt));
986 if(!backend->ctxt) {
987 failf(data, "schannel: unable to allocate memory");
988 return CURLE_OUT_OF_MEMORY;
989 }
991 /* Schannel InitializeSecurityContext:
992 https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-initializesecuritycontextw
994 At the moment we do not pass inbuf unless we are using ALPN since we only
995 use it for that, and WINE (for which we currently disable ALPN) is giving
996 us problems with inbuf regardless. https://github.com/curl/curl/issues/983
997 */
998 sspi_status = Curl_pSecFn->InitializeSecurityContext(
999 &backend->cred->cred_handle, NULL, backend->cred->sni_hostname,
1000 backend->req_flags, 0, 0,
1001 (backend->use_alpn ? &inbuf_desc : NULL),
1002 0, &backend->ctxt->ctxt_handle,
1003 &outbuf_desc, &backend->ret_flags, NULL);
1005 if(sspi_status != SEC_I_CONTINUE_NEEDED) {
1006 char buffer[STRERROR_LEN];
1007 curlx_safefree(backend->ctxt);
1008 switch(sspi_status) {
1009 case SEC_E_INSUFFICIENT_MEMORY:
1010 failf(data, "schannel: initial InitializeSecurityContext failed: %s",
1011 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1012 return CURLE_OUT_OF_MEMORY;
1013 case SEC_E_WRONG_PRINCIPAL:
1014 failf(data, "schannel: SNI or certificate check failed: %s",
1015 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1016 return CURLE_PEER_FAILED_VERIFICATION;
1017#if 0
1018 case SEC_E_INVALID_HANDLE:
1019 case SEC_E_INVALID_TOKEN:
1020 case SEC_E_LOGON_DENIED:
1021 case SEC_E_TARGET_UNKNOWN:
1022 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
1023 case SEC_E_INTERNAL_ERROR:
1024 case SEC_E_NO_CREDENTIALS:
1025 case SEC_E_UNSUPPORTED_FUNCTION:
1026 case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
1027#endif
1028 default:
1029 failf(data, "schannel: initial InitializeSecurityContext failed: %s",
1030 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1031 return CURLE_SSL_CONNECT_ERROR;
1035 DEBUGF(infof(data, "schannel: sending initial handshake data: "
1036 "sending %lu bytes.", outbuf.cbBuffer));
1038 /* send initial handshake data which is now stored in output buffer */
1039 result = Curl_conn_cf_send(cf->next, data,
1040 (const uint8_t *)outbuf.pvBuffer,
1041 outbuf.cbBuffer, FALSE,
1042 &written);
1043 Curl_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
1044 if(result || (outbuf.cbBuffer != written)) {
1045 failf(data, "schannel: failed to send initial handshake data: "
1046 "sent %zu of %lu bytes", written, outbuf.cbBuffer);
1047 return CURLE_SSL_CONNECT_ERROR;
1050 DEBUGF(infof(data, "schannel: sent initial handshake data: "
1051 "sent %zu bytes", written));
1053 backend->recv_unrecoverable_err = CURLE_OK;
1054 backend->recv_sspi_close_notify = FALSE;
1055 backend->recv_connection_closed = FALSE;
1056 backend->recv_renegotiating = FALSE;
1057 backend->renegotiate_state.started = FALSE;
1058 backend->encdata_is_incomplete = FALSE;
1059 backend->shutdown_generated = FALSE;
1060 backend->shutdown_offset = 0;
1061 memset(&backend->shutdown_token, 0, sizeof(backend->shutdown_token));
1063 /* continue to second handshake step */
1064 connssl->connecting_state = ssl_connect_2;
1066 return CURLE_OK;
1069static CURLcode schannel_error(struct Curl_easy *data,
1070 SECURITY_STATUS sspi_status)
1072 char buffer[STRERROR_LEN];
1073 switch(sspi_status) {
1074 case SEC_E_INSUFFICIENT_MEMORY:
1075 failf(data, "schannel: next InitializeSecurityContext failed: %s",
1076 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1077 return CURLE_OUT_OF_MEMORY;
1078 case SEC_E_WRONG_PRINCIPAL:
1079 failf(data, "schannel: SNI or certificate check failed: %s",
1080 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1081 return CURLE_PEER_FAILED_VERIFICATION;
1082 case SEC_E_UNTRUSTED_ROOT:
1083 failf(data, "schannel: %s",
1084 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1085 return CURLE_PEER_FAILED_VERIFICATION;
1086#if 0
1087 case SEC_E_INVALID_HANDLE:
1088 case SEC_E_INVALID_TOKEN:
1089 case SEC_E_LOGON_DENIED:
1090 case SEC_E_TARGET_UNKNOWN:
1091 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
1092 case SEC_E_INTERNAL_ERROR:
1093 case SEC_E_NO_CREDENTIALS:
1094 case SEC_E_UNSUPPORTED_FUNCTION:
1095 case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
1096#endif
1097 default:
1098 failf(data, "schannel: next InitializeSecurityContext failed: %s",
1099 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1100 return CURLE_SSL_CONNECT_ERROR;
1104static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf,
1105 struct Curl_easy *data,
1106 const char *pinnedpubkey)
1108 struct ssl_connect_data *connssl = cf->ctx;
1109 struct schannel_ssl_backend_data *backend =
1110 (struct schannel_ssl_backend_data *)connssl->backend;
1111 CERT_CONTEXT *pCertContextServer = NULL;
1113 /* Result is returned to caller */
1114 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1116 DEBUGASSERT(backend);
1118 /* if a path was not specified, do not pin */
1119 if(!pinnedpubkey)
1120 return CURLE_OK;
1122 do {
1123 SECURITY_STATUS sspi_status;
1124 uint8_t *x509_der;
1125 DWORD x509_der_len;
1126 struct Curl_X509certificate x509_parsed;
1127 struct Curl_asn1Element *pubkey;
1129 sspi_status =
1130 Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
1131 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
1132 &pCertContextServer);
1134 if((sspi_status != SEC_E_OK) || !pCertContextServer) {
1135 char buffer[STRERROR_LEN];
1136 failf(data, "schannel: Failed to read remote certificate context: %s",
1137 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
1138 break; /* failed */
1141 if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
1142 (pCertContextServer->cbCertEncoded > 0)))
1143 break;
1145 x509_der = (uint8_t *)pCertContextServer->pbCertEncoded;
1146 x509_der_len = pCertContextServer->cbCertEncoded;
1147 memset(&x509_parsed, 0, sizeof(x509_parsed));
1148 if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
1149 break;
1151 pubkey = &x509_parsed.subjectPublicKeyInfo;
1152 if(!pubkey->header || pubkey->end <= pubkey->header) {
1153 failf(data, "SSL: failed retrieving public key from server certificate");
1154 break;
1157 result = Curl_pin_peer_pubkey(data,
1158 pinnedpubkey,
1159 (const unsigned char *)pubkey->header,
1160 (size_t)(pubkey->end - pubkey->header));
1161 if(result) {
1162 failf(data, "SSL: public key does not match pinned public key");
1164 } while(0);
1166 if(pCertContextServer)
1167 CertFreeCertificateContext(pCertContextServer);
1169 return result;
1172static CURLcode ensure_encoding_size(struct Curl_easy *data,
1173 struct sbuffer *encdata,
1174 size_t min_length)
1176 size_t size;
1177 DEBUGASSERT(encdata->length >= encdata->offset);
1178 if(encdata->length < encdata->offset)
1179 return CURLE_FAILED_INIT;
1180 size = encdata->length - encdata->offset;
1181 if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE || encdata->length < min_length) {
1182 unsigned char *buffer;
1183 size_t length = encdata->offset + CURL_SCHANNEL_BUFFER_FREE_SIZE;
1184 if(length < min_length)
1185 length = min_length;
1186 buffer = curlx_realloc(encdata->buffer, length);
1187 if(!buffer) {
1188 failf(data, "schannel: unable to re-allocate memory");
1189 return CURLE_OUT_OF_MEMORY;
1192 encdata->buffer = buffer;
1193 encdata->length = length;
1194 SCH_DEV(infof(data, "schannel: encdata.buffer resized %zu",
1195 encdata->length));
1197 return CURLE_OK;
1200static CURLcode ensure_decoding_size(struct Curl_easy *data,
1201 struct sbuffer *decdata,
1202 size_t nowsize,
1203 size_t len)
1205 size_t size = nowsize > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
1206 nowsize : CURL_SCHANNEL_BUFFER_FREE_SIZE;
1207 DEBUGASSERT(decdata->length >= decdata->offset);
1208 if(decdata->length < decdata->offset)
1209 return CURLE_FAILED_INIT;
1210 else if(decdata->length - decdata->offset < size ||
1211 decdata->length < len) {
1212 /* increase internal decrypted data buffer */
1213 size_t length = decdata->offset + size;
1214 unsigned char *buffer;
1215 /* make sure that the requested amount of data fits */
1216 if(length < len)
1217 length = len;
1219 buffer = curlx_realloc(decdata->buffer, length);
1220 if(!buffer) {
1221 failf(data, "schannel: unable to re-allocate memory");
1222 return CURLE_OUT_OF_MEMORY;
1224 decdata->buffer = buffer;
1225 decdata->length = length;
1227 return CURLE_OK;
1230static CURLcode schannel_connect_step2(struct Curl_cfilter *cf,
1231 struct Curl_easy *data)
1233 struct ssl_connect_data *connssl = cf->ctx;
1234 struct schannel_ssl_backend_data *backend =
1235 (struct schannel_ssl_backend_data *)connssl->backend;
1236 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
1237 int i;
1238 size_t nread = 0;
1239 SecBuffer outbuf[3];
1240 SecBufferDesc outbuf_desc;
1241 SecBuffer inbuf[2];
1242 SecBufferDesc inbuf_desc;
1243 SECURITY_STATUS sspi_status = SEC_E_OK;
1244 CURLcode result;
1245 bool doread;
1246 const char *pubkey_ptr;
1248 DEBUGASSERT(backend);
1250 doread = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? FALSE : TRUE;
1251 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1253 DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 2/3)",
1254 connssl->peer.origin->hostname, connssl->peer.origin->port));
1256 if(!backend->cred || !backend->ctxt)
1257 return CURLE_SSL_CONNECT_ERROR;
1259 /* buffer to store previously received and decrypted data */
1260 if(!backend->decdata.buffer) {
1261 backend->decdata.offset = 0;
1262 backend->decdata.length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
1263 backend->decdata.buffer = curlx_malloc(backend->decdata.length);
1264 if(!backend->decdata.buffer) {
1265 failf(data, "schannel: unable to allocate memory");
1266 return CURLE_OUT_OF_MEMORY;
1270 /* buffer to store previously received and encrypted data */
1271 if(!backend->encdata.buffer) {
1272 backend->encdata_is_incomplete = FALSE;
1273 backend->encdata.offset = 0;
1274 backend->encdata.length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
1275 backend->encdata.buffer = curlx_malloc(backend->encdata.length);
1276 if(!backend->encdata.buffer) {
1277 failf(data, "schannel: unable to allocate memory");
1278 return CURLE_OUT_OF_MEMORY;
1282 result = ensure_encoding_size(data, &backend->encdata, 0);
1283 if(result)
1284 return result;
1286 for(;;) {
1287 if(doread) {
1288 /* read encrypted handshake data from socket */
1289 result = Curl_conn_cf_recv(cf->next, data,
1290 (char *)(backend->encdata.buffer +
1291 backend->encdata.offset),
1292 backend->encdata.length -
1293 backend->encdata.offset,
1294 &nread);
1295 if(result == CURLE_AGAIN) {
1296 if(!backend->encdata.offset || backend->encdata_is_incomplete) {
1297 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1298 DEBUGF(infof(data, "schannel: failed to receive handshake, "
1299 "need more data"));
1300 return CURLE_OK;
1302 else {
1303 DEBUGF(infof(data, "schannel: no new handshake data received, "
1304 "continuing to process existing handshake data"));
1307 else if(result || (nread == 0)) {
1308 failf(data, "schannel: failed to receive handshake, "
1309 "SSL/TLS connection failed");
1310 return CURLE_SSL_CONNECT_ERROR;
1312 else {
1313 /* increase encrypted data buffer offset */
1314 backend->encdata.offset += nread;
1315 backend->encdata_is_incomplete = FALSE;
1316 SCH_DEV(infof(data, "schannel: encrypted data got %zu", nread));
1320 SCH_DEV(infof(data,
1321 "schannel: encrypted data buffer: offset %zu length %zu",
1322 backend->encdata.offset, backend->encdata.length));
1324 /* setup input buffers */
1325 InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN,
1326 curlx_memdup0((const char *)backend->encdata.buffer,
1327 backend->encdata.offset),
1328 curlx_uztoul(backend->encdata.offset));
1329 InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
1330 InitSecBufferDesc(&inbuf_desc, inbuf, 2);
1332 /* setup output buffers */
1333 InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
1334 InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
1335 InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0);
1336 InitSecBufferDesc(&outbuf_desc, outbuf, 3);
1338 if(!inbuf[0].pvBuffer) {
1339 failf(data, "schannel: unable to allocate memory");
1340 return CURLE_OUT_OF_MEMORY;
1343 /* The socket must be writable (or a poll error occurred) before we call
1344 InitializeSecurityContext to continue processing the received TLS
1345 records. This is because that function is not idempotent and we do not
1346 support partial save/resume sending replies of handshake tokens. */
1347 if(!SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), 0)) {
1348 SCH_DEV(infof(data, "schannel: handshake waiting for writable socket"));
1349 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1350 curlx_free(inbuf[0].pvBuffer);
1351 return CURLE_OK;
1354 sspi_status = Curl_pSecFn->InitializeSecurityContext(
1355 &backend->cred->cred_handle, &backend->ctxt->ctxt_handle,
1356 backend->cred->sni_hostname, backend->req_flags,
1357 0, 0, &inbuf_desc, 0, NULL,
1358 &outbuf_desc, &backend->ret_flags, NULL);
1360 /* free buffer for received handshake data */
1361 curlx_safefree(inbuf[0].pvBuffer);
1363 /* check if the handshake was incomplete */
1364 switch(sspi_status) {
1365 case SEC_E_INCOMPLETE_MESSAGE:
1366 backend->encdata_is_incomplete = TRUE;
1367 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1368 DEBUGF(infof(data,
1369 "schannel: received incomplete message, need more data"));
1370 return CURLE_OK;
1372 case SEC_I_CONTINUE_NEEDED:
1373 case SEC_E_OK:
1374 /* check if the handshake needs to be continued */
1375 result = CURLE_OK;
1376 for(i = 0; i < 3; i++) {
1377 /* search for handshake tokens that need to be sent */
1378 if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
1379 size_t written = 0;
1380 DEBUGF(infof(data, "schannel: sending next handshake data: "
1381 "sending %lu bytes.", outbuf[i].cbBuffer));
1383 /* send handshake token to server */
1384 result = Curl_conn_cf_send(cf->next, data,
1385 (const uint8_t *)outbuf[i].pvBuffer,
1386 outbuf[i].cbBuffer,
1387 FALSE, &written);
1388 if(result || (outbuf[i].cbBuffer != written)) {
1389 failf(data, "schannel: failed to send next handshake data: "
1390 "sent %zu of %lu bytes", written, outbuf[i].cbBuffer);
1391 result = CURLE_SSL_CONNECT_ERROR;
1395 for(i = 0; i < 3; i++) {
1396 /* free obsolete buffer */
1397 if(outbuf[i].pvBuffer)
1398 Curl_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer);
1400 if(result)
1401 return result;
1402 break;
1404 case SEC_I_INCOMPLETE_CREDENTIALS:
1405 if(!(backend->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
1406 /* If the server has requested a client certificate, attempt to
1407 continue the handshake without one. This allows connections to
1408 servers which request a client certificate but do not require
1409 it. */
1410 backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
1411 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1412 DEBUGF(infof(data,
1413 "schannel: a client certificate has been requested"));
1414 return CURLE_OK;
1416 FALLTHROUGH();
1418 default:
1419 return schannel_error(data, sspi_status);
1422 /* check if there was additional remaining encrypted data */
1423 if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
1424 SCH_DEV(infof(data, "schannel: encrypted data length: %lu",
1425 inbuf[1].cbBuffer));
1426 /* There are two cases where we could be getting extra data here:
1427 1. If we are renegotiating a connection and the handshake is already
1428 complete (from the server perspective), it can encrypt app data
1429 (not handshake data) in an extra buffer at this point.
1430 2. (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a
1431 connection and this extra data is part of the handshake.
1432 We should process the data immediately; waiting for the socket to
1433 be ready may fail since the server is done sending handshake data.
1434 */
1435 /* check if the remaining data is less than the total amount
1436 and therefore begins after the already processed data */
1437 if(backend->encdata.offset > inbuf[1].cbBuffer) {
1438 memmove(backend->encdata.buffer,
1439 (backend->encdata.buffer + backend->encdata.offset) -
1440 inbuf[1].cbBuffer, inbuf[1].cbBuffer);
1441 backend->encdata.offset = inbuf[1].cbBuffer;
1442 if(sspi_status == SEC_I_CONTINUE_NEEDED) {
1443 doread = FALSE;
1444 continue;
1448 else {
1449 backend->encdata.offset = 0;
1451 break;
1454 /* check if the handshake needs to be continued */
1455 if(sspi_status == SEC_I_CONTINUE_NEEDED) {
1456 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1457 return CURLE_OK;
1460 /* check if the handshake is complete */
1461 if(sspi_status == SEC_E_OK) {
1462 connssl->connecting_state = ssl_connect_3;
1463 DEBUGF(infof(data, "schannel: SSL/TLS handshake complete"));
1466#ifndef CURL_DISABLE_PROXY
1467 pubkey_ptr = Curl_ssl_cf_is_proxy(cf) ?
1468 CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) :
1469 CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY);
1470#else
1471 pubkey_ptr = CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY);
1472#endif
1473 if(pubkey_ptr) {
1474 result = schannel_pkp_pin_peer_pubkey(cf, data, pubkey_ptr);
1475 if(result) {
1476 failf(data, "SSL: public key does not match pinned public key");
1477 return result;
1481 if(conn_config->verifypeer && backend->use_manual_cred_validation) {
1482 /* Certificate verification also verifies the hostname if verifyhost */
1483 return Curl_verify_certificate(cf, data);
1486 /* Verify the hostname manually when certificate verification is disabled,
1487 because in that case Schannel does not verify it. */
1488 if(!conn_config->verifypeer && conn_config->verifyhost)
1489 return Curl_verify_host(cf, data);
1491 return CURLE_OK;
1494static bool valid_cert_encoding(const CERT_CONTEXT *cert_context)
1496 return cert_context &&
1497 ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
1498 cert_context->pbCertEncoded &&
1499 (cert_context->cbCertEncoded > 0);
1502typedef bool (*Read_crt_func)(const CERT_CONTEXT *ccert_context,
1503 bool reverse_order, void *arg);
1505static void traverse_cert_store(const CERT_CONTEXT *context,
1506 Read_crt_func func, void *arg)
1508 const CERT_CONTEXT *current_context = NULL;
1509 bool should_continue = TRUE;
1510 bool first = TRUE;
1511 bool reverse_order = FALSE;
1512 while(should_continue &&
1513 (current_context = CertEnumCertificatesInStore(
1514 context->hCertStore,
1515 current_context)) != NULL) {
1516 /* Windows 11 22H2 OS Build 22621.674 or higher enumerates certificates in
1517 leaf-to-root order while all previous versions of Windows enumerate
1518 certificates in root-to-leaf order. Determine the order of enumeration
1519 by comparing SECPKG_ATTR_REMOTE_CERT_CONTEXT's pbCertContext with the
1520 first certificate's pbCertContext. */
1521 if(first && context->pbCertEncoded != current_context->pbCertEncoded)
1522 reverse_order = TRUE;
1523 should_continue = func(current_context, reverse_order, arg);
1524 first = FALSE;
1527 if(current_context)
1528 CertFreeCertificateContext(current_context);
1531static bool cert_counter_callback(const CERT_CONTEXT *ccert_context,
1532 bool reverse_order, void *certs_count)
1534 (void)reverse_order;
1535 if(valid_cert_encoding(ccert_context))
1536 (*(int *)certs_count)++;
1537 if(*(int *)certs_count > MAX_ALLOWED_CERT_AMOUNT)
1538 return FALSE;
1539 return TRUE;
1542struct Adder_args {
1543 struct Curl_easy *data;
1544 CURLcode result;
1545 int idx;
1546 int certs_count;
1549static bool add_cert_to_certinfo(const CERT_CONTEXT *ccert_context,
1550 bool reverse_order, void *raw_arg)
1552 struct Adder_args *args = (struct Adder_args *)raw_arg;
1553 args->result = CURLE_OK;
1554 if(valid_cert_encoding(ccert_context)) {
1555 int insert_index = reverse_order ? (args->certs_count - 1) - args->idx :
1556 args->idx;
1557 args->result = Curl_extract_certinfo(args->data, insert_index,
1558 ccert_context->pbCertEncoded,
1559 ccert_context->pbCertEncoded +
1560 ccert_context->cbCertEncoded);
1561 args->idx++;
1563 return args->result == CURLE_OK;
1566static void schannel_session_free(void *sessionid)
1568 /* this is expected to be called under sessionid lock */
1569 struct Curl_schannel_cred *cred = sessionid;
1571 if(cred) {
1572 cred->refcount--;
1573 if(cred->refcount == 0) {
1574 Curl_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
1575 curlx_free(cred->sni_hostname);
1576 if(cred->client_cert_store) {
1577 CertCloseStore(cred->client_cert_store, 0);
1578 cred->client_cert_store = NULL;
1580 curlx_safefree(cred);
1585static CURLcode schannel_connect_step3(struct Curl_cfilter *cf,
1586 struct Curl_easy *data)
1588 struct ssl_connect_data *connssl = cf->ctx;
1589 struct schannel_ssl_backend_data *backend =
1590 (struct schannel_ssl_backend_data *)connssl->backend;
1591 struct ssl_easy_config *ssl_config = Curl_ssl_cf_get_easy_config(cf, data);
1592 CURLcode result = CURLE_OK;
1593 SECURITY_STATUS sspi_status = SEC_E_OK;
1594 CERT_CONTEXT *ccert_context = NULL;
1595 SecPkgContext_ApplicationProtocol alpn_result;
1597 DEBUGASSERT(connssl->connecting_state == ssl_connect_3);
1598 DEBUGASSERT(backend);
1600 DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 3/3)",
1601 connssl->peer.origin->hostname, connssl->peer.origin->port));
1603 if(!backend->cred)
1604 return CURLE_SSL_CONNECT_ERROR;
1606 /* check if the required context attributes are met */
1607 if(backend->ret_flags != backend->req_flags) {
1608 if(!(backend->ret_flags & ISC_RET_SEQUENCE_DETECT))
1609 failf(data, "schannel: failed to setup sequence detection");
1610 if(!(backend->ret_flags & ISC_RET_REPLAY_DETECT))
1611 failf(data, "schannel: failed to setup replay detection");
1612 if(!(backend->ret_flags & ISC_RET_CONFIDENTIALITY))
1613 failf(data, "schannel: failed to setup confidentiality");
1614 if(!(backend->ret_flags & ISC_RET_ALLOCATED_MEMORY))
1615 failf(data, "schannel: failed to setup memory allocation");
1616 if(!(backend->ret_flags & ISC_RET_STREAM))
1617 failf(data, "schannel: failed to setup stream orientation");
1618 return CURLE_SSL_CONNECT_ERROR;
1621 if(backend->use_alpn) {
1622 sspi_status =
1623 Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
1624 SECPKG_ATTR_APPLICATION_PROTOCOL,
1625 &alpn_result);
1627 if(sspi_status != SEC_E_OK) {
1628 failf(data, "schannel: failed to retrieve ALPN result");
1629 return CURLE_SSL_CONNECT_ERROR;
1632 if(alpn_result.ProtoNegoStatus ==
1633 SecApplicationProtocolNegotiationStatus_Success) {
1634 if(backend->recv_renegotiating &&
1635 connssl->negotiated.alpn &&
1636 strncmp(connssl->negotiated.alpn,
1637 (const char *)alpn_result.ProtocolId,
1638 alpn_result.ProtocolIdSize)) {
1639 /* Renegotiation selected a different protocol now, we cannot
1640 * deal with this */
1641 failf(data, "schannel: server selected an ALPN protocol too late");
1642 return CURLE_SSL_CONNECT_ERROR;
1644 Curl_alpn_set_negotiated(cf, data, connssl, alpn_result.ProtocolId,
1645 alpn_result.ProtocolIdSize);
1647 else {
1648 if(!backend->recv_renegotiating)
1649 Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0);
1653 /* save the current session data for possible reuse */
1654 if(Curl_ssl_scache_use(cf, data)) {
1655 Curl_ssl_scache_lock(data);
1656 /* Up ref count since call takes ownership */
1657 backend->cred->refcount++;
1658 result = Curl_ssl_scache_add_obj(cf, data, connssl->peer.scache_key,
1659 backend->cred, schannel_session_free);
1660 Curl_ssl_scache_unlock(data);
1661 if(result)
1662 return result;
1665 if(ssl_config->certinfo) {
1666 int certs_count = 0;
1667 sspi_status =
1668 Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
1669 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
1670 &ccert_context);
1672 if((sspi_status != SEC_E_OK) || !ccert_context) {
1673 failf(data, "schannel: failed to retrieve remote cert context");
1674 return CURLE_PEER_FAILED_VERIFICATION;
1677 traverse_cert_store(ccert_context, cert_counter_callback, &certs_count);
1678 if(certs_count > MAX_ALLOWED_CERT_AMOUNT) {
1679 failf(data, "%d certificates is more than allowed (%d)",
1680 certs_count, MAX_ALLOWED_CERT_AMOUNT);
1681 CertFreeCertificateContext(ccert_context);
1682 return CURLE_SSL_CONNECT_ERROR;
1685 result = Curl_ssl_init_certinfo(data, certs_count);
1686 if(!result) {
1687 struct Adder_args args;
1688 args.data = data;
1689 args.idx = 0;
1690 args.certs_count = certs_count;
1691 args.result = CURLE_OK;
1692 traverse_cert_store(ccert_context, add_cert_to_certinfo, &args);
1693 result = args.result;
1695 CertFreeCertificateContext(ccert_context);
1696 if(result)
1697 return result;
1700 connssl->connecting_state = ssl_connect_done;
1702 return CURLE_OK;
1705static CURLcode schannel_connect(struct Curl_cfilter *cf,
1706 struct Curl_easy *data,
1707 bool *done)
1709 struct ssl_connect_data *connssl = cf->ctx;
1710 CURLcode result;
1712 /* check if the connection has already been established */
1713 if(ssl_connection_complete == connssl->state) {
1714 *done = TRUE;
1715 return CURLE_OK;
1718 *done = FALSE;
1720 if(connssl->connecting_state == ssl_connect_1) {
1721 result = schannel_connect_step1(cf, data);
1722 if(result)
1723 return result;
1726 if(connssl->connecting_state == ssl_connect_2) {
1727 result = schannel_connect_step2(cf, data);
1728 if(result)
1729 return result;
1732 if(connssl->connecting_state == ssl_connect_3) {
1733 result = schannel_connect_step3(cf, data);
1734 if(result)
1735 return result;
1738 if(connssl->connecting_state == ssl_connect_done) {
1739 struct schannel_ssl_backend_data *backend =
1740 (struct schannel_ssl_backend_data *)connssl->backend;
1741 DEBUGASSERT(backend);
1743 if(Curl_pSecFn->QueryContextAttributes(
1744 &backend->ctxt->ctxt_handle,
1745 SECPKG_ATTR_STREAM_SIZES,
1746 &backend->stream_sizes)) {
1747 failf(data, "schannel: failed getting stream sizes");
1748 return CURLE_SSL_CONNECT_ERROR;
1751 connssl->state = ssl_connection_complete;
1753 /* When SSPI is used in combination with Schannel
1754 * we need the Schannel context to create the Schannel
1755 * binding to pass the IIS extended protection checks.
1756 * Available on Windows 7 or later.
1757 */
1758 cf->conn->sslContext = &backend->ctxt->ctxt_handle;
1760 *done = TRUE;
1763 return CURLE_OK;
1766enum schannel_renegotiate_caller_t {
1767 SCH_RENEG_CALLER_IS_RECV,
1768 SCH_RENEG_CALLER_IS_SEND
1771/* The maximum time we allow for Schannel renegotiation which may in some
1772 rare cases block either due to libcurl (waiting on the socket) or Windows
1773 (waiting on an interactive security prompt). Note Schannel "renegotiation"
1774 is not necessarily literal TLS renegotiation, but means DecryptMessage
1775 returned SEC_I_RENEGOTIATE which means at least the security context needs
1776 to be re-established. */
1777#define MAX_RENEG_BLOCK_TIME (60 * 1000) /* 60 seconds in milliseconds */
1779/* This function renegotiates the connection due to a server request received
1780 by schannel_recv. This function returns CURLE_AGAIN if the renegotiation is
1781 incomplete. In that case, we remain in the renegotiation (connecting) stage
1782 and future calls to schannel_recv and schannel_send must call this function
1783 first to complete the renegotiation. */
1784static CURLcode schannel_recv_renegotiate(
1785 struct Curl_cfilter *cf, struct Curl_easy *data,
1786 enum schannel_renegotiate_caller_t caller)
1788 CURLcode result;
1789 curl_socket_t sockfd;
1790 struct ssl_connect_data *connssl = cf->ctx;
1791 struct schannel_ssl_backend_data *backend =
1792 (struct schannel_ssl_backend_data *)connssl->backend;
1793 struct schannel_renegotiate_state *rs = &backend->renegotiate_state;
1795 if(!backend || !backend->recv_renegotiating) {
1796 failf(data, "schannel: unexpected call to schannel_recv_renegotiate");
1797 return CURLE_SSL_CONNECT_ERROR;
1799 DEBUGASSERT(caller <= SCH_RENEG_CALLER_IS_SEND);
1800 if(caller == SCH_RENEG_CALLER_IS_RECV)
1801 SCH_DEV(infof(data, "schannel: renegotiation caller is schannel_recv"));
1802 else
1803 SCH_DEV(infof(data, "schannel: renegotiation caller is schannel_send"));
1805 sockfd = Curl_conn_cf_get_socket(cf, data);
1807 if(sockfd == CURL_SOCKET_BAD) {
1808 failf(data, "schannel: renegotiation missing socket");
1809 return CURLE_SSL_CONNECT_ERROR;
1812 if(!rs->started) { /* new renegotiation */
1813 infof(data, "schannel: renegotiating SSL/TLS connection");
1814 DEBUGASSERT(connssl->state == ssl_connection_complete);
1815 DEBUGASSERT(connssl->connecting_state == ssl_connect_done);
1816 connssl->state = ssl_connection_negotiating;
1817 connssl->connecting_state = ssl_connect_2;
1818 memset(rs, 0, sizeof(*rs));
1819 rs->io_need = CURL_SSL_IO_NEED_SEND;
1820 rs->start_time = *Curl_pgrs_now(data);
1821 rs->started = TRUE;
1824 for(;;) {
1825 bool block_read, block_write, blocking, done;
1826 curl_socket_t readfd, writefd;
1827 timediff_t elapsed;
1829 elapsed = curlx_ptimediff_ms(Curl_pgrs_now(data), &rs->start_time);
1830 if(elapsed >= MAX_RENEG_BLOCK_TIME) {
1831 failf(data, "schannel: renegotiation timeout");
1832 result = CURLE_SSL_CONNECT_ERROR;
1833 break;
1836 /* the current io_need state may have been overwritten since the last time
1837 this function was called. restore the io_need state needed to continue
1838 the renegotiation. */
1840 connssl->io_need = rs->io_need;
1842 result = schannel_connect(cf, data, &done);
1844 rs->io_need = connssl->io_need;
1846 if(!result && !done)
1847 result = CURLE_AGAIN;
1849 if(result != CURLE_AGAIN)
1850 break;
1852 readfd = (rs->io_need & CURL_SSL_IO_NEED_RECV) ? sockfd : CURL_SOCKET_BAD;
1853 writefd = (rs->io_need & CURL_SSL_IO_NEED_SEND) ? sockfd : CURL_SOCKET_BAD;
1855 if(readfd == CURL_SOCKET_BAD && writefd == CURL_SOCKET_BAD)
1856 continue;
1858 /* connect should not have requested io read and write together */
1859 DEBUGASSERT(readfd == CURL_SOCKET_BAD || writefd == CURL_SOCKET_BAD);
1861 /* This function is partially blocking to avoid a stoppage that would
1862 * occur if the user is waiting on the socket only in one direction.
1864 * For example, if the user has called recv then they may not be waiting
1865 * for a writable socket and vice versa, so we block to avoid that.
1867 * In practice a wait is unlikely to occur. For caller recv if handshake
1868 * data needs to be sent then we block for a writable socket that should
1869 * be writable immediately except for OS resource constraints. For caller
1870 * send if handshake data needs to be received then we block for a readable
1871 * socket, which could take some time, but it is more likely the user has
1872 * called recv since they had called it prior (only recv can start
1873 * renegotiation and probably the user is going to call it again to get
1874 * more of their data before calling send).
1875 */
1877 block_read = (caller == SCH_RENEG_CALLER_IS_SEND) ? TRUE : FALSE;
1878 block_write = (caller == SCH_RENEG_CALLER_IS_RECV) ? TRUE : FALSE;
1880 blocking = (block_read && (readfd != CURL_SOCKET_BAD)) ||
1881 (block_write && (writefd != CURL_SOCKET_BAD));
1883 SCH_DEV_SHOWBOOL(block_read);
1884 SCH_DEV_SHOWBOOL(block_write);
1885 SCH_DEV_SHOWBOOL(blocking);
1887 for(;;) {
1888 int what;
1889 timediff_t timeout_ms, remaining;
1891 result = Curl_pgrsUpdate(data);
1892 if(result)
1893 break;
1895 elapsed = curlx_ptimediff_ms(Curl_pgrs_now(data), &rs->start_time);
1896 if(elapsed >= MAX_RENEG_BLOCK_TIME) {
1897 failf(data, "schannel: renegotiation timeout");
1898 result = CURLE_SSL_CONNECT_ERROR;
1899 break;
1901 remaining = MAX_RENEG_BLOCK_TIME - elapsed;
1903 if(blocking) {
1904 timeout_ms = Curl_timeleft_ms(data);
1906 if(timeout_ms < 0) {
1907 result = CURLE_OPERATION_TIMEDOUT;
1908 break;
1911 /* the blocking is in intervals so that the progress function can be
1912 called every second */
1913 if(!timeout_ms || timeout_ms > 1000)
1914 timeout_ms = 1000;
1916 if(timeout_ms > remaining)
1917 timeout_ms = remaining;
1919 else
1920 timeout_ms = 0;
1922 SCH_DEV(infof(data, "schannel: renegotiation wait until socket is"
1923 "%s%s for up to %" FMT_TIMEDIFF_T " ms",
1924 ((readfd != CURL_SOCKET_BAD) ? " readable" : ""),
1925 ((writefd != CURL_SOCKET_BAD) ? " writable" : ""),
1926 timeout_ms));
1928 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, timeout_ms);
1930 if(what > 0 && (what & (CURL_CSELECT_IN | CURL_CSELECT_OUT))) {
1931 SCH_DEV(infof(data, "schannel: renegotiation socket %s%s",
1932 ((what & CURL_CSELECT_IN) ? "CURL_CSELECT_IN " : ""),
1933 ((what & CURL_CSELECT_OUT) ? "CURL_CSELECT_OUT " : "")));
1934 result = CURLE_AGAIN;
1935 break;
1937 else if(!what) {
1938 SCH_DEV(infof(data, "schannel: renegotiation socket timeout"));
1939 if(blocking)
1940 continue;
1941 else
1942 return CURLE_AGAIN;
1945 failf(data, "schannel: socket error during renegotiation");
1946 result = CURLE_SSL_CONNECT_ERROR;
1947 break;
1949 if(result != CURLE_AGAIN)
1950 break;
1953 DEBUGASSERT(result != CURLE_AGAIN);
1955 rs->started = FALSE;
1956 backend->recv_renegotiating = FALSE;
1957 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1959 if(result)
1960 failf(data, "schannel: renegotiation failed");
1961 else
1962 infof(data, "schannel: SSL/TLS connection renegotiated");
1964 return result;
1967static CURLcode schannel_send(struct Curl_cfilter *cf, struct Curl_easy *data,
1968 const void *buf, size_t len, size_t *pnwritten)
1970 size_t data_len = 0;
1971 unsigned char *ptr = NULL;
1972 struct ssl_connect_data *connssl = cf->ctx;
1973 SecBuffer outbuf[4];
1974 SecBufferDesc outbuf_desc;
1975 SECURITY_STATUS sspi_status = SEC_E_OK;
1976 CURLcode result = CURLE_OK;
1977 struct schannel_ssl_backend_data *backend =
1978 (struct schannel_ssl_backend_data *)connssl->backend;
1980 DEBUGASSERT(backend);
1981 *pnwritten = 0;
1983 if(backend->recv_renegotiating) {
1984 result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_SEND);
1985 if(result)
1986 return result;
1989 /* check if the buffer is longer than the maximum message length */
1990 if(len > backend->stream_sizes.cbMaximumMessage) {
1991 len = backend->stream_sizes.cbMaximumMessage;
1994 /* calculate the complete message length and prepare the send buffer */
1995 data_len = backend->stream_sizes.cbHeader + len +
1996 backend->stream_sizes.cbTrailer;
1997 if(data_len > backend->send_buffer_len) {
1998 ptr = curlx_realloc(backend->send_buffer, data_len);
1999 if(!ptr)
2000 return CURLE_OUT_OF_MEMORY;
2001 backend->send_buffer = ptr;
2002 backend->send_buffer_len = data_len;
2004 else
2005 ptr = backend->send_buffer;
2007 /* setup output buffers (header, data, trailer, empty) */
2008 InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
2009 ptr, backend->stream_sizes.cbHeader);
2010 InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
2011 ptr + backend->stream_sizes.cbHeader, curlx_uztoul(len));
2012 InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
2013 ptr + backend->stream_sizes.cbHeader + len,
2014 backend->stream_sizes.cbTrailer);
2015 InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
2016 InitSecBufferDesc(&outbuf_desc, outbuf, 4);
2018 /* copy data into output buffer */
2019 memcpy(outbuf[1].pvBuffer, buf, len);
2021 /* https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-encryptmessage */
2022 sspi_status = Curl_pSecFn->EncryptMessage(&backend->ctxt->ctxt_handle, 0,
2023 &outbuf_desc, 0);
2025 /* check if the message was encrypted */
2026 if(sspi_status == SEC_E_OK) {
2028 /* send the encrypted message including header, data and trailer */
2029 len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
2031 /* it is important to send the full message which includes the header,
2032 encrypted payload, and trailer. Until the client receives all the
2033 data a coherent message has not been delivered and the client
2034 cannot read any of it.
2036 If we wanted to buffer the unwritten encrypted bytes, we would
2037 tell the client that all data it has requested to be sent has been
2038 sent. The unwritten encrypted bytes would be the first bytes to
2039 send on the next invocation.
2040 Here's the catch with this - if we tell the client that all the
2041 bytes have been sent, does the client call this method again to
2042 send the buffered data? Looking at who calls this function, it
2043 seems the answer is NO. */
2045 /* send entire message or fail */
2046 while(len > *pnwritten) {
2047 size_t this_write = 0;
2048 int what;
2049 timediff_t timeout_ms = Curl_timeleft_ms(data);
2050 if(timeout_ms < 0) {
2051 /* we already got the timeout */
2052 failf(data, "schannel: timed out sending data (bytes sent: %zu)",
2053 *pnwritten);
2054 result = CURLE_OPERATION_TIMEDOUT;
2055 break;
2057 else if(!timeout_ms)
2058 timeout_ms = TIMEDIFF_T_MAX;
2059 what = SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), timeout_ms);
2060 if(what < 0) {
2061 /* fatal error */
2062 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
2063 result = CURLE_SEND_ERROR;
2064 break;
2066 else if(what == 0) {
2067 failf(data, "schannel: timed out sending data (bytes sent: %zu)",
2068 *pnwritten);
2069 result = CURLE_OPERATION_TIMEDOUT;
2070 break;
2072 /* socket is writable */
2074 result = Curl_conn_cf_send(cf->next, data,
2075 (const uint8_t *)ptr + *pnwritten,
2076 len - *pnwritten,
2077 FALSE, &this_write);
2078 if(result == CURLE_AGAIN)
2079 continue;
2080 else if(result) {
2081 break;
2084 *pnwritten += this_write;
2087 else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) {
2088 result = CURLE_OUT_OF_MEMORY;
2090 else {
2091 result = CURLE_SEND_ERROR;
2094 if(len == *pnwritten)
2095 /* Encrypted message including header, data and trailer entirely sent.
2096 The return value is the number of unencrypted bytes that were sent. */
2097 *pnwritten = outbuf[1].cbBuffer;
2099 return result;
2102static CURLcode schannel_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
2103 char *buf, size_t len, size_t *pnread)
2105 size_t size = 0;
2106 size_t nread = 0;
2107 struct ssl_connect_data *connssl = cf->ctx;
2108 SecBuffer inbuf[4];
2109 SecBufferDesc inbuf_desc;
2110 SECURITY_STATUS sspi_status = SEC_E_OK;
2111 struct schannel_ssl_backend_data *backend =
2112 (struct schannel_ssl_backend_data *)connssl->backend;
2113 CURLcode result = CURLE_OK;
2115 DEBUGASSERT(backend);
2116 *pnread = 0;
2118 if(backend->recv_renegotiating) {
2119 result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_RECV);
2120 if(result)
2121 return result;
2124 /****************************************************************************
2125 * Do not return or set backend->recv_unrecoverable_err unless in the
2126 * cleanup. The pattern for return error is set *err, optional infof, goto
2127 * cleanup.
2129 * Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF()
2130 * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These
2131 * messages are extra verbose and intended for curl developers debugging
2132 * Schannel recv decryption.
2134 * Our priority is to always return as much decrypted data to the caller as
2135 * possible, even if an error occurs. The state of the decrypted buffer must
2136 * always be valid. Transfer of decrypted data to the caller's buffer is
2137 * handled in the cleanup.
2138 */
2140 SCH_DEV(infof(data, "schannel: client wants to read %zu bytes", len));
2142 if(len && len <= backend->decdata.offset) {
2143 SCH_DEV(infof(data,
2144 "schannel: enough decrypted data is already available"));
2145 goto cleanup;
2147 else if(backend->recv_unrecoverable_err) {
2148 result = backend->recv_unrecoverable_err;
2149 infof(data, "schannel: an unrecoverable error occurred in a prior call");
2150 goto cleanup;
2152 else if(backend->recv_sspi_close_notify) {
2153 /* once a server has indicated shutdown there is no more encrypted data */
2154 infof(data, "schannel: server indicated shutdown in a prior call");
2155 goto cleanup;
2157 /* it is debatable what to return when !len. Regardless we cannot return
2158 immediately because there may be data to decrypt (in the case we want to
2159 decrypt all encrypted cached data) so handle !len later in cleanup. */
2160 else if(len && !backend->recv_connection_closed) {
2161 /* the encrypted buffer must be large enough to hold all the bytes
2162 requested and some TLS record overhead. 'len' is a buffer size, so this
2163 integer math cannot overflow. */
2164 const size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE;
2166 /* make sure encrypt buffer fits the requested amount of data */
2167 result = ensure_encoding_size(data, &backend->encdata, min_encdata_length);
2168 if(result)
2169 goto cleanup;
2171 SCH_DEV(infof(data,
2172 "schannel: encrypted data buffer: offset %zu length %zu",
2173 backend->encdata.offset, backend->encdata.length));
2175 /* read encrypted data from socket */
2176 result = Curl_conn_cf_recv(cf->next, data,
2177 (char *)(backend->encdata.buffer +
2178 backend->encdata.offset),
2179 backend->encdata.length -
2180 backend->encdata.offset,
2181 &nread);
2182 if(result) {
2183 if(result == CURLE_AGAIN)
2184 SCH_DEV(infof(data, "schannel: recv returned CURLE_AGAIN"));
2185 else {
2186 infof(data, "schannel: recv returned error %d", (int)result);
2187 backend->recv_unrecoverable_err = result;
2190 else if(nread == 0) {
2191 backend->recv_connection_closed = TRUE;
2192 DEBUGF(infof(data, "schannel: server closed the connection"));
2194 else {
2195 backend->encdata.offset += nread;
2196 backend->encdata_is_incomplete = FALSE;
2197 SCH_DEV(infof(data, "schannel: encrypted data got %zu", nread));
2201 SCH_DEV(infof(data, "schannel: encrypted data buffer: offset %zu length %zu",
2202 backend->encdata.offset, backend->encdata.length));
2204 /* decrypt loop */
2205 while(backend->encdata.offset > 0 && sspi_status == SEC_E_OK &&
2206 (!len || backend->decdata.offset < len ||
2207 backend->recv_connection_closed)) {
2208 /* prepare data buffer for DecryptMessage call */
2209 InitSecBuffer(&inbuf[0], SECBUFFER_DATA, backend->encdata.buffer,
2210 curlx_uztoul(backend->encdata.offset));
2212 /* we need 3 more empty input buffers for possible output */
2213 InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
2214 InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
2215 InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
2216 InitSecBufferDesc(&inbuf_desc, inbuf, 4);
2218 /* https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-decryptmessage
2219 */
2220 sspi_status = Curl_pSecFn->DecryptMessage(&backend->ctxt->ctxt_handle,
2221 &inbuf_desc, 0, NULL);
2223 /* check if everything went fine (server may want to renegotiate
2224 or shutdown the connection context) */
2225 if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE ||
2226 sspi_status == SEC_I_CONTEXT_EXPIRED) {
2227 /* check for successfully decrypted data, even before actual
2228 renegotiation or shutdown of the connection context */
2229 if(inbuf[1].BufferType == SECBUFFER_DATA) {
2230 SCH_DEV(infof(data, "schannel: decrypted data length: %lu",
2231 inbuf[1].cbBuffer));
2233 /* ensure the decode buffer fits the received amount of data */
2234 result = ensure_decoding_size(data, &backend->decdata,
2235 inbuf[1].cbBuffer, len);
2236 if(result)
2237 goto cleanup;
2239 /* copy decrypted data to internal buffer */
2240 size = inbuf[1].cbBuffer;
2241 if(size) {
2242 memcpy(backend->decdata.buffer + backend->decdata.offset,
2243 inbuf[1].pvBuffer, size);
2244 backend->decdata.offset += size;
2247 SCH_DEV(infof(data, "schannel: decrypted data added: %zu", size));
2248 SCH_DEV(infof(data,
2249 "schannel: decrypted cached: offset %zu length %zu",
2250 backend->decdata.offset, backend->decdata.length));
2253 /* check for remaining encrypted data */
2254 if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
2255 SCH_DEV(infof(data, "schannel: encrypted data length: %lu",
2256 inbuf[3].cbBuffer));
2258 /* check if the remaining data is less than the total amount
2259 * and therefore begins after the already processed data
2260 */
2261 if(backend->encdata.offset > inbuf[3].cbBuffer) {
2262 /* move remaining encrypted data forward to the beginning of
2263 buffer */
2264 memmove(backend->encdata.buffer,
2265 (backend->encdata.buffer + backend->encdata.offset) -
2266 inbuf[3].cbBuffer, inbuf[3].cbBuffer);
2267 backend->encdata.offset = inbuf[3].cbBuffer;
2270 SCH_DEV(infof(data,
2271 "schannel: encrypted cached: offset %zu length %zu",
2272 backend->encdata.offset, backend->encdata.length));
2274 else {
2275 /* reset encrypted buffer offset, because there is no data remaining */
2276 backend->encdata.offset = 0;
2279 /* check if server wants to renegotiate the connection context */
2280 if(sspi_status == SEC_I_RENEGOTIATE) {
2281 infof(data, "schannel: remote party requests renegotiation");
2282 if(result && result != CURLE_AGAIN) {
2283 infof(data, "schannel: cannot renegotiate, an error is pending");
2284 goto cleanup;
2287 backend->recv_renegotiating = TRUE;
2288 result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_RECV);
2289 if(result)
2290 goto cleanup;
2292 /* now retry receiving data */
2293 sspi_status = SEC_E_OK;
2294 continue;
2296 /* check if the server closed the connection */
2297 else if(sspi_status == SEC_I_CONTEXT_EXPIRED) {
2298 /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not
2299 returned so we have to work around that in cleanup. */
2300 backend->recv_sspi_close_notify = TRUE;
2301 if(!backend->recv_connection_closed)
2302 backend->recv_connection_closed = TRUE;
2303 /* We received the close notify fine, any error we got
2304 * from the lower filters afterwards (e.g. the socket), is not
2305 * an error on the TLS data stream. That one ended here. */
2306 if(result == CURLE_RECV_ERROR)
2307 result = CURLE_OK;
2308 infof(data,
2309 "schannel: server close notification received (close_notify)");
2310 goto cleanup;
2313 else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
2314 backend->encdata_is_incomplete = TRUE;
2315 if(!result)
2316 result = CURLE_AGAIN;
2317 SCH_DEV(infof(data, "schannel: failed to decrypt data, need more data"));
2318 goto cleanup;
2320 else {
2321 char buffer[STRERROR_LEN];
2322 failf(data, "schannel: failed to read data from server: %s",
2323 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
2324 result = CURLE_RECV_ERROR;
2325 goto cleanup;
2329 SCH_DEV(infof(data, "schannel: encrypted data buffer: offset %zu length %zu",
2330 backend->encdata.offset, backend->encdata.length));
2332 SCH_DEV(infof(data, "schannel: decrypted data buffer: offset %zu length %zu",
2333 backend->decdata.offset, backend->decdata.length));
2335cleanup:
2336 /* Warning- there is no guarantee the encdata state is valid at this point */
2337 SCH_DEV(infof(data, "schannel: schannel_recv cleanup"));
2339 /* Error if the connection has closed without a close_notify.
2341 The behavior here is a matter of debate. We do not want to be vulnerable
2342 to a truncation attack however there is some browser precedent for
2343 ignoring the close_notify for compatibility reasons. */
2344 if(len && !backend->decdata.offset && backend->recv_connection_closed &&
2345 !backend->recv_sspi_close_notify) {
2346 result = CURLE_RECV_ERROR;
2347 failf(data, "schannel: server closed abruptly (missing close_notify)");
2350 /* Any error other than CURLE_AGAIN is an unrecoverable error. */
2351 if(result && result != CURLE_AGAIN)
2352 backend->recv_unrecoverable_err = result;
2354 size = len < backend->decdata.offset ? len : backend->decdata.offset;
2355 if(size) {
2356 memcpy(buf, backend->decdata.buffer, size);
2357 memmove(backend->decdata.buffer, backend->decdata.buffer + size,
2358 backend->decdata.offset - size);
2359 backend->decdata.offset -= size;
2360 SCH_DEV(infof(data, "schannel: decrypted data returned %zu", size));
2361 SCH_DEV(infof(data,
2362 "schannel: decrypted data buffer: offset %zu length %zu",
2363 backend->decdata.offset, backend->decdata.length));
2364 *pnread = size;
2365 return CURLE_OK;
2368 if(!result && !backend->recv_connection_closed)
2369 result = CURLE_AGAIN;
2371 /* it is debatable what to return when !len. We could return whatever error
2372 we got from decryption but instead we override here so the return is
2373 consistent. */
2374 if(!len)
2375 return CURLE_OK;
2377 return result;
2380static bool schannel_data_pending(struct Curl_cfilter *cf,
2381 const struct Curl_easy *data)
2383 const struct ssl_connect_data *connssl = cf->ctx;
2384 struct schannel_ssl_backend_data *backend =
2385 (struct schannel_ssl_backend_data *)connssl->backend;
2387 (void)data;
2388 DEBUGASSERT(backend);
2390 if(backend->ctxt) /* SSL/TLS is in use */
2391 return backend->decdata.offset > 0 ||
2392 (backend->encdata.offset > 0 && !backend->encdata_is_incomplete) ||
2393 backend->recv_connection_closed ||
2394 backend->recv_sspi_close_notify ||
2395 backend->recv_unrecoverable_err;
2396 else
2397 return FALSE;
2400/* shut down the SSL connection and clean up related memory.
2401 this function can be called multiple times on the same connection including
2402 if the SSL connection failed (eg connection made but failed handshake). */
2403static CURLcode schannel_shutdown(struct Curl_cfilter *cf,
2404 struct Curl_easy *data,
2405 bool send_shutdown, bool *done)
2407 /* See https://learn.microsoft.com/windows/win32/secauthn/shutting-down-an-schannel-connection
2408 * Shutting Down an Schannel Connection
2409 */
2410 struct ssl_connect_data *connssl = cf->ctx;
2411 struct schannel_ssl_backend_data *backend =
2412 (struct schannel_ssl_backend_data *)connssl->backend;
2413 CURLcode result = CURLE_OK;
2415 if(cf->shutdown) {
2416 *done = TRUE;
2417 return CURLE_OK;
2420 DEBUGASSERT(data);
2421 DEBUGASSERT(backend);
2423 /* Not supported in schannel */
2424 (void)send_shutdown;
2426 *done = FALSE;
2427 if(backend->ctxt) {
2428 infof(data, "schannel: shutting down SSL/TLS connection with %s port %d",
2429 connssl->peer.origin->hostname, connssl->peer.origin->port);
2432 if(!backend->ctxt || cf->shutdown) {
2433 *done = TRUE;
2434 goto out;
2437 if(backend->cred && backend->ctxt && !backend->sent_shutdown &&
2438 !backend->shutdown_generated) {
2439 SecBufferDesc BuffDesc;
2440 SecBuffer Buffer;
2441 SECURITY_STATUS sspi_status;
2442 SecBuffer outbuf;
2443 SecBufferDesc outbuf_desc;
2444 DWORD dwshut = SCHANNEL_SHUTDOWN;
2446 InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
2447 InitSecBufferDesc(&BuffDesc, &Buffer, 1);
2449 sspi_status = Curl_pSecFn->ApplyControlToken(&backend->ctxt->ctxt_handle,
2450 &BuffDesc);
2452 if(sspi_status != SEC_E_OK) {
2453 char buffer[STRERROR_LEN];
2454 failf(data, "schannel: ApplyControlToken failure: %s",
2455 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
2456 result = CURLE_SEND_ERROR;
2457 goto out;
2460 /* setup output buffer */
2461 InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
2462 InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
2464 sspi_status = Curl_pSecFn->InitializeSecurityContext(
2465 &backend->cred->cred_handle,
2466 &backend->ctxt->ctxt_handle,
2467 backend->cred->sni_hostname,
2468 backend->req_flags,
2469 0,
2470 0,
2471 NULL,
2472 0,
2473 &backend->ctxt->ctxt_handle,
2474 &outbuf_desc,
2475 &backend->ret_flags, NULL);
2477 if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
2478 backend->shutdown_token = outbuf;
2479 backend->shutdown_generated = TRUE;
2481 else {
2482 char buffer[STRERROR_LEN];
2483 if(outbuf.pvBuffer)
2484 Curl_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
2485 failf(data, "schannel: generating close msg failed: %s",
2486 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
2487 result = CURLE_SEND_ERROR;
2488 goto out;
2492 if(backend->shutdown_generated && !backend->sent_shutdown) {
2493 size_t written = 0;
2494 size_t remaining;
2496 DEBUGASSERT(backend->shutdown_offset <= backend->shutdown_token.cbBuffer);
2497 remaining = backend->shutdown_token.cbBuffer - backend->shutdown_offset;
2499 if(remaining) {
2500 result = Curl_conn_cf_send(cf->next, data,
2501 ((uint8_t *)backend->shutdown_token.pvBuffer +
2502 backend->shutdown_offset),
2503 remaining, FALSE, &written);
2504 if(!result)
2505 backend->shutdown_offset += written;
2506 if(result == CURLE_AGAIN || (!result && written < remaining)) {
2507 connssl->io_need = CURL_SSL_IO_NEED_SEND;
2508 result = CURLE_OK;
2509 goto out;
2512 else /* no shutdown message to send? */
2513 result = CURLE_OK;
2514 if(result) {
2515 if(backend->recv_connection_closed) {
2516 /* The server already closed, so sending close_notify is optional. */
2517 *done = TRUE;
2518 result = CURLE_OK;
2520 else {
2521 failf(data, "schannel: error sending close msg: %d", (int)result);
2522 result = CURLE_SEND_ERROR;
2524 goto out;
2526 if(backend->shutdown_token.pvBuffer)
2527 Curl_pSecFn->FreeContextBuffer(backend->shutdown_token.pvBuffer);
2528 memset(&backend->shutdown_token, 0, sizeof(backend->shutdown_token));
2529 backend->shutdown_offset = 0;
2530 backend->sent_shutdown = TRUE;
2531 *done = TRUE;
2534 /* If the connection seems open and we have not seen the close notify
2535 * from the server yet, try to receive it. */
2536 if(backend->cred && backend->ctxt &&
2537 !backend->recv_sspi_close_notify && !backend->recv_connection_closed) {
2538 char buffer[1024];
2539 size_t nread;
2541 result = schannel_recv(cf, data, buffer, sizeof(buffer), &nread);
2542 if(result == CURLE_AGAIN) {
2543 connssl->io_need = CURL_SSL_IO_NEED_RECV;
2545 else if(result) {
2546 CURL_TRC_CF(data, cf, "SSL shutdown, error %d", (int)result);
2547 result = CURLE_RECV_ERROR;
2549 else if(nread == 0) {
2550 /* We got the close notify alert and are done. */
2551 backend->recv_connection_closed = TRUE;
2552 *done = TRUE;
2554 else {
2555 /* still data coming in? */
2559out:
2560 cf->shutdown = (result || *done);
2561 return result;
2564static void schannel_close(struct Curl_cfilter *cf, struct Curl_easy *data)
2566 struct ssl_connect_data *connssl = cf->ctx;
2567 struct schannel_ssl_backend_data *backend =
2568 (struct schannel_ssl_backend_data *)connssl->backend;
2570 DEBUGASSERT(data);
2571 DEBUGASSERT(backend);
2573 if(backend->shutdown_token.pvBuffer)
2574 Curl_pSecFn->FreeContextBuffer(backend->shutdown_token.pvBuffer);
2575 memset(&backend->shutdown_token, 0, sizeof(backend->shutdown_token));
2576 backend->shutdown_offset = 0;
2578 /* free SSPI Schannel API security context handle */
2579 if(backend->ctxt) {
2580 if(cf->conn->sslContext == &backend->ctxt->ctxt_handle)
2581 cf->conn->sslContext = NULL;
2583 DEBUGF(infof(data, "schannel: clear security context handle"));
2584 Curl_pSecFn->DeleteSecurityContext(&backend->ctxt->ctxt_handle);
2585 curlx_safefree(backend->ctxt);
2588 /* free SSPI Schannel API credential handle */
2589 if(backend->cred) {
2590 Curl_ssl_scache_lock(data);
2591 schannel_session_free(backend->cred);
2592 Curl_ssl_scache_unlock(data);
2593 backend->cred = NULL;
2596 /* free the buffer used to encrypt outgoing data */
2597 curlx_safefree(backend->send_buffer);
2598 backend->send_buffer_len = 0;
2600 /* free internal buffer for received encrypted data */
2601 if(backend->encdata.buffer) {
2602 curlx_safefree(backend->encdata.buffer);
2603 backend->encdata.length = 0;
2604 backend->encdata.offset = 0;
2605 backend->encdata_is_incomplete = FALSE;
2608 /* free internal buffer for received decrypted data */
2609 if(backend->decdata.buffer) {
2610 curlx_safefree(backend->decdata.buffer);
2611 backend->decdata.length = 0;
2612 backend->decdata.offset = 0;
2616static int schannel_init(void)
2618 typedef const char *(APIENTRY *WINE_GET_VERSION_FN)(void);
2619#if defined(__clang__) && __clang_major__ >= 16
2620#pragma clang diagnostic push
2621#pragma clang diagnostic ignored "-Wcast-function-type-strict"
2622#endif
2623 WINE_GET_VERSION_FN p_wine_get_version =
2624 CURLX_FUNCTION_CAST(WINE_GET_VERSION_FN,
2625 GetProcAddress(GetModuleHandle(TEXT("ntdll")), "wine_get_version"));
2626#if defined(__clang__) && __clang_major__ >= 16
2627#pragma clang diagnostic pop
2628#endif
2629 if(p_wine_get_version) { /* WINE detected */
2630 curl_off_t ver = 0;
2631 const char *wine_version = p_wine_get_version(); /* e.g. "6.0.2" */
2632 /* Assume ALPN support with WINE 6.0 or greater */
2633 if(wine_version)
2634 curlx_str_number(&wine_version, &ver, 20);
2635 s_win_has_alpn = (ver >= 6);
2637 else {
2638 /* ALPN is supported on Windows 8.1 / Server 2012 R2 or newer. */
2639 s_win_has_alpn = curlx_verify_windows_version(6, 3, 0, PLATFORM_WINNT,
2640 VERSION_GREATER_THAN_EQUAL);
2643 return Curl_sspi_global_init() == CURLE_OK ? 1 : 0;
2646static void schannel_cleanup(void)
2648 Curl_sspi_global_cleanup();
2651static size_t schannel_version(char *buffer, size_t size)
2653 return curl_msnprintf(buffer, size, "Schannel");
2656static CURLcode schannel_random(struct Curl_easy *data,
2657 unsigned char *entropy, size_t length)
2659 (void)data;
2661 return curlx_win32_random(entropy, length);
2664static CURLcode schannel_checksum(const unsigned char *input,
2665 size_t inputlen,
2666 unsigned char *checksum,
2667 size_t checksumlen,
2668 DWORD provType,
2669 const unsigned int algId)
2671 CURLcode result = CURLE_FAILED_INIT;
2673 HCRYPTPROV hProv = 0;
2674 HCRYPTHASH hHash = 0;
2676 size_t off;
2678 DWORD cbHashSize;
2679 DWORD dwHashSizeLen;
2680 DWORD dwChecksumLen;
2682 /* since this can fail in multiple ways, zero memory first so we never
2683 * return old data
2684 */
2685 memset(checksum, 0, checksumlen);
2687 if(!CryptAcquireContext(&hProv, NULL, NULL, provType,
2688 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2689 goto out;
2691 if(!CryptCreateHash(hProv, algId, 0, 0, &hHash))
2692 goto out;
2694 result = CURLE_BAD_FUNCTION_ARGUMENT;
2696 off = 0;
2697 while(off < inputlen) {
2698 DWORD chunk = (DWORD)CURLMIN(inputlen - off, 0xffffffffUL);
2699 if(!CryptHashData(hHash, input + off, chunk, 0))
2700 goto out;
2701 off += chunk;
2704 /* get hash size */
2705 cbHashSize = 0;
2706 dwHashSizeLen = (DWORD)sizeof(cbHashSize);
2707 if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize,
2708 &dwHashSizeLen, 0))
2709 goto out;
2711 /* check if hash fits into the return buffer */
2712 if(checksumlen < cbHashSize)
2713 goto out;
2715 dwChecksumLen = (DWORD)checksumlen;
2716 if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0) &&
2717 dwChecksumLen == cbHashSize)
2718 result = CURLE_OK;
2720out:
2721 if(hHash)
2722 CryptDestroyHash(hHash);
2724 if(hProv)
2725 CryptReleaseContext(hProv, 0);
2727 return result;
2730static CURLcode schannel_sha256sum(const unsigned char *input,
2731 size_t inputlen,
2732 unsigned char *sha256sum,
2733 size_t sha256len)
2735 return schannel_checksum(input, inputlen, sha256sum, sha256len,
2736 PROV_RSA_AES, CALG_SHA_256);
2739static void *schannel_get_internals(struct ssl_connect_data *connssl,
2740 CURLINFO info)
2742 struct schannel_ssl_backend_data *backend =
2743 (struct schannel_ssl_backend_data *)connssl->backend;
2744 (void)info;
2745 DEBUGASSERT(backend);
2746 return &backend->ctxt->ctxt_handle;
2749HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf,
2750 struct Curl_easy *data)
2752 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
2753 struct Curl_multi *multi = data->multi;
2754 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
2755 struct schannel_cert_share *share;
2756 timediff_t timeout_ms;
2757 unsigned char info_blob_digest[CURL_SHA256_DIGEST_LENGTH];
2759 DEBUGASSERT(multi);
2761 if(!multi) {
2762 return NULL;
2765 share = Curl_hash_pick(&multi->proto_hash,
2766 MPROTO_SCHANNEL_CERT_SHARE_KEY,
2767 CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY));
2768 if(!share || !share->cert_store) {
2769 return NULL;
2772 /* zero ca_cache_timeout completely disables caching */
2773 if(!data->set.ssl_ca_cache_timeout) {
2774 return NULL;
2777 /* check for cache timeout by using the cached_x509_store_expired timediff
2778 calculation pattern from openssl.c.
2779 negative timeout means retain forever. */
2780 timeout_ms = data->set.ssl_ca_cache_timeout * (timediff_t)1000;
2781 if(timeout_ms >= 0) {
2782 timediff_t elapsed_ms =
2783 curlx_ptimediff_ms(Curl_pgrs_now(data), &share->time);
2784 if(elapsed_ms >= timeout_ms) {
2785 return NULL;
2789 if(ca_info_blob) {
2790 if(share->CAinfo_blob_size != ca_info_blob->len) {
2791 return NULL;
2793 if(schannel_sha256sum((const unsigned char *)ca_info_blob->data,
2794 ca_info_blob->len,
2795 info_blob_digest,
2796 CURL_SHA256_DIGEST_LENGTH))
2797 return NULL;
2798 if(memcmp(share->CAinfo_blob_digest, info_blob_digest,
2799 CURL_SHA256_DIGEST_LENGTH)) {
2800 return NULL;
2803 else {
2804 if(!conn_config->CAfile || !share->CAfile ||
2805 strcmp(share->CAfile, conn_config->CAfile)) {
2806 return NULL;
2810 return share->cert_store;
2813static void schannel_cert_share_free(const void *key, size_t key_len, void *p)
2815 struct schannel_cert_share *share = p;
2816 DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY));
2817 DEBUGASSERT(!memcmp(MPROTO_SCHANNEL_CERT_SHARE_KEY, key, key_len));
2818 (void)key;
2819 (void)key_len;
2820 if(share->cert_store) {
2821 CertCloseStore(share->cert_store, 0);
2823 curlx_free(share->CAfile);
2824 curlx_free(share);
2827bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf,
2828 struct Curl_easy *data,
2829 HCERTSTORE cert_store)
2831 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
2832 struct Curl_multi *multi = data->multi;
2833 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
2834 struct schannel_cert_share *share;
2835 unsigned char digest[CURL_SHA256_DIGEST_LENGTH];
2836 char *CAfile = NULL;
2838 DEBUGASSERT(multi);
2840 if(!multi) {
2841 return FALSE;
2844 if(ca_info_blob) {
2845 if(schannel_sha256sum((const unsigned char *)ca_info_blob->data,
2846 ca_info_blob->len, digest, sizeof(digest))) {
2847 return FALSE;
2850 else if(conn_config->CAfile) {
2851 CAfile = curlx_strdup(conn_config->CAfile);
2852 if(!CAfile) {
2853 return FALSE;
2857 share = Curl_hash_pick(&multi->proto_hash,
2858 MPROTO_SCHANNEL_CERT_SHARE_KEY,
2859 CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY));
2860 if(!share) {
2861 share = curlx_calloc(1, sizeof(*share));
2862 if(!share) {
2863 curlx_free(CAfile);
2864 return FALSE;
2866 if(!Curl_hash_add2(&multi->proto_hash,
2867 MPROTO_SCHANNEL_CERT_SHARE_KEY,
2868 CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY),
2869 share, schannel_cert_share_free)) {
2870 curlx_free(share);
2871 curlx_free(CAfile);
2872 return FALSE;
2876 /* free old cache data */
2877 if(share->cert_store) {
2878 CertCloseStore(share->cert_store, 0);
2880 curlx_free(share->CAfile);
2882 if(ca_info_blob) {
2883 memcpy(share->CAinfo_blob_digest, digest, sizeof(digest));
2884 share->CAinfo_blob_size = ca_info_blob->len;
2886 else
2887 share->CAinfo_blob_size = 0;
2889 share->time = curlx_now();
2890 share->cert_store = cert_store;
2891 share->CAfile = CAfile;
2892 return TRUE;
2895const struct Curl_ssl Curl_ssl_schannel = {
2896 { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */
2898 SSLSUPP_CERTINFO |
2899 SSLSUPP_CAINFO_BLOB |
2900 SSLSUPP_PINNEDPUBKEY |
2901 SSLSUPP_CA_CACHE |
2902 SSLSUPP_HTTPS_PROXY |
2903 SSLSUPP_CIPHER_LIST,
2905 sizeof(struct schannel_ssl_backend_data),
2907 schannel_init, /* init */
2908 schannel_cleanup, /* cleanup */
2909 schannel_version, /* version */
2910 schannel_shutdown, /* shutdown */
2911 schannel_data_pending, /* data_pending */
2912 schannel_random, /* random */
2913 NULL, /* cert_status_request */
2914 schannel_connect, /* connect */
2915 Curl_ssl_adjust_pollset, /* adjust_pollset */
2916 schannel_get_internals, /* get_internals */
2917 schannel_close, /* close_one */
2918 NULL, /* close_all */
2919 NULL, /* engines_list */
2920 schannel_sha256sum, /* sha256sum */
2921 schannel_recv, /* recv decrypted data */
2922 schannel_send, /* send data to encrypt */
2923 NULL, /* get_channel_binding */
2926#endif /* USE_SCHANNEL */
Diagnostics4 git calls · 37 ms
CallStatusSizeTime037 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=149
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=149
git.pkt.payload.max=78
git.ls_refs.count=2
git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=293470
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=10
git.pkt.data=8
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=293470
git.pkt.payload.max=65516
git.sideband.band1.bytes=293354
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=87
git.pack.bytes=293354
git.pack.ofs_delta=0
git.pack.ref_delta=1
git.pack.chain.max=1
git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0
git.pack.full=86
Open pack map
fetch20027 KiB · hit31 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=30
git.response.bytes=27233
git.response.cache=HIT
git.response.duration_ms=31
git.fetch.wants=837ceebc2f790cc5faea457ce92f9e3e1505395b
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=27233
git.pkt.payload.max=27212
git.sideband.band1.bytes=27211
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
Ref
refs/heads/master
Commit
31c911efe5652725e930f4d2e60c9060e5f6646d
cf-ray
a5e349952d584652
Request
bde451b1…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format