schannel_verify.c 18 KB

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