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