Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(72)

Side by Side Diff: net/cert/known_roots_win.cc

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

Powered by Google App Engine
This is Rietveld 408576698