1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2012 - 2016, Marc Hoersken, <info@marc-hoersken.de>
9 * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com>
10 * Copyright (C) 2012 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
20 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21 * KIND, either express or implied.
23 ***************************************************************************/
26 * Source file for Schannel-specific certificate verification. This code should
27 * only be invoked by code in schannel.c.
30 #include "curl_setup.h"
33 #ifndef USE_WINDOWS_SSPI
34 # error "Can't compile SCHANNEL support without SSPI."
37 #define EXPOSE_SCHANNEL_INTERNAL_STRUCTS
40 #ifdef HAS_MANUAL_VERIFY_API
45 #include "curl_multibyte.h"
46 #include "curl_printf.h"
47 #include "hostcheck.h"
48 #include "version_win32.h"
50 /* The last #include file should be: */
51 #include "curl_memory.h"
54 #define BACKEND connssl->backend
56 #define MAX_CAFILE_SIZE 1048576 /* 1 MiB */
57 #define BEGIN_CERT "-----BEGIN CERTIFICATE-----"
58 #define END_CERT "\n-----END CERTIFICATE-----"
60 struct cert_chain_engine_config_win7 {
62 HCERTSTORE hRestrictedRoot;
63 HCERTSTORE hRestrictedTrust;
64 HCERTSTORE hRestrictedOther;
65 DWORD cAdditionalStore;
66 HCERTSTORE *rghAdditionalStore;
68 DWORD dwUrlRetrievalTimeout;
69 DWORD MaximumCachedCertificates;
70 DWORD CycleDetectionModulus;
71 HCERTSTORE hExclusiveRoot;
72 HCERTSTORE hExclusiveTrustedPeople;
75 static int is_cr_or_lf(char c)
77 return c == '\r' || c == '\n';
80 /* Search the substring needle,needlelen into string haystack,haystacklen
81 * Strings don't need to be terminated by a '\0'.
82 * Similar of OSX/Linux memmem (not available on Visual Studio).
83 * Return position of beginning of first occurrence or NULL if not found
85 static const char *c_memmem(const void *haystack, size_t haystacklen,
86 const void *needle, size_t needlelen)
90 const char *str_limit = (const char *)haystack + haystacklen;
91 if(!needlelen || needlelen > haystacklen)
93 first = *(const char *)needle;
94 for(p = (const char *)haystack; p <= (str_limit - needlelen); p++)
95 if(((*p) == first) && (memcmp(p, needle, needlelen) == 0))
101 static CURLcode add_certs_data_to_store(HCERTSTORE trust_store,
102 const char *ca_buffer,
103 size_t ca_buffer_size,
104 const char *ca_file_text,
105 struct Curl_easy *data)
107 const size_t begin_cert_len = strlen(BEGIN_CERT);
108 const size_t end_cert_len = strlen(END_CERT);
109 CURLcode result = CURLE_OK;
112 const char *current_ca_file_ptr = ca_buffer;
113 const char *ca_buffer_limit = ca_buffer + ca_buffer_size;
115 while(more_certs && (current_ca_file_ptr<ca_buffer_limit)) {
116 const char *begin_cert_ptr = c_memmem(current_ca_file_ptr,
117 ca_buffer_limit-current_ca_file_ptr,
120 if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[begin_cert_len])) {
124 const char *end_cert_ptr = c_memmem(begin_cert_ptr,
125 ca_buffer_limit-begin_cert_ptr,
130 "schannel: CA file '%s' is not correctly formatted",
132 result = CURLE_SSL_CACERT_BADFILE;
137 CERT_CONTEXT *cert_context = NULL;
138 BOOL add_cert_result = FALSE;
139 DWORD actual_content_type = 0;
140 DWORD cert_size = (DWORD)
141 ((end_cert_ptr + end_cert_len) - begin_cert_ptr);
143 cert_blob.pbData = (BYTE *)begin_cert_ptr;
144 cert_blob.cbData = cert_size;
145 if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
147 CERT_QUERY_CONTENT_FLAG_CERT,
148 CERT_QUERY_FORMAT_FLAG_ALL,
151 &actual_content_type,
155 (const void **)&cert_context)) {
156 char buffer[STRERROR_LEN];
158 "schannel: failed to extract certificate from CA file "
161 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
162 result = CURLE_SSL_CACERT_BADFILE;
166 current_ca_file_ptr = begin_cert_ptr + cert_size;
168 /* Sanity check that the cert_context object is the right type */
169 if(CERT_QUERY_CONTENT_CERT != actual_content_type) {
171 "schannel: unexpected content type '%d' when extracting "
172 "certificate from CA file '%s'",
173 actual_content_type, ca_file_text);
174 result = CURLE_SSL_CACERT_BADFILE;
179 CertAddCertificateContextToStore(trust_store,
181 CERT_STORE_ADD_ALWAYS,
183 CertFreeCertificateContext(cert_context);
184 if(!add_cert_result) {
185 char buffer[STRERROR_LEN];
187 "schannel: failed to add certificate from CA file '%s' "
188 "to certificate store: %s",
190 Curl_winapi_strerror(GetLastError(), buffer,
192 result = CURLE_SSL_CACERT_BADFILE;
204 if(result == CURLE_OK) {
207 "schannel: did not add any certificates from CA file '%s'",
212 "schannel: added %d certificate(s) from CA file '%s'",
213 num_certs, ca_file_text);
219 static CURLcode add_certs_file_to_store(HCERTSTORE trust_store,
221 struct Curl_easy *data)
224 HANDLE ca_file_handle = INVALID_HANDLE_VALUE;
225 LARGE_INTEGER file_size;
226 char *ca_file_buffer = NULL;
227 TCHAR *ca_file_tstr = NULL;
228 size_t ca_file_bufsize = 0;
229 DWORD total_bytes_read = 0;
231 ca_file_tstr = curlx_convert_UTF8_to_tchar((char *)ca_file);
233 char buffer[STRERROR_LEN];
235 "schannel: invalid path name for CA file '%s': %s",
237 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
238 result = CURLE_SSL_CACERT_BADFILE;
243 * Read the CA file completely into memory before parsing it. This
244 * optimizes for the common case where the CA file will be relatively
247 ca_file_handle = CreateFile(ca_file_tstr,
252 FILE_ATTRIBUTE_NORMAL,
254 if(ca_file_handle == INVALID_HANDLE_VALUE) {
255 char buffer[STRERROR_LEN];
257 "schannel: failed to open CA file '%s': %s",
259 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
260 result = CURLE_SSL_CACERT_BADFILE;
264 if(!GetFileSizeEx(ca_file_handle, &file_size)) {
265 char buffer[STRERROR_LEN];
267 "schannel: failed to determine size of CA file '%s': %s",
269 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
270 result = CURLE_SSL_CACERT_BADFILE;
274 if(file_size.QuadPart > MAX_CAFILE_SIZE) {
276 "schannel: CA file exceeds max size of %u bytes",
278 result = CURLE_SSL_CACERT_BADFILE;
282 ca_file_bufsize = (size_t)file_size.QuadPart;
283 ca_file_buffer = (char *)malloc(ca_file_bufsize + 1);
284 if(!ca_file_buffer) {
285 result = CURLE_OUT_OF_MEMORY;
289 while(total_bytes_read < ca_file_bufsize) {
290 DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read);
291 DWORD bytes_read = 0;
293 if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read,
294 bytes_to_read, &bytes_read, NULL)) {
295 char buffer[STRERROR_LEN];
297 "schannel: failed to read from CA file '%s': %s",
299 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
300 result = CURLE_SSL_CACERT_BADFILE;
303 if(bytes_read == 0) {
304 /* Premature EOF -- adjust the bufsize to the new value */
305 ca_file_bufsize = total_bytes_read;
308 total_bytes_read += bytes_read;
312 /* Null terminate the buffer */
313 ca_file_buffer[ca_file_bufsize] = '\0';
315 result = add_certs_data_to_store(trust_store,
316 ca_file_buffer, ca_file_bufsize,
321 if(ca_file_handle != INVALID_HANDLE_VALUE) {
322 CloseHandle(ca_file_handle);
324 Curl_safefree(ca_file_buffer);
325 curlx_unicodefree(ca_file_tstr);
331 * Returns the number of characters necessary to populate all the host_names.
332 * If host_names is not NULL, populate it with all the host names. Each string
333 * in the host_names is null-terminated and the last string is double
334 * null-terminated. If no DNS names are found, a single null-terminated empty
335 * string is returned.
337 static DWORD cert_get_name_string(struct Curl_easy *data,
338 CERT_CONTEXT *cert_context,
342 DWORD actual_length = 0;
343 BOOL compute_content = FALSE;
344 CERT_INFO *cert_info = NULL;
345 CERT_EXTENSION *extension = NULL;
346 CRYPT_DECODE_PARA decode_para = {0, 0, 0};
347 CERT_ALT_NAME_INFO *alt_name_info = NULL;
348 DWORD alt_name_info_size = 0;
349 BOOL ret_val = FALSE;
350 LPTSTR current_pos = NULL;
353 /* CERT_NAME_SEARCH_ALL_NAMES_FLAG is available from Windows 8 onwards. */
354 if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT,
355 VERSION_GREATER_THAN_EQUAL)) {
356 #ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG
357 /* CertGetNameString will provide the 8-bit character string without
360 CERT_NAME_DISABLE_IE4_UTF8_FLAG | CERT_NAME_SEARCH_ALL_NAMES_FLAG;
361 actual_length = CertGetNameString(cert_context,
367 return actual_length;
371 compute_content = host_names != NULL && length != 0;
373 /* Initialize default return values. */
375 if(compute_content) {
380 failf(data, "schannel: Null certificate context.");
381 return actual_length;
384 cert_info = cert_context->pCertInfo;
386 failf(data, "schannel: Null certificate info.");
387 return actual_length;
390 extension = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
391 cert_info->cExtension,
392 cert_info->rgExtension);
394 failf(data, "schannel: CertFindExtension() returned no extension.");
395 return actual_length;
398 decode_para.cbSize = sizeof(CRYPT_DECODE_PARA);
401 CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
402 szOID_SUBJECT_ALT_NAME2,
403 extension->Value.pbData,
404 extension->Value.cbData,
405 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
408 &alt_name_info_size);
411 "schannel: CryptDecodeObjectEx() returned no alternate name "
413 return actual_length;
416 current_pos = host_names;
418 /* Iterate over the alternate names and populate host_names. */
419 for(i = 0; i < alt_name_info->cAltEntry; i++) {
420 const CERT_ALT_NAME_ENTRY *entry = &alt_name_info->rgAltEntry[i];
421 wchar_t *dns_w = NULL;
422 size_t current_length = 0;
424 if(entry->dwAltNameChoice != CERT_ALT_NAME_DNS_NAME) {
427 if(!entry->pwszDNSName) {
428 infof(data, "schannel: Empty DNS name.");
431 current_length = wcslen(entry->pwszDNSName) + 1;
432 if(!compute_content) {
433 actual_length += (DWORD)current_length;
436 /* Sanity check to prevent buffer overrun. */
437 if((actual_length + current_length) > length) {
438 failf(data, "schannel: Not enough memory to list all host names.");
441 dns_w = entry->pwszDNSName;
442 /* pwszDNSName is in ia5 string format and hence doesn't contain any
443 * non-ascii characters. */
444 while(*dns_w != '\0') {
445 *current_pos++ = (char)(*dns_w++);
447 *current_pos++ = '\0';
448 actual_length += (DWORD)current_length;
450 if(compute_content) {
451 /* Last string has double null-terminator. */
454 return actual_length;
457 static CURLcode verify_host(struct Curl_easy *data,
458 CERT_CONTEXT *pCertContextServer,
459 const char * const conn_hostname)
461 CURLcode result = CURLE_PEER_FAILED_VERIFICATION;
462 TCHAR *cert_hostname_buff = NULL;
463 size_t cert_hostname_buff_index = 0;
464 size_t hostlen = strlen(conn_hostname);
466 DWORD actual_len = 0;
468 /* Determine the size of the string needed for the cert hostname */
469 len = cert_get_name_string(data, pCertContextServer, NULL, 0);
472 "schannel: CertGetNameString() returned no "
473 "certificate name information");
474 result = CURLE_PEER_FAILED_VERIFICATION;
478 /* CertGetNameString guarantees that the returned name will not contain
479 * embedded null bytes. This appears to be undocumented behavior.
481 cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR));
482 if(!cert_hostname_buff) {
483 result = CURLE_OUT_OF_MEMORY;
486 actual_len = cert_get_name_string(
487 data, pCertContextServer, (LPTSTR)cert_hostname_buff, len);
490 if(actual_len != len) {
492 "schannel: CertGetNameString() returned certificate "
493 "name information of unexpected size");
494 result = CURLE_PEER_FAILED_VERIFICATION;
498 /* If HAVE_CERT_NAME_SEARCH_ALL_NAMES is available, the output
499 * will contain all DNS names, where each name is null-terminated
500 * and the last DNS name is double null-terminated. Due to this
501 * encoding, use the length of the buffer to iterate over all names.
503 result = CURLE_PEER_FAILED_VERIFICATION;
504 while(cert_hostname_buff_index < len &&
505 cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') &&
506 result == CURLE_PEER_FAILED_VERIFICATION) {
510 /* Comparing the cert name and the connection hostname encoded as UTF-8
511 * is acceptable since both values are assumed to use ASCII
512 * (or some equivalent) encoding
514 cert_hostname = curlx_convert_tchar_to_UTF8(
515 &cert_hostname_buff[cert_hostname_buff_index]);
517 result = CURLE_OUT_OF_MEMORY;
520 if(Curl_cert_hostcheck(cert_hostname, strlen(cert_hostname),
521 conn_hostname, hostlen)) {
523 "schannel: connection hostname (%s) validated "
524 "against certificate name (%s)",
525 conn_hostname, cert_hostname);
529 size_t cert_hostname_len;
532 "schannel: connection hostname (%s) did not match "
533 "against certificate name (%s)",
534 conn_hostname, cert_hostname);
537 _tcslen(&cert_hostname_buff[cert_hostname_buff_index]);
539 /* Move on to next cert name */
540 cert_hostname_buff_index += cert_hostname_len + 1;
542 result = CURLE_PEER_FAILED_VERIFICATION;
544 curlx_unicodefree(cert_hostname);
548 if(result == CURLE_PEER_FAILED_VERIFICATION) {
550 "schannel: CertGetNameString() failed to match "
551 "connection hostname (%s) against server certificate names",
554 else if(result != CURLE_OK)
555 failf(data, "schannel: server certificate name verification failed");
558 Curl_safefree(cert_hostname_buff);
563 CURLcode Curl_verify_certificate(struct Curl_easy *data,
564 struct connectdata *conn, int sockindex)
566 SECURITY_STATUS sspi_status;
567 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
568 CURLcode result = CURLE_OK;
569 CERT_CONTEXT *pCertContextServer = NULL;
570 const CERT_CHAIN_CONTEXT *pChainContext = NULL;
571 HCERTCHAINENGINE cert_chain_engine = NULL;
572 HCERTSTORE trust_store = NULL;
573 const char * const conn_hostname = SSL_HOST_NAME();
575 DEBUGASSERT(BACKEND);
578 s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
579 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
580 &pCertContextServer);
582 if((sspi_status != SEC_E_OK) || !pCertContextServer) {
583 char buffer[STRERROR_LEN];
584 failf(data, "schannel: Failed to read remote certificate context: %s",
585 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
586 result = CURLE_PEER_FAILED_VERIFICATION;
589 if(result == CURLE_OK &&
590 (SSL_CONN_CONFIG(CAfile) || SSL_CONN_CONFIG(ca_info_blob)) &&
591 BACKEND->use_manual_cred_validation) {
593 * Create a chain engine that uses the certificates in the CA file as
594 * trusted certificates. This is only supported on Windows 7+.
597 if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT,
598 VERSION_LESS_THAN)) {
599 failf(data, "schannel: this version of Windows is too old to support "
600 "certificate verification via CA bundle file.");
601 result = CURLE_SSL_CACERT_BADFILE;
604 /* Open the certificate store */
605 trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY,
608 CERT_STORE_CREATE_NEW_FLAG,
611 char buffer[STRERROR_LEN];
612 failf(data, "schannel: failed to create certificate store: %s",
613 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
614 result = CURLE_SSL_CACERT_BADFILE;
617 const struct curl_blob *ca_info_blob = SSL_CONN_CONFIG(ca_info_blob);
619 result = add_certs_data_to_store(trust_store,
620 (const char *)ca_info_blob->data,
626 result = add_certs_file_to_store(trust_store,
627 SSL_CONN_CONFIG(CAfile),
633 if(result == CURLE_OK) {
634 struct cert_chain_engine_config_win7 engine_config;
635 BOOL create_engine_result;
637 memset(&engine_config, 0, sizeof(engine_config));
638 engine_config.cbSize = sizeof(engine_config);
639 engine_config.hExclusiveRoot = trust_store;
641 /* CertCreateCertificateChainEngine will check the expected size of the
642 * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size
643 * does not match the expected size. When this occurs, it indicates that
644 * CAINFO is not supported on the version of Windows in use.
646 create_engine_result =
647 CertCreateCertificateChainEngine(
648 (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine);
649 if(!create_engine_result) {
650 char buffer[STRERROR_LEN];
652 "schannel: failed to create certificate chain engine: %s",
653 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
654 result = CURLE_SSL_CACERT_BADFILE;
659 if(result == CURLE_OK) {
660 CERT_CHAIN_PARA ChainPara;
662 memset(&ChainPara, 0, sizeof(ChainPara));
663 ChainPara.cbSize = sizeof(ChainPara);
665 if(!CertGetCertificateChain(cert_chain_engine,
668 pCertContextServer->hCertStore,
670 (SSL_SET_OPTION(no_revoke) ? 0 :
671 CERT_CHAIN_REVOCATION_CHECK_CHAIN),
674 char buffer[STRERROR_LEN];
675 failf(data, "schannel: CertGetCertificateChain failed: %s",
676 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
677 pChainContext = NULL;
678 result = CURLE_PEER_FAILED_VERIFICATION;
681 if(result == CURLE_OK) {
682 CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
683 DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED);
684 dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
686 if(data->set.ssl.revoke_best_effort) {
687 /* Ignore errors when root certificates are missing the revocation
688 * list URL, or when the list could not be downloaded because the
689 * server is currently unreachable. */
690 dwTrustErrorMask &= ~(DWORD)(CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
691 CERT_TRUST_IS_OFFLINE_REVOCATION);
694 if(dwTrustErrorMask) {
695 if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED)
696 failf(data, "schannel: CertGetCertificateChain trust error"
697 " CERT_TRUST_IS_REVOKED");
698 else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
699 failf(data, "schannel: CertGetCertificateChain trust error"
700 " CERT_TRUST_IS_PARTIAL_CHAIN");
701 else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
702 failf(data, "schannel: CertGetCertificateChain trust error"
703 " CERT_TRUST_IS_UNTRUSTED_ROOT");
704 else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
705 failf(data, "schannel: CertGetCertificateChain trust error"
706 " CERT_TRUST_IS_NOT_TIME_VALID");
707 else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
708 failf(data, "schannel: CertGetCertificateChain trust error"
709 " CERT_TRUST_REVOCATION_STATUS_UNKNOWN");
711 failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x",
713 result = CURLE_PEER_FAILED_VERIFICATION;
718 if(result == CURLE_OK) {
719 if(SSL_CONN_CONFIG(verifyhost)) {
720 result = verify_host(data, pCertContextServer, conn_hostname);
724 if(cert_chain_engine) {
725 CertFreeCertificateChainEngine(cert_chain_engine);
729 CertCloseStore(trust_store, 0);
733 CertFreeCertificateChain(pChainContext);
735 if(pCertContextServer)
736 CertFreeCertificateContext(pCertContextServer);
741 #endif /* HAS_MANUAL_VERIFY_API */
742 #endif /* USE_SCHANNEL */