schannel_verify.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Marc Hoersken, <info@marc-hoersken.de>
  9. * Copyright (C) Mark Salisbury, <mark.salisbury@hp.com>
  10. * Copyright (C) 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.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 Schannel-specific certificate verification. This code should
  28. * only be invoked by code in schannel.c.
  29. */
  30. #include "curl_setup.h"
  31. #ifdef USE_SCHANNEL
  32. #ifndef USE_WINDOWS_SSPI
  33. # error "cannot compile SCHANNEL support without SSPI."
  34. #endif
  35. #include "schannel.h"
  36. #include "schannel_int.h"
  37. #include "inet_pton.h"
  38. #include "vtls.h"
  39. #include "vtls_int.h"
  40. #include "sendf.h"
  41. #include "strerror.h"
  42. #include "curl_multibyte.h"
  43. #include "curl_printf.h"
  44. #include "hostcheck.h"
  45. #include "version_win32.h"
  46. /* The last #include file should be: */
  47. #include "curl_memory.h"
  48. #include "memdebug.h"
  49. #define BACKEND ((struct schannel_ssl_backend_data *)connssl->backend)
  50. #ifdef HAS_MANUAL_VERIFY_API
  51. #define MAX_CAFILE_SIZE 1048576 /* 1 MiB */
  52. #define BEGIN_CERT "-----BEGIN CERTIFICATE-----"
  53. #define END_CERT "\n-----END CERTIFICATE-----"
  54. struct cert_chain_engine_config_win7 {
  55. DWORD cbSize;
  56. HCERTSTORE hRestrictedRoot;
  57. HCERTSTORE hRestrictedTrust;
  58. HCERTSTORE hRestrictedOther;
  59. DWORD cAdditionalStore;
  60. HCERTSTORE *rghAdditionalStore;
  61. DWORD dwFlags;
  62. DWORD dwUrlRetrievalTimeout;
  63. DWORD MaximumCachedCertificates;
  64. DWORD CycleDetectionModulus;
  65. HCERTSTORE hExclusiveRoot;
  66. HCERTSTORE hExclusiveTrustedPeople;
  67. };
  68. static int is_cr_or_lf(char c)
  69. {
  70. return c == '\r' || c == '\n';
  71. }
  72. /* Search the substring needle,needlelen into string haystack,haystacklen
  73. * Strings do not need to be terminated by a '\0'.
  74. * Similar of macOS/Linux memmem (not available on Visual Studio).
  75. * Return position of beginning of first occurrence or NULL if not found
  76. */
  77. static const char *c_memmem(const void *haystack, size_t haystacklen,
  78. const void *needle, size_t needlelen)
  79. {
  80. const char *p;
  81. char first;
  82. const char *str_limit = (const char *)haystack + haystacklen;
  83. if(!needlelen || needlelen > haystacklen)
  84. return NULL;
  85. first = *(const char *)needle;
  86. for(p = (const char *)haystack; p <= (str_limit - needlelen); p++)
  87. if(((*p) == first) && (memcmp(p, needle, needlelen) == 0))
  88. return p;
  89. return NULL;
  90. }
  91. static CURLcode add_certs_data_to_store(HCERTSTORE trust_store,
  92. const char *ca_buffer,
  93. size_t ca_buffer_size,
  94. const char *ca_file_text,
  95. struct Curl_easy *data)
  96. {
  97. const size_t begin_cert_len = strlen(BEGIN_CERT);
  98. const size_t end_cert_len = strlen(END_CERT);
  99. CURLcode result = CURLE_OK;
  100. int num_certs = 0;
  101. bool more_certs = 1;
  102. const char *current_ca_file_ptr = ca_buffer;
  103. const char *ca_buffer_limit = ca_buffer + ca_buffer_size;
  104. while(more_certs && (current_ca_file_ptr < ca_buffer_limit)) {
  105. const char *begin_cert_ptr = c_memmem(current_ca_file_ptr,
  106. ca_buffer_limit-current_ca_file_ptr,
  107. BEGIN_CERT,
  108. begin_cert_len);
  109. if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[begin_cert_len])) {
  110. more_certs = 0;
  111. }
  112. else {
  113. const char *end_cert_ptr = c_memmem(begin_cert_ptr,
  114. ca_buffer_limit-begin_cert_ptr,
  115. END_CERT,
  116. end_cert_len);
  117. if(!end_cert_ptr) {
  118. failf(data,
  119. "schannel: CA file '%s' is not correctly formatted",
  120. ca_file_text);
  121. result = CURLE_SSL_CACERT_BADFILE;
  122. more_certs = 0;
  123. }
  124. else {
  125. CERT_BLOB cert_blob;
  126. CERT_CONTEXT *cert_context = NULL;
  127. BOOL add_cert_result = FALSE;
  128. DWORD actual_content_type = 0;
  129. DWORD cert_size = (DWORD)
  130. ((end_cert_ptr + end_cert_len) - begin_cert_ptr);
  131. cert_blob.pbData = (BYTE *)begin_cert_ptr;
  132. cert_blob.cbData = cert_size;
  133. if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
  134. &cert_blob,
  135. CERT_QUERY_CONTENT_FLAG_CERT,
  136. CERT_QUERY_FORMAT_FLAG_ALL,
  137. 0,
  138. NULL,
  139. &actual_content_type,
  140. NULL,
  141. NULL,
  142. NULL,
  143. (const void **)&cert_context)) {
  144. char buffer[STRERROR_LEN];
  145. failf(data,
  146. "schannel: failed to extract certificate from CA file "
  147. "'%s': %s",
  148. ca_file_text,
  149. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  150. result = CURLE_SSL_CACERT_BADFILE;
  151. more_certs = 0;
  152. }
  153. else {
  154. current_ca_file_ptr = begin_cert_ptr + cert_size;
  155. /* Sanity check that the cert_context object is the right type */
  156. if(CERT_QUERY_CONTENT_CERT != actual_content_type) {
  157. failf(data,
  158. "schannel: unexpected content type '%lu' when extracting "
  159. "certificate from CA file '%s'",
  160. actual_content_type, ca_file_text);
  161. result = CURLE_SSL_CACERT_BADFILE;
  162. more_certs = 0;
  163. }
  164. else {
  165. add_cert_result =
  166. CertAddCertificateContextToStore(trust_store,
  167. cert_context,
  168. CERT_STORE_ADD_ALWAYS,
  169. NULL);
  170. CertFreeCertificateContext(cert_context);
  171. if(!add_cert_result) {
  172. char buffer[STRERROR_LEN];
  173. failf(data,
  174. "schannel: failed to add certificate from CA file '%s' "
  175. "to certificate store: %s",
  176. ca_file_text,
  177. Curl_winapi_strerror(GetLastError(), buffer,
  178. sizeof(buffer)));
  179. result = CURLE_SSL_CACERT_BADFILE;
  180. more_certs = 0;
  181. }
  182. else {
  183. num_certs++;
  184. }
  185. }
  186. }
  187. }
  188. }
  189. }
  190. if(result == CURLE_OK) {
  191. if(!num_certs) {
  192. infof(data,
  193. "schannel: did not add any certificates from CA file '%s'",
  194. ca_file_text);
  195. }
  196. else {
  197. infof(data,
  198. "schannel: added %d certificate(s) from CA file '%s'",
  199. num_certs, ca_file_text);
  200. }
  201. }
  202. return result;
  203. }
  204. static CURLcode add_certs_file_to_store(HCERTSTORE trust_store,
  205. const char *ca_file,
  206. struct Curl_easy *data)
  207. {
  208. CURLcode result;
  209. HANDLE ca_file_handle = INVALID_HANDLE_VALUE;
  210. LARGE_INTEGER file_size;
  211. char *ca_file_buffer = NULL;
  212. TCHAR *ca_file_tstr = NULL;
  213. size_t ca_file_bufsize = 0;
  214. DWORD total_bytes_read = 0;
  215. ca_file_tstr = curlx_convert_UTF8_to_tchar((char *)ca_file);
  216. if(!ca_file_tstr) {
  217. char buffer[STRERROR_LEN];
  218. failf(data,
  219. "schannel: invalid path name for CA file '%s': %s",
  220. ca_file,
  221. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  222. result = CURLE_SSL_CACERT_BADFILE;
  223. goto cleanup;
  224. }
  225. /*
  226. * Read the CA file completely into memory before parsing it. This
  227. * optimizes for the common case where the CA file will be relatively
  228. * small ( < 1 MiB ).
  229. */
  230. ca_file_handle = CreateFile(ca_file_tstr,
  231. GENERIC_READ,
  232. FILE_SHARE_READ,
  233. NULL,
  234. OPEN_EXISTING,
  235. FILE_ATTRIBUTE_NORMAL,
  236. NULL);
  237. if(ca_file_handle == INVALID_HANDLE_VALUE) {
  238. char buffer[STRERROR_LEN];
  239. failf(data,
  240. "schannel: failed to open CA file '%s': %s",
  241. ca_file,
  242. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  243. result = CURLE_SSL_CACERT_BADFILE;
  244. goto cleanup;
  245. }
  246. if(!GetFileSizeEx(ca_file_handle, &file_size)) {
  247. char buffer[STRERROR_LEN];
  248. failf(data,
  249. "schannel: failed to determine size of CA file '%s': %s",
  250. ca_file,
  251. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  252. result = CURLE_SSL_CACERT_BADFILE;
  253. goto cleanup;
  254. }
  255. if(file_size.QuadPart > MAX_CAFILE_SIZE) {
  256. failf(data,
  257. "schannel: CA file exceeds max size of %u bytes",
  258. MAX_CAFILE_SIZE);
  259. result = CURLE_SSL_CACERT_BADFILE;
  260. goto cleanup;
  261. }
  262. ca_file_bufsize = (size_t)file_size.QuadPart;
  263. ca_file_buffer = (char *)malloc(ca_file_bufsize + 1);
  264. if(!ca_file_buffer) {
  265. result = CURLE_OUT_OF_MEMORY;
  266. goto cleanup;
  267. }
  268. while(total_bytes_read < ca_file_bufsize) {
  269. DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read);
  270. DWORD bytes_read = 0;
  271. if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read,
  272. bytes_to_read, &bytes_read, NULL)) {
  273. char buffer[STRERROR_LEN];
  274. failf(data,
  275. "schannel: failed to read from CA file '%s': %s",
  276. ca_file,
  277. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  278. result = CURLE_SSL_CACERT_BADFILE;
  279. goto cleanup;
  280. }
  281. if(bytes_read == 0) {
  282. /* Premature EOF -- adjust the bufsize to the new value */
  283. ca_file_bufsize = total_bytes_read;
  284. }
  285. else {
  286. total_bytes_read += bytes_read;
  287. }
  288. }
  289. /* Null terminate the buffer */
  290. ca_file_buffer[ca_file_bufsize] = '\0';
  291. result = add_certs_data_to_store(trust_store,
  292. ca_file_buffer, ca_file_bufsize,
  293. ca_file,
  294. data);
  295. cleanup:
  296. if(ca_file_handle != INVALID_HANDLE_VALUE) {
  297. CloseHandle(ca_file_handle);
  298. }
  299. Curl_safefree(ca_file_buffer);
  300. curlx_unicodefree(ca_file_tstr);
  301. return result;
  302. }
  303. #endif /* HAS_MANUAL_VERIFY_API */
  304. /*
  305. * Returns the number of characters necessary to populate all the host_names.
  306. * If host_names is not NULL, populate it with all the hostnames. Each string
  307. * in the host_names is null-terminated and the last string is double
  308. * null-terminated. If no DNS names are found, a single null-terminated empty
  309. * string is returned.
  310. */
  311. static DWORD cert_get_name_string(struct Curl_easy *data,
  312. CERT_CONTEXT *cert_context,
  313. LPTSTR host_names,
  314. DWORD length,
  315. PCERT_ALT_NAME_INFO alt_name_info,
  316. BOOL Win8_compat)
  317. {
  318. DWORD actual_length = 0;
  319. #if defined(CURL_WINDOWS_UWP)
  320. (void)data;
  321. (void)cert_context;
  322. (void)host_names;
  323. (void)length;
  324. (void)alt_name_info;
  325. (void)Win8_compat;
  326. #else
  327. BOOL compute_content = FALSE;
  328. LPTSTR current_pos = NULL;
  329. DWORD i;
  330. #ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG
  331. /* CERT_NAME_SEARCH_ALL_NAMES_FLAG is available from Windows 8 onwards. */
  332. if(Win8_compat) {
  333. /* CertGetNameString will provide the 8-bit character string without
  334. * any decoding */
  335. DWORD name_flags =
  336. CERT_NAME_DISABLE_IE4_UTF8_FLAG | CERT_NAME_SEARCH_ALL_NAMES_FLAG;
  337. actual_length = CertGetNameString(cert_context,
  338. CERT_NAME_DNS_TYPE,
  339. name_flags,
  340. NULL,
  341. host_names,
  342. length);
  343. return actual_length;
  344. }
  345. #else
  346. (void)cert_context;
  347. (void)Win8_compat;
  348. #endif
  349. compute_content = host_names != NULL && length != 0;
  350. /* Initialize default return values. */
  351. actual_length = 1;
  352. if(compute_content) {
  353. *host_names = '\0';
  354. }
  355. current_pos = host_names;
  356. /* Iterate over the alternate names and populate host_names. */
  357. for(i = 0; i < alt_name_info->cAltEntry; i++) {
  358. const CERT_ALT_NAME_ENTRY *entry = &alt_name_info->rgAltEntry[i];
  359. wchar_t *dns_w = NULL;
  360. size_t current_length = 0;
  361. if(entry->dwAltNameChoice != CERT_ALT_NAME_DNS_NAME) {
  362. continue;
  363. }
  364. if(!entry->pwszDNSName) {
  365. infof(data, "schannel: Empty DNS name.");
  366. continue;
  367. }
  368. current_length = wcslen(entry->pwszDNSName) + 1;
  369. if(!compute_content) {
  370. actual_length += (DWORD)current_length;
  371. continue;
  372. }
  373. /* Sanity check to prevent buffer overrun. */
  374. if((actual_length + current_length) > length) {
  375. failf(data, "schannel: Not enough memory to list all hostnames.");
  376. break;
  377. }
  378. dns_w = entry->pwszDNSName;
  379. /* pwszDNSName is in ia5 string format and hence does not contain any
  380. * non-ASCII characters. */
  381. while(*dns_w != '\0') {
  382. *current_pos++ = (TCHAR)(*dns_w++);
  383. }
  384. *current_pos++ = '\0';
  385. actual_length += (DWORD)current_length;
  386. }
  387. if(compute_content) {
  388. /* Last string has double null-terminator. */
  389. *current_pos = '\0';
  390. }
  391. #endif
  392. return actual_length;
  393. }
  394. /*
  395. * Returns TRUE if the hostname is a numeric IPv4/IPv6 Address,
  396. * and populates the buffer with IPv4/IPv6 info.
  397. */
  398. static bool get_num_host_info(struct num_ip_data *ip_blob,
  399. LPCSTR hostname)
  400. {
  401. struct in_addr ia;
  402. struct in6_addr ia6;
  403. bool result = FALSE;
  404. int res = Curl_inet_pton(AF_INET, hostname, &ia);
  405. if(res) {
  406. ip_blob->size = sizeof(struct in_addr);
  407. memcpy(&ip_blob->bData.ia, &ia, sizeof(struct in_addr));
  408. result = TRUE;
  409. }
  410. else {
  411. res = Curl_inet_pton(AF_INET6, hostname, &ia6);
  412. if(res) {
  413. ip_blob->size = sizeof(struct in6_addr);
  414. memcpy(&ip_blob->bData.ia6, &ia6, sizeof(struct in6_addr));
  415. result = TRUE;
  416. }
  417. }
  418. return result;
  419. }
  420. static bool get_alt_name_info(struct Curl_easy *data,
  421. PCCERT_CONTEXT ctx,
  422. PCERT_ALT_NAME_INFO *alt_name_info,
  423. LPDWORD alt_name_info_size)
  424. {
  425. bool result = FALSE;
  426. #if defined(CURL_WINDOWS_UWP)
  427. (void)data;
  428. (void)ctx;
  429. (void)alt_name_info;
  430. (void)alt_name_info_size;
  431. #else
  432. PCERT_INFO cert_info = NULL;
  433. PCERT_EXTENSION extension = NULL;
  434. CRYPT_DECODE_PARA decode_para = { sizeof(CRYPT_DECODE_PARA), NULL, NULL };
  435. if(!ctx) {
  436. failf(data, "schannel: Null certificate context.");
  437. return result;
  438. }
  439. cert_info = ctx->pCertInfo;
  440. if(!cert_info) {
  441. failf(data, "schannel: Null certificate info.");
  442. return result;
  443. }
  444. extension = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
  445. cert_info->cExtension,
  446. cert_info->rgExtension);
  447. if(!extension) {
  448. failf(data, "schannel: CertFindExtension() returned no extension.");
  449. return result;
  450. }
  451. if(!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
  452. szOID_SUBJECT_ALT_NAME2,
  453. extension->Value.pbData,
  454. extension->Value.cbData,
  455. CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
  456. &decode_para,
  457. alt_name_info,
  458. alt_name_info_size)) {
  459. failf(data,
  460. "schannel: CryptDecodeObjectEx() returned no alternate name "
  461. "information.");
  462. return result;
  463. }
  464. result = TRUE;
  465. #endif
  466. return result;
  467. }
  468. /* Verify the server's hostname */
  469. CURLcode Curl_verify_host(struct Curl_cfilter *cf,
  470. struct Curl_easy *data)
  471. {
  472. struct ssl_connect_data *connssl = cf->ctx;
  473. SECURITY_STATUS sspi_status;
  474. CURLcode result = CURLE_PEER_FAILED_VERIFICATION;
  475. CERT_CONTEXT *pCertContextServer = NULL;
  476. TCHAR *cert_hostname_buff = NULL;
  477. size_t cert_hostname_buff_index = 0;
  478. const char *conn_hostname = connssl->peer.hostname;
  479. size_t hostlen = strlen(conn_hostname);
  480. DWORD len = 0;
  481. DWORD actual_len = 0;
  482. PCERT_ALT_NAME_INFO alt_name_info = NULL;
  483. DWORD alt_name_info_size = 0;
  484. struct num_ip_data ip_blob = { 0 };
  485. bool Win8_compat;
  486. struct num_ip_data *p = &ip_blob;
  487. DWORD i;
  488. sspi_status =
  489. Curl_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
  490. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  491. &pCertContextServer);
  492. if((sspi_status != SEC_E_OK) || !pCertContextServer) {
  493. char buffer[STRERROR_LEN];
  494. failf(data, "schannel: Failed to read remote certificate context: %s",
  495. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  496. goto cleanup;
  497. }
  498. Win8_compat = curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT,
  499. VERSION_GREATER_THAN_EQUAL);
  500. if(get_num_host_info(p, conn_hostname) || !Win8_compat) {
  501. if(!get_alt_name_info(data, pCertContextServer,
  502. &alt_name_info, &alt_name_info_size)) {
  503. goto cleanup;
  504. }
  505. }
  506. if(p->size && alt_name_info) {
  507. for(i = 0; i < alt_name_info->cAltEntry; ++i) {
  508. PCERT_ALT_NAME_ENTRY entry = &alt_name_info->rgAltEntry[i];
  509. if(entry->dwAltNameChoice == CERT_ALT_NAME_IP_ADDRESS) {
  510. if(entry->IPAddress.cbData == p->size) {
  511. if(!memcmp(entry->IPAddress.pbData, &p->bData,
  512. entry->IPAddress.cbData)) {
  513. result = CURLE_OK;
  514. infof(data,
  515. "schannel: connection hostname (%s) matched cert's IP address!",
  516. conn_hostname);
  517. break;
  518. }
  519. }
  520. }
  521. }
  522. }
  523. else {
  524. /* Determine the size of the string needed for the cert hostname */
  525. len = cert_get_name_string(data, pCertContextServer,
  526. NULL, 0, alt_name_info, Win8_compat);
  527. if(len == 0) {
  528. failf(data,
  529. "schannel: CertGetNameString() returned no "
  530. "certificate name information");
  531. goto cleanup;
  532. }
  533. /* CertGetNameString guarantees that the returned name will not contain
  534. * embedded null bytes. This appears to be undocumented behavior.
  535. */
  536. cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR));
  537. if(!cert_hostname_buff) {
  538. result = CURLE_OUT_OF_MEMORY;
  539. goto cleanup;
  540. }
  541. actual_len = cert_get_name_string(data, pCertContextServer,
  542. (LPTSTR)cert_hostname_buff, len, alt_name_info, Win8_compat);
  543. /* Sanity check */
  544. if(actual_len != len) {
  545. failf(data,
  546. "schannel: CertGetNameString() returned certificate "
  547. "name information of unexpected size");
  548. goto cleanup;
  549. }
  550. /* cert_hostname_buff contains all DNS names, where each name is
  551. * null-terminated and the last DNS name is double null-terminated. Due to
  552. * this encoding, use the length of the buffer to iterate over all names.
  553. */
  554. while(cert_hostname_buff_index < len &&
  555. cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') &&
  556. result == CURLE_PEER_FAILED_VERIFICATION) {
  557. char *cert_hostname;
  558. /* Comparing the cert name and the connection hostname encoded as UTF-8
  559. * is acceptable since both values are assumed to use ASCII
  560. * (or some equivalent) encoding
  561. */
  562. cert_hostname = curlx_convert_tchar_to_UTF8(
  563. &cert_hostname_buff[cert_hostname_buff_index]);
  564. if(!cert_hostname) {
  565. result = CURLE_OUT_OF_MEMORY;
  566. }
  567. else {
  568. if(Curl_cert_hostcheck(cert_hostname, strlen(cert_hostname),
  569. conn_hostname, hostlen)) {
  570. infof(data,
  571. "schannel: connection hostname (%s) validated "
  572. "against certificate name (%s)",
  573. conn_hostname, cert_hostname);
  574. result = CURLE_OK;
  575. }
  576. else {
  577. size_t cert_hostname_len;
  578. infof(data,
  579. "schannel: connection hostname (%s) did not match "
  580. "against certificate name (%s)",
  581. conn_hostname, cert_hostname);
  582. cert_hostname_len =
  583. _tcslen(&cert_hostname_buff[cert_hostname_buff_index]);
  584. /* Move on to next cert name */
  585. cert_hostname_buff_index += cert_hostname_len + 1;
  586. result = CURLE_PEER_FAILED_VERIFICATION;
  587. }
  588. curlx_unicodefree(cert_hostname);
  589. }
  590. }
  591. if(result == CURLE_PEER_FAILED_VERIFICATION) {
  592. failf(data,
  593. "schannel: CertGetNameString() failed to match "
  594. "connection hostname (%s) against server certificate names",
  595. conn_hostname);
  596. }
  597. else if(result != CURLE_OK)
  598. failf(data, "schannel: server certificate name verification failed");
  599. }
  600. cleanup:
  601. Curl_safefree(cert_hostname_buff);
  602. if(pCertContextServer)
  603. CertFreeCertificateContext(pCertContextServer);
  604. return result;
  605. }
  606. #ifdef HAS_MANUAL_VERIFY_API
  607. /* Verify the server's certificate and hostname */
  608. CURLcode Curl_verify_certificate(struct Curl_cfilter *cf,
  609. struct Curl_easy *data)
  610. {
  611. struct ssl_connect_data *connssl = cf->ctx;
  612. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  613. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  614. SECURITY_STATUS sspi_status;
  615. CURLcode result = CURLE_OK;
  616. CERT_CONTEXT *pCertContextServer = NULL;
  617. const CERT_CHAIN_CONTEXT *pChainContext = NULL;
  618. HCERTCHAINENGINE cert_chain_engine = NULL;
  619. HCERTSTORE trust_store = NULL;
  620. HCERTSTORE own_trust_store = NULL;
  621. DEBUGASSERT(BACKEND);
  622. sspi_status =
  623. Curl_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
  624. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  625. &pCertContextServer);
  626. if((sspi_status != SEC_E_OK) || !pCertContextServer) {
  627. char buffer[STRERROR_LEN];
  628. failf(data, "schannel: Failed to read remote certificate context: %s",
  629. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  630. result = CURLE_PEER_FAILED_VERIFICATION;
  631. }
  632. if(result == CURLE_OK &&
  633. (conn_config->CAfile || conn_config->ca_info_blob) &&
  634. BACKEND->use_manual_cred_validation) {
  635. /*
  636. * Create a chain engine that uses the certificates in the CA file as
  637. * trusted certificates. This is only supported on Windows 7+.
  638. */
  639. if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT,
  640. VERSION_LESS_THAN)) {
  641. failf(data, "schannel: this version of Windows is too old to support "
  642. "certificate verification via CA bundle file.");
  643. result = CURLE_SSL_CACERT_BADFILE;
  644. }
  645. else {
  646. /* try cache */
  647. trust_store = Curl_schannel_get_cached_cert_store(cf, data);
  648. if(trust_store) {
  649. infof(data, "schannel: reusing certificate store from cache");
  650. }
  651. else {
  652. /* Open the certificate store */
  653. trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY,
  654. 0,
  655. (HCRYPTPROV)NULL,
  656. CERT_STORE_CREATE_NEW_FLAG,
  657. NULL);
  658. if(!trust_store) {
  659. char buffer[STRERROR_LEN];
  660. failf(data, "schannel: failed to create certificate store: %s",
  661. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  662. result = CURLE_SSL_CACERT_BADFILE;
  663. }
  664. else {
  665. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  666. own_trust_store = trust_store;
  667. if(ca_info_blob) {
  668. result = add_certs_data_to_store(trust_store,
  669. (const char *)ca_info_blob->data,
  670. ca_info_blob->len,
  671. "(memory blob)",
  672. data);
  673. }
  674. else {
  675. result = add_certs_file_to_store(trust_store,
  676. conn_config->CAfile,
  677. data);
  678. }
  679. if(result == CURLE_OK) {
  680. if(Curl_schannel_set_cached_cert_store(cf, data, trust_store)) {
  681. own_trust_store = NULL;
  682. }
  683. }
  684. }
  685. }
  686. }
  687. if(result == CURLE_OK) {
  688. struct cert_chain_engine_config_win7 engine_config;
  689. BOOL create_engine_result;
  690. memset(&engine_config, 0, sizeof(engine_config));
  691. engine_config.cbSize = sizeof(engine_config);
  692. engine_config.hExclusiveRoot = trust_store;
  693. /* CertCreateCertificateChainEngine will check the expected size of the
  694. * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size
  695. * does not match the expected size. When this occurs, it indicates that
  696. * CAINFO is not supported on the version of Windows in use.
  697. */
  698. create_engine_result =
  699. CertCreateCertificateChainEngine(
  700. (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine);
  701. if(!create_engine_result) {
  702. char buffer[STRERROR_LEN];
  703. failf(data,
  704. "schannel: failed to create certificate chain engine: %s",
  705. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  706. result = CURLE_SSL_CACERT_BADFILE;
  707. }
  708. }
  709. }
  710. if(result == CURLE_OK) {
  711. CERT_CHAIN_PARA ChainPara;
  712. memset(&ChainPara, 0, sizeof(ChainPara));
  713. ChainPara.cbSize = sizeof(ChainPara);
  714. if(!CertGetCertificateChain(cert_chain_engine,
  715. pCertContextServer,
  716. NULL,
  717. pCertContextServer->hCertStore,
  718. &ChainPara,
  719. (ssl_config->no_revoke ? 0 :
  720. CERT_CHAIN_REVOCATION_CHECK_CHAIN),
  721. NULL,
  722. &pChainContext)) {
  723. char buffer[STRERROR_LEN];
  724. failf(data, "schannel: CertGetCertificateChain failed: %s",
  725. Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
  726. pChainContext = NULL;
  727. result = CURLE_PEER_FAILED_VERIFICATION;
  728. }
  729. if(result == CURLE_OK) {
  730. CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
  731. DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED);
  732. dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
  733. if(data->set.ssl.revoke_best_effort) {
  734. /* Ignore errors when root certificates are missing the revocation
  735. * list URL, or when the list could not be downloaded because the
  736. * server is currently unreachable. */
  737. dwTrustErrorMask &= ~(DWORD)(CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
  738. CERT_TRUST_IS_OFFLINE_REVOCATION);
  739. }
  740. if(dwTrustErrorMask) {
  741. if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED)
  742. failf(data, "schannel: CertGetCertificateChain trust error"
  743. " CERT_TRUST_IS_REVOKED");
  744. else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
  745. failf(data, "schannel: CertGetCertificateChain trust error"
  746. " CERT_TRUST_IS_PARTIAL_CHAIN");
  747. else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
  748. failf(data, "schannel: CertGetCertificateChain trust error"
  749. " CERT_TRUST_IS_UNTRUSTED_ROOT");
  750. else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
  751. failf(data, "schannel: CertGetCertificateChain trust error"
  752. " CERT_TRUST_IS_NOT_TIME_VALID");
  753. else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
  754. failf(data, "schannel: CertGetCertificateChain trust error"
  755. " CERT_TRUST_REVOCATION_STATUS_UNKNOWN");
  756. else
  757. failf(data, "schannel: CertGetCertificateChain error mask: 0x%08lx",
  758. dwTrustErrorMask);
  759. result = CURLE_PEER_FAILED_VERIFICATION;
  760. }
  761. }
  762. }
  763. if(result == CURLE_OK) {
  764. if(conn_config->verifyhost) {
  765. result = Curl_verify_host(cf, data);
  766. }
  767. }
  768. if(cert_chain_engine) {
  769. CertFreeCertificateChainEngine(cert_chain_engine);
  770. }
  771. if(own_trust_store) {
  772. CertCloseStore(own_trust_store, 0);
  773. }
  774. if(pChainContext)
  775. CertFreeCertificateChain(pChainContext);
  776. if(pCertContextServer)
  777. CertFreeCertificateContext(pCertContextServer);
  778. return result;
  779. }
  780. #endif /* HAS_MANUAL_VERIFY_API */
  781. #endif /* USE_SCHANNEL */