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.h"
6 
7 #include <stdint.h>
8 
9 #include <algorithm>
10 
11 #include "base/containers/span.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/histogram_functions.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/threading/scoped_blocking_call.h"
19 #include "base/time/time.h"
20 #include "crypto/sha2.h"
21 #include "net/base/features.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
24 #include "net/base/url_util.h"
25 #include "net/cert/asn1_util.h"
26 #include "net/cert/cert_net_fetcher.h"
27 #include "net/cert/cert_status_flags.h"
28 #include "net/cert/cert_verifier.h"
29 #include "net/cert/cert_verify_result.h"
30 #include "net/cert/crl_set.h"
31 #include "net/cert/internal/ocsp.h"
32 #include "net/cert/internal/parse_certificate.h"
33 #include "net/cert/internal/revocation_checker.h"
34 #include "net/cert/internal/signature_algorithm.h"
35 #include "net/cert/known_roots.h"
36 #include "net/cert/ocsp_revocation_status.h"
37 #include "net/cert/pem.h"
38 #include "net/cert/symantec_certs.h"
39 #include "net/cert/x509_certificate.h"
40 #include "net/cert/x509_certificate_net_log_param.h"
41 #include "net/cert/x509_util.h"
42 #include "net/der/encode_values.h"
43 #include "net/log/net_log_event_type.h"
44 #include "net/log/net_log_values.h"
45 #include "net/log/net_log_with_source.h"
46 #include "net/net_buildflags.h"
47 #include "third_party/boringssl/src/include/openssl/pool.h"
48 #include "url/url_canon.h"
49 
50 #if defined(OS_FUCHSIA) || defined(USE_NSS_CERTS) || defined(OS_MAC)
51 #include "net/cert/cert_verify_proc_builtin.h"
52 #endif
53 
54 #if defined(OS_ANDROID)
55 #include "net/cert/cert_verify_proc_android.h"
56 #elif defined(OS_IOS)
57 #include "net/cert/cert_verify_proc_ios.h"
58 #elif defined(OS_MAC)
59 #include "net/cert/cert_verify_proc_mac.h"
60 #elif defined(OS_WIN)
61 #include "base/win/windows_version.h"
62 #include "net/cert/cert_verify_proc_win.h"
63 #endif
64 
65 namespace net {
66 
67 namespace {
68 
69 // Constants used to build histogram names
70 const char kLeafCert[] = "Leaf";
71 const char kIntermediateCert[] = "Intermediate";
72 const char kRootCert[] = "Root";
73 
74 // Histogram buckets for RSA/DSA/DH key sizes.
75 const int kRsaDsaKeySizes[] = {512, 768, 1024, 1536, 2048, 3072, 4096, 8192,
76                                16384};
77 // Histogram buckets for ECDSA/ECDH key sizes. The list is based upon the FIPS
78 // 186-4 approved curves.
79 const int kEccKeySizes[] = {163, 192, 224, 233, 256, 283, 384, 409, 521, 571};
80 
CertTypeToString(X509Certificate::PublicKeyType cert_type)81 const char* CertTypeToString(X509Certificate::PublicKeyType cert_type) {
82   switch (cert_type) {
83     case X509Certificate::kPublicKeyTypeUnknown:
84       return "Unknown";
85     case X509Certificate::kPublicKeyTypeRSA:
86       return "RSA";
87     case X509Certificate::kPublicKeyTypeDSA:
88       return "DSA";
89     case X509Certificate::kPublicKeyTypeECDSA:
90       return "ECDSA";
91     case X509Certificate::kPublicKeyTypeDH:
92       return "DH";
93     case X509Certificate::kPublicKeyTypeECDH:
94       return "ECDH";
95   }
96   NOTREACHED();
97   return "Unsupported";
98 }
99 
RecordPublicKeyHistogram(const char * chain_position,bool baseline_keysize_applies,size_t size_bits,X509Certificate::PublicKeyType cert_type)100 void RecordPublicKeyHistogram(const char* chain_position,
101                               bool baseline_keysize_applies,
102                               size_t size_bits,
103                               X509Certificate::PublicKeyType cert_type) {
104   std::string histogram_name =
105       base::StringPrintf("CertificateType2.%s.%s.%s",
106                          baseline_keysize_applies ? "BR" : "NonBR",
107                          chain_position,
108                          CertTypeToString(cert_type));
109   // Do not use UMA_HISTOGRAM_... macros here, as it caches the Histogram
110   // instance and thus only works if |histogram_name| is constant.
111   base::HistogramBase* counter = nullptr;
112 
113   // Histogram buckets are contingent upon the underlying algorithm being used.
114   if (cert_type == X509Certificate::kPublicKeyTypeECDH ||
115       cert_type == X509Certificate::kPublicKeyTypeECDSA) {
116     // Typical key sizes match SECP/FIPS 186-3 recommendations for prime and
117     // binary curves - which range from 163 bits to 571 bits.
118     counter = base::CustomHistogram::FactoryGet(
119         histogram_name,
120         base::CustomHistogram::ArrayToCustomEnumRanges(kEccKeySizes),
121         base::HistogramBase::kUmaTargetedHistogramFlag);
122   } else {
123     // Key sizes < 1024 bits should cause errors, while key sizes > 16K are not
124     // uniformly supported by the underlying cryptographic libraries.
125     counter = base::CustomHistogram::FactoryGet(
126         histogram_name,
127         base::CustomHistogram::ArrayToCustomEnumRanges(kRsaDsaKeySizes),
128         base::HistogramBase::kUmaTargetedHistogramFlag);
129   }
130   counter->Add(size_bits);
131 }
132 
133 // Returns true if |type| is |kPublicKeyTypeRSA| or |kPublicKeyTypeDSA|, and
134 // if |size_bits| is < 1024. Note that this means there may be false
135 // negatives: keys for other algorithms and which are weak will pass this
136 // test.
IsWeakKey(X509Certificate::PublicKeyType type,size_t size_bits)137 bool IsWeakKey(X509Certificate::PublicKeyType type, size_t size_bits) {
138   switch (type) {
139     case X509Certificate::kPublicKeyTypeRSA:
140     case X509Certificate::kPublicKeyTypeDSA:
141       return size_bits < 1024;
142     default:
143       return false;
144   }
145 }
146 
147 // Returns true if |cert| contains a known-weak key. Additionally, histograms
148 // the observed keys for future tightening of the definition of what
149 // constitutes a weak key.
ExaminePublicKeys(const scoped_refptr<X509Certificate> & cert,bool should_histogram)150 bool ExaminePublicKeys(const scoped_refptr<X509Certificate>& cert,
151                        bool should_histogram) {
152   // The effective date of the CA/Browser Forum's Baseline Requirements -
153   // 2012-07-01 00:00:00 UTC.
154   const base::Time kBaselineEffectiveDate =
155       base::Time::FromInternalValue(INT64_C(12985574400000000));
156   // The effective date of the key size requirements from Appendix A, v1.1.5
157   // 2014-01-01 00:00:00 UTC.
158   const base::Time kBaselineKeysizeEffectiveDate =
159       base::Time::FromInternalValue(INT64_C(13033008000000000));
160 
161   size_t size_bits = 0;
162   X509Certificate::PublicKeyType type = X509Certificate::kPublicKeyTypeUnknown;
163   bool weak_key = false;
164   bool baseline_keysize_applies =
165       cert->valid_start() >= kBaselineEffectiveDate &&
166       cert->valid_expiry() >= kBaselineKeysizeEffectiveDate;
167 
168   X509Certificate::GetPublicKeyInfo(cert->cert_buffer(), &size_bits, &type);
169   if (should_histogram) {
170     RecordPublicKeyHistogram(kLeafCert, baseline_keysize_applies, size_bits,
171                              type);
172   }
173   if (IsWeakKey(type, size_bits))
174     weak_key = true;
175 
176   const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediates =
177       cert->intermediate_buffers();
178   for (size_t i = 0; i < intermediates.size(); ++i) {
179     X509Certificate::GetPublicKeyInfo(intermediates[i].get(), &size_bits,
180                                       &type);
181     if (should_histogram) {
182       RecordPublicKeyHistogram(
183           (i < intermediates.size() - 1) ? kIntermediateCert : kRootCert,
184           baseline_keysize_applies,
185           size_bits,
186           type);
187     }
188     if (!weak_key && IsWeakKey(type, size_bits))
189       weak_key = true;
190   }
191 
192   return weak_key;
193 }
194 
195 // See
196 // https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html
197 // for more details.
IsUntrustedSymantecCert(const X509Certificate & cert)198 bool IsUntrustedSymantecCert(const X509Certificate& cert) {
199   const base::Time& start = cert.valid_start();
200   if (start.is_max() || start.is_null())
201     return true;
202 
203   // Certificates issued on/after 2017-12-01 00:00:00 UTC are no longer
204   // trusted.
205   const base::Time kSymantecDeprecationDate =
206       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1512086400);
207   if (start >= kSymantecDeprecationDate)
208     return true;
209 
210   // Certificates issued prior to 2016-06-01 00:00:00 UTC are no longer
211   // trusted.
212   const base::Time kFirstAcceptedCertDate =
213       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1464739200);
214   if (start < kFirstAcceptedCertDate)
215     return true;
216 
217   return false;
218 }
219 
BestEffortCheckOCSP(const std::string & raw_response,const X509Certificate & certificate,OCSPVerifyResult * verify_result)220 void BestEffortCheckOCSP(const std::string& raw_response,
221                          const X509Certificate& certificate,
222                          OCSPVerifyResult* verify_result) {
223   if (raw_response.empty()) {
224     *verify_result = OCSPVerifyResult();
225     verify_result->response_status = OCSPVerifyResult::MISSING;
226     return;
227   }
228 
229   base::StringPiece cert_der =
230       x509_util::CryptoBufferAsStringPiece(certificate.cert_buffer());
231 
232   // Try to get the certificate that signed |certificate|. This will run into
233   // problems if the CertVerifyProc implementation doesn't return the ordered
234   // certificates. If that happens the OCSP verification may be incorrect.
235   base::StringPiece issuer_der;
236   if (certificate.intermediate_buffers().empty()) {
237     if (X509Certificate::IsSelfSigned(certificate.cert_buffer())) {
238       issuer_der = cert_der;
239     } else {
240       // A valid cert chain wasn't provided.
241       *verify_result = OCSPVerifyResult();
242       return;
243     }
244   } else {
245     issuer_der = x509_util::CryptoBufferAsStringPiece(
246         certificate.intermediate_buffers().front().get());
247   }
248 
249   verify_result->revocation_status =
250       CheckOCSP(raw_response, cert_der, issuer_der, base::Time::Now(),
251                 kMaxRevocationLeafUpdateAge, &verify_result->response_status);
252 }
253 
254 // Records histograms indicating whether the certificate |cert|, which
255 // is assumed to have been validated chaining to a private root,
256 // contains the TLS Feature Extension (https://tools.ietf.org/html/rfc7633) and
257 // has valid OCSP information stapled.
RecordTLSFeatureExtensionWithPrivateRoot(X509Certificate * cert,const OCSPVerifyResult & ocsp_result)258 void RecordTLSFeatureExtensionWithPrivateRoot(
259     X509Certificate* cert,
260     const OCSPVerifyResult& ocsp_result) {
261   // This checks only for the presence of the TLS Feature Extension, but
262   // does not check the feature list, and in particular does not verify that
263   // its value is 'status_request' or 'status_request2'. In practice the
264   // only use of the TLS feature extension is for OCSP stapling, so
265   // don't bother to check the value.
266   bool has_extension = asn1::HasTLSFeatureExtension(
267       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()));
268 
269   UMA_HISTOGRAM_BOOLEAN("Net.Certificate.TLSFeatureExtensionWithPrivateRoot",
270                         has_extension);
271   if (!has_extension)
272     return;
273 
274   UMA_HISTOGRAM_BOOLEAN(
275       "Net.Certificate.TLSFeatureExtensionWithPrivateRootHasOCSP",
276       (ocsp_result.response_status != OCSPVerifyResult::MISSING));
277 }
278 
279 // Records details about the most-specific trust anchor in |hashes|, which is
280 // expected to be ordered with the leaf cert first and the root cert last.
281 // "Most-specific" refers to the case that it is not uncommon to have multiple
282 // potential trust anchors present in a chain, depending on the client trust
283 // store. For example, '1999-Root' cross-signing '2005-Root' cross-signing
284 // '2012-Root' cross-signing '2017-Root', then followed by intermediate and
285 // leaf. For purposes of assessing impact of, say, removing 1999-Root, while
286 // including 2017-Root as a trust anchor, then the validation should be
287 // counted as 2017-Root, rather than 1999-Root.
288 //
289 // This also accounts for situations in which a new CA is introduced, and
290 // has been cross-signed by an existing CA. Assessing impact should use the
291 // most-specific trust anchor, when possible.
292 //
293 // This also histograms for divergence between the root store and
294 // |spki_hashes| - that is, situations in which the OS methods of detecting
295 // a known root flag a certificate as known, but its hash is not known as part
296 // of the built-in list.
RecordTrustAnchorHistogram(const HashValueVector & spki_hashes,bool is_issued_by_known_root)297 void RecordTrustAnchorHistogram(const HashValueVector& spki_hashes,
298                                 bool is_issued_by_known_root) {
299   int32_t id = 0;
300   for (const auto& hash : spki_hashes) {
301     id = GetNetTrustAnchorHistogramIdForSPKI(hash);
302     if (id != 0)
303       break;
304   }
305   base::UmaHistogramSparse("Net.Certificate.TrustAnchor.Verify", id);
306 
307   // Record when a known trust anchor is not found within the chain, but the
308   // certificate is flagged as being from a known root (meaning a fallback to
309   // OS-based methods of determination).
310   if (id == 0) {
311     UMA_HISTOGRAM_BOOLEAN("Net.Certificate.TrustAnchor.VerifyOutOfDate",
312                           is_issued_by_known_root);
313   }
314 }
315 
AreSHA1IntermediatesAllowed()316 bool AreSHA1IntermediatesAllowed() {
317 #if defined(OS_WIN)
318   // TODO(rsleevi): Remove this once https://crbug.com/588789 is resolved
319   // for Windows 7/2008 users.
320   // Note: This must be kept in sync with cert_verify_proc_unittest.cc
321   return base::win::GetVersion() < base::win::Version::WIN8;
322 #else
323   return false;
324 #endif
325 }
326 
327 // Sets the "has_*" boolean members in |verify_result| that correspond with
328 // the the presence of |hash| somewhere in the certificate chain (excluding the
329 // trust anchor).
MapAlgorithmToBool(DigestAlgorithm hash,CertVerifyResult * verify_result)330 void MapAlgorithmToBool(DigestAlgorithm hash, CertVerifyResult* verify_result) {
331   switch (hash) {
332     case DigestAlgorithm::Md2:
333       verify_result->has_md2 = true;
334       break;
335     case DigestAlgorithm::Md4:
336       verify_result->has_md4 = true;
337       break;
338     case DigestAlgorithm::Md5:
339       verify_result->has_md5 = true;
340       break;
341     case DigestAlgorithm::Sha1:
342       verify_result->has_sha1 = true;
343       break;
344     case DigestAlgorithm::Sha256:
345     case DigestAlgorithm::Sha384:
346     case DigestAlgorithm::Sha512:
347       break;
348   }
349 }
350 
351 // Inspects the signature algorithms in a single certificate |cert|.
352 //
353 //   * Sets |verify_result->has_md2| to true if the certificate uses MD2.
354 //   * Sets |verify_result->has_md4| to true if the certificate uses MD4.
355 //   * Sets |verify_result->has_md5| to true if the certificate uses MD5.
356 //   * Sets |verify_result->has_sha1| to true if the certificate uses SHA1.
357 //
358 // Returns false if the signature algorithm was unknown or mismatched.
InspectSignatureAlgorithmForCert(const CRYPTO_BUFFER * cert,CertVerifyResult * verify_result)359 WARN_UNUSED_RESULT bool InspectSignatureAlgorithmForCert(
360     const CRYPTO_BUFFER* cert,
361     CertVerifyResult* verify_result) {
362   base::StringPiece cert_algorithm_sequence;
363   base::StringPiece tbs_algorithm_sequence;
364 
365   // Extract the AlgorithmIdentifier SEQUENCEs
366   if (!asn1::ExtractSignatureAlgorithmsFromDERCert(
367           x509_util::CryptoBufferAsStringPiece(cert), &cert_algorithm_sequence,
368           &tbs_algorithm_sequence)) {
369     return false;
370   }
371 
372   if (!SignatureAlgorithm::IsEquivalent(der::Input(cert_algorithm_sequence),
373                                         der::Input(tbs_algorithm_sequence))) {
374     return false;
375   }
376 
377   std::unique_ptr<SignatureAlgorithm> algorithm =
378       SignatureAlgorithm::Create(der::Input(cert_algorithm_sequence), nullptr);
379   if (!algorithm)
380     return false;
381 
382   MapAlgorithmToBool(algorithm->digest(), verify_result);
383 
384   // Check algorithm-specific parameters.
385   switch (algorithm->algorithm()) {
386     case SignatureAlgorithmId::Dsa:
387     case SignatureAlgorithmId::RsaPkcs1:
388     case SignatureAlgorithmId::Ecdsa:
389       DCHECK(!algorithm->has_params());
390       break;
391     case SignatureAlgorithmId::RsaPss:
392       MapAlgorithmToBool(algorithm->ParamsForRsaPss()->mgf1_hash(),
393                          verify_result);
394       break;
395   }
396 
397   return true;
398 }
399 
400 // InspectSignatureAlgorithmsInChain() sets |verify_result->has_*| based on
401 // the signature algorithms used in the chain, and also checks that certificates
402 // don't have contradictory signature algorithms.
403 //
404 // Returns false if any signature algorithm in the chain is unknown or
405 // mismatched.
406 //
407 // Background:
408 //
409 // X.509 certificates contain two redundant descriptors for the signature
410 // algorithm; one is covered by the signature, but in order to verify the
411 // signature, the other signature algorithm is untrusted.
412 //
413 // RFC 5280 states that the two should be equal, in order to mitigate risk of
414 // signature substitution attacks, but also discourages verifiers from enforcing
415 // the profile of RFC 5280.
416 //
417 // System verifiers are inconsistent - some use the unsigned signature, some use
418 // the signed signature, and they generally do not enforce that both match. This
419 // creates confusion, as it's possible that the signature itself may be checked
420 // using algorithm A, but if subsequent consumers report the certificate
421 // algorithm, they may end up reporting algorithm B, which was not used to
422 // verify the certificate. This function enforces that the two signatures match
423 // in order to prevent such confusion.
InspectSignatureAlgorithmsInChain(CertVerifyResult * verify_result)424 WARN_UNUSED_RESULT bool InspectSignatureAlgorithmsInChain(
425     CertVerifyResult* verify_result) {
426   const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediates =
427       verify_result->verified_cert->intermediate_buffers();
428 
429   // If there are no intermediates, then the leaf is trusted or verification
430   // failed.
431   if (intermediates.empty())
432     return true;
433 
434   DCHECK(!verify_result->has_sha1);
435 
436   // Fill in hash algorithms for the leaf certificate.
437   if (!InspectSignatureAlgorithmForCert(
438           verify_result->verified_cert->cert_buffer(), verify_result)) {
439     return false;
440   }
441 
442   verify_result->has_sha1_leaf = verify_result->has_sha1;
443 
444   // Fill in hash algorithms for the intermediate cerificates, excluding the
445   // final one (which is presumably the trust anchor; may be incorrect for
446   // partial chains).
447   for (size_t i = 0; i + 1 < intermediates.size(); ++i) {
448     if (!InspectSignatureAlgorithmForCert(intermediates[i].get(),
449                                           verify_result))
450       return false;
451   }
452 
453   return true;
454 }
455 
CertVerifyParams(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)456 base::Value CertVerifyParams(X509Certificate* cert,
457                              const std::string& hostname,
458                              const std::string& ocsp_response,
459                              const std::string& sct_list,
460                              int flags,
461                              CRLSet* crl_set,
462                              const CertificateList& additional_trust_anchors) {
463   base::Value dict(base::Value::Type::DICTIONARY);
464   dict.SetKey("certificates", NetLogX509CertificateList(cert));
465   if (!ocsp_response.empty()) {
466     dict.SetStringKey("ocsp_response",
467                       PEMEncode(ocsp_response, "NETLOG OCSP RESPONSE"));
468   }
469   if (!sct_list.empty()) {
470     dict.SetStringKey("sct_list", PEMEncode(sct_list, "NETLOG SCT LIST"));
471   }
472   dict.SetKey("host", NetLogStringValue(hostname));
473   dict.SetIntKey("verify_flags", flags);
474   dict.SetKey("crlset_sequence", NetLogNumberValue(crl_set->sequence()));
475   if (crl_set->IsExpired())
476     dict.SetBoolKey("crlset_is_expired", true);
477 
478   if (!additional_trust_anchors.empty()) {
479     base::Value certs(base::Value::Type::LIST);
480     for (auto& cert : additional_trust_anchors) {
481       std::string pem_encoded;
482       if (X509Certificate::GetPEMEncodedFromDER(
483               x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()),
484               &pem_encoded)) {
485         certs.Append(std::move(pem_encoded));
486       }
487     }
488     dict.SetKey("additional_trust_anchors", std::move(certs));
489   }
490 
491   return dict;
492 }
493 
494 }  // namespace
495 
496 #if !(defined(OS_FUCHSIA) || defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD))
497 // static
CreateSystemVerifyProc(scoped_refptr<CertNetFetcher> cert_net_fetcher)498 scoped_refptr<CertVerifyProc> CertVerifyProc::CreateSystemVerifyProc(
499     scoped_refptr<CertNetFetcher> cert_net_fetcher) {
500 #if defined(OS_ANDROID)
501   return new CertVerifyProcAndroid(std::move(cert_net_fetcher));
502 #elif defined(OS_IOS)
503   return new CertVerifyProcIOS();
504 #elif defined(OS_MAC)
505   return new CertVerifyProcMac();
506 #elif defined(OS_WIN)
507   return new CertVerifyProcWin();
508 #else
509 #error Unsupported platform
510 #endif
511 }
512 #endif
513 
514 #if defined(OS_FUCHSIA) || defined(USE_NSS_CERTS) || defined(OS_MAC)
515 // static
CreateBuiltinVerifyProc(scoped_refptr<CertNetFetcher> cert_net_fetcher)516 scoped_refptr<CertVerifyProc> CertVerifyProc::CreateBuiltinVerifyProc(
517     scoped_refptr<CertNetFetcher> cert_net_fetcher) {
518   return CreateCertVerifyProcBuiltin(
519       std::move(cert_net_fetcher),
520       SystemTrustStoreProvider::CreateDefaultForSSL());
521 }
522 #endif
523 
CertVerifyProc()524 CertVerifyProc::CertVerifyProc() {}
525 
526 CertVerifyProc::~CertVerifyProc() = default;
527 
Verify(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)528 int CertVerifyProc::Verify(X509Certificate* cert,
529                            const std::string& hostname,
530                            const std::string& ocsp_response,
531                            const std::string& sct_list,
532                            int flags,
533                            CRLSet* crl_set,
534                            const CertificateList& additional_trust_anchors,
535                            CertVerifyResult* verify_result,
536                            const NetLogWithSource& net_log) {
537   net_log.BeginEvent(NetLogEventType::CERT_VERIFY_PROC, [&] {
538     return CertVerifyParams(cert, hostname, ocsp_response, sct_list, flags,
539                             crl_set, additional_trust_anchors);
540   });
541   // CertVerifyProc's contract allows ::VerifyInternal() to wait on File I/O
542   // (such as the Windows registry or smart cards on all platforms) or may re-
543   // enter this code via extension hooks (such as smart card UI). To ensure
544   // threads are not starved or deadlocked, the base::ScopedBlockingCall below
545   // increments the thread pool capacity when this method takes too much time to
546   // run.
547   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
548                                                 base::BlockingType::MAY_BLOCK);
549 
550   verify_result->Reset();
551   verify_result->verified_cert = cert;
552 
553   DCHECK(crl_set);
554   int rv =
555       VerifyInternal(cert, hostname, ocsp_response, sct_list, flags, crl_set,
556                      additional_trust_anchors, verify_result, net_log);
557 
558   // Check for mismatched signature algorithms and unknown signature algorithms
559   // in the chain. Also fills in the has_* booleans for the digest algorithms
560   // present in the chain.
561   if (!InspectSignatureAlgorithmsInChain(verify_result)) {
562     verify_result->cert_status |= CERT_STATUS_INVALID;
563     rv = MapCertStatusToNetError(verify_result->cert_status);
564   }
565 
566   if (!cert->VerifyNameMatch(hostname)) {
567     verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
568     rv = MapCertStatusToNetError(verify_result->cert_status);
569   }
570 
571   if (verify_result->ocsp_result.response_status ==
572       OCSPVerifyResult::NOT_CHECKED) {
573     // If VerifyInternal did not record the result of checking stapled OCSP,
574     // do it now.
575     BestEffortCheckOCSP(ocsp_response, *verify_result->verified_cert,
576                         &verify_result->ocsp_result);
577   }
578 
579   // Check to see if the connection is being intercepted.
580   if (crl_set) {
581     for (const auto& hash : verify_result->public_key_hashes) {
582       if (hash.tag() != HASH_VALUE_SHA256)
583         continue;
584       if (!crl_set->IsKnownInterceptionKey(base::StringPiece(
585               reinterpret_cast<const char*>(hash.data()), hash.size())))
586         continue;
587 
588       if (verify_result->cert_status & CERT_STATUS_REVOKED) {
589         // If the chain was revoked, and a known MITM was present, signal that
590         // with a more meaningful error message.
591         verify_result->cert_status |= CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED;
592         rv = MapCertStatusToNetError(verify_result->cert_status);
593       } else {
594         // Otherwise, simply signal informatively. Both statuses are not set
595         // simultaneously.
596         verify_result->cert_status |= CERT_STATUS_KNOWN_INTERCEPTION_DETECTED;
597       }
598       break;
599     }
600   }
601 
602   std::vector<std::string> dns_names, ip_addrs;
603   cert->GetSubjectAltName(&dns_names, &ip_addrs);
604   if (HasNameConstraintsViolation(verify_result->public_key_hashes,
605                                   cert->subject().common_name,
606                                   dns_names,
607                                   ip_addrs)) {
608     verify_result->cert_status |= CERT_STATUS_NAME_CONSTRAINT_VIOLATION;
609     rv = MapCertStatusToNetError(verify_result->cert_status);
610   }
611 
612   // Check for weak keys in the entire verified chain.
613   bool weak_key = ExaminePublicKeys(verify_result->verified_cert,
614                                     verify_result->is_issued_by_known_root);
615 
616   if (weak_key) {
617     verify_result->cert_status |= CERT_STATUS_WEAK_KEY;
618     // Avoid replacing a more serious error, such as an OS/library failure,
619     // by ensuring that if verification failed, it failed with a certificate
620     // error.
621     if (rv == OK || IsCertificateError(rv))
622       rv = MapCertStatusToNetError(verify_result->cert_status);
623   }
624 
625   // Treat certificates signed using broken signature algorithms as invalid.
626   if (verify_result->has_md2 || verify_result->has_md4) {
627     verify_result->cert_status |= CERT_STATUS_INVALID;
628     rv = MapCertStatusToNetError(verify_result->cert_status);
629   }
630 
631   if (verify_result->has_sha1)
632     verify_result->cert_status |= CERT_STATUS_SHA1_SIGNATURE_PRESENT;
633 
634   // Flag certificates using weak signature algorithms.
635 
636   // Current SHA-1 behaviour:
637   // - Reject all SHA-1
638   // - ... unless it's not publicly trusted and SHA-1 is allowed
639   // - ... or SHA-1 is in the intermediate and SHA-1 intermediates are
640   //   allowed for that platform. See https://crbug.com/588789
641   bool current_sha1_issue =
642       (verify_result->is_issued_by_known_root ||
643        !(flags & VERIFY_ENABLE_SHA1_LOCAL_ANCHORS)) &&
644       (verify_result->has_sha1_leaf ||
645        (verify_result->has_sha1 && !AreSHA1IntermediatesAllowed()));
646 
647   if (verify_result->has_md5 || current_sha1_issue) {
648     verify_result->cert_status |= CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;
649     // Avoid replacing a more serious error, such as an OS/library failure,
650     // by ensuring that if verification failed, it failed with a certificate
651     // error.
652     if (rv == OK || IsCertificateError(rv))
653       rv = MapCertStatusToNetError(verify_result->cert_status);
654   }
655 
656   // Distrust Symantec-issued certificates, as described at
657   // https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html
658   if (!(flags & VERIFY_DISABLE_SYMANTEC_ENFORCEMENT) &&
659       IsLegacySymantecCert(verify_result->public_key_hashes)) {
660     if (base::FeatureList::IsEnabled(kLegacySymantecPKIEnforcement) ||
661         IsUntrustedSymantecCert(*verify_result->verified_cert)) {
662       verify_result->cert_status |= CERT_STATUS_SYMANTEC_LEGACY;
663       if (rv == OK || IsCertificateError(rv))
664         rv = MapCertStatusToNetError(verify_result->cert_status);
665     }
666   }
667 
668   // Flag certificates from publicly-trusted CAs that are issued to intranet
669   // hosts. While the CA/Browser Forum Baseline Requirements (v1.1) permit
670   // these to be issued until 1 November 2015, they represent a real risk for
671   // the deployment of gTLDs and are being phased out ahead of the hard
672   // deadline.
673   if (verify_result->is_issued_by_known_root && IsHostnameNonUnique(hostname)) {
674     verify_result->cert_status |= CERT_STATUS_NON_UNIQUE_NAME;
675     // CERT_STATUS_NON_UNIQUE_NAME will eventually become a hard error. For
676     // now treat it as a warning and do not map it to an error return value.
677   }
678 
679   // Flag certificates using too long validity periods.
680   if (verify_result->is_issued_by_known_root && HasTooLongValidity(*cert)) {
681     verify_result->cert_status |= CERT_STATUS_VALIDITY_TOO_LONG;
682     if (rv == OK)
683       rv = MapCertStatusToNetError(verify_result->cert_status);
684   }
685 
686   // Record a histogram for the presence of the TLS feature extension in
687   // a certificate chaining to a private root.
688   if (rv == OK && !verify_result->is_issued_by_known_root)
689     RecordTLSFeatureExtensionWithPrivateRoot(cert, verify_result->ocsp_result);
690 
691   // Record a histogram for per-verification usage of root certs.
692   if (rv == OK) {
693     RecordTrustAnchorHistogram(verify_result->public_key_hashes,
694                                verify_result->is_issued_by_known_root);
695   }
696 
697   net_log.EndEvent(NetLogEventType::CERT_VERIFY_PROC,
698                    [&] { return verify_result->NetLogParams(rv); });
699   return rv;
700 }
701 
702 // static
LogNameNormalizationResult(const std::string & histogram_suffix,NameNormalizationResult result)703 void CertVerifyProc::LogNameNormalizationResult(
704     const std::string& histogram_suffix,
705     NameNormalizationResult result) {
706   base::UmaHistogramEnumeration(
707       std::string("Net.CertVerifier.NameNormalizationPrivateRoots") +
708           histogram_suffix,
709       result);
710 }
711 
712 // static
LogNameNormalizationMetrics(const std::string & histogram_suffix,X509Certificate * verified_cert,bool is_issued_by_known_root)713 void CertVerifyProc::LogNameNormalizationMetrics(
714     const std::string& histogram_suffix,
715     X509Certificate* verified_cert,
716     bool is_issued_by_known_root) {
717   if (is_issued_by_known_root)
718     return;
719 
720   if (verified_cert->intermediate_buffers().empty()) {
721     LogNameNormalizationResult(histogram_suffix,
722                                NameNormalizationResult::kChainLengthOne);
723     return;
724   }
725 
726   std::vector<CRYPTO_BUFFER*> der_certs;
727   der_certs.push_back(verified_cert->cert_buffer());
728   for (const auto& buf : verified_cert->intermediate_buffers())
729     der_certs.push_back(buf.get());
730 
731   ParseCertificateOptions options;
732   options.allow_invalid_serial_numbers = true;
733 
734   std::vector<der::Input> subjects;
735   std::vector<der::Input> issuers;
736 
737   for (auto* buf : der_certs) {
738     der::Input tbs_certificate_tlv;
739     der::Input signature_algorithm_tlv;
740     der::BitString signature_value;
741     ParsedTbsCertificate tbs;
742     if (!ParseCertificate(
743             der::Input(CRYPTO_BUFFER_data(buf), CRYPTO_BUFFER_len(buf)),
744             &tbs_certificate_tlv, &signature_algorithm_tlv, &signature_value,
745             nullptr /* errors*/) ||
746         !ParseTbsCertificate(tbs_certificate_tlv, options, &tbs,
747                              nullptr /*errors*/)) {
748       LogNameNormalizationResult(histogram_suffix,
749                                  NameNormalizationResult::kError);
750       return;
751     }
752     subjects.push_back(tbs.subject_tlv);
753     issuers.push_back(tbs.issuer_tlv);
754   }
755 
756   for (size_t i = 0; i < subjects.size() - 1; ++i) {
757     if (issuers[i] != subjects[i + 1]) {
758       LogNameNormalizationResult(histogram_suffix,
759                                  NameNormalizationResult::kNormalized);
760       return;
761     }
762   }
763 
764   LogNameNormalizationResult(histogram_suffix,
765                              NameNormalizationResult::kByteEqual);
766 }
767 
768 // CheckNameConstraints verifies that every name in |dns_names| is in one of
769 // the domains specified by |domains|.
CheckNameConstraints(const std::vector<std::string> & dns_names,base::span<const base::StringPiece> domains)770 static bool CheckNameConstraints(const std::vector<std::string>& dns_names,
771                                  base::span<const base::StringPiece> domains) {
772   for (const auto& host : dns_names) {
773     bool ok = false;
774     url::CanonHostInfo host_info;
775     const std::string dns_name = CanonicalizeHost(host, &host_info);
776     if (host_info.IsIPAddress())
777       continue;
778 
779     // If the name is not in a known TLD, ignore it. This permits internal
780     // server names.
781     if (!registry_controlled_domains::HostHasRegistryControlledDomain(
782             dns_name, registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
783             registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
784       continue;
785     }
786 
787     for (const auto& domain : domains) {
788       // The |domain| must be of ".somesuffix" form, and |dns_name| must
789       // have |domain| as a suffix.
790       DCHECK_EQ('.', domain[0]);
791       if (dns_name.size() <= domain.size())
792         continue;
793       base::StringPiece suffix =
794           base::StringPiece(dns_name).substr(dns_name.size() - domain.size());
795       if (!base::LowerCaseEqualsASCII(suffix, domain))
796         continue;
797       ok = true;
798       break;
799     }
800 
801     if (!ok)
802       return false;
803   }
804 
805   return true;
806 }
807 
808 // static
HasNameConstraintsViolation(const HashValueVector & public_key_hashes,const std::string & common_name,const std::vector<std::string> & dns_names,const std::vector<std::string> & ip_addrs)809 bool CertVerifyProc::HasNameConstraintsViolation(
810     const HashValueVector& public_key_hashes,
811     const std::string& common_name,
812     const std::vector<std::string>& dns_names,
813     const std::vector<std::string>& ip_addrs) {
814   static constexpr base::StringPiece kDomainsANSSI[] = {
815       ".fr",  // France
816       ".gp",  // Guadeloupe
817       ".gf",  // Guyane
818       ".mq",  // Martinique
819       ".re",  // Réunion
820       ".yt",  // Mayotte
821       ".pm",  // Saint-Pierre et Miquelon
822       ".bl",  // Saint Barthélemy
823       ".mf",  // Saint Martin
824       ".wf",  // Wallis et Futuna
825       ".pf",  // Polynésie française
826       ".nc",  // Nouvelle Calédonie
827       ".tf",  // Terres australes et antarctiques françaises
828   };
829 
830   static constexpr base::StringPiece kDomainsIndiaCCA[] = {
831       ".gov.in",   ".nic.in",    ".ac.in", ".rbi.org.in", ".bankofindia.co.in",
832       ".ncode.in", ".tcs.co.in",
833   };
834 
835   static constexpr base::StringPiece kDomainsTest[] = {
836       ".example.com",
837   };
838 
839   // PublicKeyDomainLimitation contains SHA-256(SPKI) and a pointer to an array
840   // of fixed-length strings that contain the domains that the SPKI is allowed
841   // to issue for.
842   static const struct PublicKeyDomainLimitation {
843     SHA256HashValue public_key_hash;
844     base::span<const base::StringPiece> domains;
845   } kLimits[] = {
846       // C=FR, ST=France, L=Paris, O=PM/SGDN, OU=DCSSI,
847       // CN=IGC/A/emailAddress=igca@sgdn.pm.gouv.fr
848       //
849       // net/data/ssl/blocklist/b9bea7860a962ea3611dab97ab6da3e21c1068b97d55575ed0e11279c11c8932.pem
850       {
851           {{0x86, 0xc1, 0x3a, 0x34, 0x08, 0xdd, 0x1a, 0xa7, 0x7e, 0xe8, 0xb6,
852             0x94, 0x7c, 0x03, 0x95, 0x87, 0x72, 0xf5, 0x31, 0x24, 0x8c, 0x16,
853             0x27, 0xbe, 0xfb, 0x2c, 0x4f, 0x4b, 0x04, 0xd0, 0x44, 0x96}},
854           kDomainsANSSI,
855       },
856       // C=IN, O=India PKI, CN=CCA India 2007
857       // Expires: July 4th 2015.
858       //
859       // net/data/ssl/blocklist/f375e2f77a108bacc4234894a9af308edeca1acd8fbde0e7aaa9634e9daf7e1c.pem
860       {
861           {{0x7e, 0x6a, 0xcd, 0x85, 0x3c, 0xac, 0xc6, 0x93, 0x2e, 0x9b, 0x51,
862             0x9f, 0xda, 0xd1, 0xbe, 0xb5, 0x15, 0xed, 0x2a, 0x2d, 0x00, 0x25,
863             0xcf, 0xd3, 0x98, 0xc3, 0xac, 0x1f, 0x0d, 0xbb, 0x75, 0x4b}},
864           kDomainsIndiaCCA,
865       },
866       // C=IN, O=India PKI, CN=CCA India 2011
867       // Expires: March 11 2016.
868       //
869       // net/data/ssl/blocklist/2d66a702ae81ba03af8cff55ab318afa919039d9f31b4d64388680f81311b65a.pem
870       {
871           {{0x42, 0xa7, 0x09, 0x84, 0xff, 0xd3, 0x99, 0xc4, 0xea, 0xf0, 0xe7,
872             0x02, 0xa4, 0x4b, 0xef, 0x2a, 0xd8, 0xa7, 0x9b, 0x8b, 0xf4, 0x64,
873             0x8f, 0x6b, 0xb2, 0x10, 0xe1, 0x23, 0xfd, 0x07, 0x57, 0x93}},
874           kDomainsIndiaCCA,
875       },
876       // C=IN, O=India PKI, CN=CCA India 2014
877       // Expires: March 5 2024.
878       //
879       // net/data/ssl/blocklist/60109bc6c38328598a112c7a25e38b0f23e5a7511cb815fb64e0c4ff05db7df7.pem
880       {
881           {{0x9c, 0xf4, 0x70, 0x4f, 0x3e, 0xe5, 0xa5, 0x98, 0x94, 0xb1, 0x6b,
882             0xf0, 0x0c, 0xfe, 0x73, 0xd5, 0x88, 0xda, 0xe2, 0x69, 0xf5, 0x1d,
883             0xe6, 0x6a, 0x4b, 0xa7, 0x74, 0x46, 0xee, 0x2b, 0xd1, 0xf7}},
884           kDomainsIndiaCCA,
885       },
886       // Not a real certificate - just for testing.
887       // net/data/ssl/certificates/name_constraint_*.pem
888       {
889           {{0x0d, 0x93, 0x13, 0xa7, 0xd7, 0x0d, 0x35, 0x89, 0x33, 0x50, 0x6e,
890             0x9b, 0x68, 0x30, 0x7a, 0x4f, 0x7d, 0x3a, 0x7a, 0x42, 0xd4, 0x60,
891             0x9a, 0x5e, 0x10, 0x4b, 0x58, 0xa5, 0xa7, 0x90, 0xa5, 0x81}},
892           kDomainsTest,
893       },
894   };
895 
896   for (const auto& limit : kLimits) {
897     for (const auto& hash : public_key_hashes) {
898       if (hash.tag() != HASH_VALUE_SHA256)
899         continue;
900       if (memcmp(hash.data(), limit.public_key_hash.data, hash.size()) != 0)
901         continue;
902       if (dns_names.empty() && ip_addrs.empty()) {
903         std::vector<std::string> names;
904         names.push_back(common_name);
905         if (!CheckNameConstraints(names, limit.domains))
906           return true;
907       } else {
908         if (!CheckNameConstraints(dns_names, limit.domains))
909           return true;
910       }
911     }
912   }
913 
914   return false;
915 }
916 
917 // static
HasTooLongValidity(const X509Certificate & cert)918 bool CertVerifyProc::HasTooLongValidity(const X509Certificate& cert) {
919   const base::Time& start = cert.valid_start();
920   const base::Time& expiry = cert.valid_expiry();
921   if (start.is_max() || start.is_null() || expiry.is_max() ||
922       expiry.is_null() || start > expiry) {
923     return true;
924   }
925 
926   // These dates are derived from the transitions noted in Section 1.2.2
927   // (Relevant Dates) of the Baseline Requirements.
928   const base::Time time_2012_07_01 =
929       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1341100800);
930   const base::Time time_2015_04_01 =
931       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1427846400);
932   const base::Time time_2018_03_01 =
933       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1519862400);
934   const base::Time time_2019_07_01 =
935       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1561939200);
936   // From Chrome Root Certificate Policy
937   const base::Time time_2020_09_01 =
938       base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1598918400);
939 
940   // Compute the maximally permissive interpretations, accounting for leap
941   // years.
942   // 10 years - two possible leap years.
943   constexpr base::TimeDelta kTenYears =
944       base::TimeDelta::FromDays((365 * 8) + (366 * 2));
945   // 5 years - two possible leap years (year 0/year 4 or year 1/year 5).
946   constexpr base::TimeDelta kSixtyMonths =
947       base::TimeDelta::FromDays((365 * 3) + (366 * 2));
948   // 39 months - one possible leap year, two at 365 days, and the longest
949   // monthly sequence of 31/31/30 days (June/July/August).
950   constexpr base::TimeDelta kThirtyNineMonths =
951       base::TimeDelta::FromDays(366 + 365 + 365 + 31 + 31 + 30);
952 
953   base::TimeDelta validity_duration = cert.valid_expiry() - cert.valid_start();
954 
955   // For certificates issued before the BRs took effect.
956   if (start < time_2012_07_01 &&
957       (validity_duration > kTenYears || expiry > time_2019_07_01)) {
958     return true;
959   }
960 
961   // For certificates issued on-or-after the BR effective date of 1 July 2012:
962   // 60 months.
963   if (start >= time_2012_07_01 && validity_duration > kSixtyMonths)
964     return true;
965 
966   // For certificates issued on-or-after 1 April 2015: 39 months.
967   if (start >= time_2015_04_01 && validity_duration > kThirtyNineMonths)
968     return true;
969 
970   // For certificates issued on-or-after 1 March 2018: 825 days.
971   if (start >= time_2018_03_01 &&
972       validity_duration > base::TimeDelta::FromDays(825)) {
973     return true;
974   }
975 
976   // For certificates issued on-or-after 1 September 2020: 398 days.
977   if (start >= time_2020_09_01 &&
978       validity_duration > base::TimeDelta::FromDays(398)) {
979     return true;
980   }
981 
982   return false;
983 }
984 
985 // static
986 const base::Feature CertVerifyProc::kLegacySymantecPKIEnforcement{
987     "LegacySymantecPKI", base::FEATURE_ENABLED_BY_DEFAULT};
988 
989 }  // namespace net
990