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