cert_verify_proc_win.cc 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/cert/cert_verify_proc_win.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <string>
  8. #include "base/bind.h"
  9. #include "base/memory/free_deleter.h"
  10. #include "base/metrics/histogram_macros.h"
  11. #include "base/no_destructor.h"
  12. #include "base/strings/string_util.h"
  13. #include "base/strings/utf_string_conversions.h"
  14. #include "base/synchronization/lock.h"
  15. #include "base/task/thread_pool.h"
  16. #include "base/threading/thread_local.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "base/win/registry.h"
  19. #include "base/win/windows_version.h"
  20. #include "crypto/capi_util.h"
  21. #include "crypto/scoped_capi_types.h"
  22. #include "crypto/sha2.h"
  23. #include "net/base/net_errors.h"
  24. #include "net/cert/asn1_util.h"
  25. #include "net/cert/cert_status_flags.h"
  26. #include "net/cert/cert_verifier.h"
  27. #include "net/cert/cert_verify_result.h"
  28. #include "net/cert/crl_set.h"
  29. #include "net/cert/ev_root_ca_metadata.h"
  30. #include "net/cert/known_roots.h"
  31. #include "net/cert/known_roots_win.h"
  32. #include "net/cert/test_root_certs.h"
  33. #include "net/cert/x509_certificate.h"
  34. #include "net/cert/x509_util_win.h"
  35. #if !defined(CERT_TRUST_HAS_WEAK_SIGNATURE)
  36. // This was introduced in Windows 8 / Windows Server 2012, but retroactively
  37. // ported as far back as Windows XP via system update.
  38. #define CERT_TRUST_HAS_WEAK_SIGNATURE 0x00100000
  39. #endif
  40. namespace net {
  41. namespace {
  42. const void* kResultDebugDataKey = &kResultDebugDataKey;
  43. int MapSecurityError(SECURITY_STATUS err) {
  44. // There are numerous security error codes, but these are the ones we thus
  45. // far find interesting.
  46. switch (err) {
  47. case SEC_E_WRONG_PRINCIPAL: // Schannel
  48. case CERT_E_CN_NO_MATCH: // CryptoAPI
  49. return ERR_CERT_COMMON_NAME_INVALID;
  50. case SEC_E_UNTRUSTED_ROOT: // Schannel
  51. case CERT_E_UNTRUSTEDROOT: // CryptoAPI
  52. case TRUST_E_CERT_SIGNATURE: // CryptoAPI. Caused by weak crypto or bad
  53. // signatures, but not differentiable.
  54. return ERR_CERT_AUTHORITY_INVALID;
  55. case SEC_E_CERT_EXPIRED: // Schannel
  56. case CERT_E_EXPIRED: // CryptoAPI
  57. return ERR_CERT_DATE_INVALID;
  58. case CRYPT_E_NO_REVOCATION_CHECK:
  59. return ERR_CERT_NO_REVOCATION_MECHANISM;
  60. case CRYPT_E_REVOCATION_OFFLINE:
  61. return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;
  62. case CRYPT_E_REVOKED: // Schannel and CryptoAPI
  63. return ERR_CERT_REVOKED;
  64. case SEC_E_CERT_UNKNOWN:
  65. case CERT_E_ROLE:
  66. return ERR_CERT_INVALID;
  67. case CERT_E_WRONG_USAGE:
  68. // TODO(wtc): Should we add ERR_CERT_WRONG_USAGE?
  69. return ERR_CERT_INVALID;
  70. // We received an unexpected_message or illegal_parameter alert message
  71. // from the server.
  72. case SEC_E_ILLEGAL_MESSAGE:
  73. return ERR_SSL_PROTOCOL_ERROR;
  74. case SEC_E_ALGORITHM_MISMATCH:
  75. return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
  76. case SEC_E_INVALID_HANDLE:
  77. return ERR_UNEXPECTED;
  78. case SEC_E_OK:
  79. return OK;
  80. default:
  81. LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
  82. return ERR_FAILED;
  83. }
  84. }
  85. // Map the errors in the chain_context->TrustStatus.dwErrorStatus returned by
  86. // CertGetCertificateChain to our certificate status flags.
  87. int MapCertChainErrorStatusToCertStatus(DWORD error_status) {
  88. CertStatus cert_status = 0;
  89. // We don't include CERT_TRUST_IS_NOT_TIME_NESTED because it's obsolete and
  90. // we wouldn't consider it an error anyway
  91. const DWORD kDateInvalidErrors = CERT_TRUST_IS_NOT_TIME_VALID |
  92. CERT_TRUST_CTL_IS_NOT_TIME_VALID;
  93. if (error_status & kDateInvalidErrors)
  94. cert_status |= CERT_STATUS_DATE_INVALID;
  95. const DWORD kAuthorityInvalidErrors = CERT_TRUST_IS_UNTRUSTED_ROOT |
  96. CERT_TRUST_IS_EXPLICIT_DISTRUST |
  97. CERT_TRUST_IS_PARTIAL_CHAIN;
  98. if (error_status & kAuthorityInvalidErrors)
  99. cert_status |= CERT_STATUS_AUTHORITY_INVALID;
  100. if ((error_status & CERT_TRUST_REVOCATION_STATUS_UNKNOWN) &&
  101. !(error_status & CERT_TRUST_IS_OFFLINE_REVOCATION))
  102. cert_status |= CERT_STATUS_NO_REVOCATION_MECHANISM;
  103. if (error_status & CERT_TRUST_IS_OFFLINE_REVOCATION)
  104. cert_status |= CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
  105. if (error_status & CERT_TRUST_IS_REVOKED)
  106. cert_status |= CERT_STATUS_REVOKED;
  107. const DWORD kWrongUsageErrors = CERT_TRUST_IS_NOT_VALID_FOR_USAGE |
  108. CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE;
  109. if (error_status & kWrongUsageErrors) {
  110. // TODO(wtc): Should we add CERT_STATUS_WRONG_USAGE?
  111. cert_status |= CERT_STATUS_INVALID;
  112. }
  113. if (error_status & CERT_TRUST_IS_NOT_SIGNATURE_VALID) {
  114. // Check for a signature that does not meet the OS criteria for strong
  115. // signatures.
  116. // Note: These checks may be more restrictive than the current weak key
  117. // criteria implemented within CertVerifier, such as excluding SHA-1 or
  118. // excluding RSA keys < 2048 bits. However, if the user has configured
  119. // these more stringent checks, respect that configuration and err on the
  120. // more restrictive criteria.
  121. if (error_status & CERT_TRUST_HAS_WEAK_SIGNATURE) {
  122. cert_status |= CERT_STATUS_WEAK_KEY;
  123. } else {
  124. cert_status |= CERT_STATUS_AUTHORITY_INVALID;
  125. }
  126. }
  127. // The rest of the errors.
  128. const DWORD kCertInvalidErrors =
  129. CERT_TRUST_IS_CYCLIC |
  130. CERT_TRUST_INVALID_EXTENSION |
  131. CERT_TRUST_INVALID_POLICY_CONSTRAINTS |
  132. CERT_TRUST_INVALID_BASIC_CONSTRAINTS |
  133. CERT_TRUST_INVALID_NAME_CONSTRAINTS |
  134. CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID |
  135. CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT |
  136. CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT |
  137. CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT |
  138. CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT |
  139. CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY |
  140. CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT;
  141. if (error_status & kCertInvalidErrors)
  142. cert_status |= CERT_STATUS_INVALID;
  143. return cert_status;
  144. }
  145. // Returns true if any common name in the certificate's Subject field contains
  146. // a NULL character.
  147. bool CertSubjectCommonNameHasNull(PCCERT_CONTEXT cert) {
  148. CRYPT_DECODE_PARA decode_para;
  149. decode_para.cbSize = sizeof(decode_para);
  150. decode_para.pfnAlloc = crypto::CryptAlloc;
  151. decode_para.pfnFree = crypto::CryptFree;
  152. CERT_NAME_INFO* name_info = nullptr;
  153. DWORD name_info_size = 0;
  154. BOOL rv;
  155. rv = CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
  156. WINCRYPT_X509_NAME,
  157. cert->pCertInfo->Subject.pbData,
  158. cert->pCertInfo->Subject.cbData,
  159. CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
  160. &decode_para,
  161. &name_info,
  162. &name_info_size);
  163. if (rv) {
  164. std::unique_ptr<CERT_NAME_INFO, base::FreeDeleter> scoped_name_info(
  165. name_info);
  166. // The Subject field may have multiple common names. According to the
  167. // "PKI Layer Cake" paper, CryptoAPI uses every common name in the
  168. // Subject field, so we inspect every common name.
  169. //
  170. // From RFC 5280:
  171. // X520CommonName ::= CHOICE {
  172. // teletexString TeletexString (SIZE (1..ub-common-name)),
  173. // printableString PrintableString (SIZE (1..ub-common-name)),
  174. // universalString UniversalString (SIZE (1..ub-common-name)),
  175. // utf8String UTF8String (SIZE (1..ub-common-name)),
  176. // bmpString BMPString (SIZE (1..ub-common-name)) }
  177. //
  178. // We also check IA5String and VisibleString.
  179. for (DWORD i = 0; i < name_info->cRDN; ++i) {
  180. PCERT_RDN rdn = &name_info->rgRDN[i];
  181. for (DWORD j = 0; j < rdn->cRDNAttr; ++j) {
  182. PCERT_RDN_ATTR rdn_attr = &rdn->rgRDNAttr[j];
  183. if (strcmp(rdn_attr->pszObjId, szOID_COMMON_NAME) == 0) {
  184. switch (rdn_attr->dwValueType) {
  185. // After the CryptoAPI ASN.1 security vulnerabilities described in
  186. // http://www.microsoft.com/technet/security/Bulletin/MS09-056.mspx
  187. // were patched, we get CERT_RDN_ENCODED_BLOB for a common name
  188. // that contains a NULL character.
  189. case CERT_RDN_ENCODED_BLOB:
  190. break;
  191. // Array of 8-bit characters.
  192. case CERT_RDN_PRINTABLE_STRING:
  193. case CERT_RDN_TELETEX_STRING:
  194. case CERT_RDN_IA5_STRING:
  195. case CERT_RDN_VISIBLE_STRING:
  196. for (DWORD k = 0; k < rdn_attr->Value.cbData; ++k) {
  197. if (rdn_attr->Value.pbData[k] == '\0')
  198. return true;
  199. }
  200. break;
  201. // Array of 16-bit characters.
  202. case CERT_RDN_BMP_STRING:
  203. case CERT_RDN_UTF8_STRING: {
  204. DWORD num_wchars = rdn_attr->Value.cbData / 2;
  205. wchar_t* common_name =
  206. reinterpret_cast<wchar_t*>(rdn_attr->Value.pbData);
  207. for (DWORD k = 0; k < num_wchars; ++k) {
  208. if (common_name[k] == L'\0')
  209. return true;
  210. }
  211. break;
  212. }
  213. // Array of ints (32-bit).
  214. case CERT_RDN_UNIVERSAL_STRING: {
  215. DWORD num_ints = rdn_attr->Value.cbData / 4;
  216. int* common_name =
  217. reinterpret_cast<int*>(rdn_attr->Value.pbData);
  218. for (DWORD k = 0; k < num_ints; ++k) {
  219. if (common_name[k] == 0)
  220. return true;
  221. }
  222. break;
  223. }
  224. default:
  225. NOTREACHED();
  226. break;
  227. }
  228. }
  229. }
  230. }
  231. }
  232. return false;
  233. }
  234. // Saves some information about the certificate chain |chain_context| in
  235. // |*verify_result|. The caller MUST initialize |*verify_result| before
  236. // calling this function.
  237. void GetCertChainInfo(PCCERT_CHAIN_CONTEXT chain_context,
  238. CertVerifyResult* verify_result) {
  239. if (chain_context->cChain == 0 || chain_context->rgpChain[0]->cElement == 0) {
  240. verify_result->cert_status |= CERT_STATUS_INVALID;
  241. return;
  242. }
  243. PCERT_SIMPLE_CHAIN first_chain = chain_context->rgpChain[0];
  244. DWORD num_elements = first_chain->cElement;
  245. PCERT_CHAIN_ELEMENT* element = first_chain->rgpElement;
  246. PCCERT_CONTEXT verified_cert = nullptr;
  247. std::vector<PCCERT_CONTEXT> verified_chain;
  248. if (base::win::GetVersion() >= base::win::Version::WIN10) {
  249. // Recheck signatures in the event junk data was provided.
  250. for (DWORD i = 0; i < num_elements - 1; ++i) {
  251. PCCERT_CONTEXT issuer = element[i + 1]->pCertContext;
  252. // If Issuer isn't ECC, skip this certificate.
  253. if (strcmp(issuer->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId,
  254. szOID_ECC_PUBLIC_KEY)) {
  255. continue;
  256. }
  257. PCCERT_CONTEXT cert = element[i]->pCertContext;
  258. if (!CryptVerifyCertificateSignatureEx(
  259. NULL, X509_ASN_ENCODING, CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
  260. const_cast<PCERT_CONTEXT>(cert),
  261. CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
  262. const_cast<PCERT_CONTEXT>(issuer), 0, nullptr)) {
  263. verify_result->cert_status |= CERT_STATUS_INVALID;
  264. break;
  265. }
  266. }
  267. }
  268. bool has_root_ca = num_elements > 1 &&
  269. !(chain_context->TrustStatus.dwErrorStatus &
  270. CERT_TRUST_IS_PARTIAL_CHAIN);
  271. // Each chain starts with the end entity certificate (i = 0) and ends with
  272. // either the root CA certificate or the last available intermediate. If a
  273. // root CA certificate is present, do not inspect the signature algorithm of
  274. // the root CA certificate because the signature on the trust anchor is not
  275. // important.
  276. if (has_root_ca) {
  277. // If a full chain was constructed, regardless of whether it was trusted,
  278. // don't inspect the root's signature algorithm.
  279. num_elements -= 1;
  280. }
  281. for (DWORD i = 0; i < num_elements; ++i) {
  282. PCCERT_CONTEXT cert = element[i]->pCertContext;
  283. if (i == 0) {
  284. verified_cert = cert;
  285. } else {
  286. verified_chain.push_back(cert);
  287. }
  288. }
  289. if (verified_cert) {
  290. // Add the root certificate, if present, as it was not added above.
  291. if (has_root_ca)
  292. verified_chain.push_back(element[num_elements]->pCertContext);
  293. scoped_refptr<X509Certificate> verified_cert_with_chain =
  294. x509_util::CreateX509CertificateFromCertContexts(verified_cert,
  295. verified_chain);
  296. if (verified_cert_with_chain)
  297. verify_result->verified_cert = std::move(verified_cert_with_chain);
  298. else
  299. verify_result->cert_status |= CERT_STATUS_INVALID;
  300. }
  301. }
  302. // Decodes the cert's certificatePolicies extension into a CERT_POLICIES_INFO
  303. // structure and stores it in *output.
  304. void GetCertPoliciesInfo(
  305. PCCERT_CONTEXT cert,
  306. std::unique_ptr<CERT_POLICIES_INFO, base::FreeDeleter>* output) {
  307. PCERT_EXTENSION extension = CertFindExtension(szOID_CERT_POLICIES,
  308. cert->pCertInfo->cExtension,
  309. cert->pCertInfo->rgExtension);
  310. if (!extension)
  311. return;
  312. CRYPT_DECODE_PARA decode_para;
  313. decode_para.cbSize = sizeof(decode_para);
  314. decode_para.pfnAlloc = crypto::CryptAlloc;
  315. decode_para.pfnFree = crypto::CryptFree;
  316. CERT_POLICIES_INFO* policies_info = nullptr;
  317. DWORD policies_info_size = 0;
  318. BOOL rv;
  319. rv = CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
  320. szOID_CERT_POLICIES,
  321. extension->Value.pbData,
  322. extension->Value.cbData,
  323. CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
  324. &decode_para,
  325. &policies_info,
  326. &policies_info_size);
  327. if (rv)
  328. output->reset(policies_info);
  329. }
  330. // Computes the SHA-256 hash of the SPKI of |cert| and stores it in |hash|,
  331. // returning true. If an error occurs, returns false and leaves |hash|
  332. // unmodified.
  333. bool HashSPKI(PCCERT_CONTEXT cert, std::string* hash) {
  334. base::StringPiece der_bytes(
  335. reinterpret_cast<const char*>(cert->pbCertEncoded), cert->cbCertEncoded);
  336. base::StringPiece spki;
  337. if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki))
  338. return false;
  339. *hash = crypto::SHA256HashString(spki);
  340. return true;
  341. }
  342. bool GetSubject(PCCERT_CONTEXT cert, base::StringPiece* out_subject) {
  343. base::StringPiece der_bytes(
  344. reinterpret_cast<const char*>(cert->pbCertEncoded), cert->cbCertEncoded);
  345. return asn1::ExtractSubjectFromDERCert(der_bytes, out_subject);
  346. }
  347. enum CRLSetResult {
  348. // Indicates an error happened while attempting to determine CRLSet status.
  349. // For example, if the certificate's SPKI could not be extracted.
  350. kCRLSetError,
  351. // Indicates there is no fresh information about the certificate, or if the
  352. // CRLSet has expired.
  353. // In the case of certificate chains, this is only returned if the leaf
  354. // certificate is not covered by the CRLSet; this is because some
  355. // intermediates are fully covered, but after filtering, the issuer's CRL
  356. // is empty and thus omitted from the CRLSet. Since online checking is
  357. // performed for EV certificates when this status is returned, this would
  358. // result in needless online lookups for certificates known not-revoked.
  359. kCRLSetUnknown,
  360. // Indicates that the certificate (or a certificate in the chain) has been
  361. // revoked.
  362. kCRLSetRevoked,
  363. // The certificate (or certificate chain) has no revocations.
  364. kCRLSetOk,
  365. };
  366. // Determines if |subject_cert| is revoked within |crl_set|,
  367. // storing the SubjectPublicKeyInfo hash of |subject_cert| in
  368. // |*previous_hash|.
  369. //
  370. // CRLSets store revocations by both SPKI and by the tuple of Issuer SPKI
  371. // Hash & Serial. While |subject_cert| contains enough information to check
  372. // for SPKI revocations, to determine the issuer's SPKI, either |issuer_cert|
  373. // must be supplied, or the hash of the issuer's SPKI provided in
  374. // |*previous_hash|. If |issuer_cert| is omitted, and |*previous_hash| is empty,
  375. // only SPKI checks are performed.
  376. //
  377. // To avoid recomputing SPKI hashes, the hash of |subject_cert| is stored in
  378. // |*previous_hash|. This allows chaining revocation checking, by starting
  379. // at the root and iterating to the leaf, supplying |previous_hash| each time.
  380. //
  381. // In the event of a parsing error, |*previous_hash| is cleared, to prevent the
  382. // wrong Issuer&Serial tuple from being used.
  383. CRLSetResult CheckRevocationWithCRLSet(CRLSet* crl_set,
  384. PCCERT_CONTEXT subject_cert,
  385. PCCERT_CONTEXT issuer_cert,
  386. std::string* previous_hash) {
  387. DCHECK(crl_set);
  388. DCHECK(subject_cert);
  389. // Check to see if |subject_cert|'s SPKI or Subject is revoked.
  390. std::string subject_hash;
  391. base::StringPiece subject_name;
  392. if (!HashSPKI(subject_cert, &subject_hash) ||
  393. !GetSubject(subject_cert, &subject_name)) {
  394. NOTREACHED(); // Indicates Windows accepted something irrecoverably bad.
  395. previous_hash->clear();
  396. return kCRLSetError;
  397. }
  398. if (crl_set->CheckSPKI(subject_hash) == CRLSet::REVOKED ||
  399. crl_set->CheckSubject(subject_name, subject_hash) == CRLSet::REVOKED) {
  400. return kCRLSetRevoked;
  401. }
  402. // If no issuer cert is provided, nor a hash of the issuer's SPKI, no
  403. // further checks can be done.
  404. if (!issuer_cert && previous_hash->empty()) {
  405. previous_hash->swap(subject_hash);
  406. return kCRLSetUnknown;
  407. }
  408. // Compute the subject's serial.
  409. const CRYPT_INTEGER_BLOB* serial_blob =
  410. &subject_cert->pCertInfo->SerialNumber;
  411. auto serial_bytes = std::make_unique<uint8_t[]>(serial_blob->cbData);
  412. // The bytes of the serial number are stored little-endian.
  413. // Note: While MSDN implies that bytes are stripped from this serial,
  414. // they are not - only CertCompareIntegerBlob actually removes bytes.
  415. for (DWORD j = 0; j < serial_blob->cbData; j++)
  416. serial_bytes[j] = serial_blob->pbData[serial_blob->cbData - j - 1];
  417. base::StringPiece serial(reinterpret_cast<const char*>(serial_bytes.get()),
  418. serial_blob->cbData);
  419. // Compute the issuer's hash. If it was provided (via previous_hash),
  420. // use that; otherwise, compute it based on |issuer_cert|.
  421. std::string issuer_hash_local;
  422. std::string* issuer_hash = previous_hash;
  423. if (issuer_hash->empty()) {
  424. if (!HashSPKI(issuer_cert, &issuer_hash_local)) {
  425. NOTREACHED(); // Indicates Windows accepted something irrecoverably bad.
  426. previous_hash->clear();
  427. return kCRLSetError;
  428. }
  429. issuer_hash = &issuer_hash_local;
  430. }
  431. // Look up by serial & issuer SPKI.
  432. const CRLSet::Result result = crl_set->CheckSerial(serial, *issuer_hash);
  433. if (result == CRLSet::REVOKED)
  434. return kCRLSetRevoked;
  435. previous_hash->swap(subject_hash);
  436. if (result == CRLSet::GOOD)
  437. return kCRLSetOk;
  438. if (result == CRLSet::UNKNOWN)
  439. return kCRLSetUnknown;
  440. NOTREACHED();
  441. return kCRLSetError;
  442. }
  443. // CheckChainRevocationWithCRLSet attempts to check each element of |chain|
  444. // against |crl_set|. It returns:
  445. // kCRLSetRevoked: if any element of the chain is known to have been revoked.
  446. // kCRLSetUnknown: if there is no fresh information about the leaf
  447. // certificate in the chain or if the CRLSet has expired.
  448. //
  449. // Only the leaf certificate is considered for coverage because some
  450. // intermediates have CRLs with no revocations (after filtering) and
  451. // those CRLs are pruned from the CRLSet at generation time. This means
  452. // that some EV sites would otherwise take the hit of an OCSP lookup for
  453. // no reason.
  454. // kCRLSetOk: otherwise.
  455. CRLSetResult CheckChainRevocationWithCRLSet(PCCERT_CHAIN_CONTEXT chain,
  456. CRLSet* crl_set) {
  457. if (chain->cChain == 0 || chain->rgpChain[0]->cElement == 0)
  458. return kCRLSetOk;
  459. PCERT_CHAIN_ELEMENT* elements = chain->rgpChain[0]->rgpElement;
  460. DWORD num_elements = chain->rgpChain[0]->cElement;
  461. bool had_error = false;
  462. CRLSetResult result = kCRLSetError;
  463. std::string issuer_spki_hash;
  464. for (DWORD i = 0; i < num_elements; ++i) {
  465. PCCERT_CONTEXT subject = elements[num_elements - i - 1]->pCertContext;
  466. result =
  467. CheckRevocationWithCRLSet(crl_set, subject, nullptr, &issuer_spki_hash);
  468. if (result == kCRLSetRevoked)
  469. return result;
  470. if (result == kCRLSetError)
  471. had_error = true;
  472. }
  473. if (had_error || crl_set->IsExpired())
  474. return kCRLSetUnknown;
  475. return result;
  476. }
  477. void AppendPublicKeyHashesAndUpdateKnownRoot(PCCERT_CHAIN_CONTEXT chain,
  478. HashValueVector* hashes,
  479. bool* known_root) {
  480. if (chain->cChain == 0)
  481. return;
  482. PCERT_SIMPLE_CHAIN first_chain = chain->rgpChain[0];
  483. PCERT_CHAIN_ELEMENT* const element = first_chain->rgpElement;
  484. const DWORD num_elements = first_chain->cElement;
  485. // Walk the chain in reverse, from the probable root to the known leaf, as
  486. // an optimization for IsKnownRoot checks.
  487. for (DWORD i = num_elements; i > 0; i--) {
  488. PCCERT_CONTEXT cert = element[i - 1]->pCertContext;
  489. base::StringPiece der_bytes(
  490. reinterpret_cast<const char*>(cert->pbCertEncoded),
  491. cert->cbCertEncoded);
  492. base::StringPiece spki_bytes;
  493. if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
  494. continue;
  495. HashValue sha256(HASH_VALUE_SHA256);
  496. crypto::SHA256HashString(spki_bytes, sha256.data(), crypto::kSHA256Length);
  497. hashes->push_back(sha256);
  498. if (!*known_root) {
  499. *known_root =
  500. GetNetTrustAnchorHistogramIdForSPKI(sha256) != 0 || IsKnownRoot(cert);
  501. }
  502. }
  503. // Reverse the hash list, such that it's ordered from leaf to root.
  504. std::reverse(hashes->begin(), hashes->end());
  505. }
  506. // Returns true if the certificate is an extended-validation certificate.
  507. //
  508. // This function checks the certificatePolicies extensions of the
  509. // certificates in the certificate chain according to Section 7 (pp. 11-12)
  510. // of the EV Certificate Guidelines Version 1.0 at
  511. // http://cabforum.org/EV_Certificate_Guidelines.pdf.
  512. bool CheckEV(PCCERT_CHAIN_CONTEXT chain_context,
  513. bool rev_checking_enabled,
  514. const char* policy_oid) {
  515. DCHECK_NE(static_cast<DWORD>(0), chain_context->cChain);
  516. // If the cert doesn't match any of the policies, the
  517. // CERT_TRUST_IS_NOT_VALID_FOR_USAGE bit (0x10) in
  518. // chain_context->TrustStatus.dwErrorStatus is set.
  519. DWORD error_status = chain_context->TrustStatus.dwErrorStatus;
  520. if (!rev_checking_enabled) {
  521. // If online revocation checking is disabled then we will have still
  522. // requested that the revocation cache be checked. However, that will often
  523. // cause the following two error bits to be set. These error bits mean that
  524. // the local OCSP/CRL is stale or missing entries for these certificates.
  525. // Since they are expected, we mask them away.
  526. error_status &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION |
  527. CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
  528. }
  529. if (!chain_context->cChain || error_status != CERT_TRUST_NO_ERROR)
  530. return false;
  531. // Check the end certificate simple chain (chain_context->rgpChain[0]).
  532. // If the end certificate's certificatePolicies extension contains the
  533. // EV policy OID of the root CA, return true.
  534. PCERT_CHAIN_ELEMENT* element = chain_context->rgpChain[0]->rgpElement;
  535. int num_elements = chain_context->rgpChain[0]->cElement;
  536. if (num_elements < 2)
  537. return false;
  538. // Look up the EV policy OID of the root CA.
  539. PCCERT_CONTEXT root_cert = element[num_elements - 1]->pCertContext;
  540. SHA256HashValue fingerprint = x509_util::CalculateFingerprint256(root_cert);
  541. EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
  542. return metadata->HasEVPolicyOID(fingerprint, policy_oid);
  543. }
  544. // Custom revocation provider function that compares incoming certificates with
  545. // those in CRLSets. This is called BEFORE the default CRL & OCSP handling
  546. // is invoked (which is handled by the revocation provider function
  547. // "CertDllVerifyRevocation" in cryptnet.dll)
  548. BOOL WINAPI
  549. CertDllVerifyRevocationWithCRLSet(DWORD encoding_type,
  550. DWORD revocation_type,
  551. DWORD num_contexts,
  552. void* rgpvContext[],
  553. DWORD flags,
  554. PCERT_REVOCATION_PARA revocation_params,
  555. PCERT_REVOCATION_STATUS revocation_status);
  556. // Helper class that installs the CRLSet-based Revocation Provider as the
  557. // default revocation provider. Because it is installed as a function address
  558. // (meaning only scoped to the process, and not stored in the registry), it
  559. // will be used before any registry-based providers, including Microsoft's
  560. // default provider.
  561. class RevocationInjector {
  562. public:
  563. CRLSet* GetCRLSet() { return thread_local_crlset.Get(); }
  564. void SetCRLSet(CRLSet* crl_set) { thread_local_crlset.Set(crl_set); }
  565. private:
  566. friend struct base::LazyInstanceTraitsBase<RevocationInjector>;
  567. RevocationInjector() {
  568. const CRYPT_OID_FUNC_ENTRY kInterceptFunction[] = {
  569. {CRYPT_DEFAULT_OID,
  570. reinterpret_cast<void*>(&CertDllVerifyRevocationWithCRLSet)},
  571. };
  572. BOOL ok = CryptInstallOIDFunctionAddress(
  573. nullptr, X509_ASN_ENCODING, CRYPT_OID_VERIFY_REVOCATION_FUNC,
  574. std::size(kInterceptFunction), kInterceptFunction,
  575. CRYPT_INSTALL_OID_FUNC_BEFORE_FLAG);
  576. DCHECK(ok);
  577. }
  578. ~RevocationInjector() {}
  579. // As the revocation parameters passed to CertVerifyProc::VerifyInternal
  580. // cannot be officially smuggled to the Revocation Provider
  581. base::ThreadLocalPointer<CRLSet> thread_local_crlset;
  582. };
  583. // Leaky, as CertVerifyProc workers are themselves leaky.
  584. base::LazyInstance<RevocationInjector>::Leaky g_revocation_injector =
  585. LAZY_INSTANCE_INITIALIZER;
  586. BOOL WINAPI
  587. CertDllVerifyRevocationWithCRLSet(DWORD encoding_type,
  588. DWORD revocation_type,
  589. DWORD num_contexts,
  590. void* rgpvContext[],
  591. DWORD flags,
  592. PCERT_REVOCATION_PARA revocation_params,
  593. PCERT_REVOCATION_STATUS revocation_status) {
  594. PCERT_CONTEXT* cert_contexts = reinterpret_cast<PCERT_CONTEXT*>(rgpvContext);
  595. // The dummy CRLSet provider never returns that something is affirmatively
  596. // *un*revoked, as this would disable other revocation providers from being
  597. // checked for this certificate (much like an OCSP "Good" status would).
  598. // Instead, it merely indicates that insufficient information existed to
  599. // determine if the certificate was revoked (in the good case), or that a cert
  600. // is affirmatively revoked in the event it appears within the CRLSet.
  601. // Because of this, set up some basic bookkeeping for the results.
  602. CHECK(revocation_status);
  603. revocation_status->dwIndex = 0;
  604. revocation_status->dwError = static_cast<DWORD>(CRYPT_E_NO_REVOCATION_CHECK);
  605. revocation_status->dwReason = 0;
  606. if (num_contexts == 0 || !cert_contexts[0]) {
  607. SetLastError(static_cast<DWORD>(E_INVALIDARG));
  608. return FALSE;
  609. }
  610. if ((GET_CERT_ENCODING_TYPE(encoding_type) != X509_ASN_ENCODING) ||
  611. revocation_type != CERT_CONTEXT_REVOCATION_TYPE) {
  612. SetLastError(static_cast<DWORD>(CRYPT_E_NO_REVOCATION_CHECK));
  613. return FALSE;
  614. }
  615. // No revocation checking possible if there is no associated
  616. // CRLSet.
  617. CRLSet* crl_set = g_revocation_injector.Get().GetCRLSet();
  618. if (!crl_set)
  619. return FALSE;
  620. // |revocation_params| is an optional structure; to make life simple and avoid
  621. // the need to constantly check whether or not it was supplied, create a local
  622. // copy. If the caller didn't supply anything, it will be empty; otherwise,
  623. // it will be (non-owning) copies of the caller's original params.
  624. CERT_REVOCATION_PARA local_params;
  625. memset(&local_params, 0, sizeof(local_params));
  626. if (revocation_params) {
  627. DWORD bytes_to_copy = std::min(revocation_params->cbSize,
  628. static_cast<DWORD>(sizeof(local_params)));
  629. memcpy(&local_params, revocation_params, bytes_to_copy);
  630. }
  631. local_params.cbSize = sizeof(local_params);
  632. PCERT_CONTEXT subject_cert = cert_contexts[0];
  633. if ((flags & CERT_VERIFY_REV_CHAIN_FLAG) && num_contexts > 1) {
  634. // Verifying a chain; first verify from the last certificate in the
  635. // chain to the first, and then leave the last certificate (which
  636. // is presumably self-issued, although it may simply be a trust
  637. // anchor) as the |subject_cert| in order to scan for more
  638. // revocations.
  639. std::string issuer_hash;
  640. PCCERT_CONTEXT issuer_cert = nullptr;
  641. for (DWORD i = num_contexts; i > 0; --i) {
  642. subject_cert = cert_contexts[i - 1];
  643. if (!subject_cert) {
  644. SetLastError(static_cast<DWORD>(E_INVALIDARG));
  645. return FALSE;
  646. }
  647. CRLSetResult result = CheckRevocationWithCRLSet(
  648. crl_set, subject_cert, issuer_cert, &issuer_hash);
  649. if (result == kCRLSetRevoked) {
  650. revocation_status->dwIndex = i - 1;
  651. revocation_status->dwError = static_cast<DWORD>(CRYPT_E_REVOKED);
  652. revocation_status->dwReason = CRL_REASON_UNSPECIFIED;
  653. SetLastError(revocation_status->dwError);
  654. return FALSE;
  655. }
  656. issuer_cert = subject_cert;
  657. }
  658. // Verified all certificates from the trust anchor to the leaf, and none
  659. // were explicitly revoked. Now do a second pass to attempt to determine
  660. // the issuer for cert_contexts[num_contexts - 1], so that the
  661. // Issuer SPKI+Serial can be checked for that certificate.
  662. //
  663. // This code intentionally ignores the flag
  664. subject_cert = cert_contexts[num_contexts - 1];
  665. // Reset local_params.pIssuerCert, since it would contain the issuer
  666. // for cert_contexts[0].
  667. local_params.pIssuerCert = nullptr;
  668. // Fixup the revocation index to point to this cert (in the event it is
  669. // revoked). If it isn't revoked, this will be done undone later.
  670. revocation_status->dwIndex = num_contexts - 1;
  671. }
  672. // Determine the issuer cert for the incoming cert
  673. crypto::ScopedPCCERT_CONTEXT issuer_cert;
  674. if (local_params.pIssuerCert &&
  675. CryptVerifyCertificateSignatureEx(
  676. NULL, subject_cert->dwCertEncodingType,
  677. CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, subject_cert,
  678. CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
  679. const_cast<PCERT_CONTEXT>(local_params.pIssuerCert), 0, nullptr)) {
  680. // Caller has already supplied the issuer cert via the revocation params;
  681. // just use that.
  682. issuer_cert.reset(
  683. CertDuplicateCertificateContext(local_params.pIssuerCert));
  684. } else if (CertCompareCertificateName(subject_cert->dwCertEncodingType,
  685. &subject_cert->pCertInfo->Subject,
  686. &subject_cert->pCertInfo->Issuer) &&
  687. CryptVerifyCertificateSignatureEx(
  688. NULL, subject_cert->dwCertEncodingType,
  689. CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, subject_cert,
  690. CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, subject_cert, 0,
  691. nullptr)) {
  692. // Certificate is self-signed; use it as its own issuer.
  693. issuer_cert.reset(CertDuplicateCertificateContext(subject_cert));
  694. } else {
  695. // Scan the caller-supplied stores first, to try and find the issuer cert.
  696. for (DWORD i = 0; i < local_params.cCertStore && !issuer_cert; ++i) {
  697. PCCERT_CONTEXT previous_cert = nullptr;
  698. for (;;) {
  699. DWORD store_search_flags = CERT_STORE_SIGNATURE_FLAG;
  700. previous_cert = CertGetIssuerCertificateFromStore(
  701. local_params.rgCertStore[i], subject_cert, previous_cert,
  702. &store_search_flags);
  703. if (!previous_cert)
  704. break;
  705. // If a cert is found and meets the criteria, the flag will be reset to
  706. // zero. Thus NOT having the bit set is equivalent to having found a
  707. // matching certificate.
  708. if (!(store_search_flags & CERT_STORE_SIGNATURE_FLAG)) {
  709. // No need to dupe; reference is held.
  710. issuer_cert.reset(previous_cert);
  711. break;
  712. }
  713. }
  714. if (issuer_cert)
  715. break;
  716. if (GetLastError() == static_cast<DWORD>(CRYPT_E_SELF_SIGNED)) {
  717. issuer_cert.reset(CertDuplicateCertificateContext(subject_cert));
  718. break;
  719. }
  720. }
  721. // At this point, the Microsoft provider opens up the "CA", "Root", and
  722. // "SPC" stores to search for the issuer certificate, if not found in the
  723. // caller-supplied stores. It is unclear whether that is necessary here.
  724. }
  725. if (!issuer_cert) {
  726. // Rather than return CRYPT_E_NO_REVOCATION_CHECK (indicating everything
  727. // is fine to try the next provider), return CRYPT_E_REVOCATION_OFFLINE.
  728. // This propogates up to the caller as an error while checking revocation,
  729. // which is the desired intent if there are certificates that cannot
  730. // be checked.
  731. revocation_status->dwIndex = 0;
  732. revocation_status->dwError = static_cast<DWORD>(CRYPT_E_REVOCATION_OFFLINE);
  733. SetLastError(revocation_status->dwError);
  734. return FALSE;
  735. }
  736. std::string unused;
  737. CRLSetResult result = CheckRevocationWithCRLSet(crl_set, subject_cert,
  738. issuer_cert.get(), &unused);
  739. if (result == kCRLSetRevoked) {
  740. revocation_status->dwError = static_cast<DWORD>(CRYPT_E_REVOKED);
  741. revocation_status->dwReason = CRL_REASON_UNSPECIFIED;
  742. SetLastError(revocation_status->dwError);
  743. return FALSE;
  744. }
  745. // The result is ALWAYS FALSE in order to allow the next revocation provider
  746. // a chance to examine. The only difference is whether or not an error is
  747. // indicated via dwError (and SetLastError()).
  748. // Reset the error index so that Windows does not believe this code has
  749. // examined the entire chain and found no issues until the last cert (thus
  750. // skipping other revocation providers).
  751. revocation_status->dwIndex = 0;
  752. return FALSE;
  753. }
  754. class ScopedThreadLocalCRLSet {
  755. public:
  756. explicit ScopedThreadLocalCRLSet(CRLSet* crl_set) {
  757. g_revocation_injector.Get().SetCRLSet(crl_set);
  758. }
  759. ~ScopedThreadLocalCRLSet() { g_revocation_injector.Get().SetCRLSet(nullptr); }
  760. };
  761. // Helper class to determine the current version of AuthRoot, as stored in the
  762. // registry. Because calling `RegNotifyChangeKeyValue` associates the event
  763. // with the current thread, and `CertVerifyProc` exists to be used on
  764. // short-lived worker threads, this class handles the thread management to
  765. // ensure a cached, current value is always available.
  766. class AuthRootVersionChecker {
  767. public:
  768. struct AuthRootVersion {
  769. // The sequence number of the CTL.
  770. // Note: This is sorted big endian, similar to the encoded representation,
  771. // and not little-endian, like CRYPT_INTEGER_BLOBs are stored by Windows.
  772. std::vector<uint8_t> sequence_number;
  773. // The ThisUpdate of the AuthRoot CTL.
  774. // Note: If the AuthRoot version could not be determined, this will be the
  775. // default time, and is_null() will return true.
  776. base::Time this_update;
  777. };
  778. // Initializes the AuthRootVersionChecker. Note that this will open a
  779. // registry key on the current thread, which is expected to be persistent,
  780. // and begin monitoring for changes. This can be simplified once Windows 7
  781. // support is dropped.
  782. AuthRootVersionChecker();
  783. // Returns the current (potentially cached) version details from the
  784. // AuthRoot stored in the registry (if any).
  785. AuthRootVersion GetAuthRootVersion();
  786. private:
  787. ~AuthRootVersionChecker() = default;
  788. // Begins monitoring the registry for subsequent changes (e.g. to refresh
  789. // the cached value).
  790. void RefreshWatch();
  791. // Returns true if the currently cached value may be stale and requires
  792. // re-processing. If it returns true, the caller is responsible for calling
  793. // `UpdateAuthRootVersion()` and `RefreshWatch()` (in any order).
  794. bool ShouldUpdate() EXCLUSIVE_LOCKS_REQUIRED(lock_);
  795. // Updates the current AuthRoot version, which may block due to reading
  796. // the registry and parsing AuthRoot. Should only be called on a worker,
  797. // and while holding `lock_`.
  798. void UpdateAuthRootVersion() EXCLUSIVE_LOCKS_REQUIRED(lock_);
  799. base::win::RegKey key_;
  800. // On >= Win 8, the event signalled by Windows whenever the registry has
  801. // changed.
  802. const base::win::ScopedHandle event_;
  803. base::Lock lock_;
  804. AuthRootVersion auth_root_version_ GUARDED_BY(lock_);
  805. // On <= Win 7, stores the last update time of the registry key; used to
  806. // avoid needing to constantly reparse the registry value.
  807. base::Time last_update_ GUARDED_BY(lock_);
  808. };
  809. AuthRootVersionChecker::AuthRootVersionChecker()
  810. : event_(CreateEvent(nullptr, FALSE, TRUE, nullptr)) {
  811. DCHECK(event_.IsValid());
  812. constexpr wchar_t kAuthRootPath[] =
  813. L"SOFTWARE\\Microsoft\\SystemCertificates\\AuthRoot\\AutoUpdate";
  814. if (key_.Open(HKEY_LOCAL_MACHINE, kAuthRootPath, KEY_READ) != ERROR_SUCCESS)
  815. return;
  816. // On Win 7, last_update_ is the zero time, and thus will dirty the cache.
  817. // On Win 8+, event_ is initially signalled, simulating a dirty cache.
  818. }
  819. AuthRootVersionChecker::AuthRootVersion
  820. AuthRootVersionChecker::GetAuthRootVersion() {
  821. base::AutoLock guard(lock_);
  822. if (ShouldUpdate()) {
  823. UpdateAuthRootVersion();
  824. RefreshWatch();
  825. }
  826. return auth_root_version_;
  827. }
  828. void AuthRootVersionChecker::RefreshWatch() {
  829. // If the registry is corrupted, don't bother.
  830. if (!key_.Valid())
  831. return;
  832. if (base::win::GetVersion() < base::win::Version::WIN8) {
  833. // On Windows 7 and earlier, using RegNotifyChangeKeyValue from a worker
  834. // thread will abandon the notification if that thread ends. Rather than
  835. // marshalling to a persistent thread, on these versions, `ShouldUpdate()`
  836. // just takes a less-optimized path.
  837. return;
  838. }
  839. // On Windows 8 or later, any thread can monitor the registry for changes,
  840. // and monitoring is not abandoned if the thread ends.
  841. DWORD flags = REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
  842. RegNotifyChangeKeyValue(key_.Handle(), FALSE, flags, event_.Get(), TRUE);
  843. }
  844. bool AuthRootVersionChecker::ShouldUpdate() {
  845. lock_.AssertAcquired();
  846. // If the registry is corrupted, don't bother.
  847. if (!key_.Valid())
  848. return false;
  849. if (base::win::GetVersion() >= base::win::Version::WIN8) {
  850. // On Win 8+, just check if the event is signaled.
  851. return WaitForSingleObject(event_.Get(), 0) == WAIT_OBJECT_0;
  852. }
  853. // On Win 7 and earlier, check the last modification time of the registry.
  854. // This is less efficient than using the event, but a simpler implementation
  855. // than needing to marshal RegNotifyChangeKeyValue to a persistent thread.
  856. FILETIME current_timestamp = {0, 0};
  857. LSTATUS result = RegQueryInfoKeyW(key_.Handle(), nullptr, nullptr, nullptr,
  858. nullptr, nullptr, nullptr, nullptr, nullptr,
  859. nullptr, nullptr, &current_timestamp);
  860. // If for some reason things failed, rather than constantly querying the
  861. // registry every time, fail closed and just use the stale value.
  862. if (result != ERROR_SUCCESS)
  863. return false;
  864. base::Time update_time = base::Time::FromFileTime(current_timestamp);
  865. if (update_time > last_update_) {
  866. last_update_ = update_time;
  867. return true;
  868. }
  869. return false;
  870. }
  871. void AuthRootVersionChecker::UpdateAuthRootVersion() {
  872. lock_.AssertAcquired();
  873. if (!key_.Valid())
  874. return;
  875. constexpr wchar_t kCtlValueName[] = L"EncodedCtl";
  876. DWORD data_type = REG_BINARY;
  877. DWORD value_size = 0;
  878. LONG rv = key_.ReadValue(kCtlValueName, nullptr, &value_size, &data_type);
  879. if (rv != ERROR_SUCCESS || !value_size || data_type != REG_BINARY)
  880. return;
  881. std::vector<uint8_t> value(value_size);
  882. rv = key_.ReadValue(kCtlValueName, value.data(), &value_size, &data_type);
  883. if (rv != ERROR_SUCCESS || value_size == 0 || data_type != REG_BINARY)
  884. return;
  885. value.resize(value_size);
  886. crypto::ScopedPCCTL_CONTEXT ctl_context(
  887. CertCreateCTLContext(PKCS_7_ASN_ENCODING, value.data(), value.size()));
  888. if (!ctl_context || ctl_context->pCtlInfo->SequenceNumber.cbData == 0)
  889. return;
  890. auth_root_version_.sequence_number.assign(
  891. ctl_context->pCtlInfo->SequenceNumber.pbData,
  892. ctl_context->pCtlInfo->SequenceNumber.pbData +
  893. ctl_context->pCtlInfo->SequenceNumber.cbData);
  894. // Convert from Windows' little-endian representation to the expected (as
  895. // encoded) big-endian form.
  896. std::reverse(std::begin(auth_root_version_.sequence_number),
  897. std::end(auth_root_version_.sequence_number));
  898. auth_root_version_.this_update =
  899. base::Time::FromFileTime(ctl_context->pCtlInfo->ThisUpdate);
  900. }
  901. } // namespace
  902. CertVerifyProcWin::ResultDebugData::ResultDebugData(
  903. base::Time authroot_this_update,
  904. std::vector<uint8_t> authroot_sequence_number)
  905. : authroot_this_update_(authroot_this_update),
  906. authroot_sequence_number_(std::move(authroot_sequence_number)) {}
  907. CertVerifyProcWin::ResultDebugData::ResultDebugData(
  908. const ResultDebugData& other) = default;
  909. CertVerifyProcWin::ResultDebugData::~ResultDebugData() = default;
  910. // static
  911. const CertVerifyProcWin::ResultDebugData*
  912. CertVerifyProcWin::ResultDebugData::Get(
  913. const base::SupportsUserData* debug_data) {
  914. return static_cast<ResultDebugData*>(
  915. debug_data->GetUserData(kResultDebugDataKey));
  916. }
  917. // static
  918. void CertVerifyProcWin::ResultDebugData::Create(
  919. base::Time authroot_this_update,
  920. std::vector<uint8_t> authroot_sequence_number,
  921. base::SupportsUserData* debug_data) {
  922. debug_data->SetUserData(
  923. kResultDebugDataKey,
  924. std::make_unique<ResultDebugData>(authroot_this_update,
  925. std::move(authroot_sequence_number)));
  926. }
  927. std::unique_ptr<base::SupportsUserData::Data>
  928. CertVerifyProcWin::ResultDebugData::Clone() {
  929. return std::make_unique<ResultDebugData>(*this);
  930. }
  931. CertVerifyProcWin::CertVerifyProcWin() = default;
  932. CertVerifyProcWin::~CertVerifyProcWin() = default;
  933. bool CertVerifyProcWin::SupportsAdditionalTrustAnchors() const {
  934. return false;
  935. }
  936. int CertVerifyProcWin::VerifyInternal(
  937. X509Certificate* cert,
  938. const std::string& hostname,
  939. const std::string& ocsp_response,
  940. const std::string& sct_list,
  941. int flags,
  942. CRLSet* crl_set,
  943. const CertificateList& additional_trust_anchors,
  944. CertVerifyResult* verify_result,
  945. const NetLogWithSource& net_log) {
  946. // Ensure the Revocation Provider has been installed and configured for this
  947. // CRLSet.
  948. ScopedThreadLocalCRLSet thread_local_crlset(crl_set);
  949. crypto::ScopedPCCERT_CONTEXT cert_list =
  950. x509_util::CreateCertContextWithChain(
  951. cert, x509_util::InvalidIntermediateBehavior::kIgnore);
  952. if (!cert_list) {
  953. verify_result->cert_status |= CERT_STATUS_INVALID;
  954. return ERR_CERT_INVALID;
  955. }
  956. // Build and validate certificate chain.
  957. CERT_CHAIN_PARA chain_para;
  958. memset(&chain_para, 0, sizeof(chain_para));
  959. chain_para.cbSize = sizeof(chain_para);
  960. // ExtendedKeyUsage.
  961. // We still need to request szOID_SERVER_GATED_CRYPTO and szOID_SGC_NETSCAPE
  962. // today because some certificate chains need them. IE also requests these
  963. // two usages.
  964. static const LPCSTR usage[] = {
  965. szOID_PKIX_KP_SERVER_AUTH,
  966. szOID_SERVER_GATED_CRYPTO,
  967. szOID_SGC_NETSCAPE
  968. };
  969. chain_para.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
  970. chain_para.RequestedUsage.Usage.cUsageIdentifier = std::size(usage);
  971. chain_para.RequestedUsage.Usage.rgpszUsageIdentifier =
  972. const_cast<LPSTR*>(usage);
  973. // Get the certificatePolicies extension of the certificate.
  974. std::unique_ptr<CERT_POLICIES_INFO, base::FreeDeleter> policies_info;
  975. LPSTR ev_policy_oid = nullptr;
  976. GetCertPoliciesInfo(cert_list.get(), &policies_info);
  977. if (policies_info) {
  978. EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
  979. for (DWORD i = 0; i < policies_info->cPolicyInfo; ++i) {
  980. LPSTR policy_oid = policies_info->rgPolicyInfo[i].pszPolicyIdentifier;
  981. if (metadata->IsEVPolicyOID(policy_oid)) {
  982. ev_policy_oid = policy_oid;
  983. chain_para.RequestedIssuancePolicy.dwType = USAGE_MATCH_TYPE_AND;
  984. chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = 1;
  985. chain_para.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier =
  986. &ev_policy_oid;
  987. // De-prioritize the CA/Browser forum Extended Validation policy
  988. // (2.23.140.1.1). See https://crbug.com/705285.
  989. if (!EVRootCAMetadata::IsCaBrowserForumEvOid(ev_policy_oid))
  990. break;
  991. }
  992. }
  993. }
  994. // Revocation checking is always enabled, in order to enable CRLSets to be
  995. // evaluated as part of a revocation provider. However, when the caller did
  996. // not explicitly request revocation checking (which is to say, online
  997. // revocation checking), then only enable cached results. This disables OCSP
  998. // and CRL fetching, but still allows the revocation provider to be called.
  999. // Note: The root cert is also checked for revocation status, so that CRLSets
  1000. // will cover revoked SPKIs.
  1001. DWORD chain_flags = CERT_CHAIN_REVOCATION_CHECK_CHAIN;
  1002. bool rev_checking_enabled = (flags & VERIFY_REV_CHECKING_ENABLED);
  1003. if (rev_checking_enabled) {
  1004. verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
  1005. } else {
  1006. chain_flags |= CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY;
  1007. }
  1008. // By default, use the default HCERTCHAINENGINE (aka HCCE_CURRENT_USER). When
  1009. // running tests, use a dynamic HCERTCHAINENGINE. All of the status and cache
  1010. // of verified certificates and chains is tied to the HCERTCHAINENGINE. As
  1011. // each invocation may have changed the set of known roots, invalidate the
  1012. // cache between runs.
  1013. //
  1014. // This is not the most efficient means of doing so; it's possible to mark the
  1015. // Root store used by TestRootCerts as changed, via CertControlStore with the
  1016. // CERT_STORE_CTRL_NOTIFY_CHANGE / CERT_STORE_CTRL_RESYNC, but that's more
  1017. // complexity for what is test-only code.
  1018. crypto::ScopedHCERTCHAINENGINE chain_engine;
  1019. if (TestRootCerts::HasInstance())
  1020. chain_engine = TestRootCerts::GetInstance()->GetChainEngine();
  1021. // Add stapled OCSP response data, which will be preferred over online checks
  1022. // and used when in cache-only mode.
  1023. if (!ocsp_response.empty()) {
  1024. CRYPT_DATA_BLOB ocsp_response_blob;
  1025. ocsp_response_blob.cbData = base::checked_cast<DWORD>(ocsp_response.size());
  1026. ocsp_response_blob.pbData =
  1027. reinterpret_cast<BYTE*>(const_cast<char*>(ocsp_response.data()));
  1028. CertSetCertificateContextProperty(
  1029. cert_list.get(), CERT_OCSP_RESPONSE_PROP_ID,
  1030. CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG, &ocsp_response_blob);
  1031. }
  1032. CERT_STRONG_SIGN_SERIALIZED_INFO strong_signed_info;
  1033. memset(&strong_signed_info, 0, sizeof(strong_signed_info));
  1034. strong_signed_info.dwFlags = 0; // Don't check OCSP or CRL signatures.
  1035. // Note that the following two configurations result in disabling support for
  1036. // any CNG-added algorithms, which may result in some disruption for internal
  1037. // PKI operations that use national forms of crypto (e.g. GOST). However, the
  1038. // fallback mechanism for this (to support SHA-1 chains) will re-enable them,
  1039. // so they should continue to work - just with added latency.
  1040. wchar_t hash_algs[] =
  1041. L"RSA/SHA256;RSA/SHA384;RSA/SHA512;"
  1042. L"ECDSA/SHA256;ECDSA/SHA384;ECDSA/SHA512";
  1043. strong_signed_info.pwszCNGSignHashAlgids = hash_algs;
  1044. // RSA-1024 bit support is intentionally enabled here. More investigation is
  1045. // needed to determine if setting CERT_STRONG_SIGN_DISABLE_END_CHECK_FLAG in
  1046. // the dwStrongSignFlags of |chain_para| would allow the ability to disable
  1047. // support for intermediates/roots < 2048-bits, while still ensuring that
  1048. // end-entity certs signed with SHA-1 are flagged/rejected.
  1049. wchar_t key_sizes[] = L"RSA/1024;ECDSA/256";
  1050. strong_signed_info.pwszCNGPubKeyMinBitLengths = key_sizes;
  1051. CERT_STRONG_SIGN_PARA strong_sign_params;
  1052. memset(&strong_sign_params, 0, sizeof(strong_sign_params));
  1053. strong_sign_params.cbSize = sizeof(strong_sign_params);
  1054. strong_sign_params.dwInfoChoice = CERT_STRONG_SIGN_SERIALIZED_INFO_CHOICE;
  1055. strong_sign_params.pSerializedInfo = &strong_signed_info;
  1056. chain_para.dwStrongSignFlags = 0;
  1057. chain_para.pStrongSignPara = &strong_sign_params;
  1058. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  1059. // First, try to verify with strong signing enabled. If this fails, or if the
  1060. // chain is rejected, then clear it from |chain_para| so that all subsequent
  1061. // calls will use the fallback path.
  1062. BOOL chain_result =
  1063. CertGetCertificateChain(chain_engine.get(), cert_list.get(),
  1064. nullptr, // current system time
  1065. cert_list->hCertStore, &chain_para, chain_flags,
  1066. nullptr, // reserved
  1067. &chain_context);
  1068. if (chain_result && chain_context &&
  1069. (chain_context->TrustStatus.dwErrorStatus &
  1070. (CERT_TRUST_HAS_WEAK_SIGNATURE | CERT_TRUST_IS_NOT_SIGNATURE_VALID))) {
  1071. // The attempt to verify with strong-sign (only SHA-2) failed, so fall back
  1072. // to disabling it. This will allow SHA-1 chains to be returned, which will
  1073. // then be subsequently signalled as weak if necessary.
  1074. CertFreeCertificateChain(chain_context);
  1075. chain_context = nullptr;
  1076. chain_para.pStrongSignPara = nullptr;
  1077. chain_para.dwStrongSignFlags = 0;
  1078. chain_result =
  1079. CertGetCertificateChain(chain_engine.get(), cert_list.get(),
  1080. nullptr, // current system time
  1081. cert_list->hCertStore, &chain_para, chain_flags,
  1082. nullptr, // reserved
  1083. &chain_context);
  1084. }
  1085. if (!chain_result) {
  1086. verify_result->cert_status |= CERT_STATUS_INVALID;
  1087. return MapSecurityError(GetLastError());
  1088. }
  1089. // Include diagnostics about the current AuthRoot version.
  1090. static base::NoDestructor<AuthRootVersionChecker> authroot_version_checker;
  1091. AuthRootVersionChecker::AuthRootVersion authroot_version =
  1092. authroot_version_checker->GetAuthRootVersion();
  1093. ResultDebugData::Create(std::move(authroot_version.this_update),
  1094. std::move(authroot_version.sequence_number),
  1095. verify_result);
  1096. // Perform a second check with CRLSets. Although the Revocation Provider
  1097. // should have prevented invalid paths from being built, the behaviour and
  1098. // timing of how a Revocation Provider is invoked is not well documented. This
  1099. // is just defense in depth.
  1100. CRLSetResult crl_set_result =
  1101. CheckChainRevocationWithCRLSet(chain_context, crl_set);
  1102. if (crl_set_result == kCRLSetRevoked) {
  1103. verify_result->cert_status |= CERT_STATUS_REVOKED;
  1104. }
  1105. // Even if the cert is possibly EV and crl_set_result == kCRLSetUnknown, we
  1106. // don't check with online revocation checking enabled. See crbug.com/1268848.
  1107. if (chain_context->TrustStatus.dwErrorStatus &
  1108. CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
  1109. // Could not verify the cert with the EV policy. Remove the EV policy and
  1110. // try again.
  1111. ev_policy_oid = nullptr;
  1112. chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = 0;
  1113. chain_para.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = nullptr;
  1114. CertFreeCertificateChain(chain_context);
  1115. if (!CertGetCertificateChain(chain_engine.get(), cert_list.get(),
  1116. nullptr, // current system time
  1117. cert_list->hCertStore, &chain_para,
  1118. chain_flags,
  1119. nullptr, // reserved
  1120. &chain_context)) {
  1121. verify_result->cert_status |= CERT_STATUS_INVALID;
  1122. return MapSecurityError(GetLastError());
  1123. }
  1124. }
  1125. CertVerifyResult temp_verify_result = *verify_result;
  1126. GetCertChainInfo(chain_context, verify_result);
  1127. if (!verify_result->is_issued_by_known_root &&
  1128. (flags & VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS)) {
  1129. *verify_result = temp_verify_result;
  1130. rev_checking_enabled = true;
  1131. verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
  1132. chain_flags &= ~CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY;
  1133. CertFreeCertificateChain(chain_context);
  1134. if (!CertGetCertificateChain(chain_engine.get(), cert_list.get(),
  1135. nullptr, // current system time
  1136. cert_list->hCertStore, &chain_para,
  1137. chain_flags,
  1138. nullptr, // reserved
  1139. &chain_context)) {
  1140. verify_result->cert_status |= CERT_STATUS_INVALID;
  1141. return MapSecurityError(GetLastError());
  1142. }
  1143. GetCertChainInfo(chain_context, verify_result);
  1144. }
  1145. crypto::ScopedPCCERT_CHAIN_CONTEXT scoped_chain_context(chain_context);
  1146. verify_result->cert_status |= MapCertChainErrorStatusToCertStatus(
  1147. chain_context->TrustStatus.dwErrorStatus);
  1148. // Flag certificates that have a Subject common name with a NULL character.
  1149. if (CertSubjectCommonNameHasNull(cert_list.get()))
  1150. verify_result->cert_status |= CERT_STATUS_INVALID;
  1151. std::u16string hostname16 = base::ASCIIToUTF16(hostname);
  1152. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para;
  1153. memset(&extra_policy_para, 0, sizeof(extra_policy_para));
  1154. extra_policy_para.cbSize = sizeof(extra_policy_para);
  1155. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  1156. // Certificate name validation happens separately, later, using an internal
  1157. // routine that has better support for RFC 6125 name matching.
  1158. extra_policy_para.fdwChecks =
  1159. 0x00001000; // SECURITY_FLAG_IGNORE_CERT_CN_INVALID
  1160. extra_policy_para.pwszServerName = base::as_writable_wcstr(hostname16);
  1161. CERT_CHAIN_POLICY_PARA policy_para;
  1162. memset(&policy_para, 0, sizeof(policy_para));
  1163. policy_para.cbSize = sizeof(policy_para);
  1164. policy_para.dwFlags = 0;
  1165. policy_para.pvExtraPolicyPara = &extra_policy_para;
  1166. CERT_CHAIN_POLICY_STATUS policy_status;
  1167. memset(&policy_status, 0, sizeof(policy_status));
  1168. policy_status.cbSize = sizeof(policy_status);
  1169. if (!CertVerifyCertificateChainPolicy(
  1170. CERT_CHAIN_POLICY_SSL,
  1171. chain_context,
  1172. &policy_para,
  1173. &policy_status)) {
  1174. return MapSecurityError(GetLastError());
  1175. }
  1176. if (policy_status.dwError) {
  1177. verify_result->cert_status |= MapNetErrorToCertStatus(
  1178. MapSecurityError(policy_status.dwError));
  1179. }
  1180. // Mask off revocation checking failures unless hard-fail revocation checking
  1181. // for local anchors is enabled and the chain is issued by a local root.
  1182. // (CheckEV will still check chain_context->TrustStatus.dwErrorStatus directly
  1183. // so as to not mark as EV if revocation information was not available.)
  1184. if (!(!verify_result->is_issued_by_known_root &&
  1185. (flags & VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS))) {
  1186. verify_result->cert_status &= ~(CERT_STATUS_NO_REVOCATION_MECHANISM |
  1187. CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
  1188. }
  1189. AppendPublicKeyHashesAndUpdateKnownRoot(
  1190. chain_context, &verify_result->public_key_hashes,
  1191. &verify_result->is_issued_by_known_root);
  1192. if (IsCertStatusError(verify_result->cert_status))
  1193. return MapCertStatusToNetError(verify_result->cert_status);
  1194. if (ev_policy_oid &&
  1195. CheckEV(chain_context, rev_checking_enabled, ev_policy_oid)) {
  1196. verify_result->cert_status |= CERT_STATUS_IS_EV;
  1197. }
  1198. LogNameNormalizationMetrics(".Win", verify_result->verified_cert.get(),
  1199. verify_result->is_issued_by_known_root);
  1200. return OK;
  1201. }
  1202. } // namespace net