1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
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 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
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.haxx.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 ***************************************************************************/
24
25/*
26 * Source file for Schannel-specific certificate verification. This code should
27 * only be invoked by code in schannel.c.
28 */
29
30#include "curl_setup.h"
31
32#ifdef USE_SCHANNEL
33#ifndef USE_WINDOWS_SSPI
34# error "Can't compile SCHANNEL support without SSPI."
35#endif
36
37#define EXPOSE_SCHANNEL_INTERNAL_STRUCTS
38#include "schannel.h"
39
40#ifdef HAS_MANUAL_VERIFY_API
41
42#include "vtls.h"
43#include "sendf.h"
44#include "strerror.h"
45#include "curl_multibyte.h"
46#include "curl_printf.h"
47#include "hostcheck.h"
48#include "system_win32.h"
49
50/* The last #include file should be: */
51#include "curl_memory.h"
52#include "memdebug.h"
53
54#define BACKEND connssl->backend
55
56#define MAX_CAFILE_SIZE 1048576 /* 1 MiB */
57#define BEGIN_CERT "-----BEGIN CERTIFICATE-----"
58#define END_CERT "\n-----END CERTIFICATE-----"
59
60typedef struct {
61 DWORD cbSize;
62 HCERTSTORE hRestrictedRoot;
63 HCERTSTORE hRestrictedTrust;
64 HCERTSTORE hRestrictedOther;
65 DWORD cAdditionalStore;
66 HCERTSTORE *rghAdditionalStore;
67 DWORD dwFlags;
68 DWORD dwUrlRetrievalTimeout;
69 DWORD MaximumCachedCertificates;
70 DWORD CycleDetectionModulus;
71 HCERTSTORE hExclusiveRoot;
72 HCERTSTORE hExclusiveTrustedPeople;
73} CERT_CHAIN_ENGINE_CONFIG_WIN7, *PCERT_CHAIN_ENGINE_CONFIG_WIN7;
74
75static int is_cr_or_lf(char c)
76{
77 return c == '\r' || c == '\n';
78}
79
80static CURLcode add_certs_to_store(HCERTSTORE trust_store,
81 const char *ca_file,
82 struct connectdata *conn)
83{
84 CURLcode result;
85 struct Curl_easy *data = conn->data;
86 HANDLE ca_file_handle = INVALID_HANDLE_VALUE;
87 LARGE_INTEGER file_size;
88 char *ca_file_buffer = NULL;
89 char *current_ca_file_ptr = NULL;
90 TCHAR *ca_file_tstr = NULL;
91 size_t ca_file_bufsize = 0;
92 DWORD total_bytes_read = 0;
93 bool more_certs = 0;
94 int num_certs = 0;
95 size_t END_CERT_LEN;
96
97 ca_file_tstr = Curl_convert_UTF8_to_tchar((char *)ca_file);
98 if(!ca_file_tstr) {
99 char buffer[STRERROR_LEN];
100 failf(data,
101 "schannel: invalid path name for CA file '%s': %s",
102 ca_file,
103 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
104 result = CURLE_SSL_CACERT_BADFILE;
105 goto cleanup;
106 }
107
108 /*
109 * Read the CA file completely into memory before parsing it. This
110 * optimizes for the common case where the CA file will be relatively
111 * small ( < 1 MiB ).
112 */
113 ca_file_handle = CreateFile(ca_file_tstr,
114 GENERIC_READ,
115 FILE_SHARE_READ,
116 NULL,
117 OPEN_EXISTING,
118 FILE_ATTRIBUTE_NORMAL,
119 NULL);
120 if(ca_file_handle == INVALID_HANDLE_VALUE) {
121 char buffer[STRERROR_LEN];
122 failf(data,
123 "schannel: failed to open CA file '%s': %s",
124 ca_file,
125 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
126 result = CURLE_SSL_CACERT_BADFILE;
127 goto cleanup;
128 }
129
130 if(!GetFileSizeEx(ca_file_handle, &file_size)) {
131 char buffer[STRERROR_LEN];
132 failf(data,
133 "schannel: failed to determine size of CA file '%s': %s",
134 ca_file,
135 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
136 result = CURLE_SSL_CACERT_BADFILE;
137 goto cleanup;
138 }
139
140 if(file_size.QuadPart > MAX_CAFILE_SIZE) {
141 failf(data,
142 "schannel: CA file exceeds max size of %u bytes",
143 MAX_CAFILE_SIZE);
144 result = CURLE_SSL_CACERT_BADFILE;
145 goto cleanup;
146 }
147
148 ca_file_bufsize = (size_t)file_size.QuadPart;
149 ca_file_buffer = (char *)malloc(ca_file_bufsize + 1);
150 if(!ca_file_buffer) {
151 result = CURLE_OUT_OF_MEMORY;
152 goto cleanup;
153 }
154
155 result = CURLE_OK;
156 while(total_bytes_read < ca_file_bufsize) {
157 DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read);
158 DWORD bytes_read = 0;
159
160 if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read,
161 bytes_to_read, &bytes_read, NULL)) {
162 char buffer[STRERROR_LEN];
163 failf(data,
164 "schannel: failed to read from CA file '%s': %s",
165 ca_file,
166 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
167 result = CURLE_SSL_CACERT_BADFILE;
168 goto cleanup;
169 }
170 if(bytes_read == 0) {
171 /* Premature EOF -- adjust the bufsize to the new value */
172 ca_file_bufsize = total_bytes_read;
173 }
174 else {
175 total_bytes_read += bytes_read;
176 }
177 }
178
179 /* Null terminate the buffer */
180 ca_file_buffer[ca_file_bufsize] = '\0';
181
182 if(result != CURLE_OK) {
183 goto cleanup;
184 }
185
186 END_CERT_LEN = strlen(END_CERT);
187
188 more_certs = 1;
189 current_ca_file_ptr = ca_file_buffer;
190 while(more_certs && *current_ca_file_ptr != '\0') {
191 char *begin_cert_ptr = strstr(current_ca_file_ptr, BEGIN_CERT);
192 if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[strlen(BEGIN_CERT)])) {
193 more_certs = 0;
194 }
195 else {
196 char *end_cert_ptr = strstr(begin_cert_ptr, END_CERT);
197 if(!end_cert_ptr) {
198 failf(data,
199 "schannel: CA file '%s' is not correctly formatted",
200 ca_file);
201 result = CURLE_SSL_CACERT_BADFILE;
202 more_certs = 0;
203 }
204 else {
205 CERT_BLOB cert_blob;
206 CERT_CONTEXT *cert_context = NULL;
207 BOOL add_cert_result = FALSE;
208 DWORD actual_content_type = 0;
209 DWORD cert_size = (DWORD)
210 ((end_cert_ptr + END_CERT_LEN) - begin_cert_ptr);
211
212 cert_blob.pbData = (BYTE *)begin_cert_ptr;
213 cert_blob.cbData = cert_size;
214 if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
215 &cert_blob,
216 CERT_QUERY_CONTENT_FLAG_CERT,
217 CERT_QUERY_FORMAT_FLAG_ALL,
218 0,
219 NULL,
220 &actual_content_type,
221 NULL,
222 NULL,
223 NULL,
224 (const void **)&cert_context)) {
225 char buffer[STRERROR_LEN];
226 failf(data,
227 "schannel: failed to extract certificate from CA file "
228 "'%s': %s",
229 ca_file,
230 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
231 result = CURLE_SSL_CACERT_BADFILE;
232 more_certs = 0;
233 }
234 else {
235 current_ca_file_ptr = begin_cert_ptr + cert_size;
236
237 /* Sanity check that the cert_context object is the right type */
238 if(CERT_QUERY_CONTENT_CERT != actual_content_type) {
239 failf(data,
240 "schannel: unexpected content type '%d' when extracting "
241 "certificate from CA file '%s'",
242 actual_content_type, ca_file);
243 result = CURLE_SSL_CACERT_BADFILE;
244 more_certs = 0;
245 }
246 else {
247 add_cert_result =
248 CertAddCertificateContextToStore(trust_store,
249 cert_context,
250 CERT_STORE_ADD_ALWAYS,
251 NULL);
252 CertFreeCertificateContext(cert_context);
253 if(!add_cert_result) {
254 char buffer[STRERROR_LEN];
255 failf(data,
256 "schannel: failed to add certificate from CA file '%s' "
257 "to certificate store: %s",
258 ca_file,
259 Curl_winapi_strerror(GetLastError(), buffer,
260 sizeof(buffer)));
261 result = CURLE_SSL_CACERT_BADFILE;
262 more_certs = 0;
263 }
264 else {
265 num_certs++;
266 }
267 }
268 }
269 }
270 }
271 }
272
273 if(result == CURLE_OK) {
274 if(!num_certs) {
275 infof(data,
276 "schannel: did not add any certificates from CA file '%s'\n",
277 ca_file);
278 }
279 else {
280 infof(data,
281 "schannel: added %d certificate(s) from CA file '%s'\n",
282 num_certs, ca_file);
283 }
284 }
285
286cleanup:
287 if(ca_file_handle != INVALID_HANDLE_VALUE) {
288 CloseHandle(ca_file_handle);
289 }
290 Curl_safefree(ca_file_buffer);
291 Curl_unicodefree(ca_file_tstr);
292
293 return result;
294}
295
296static CURLcode verify_host(struct Curl_easy *data,
297 CERT_CONTEXT *pCertContextServer,
298 const char * const conn_hostname)
299{
300 CURLcode result = CURLE_PEER_FAILED_VERIFICATION;
301 TCHAR *cert_hostname_buff = NULL;
302 size_t cert_hostname_buff_index = 0;
303 DWORD len = 0;
304 DWORD actual_len = 0;
305
306 /* CertGetNameString will provide the 8-bit character string without
307 * any decoding */
308 DWORD name_flags = CERT_NAME_DISABLE_IE4_UTF8_FLAG;
309
310#ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG
311 name_flags |= CERT_NAME_SEARCH_ALL_NAMES_FLAG;
312#endif
313
314 /* Determine the size of the string needed for the cert hostname */
315 len = CertGetNameString(pCertContextServer,
316 CERT_NAME_DNS_TYPE,
317 name_flags,
318 NULL,
319 NULL,
320 0);
321 if(len == 0) {
322 failf(data,
323 "schannel: CertGetNameString() returned no "
324 "certificate name information");
325 result = CURLE_PEER_FAILED_VERIFICATION;
326 goto cleanup;
327 }
328
329 /* CertGetNameString guarantees that the returned name will not contain
330 * embedded null bytes. This appears to be undocumented behavior.
331 */
332 cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR));
333 if(!cert_hostname_buff) {
334 result = CURLE_OUT_OF_MEMORY;
335 goto cleanup;
336 }
337 actual_len = CertGetNameString(pCertContextServer,
338 CERT_NAME_DNS_TYPE,
339 name_flags,
340 NULL,
341 (LPTSTR) cert_hostname_buff,
342 len);
343
344 /* Sanity check */
345 if(actual_len != len) {
346 failf(data,
347 "schannel: CertGetNameString() returned certificate "
348 "name information of unexpected size");
349 result = CURLE_PEER_FAILED_VERIFICATION;
350 goto cleanup;
351 }
352
353 /* If HAVE_CERT_NAME_SEARCH_ALL_NAMES is available, the output
354 * will contain all DNS names, where each name is null-terminated
355 * and the last DNS name is double null-terminated. Due to this
356 * encoding, use the length of the buffer to iterate over all names.
357 */
358 result = CURLE_PEER_FAILED_VERIFICATION;
359 while(cert_hostname_buff_index < len &&
360 cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') &&
361 result == CURLE_PEER_FAILED_VERIFICATION) {
362
363 char *cert_hostname;
364
365 /* Comparing the cert name and the connection hostname encoded as UTF-8
366 * is acceptable since both values are assumed to use ASCII
367 * (or some equivalent) encoding
368 */
369 cert_hostname = Curl_convert_tchar_to_UTF8(
370 &cert_hostname_buff[cert_hostname_buff_index]);
371 if(!cert_hostname) {
372 result = CURLE_OUT_OF_MEMORY;
373 }
374 else {
375 int match_result;
376
377 match_result = Curl_cert_hostcheck(cert_hostname, conn_hostname);
378 if(match_result == CURL_HOST_MATCH) {
379 infof(data,
380 "schannel: connection hostname (%s) validated "
381 "against certificate name (%s)\n",
382 conn_hostname, cert_hostname);
383 result = CURLE_OK;
384 }
385 else {
386 size_t cert_hostname_len;
387
388 infof(data,
389 "schannel: connection hostname (%s) did not match "
390 "against certificate name (%s)\n",
391 conn_hostname, cert_hostname);
392
393 cert_hostname_len = _tcslen(
394 &cert_hostname_buff[cert_hostname_buff_index]);
395
396 /* Move on to next cert name */
397 cert_hostname_buff_index += cert_hostname_len + 1;
398
399 result = CURLE_PEER_FAILED_VERIFICATION;
400 }
401 Curl_unicodefree(cert_hostname);
402 }
403 }
404
405 if(result == CURLE_PEER_FAILED_VERIFICATION) {
406 failf(data,
407 "schannel: CertGetNameString() failed to match "
408 "connection hostname (%s) against server certificate names",
409 conn_hostname);
410 }
411 else if(result != CURLE_OK)
412 failf(data, "schannel: server certificate name verification failed");
413
414cleanup:
415 Curl_unicodefree(cert_hostname_buff);
416
417 return result;
418}
419
420CURLcode Curl_verify_certificate(struct connectdata *conn, int sockindex)
421{
422 SECURITY_STATUS sspi_status;
423 struct Curl_easy *data = conn->data;
424 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
425 CURLcode result = CURLE_OK;
426 CERT_CONTEXT *pCertContextServer = NULL;
427 const CERT_CHAIN_CONTEXT *pChainContext = NULL;
428 HCERTCHAINENGINE cert_chain_engine = NULL;
429 HCERTSTORE trust_store = NULL;
430 const char * const conn_hostname = SSL_IS_PROXY() ?
431 conn->http_proxy.host.name :
432 conn->host.name;
433
434 sspi_status =
435 s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
436 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
437 &pCertContextServer);
438
439 if((sspi_status != SEC_E_OK) || (pCertContextServer == NULL)) {
440 char buffer[STRERROR_LEN];
441 failf(data, "schannel: Failed to read remote certificate context: %s",
442 Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
443 result = CURLE_PEER_FAILED_VERIFICATION;
444 }
445
446 if(result == CURLE_OK && SSL_CONN_CONFIG(CAfile) &&
447 BACKEND->use_manual_cred_validation) {
448 /*
449 * Create a chain engine that uses the certificates in the CA file as
450 * trusted certificates. This is only supported on Windows 7+.
451 */
452
453 if(Curl_verify_windows_version(6, 1, PLATFORM_WINNT, VERSION_LESS_THAN)) {
454 failf(data, "schannel: this version of Windows is too old to support "
455 "certificate verification via CA bundle file.");
456 result = CURLE_SSL_CACERT_BADFILE;
457 }
458 else {
459 /* Open the certificate store */
460 trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY,
461 0,
462 (HCRYPTPROV)NULL,
463 CERT_STORE_CREATE_NEW_FLAG,
464 NULL);
465 if(!trust_store) {
466 char buffer[STRERROR_LEN];
467 failf(data, "schannel: failed to create certificate store: %s",
468 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
469 result = CURLE_SSL_CACERT_BADFILE;
470 }
471 else {
472 result = add_certs_to_store(trust_store, SSL_CONN_CONFIG(CAfile),
473 conn);
474 }
475 }
476
477 if(result == CURLE_OK) {
478 CERT_CHAIN_ENGINE_CONFIG_WIN7 engine_config;
479 BOOL create_engine_result;
480
481 memset(&engine_config, 0, sizeof(engine_config));
482 engine_config.cbSize = sizeof(engine_config);
483 engine_config.hExclusiveRoot = trust_store;
484
485 /* CertCreateCertificateChainEngine will check the expected size of the
486 * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size
487 * does not match the expected size. When this occurs, it indicates that
488 * CAINFO is not supported on the version of Windows in use.
489 */
490 create_engine_result =
491 CertCreateCertificateChainEngine(
492 (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine);
493 if(!create_engine_result) {
494 char buffer[STRERROR_LEN];
495 failf(data,
496 "schannel: failed to create certificate chain engine: %s",
497 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
498 result = CURLE_SSL_CACERT_BADFILE;
499 }
500 }
501 }
502
503 if(result == CURLE_OK) {
504 CERT_CHAIN_PARA ChainPara;
505
506 memset(&ChainPara, 0, sizeof(ChainPara));
507 ChainPara.cbSize = sizeof(ChainPara);
508
509 if(!CertGetCertificateChain(cert_chain_engine,
510 pCertContextServer,
511 NULL,
512 pCertContextServer->hCertStore,
513 &ChainPara,
514 (data->set.ssl.no_revoke ? 0 :
515 CERT_CHAIN_REVOCATION_CHECK_CHAIN),
516 NULL,
517 &pChainContext)) {
518 char buffer[STRERROR_LEN];
519 failf(data, "schannel: CertGetCertificateChain failed: %s",
520 Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
521 pChainContext = NULL;
522 result = CURLE_PEER_FAILED_VERIFICATION;
523 }
524
525 if(result == CURLE_OK) {
526 CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
527 DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED);
528 dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
529 if(dwTrustErrorMask) {
530 if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED)
531 failf(data, "schannel: CertGetCertificateChain trust error"
532 " CERT_TRUST_IS_REVOKED");
533 else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
534 failf(data, "schannel: CertGetCertificateChain trust error"
535 " CERT_TRUST_IS_PARTIAL_CHAIN");
536 else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
537 failf(data, "schannel: CertGetCertificateChain trust error"
538 " CERT_TRUST_IS_UNTRUSTED_ROOT");
539 else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
540 failf(data, "schannel: CertGetCertificateChain trust error"
541 " CERT_TRUST_IS_NOT_TIME_VALID");
542 else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
543 failf(data, "schannel: CertGetCertificateChain trust error"
544 " CERT_TRUST_REVOCATION_STATUS_UNKNOWN");
545 else
546 failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x",
547 dwTrustErrorMask);
548 result = CURLE_PEER_FAILED_VERIFICATION;
549 }
550 }
551 }
552
553 if(result == CURLE_OK) {
554 if(SSL_CONN_CONFIG(verifyhost)) {
555 result = verify_host(conn->data, pCertContextServer, conn_hostname);
556 }
557 }
558
559 if(cert_chain_engine) {
560 CertFreeCertificateChainEngine(cert_chain_engine);
561 }
562
563 if(trust_store) {
564 CertCloseStore(trust_store, 0);
565 }
566
567 if(pChainContext)
568 CertFreeCertificateChain(pChainContext);
569
570 if(pCertContextServer)
571 CertFreeCertificateContext(pCertContextServer);
572
573 return result;
574}
575
576#endif /* HAS_MANUAL_VERIFY_API */
577#endif /* USE_SCHANNEL */
578