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