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 #include <optional>
11 #include <string_view>
12
13 #include "base/containers/flat_set.h"
14 #include "base/containers/span.h"
15 #include "base/metrics/histogram.h"
16 #include "base/metrics/histogram_functions.h"
17 #include "base/metrics/histogram_macros.h"
18 #include "base/strings/strcat.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/threading/scoped_blocking_call.h"
22 #include "base/time/time.h"
23 #include "build/build_config.h"
24 #include "crypto/crypto_buildflags.h"
25 #include "crypto/sha2.h"
26 #include "net/base/features.h"
27 #include "net/base/net_errors.h"
28 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
29 #include "net/base/url_util.h"
30 #include "net/cert/asn1_util.h"
31 #include "net/cert/cert_net_fetcher.h"
32 #include "net/cert/cert_status_flags.h"
33 #include "net/cert/cert_verifier.h"
34 #include "net/cert/cert_verify_result.h"
35 #include "net/cert/crl_set.h"
36 #include "net/cert/internal/revocation_checker.h"
37 #include "net/cert/internal/system_trust_store.h"
38 #include "net/cert/known_roots.h"
39 #include "net/cert/symantec_certs.h"
40 #include "net/cert/x509_certificate.h"
41 #include "net/cert/x509_certificate_net_log_param.h"
42 #include "net/cert/x509_util.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 "third_party/boringssl/src/include/openssl/pool.h"
47 #include "third_party/boringssl/src/pki/encode_values.h"
48 #include "third_party/boringssl/src/pki/extended_key_usage.h"
49 #include "third_party/boringssl/src/pki/ocsp.h"
50 #include "third_party/boringssl/src/pki/ocsp_revocation_status.h"
51 #include "third_party/boringssl/src/pki/parse_certificate.h"
52 #include "third_party/boringssl/src/pki/pem.h"
53 #include "third_party/boringssl/src/pki/signature_algorithm.h"
54 #include "url/url_canon.h"
55
56 #if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
57 #include "net/cert/cert_verify_proc_builtin.h"
58 #endif
59
60 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
61 #include "net/cert/internal/trust_store_chrome.h"
62 #endif // CHROME_ROOT_STORE_SUPPORTED
63
64 #if BUILDFLAG(IS_ANDROID)
65 #include "net/cert/cert_verify_proc_android.h"
66 #elif BUILDFLAG(IS_IOS)
67 #include "net/cert/cert_verify_proc_ios.h"
68 #endif
69
70 namespace net {
71
72 namespace {
73
74 // Constants used to build histogram names
75 const char kLeafCert[] = "Leaf";
76 const char kIntermediateCert[] = "Intermediate";
77 const char kRootCert[] = "Root";
78
79 // Histogram buckets for RSA/DSA/DH key sizes.
80 const int kRsaDsaKeySizes[] = {512, 768, 1024, 1536, 2048, 3072, 4096, 8192,
81 16384};
82 // Histogram buckets for ECDSA/ECDH key sizes. The list is based upon the FIPS
83 // 186-4 approved curves.
84 const int kEccKeySizes[] = {163, 192, 224, 233, 256, 283, 384, 409, 521, 571};
85
CertTypeToString(X509Certificate::PublicKeyType cert_type)86 const char* CertTypeToString(X509Certificate::PublicKeyType cert_type) {
87 switch (cert_type) {
88 case X509Certificate::kPublicKeyTypeUnknown:
89 return "Unknown";
90 case X509Certificate::kPublicKeyTypeRSA:
91 return "RSA";
92 case X509Certificate::kPublicKeyTypeDSA:
93 return "DSA";
94 case X509Certificate::kPublicKeyTypeECDSA:
95 return "ECDSA";
96 case X509Certificate::kPublicKeyTypeDH:
97 return "DH";
98 case X509Certificate::kPublicKeyTypeECDH:
99 return "ECDH";
100 }
101 NOTREACHED();
102 return "Unsupported";
103 }
104
RecordPublicKeyHistogram(const char * chain_position,bool baseline_keysize_applies,size_t size_bits,X509Certificate::PublicKeyType cert_type)105 void RecordPublicKeyHistogram(const char* chain_position,
106 bool baseline_keysize_applies,
107 size_t size_bits,
108 X509Certificate::PublicKeyType cert_type) {
109 std::string histogram_name =
110 base::StringPrintf("CertificateType2.%s.%s.%s",
111 baseline_keysize_applies ? "BR" : "NonBR",
112 chain_position,
113 CertTypeToString(cert_type));
114 // Do not use UMA_HISTOGRAM_... macros here, as it caches the Histogram
115 // instance and thus only works if |histogram_name| is constant.
116 base::HistogramBase* counter = nullptr;
117
118 // Histogram buckets are contingent upon the underlying algorithm being used.
119 if (cert_type == X509Certificate::kPublicKeyTypeECDH ||
120 cert_type == X509Certificate::kPublicKeyTypeECDSA) {
121 // Typical key sizes match SECP/FIPS 186-3 recommendations for prime and
122 // binary curves - which range from 163 bits to 571 bits.
123 counter = base::CustomHistogram::FactoryGet(
124 histogram_name,
125 base::CustomHistogram::ArrayToCustomEnumRanges(kEccKeySizes),
126 base::HistogramBase::kUmaTargetedHistogramFlag);
127 } else {
128 // Key sizes < 1024 bits should cause errors, while key sizes > 16K are not
129 // uniformly supported by the underlying cryptographic libraries.
130 counter = base::CustomHistogram::FactoryGet(
131 histogram_name,
132 base::CustomHistogram::ArrayToCustomEnumRanges(kRsaDsaKeySizes),
133 base::HistogramBase::kUmaTargetedHistogramFlag);
134 }
135 counter->Add(size_bits);
136 }
137
138 // Returns true if |type| is |kPublicKeyTypeRSA| or |kPublicKeyTypeDSA|, and
139 // if |size_bits| is < 1024. Note that this means there may be false
140 // negatives: keys for other algorithms and which are weak will pass this
141 // test.
IsWeakKey(X509Certificate::PublicKeyType type,size_t size_bits)142 bool IsWeakKey(X509Certificate::PublicKeyType type, size_t size_bits) {
143 switch (type) {
144 case X509Certificate::kPublicKeyTypeRSA:
145 case X509Certificate::kPublicKeyTypeDSA:
146 return size_bits < 1024;
147 default:
148 return false;
149 }
150 }
151
152 // Returns true if |cert| contains a known-weak key. Additionally, histograms
153 // the observed keys for future tightening of the definition of what
154 // constitutes a weak key.
ExaminePublicKeys(const scoped_refptr<X509Certificate> & cert,bool should_histogram)155 bool ExaminePublicKeys(const scoped_refptr<X509Certificate>& cert,
156 bool should_histogram) {
157 // The effective date of the CA/Browser Forum's Baseline Requirements -
158 // 2012-07-01 00:00:00 UTC.
159 const base::Time kBaselineEffectiveDate =
160 base::Time::FromInternalValue(INT64_C(12985574400000000));
161 // The effective date of the key size requirements from Appendix A, v1.1.5
162 // 2014-01-01 00:00:00 UTC.
163 const base::Time kBaselineKeysizeEffectiveDate =
164 base::Time::FromInternalValue(INT64_C(13033008000000000));
165
166 size_t size_bits = 0;
167 X509Certificate::PublicKeyType type = X509Certificate::kPublicKeyTypeUnknown;
168 bool weak_key = false;
169 bool baseline_keysize_applies =
170 cert->valid_start() >= kBaselineEffectiveDate &&
171 cert->valid_expiry() >= kBaselineKeysizeEffectiveDate;
172
173 X509Certificate::GetPublicKeyInfo(cert->cert_buffer(), &size_bits, &type);
174 if (should_histogram) {
175 RecordPublicKeyHistogram(kLeafCert, baseline_keysize_applies, size_bits,
176 type);
177 }
178 if (IsWeakKey(type, size_bits))
179 weak_key = true;
180
181 const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediates =
182 cert->intermediate_buffers();
183 for (size_t i = 0; i < intermediates.size(); ++i) {
184 X509Certificate::GetPublicKeyInfo(intermediates[i].get(), &size_bits,
185 &type);
186 if (should_histogram) {
187 RecordPublicKeyHistogram(
188 (i < intermediates.size() - 1) ? kIntermediateCert : kRootCert,
189 baseline_keysize_applies,
190 size_bits,
191 type);
192 }
193 if (!weak_key && IsWeakKey(type, size_bits))
194 weak_key = true;
195 }
196
197 return weak_key;
198 }
199
BestEffortCheckOCSP(const std::string & raw_response,const X509Certificate & certificate,bssl::OCSPVerifyResult * verify_result)200 void BestEffortCheckOCSP(const std::string& raw_response,
201 const X509Certificate& certificate,
202 bssl::OCSPVerifyResult* verify_result) {
203 if (raw_response.empty()) {
204 *verify_result = bssl::OCSPVerifyResult();
205 verify_result->response_status = bssl::OCSPVerifyResult::MISSING;
206 return;
207 }
208
209 std::string_view cert_der =
210 x509_util::CryptoBufferAsStringPiece(certificate.cert_buffer());
211
212 // Try to get the certificate that signed |certificate|. This will run into
213 // problems if the CertVerifyProc implementation doesn't return the ordered
214 // certificates. If that happens the OCSP verification may be incorrect.
215 std::string_view issuer_der;
216 if (certificate.intermediate_buffers().empty()) {
217 if (X509Certificate::IsSelfSigned(certificate.cert_buffer())) {
218 issuer_der = cert_der;
219 } else {
220 // A valid cert chain wasn't provided.
221 *verify_result = bssl::OCSPVerifyResult();
222 return;
223 }
224 } else {
225 issuer_der = x509_util::CryptoBufferAsStringPiece(
226 certificate.intermediate_buffers().front().get());
227 }
228
229 verify_result->revocation_status = bssl::CheckOCSP(
230 raw_response, cert_der, issuer_der, base::Time::Now().ToTimeT(),
231 kMaxRevocationLeafUpdateAge.InSeconds(), &verify_result->response_status);
232 }
233
234 // Records details about the most-specific trust anchor in |hashes|, which is
235 // expected to be ordered with the leaf cert first and the root cert last.
236 // "Most-specific" refers to the case that it is not uncommon to have multiple
237 // potential trust anchors present in a chain, depending on the client trust
238 // store. For example, '1999-Root' cross-signing '2005-Root' cross-signing
239 // '2012-Root' cross-signing '2017-Root', then followed by intermediate and
240 // leaf. For purposes of assessing impact of, say, removing 1999-Root, while
241 // including 2017-Root as a trust anchor, then the validation should be
242 // counted as 2017-Root, rather than 1999-Root.
243 //
244 // This also accounts for situations in which a new CA is introduced, and
245 // has been cross-signed by an existing CA. Assessing impact should use the
246 // most-specific trust anchor, when possible.
247 //
248 // This also histograms for divergence between the root store and
249 // |spki_hashes| - that is, situations in which the OS methods of detecting
250 // a known root flag a certificate as known, but its hash is not known as part
251 // of the built-in list.
RecordTrustAnchorHistogram(const HashValueVector & spki_hashes,bool is_issued_by_known_root)252 void RecordTrustAnchorHistogram(const HashValueVector& spki_hashes,
253 bool is_issued_by_known_root) {
254 int32_t id = 0;
255 for (const auto& hash : spki_hashes) {
256 id = GetNetTrustAnchorHistogramIdForSPKI(hash);
257 if (id != 0)
258 break;
259 }
260 base::UmaHistogramSparse("Net.Certificate.TrustAnchor.Verify", id);
261
262 // Record when a known trust anchor is not found within the chain, but the
263 // certificate is flagged as being from a known root (meaning a fallback to
264 // OS-based methods of determination).
265 if (id == 0) {
266 UMA_HISTOGRAM_BOOLEAN("Net.Certificate.TrustAnchor.VerifyOutOfDate",
267 is_issued_by_known_root);
268 }
269 }
270
271 // Inspects the signature algorithms in a single certificate |cert|.
272 //
273 // * Sets |verify_result->has_sha1| to true if the certificate uses SHA1.
274 //
275 // Returns false if the signature algorithm was unknown or mismatched.
InspectSignatureAlgorithmForCert(const CRYPTO_BUFFER * cert,CertVerifyResult * verify_result)276 [[nodiscard]] bool InspectSignatureAlgorithmForCert(
277 const CRYPTO_BUFFER* cert,
278 CertVerifyResult* verify_result) {
279 std::string_view cert_algorithm_sequence;
280 std::string_view tbs_algorithm_sequence;
281
282 // Extract the AlgorithmIdentifier SEQUENCEs
283 if (!asn1::ExtractSignatureAlgorithmsFromDERCert(
284 x509_util::CryptoBufferAsStringPiece(cert), &cert_algorithm_sequence,
285 &tbs_algorithm_sequence)) {
286 return false;
287 }
288
289 std::optional<bssl::SignatureAlgorithm> cert_algorithm =
290 bssl::ParseSignatureAlgorithm(bssl::der::Input(cert_algorithm_sequence));
291 std::optional<bssl::SignatureAlgorithm> tbs_algorithm =
292 bssl::ParseSignatureAlgorithm(bssl::der::Input(tbs_algorithm_sequence));
293 if (!cert_algorithm || !tbs_algorithm || *cert_algorithm != *tbs_algorithm) {
294 return false;
295 }
296
297 switch (*cert_algorithm) {
298 case bssl::SignatureAlgorithm::kRsaPkcs1Sha1:
299 case bssl::SignatureAlgorithm::kEcdsaSha1:
300 verify_result->has_sha1 = true;
301 return true; // For now.
302
303 case bssl::SignatureAlgorithm::kRsaPkcs1Sha256:
304 case bssl::SignatureAlgorithm::kRsaPkcs1Sha384:
305 case bssl::SignatureAlgorithm::kRsaPkcs1Sha512:
306 case bssl::SignatureAlgorithm::kEcdsaSha256:
307 case bssl::SignatureAlgorithm::kEcdsaSha384:
308 case bssl::SignatureAlgorithm::kEcdsaSha512:
309 case bssl::SignatureAlgorithm::kRsaPssSha256:
310 case bssl::SignatureAlgorithm::kRsaPssSha384:
311 case bssl::SignatureAlgorithm::kRsaPssSha512:
312 return true;
313 }
314
315 NOTREACHED();
316 return false;
317 }
318
319 // InspectSignatureAlgorithmsInChain() sets |verify_result->has_*| based on
320 // the signature algorithms used in the chain, and also checks that certificates
321 // don't have contradictory signature algorithms.
322 //
323 // Returns false if any signature algorithm in the chain is unknown or
324 // mismatched.
325 //
326 // Background:
327 //
328 // X.509 certificates contain two redundant descriptors for the signature
329 // algorithm; one is covered by the signature, but in order to verify the
330 // signature, the other signature algorithm is untrusted.
331 //
332 // RFC 5280 states that the two should be equal, in order to mitigate risk of
333 // signature substitution attacks, but also discourages verifiers from enforcing
334 // the profile of RFC 5280.
335 //
336 // System verifiers are inconsistent - some use the unsigned signature, some use
337 // the signed signature, and they generally do not enforce that both match. This
338 // creates confusion, as it's possible that the signature itself may be checked
339 // using algorithm A, but if subsequent consumers report the certificate
340 // algorithm, they may end up reporting algorithm B, which was not used to
341 // verify the certificate. This function enforces that the two signatures match
342 // in order to prevent such confusion.
InspectSignatureAlgorithmsInChain(CertVerifyResult * verify_result)343 [[nodiscard]] bool InspectSignatureAlgorithmsInChain(
344 CertVerifyResult* verify_result) {
345 const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediates =
346 verify_result->verified_cert->intermediate_buffers();
347
348 // If there are no intermediates, then the leaf is trusted or verification
349 // failed.
350 if (intermediates.empty())
351 return true;
352
353 DCHECK(!verify_result->has_sha1);
354
355 // Fill in hash algorithms for the leaf certificate.
356 if (!InspectSignatureAlgorithmForCert(
357 verify_result->verified_cert->cert_buffer(), verify_result)) {
358 return false;
359 }
360
361 // Fill in hash algorithms for the intermediate cerificates, excluding the
362 // final one (which is presumably the trust anchor; may be incorrect for
363 // partial chains).
364 for (size_t i = 0; i + 1 < intermediates.size(); ++i) {
365 if (!InspectSignatureAlgorithmForCert(intermediates[i].get(),
366 verify_result))
367 return false;
368 }
369
370 return true;
371 }
372
CertVerifyParams(X509Certificate * cert,const std::string & hostname,const std::string & ocsp_response,const std::string & sct_list,int flags,CRLSet * crl_set)373 base::Value::Dict CertVerifyParams(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 base::Value::Dict dict;
380 dict.Set("certificates", NetLogX509CertificateList(cert));
381 if (!ocsp_response.empty()) {
382 dict.Set("ocsp_response",
383 bssl::PEMEncode(ocsp_response, "NETLOG OCSP RESPONSE"));
384 }
385 if (!sct_list.empty()) {
386 dict.Set("sct_list", bssl::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 return dict;
395 }
396
397 } // namespace
398
399 #if !(BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(CHROME_ROOT_STORE_ONLY))
400 // static
CreateSystemVerifyProc(scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set)401 scoped_refptr<CertVerifyProc> CertVerifyProc::CreateSystemVerifyProc(
402 scoped_refptr<CertNetFetcher> cert_net_fetcher,
403 scoped_refptr<CRLSet> crl_set) {
404 #if BUILDFLAG(IS_ANDROID)
405 return base::MakeRefCounted<CertVerifyProcAndroid>(
406 std::move(cert_net_fetcher), std::move(crl_set));
407 #elif BUILDFLAG(IS_IOS)
408 return base::MakeRefCounted<CertVerifyProcIOS>(std::move(crl_set));
409 #else
410 #error Unsupported platform
411 #endif
412 }
413 #endif
414
415 #if BUILDFLAG(IS_FUCHSIA)
416 // static
CreateBuiltinVerifyProc(scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set,std::unique_ptr<CTVerifier> ct_verifier,scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,const InstanceParams instance_params)417 scoped_refptr<CertVerifyProc> CertVerifyProc::CreateBuiltinVerifyProc(
418 scoped_refptr<CertNetFetcher> cert_net_fetcher,
419 scoped_refptr<CRLSet> crl_set,
420 std::unique_ptr<CTVerifier> ct_verifier,
421 scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,
422 const InstanceParams instance_params) {
423 return CreateCertVerifyProcBuiltin(
424 std::move(cert_net_fetcher), std::move(crl_set), std::move(ct_verifier),
425 std::move(ct_policy_enforcer), CreateSslSystemTrustStore(),
426 instance_params);
427 }
428 #endif
429
430 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
431 // static
CreateBuiltinWithChromeRootStore(scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set,std::unique_ptr<CTVerifier> ct_verifier,scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,const ChromeRootStoreData * root_store_data,const InstanceParams instance_params)432 scoped_refptr<CertVerifyProc> CertVerifyProc::CreateBuiltinWithChromeRootStore(
433 scoped_refptr<CertNetFetcher> cert_net_fetcher,
434 scoped_refptr<CRLSet> crl_set,
435 std::unique_ptr<CTVerifier> ct_verifier,
436 scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,
437 const ChromeRootStoreData* root_store_data,
438 const InstanceParams instance_params) {
439 std::unique_ptr<TrustStoreChrome> chrome_root =
440 root_store_data ? std::make_unique<TrustStoreChrome>(*root_store_data)
441 : std::make_unique<TrustStoreChrome>();
442 return CreateCertVerifyProcBuiltin(
443 std::move(cert_net_fetcher), std::move(crl_set), std::move(ct_verifier),
444 std::move(ct_policy_enforcer),
445 CreateSslSystemTrustStoreChromeRoot(std::move(chrome_root)),
446 instance_params);
447 }
448 #endif
449
CertVerifyProc(scoped_refptr<CRLSet> crl_set)450 CertVerifyProc::CertVerifyProc(scoped_refptr<CRLSet> crl_set)
451 : crl_set_(std::move(crl_set)) {
452 CHECK(crl_set_);
453 }
454
455 CertVerifyProc::~CertVerifyProc() = default;
456
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,std::optional<base::Time> time_now)457 int CertVerifyProc::Verify(X509Certificate* cert,
458 const std::string& hostname,
459 const std::string& ocsp_response,
460 const std::string& sct_list,
461 int flags,
462 CertVerifyResult* verify_result,
463 const NetLogWithSource& net_log,
464 std::optional<base::Time> time_now) {
465 CHECK(cert);
466 CHECK(verify_result);
467
468 net_log.BeginEvent(NetLogEventType::CERT_VERIFY_PROC, [&] {
469 return CertVerifyParams(cert, hostname, ocsp_response, sct_list, flags,
470 crl_set());
471 });
472 // CertVerifyProc's contract allows ::VerifyInternal() to wait on File I/O
473 // (such as the Windows registry or smart cards on all platforms) or may re-
474 // enter this code via extension hooks (such as smart card UI). To ensure
475 // threads are not starved or deadlocked, the base::ScopedBlockingCall below
476 // increments the thread pool capacity when this method takes too much time to
477 // run.
478 base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
479 base::BlockingType::MAY_BLOCK);
480
481 verify_result->Reset();
482 verify_result->verified_cert = cert;
483
484 int rv = VerifyInternal(cert, hostname, ocsp_response, sct_list, flags,
485 verify_result, net_log, time_now);
486
487 CHECK(verify_result->verified_cert);
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 bssl::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(std::string_view(
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 bssl::ParseCertificateOptions options;
639 options.allow_invalid_serial_numbers = true;
640
641 std::vector<bssl::der::Input> subjects;
642 std::vector<bssl::der::Input> issuers;
643
644 for (auto* buf : der_certs) {
645 bssl::der::Input tbs_certificate_tlv;
646 bssl::der::Input signature_algorithm_tlv;
647 bssl::der::BitString signature_value;
648 bssl::ParsedTbsCertificate tbs;
649 if (!bssl::ParseCertificate(
650 bssl::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 std::string_view> domains)677 static bool CheckNameConstraints(const std::vector<std::string>& dns_names,
678 base::span<const std::string_view> 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 std::string_view suffix =
701 std::string_view(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 std::string_view 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 std::string_view kDomainsTest[] = {
738 ".example.com",
739 };
740
741 // PublicKeyDomainLimitation contains SHA-256(SPKI) and a pointer to an array
742 // of fixed-length strings that contain the domains that the SPKI is allowed
743 // to issue for.
744 //
745 // A public key hash can be generated with the following command:
746 // openssl x509 -noout -in <cert>.pem -pubkey | \
747 // openssl asn1parse -noout -inform pem -out - | \
748 // openssl dgst -sha256 -binary | xxd -i
749 static const struct PublicKeyDomainLimitation {
750 SHA256HashValue public_key_hash;
751 base::span<const std::string_view> domains;
752 } kLimits[] = {
753 // C=FR, ST=France, L=Paris, O=PM/SGDN, OU=DCSSI,
754 // CN=IGC/A/emailAddress[email protected]
755 //
756 // net/data/ssl/name_constrained/b9bea7860a962ea3611dab97ab6da3e21c1068b97d55575ed0e11279c11c8932.pem
757 {
758 {{0x86, 0xc1, 0x3a, 0x34, 0x08, 0xdd, 0x1a, 0xa7, 0x7e, 0xe8, 0xb6,
759 0x94, 0x7c, 0x03, 0x95, 0x87, 0x72, 0xf5, 0x31, 0x24, 0x8c, 0x16,
760 0x27, 0xbe, 0xfb, 0x2c, 0x4f, 0x4b, 0x04, 0xd0, 0x44, 0x96}},
761 kDomainsANSSI,
762 },
763 // Not a real certificate - just for testing.
764 // net/data/ssl/certificates/name_constrained_key.pem
765 {
766 {{0xa2, 0x2a, 0x88, 0x82, 0xba, 0x0c, 0xae, 0x9d, 0xf2, 0xc4, 0x5b,
767 0x15, 0xa6, 0x1e, 0xfd, 0xfd, 0x19, 0x6b, 0xb1, 0x09, 0x19, 0xfd,
768 0xac, 0x77, 0x9b, 0xd6, 0x08, 0x66, 0xda, 0xa8, 0xd2, 0x88}},
769 kDomainsTest,
770 },
771 };
772
773 for (const auto& limit : kLimits) {
774 for (const auto& hash : public_key_hashes) {
775 if (hash.tag() != HASH_VALUE_SHA256)
776 continue;
777 if (memcmp(hash.data(), limit.public_key_hash.data, hash.size()) != 0)
778 continue;
779 if (dns_names.empty() && ip_addrs.empty()) {
780 std::vector<std::string> names;
781 names.push_back(common_name);
782 if (!CheckNameConstraints(names, limit.domains))
783 return true;
784 } else {
785 if (!CheckNameConstraints(dns_names, limit.domains))
786 return true;
787 }
788 }
789 }
790
791 return false;
792 }
793
794 // static
HasTooLongValidity(const X509Certificate & cert)795 bool CertVerifyProc::HasTooLongValidity(const X509Certificate& cert) {
796 const base::Time& start = cert.valid_start();
797 const base::Time& expiry = cert.valid_expiry();
798 if (start.is_max() || start.is_null() || expiry.is_max() ||
799 expiry.is_null() || start > expiry) {
800 return true;
801 }
802
803 // The maximum lifetime of publicly trusted certificates has reduced
804 // gradually over time. These dates are derived from the transitions noted in
805 // Section 1.2.2 (Relevant Dates) of the Baseline Requirements.
806 //
807 // * Certificates issued before BRs took effect, Chrome limited to max of ten
808 // years validity and a max notAfter date of 2019-07-01.
809 // * Last possible expiry: 2019-07-01.
810 //
811 // * Cerificates issued on-or-after the BR effective date of 1 July 2012: 60
812 // months.
813 // * Last possible expiry: 1 April 2015 + 60 months = 2020-04-01
814 //
815 // * Certificates issued on-or-after 1 April 2015: 39 months.
816 // * Last possible expiry: 1 March 2018 + 39 months = 2021-06-01
817 //
818 // * Certificates issued on-or-after 1 March 2018: 825 days.
819 // * Last possible expiry: 1 September 2020 + 825 days = 2022-12-05
820 //
821 // The current limit, from Chrome Root Certificate Policy:
822 // * Certificates issued on-or-after 1 September 2020: 398 days.
823
824 base::TimeDelta validity_duration = cert.valid_expiry() - cert.valid_start();
825
826 // No certificates issued before the latest lifetime requirement was enacted
827 // could possibly still be accepted, so we don't need to check the older
828 // limits explicitly.
829 return validity_duration > base::Days(398);
830 }
831
ImplParams()832 CertVerifyProc::ImplParams::ImplParams() {
833 crl_set = net::CRLSet::BuiltinCRLSet();
834 #if BUILDFLAG(CHROME_ROOT_STORE_OPTIONAL)
835 // Defaults to using Chrome Root Store, though we have to keep this option in
836 // here to allow WebView to turn this option off.
837 use_chrome_root_store = true;
838 #endif
839 }
840
841 CertVerifyProc::ImplParams::~ImplParams() = default;
842
843 CertVerifyProc::ImplParams::ImplParams(const ImplParams&) = default;
844 CertVerifyProc::ImplParams& CertVerifyProc::ImplParams::operator=(
845 const ImplParams& other) = default;
846 CertVerifyProc::ImplParams::ImplParams(ImplParams&&) = default;
847 CertVerifyProc::ImplParams& CertVerifyProc::ImplParams::operator=(
848 ImplParams&& other) = default;
849
850 CertVerifyProc::InstanceParams::InstanceParams() = default;
851 CertVerifyProc::InstanceParams::~InstanceParams() = default;
852
853 CertVerifyProc::InstanceParams::InstanceParams(const InstanceParams&) = default;
854 CertVerifyProc::InstanceParams& CertVerifyProc::InstanceParams::operator=(
855 const InstanceParams& other) = default;
856 CertVerifyProc::InstanceParams::InstanceParams(InstanceParams&&) = default;
857 CertVerifyProc::InstanceParams& CertVerifyProc::InstanceParams::operator=(
858 InstanceParams&& other) = default;
859
860 CertVerifyProc::CertificateWithConstraints::CertificateWithConstraints() =
861 default;
862 CertVerifyProc::CertificateWithConstraints::~CertificateWithConstraints() =
863 default;
864
865 CertVerifyProc::CertificateWithConstraints::CertificateWithConstraints(
866 const CertificateWithConstraints&) = default;
867 CertVerifyProc::CertificateWithConstraints&
868 CertVerifyProc::CertificateWithConstraints::operator=(
869 const CertificateWithConstraints& other) = default;
870 CertVerifyProc::CertificateWithConstraints::CertificateWithConstraints(
871 CertificateWithConstraints&&) = default;
872 CertVerifyProc::CertificateWithConstraints&
873 CertVerifyProc::CertificateWithConstraints::operator=(
874 CertificateWithConstraints&& other) = default;
875
876 } // namespace net
877