• 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 <memory>
8 #include <vector>
9 
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/functional/bind.h"
13 #include "base/functional/callback_helpers.h"
14 #include "base/logging.h"
15 #include "base/memory/raw_ptr.h"
16 #include "base/message_loop/message_pump_type.h"
17 #include "base/rand_util.h"
18 #include "base/ranges/algorithm.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_piece.h"
21 #include "base/strings/string_util.h"
22 #include "base/test/metrics/histogram_tester.h"
23 #include "base/test/scoped_feature_list.h"
24 #include "base/test/task_environment.h"
25 #include "base/threading/thread.h"
26 #include "base/time/time.h"
27 #include "build/build_config.h"
28 #include "crypto/sha2.h"
29 #include "net/base/net_errors.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_proc_builtin.h"
35 #include "net/cert/cert_verify_result.h"
36 #include "net/cert/crl_set.h"
37 #include "net/cert/ev_root_ca_metadata.h"
38 #include "net/cert/internal/system_trust_store.h"
39 #include "net/cert/test_root_certs.h"
40 #include "net/cert/x509_certificate.h"
41 #include "net/cert/x509_util.h"
42 #include "net/cert_net/cert_net_fetcher_url_request.h"
43 #include "net/log/test_net_log.h"
44 #include "net/proxy_resolution/proxy_config.h"
45 #include "net/proxy_resolution/proxy_config_service_fixed.h"
46 #include "net/test/cert_builder.h"
47 #include "net/test/cert_test_util.h"
48 #include "net/test/embedded_test_server/embedded_test_server.h"
49 #include "net/test/embedded_test_server/http_request.h"
50 #include "net/test/embedded_test_server/http_response.h"
51 #include "net/test/gtest_util.h"
52 #include "net/test/revocation_builder.h"
53 #include "net/test/test_certificate_data.h"
54 #include "net/test/test_data_directory.h"
55 #include "net/url_request/url_request_context.h"
56 #include "net/url_request/url_request_context_builder.h"
57 #include "net/url_request/url_request_context_getter.h"
58 #include "testing/gmock/include/gmock/gmock.h"
59 #include "testing/gtest/include/gtest/gtest.h"
60 #include "third_party/boringssl/src/include/openssl/bytestring.h"
61 #include "third_party/boringssl/src/include/openssl/mem.h"
62 #include "third_party/boringssl/src/include/openssl/pool.h"
63 #include "third_party/boringssl/src/pki/extended_key_usage.h"
64 #include "third_party/boringssl/src/pki/input.h"
65 #include "third_party/boringssl/src/pki/ocsp_revocation_status.h"
66 #include "third_party/boringssl/src/pki/parse_certificate.h"
67 #include "third_party/boringssl/src/pki/parser.h"
68 #include "third_party/boringssl/src/pki/pem.h"
69 #include "third_party/boringssl/src/pki/signature_algorithm.h"
70 #include "third_party/boringssl/src/pki/trust_store.h"
71 
72 #if BUILDFLAG(IS_ANDROID)
73 #include "net/cert/cert_verify_proc_android.h"
74 #elif BUILDFLAG(IS_IOS)
75 #include "base/ios/ios_util.h"
76 #include "net/cert/cert_verify_proc_ios.h"
77 #elif BUILDFLAG(IS_MAC)
78 #include "base/mac/mac_util.h"
79 #endif
80 
81 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
82 #include "net/cert/internal/trust_store_chrome.h"
83 #endif
84 
85 // TODO(crbug.com/649017): Add tests that only certificates with
86 // serverAuth are accepted.
87 
88 using net::test::IsError;
89 using net::test::IsOk;
90 
91 using base::HexEncode;
92 
93 namespace net {
94 
95 namespace {
96 
97 const char kTrustAnchorVerifyHistogram[] = "Net.Certificate.TrustAnchor.Verify";
98 const char kTrustAnchorVerifyOutOfDateHistogram[] =
99     "Net.Certificate.TrustAnchor.VerifyOutOfDate";
100 
101 // Returns a TLV to use as an unknown signature algorithm when building a cert.
102 // The specific contents are as follows (the OID is from
103 // https://davidben.net/oid):
104 //
105 // SEQUENCE {
106 //   OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.0 }
107 //   NULL {}
108 // }
TestOid0SignatureAlgorithmTLV()109 std::string TestOid0SignatureAlgorithmTLV() {
110   constexpr uint8_t kTestOid0SigAlgTLV[] = {0x30, 0x10, 0x06, 0x0c, 0x2a, 0x86,
111                                             0x48, 0x86, 0xf7, 0x12, 0x04, 0x01,
112                                             0x84, 0xb7, 0x09, 0x00, 0x05, 0x00};
113   return std::string(std::begin(kTestOid0SigAlgTLV),
114                      std::end(kTestOid0SigAlgTLV));
115 }
116 
117 // An OID for use in tests, from https://davidben.net/oid
118 // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.0 }
TestOid0()119 bssl::der::Input TestOid0() {
120   static uint8_t kTestOid0[] = {0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7,
121                                 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x00};
122   return bssl::der::Input(kTestOid0);
123 }
124 
125 // Mock CertVerifyProc that sets the CertVerifyResult to a given value for
126 // all certificates that are Verify()'d
127 class MockCertVerifyProc : public CertVerifyProc {
128  public:
MockCertVerifyProc(const CertVerifyResult & result)129   explicit MockCertVerifyProc(const CertVerifyResult& result)
130       : CertVerifyProc(CRLSet::BuiltinCRLSet()), result_(result) {}
MockCertVerifyProc(const CertVerifyResult & result,int error)131   MockCertVerifyProc(const CertVerifyResult& result, int error)
132       : CertVerifyProc(CRLSet::BuiltinCRLSet()),
133         result_(result),
134         error_(error) {}
135 
136   MockCertVerifyProc(const MockCertVerifyProc&) = delete;
137   MockCertVerifyProc& operator=(const MockCertVerifyProc&) = delete;
138 
139  protected:
140   ~MockCertVerifyProc() override = default;
141 
142  private:
143   int VerifyInternal(X509Certificate* cert,
144                      const std::string& hostname,
145                      const std::string& ocsp_response,
146                      const std::string& sct_list,
147                      int flags,
148                      CertVerifyResult* verify_result,
149                      const NetLogWithSource& net_log) override;
150 
151   const CertVerifyResult result_;
152   const int error_ = OK;
153 };
154 
VerifyInternal(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)155 int MockCertVerifyProc::VerifyInternal(X509Certificate* cert,
156                                        const std::string& hostname,
157                                        const std::string& ocsp_response,
158                                        const std::string& sct_list,
159                                        int flags,
160                                        CertVerifyResult* verify_result,
161                                        const NetLogWithSource& net_log) {
162   *verify_result = result_;
163   verify_result->verified_cert = cert;
164   return error_;
165 }
166 
167 // This enum identifies a concrete implemenation of CertVerifyProc.
168 //
169 // The type is erased by CreateCertVerifyProc(), however needs to be known for
170 // some of the test expectations.
171 enum CertVerifyProcType {
172   CERT_VERIFY_PROC_ANDROID,
173   CERT_VERIFY_PROC_IOS,
174   CERT_VERIFY_PROC_BUILTIN,
175   CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS,
176 };
177 
178 // Returns a textual description of the CertVerifyProc implementation
179 // that is being tested, used to give better names to parameterized
180 // tests.
VerifyProcTypeToName(const testing::TestParamInfo<CertVerifyProcType> & params)181 std::string VerifyProcTypeToName(
182     const testing::TestParamInfo<CertVerifyProcType>& params) {
183   switch (params.param) {
184     case CERT_VERIFY_PROC_ANDROID:
185       return "CertVerifyProcAndroid";
186     case CERT_VERIFY_PROC_IOS:
187       return "CertVerifyProcIOS";
188     case CERT_VERIFY_PROC_BUILTIN:
189       return "CertVerifyProcBuiltin";
190     case CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS:
191       return "CertVerifyProcBuiltinChromeRoots";
192   }
193 
194   return "";
195 }
196 
CreateCertVerifyProc(CertVerifyProcType type,scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set,CertificateList additional_trust_anchors,CertificateList additional_untrusted_authorities)197 scoped_refptr<CertVerifyProc> CreateCertVerifyProc(
198     CertVerifyProcType type,
199     scoped_refptr<CertNetFetcher> cert_net_fetcher,
200     scoped_refptr<CRLSet> crl_set,
201     CertificateList additional_trust_anchors,
202     CertificateList additional_untrusted_authorities) {
203   CertVerifyProc::InstanceParams instance_params;
204   instance_params.additional_trust_anchors = additional_trust_anchors;
205   instance_params.additional_untrusted_authorities =
206       additional_untrusted_authorities;
207   switch (type) {
208 #if BUILDFLAG(IS_ANDROID)
209     case CERT_VERIFY_PROC_ANDROID:
210       return base::MakeRefCounted<CertVerifyProcAndroid>(
211           std::move(cert_net_fetcher), std::move(crl_set));
212 #elif BUILDFLAG(IS_IOS)
213     case CERT_VERIFY_PROC_IOS:
214       return base::MakeRefCounted<CertVerifyProcIOS>(std::move(crl_set));
215 #endif
216 #if BUILDFLAG(IS_FUCHSIA)
217     case CERT_VERIFY_PROC_BUILTIN:
218       return CreateCertVerifyProcBuiltin(
219           std::move(cert_net_fetcher), std::move(crl_set),
220           CreateSslSystemTrustStore(), instance_params);
221 #endif
222 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
223     case CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS:
224       return CreateCertVerifyProcBuiltin(
225           std::move(cert_net_fetcher), std::move(crl_set),
226           CreateSslSystemTrustStoreChromeRoot(
227               std::make_unique<net::TrustStoreChrome>()),
228           instance_params);
229 #endif
230     default:
231       return nullptr;
232   }
233 }
234 
235 // The set of all CertVerifyProcTypes that tests should be parameterized on.
236 // This needs to be kept in sync with CertVerifyProc::CreateSystemVerifyProc()
237 // and the platforms where CreateSslSystemTrustStore() is not a dummy store.
238 // TODO(crbug.com/649017): Enable CERT_VERIFY_PROC_BUILTIN everywhere. Right
239 // now this is gated on having CertVerifyProcBuiltin understand the roots added
240 // via TestRootCerts.
241 constexpr CertVerifyProcType kAllCertVerifiers[] = {
242 #if BUILDFLAG(IS_ANDROID)
243     CERT_VERIFY_PROC_ANDROID,
244 #elif BUILDFLAG(IS_IOS)
245     CERT_VERIFY_PROC_IOS,
246 #elif BUILDFLAG(IS_FUCHSIA)
247     CERT_VERIFY_PROC_BUILTIN,
248 #endif
249 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
250     CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS,
251 #endif
252 };
253 static_assert(std::size(kAllCertVerifiers) != 0, "Unsupported platform");
254 
255 // Returns true if a test root added through ScopedTestRoot can verify
256 // successfully as a target certificate with chain of length 1 on the given
257 // CertVerifyProcType.
ScopedTestRootCanTrustTargetCert(CertVerifyProcType verify_proc_type)258 bool ScopedTestRootCanTrustTargetCert(CertVerifyProcType verify_proc_type) {
259   return verify_proc_type == CERT_VERIFY_PROC_IOS ||
260          verify_proc_type == CERT_VERIFY_PROC_ANDROID;
261 }
262 
263 // Returns true if a non-self-signed CA certificate added through
264 // ScopedTestRoot can verify successfully as the root of a chain by the given
265 // CertVerifyProcType.
ScopedTestRootCanTrustIntermediateCert(CertVerifyProcType verify_proc_type)266 bool ScopedTestRootCanTrustIntermediateCert(
267     CertVerifyProcType verify_proc_type) {
268   return verify_proc_type == CERT_VERIFY_PROC_IOS ||
269          verify_proc_type == CERT_VERIFY_PROC_BUILTIN ||
270          verify_proc_type == CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS ||
271          verify_proc_type == CERT_VERIFY_PROC_ANDROID;
272 }
273 
MakeRandomHexString(size_t num_bytes)274 std::string MakeRandomHexString(size_t num_bytes) {
275   std::vector<char> rand_bytes;
276   rand_bytes.resize(num_bytes);
277 
278   base::RandBytes(rand_bytes.data(), rand_bytes.size());
279   return base::HexEncode(rand_bytes.data(), rand_bytes.size());
280 }
281 
282 }  // namespace
283 
284 // This fixture is for tests that apply to concrete implementations of
285 // CertVerifyProc. It will be run for all of the concrete CertVerifyProc types.
286 //
287 // It is called "Internal" as it tests the internal methods like
288 // "VerifyInternal()".
289 class CertVerifyProcInternalTest
290     : public testing::TestWithParam<CertVerifyProcType> {
291  protected:
SetUp()292   void SetUp() override { SetUpCertVerifyProc(CRLSet::BuiltinCRLSet()); }
293 
294   // CertNetFetcher may be initialized by subclasses that want to use net
295   // fetching by calling SetUpWithCertNetFetcher instead of SetUp.
SetUpWithCertNetFetcher(scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set,CertificateList additional_trust_anchors,CertificateList additional_untrusted_authorities)296   void SetUpWithCertNetFetcher(
297       scoped_refptr<CertNetFetcher> cert_net_fetcher,
298       scoped_refptr<CRLSet> crl_set,
299       CertificateList additional_trust_anchors,
300       CertificateList additional_untrusted_authorities) {
301     CertVerifyProcType type = verify_proc_type();
302     verify_proc_ = CreateCertVerifyProc(
303         type, std::move(cert_net_fetcher), std::move(crl_set),
304         additional_trust_anchors, additional_untrusted_authorities);
305     ASSERT_TRUE(verify_proc_);
306   }
307 
SetUpCertVerifyProc(scoped_refptr<CRLSet> crl_set)308   virtual void SetUpCertVerifyProc(scoped_refptr<CRLSet> crl_set) {
309     SetUpWithCertNetFetcher(nullptr, std::move(crl_set),
310                             /*additional_trust_anchors=*/{},
311                             /*additional_untrusted_authorities=*/{});
312   }
313 
SetUpWithAdditionalCerts(CertificateList additional_trust_anchors,CertificateList additional_untrusted_authorities)314   virtual void SetUpWithAdditionalCerts(
315       CertificateList additional_trust_anchors,
316       CertificateList additional_untrusted_authorities) {
317     SetUpWithCertNetFetcher(nullptr, CRLSet::BuiltinCRLSet(),
318                             additional_trust_anchors,
319                             additional_untrusted_authorities);
320   }
321 
Verify(X509Certificate * cert,const std::string & hostname,int flags,CertVerifyResult * verify_result,const NetLogWithSource & net_log)322   int Verify(X509Certificate* cert,
323              const std::string& hostname,
324              int flags,
325              CertVerifyResult* verify_result,
326              const NetLogWithSource& net_log) {
327     return verify_proc_->Verify(cert, hostname, /*ocsp_response=*/std::string(),
328                                 /*sct_list=*/std::string(), flags,
329                                 verify_result, net_log);
330   }
331 
Verify(X509Certificate * cert,const std::string & hostname,int flags,CertVerifyResult * verify_result)332   int Verify(X509Certificate* cert,
333              const std::string& hostname,
334              int flags,
335              CertVerifyResult* verify_result) {
336     return Verify(cert, hostname, flags, verify_result, NetLogWithSource());
337   }
338 
Verify(X509Certificate * cert,const std::string & hostname)339   int Verify(X509Certificate* cert, const std::string& hostname) {
340     CertVerifyResult verify_result;
341     int flags = 0;
342     return Verify(cert, hostname, flags, &verify_result);
343   }
344 
verify_proc_type() const345   CertVerifyProcType verify_proc_type() const { return GetParam(); }
346 
347   // Returns true if the RSA/DSA keysize will be considered weak on the current
348   // platform. IsInvalidRsaDsaKeySize should be checked prior, since some very
349   // weak keys may be considered invalid.
IsWeakRsaDsaKeySize(int size) const350   bool IsWeakRsaDsaKeySize(int size) const {
351 #if BUILDFLAG(IS_IOS)
352     // Beginning with iOS 13, the minimum key size for RSA/DSA algorithms is
353     // 2048 bits. See https://support.apple.com/en-us/HT210176
354     if (verify_proc_type() == CERT_VERIFY_PROC_IOS &&
355         base::ios::IsRunningOnIOS13OrLater()) {
356       return size < 2048;
357     }
358 #endif
359 
360     return size < 1024;
361   }
362 
363   // Returns true if the RSA/DSA keysize will be considered invalid on the
364   // current platform.
IsInvalidRsaDsaKeySize(int size) const365   bool IsInvalidRsaDsaKeySize(int size) const {
366 #if BUILDFLAG(IS_IOS)
367     if (base::ios::IsRunningOnIOS12OrLater()) {
368       // On iOS using SecTrustEvaluateWithError it is not possible to
369       // distinguish between weak and invalid key sizes.
370       return IsWeakRsaDsaKeySize(size);
371     }
372 #endif
373 
374     // This platform does not mark certificates with weak keys as invalid.
375     return false;
376   }
377 
ParseKeyType(const std::string & key_type,std::string * type,int * size)378   static bool ParseKeyType(const std::string& key_type,
379                            std::string* type,
380                            int* size) {
381     size_t pos = key_type.find("-");
382     *type = key_type.substr(0, pos);
383     std::string size_str = key_type.substr(pos + 1);
384     return base::StringToInt(size_str, size);
385   }
386 
387   // Some platforms may reject certificates with very weak keys as invalid.
IsInvalidKeyType(const std::string & key_type) const388   bool IsInvalidKeyType(const std::string& key_type) const {
389     std::string type;
390     int size = 0;
391     if (!ParseKeyType(key_type, &type, &size))
392       return false;
393 
394     if (type == "rsa" || type == "dsa")
395       return IsInvalidRsaDsaKeySize(size);
396 
397     return false;
398   }
399 
400   // Currently, only RSA and DSA keys are checked for weakness, and our example
401   // weak size is 768. These could change in the future.
402   //
403   // Note that this means there may be false negatives: keys for other
404   // algorithms and which are weak will pass this test.
405   //
406   // Also, IsInvalidKeyType should be checked prior, since some weak keys may be
407   // considered invalid.
IsWeakKeyType(const std::string & key_type) const408   bool IsWeakKeyType(const std::string& key_type) const {
409     std::string type;
410     int size = 0;
411     if (!ParseKeyType(key_type, &type, &size))
412       return false;
413 
414     if (type == "rsa" || type == "dsa")
415       return IsWeakRsaDsaKeySize(size);
416 
417     return false;
418   }
419 
SupportsCRLSet() const420   bool SupportsCRLSet() const { return VerifyProcTypeIsBuiltin(); }
421 
SupportsCRLSetsInPathBuilding() const422   bool SupportsCRLSetsInPathBuilding() const {
423     return VerifyProcTypeIsBuiltin();
424   }
425 
SupportsEV() const426   bool SupportsEV() const {
427     // Android and iOS do not support EV.  See https://crbug.com/117478#7
428 #if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
429     return true;
430 #else
431     return false;
432 #endif
433   }
434 
SupportsSoftFailRevChecking() const435   bool SupportsSoftFailRevChecking() const { return VerifyProcTypeIsBuiltin(); }
436 
SupportsRevCheckingRequiredLocalAnchors() const437   bool SupportsRevCheckingRequiredLocalAnchors() const {
438     return VerifyProcTypeIsBuiltin();
439   }
440 
VerifyProcTypeIsBuiltin() const441   bool VerifyProcTypeIsBuiltin() const {
442     return verify_proc_type() == CERT_VERIFY_PROC_BUILTIN ||
443            verify_proc_type() == CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS;
444   }
445 
VerifyProcTypeIsIOSAtMostOS14() const446   bool VerifyProcTypeIsIOSAtMostOS14() const {
447 #if BUILDFLAG(IS_IOS)
448     if (verify_proc_type() == CERT_VERIFY_PROC_IOS &&
449         !base::ios::IsRunningOnIOS15OrLater()) {
450       return true;
451     }
452 #endif
453     return false;
454   }
455 
VerifyProcTypeIsIOSAtMostOS15() const456   bool VerifyProcTypeIsIOSAtMostOS15() const {
457 #if BUILDFLAG(IS_IOS)
458     if (verify_proc_type() == CERT_VERIFY_PROC_IOS &&
459         !base::ios::IsRunningOnIOS16OrLater()) {
460       return true;
461     }
462 #endif
463     return false;
464   }
465 
verify_proc() const466   CertVerifyProc* verify_proc() const { return verify_proc_.get(); }
467 
468  private:
469   scoped_refptr<CertVerifyProc> verify_proc_;
470 };
471 
472 INSTANTIATE_TEST_SUITE_P(All,
473                          CertVerifyProcInternalTest,
474                          testing::ValuesIn(kAllCertVerifiers),
475                          VerifyProcTypeToName);
476 
TEST_P(CertVerifyProcInternalTest,DistrustedIntermediate)477 TEST_P(CertVerifyProcInternalTest, DistrustedIntermediate) {
478   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
479   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
480   constexpr char kHostname[] = "www.example.com";
481 
482   // Chain should not verify without any ScopedTestRoots.
483   EXPECT_THAT(Verify(chain.get(), kHostname),
484               IsError(ERR_CERT_AUTHORITY_INVALID));
485 
486   // Trusting root should cause chain to verify successfully.
487   ScopedTestRoot trust_root(root->GetX509Certificate(),
488                             bssl::CertificateTrust::ForTrustAnchor());
489   EXPECT_THAT(Verify(chain.get(), kHostname), IsOk());
490 
491   ScopedTestRoot distrust_intermediate(intermediate->GetX509Certificate(),
492                                        bssl::CertificateTrust::ForDistrusted());
493   if (VerifyProcTypeIsBuiltin()) {
494     // Distrusting intermediate should cause chain to not verify again.
495     EXPECT_THAT(Verify(chain.get(), kHostname),
496                 IsError(ERR_CERT_AUTHORITY_INVALID));
497   } else {
498     // Specifying trust types for the platform verifiers through ScopedTestRoot
499     // is not supported, so this should still verify successfully.
500     EXPECT_THAT(Verify(chain.get(), kHostname), IsOk());
501   }
502 }
503 
504 // Tests that a certificate is recognized as EV, when the valid EV policy OID
505 // for the trust anchor is the second candidate EV oid in the target
506 // certificate. This is a regression test for crbug.com/705285.
TEST_P(CertVerifyProcInternalTest,EVVerificationMultipleOID)507 TEST_P(CertVerifyProcInternalTest, EVVerificationMultipleOID) {
508   if (!SupportsEV()) {
509     LOG(INFO) << "Skipping test as EV verification is not yet supported";
510     return;
511   }
512 
513   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
514 
515   // The policies that target certificate asserts.
516   static const char kOtherTestCertPolicy[] = "2.23.140.1.1";
517   static const char kEVTestCertPolicy[] = "1.2.3.4";
518   // Specify the extraneous policy first, then the actual policy.
519   leaf->SetCertificatePolicies({kOtherTestCertPolicy, kEVTestCertPolicy});
520 
521   scoped_refptr<X509Certificate> cert = leaf->GetX509Certificate();
522   ScopedTestRoot test_root(root->GetX509Certificate());
523 
524   // Build a CRLSet that covers the target certificate.
525   //
526   // This way CRLSet coverage will be sufficient for EV revocation checking,
527   // so this test does not depend on online revocation checking.
528   base::StringPiece spki;
529   ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(
530       x509_util::CryptoBufferAsStringPiece(root->GetCertBuffer()), &spki));
531   SHA256HashValue spki_sha256;
532   crypto::SHA256HashString(spki, spki_sha256.data, sizeof(spki_sha256.data));
533   SetUpCertVerifyProc(CRLSet::ForTesting(false, &spki_sha256, "", "", {}));
534 
535   // Consider the root of the test chain a valid EV root for the test policy.
536   ScopedTestEVPolicy scoped_test_ev_policy(
537       EVRootCAMetadata::GetInstance(),
538       X509Certificate::CalculateFingerprint256(root->GetCertBuffer()),
539       kEVTestCertPolicy);
540   ScopedTestEVPolicy scoped_test_other_policy(
541       EVRootCAMetadata::GetInstance(), SHA256HashValue(), kOtherTestCertPolicy);
542 
543   CertVerifyResult verify_result;
544   int flags = 0;
545   int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
546   EXPECT_THAT(error, IsOk());
547   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
548 }
549 
550 // Target cert has an EV policy, and verifies successfully, but has a chain of
551 // length 1 because the target cert was directly trusted in the trust store.
552 // Should verify OK but not with STATUS_IS_EV.
TEST_P(CertVerifyProcInternalTest,TrustedTargetCertWithEVPolicy)553 TEST_P(CertVerifyProcInternalTest, TrustedTargetCertWithEVPolicy) {
554   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
555 
556   static const char kEVTestCertPolicy[] = "1.2.3.4";
557   leaf->SetCertificatePolicies({kEVTestCertPolicy});
558   ScopedTestEVPolicy scoped_test_ev_policy(
559       EVRootCAMetadata::GetInstance(), SHA256HashValue(), kEVTestCertPolicy);
560 
561   scoped_refptr<X509Certificate> cert = leaf->GetX509Certificate();
562   ScopedTestRoot scoped_test_root(cert);
563 
564   CertVerifyResult verify_result;
565   int flags = 0;
566   int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
567   if (ScopedTestRootCanTrustTargetCert(verify_proc_type())) {
568     EXPECT_THAT(error, IsOk());
569     ASSERT_TRUE(verify_result.verified_cert);
570     EXPECT_TRUE(verify_result.verified_cert->intermediate_buffers().empty());
571   } else {
572     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
573   }
574   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
575 }
576 
577 // Target cert has an EV policy, and verifies successfully with a chain of
578 // length 1, and its fingerprint matches the cert fingerprint for that ev
579 // policy. This should never happen in reality, but just test that things don't
580 // explode if it does.
TEST_P(CertVerifyProcInternalTest,TrustedTargetCertWithEVPolicyAndEVFingerprint)581 TEST_P(CertVerifyProcInternalTest,
582        TrustedTargetCertWithEVPolicyAndEVFingerprint) {
583   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
584 
585   static const char kEVTestCertPolicy[] = "1.2.3.4";
586   leaf->SetCertificatePolicies({kEVTestCertPolicy});
587   ScopedTestEVPolicy scoped_test_ev_policy(
588       EVRootCAMetadata::GetInstance(),
589       X509Certificate::CalculateFingerprint256(leaf->GetCertBuffer()),
590       kEVTestCertPolicy);
591   scoped_refptr<X509Certificate> cert = leaf->GetX509Certificate();
592   ScopedTestRoot scoped_test_root(cert);
593 
594   CertVerifyResult verify_result;
595   int flags = 0;
596   int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
597   if (ScopedTestRootCanTrustTargetCert(verify_proc_type())) {
598     EXPECT_THAT(error, IsOk());
599     ASSERT_TRUE(verify_result.verified_cert);
600     EXPECT_TRUE(verify_result.verified_cert->intermediate_buffers().empty());
601   } else {
602     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
603   }
604   // An EV Root certificate should never be used as an end-entity certificate.
605   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
606 }
607 
608 // Target cert has an EV policy, and has a valid path to the EV root, but the
609 // intermediate has been trusted directly. Should stop building the path at the
610 // intermediate and verify OK but not with STATUS_IS_EV.
611 // See https://crbug.com/979801
TEST_P(CertVerifyProcInternalTest,TrustedIntermediateCertWithEVPolicy)612 TEST_P(CertVerifyProcInternalTest, TrustedIntermediateCertWithEVPolicy) {
613   if (!SupportsEV()) {
614     LOG(INFO) << "Skipping test as EV verification is not yet supported";
615     return;
616   }
617   if (!ScopedTestRootCanTrustIntermediateCert(verify_proc_type())) {
618     LOG(INFO) << "Skipping test as intermediate cert cannot be trusted";
619     return;
620   }
621 
622   for (bool trust_the_intermediate : {false, true}) {
623     SCOPED_TRACE(trust_the_intermediate);
624 
625     // Need to build unique certs for each try otherwise caching can break
626     // things.
627     auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
628 
629     static const char kEVTestCertPolicy[] = "1.2.3.4";
630     leaf->SetCertificatePolicies({kEVTestCertPolicy});
631     intermediate->SetCertificatePolicies({kEVTestCertPolicy});
632     // Consider the root of the test chain a valid EV root for the test policy.
633     ScopedTestEVPolicy scoped_test_ev_policy(
634         EVRootCAMetadata::GetInstance(),
635         X509Certificate::CalculateFingerprint256(root->GetCertBuffer()),
636         kEVTestCertPolicy);
637 
638     scoped_refptr<X509Certificate> cert = leaf->GetX509CertificateChain();
639     ASSERT_TRUE(cert.get());
640 
641     scoped_refptr<X509Certificate> intermediate_cert =
642         intermediate->GetX509Certificate();
643     ASSERT_TRUE(intermediate_cert.get());
644 
645     scoped_refptr<X509Certificate> root_cert = root->GetX509Certificate();
646     ASSERT_TRUE(root_cert.get());
647 
648     if (!trust_the_intermediate) {
649       // First trust just the root. This verifies that the test setup is
650       // actually correct.
651       ScopedTestRoot scoped_test_root({root_cert});
652       CertVerifyResult verify_result;
653       int flags = 0;
654       int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
655       EXPECT_THAT(error, IsOk());
656       ASSERT_TRUE(verify_result.verified_cert);
657       // Verified chain should include the intermediate and the root.
658       EXPECT_EQ(2U, verify_result.verified_cert->intermediate_buffers().size());
659       // Should be EV.
660       EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
661     } else {
662       // Now try with trusting both the intermediate and the root.
663       ScopedTestRoot scoped_test_root({intermediate_cert, root_cert});
664       CertVerifyResult verify_result;
665       int flags = 0;
666       int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
667       EXPECT_THAT(error, IsOk());
668       ASSERT_TRUE(verify_result.verified_cert);
669       // Verified chain should only go to the trusted intermediate, not the
670       // root.
671       EXPECT_EQ(1U, verify_result.verified_cert->intermediate_buffers().size());
672       // Should not be EV.
673       EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
674     }
675   }
676 }
677 
TEST_P(CertVerifyProcInternalTest,CertWithNullInCommonNameAndNoSAN)678 TEST_P(CertVerifyProcInternalTest, CertWithNullInCommonNameAndNoSAN) {
679   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
680 
681   leaf->EraseExtension(bssl::der::Input(bssl::kSubjectAltNameOid));
682 
683   std::string common_name;
684   common_name += "www.fake.com";
685   common_name += '\0';
686   common_name += "a" + MakeRandomHexString(12) + ".example.com";
687   leaf->SetSubjectCommonName(common_name);
688 
689   // Trust the root and build a chain to verify that includes the intermediate.
690   ScopedTestRoot scoped_root(root->GetX509Certificate());
691   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
692   ASSERT_TRUE(chain.get());
693 
694   int flags = 0;
695   CertVerifyResult verify_result;
696   int error = Verify(chain.get(), "www.fake.com", flags, &verify_result);
697 
698   // This actually fails because Chrome only looks for hostnames in
699   // SubjectAltNames now and no SubjectAltName is present.
700   EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
701 }
702 
TEST_P(CertVerifyProcInternalTest,CertWithNullInCommonNameAndValidSAN)703 TEST_P(CertVerifyProcInternalTest, CertWithNullInCommonNameAndValidSAN) {
704   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
705 
706   leaf->SetSubjectAltName("www.fake.com");
707 
708   std::string common_name;
709   common_name += "www.fake.com";
710   common_name += '\0';
711   common_name += "a" + MakeRandomHexString(12) + ".example.com";
712   leaf->SetSubjectCommonName(common_name);
713 
714   // Trust the root and build a chain to verify that includes the intermediate.
715   ScopedTestRoot scoped_root(root->GetX509Certificate());
716   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
717   ASSERT_TRUE(chain.get());
718 
719   int flags = 0;
720   CertVerifyResult verify_result;
721   int error = Verify(chain.get(), "www.fake.com", flags, &verify_result);
722 
723   // SubjectAltName is valid and Chrome does not use the common name.
724   EXPECT_THAT(error, IsOk());
725 }
726 
TEST_P(CertVerifyProcInternalTest,CertWithNullInSAN)727 TEST_P(CertVerifyProcInternalTest, CertWithNullInSAN) {
728   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
729 
730   std::string hostname;
731   hostname += "www.fake.com";
732   hostname += '\0';
733   hostname += "a" + MakeRandomHexString(12) + ".example.com";
734   leaf->SetSubjectAltName(hostname);
735 
736   // Trust the root and build a chain to verify that includes the intermediate.
737   ScopedTestRoot scoped_root(root->GetX509Certificate());
738   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
739   ASSERT_TRUE(chain.get());
740 
741   int flags = 0;
742   CertVerifyResult verify_result;
743   int error = Verify(chain.get(), "www.fake.com", flags, &verify_result);
744 
745   // SubjectAltName is invalid.
746   EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
747 }
748 
749 // Tests the case where the target certificate is accepted by
750 // X509CertificateBytes, but has errors that should cause verification to fail.
TEST_P(CertVerifyProcInternalTest,InvalidTarget)751 TEST_P(CertVerifyProcInternalTest, InvalidTarget) {
752   base::FilePath certs_dir =
753       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
754   scoped_refptr<X509Certificate> bad_cert;
755   if (VerifyProcTypeIsBuiltin()) {
756     // Builtin verifier doesn't distinguish between invalid signature algorithm
757     // and unknown signature algorithm, so use a different test file that will
758     // fail in bssl::ParsedCertificate::Create. The other verifiers use a
759     // different test file since the platform verifiers don't all consider empty
760     // extensions sequence invalid.
761     bad_cert = ImportCertFromFile(certs_dir, "extensions_empty_sequence.pem");
762   } else {
763     bad_cert = ImportCertFromFile(certs_dir, "signature_algorithm_null.pem");
764   }
765   ASSERT_TRUE(bad_cert);
766 
767   scoped_refptr<X509Certificate> ok_cert(
768       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
769   ASSERT_TRUE(ok_cert);
770 
771   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
772   intermediates.push_back(bssl::UpRef(ok_cert->cert_buffer()));
773   scoped_refptr<X509Certificate> cert_with_bad_target(
774       X509Certificate::CreateFromBuffer(bssl::UpRef(bad_cert->cert_buffer()),
775                                         std::move(intermediates)));
776   ASSERT_TRUE(cert_with_bad_target);
777   EXPECT_EQ(1U, cert_with_bad_target->intermediate_buffers().size());
778 
779   int flags = 0;
780   CertVerifyResult verify_result;
781   int error =
782       Verify(cert_with_bad_target.get(), "127.0.0.1", flags, &verify_result);
783 
784   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
785   EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
786 }
787 
788 // Tests the case where an intermediate certificate is accepted by
789 // X509CertificateBytes, but has errors that should prevent using it during
790 // verification.  The verification should succeed, since the intermediate
791 // wasn't necessary.
TEST_P(CertVerifyProcInternalTest,UnnecessaryInvalidIntermediate)792 TEST_P(CertVerifyProcInternalTest, UnnecessaryInvalidIntermediate) {
793   ScopedTestRoot test_root(
794       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"));
795 
796   base::FilePath certs_dir =
797       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
798   bssl::UniquePtr<CRYPTO_BUFFER> bad_cert =
799       x509_util::CreateCryptoBuffer(base::StringPiece("invalid"));
800   ASSERT_TRUE(bad_cert);
801 
802   scoped_refptr<X509Certificate> ok_cert(
803       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
804   ASSERT_TRUE(ok_cert);
805 
806   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
807   intermediates.push_back(std::move(bad_cert));
808   scoped_refptr<X509Certificate> cert_with_bad_intermediate(
809       X509Certificate::CreateFromBuffer(bssl::UpRef(ok_cert->cert_buffer()),
810                                         std::move(intermediates)));
811   ASSERT_TRUE(cert_with_bad_intermediate);
812   EXPECT_EQ(1U, cert_with_bad_intermediate->intermediate_buffers().size());
813 
814   RecordingNetLogObserver net_log_observer(NetLogCaptureMode::kDefault);
815   NetLogWithSource net_log(NetLogWithSource::Make(
816       net::NetLog::Get(), net::NetLogSourceType::CERT_VERIFIER_TASK));
817   int flags = 0;
818   CertVerifyResult verify_result;
819   int error = Verify(cert_with_bad_intermediate.get(), "127.0.0.1", flags,
820                      &verify_result, net_log);
821 
822   EXPECT_THAT(error, IsOk());
823   EXPECT_EQ(0u, verify_result.cert_status);
824 
825   auto events = net_log_observer.GetEntriesForSource(net_log.source());
826   EXPECT_FALSE(events.empty());
827 
828   auto event = base::ranges::find(events, NetLogEventType::CERT_VERIFY_PROC,
829                                   &NetLogEntry::type);
830   ASSERT_NE(event, events.end());
831   EXPECT_EQ(net::NetLogEventPhase::BEGIN, event->phase);
832   const std::string* host = event->params.FindString("host");
833   ASSERT_TRUE(host);
834   EXPECT_EQ("127.0.0.1", *host);
835 
836   if (VerifyProcTypeIsBuiltin()) {
837     event =
838         base::ranges::find(events, NetLogEventType::CERT_VERIFY_PROC_INPUT_CERT,
839                            &NetLogEntry::type);
840     ASSERT_NE(event, events.end());
841     EXPECT_EQ(net::NetLogEventPhase::NONE, event->phase);
842     const std::string* errors = event->params.FindString("errors");
843     ASSERT_TRUE(errors);
844     EXPECT_EQ(
845         "ERROR: Failed parsing Certificate SEQUENCE\nERROR: Failed parsing "
846         "Certificate\n",
847         *errors);
848   }
849 }
850 
TEST_P(CertVerifyProcInternalTest,RejectExpiredCert)851 TEST_P(CertVerifyProcInternalTest, RejectExpiredCert) {
852   base::FilePath certs_dir = GetTestCertsDirectory();
853 
854   // Load root_ca_cert.pem into the test root store.
855   ScopedTestRoot test_root(ImportCertFromFile(certs_dir, "root_ca_cert.pem"));
856 
857   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
858       certs_dir, "expired_cert.pem", X509Certificate::FORMAT_AUTO);
859   ASSERT_TRUE(cert);
860   ASSERT_EQ(0U, cert->intermediate_buffers().size());
861 
862   int flags = 0;
863   CertVerifyResult verify_result;
864   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
865   EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
866   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
867 }
868 
TEST_P(CertVerifyProcInternalTest,RejectWeakKeys)869 TEST_P(CertVerifyProcInternalTest, RejectWeakKeys) {
870   base::FilePath certs_dir = GetTestCertsDirectory();
871   typedef std::vector<std::string> Strings;
872   Strings key_types;
873 
874   // These values mush match the prefixes of the key filenames generated by
875   // generate-test-keys.sh:
876   key_types.push_back("rsa-768");
877   key_types.push_back("rsa-1024");
878   key_types.push_back("rsa-2048");
879   key_types.push_back("ec-prime256v1");
880 
881   // Now test each chain.
882   for (const std::string& ee_type : key_types) {
883     for (const std::string& signer_type : key_types) {
884       SCOPED_TRACE("ee_type:" + ee_type + " signer_type:" + signer_type);
885 
886       auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
887 
888       ASSERT_TRUE(
889           leaf->UseKeyFromFile(certs_dir.AppendASCII(ee_type + "-1.key")));
890       ASSERT_TRUE(intermediate->UseKeyFromFile(
891           certs_dir.AppendASCII(signer_type + "-2.key")));
892 
893       ScopedTestRoot scoped_root(root->GetX509Certificate());
894 
895       CertVerifyResult verify_result;
896       int error = Verify(leaf->GetX509CertificateChain().get(),
897                          "www.example.com", 0, &verify_result);
898 
899       if (IsInvalidKeyType(ee_type) || IsInvalidKeyType(signer_type)) {
900         EXPECT_NE(OK, error);
901         EXPECT_EQ(CERT_STATUS_INVALID,
902                   verify_result.cert_status & CERT_STATUS_INVALID);
903       } else if (IsWeakKeyType(ee_type) || IsWeakKeyType(signer_type)) {
904         EXPECT_NE(OK, error);
905         EXPECT_EQ(CERT_STATUS_WEAK_KEY,
906                   verify_result.cert_status & CERT_STATUS_WEAK_KEY);
907         EXPECT_EQ(0u, verify_result.cert_status & CERT_STATUS_INVALID);
908       } else {
909         EXPECT_THAT(error, IsOk());
910         EXPECT_EQ(0U, verify_result.cert_status & CERT_STATUS_WEAK_KEY);
911       }
912     }
913   }
914 }
915 
916 // Regression test for http://crbug.com/108514.
917 // Generates a chain with a root with a SHA256 signature, and another root with
918 // the same name/SPKI/keyid but with a SHA1 signature. The SHA256 root is
919 // trusted. The SHA1 certificate is supplied as an extra cert, but should be
920 // ignored as the verifier should prefer the trusted cert when path building
921 // from the leaf, generating the shortest chain of "leaf -> sha256root". If the
922 // path builder doesn't prioritize it could build an unoptimal but valid path
923 // like "leaf -> sha1root -> sha256root".
TEST_P(CertVerifyProcInternalTest,ExtraneousRootCert)924 TEST_P(CertVerifyProcInternalTest, ExtraneousRootCert) {
925   auto [leaf_builder, root_builder] = CertBuilder::CreateSimpleChain2();
926 
927   root_builder->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha256);
928   scoped_refptr<X509Certificate> root_cert = root_builder->GetX509Certificate();
929 
930   scoped_refptr<X509Certificate> server_cert =
931       leaf_builder->GetX509Certificate();
932 
933   // Use the same root_builder but with a new serial number and setting the
934   // signature to SHA1, to generate an extraneous self-signed certificate that
935   // also signs the leaf cert and which could be used in path-building if the
936   // path builder doesn't prioritize trusted roots above other certs.
937   root_builder->SetRandomSerialNumber();
938   root_builder->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha1);
939   scoped_refptr<X509Certificate> extra_cert =
940       root_builder->GetX509Certificate();
941 
942   ScopedTestRoot scoped_root(root_cert);
943 
944   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
945   intermediates.push_back(bssl::UpRef(extra_cert->cert_buffer()));
946   scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromBuffer(
947       bssl::UpRef(server_cert->cert_buffer()), std::move(intermediates));
948   ASSERT_TRUE(cert_chain);
949 
950   CertVerifyResult verify_result;
951   int flags = 0;
952   int error =
953       Verify(cert_chain.get(), "www.example.com", flags, &verify_result);
954   EXPECT_THAT(error, IsOk());
955 
956   // The extra root should be discarded.
957   ASSERT_TRUE(verify_result.verified_cert.get());
958   ASSERT_EQ(1u, verify_result.verified_cert->intermediate_buffers().size());
959   EXPECT_TRUE(x509_util::CryptoBufferEqual(
960       verify_result.verified_cert->intermediate_buffers().front().get(),
961       root_cert->cert_buffer()));
962 }
963 
964 // Test for bug 94673.
TEST_P(CertVerifyProcInternalTest,GoogleDigiNotarTest)965 TEST_P(CertVerifyProcInternalTest, GoogleDigiNotarTest) {
966   base::FilePath certs_dir = GetTestCertsDirectory();
967 
968   scoped_refptr<X509Certificate> server_cert =
969       ImportCertFromFile(certs_dir, "google_diginotar.pem");
970   ASSERT_NE(static_cast<X509Certificate*>(nullptr), server_cert.get());
971 
972   scoped_refptr<X509Certificate> intermediate_cert =
973       ImportCertFromFile(certs_dir, "diginotar_public_ca_2025.pem");
974   ASSERT_NE(static_cast<X509Certificate*>(nullptr), intermediate_cert.get());
975 
976   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
977   intermediates.push_back(bssl::UpRef(intermediate_cert->cert_buffer()));
978   scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromBuffer(
979       bssl::UpRef(server_cert->cert_buffer()), std::move(intermediates));
980   ASSERT_TRUE(cert_chain);
981 
982   CertVerifyResult verify_result;
983   int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
984   int error =
985       Verify(cert_chain.get(), "mail.google.com", flags, &verify_result);
986   EXPECT_NE(OK, error);
987 
988   // Now turn off revocation checking.  Certificate verification should still
989   // fail.
990   flags = 0;
991   error = Verify(cert_chain.get(), "mail.google.com", flags, &verify_result);
992   EXPECT_NE(OK, error);
993 }
994 
TEST_P(CertVerifyProcInternalTest,NameConstraintsOk)995 TEST_P(CertVerifyProcInternalTest, NameConstraintsOk) {
996   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
997 
998   // Use the private key matching the public_key_hash of the kDomainsTest
999   // constraint in CertVerifyProc::HasNameConstraintsViolation.
1000   ASSERT_TRUE(leaf->UseKeyFromFile(
1001       GetTestCertsDirectory().AppendASCII("name_constrained_key.pem")));
1002   // example.com is allowed by kDomainsTest, and notarealtld is not a known
1003   // TLD, so that's allowed too.
1004   leaf->SetSubjectAltNames({"test.ExAmPlE.CoM", "example.notarealtld",
1005                             "*.test2.ExAmPlE.CoM", "*.example2.notarealtld"},
1006                            {});
1007 
1008   ScopedTestRoot test_root(root->GetX509Certificate());
1009 
1010   scoped_refptr<X509Certificate> leaf_cert = leaf->GetX509Certificate();
1011 
1012   int flags = 0;
1013   CertVerifyResult verify_result;
1014   int error =
1015       Verify(leaf_cert.get(), "test.example.com", flags, &verify_result);
1016   EXPECT_THAT(error, IsOk());
1017   EXPECT_EQ(0U, verify_result.cert_status);
1018 
1019   error =
1020       Verify(leaf_cert.get(), "foo.test2.example.com", flags, &verify_result);
1021   EXPECT_THAT(error, IsOk());
1022   EXPECT_EQ(0U, verify_result.cert_status);
1023 }
1024 
TEST_P(CertVerifyProcInternalTest,NameConstraintsFailure)1025 TEST_P(CertVerifyProcInternalTest, NameConstraintsFailure) {
1026   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
1027 
1028   // Use the private key matching the public_key_hash of the kDomainsTest
1029   // constraint in CertVerifyProc::HasNameConstraintsViolation.
1030   ASSERT_TRUE(leaf->UseKeyFromFile(
1031       GetTestCertsDirectory().AppendASCII("name_constrained_key.pem")));
1032   // example.com is allowed by kDomainsTest, but example.org is not.
1033   leaf->SetSubjectAltNames({"test.ExAmPlE.CoM", "test.ExAmPlE.OrG"}, {});
1034 
1035   ScopedTestRoot test_root(root->GetX509Certificate());
1036 
1037   scoped_refptr<X509Certificate> leaf_cert = leaf->GetX509Certificate();
1038 
1039   int flags = 0;
1040   CertVerifyResult verify_result;
1041   int error =
1042       Verify(leaf_cert.get(), "test.example.com", flags, &verify_result);
1043   EXPECT_THAT(error, IsError(ERR_CERT_NAME_CONSTRAINT_VIOLATION));
1044   EXPECT_EQ(CERT_STATUS_NAME_CONSTRAINT_VIOLATION,
1045             verify_result.cert_status & CERT_STATUS_NAME_CONSTRAINT_VIOLATION);
1046 }
1047 
1048 // This fixture is for testing the verification of a certificate chain which
1049 // has some sort of mismatched signature algorithm (i.e.
1050 // Certificate.signatureAlgorithm and TBSCertificate.algorithm are different).
1051 class CertVerifyProcInspectSignatureAlgorithmsTest : public ::testing::Test {
1052  protected:
1053   // In the test setup, SHA384 is given special treatment as an unknown
1054   // algorithm.
1055   static constexpr bssl::DigestAlgorithm kUnknownDigestAlgorithm =
1056       bssl::DigestAlgorithm::Sha384;
1057 
1058   struct CertParams {
1059     // Certificate.signatureAlgorithm
1060     bssl::DigestAlgorithm cert_algorithm;
1061 
1062     // TBSCertificate.algorithm
1063     bssl::DigestAlgorithm tbs_algorithm;
1064   };
1065 
1066   // Shorthand for VerifyChain() where only the leaf's parameters need
1067   // to be specified.
VerifyLeaf(const CertParams & leaf_params)1068   [[nodiscard]] int VerifyLeaf(const CertParams& leaf_params) {
1069     return VerifyChain(
1070         {// Target
1071          leaf_params,
1072          // Root
1073          {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256}});
1074   }
1075 
1076   // Shorthand for VerifyChain() where only the intermediate's parameters need
1077   // to be specified.
VerifyIntermediate(const CertParams & intermediate_params)1078   [[nodiscard]] int VerifyIntermediate(const CertParams& intermediate_params) {
1079     return VerifyChain(
1080         {// Target
1081          {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256},
1082          // Intermediate
1083          intermediate_params,
1084          // Root
1085          {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256}});
1086   }
1087 
1088   // Shorthand for VerifyChain() where only the root's parameters need to be
1089   // specified.
VerifyRoot(const CertParams & root_params)1090   [[nodiscard]] int VerifyRoot(const CertParams& root_params) {
1091     return VerifyChain(
1092         {// Target
1093          {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256},
1094          // Intermediate
1095          {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256},
1096          // Root
1097          root_params});
1098   }
1099 
1100   // Manufactures a certificate chain where each certificate has the indicated
1101   // signature algorithms, and then returns the result of verifying this chain.
1102   //
1103   // TODO(mattm): Replace the custom cert mangling code in this test with
1104   // CertBuilder.
VerifyChain(const std::vector<CertParams> & chain_params)1105   [[nodiscard]] int VerifyChain(const std::vector<CertParams>& chain_params) {
1106     auto chain = CreateChain(chain_params);
1107     if (!chain) {
1108       ADD_FAILURE() << "Failed creating certificate chain";
1109       return ERR_UNEXPECTED;
1110     }
1111 
1112     int flags = 0;
1113     CertVerifyResult dummy_result;
1114     CertVerifyResult verify_result;
1115 
1116     auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(dummy_result);
1117 
1118     return verify_proc->Verify(
1119         chain.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
1120         /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
1121   }
1122 
1123  private:
1124   // Overwrites the AlgorithmIdentifier pointed to by |algorithm_sequence| with
1125   // |algorithm|. Note this violates the constness of StringPiece.
SetAlgorithmSequence(bssl::DigestAlgorithm algorithm,base::StringPiece * algorithm_sequence)1126   [[nodiscard]] static bool SetAlgorithmSequence(
1127       bssl::DigestAlgorithm algorithm,
1128       base::StringPiece* algorithm_sequence) {
1129     // This string of bytes is the full SEQUENCE for an AlgorithmIdentifier.
1130     std::vector<uint8_t> replacement_sequence;
1131     switch (algorithm) {
1132       case bssl::DigestAlgorithm::Sha1:
1133         // sha1WithRSAEncryption
1134         replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
1135                                 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
1136         break;
1137       case bssl::DigestAlgorithm::Sha256:
1138         // sha256WithRSAEncryption
1139         replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
1140                                 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
1141         break;
1142       case kUnknownDigestAlgorithm:
1143         // This shouldn't be anything meaningful (modified numbers at random).
1144         replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x8a, 0x87, 0x18, 0x46,
1145                                 0xd7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
1146         break;
1147       default:
1148         ADD_FAILURE() << "Unsupported digest algorithm";
1149         return false;
1150     }
1151 
1152     // For this simple replacement to work (without modifying any
1153     // other sequence lengths) the original algorithm and replacement
1154     // algorithm must have the same encoded length.
1155     if (algorithm_sequence->size() != replacement_sequence.size()) {
1156       ADD_FAILURE() << "AlgorithmIdentifier must have length "
1157                     << replacement_sequence.size();
1158       return false;
1159     }
1160 
1161     memcpy(const_cast<char*>(algorithm_sequence->data()),
1162            replacement_sequence.data(), replacement_sequence.size());
1163     return true;
1164   }
1165 
1166   // Locate the serial number bytes.
ExtractSerialNumberFromDERCert(base::StringPiece der_cert,base::StringPiece * serial_value)1167   [[nodiscard]] static bool ExtractSerialNumberFromDERCert(
1168       base::StringPiece der_cert,
1169       base::StringPiece* serial_value) {
1170     bssl::der::Parser parser((bssl::der::Input(der_cert)));
1171     bssl::der::Parser certificate;
1172     if (!parser.ReadSequence(&certificate))
1173       return false;
1174 
1175     bssl::der::Parser tbs_certificate;
1176     if (!certificate.ReadSequence(&tbs_certificate))
1177       return false;
1178 
1179     bool unused;
1180     if (!tbs_certificate.SkipOptionalTag(
1181             bssl::der::kTagConstructed | bssl::der::kTagContextSpecific | 0,
1182             &unused)) {
1183       return false;
1184     }
1185 
1186     // serialNumber
1187     bssl::der::Input serial_value_der;
1188     if (!tbs_certificate.ReadTag(bssl::der::kInteger, &serial_value_der)) {
1189       return false;
1190     }
1191 
1192     *serial_value = serial_value_der.AsStringView();
1193     return true;
1194   }
1195 
1196   // Creates a certificate (based on some base certificate file) using the
1197   // specified signature algorithms.
CreateCertificate(const CertParams & params)1198   static scoped_refptr<X509Certificate> CreateCertificate(
1199       const CertParams& params) {
1200     // Dosn't really matter which base certificate is used, so long as it is
1201     // valid and uses a signature AlgorithmIdentifier with the same encoded
1202     // length as sha1WithRSASignature.
1203     const char* kLeafFilename = "ok_cert.pem";
1204 
1205     auto cert = CreateCertificateChainFromFile(
1206         GetTestCertsDirectory(), kLeafFilename, X509Certificate::FORMAT_AUTO);
1207     if (!cert) {
1208       ADD_FAILURE() << "Failed to load certificate: " << kLeafFilename;
1209       return nullptr;
1210     }
1211 
1212     // Start with the DER bytes of a valid certificate. The der data is copied
1213     // to a new std::string as it will modified to create a new certificate.
1214     std::string cert_der(
1215         x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()));
1216 
1217     // Parse the certificate and identify the locations of interest within
1218     // |cert_der|.
1219     base::StringPiece cert_algorithm_sequence;
1220     base::StringPiece tbs_algorithm_sequence;
1221     if (!asn1::ExtractSignatureAlgorithmsFromDERCert(
1222             cert_der, &cert_algorithm_sequence, &tbs_algorithm_sequence)) {
1223       ADD_FAILURE() << "Failed parsing certificate algorithms";
1224       return nullptr;
1225     }
1226 
1227     base::StringPiece serial_value;
1228     if (!ExtractSerialNumberFromDERCert(cert_der, &serial_value)) {
1229       ADD_FAILURE() << "Failed parsing certificate serial number";
1230       return nullptr;
1231     }
1232 
1233     // Give each certificate a unique serial number based on its content (which
1234     // in turn is a function of |params|, otherwise importing it may fail.
1235 
1236     // Upper bound for last entry in DigestAlgorithm
1237     const int kNumDigestAlgorithms = 15;
1238     *const_cast<char*>(serial_value.data()) +=
1239         static_cast<int>(params.tbs_algorithm) * kNumDigestAlgorithms +
1240         static_cast<int>(params.cert_algorithm);
1241 
1242     // Change the signature AlgorithmIdentifiers.
1243     if (!SetAlgorithmSequence(params.cert_algorithm,
1244                               &cert_algorithm_sequence) ||
1245         !SetAlgorithmSequence(params.tbs_algorithm, &tbs_algorithm_sequence)) {
1246       return nullptr;
1247     }
1248 
1249     // NOTE: The signature is NOT recomputed over TBSCertificate -- for these
1250     // tests it isn't needed.
1251     return X509Certificate::CreateFromBytes(
1252         base::as_bytes(base::make_span(cert_der)));
1253   }
1254 
CreateChain(const std::vector<CertParams> & params)1255   static scoped_refptr<X509Certificate> CreateChain(
1256       const std::vector<CertParams>& params) {
1257     // Manufacture a chain with the given combinations of signature algorithms.
1258     // This chain isn't actually a valid chain, but it is good enough for
1259     // testing the base CertVerifyProc.
1260     CertificateList certs;
1261     for (const auto& cert_params : params) {
1262       certs.push_back(CreateCertificate(cert_params));
1263       if (!certs.back())
1264         return nullptr;
1265     }
1266 
1267     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
1268     for (size_t i = 1; i < certs.size(); ++i)
1269       intermediates.push_back(bssl::UpRef(certs[i]->cert_buffer()));
1270 
1271     return X509Certificate::CreateFromBuffer(
1272         bssl::UpRef(certs[0]->cert_buffer()), std::move(intermediates));
1273   }
1274 };
1275 
1276 // This is a control test to make sure that the test helper
1277 // VerifyLeaf() works as expected. There is no actual mismatch in the
1278 // algorithms used here.
1279 //
1280 //  Certificate.signatureAlgorithm:  sha1WithRSASignature
1281 //  TBSCertificate.algorithm:        sha1WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafSha1Sha1)1282 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha1Sha1) {
1283   int rv =
1284       VerifyLeaf({bssl::DigestAlgorithm::Sha1, bssl::DigestAlgorithm::Sha1});
1285   ASSERT_THAT(rv, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
1286 }
1287 
1288 // This is a control test to make sure that the test helper
1289 // VerifyLeaf() works as expected. There is no actual mismatch in the
1290 // algorithms used here.
1291 //
1292 //  Certificate.signatureAlgorithm:  sha256WithRSASignature
1293 //  TBSCertificate.algorithm:        sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafSha256Sha256)1294 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Sha256) {
1295   int rv = VerifyLeaf(
1296       {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha256});
1297   ASSERT_THAT(rv, IsOk());
1298 }
1299 
1300 // Mismatched signature algorithms in the leaf certificate.
1301 //
1302 //  Certificate.signatureAlgorithm:  sha1WithRSASignature
1303 //  TBSCertificate.algorithm:        sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafSha1Sha256)1304 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha1Sha256) {
1305   int rv =
1306       VerifyLeaf({bssl::DigestAlgorithm::Sha1, bssl::DigestAlgorithm::Sha256});
1307   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1308 }
1309 
1310 // Mismatched signature algorithms in the leaf certificate.
1311 //
1312 //  Certificate.signatureAlgorithm:  sha256WithRSAEncryption
1313 //  TBSCertificate.algorithm:        sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafSha256Sha1)1314 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Sha1) {
1315   int rv =
1316       VerifyLeaf({bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha1});
1317   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1318 }
1319 
1320 // Unrecognized signature algorithm in the leaf certificate.
1321 //
1322 //  Certificate.signatureAlgorithm:  sha256WithRSAEncryption
1323 //  TBSCertificate.algorithm:        ?
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafSha256Unknown)1324 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Unknown) {
1325   int rv = VerifyLeaf({bssl::DigestAlgorithm::Sha256, kUnknownDigestAlgorithm});
1326   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1327 }
1328 
1329 // Unrecognized signature algorithm in the leaf certificate.
1330 //
1331 //  Certificate.signatureAlgorithm:  ?
1332 //  TBSCertificate.algorithm:        sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,LeafUnknownSha256)1333 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafUnknownSha256) {
1334   int rv = VerifyLeaf({kUnknownDigestAlgorithm, bssl::DigestAlgorithm::Sha256});
1335   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1336 }
1337 
1338 // Mismatched signature algorithms in the intermediate certificate.
1339 //
1340 //  Certificate.signatureAlgorithm:  sha1WithRSASignature
1341 //  TBSCertificate.algorithm:        sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,IntermediateSha1Sha256)1342 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, IntermediateSha1Sha256) {
1343   int rv = VerifyIntermediate(
1344       {bssl::DigestAlgorithm::Sha1, bssl::DigestAlgorithm::Sha256});
1345   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1346 }
1347 
1348 // Mismatched signature algorithms in the intermediate certificate.
1349 //
1350 //  Certificate.signatureAlgorithm:  sha256WithRSAEncryption
1351 //  TBSCertificate.algorithm:        sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,IntermediateSha256Sha1)1352 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, IntermediateSha256Sha1) {
1353   int rv = VerifyIntermediate(
1354       {bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha1});
1355   ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
1356 }
1357 
1358 // Mismatched signature algorithms in the root certificate.
1359 //
1360 //  Certificate.signatureAlgorithm:  sha256WithRSAEncryption
1361 //  TBSCertificate.algorithm:        sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,RootSha256Sha1)1362 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, RootSha256Sha1) {
1363   int rv =
1364       VerifyRoot({bssl::DigestAlgorithm::Sha256, bssl::DigestAlgorithm::Sha1});
1365   ASSERT_THAT(rv, IsOk());
1366 }
1367 
1368 // Unrecognized signature algorithm in the root certificate.
1369 //
1370 //  Certificate.signatureAlgorithm:  ?
1371 //  TBSCertificate.algorithm:        sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest,RootUnknownSha256)1372 TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, RootUnknownSha256) {
1373   int rv = VerifyRoot({kUnknownDigestAlgorithm, bssl::DigestAlgorithm::Sha256});
1374   ASSERT_THAT(rv, IsOk());
1375 }
1376 
TEST(CertVerifyProcTest,TestHasTooLongValidity)1377 TEST(CertVerifyProcTest, TestHasTooLongValidity) {
1378   struct {
1379     const char* const file;
1380     bool is_valid_too_long;
1381   } tests[] = {
1382       {"start_after_expiry.pem", true},
1383       {"pre_br_validity_ok.pem", true},
1384       {"pre_br_validity_bad_121.pem", true},
1385       {"pre_br_validity_bad_2020.pem", true},
1386       {"10_year_validity.pem", true},
1387       {"11_year_validity.pem", true},
1388       {"39_months_after_2015_04.pem", true},
1389       {"40_months_after_2015_04.pem", true},
1390       {"60_months_after_2012_07.pem", true},
1391       {"61_months_after_2012_07.pem", true},
1392       {"825_days_after_2018_03_01.pem", true},
1393       {"826_days_after_2018_03_01.pem", true},
1394       {"825_days_1_second_after_2018_03_01.pem", true},
1395       {"39_months_based_on_last_day.pem", true},
1396       {"398_days_after_2020_09_01.pem", false},
1397       {"399_days_after_2020_09_01.pem", true},
1398       {"398_days_1_second_after_2020_09_01.pem", true},
1399   };
1400 
1401   base::FilePath certs_dir = GetTestCertsDirectory();
1402 
1403   for (const auto& test : tests) {
1404     SCOPED_TRACE(test.file);
1405 
1406     scoped_refptr<X509Certificate> certificate =
1407         ImportCertFromFile(certs_dir, test.file);
1408     ASSERT_TRUE(certificate);
1409     EXPECT_EQ(test.is_valid_too_long,
1410               CertVerifyProc::HasTooLongValidity(*certificate));
1411   }
1412 }
1413 
1414 // Integration test for CertVerifyProc::HasTooLongValidity.
1415 // There isn't a way to add test entries to the known roots list for testing
1416 // the full CertVerifyProc implementations, but HasTooLongValidity is checked
1417 // by the outer CertVerifyProc::Verify. Thus the test can mock the
1418 // VerifyInternal result to pretend there was a successful verification with
1419 // is_issued_by_known_root and see that Verify overrides that with error.
TEST(CertVerifyProcTest,VerifyCertValidityTooLong)1420 TEST(CertVerifyProcTest, VerifyCertValidityTooLong) {
1421   scoped_refptr<X509Certificate> cert(ImportCertFromFile(
1422       GetTestCertsDirectory(), "900_days_after_2019_07_01.pem"));
1423   ASSERT_TRUE(cert);
1424 
1425   {
1426     // Locally trusted cert should be ok.
1427     CertVerifyResult dummy_result;
1428     dummy_result.is_issued_by_known_root = false;
1429     auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(dummy_result);
1430     CertVerifyResult verify_result;
1431     int error = verify_proc->Verify(
1432         cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
1433         /*sct_list=*/std::string(), 0, &verify_result, NetLogWithSource());
1434     EXPECT_THAT(error, IsOk());
1435     EXPECT_EQ(0u, verify_result.cert_status & CERT_STATUS_ALL_ERRORS);
1436   }
1437 
1438   {
1439     // Publicly trusted cert that was otherwise okay should get changed to
1440     // ERR_CERT_VALIDITY_TOO_LONG.
1441     CertVerifyResult dummy_result;
1442     dummy_result.is_issued_by_known_root = true;
1443     auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(dummy_result);
1444     CertVerifyResult verify_result;
1445     int error = verify_proc->Verify(
1446         cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
1447         /*sct_list=*/std::string(), 0, &verify_result, NetLogWithSource());
1448     EXPECT_THAT(error, IsError(ERR_CERT_VALIDITY_TOO_LONG));
1449     // TODO(mattm): generate a dedicated cert or use CertBuilder so that this
1450     // test doesn't also hit CERT_STATUS_NON_UNIQUE_NAME.
1451     EXPECT_EQ(CERT_STATUS_VALIDITY_TOO_LONG | CERT_STATUS_NON_UNIQUE_NAME,
1452               verify_result.cert_status & CERT_STATUS_ALL_ERRORS);
1453   }
1454 
1455   {
1456     // Publicly trusted cert that had some other error should retain the
1457     // original error, but CERT_STATUS_VALIDITY_TOO_LONG should be added to
1458     // cert_status.
1459     CertVerifyResult dummy_result;
1460     dummy_result.is_issued_by_known_root = true;
1461     dummy_result.cert_status = CERT_STATUS_AUTHORITY_INVALID;
1462     auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(
1463         dummy_result, ERR_CERT_AUTHORITY_INVALID);
1464     CertVerifyResult verify_result;
1465     int error = verify_proc->Verify(
1466         cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
1467         /*sct_list=*/std::string(), 0, &verify_result, NetLogWithSource());
1468     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
1469     // TODO(mattm): generate a dedicated cert or use CertBuilder so that this
1470     // test doesn't also hit CERT_STATUS_NON_UNIQUE_NAME.
1471     EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID | CERT_STATUS_VALIDITY_TOO_LONG |
1472                   CERT_STATUS_NON_UNIQUE_NAME,
1473               verify_result.cert_status & CERT_STATUS_ALL_ERRORS);
1474   }
1475 }
1476 
TEST_P(CertVerifyProcInternalTest,TestKnownRoot)1477 TEST_P(CertVerifyProcInternalTest, TestKnownRoot) {
1478   base::FilePath certs_dir = GetTestCertsDirectory();
1479   scoped_refptr<X509Certificate> cert_chain = CreateCertificateChainFromFile(
1480       certs_dir, "leaf_from_known_root.pem", X509Certificate::FORMAT_AUTO);
1481   ASSERT_TRUE(cert_chain);
1482 
1483   int flags = 0;
1484   CertVerifyResult verify_result;
1485   int error =
1486       Verify(cert_chain.get(), "smallstrategies.com", flags, &verify_result);
1487   EXPECT_THAT(error, IsOk())
1488       << "This test relies on a real certificate that "
1489       << "expires on Nov 29 2024. If failing on/after "
1490       << "that date, please disable and file a bug "
1491       << "against mattm. Current time: " << base::Time::Now();
1492   EXPECT_TRUE(verify_result.is_issued_by_known_root);
1493 }
1494 
1495 // This tests that on successful certificate verification,
1496 // CertVerifyResult::public_key_hashes is filled with a SHA256 hash for each
1497 // of the certificates in the chain.
TEST_P(CertVerifyProcInternalTest,PublicKeyHashes)1498 TEST_P(CertVerifyProcInternalTest, PublicKeyHashes) {
1499   base::FilePath certs_dir = GetTestCertsDirectory();
1500   CertificateList certs = CreateCertificateListFromFile(
1501       certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
1502   ASSERT_EQ(3U, certs.size());
1503 
1504   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
1505   intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
1506   intermediates.push_back(bssl::UpRef(certs[2]->cert_buffer()));
1507 
1508   ScopedTestRoot scoped_root(certs[2]);
1509   scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromBuffer(
1510       bssl::UpRef(certs[0]->cert_buffer()), std::move(intermediates));
1511   ASSERT_TRUE(cert_chain);
1512   ASSERT_EQ(2U, cert_chain->intermediate_buffers().size());
1513 
1514   int flags = 0;
1515   CertVerifyResult verify_result;
1516   int error = Verify(cert_chain.get(), "127.0.0.1", flags, &verify_result);
1517   EXPECT_THAT(error, IsOk());
1518 
1519   EXPECT_EQ(3u, verify_result.public_key_hashes.size());
1520 
1521   // Convert |public_key_hashes| to strings for ease of comparison.
1522   std::vector<std::string> public_key_hash_strings;
1523   for (const auto& public_key_hash : verify_result.public_key_hashes)
1524     public_key_hash_strings.push_back(public_key_hash.ToString());
1525 
1526   std::vector<std::string> expected_public_key_hashes = {
1527       // Target
1528       "sha256/Ru/08Ru275Zlf42sbI6lqi2OUun3r4YgrrK/vJ3+Yzk=",
1529 
1530       // Intermediate
1531       "sha256/D9u0epgvPYlG9YiVp7V+IMT+xhUpB5BhsS/INjDXc4Y=",
1532 
1533       // Trust anchor
1534       "sha256/VypP3VWL7OaqTJ7mIBehWYlv8khPuFHpWiearZI2YjI="};
1535 
1536   // |public_key_hashes| does not have an ordering guarantee.
1537   EXPECT_THAT(expected_public_key_hashes,
1538               testing::UnorderedElementsAreArray(public_key_hash_strings));
1539 }
1540 
1541 // Tests that a Netscape Server Gated crypto is accepted in place of a
1542 // serverAuth EKU.
1543 // TODO(crbug.com/843735): Deprecate support for this.
TEST_P(CertVerifyProcInternalTest,Sha1IntermediateUsesServerGatedCrypto)1544 TEST_P(CertVerifyProcInternalTest, Sha1IntermediateUsesServerGatedCrypto) {
1545   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
1546 
1547   ASSERT_TRUE(root->UseKeyFromFile(
1548       GetTestCertsDirectory().AppendASCII("rsa-2048-1.key")));
1549   root->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kRsaPkcs1Sha1);
1550 
1551   intermediate->SetExtendedKeyUsages(
1552       {bssl::der::Input(bssl::kNetscapeServerGatedCrypto)});
1553   intermediate->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kRsaPkcs1Sha1);
1554 
1555   ScopedTestRoot scoped_root(root->GetX509Certificate());
1556 
1557   int flags = 0;
1558   CertVerifyResult verify_result;
1559   // The cert chain including the root is passed to Verify, as on recent
1560   // Android versions (something like 11+) the verifier fails on SHA1 certs and
1561   // then the CertVerifyProc wrapper just returns the input chain, which this
1562   // test then depends on for its expectations. (This is all kind of silly, but
1563   // this is just matching how the test was originally written, and we'll
1564   // delete this sometime soon anyway so there's not much benefit to thinking
1565   // about it too hard.)
1566   int error = Verify(leaf->GetX509CertificateFullChain().get(),
1567                      "www.example.com", flags, &verify_result);
1568 
1569   EXPECT_NE(error, OK);
1570   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
1571   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
1572 }
1573 
1574 // Basic test for returning the chain in CertVerifyResult. Note that the
1575 // returned chain may just be a reflection of the originally supplied chain;
1576 // that is, if any errors occur, the default chain returned is an exact copy
1577 // of the certificate to be verified. The remaining VerifyReturn* tests are
1578 // used to ensure that the actual, verified chain is being returned by
1579 // Verify().
TEST_P(CertVerifyProcInternalTest,VerifyReturnChainBasic)1580 TEST_P(CertVerifyProcInternalTest, VerifyReturnChainBasic) {
1581   base::FilePath certs_dir = GetTestCertsDirectory();
1582   CertificateList certs = CreateCertificateListFromFile(
1583       certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
1584   ASSERT_EQ(3U, certs.size());
1585 
1586   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
1587   intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
1588   intermediates.push_back(bssl::UpRef(certs[2]->cert_buffer()));
1589 
1590   ScopedTestRoot scoped_root(certs[2]);
1591 
1592   scoped_refptr<X509Certificate> google_full_chain =
1593       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
1594                                         std::move(intermediates));
1595   ASSERT_NE(static_cast<X509Certificate*>(nullptr), google_full_chain.get());
1596   ASSERT_EQ(2U, google_full_chain->intermediate_buffers().size());
1597 
1598   CertVerifyResult verify_result;
1599   EXPECT_EQ(static_cast<X509Certificate*>(nullptr),
1600             verify_result.verified_cert.get());
1601   int error = Verify(google_full_chain.get(), "127.0.0.1", 0, &verify_result);
1602   EXPECT_THAT(error, IsOk());
1603   ASSERT_NE(static_cast<X509Certificate*>(nullptr),
1604             verify_result.verified_cert.get());
1605 
1606   EXPECT_TRUE(
1607       x509_util::CryptoBufferEqual(google_full_chain->cert_buffer(),
1608                                    verify_result.verified_cert->cert_buffer()));
1609   const auto& return_intermediates =
1610       verify_result.verified_cert->intermediate_buffers();
1611   ASSERT_EQ(2U, return_intermediates.size());
1612   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[0].get(),
1613                                            certs[1]->cert_buffer()));
1614   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[1].get(),
1615                                            certs[2]->cert_buffer()));
1616 }
1617 
1618 // Test that certificates issued for 'intranet' names (that is, containing no
1619 // known public registry controlled domain information) issued by well-known
1620 // CAs are flagged appropriately, while certificates that are issued by
1621 // internal CAs are not flagged.
TEST(CertVerifyProcTest,IntranetHostsRejected)1622 TEST(CertVerifyProcTest, IntranetHostsRejected) {
1623   const std::string kIntranetHostname = "webmail";
1624 
1625   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
1626   leaf->SetSubjectAltName(kIntranetHostname);
1627 
1628   scoped_refptr<X509Certificate> cert(leaf->GetX509Certificate());
1629 
1630   CertVerifyResult verify_result;
1631   int error = 0;
1632 
1633   // Intranet names for public CAs should be flagged:
1634   CertVerifyResult dummy_result;
1635   dummy_result.is_issued_by_known_root = true;
1636   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(dummy_result);
1637   error = verify_proc->Verify(cert.get(), kIntranetHostname,
1638                               /*ocsp_response=*/std::string(),
1639                               /*sct_list=*/std::string(), 0, &verify_result,
1640                               NetLogWithSource());
1641   EXPECT_THAT(error, IsOk());
1642   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_NON_UNIQUE_NAME);
1643 
1644   // However, if the CA is not well known, these should not be flagged:
1645   dummy_result.Reset();
1646   dummy_result.is_issued_by_known_root = false;
1647   verify_proc = base::MakeRefCounted<MockCertVerifyProc>(dummy_result);
1648   error = verify_proc->Verify(cert.get(), kIntranetHostname,
1649                               /*ocsp_response=*/std::string(),
1650                               /*sct_list=*/std::string(), 0, &verify_result,
1651                               NetLogWithSource());
1652   EXPECT_THAT(error, IsOk());
1653   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_NON_UNIQUE_NAME);
1654 }
1655 
1656 // Tests that certificates issued by Symantec's legacy infrastructure
1657 // are rejected according to the policies outlined in
1658 // https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html
1659 // unless the caller has explicitly disabled that enforcement.
TEST(CertVerifyProcTest,SymantecCertsRejected)1660 TEST(CertVerifyProcTest, SymantecCertsRejected) {
1661   constexpr SHA256HashValue kSymantecHashValue = {
1662       {0xb2, 0xde, 0xf5, 0x36, 0x2a, 0xd3, 0xfa, 0xcd, 0x04, 0xbd, 0x29,
1663        0x04, 0x7a, 0x43, 0x84, 0x4f, 0x76, 0x70, 0x34, 0xea, 0x48, 0x92,
1664        0xf8, 0x0e, 0x56, 0xbe, 0xe6, 0x90, 0x24, 0x3e, 0x25, 0x02}};
1665   constexpr SHA256HashValue kGoogleHashValue = {
1666       {0xec, 0x72, 0x29, 0x69, 0xcb, 0x64, 0x20, 0x0a, 0xb6, 0x63, 0x8f,
1667        0x68, 0xac, 0x53, 0x8e, 0x40, 0xab, 0xab, 0x5b, 0x19, 0xa6, 0x48,
1668        0x56, 0x61, 0x04, 0x2a, 0x10, 0x61, 0xc4, 0x61, 0x27, 0x76}};
1669 
1670   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
1671 
1672   static constexpr base::Time may_1_2016 = base::Time::FromTimeT(1462060800);
1673   leaf->SetValidity(may_1_2016, may_1_2016 + base::Days(1));
1674   scoped_refptr<X509Certificate> leaf_pre_june_2016 =
1675       leaf->GetX509Certificate();
1676 
1677   static constexpr base::Time june_1_2016 = base::Time::FromTimeT(1464739200);
1678   leaf->SetValidity(june_1_2016, june_1_2016 + base::Days(1));
1679   scoped_refptr<X509Certificate> leaf_post_june_2016 =
1680       leaf->GetX509Certificate();
1681 
1682   static constexpr base::Time dec_20_2017 = base::Time::FromTimeT(1513728000);
1683   leaf->SetValidity(dec_20_2017, dec_20_2017 + base::Days(1));
1684   scoped_refptr<X509Certificate> leaf_dec_2017 = leaf->GetX509Certificate();
1685 
1686   // Test that certificates from the legacy Symantec infrastructure are
1687   // rejected:
1688   // leaf_dec_2017: A certificate issued after 2017-12-01, which is rejected
1689   //                as of M65
1690   // leaf_pre_june_2016: A certificate issued prior to 2016-06-01, which is
1691   //                     rejected as of M66.
1692   for (X509Certificate* cert :
1693        {leaf_dec_2017.get(), leaf_pre_june_2016.get()}) {
1694     scoped_refptr<CertVerifyProc> verify_proc;
1695     int error = 0;
1696 
1697     // Test that a legacy Symantec certificate is rejected.
1698     CertVerifyResult symantec_result;
1699     symantec_result.verified_cert = cert;
1700     symantec_result.public_key_hashes.push_back(HashValue(kSymantecHashValue));
1701     symantec_result.is_issued_by_known_root = true;
1702     verify_proc = base::MakeRefCounted<MockCertVerifyProc>(symantec_result);
1703 
1704     CertVerifyResult test_result_1;
1705     error = verify_proc->Verify(
1706         cert, "www.example.com", /*ocsp_response=*/std::string(),
1707         /*sct_list=*/std::string(), 0, &test_result_1, NetLogWithSource());
1708     EXPECT_THAT(error, IsError(ERR_CERT_SYMANTEC_LEGACY));
1709     EXPECT_TRUE(test_result_1.cert_status & CERT_STATUS_SYMANTEC_LEGACY);
1710 
1711     // ... Unless the Symantec cert chains through a allowlisted intermediate.
1712     CertVerifyResult allowlisted_result;
1713     allowlisted_result.verified_cert = cert;
1714     allowlisted_result.public_key_hashes.push_back(
1715         HashValue(kSymantecHashValue));
1716     allowlisted_result.public_key_hashes.push_back(HashValue(kGoogleHashValue));
1717     allowlisted_result.is_issued_by_known_root = true;
1718     verify_proc = base::MakeRefCounted<MockCertVerifyProc>(allowlisted_result);
1719 
1720     CertVerifyResult test_result_2;
1721     error = verify_proc->Verify(
1722         cert, "www.example.com", /*ocsp_response=*/std::string(),
1723         /*sct_list=*/std::string(), 0, &test_result_2, NetLogWithSource());
1724     EXPECT_THAT(error, IsOk());
1725     EXPECT_FALSE(test_result_2.cert_status & CERT_STATUS_AUTHORITY_INVALID);
1726 
1727     // ... Or the caller disabled enforcement of Symantec policies.
1728     CertVerifyResult test_result_3;
1729     error = verify_proc->Verify(
1730         cert, "www.example.com", /*ocsp_response=*/std::string(),
1731         /*sct_list=*/std::string(),
1732         CertVerifyProc::VERIFY_DISABLE_SYMANTEC_ENFORCEMENT, &test_result_3,
1733         NetLogWithSource());
1734     EXPECT_THAT(error, IsOk());
1735     EXPECT_FALSE(test_result_3.cert_status & CERT_STATUS_SYMANTEC_LEGACY);
1736   }
1737 
1738   // Test that certificates from the legacy Symantec infrastructure issued
1739   // after 2016-06-01 appropriately rejected.
1740   scoped_refptr<X509Certificate> cert = leaf_post_june_2016;
1741 
1742   scoped_refptr<CertVerifyProc> verify_proc;
1743   int error = 0;
1744 
1745   // Test that a legacy Symantec certificate is rejected if the feature
1746   // flag is enabled, and accepted if it is not.
1747   CertVerifyResult symantec_result;
1748   symantec_result.verified_cert = cert;
1749   symantec_result.public_key_hashes.push_back(HashValue(kSymantecHashValue));
1750   symantec_result.is_issued_by_known_root = true;
1751   verify_proc = base::MakeRefCounted<MockCertVerifyProc>(symantec_result);
1752 
1753   CertVerifyResult test_result_1;
1754   error = verify_proc->Verify(cert.get(), "www.example.com",
1755                               /*ocsp_response=*/std::string(),
1756                               /*sct_list=*/std::string(), 0, &test_result_1,
1757                               NetLogWithSource());
1758   EXPECT_THAT(error, IsError(ERR_CERT_SYMANTEC_LEGACY));
1759   EXPECT_TRUE(test_result_1.cert_status & CERT_STATUS_SYMANTEC_LEGACY);
1760 
1761   // ... Unless the Symantec cert chains through a allowlisted intermediate.
1762   CertVerifyResult allowlisted_result;
1763   allowlisted_result.verified_cert = cert;
1764   allowlisted_result.public_key_hashes.push_back(HashValue(kSymantecHashValue));
1765   allowlisted_result.public_key_hashes.push_back(HashValue(kGoogleHashValue));
1766   allowlisted_result.is_issued_by_known_root = true;
1767   verify_proc = base::MakeRefCounted<MockCertVerifyProc>(allowlisted_result);
1768 
1769   CertVerifyResult test_result_2;
1770   error = verify_proc->Verify(cert.get(), "www.example.com",
1771                               /*ocsp_response=*/std::string(),
1772                               /*sct_list=*/std::string(), 0, &test_result_2,
1773                               NetLogWithSource());
1774   EXPECT_THAT(error, IsOk());
1775   EXPECT_FALSE(test_result_2.cert_status & CERT_STATUS_AUTHORITY_INVALID);
1776 
1777   // ... Or the caller disabled enforcement of Symantec policies.
1778   CertVerifyResult test_result_3;
1779   error = verify_proc->Verify(
1780       cert.get(), "www.example.com", /*ocsp_response=*/std::string(),
1781       /*sct_list=*/std::string(),
1782       CertVerifyProc::VERIFY_DISABLE_SYMANTEC_ENFORCEMENT, &test_result_3,
1783       NetLogWithSource());
1784   EXPECT_THAT(error, IsOk());
1785   EXPECT_FALSE(test_result_3.cert_status & CERT_STATUS_SYMANTEC_LEGACY);
1786 }
1787 
1788 // Test that the certificate returned in CertVerifyResult is able to reorder
1789 // certificates that are not ordered from end-entity to root. While this is
1790 // a protocol violation if sent during a TLS handshake, if multiple sources
1791 // of intermediate certificates are combined, it's possible that order may
1792 // not be maintained.
TEST_P(CertVerifyProcInternalTest,VerifyReturnChainProperlyOrdered)1793 TEST_P(CertVerifyProcInternalTest, VerifyReturnChainProperlyOrdered) {
1794   base::FilePath certs_dir = GetTestCertsDirectory();
1795   CertificateList certs = CreateCertificateListFromFile(
1796       certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
1797   ASSERT_EQ(3U, certs.size());
1798 
1799   // Construct the chain out of order.
1800   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
1801   intermediates.push_back(bssl::UpRef(certs[2]->cert_buffer()));
1802   intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
1803 
1804   ScopedTestRoot scoped_root(certs[2]);
1805 
1806   scoped_refptr<X509Certificate> google_full_chain =
1807       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
1808                                         std::move(intermediates));
1809   ASSERT_TRUE(google_full_chain);
1810   ASSERT_EQ(2U, google_full_chain->intermediate_buffers().size());
1811 
1812   CertVerifyResult verify_result;
1813   EXPECT_FALSE(verify_result.verified_cert);
1814   int error = Verify(google_full_chain.get(), "127.0.0.1", 0, &verify_result);
1815   EXPECT_THAT(error, IsOk());
1816   ASSERT_TRUE(verify_result.verified_cert);
1817 
1818   EXPECT_NE(google_full_chain, verify_result.verified_cert);
1819   EXPECT_TRUE(
1820       x509_util::CryptoBufferEqual(google_full_chain->cert_buffer(),
1821                                    verify_result.verified_cert->cert_buffer()));
1822   const auto& return_intermediates =
1823       verify_result.verified_cert->intermediate_buffers();
1824   ASSERT_EQ(2U, return_intermediates.size());
1825   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[0].get(),
1826                                            certs[1]->cert_buffer()));
1827   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[1].get(),
1828                                            certs[2]->cert_buffer()));
1829 }
1830 
1831 // Test that Verify() filters out certificates which are not related to
1832 // or part of the certificate chain being verified.
TEST_P(CertVerifyProcInternalTest,VerifyReturnChainFiltersUnrelatedCerts)1833 TEST_P(CertVerifyProcInternalTest, VerifyReturnChainFiltersUnrelatedCerts) {
1834   base::FilePath certs_dir = GetTestCertsDirectory();
1835   CertificateList certs = CreateCertificateListFromFile(
1836       certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
1837   ASSERT_EQ(3U, certs.size());
1838   ScopedTestRoot scoped_root(certs[2]);
1839 
1840   scoped_refptr<X509Certificate> unrelated_certificate =
1841       ImportCertFromFile(certs_dir, "duplicate_cn_1.pem");
1842   scoped_refptr<X509Certificate> unrelated_certificate2 =
1843       ImportCertFromFile(certs_dir, "google.single.pem");
1844   ASSERT_NE(static_cast<X509Certificate*>(nullptr),
1845             unrelated_certificate.get());
1846   ASSERT_NE(static_cast<X509Certificate*>(nullptr),
1847             unrelated_certificate2.get());
1848 
1849   // Interject unrelated certificates into the list of intermediates.
1850   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
1851   intermediates.push_back(bssl::UpRef(unrelated_certificate->cert_buffer()));
1852   intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
1853   intermediates.push_back(bssl::UpRef(unrelated_certificate2->cert_buffer()));
1854   intermediates.push_back(bssl::UpRef(certs[2]->cert_buffer()));
1855 
1856   scoped_refptr<X509Certificate> google_full_chain =
1857       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
1858                                         std::move(intermediates));
1859   ASSERT_TRUE(google_full_chain);
1860   ASSERT_EQ(4U, google_full_chain->intermediate_buffers().size());
1861 
1862   CertVerifyResult verify_result;
1863   EXPECT_FALSE(verify_result.verified_cert);
1864   int error = Verify(google_full_chain.get(), "127.0.0.1", 0, &verify_result);
1865   EXPECT_THAT(error, IsOk());
1866   ASSERT_TRUE(verify_result.verified_cert);
1867 
1868   EXPECT_NE(google_full_chain, verify_result.verified_cert);
1869   EXPECT_TRUE(
1870       x509_util::CryptoBufferEqual(google_full_chain->cert_buffer(),
1871                                    verify_result.verified_cert->cert_buffer()));
1872   const auto& return_intermediates =
1873       verify_result.verified_cert->intermediate_buffers();
1874   ASSERT_EQ(2U, return_intermediates.size());
1875   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[0].get(),
1876                                            certs[1]->cert_buffer()));
1877   EXPECT_TRUE(x509_util::CryptoBufferEqual(return_intermediates[1].get(),
1878                                            certs[2]->cert_buffer()));
1879 }
1880 
TEST_P(CertVerifyProcInternalTest,AdditionalTrustAnchors)1881 TEST_P(CertVerifyProcInternalTest, AdditionalTrustAnchors) {
1882   if (!VerifyProcTypeIsBuiltin()) {
1883     LOG(INFO) << "Skipping this test in this platform.";
1884     return;
1885   }
1886 
1887   // |ca_cert| is the issuer of |cert|.
1888   CertificateList ca_cert_list =
1889       CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
1890                                     X509Certificate::FORMAT_AUTO);
1891   ASSERT_EQ(1U, ca_cert_list.size());
1892   scoped_refptr<X509Certificate> ca_cert(ca_cert_list[0]);
1893 
1894   CertificateList cert_list = CreateCertificateListFromFile(
1895       GetTestCertsDirectory(), "ok_cert.pem", X509Certificate::FORMAT_AUTO);
1896   ASSERT_EQ(1U, cert_list.size());
1897   scoped_refptr<X509Certificate> cert(cert_list[0]);
1898 
1899   // Verification of |cert| fails when |ca_cert| is not in the trust anchors
1900   // list.
1901   int flags = 0;
1902   CertVerifyResult verify_result;
1903   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
1904   EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
1905   EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result.cert_status);
1906   EXPECT_FALSE(verify_result.is_issued_by_additional_trust_anchor);
1907 
1908   // Now add the |ca_cert| to the |trust_anchors|, and verification should pass.
1909   CertificateList trust_anchors;
1910   trust_anchors.push_back(ca_cert);
1911   SetUpWithAdditionalCerts(trust_anchors, {});
1912   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
1913   EXPECT_THAT(error, IsOk());
1914   EXPECT_EQ(0U, verify_result.cert_status);
1915   EXPECT_TRUE(verify_result.is_issued_by_additional_trust_anchor);
1916 
1917   // Clearing the |trust_anchors| makes verification fail again (the cache
1918   // should be skipped).
1919   SetUpWithAdditionalCerts({}, {});
1920   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
1921   EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
1922   EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result.cert_status);
1923   EXPECT_FALSE(verify_result.is_issued_by_additional_trust_anchor);
1924 }
1925 
TEST_P(CertVerifyProcInternalTest,AdditionalIntermediates)1926 TEST_P(CertVerifyProcInternalTest, AdditionalIntermediates) {
1927   if (!VerifyProcTypeIsBuiltin()) {
1928     LOG(INFO) << "Skipping this test in this platform.";
1929     return;
1930   }
1931 
1932   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
1933   scoped_refptr<X509Certificate> leaf_cert = leaf->GetX509Certificate();
1934   scoped_refptr<X509Certificate> intermediate_cert =
1935       intermediate->GetX509Certificate();
1936   scoped_refptr<X509Certificate> root_cert = root->GetX509Certificate();
1937   constexpr char kHostname[] = "www.example.com";
1938 
1939   ScopedTestRoot trust_root(root_cert);
1940   // Leaf should not verify without intermediate found
1941   EXPECT_THAT(Verify(leaf_cert.get(), kHostname),
1942               IsError(ERR_CERT_AUTHORITY_INVALID));
1943 
1944   // Leaf should verify after intermediate is passed in to CertVerifyProc. Chain
1945   // should be {leaf, intermediate, root}.
1946   SetUpWithAdditionalCerts({}, {intermediate->GetX509Certificate()});
1947   CertVerifyResult verify_result;
1948   int error = Verify(leaf_cert.get(), kHostname, /*flags=*/0, &verify_result);
1949   EXPECT_THAT(error, IsOk());
1950   ASSERT_TRUE(verify_result.verified_cert);
1951   EXPECT_EQ(verify_result.verified_cert->intermediate_buffers().size(), 2U);
1952   EXPECT_TRUE(x509_util::CryptoBufferEqual(
1953       verify_result.verified_cert->intermediate_buffers().back().get(),
1954       root_cert->cert_buffer()));
1955   EXPECT_TRUE(x509_util::CryptoBufferEqual(
1956       verify_result.verified_cert->intermediate_buffers().front().get(),
1957       intermediate_cert->cert_buffer()));
1958 }
1959 
TEST_P(CertVerifyProcInternalTest,AdditionalTrustAnchorDuplicateIntermediate)1960 TEST_P(CertVerifyProcInternalTest, AdditionalTrustAnchorDuplicateIntermediate) {
1961   if (!VerifyProcTypeIsBuiltin()) {
1962     LOG(INFO) << "Skipping this test in this platform.";
1963     return;
1964   }
1965 
1966   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
1967   constexpr char kHostname[] = "www.example.com";
1968 
1969   // Leaf should not verify without anything set up.
1970   EXPECT_THAT(Verify(leaf->GetX509Certificate().get(), kHostname),
1971               IsError(ERR_CERT_AUTHORITY_INVALID));
1972 
1973   // Leaf should verify with intermediate and root added.
1974   CertificateList trust_anchors, intermediates;
1975   intermediates.push_back(intermediate->GetX509Certificate());
1976   trust_anchors.push_back(root->GetX509Certificate());
1977   SetUpWithAdditionalCerts(trust_anchors, intermediates);
1978   EXPECT_THAT(Verify(leaf->GetX509Certificate().get(), kHostname), IsOk());
1979 
1980   // Leaf should still verify after root is also in intermediates list.
1981   intermediates.push_back(root->GetX509Certificate());
1982   SetUpWithAdditionalCerts(trust_anchors, intermediates);
1983   EXPECT_THAT(Verify(leaf->GetX509Certificate().get(), kHostname), IsOk());
1984 }
1985 
1986 // Tests that certificates issued by user-supplied roots are not flagged as
1987 // issued by a known root. This should pass whether or not the platform supports
1988 // detecting known roots.
TEST_P(CertVerifyProcInternalTest,IsIssuedByKnownRootIgnoresTestRoots)1989 TEST_P(CertVerifyProcInternalTest, IsIssuedByKnownRootIgnoresTestRoots) {
1990   // Load root_ca_cert.pem into the test root store.
1991   ScopedTestRoot test_root(
1992       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"));
1993 
1994   scoped_refptr<X509Certificate> cert(
1995       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
1996 
1997   // Verification should pass.
1998   int flags = 0;
1999   CertVerifyResult verify_result;
2000   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2001   EXPECT_THAT(error, IsOk());
2002   EXPECT_EQ(0U, verify_result.cert_status);
2003   // But should not be marked as a known root.
2004   EXPECT_FALSE(verify_result.is_issued_by_known_root);
2005 }
2006 
2007 // Test that CRLSets are effective in making a certificate appear to be
2008 // revoked.
TEST_P(CertVerifyProcInternalTest,CRLSet)2009 TEST_P(CertVerifyProcInternalTest, CRLSet) {
2010   if (!SupportsCRLSet()) {
2011     LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
2012     return;
2013   }
2014 
2015   CertificateList ca_cert_list =
2016       CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
2017                                     X509Certificate::FORMAT_AUTO);
2018   ASSERT_EQ(1U, ca_cert_list.size());
2019   ScopedTestRoot test_root(ca_cert_list[0]);
2020 
2021   CertificateList cert_list = CreateCertificateListFromFile(
2022       GetTestCertsDirectory(), "ok_cert.pem", X509Certificate::FORMAT_AUTO);
2023   ASSERT_EQ(1U, cert_list.size());
2024   scoped_refptr<X509Certificate> cert(cert_list[0]);
2025 
2026   int flags = 0;
2027   CertVerifyResult verify_result;
2028   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2029   EXPECT_THAT(error, IsOk());
2030   EXPECT_EQ(0U, verify_result.cert_status);
2031 
2032   scoped_refptr<CRLSet> crl_set;
2033   std::string crl_set_bytes;
2034 
2035   // First test blocking by SPKI.
2036   EXPECT_TRUE(base::ReadFileToString(
2037       GetTestCertsDirectory().AppendASCII("crlset_by_leaf_spki.raw"),
2038       &crl_set_bytes));
2039   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2040 
2041   SetUpCertVerifyProc(crl_set);
2042   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2043   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2044 
2045   // Second, test revocation by serial number of a cert directly under the
2046   // root.
2047   crl_set_bytes.clear();
2048   EXPECT_TRUE(base::ReadFileToString(
2049       GetTestCertsDirectory().AppendASCII("crlset_by_root_serial.raw"),
2050       &crl_set_bytes));
2051   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2052 
2053   SetUpCertVerifyProc(crl_set);
2054   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2055   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2056 }
2057 
TEST_P(CertVerifyProcInternalTest,CRLSetLeafSerial)2058 TEST_P(CertVerifyProcInternalTest, CRLSetLeafSerial) {
2059   if (!SupportsCRLSet()) {
2060     LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
2061     return;
2062   }
2063 
2064   CertificateList ca_cert_list =
2065       CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
2066                                     X509Certificate::FORMAT_AUTO);
2067   ASSERT_EQ(1U, ca_cert_list.size());
2068   ScopedTestRoot test_root(ca_cert_list[0]);
2069 
2070   scoped_refptr<X509Certificate> leaf = CreateCertificateChainFromFile(
2071       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
2072       X509Certificate::FORMAT_AUTO);
2073   ASSERT_TRUE(leaf);
2074   ASSERT_EQ(1U, leaf->intermediate_buffers().size());
2075 
2076   int flags = 0;
2077   CertVerifyResult verify_result;
2078   int error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2079   EXPECT_THAT(error, IsOk());
2080 
2081   // Test revocation by serial number of a certificate not under the root.
2082   scoped_refptr<CRLSet> crl_set;
2083   std::string crl_set_bytes;
2084   ASSERT_TRUE(base::ReadFileToString(
2085       GetTestCertsDirectory().AppendASCII("crlset_by_intermediate_serial.raw"),
2086       &crl_set_bytes));
2087   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2088 
2089   SetUpCertVerifyProc(crl_set);
2090   error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2091   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2092 }
2093 
TEST_P(CertVerifyProcInternalTest,CRLSetRootReturnsChain)2094 TEST_P(CertVerifyProcInternalTest, CRLSetRootReturnsChain) {
2095   if (!SupportsCRLSet()) {
2096     LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
2097     return;
2098   }
2099 
2100   CertificateList ca_cert_list =
2101       CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
2102                                     X509Certificate::FORMAT_AUTO);
2103   ASSERT_EQ(1U, ca_cert_list.size());
2104   ScopedTestRoot test_root(ca_cert_list[0]);
2105 
2106   scoped_refptr<X509Certificate> leaf = CreateCertificateChainFromFile(
2107       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
2108       X509Certificate::FORMAT_AUTO);
2109   ASSERT_TRUE(leaf);
2110   ASSERT_EQ(1U, leaf->intermediate_buffers().size());
2111 
2112   int flags = 0;
2113   CertVerifyResult verify_result;
2114   int error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2115   EXPECT_THAT(error, IsOk());
2116 
2117   // Test revocation of the root itself.
2118   scoped_refptr<CRLSet> crl_set;
2119   std::string crl_set_bytes;
2120   ASSERT_TRUE(base::ReadFileToString(
2121       GetTestCertsDirectory().AppendASCII("crlset_by_root_spki.raw"),
2122       &crl_set_bytes));
2123   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2124 
2125   SetUpCertVerifyProc(crl_set);
2126   error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2127   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2128 
2129   EXPECT_EQ(3u, verify_result.public_key_hashes.size());
2130   ASSERT_TRUE(verify_result.verified_cert);
2131   EXPECT_EQ(2u, verify_result.verified_cert->intermediate_buffers().size());
2132 }
2133 
2134 // Tests that CertVerifyProc implementations apply CRLSet revocations by
2135 // subject.
TEST_P(CertVerifyProcInternalTest,CRLSetRevokedBySubject)2136 TEST_P(CertVerifyProcInternalTest, CRLSetRevokedBySubject) {
2137   if (!SupportsCRLSet()) {
2138     LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
2139     return;
2140   }
2141 
2142   scoped_refptr<X509Certificate> root(
2143       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem"));
2144   ASSERT_TRUE(root);
2145 
2146   scoped_refptr<X509Certificate> leaf(
2147       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
2148   ASSERT_TRUE(leaf);
2149 
2150   ScopedTestRoot scoped_root(root);
2151 
2152   int flags = 0;
2153   CertVerifyResult verify_result;
2154 
2155   // Confirm that verifying the certificate chain with an empty CRLSet succeeds.
2156   SetUpCertVerifyProc(CRLSet::EmptyCRLSetForTesting());
2157   int error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2158   EXPECT_THAT(error, IsOk());
2159 
2160   std::string crl_set_bytes;
2161   scoped_refptr<CRLSet> crl_set;
2162 
2163   // Revoke the leaf by subject. Verification should now fail.
2164   ASSERT_TRUE(base::ReadFileToString(
2165       GetTestCertsDirectory().AppendASCII("crlset_by_leaf_subject_no_spki.raw"),
2166       &crl_set_bytes));
2167   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2168 
2169   SetUpCertVerifyProc(crl_set);
2170   error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2171   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2172 
2173   // Revoke the root by subject. Verification should now fail.
2174   ASSERT_TRUE(base::ReadFileToString(
2175       GetTestCertsDirectory().AppendASCII("crlset_by_root_subject_no_spki.raw"),
2176       &crl_set_bytes));
2177   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2178 
2179   SetUpCertVerifyProc(crl_set);
2180   error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2181   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
2182 
2183   // Revoke the leaf by subject, but only if the SPKI doesn't match the given
2184   // one. Verification should pass when using the certificate's actual SPKI.
2185   ASSERT_TRUE(base::ReadFileToString(
2186       GetTestCertsDirectory().AppendASCII("crlset_by_root_subject.raw"),
2187       &crl_set_bytes));
2188   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2189 
2190   SetUpCertVerifyProc(crl_set);
2191   error = Verify(leaf.get(), "127.0.0.1", flags, &verify_result);
2192   EXPECT_THAT(error, IsOk());
2193 }
2194 
2195 // Ensures that CRLSets can be used to block known interception roots on
2196 // platforms that support CRLSets, while otherwise detect known interception
2197 // on platforms that do not.
TEST_P(CertVerifyProcInternalTest,BlockedInterceptionByRoot)2198 TEST_P(CertVerifyProcInternalTest, BlockedInterceptionByRoot) {
2199   scoped_refptr<X509Certificate> root =
2200       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
2201   ASSERT_TRUE(root);
2202   ScopedTestRoot test_root(root);
2203 
2204   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
2205       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
2206       X509Certificate::FORMAT_AUTO);
2207   ASSERT_TRUE(cert);
2208 
2209   // A default/built-in CRLSet should not block
2210   scoped_refptr<CRLSet> crl_set = CRLSet::BuiltinCRLSet();
2211   SetUpCertVerifyProc(crl_set);
2212   int flags = 0;
2213   CertVerifyResult verify_result;
2214   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2215   EXPECT_THAT(error, IsOk());
2216   EXPECT_EQ(0U, verify_result.cert_status);
2217 
2218   // Read in a CRLSet that marks the root as blocked for interception.
2219   std::string crl_set_bytes;
2220   ASSERT_TRUE(
2221       base::ReadFileToString(GetTestCertsDirectory().AppendASCII(
2222                                  "crlset_blocked_interception_by_root.raw"),
2223                              &crl_set_bytes));
2224   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2225 
2226   SetUpCertVerifyProc(crl_set);
2227   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2228   if (SupportsCRLSet()) {
2229     EXPECT_THAT(error, IsError(ERR_CERT_KNOWN_INTERCEPTION_BLOCKED));
2230     EXPECT_TRUE(verify_result.cert_status &
2231                 CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
2232   } else {
2233     EXPECT_THAT(error, IsOk());
2234     EXPECT_TRUE(verify_result.cert_status &
2235                 CERT_STATUS_KNOWN_INTERCEPTION_DETECTED);
2236   }
2237 }
2238 
2239 // Ensures that CRLSets can be used to block known interception intermediates,
2240 // while still allowing other certificates from that root..
TEST_P(CertVerifyProcInternalTest,BlockedInterceptionByIntermediate)2241 TEST_P(CertVerifyProcInternalTest, BlockedInterceptionByIntermediate) {
2242   scoped_refptr<X509Certificate> root =
2243       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
2244   ASSERT_TRUE(root);
2245   ScopedTestRoot test_root(root);
2246 
2247   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
2248       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
2249       X509Certificate::FORMAT_AUTO);
2250   ASSERT_TRUE(cert);
2251 
2252   // A default/built-in CRLSEt should not block
2253   scoped_refptr<CRLSet> crl_set = CRLSet::BuiltinCRLSet();
2254   SetUpCertVerifyProc(crl_set);
2255   int flags = 0;
2256   CertVerifyResult verify_result;
2257   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2258   EXPECT_THAT(error, IsOk());
2259   EXPECT_EQ(0U, verify_result.cert_status);
2260 
2261   // Read in a CRLSet that marks the intermediate as blocked for interception.
2262   std::string crl_set_bytes;
2263   ASSERT_TRUE(base::ReadFileToString(
2264       GetTestCertsDirectory().AppendASCII(
2265           "crlset_blocked_interception_by_intermediate.raw"),
2266       &crl_set_bytes));
2267   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2268 
2269   SetUpCertVerifyProc(crl_set);
2270   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2271   if (SupportsCRLSet()) {
2272     EXPECT_THAT(error, IsError(ERR_CERT_KNOWN_INTERCEPTION_BLOCKED));
2273     EXPECT_TRUE(verify_result.cert_status &
2274                 CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
2275   } else {
2276     EXPECT_THAT(error, IsOk());
2277     EXPECT_TRUE(verify_result.cert_status &
2278                 CERT_STATUS_KNOWN_INTERCEPTION_DETECTED);
2279   }
2280 
2281   // Load a different certificate from that root, which should be unaffected.
2282   scoped_refptr<X509Certificate> second_cert = CreateCertificateChainFromFile(
2283       GetTestCertsDirectory(), "ok_cert.pem", X509Certificate::FORMAT_AUTO);
2284   ASSERT_TRUE(second_cert);
2285 
2286   SetUpCertVerifyProc(crl_set);
2287   error = Verify(second_cert.get(), "127.0.0.1", flags, &verify_result);
2288   EXPECT_THAT(error, IsOk());
2289   EXPECT_EQ(0U, verify_result.cert_status);
2290 }
2291 
2292 // Ensures that CRLSets can be used to flag known interception roots, even
2293 // when they are not blocked.
TEST_P(CertVerifyProcInternalTest,DetectsInterceptionByRoot)2294 TEST_P(CertVerifyProcInternalTest, DetectsInterceptionByRoot) {
2295   scoped_refptr<X509Certificate> root =
2296       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
2297   ASSERT_TRUE(root);
2298   ScopedTestRoot test_root(root);
2299 
2300   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
2301       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
2302       X509Certificate::FORMAT_AUTO);
2303   ASSERT_TRUE(cert);
2304 
2305   // A default/built-in CRLSet should not block
2306   scoped_refptr<CRLSet> crl_set = CRLSet::BuiltinCRLSet();
2307   SetUpCertVerifyProc(crl_set);
2308   int flags = 0;
2309   CertVerifyResult verify_result;
2310   int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2311   EXPECT_THAT(error, IsOk());
2312   EXPECT_EQ(0U, verify_result.cert_status);
2313 
2314   // Read in a CRLSet that marks the root as blocked for interception.
2315   std::string crl_set_bytes;
2316   ASSERT_TRUE(
2317       base::ReadFileToString(GetTestCertsDirectory().AppendASCII(
2318                                  "crlset_known_interception_by_root.raw"),
2319                              &crl_set_bytes));
2320   ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2321 
2322   SetUpCertVerifyProc(crl_set);
2323   error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2324   EXPECT_THAT(error, IsOk());
2325   EXPECT_TRUE(verify_result.cert_status &
2326               CERT_STATUS_KNOWN_INTERCEPTION_DETECTED);
2327 }
2328 
2329 // Tests that CRLSets participate in path building functions, and that as
2330 // long as a valid path exists within the verification graph, verification
2331 // succeeds.
2332 //
2333 // In this test, there are two roots (D and E), and three possible paths
2334 // to validate a leaf (A):
2335 // 1. A(B) -> B(C) -> C(D) -> D(D)
2336 // 2. A(B) -> B(C) -> C(E) -> E(E)
2337 // 3. A(B) -> B(F) -> F(E) -> E(E)
2338 //
2339 // Each permutation of revocation is tried:
2340 // 1. Revoking E by SPKI, so that only Path 1 is valid (as E is in Paths 2 & 3)
2341 // 2. Revoking C(D) and F(E) by serial, so that only Path 2 is valid.
2342 // 3. Revoking C by SPKI, so that only Path 3 is valid (as C is in Paths 1 & 2)
TEST_P(CertVerifyProcInternalTest,CRLSetDuringPathBuilding)2343 TEST_P(CertVerifyProcInternalTest, CRLSetDuringPathBuilding) {
2344   if (!SupportsCRLSetsInPathBuilding()) {
2345     LOG(INFO) << "Skipping this test on this platform.";
2346     return;
2347   }
2348 
2349   CertificateList path_1_certs;
2350   ASSERT_TRUE(
2351       LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-C.pem",
2352                             "multi-root-C-by-D.pem", "multi-root-D-by-D.pem"},
2353                            &path_1_certs));
2354 
2355   CertificateList path_2_certs;
2356   ASSERT_TRUE(
2357       LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-C.pem",
2358                             "multi-root-C-by-E.pem", "multi-root-E-by-E.pem"},
2359                            &path_2_certs));
2360 
2361   CertificateList path_3_certs;
2362   ASSERT_TRUE(
2363       LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-F.pem",
2364                             "multi-root-F-by-E.pem", "multi-root-E-by-E.pem"},
2365                            &path_3_certs));
2366 
2367   // Add D and E as trust anchors.
2368   ScopedTestRoot test_root_D(path_1_certs[3]);  // D-by-D
2369   ScopedTestRoot test_root_E(path_2_certs[3]);  // E-by-E
2370 
2371   // Create a chain that contains all the certificate paths possible.
2372   // CertVerifyProcInternalTest.VerifyReturnChainFiltersUnrelatedCerts already
2373   // ensures that it's safe to send additional certificates as inputs, and
2374   // that they're ignored if not necessary.
2375   // This is to avoid relying on AIA or internal object caches when
2376   // interacting with the underlying library.
2377   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
2378   intermediates.push_back(
2379       bssl::UpRef(path_1_certs[1]->cert_buffer()));  // B-by-C
2380   intermediates.push_back(
2381       bssl::UpRef(path_1_certs[2]->cert_buffer()));  // C-by-D
2382   intermediates.push_back(
2383       bssl::UpRef(path_2_certs[2]->cert_buffer()));  // C-by-E
2384   intermediates.push_back(
2385       bssl::UpRef(path_3_certs[1]->cert_buffer()));  // B-by-F
2386   intermediates.push_back(
2387       bssl::UpRef(path_3_certs[2]->cert_buffer()));  // F-by-E
2388   scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
2389       bssl::UpRef(path_1_certs[0]->cert_buffer()), std::move(intermediates));
2390   ASSERT_TRUE(cert);
2391 
2392   struct TestPermutations {
2393     const char* crlset;
2394     bool expect_valid;
2395     scoped_refptr<X509Certificate> expected_intermediate;
2396   } kTests[] = {
2397       {"multi-root-crlset-D-and-E.raw", false, nullptr},
2398       {"multi-root-crlset-E.raw", true, path_1_certs[2].get()},
2399       {"multi-root-crlset-CD-and-FE.raw", true, path_2_certs[2].get()},
2400       {"multi-root-crlset-C.raw", true, path_3_certs[2].get()},
2401       {"multi-root-crlset-unrelated.raw", true, nullptr}};
2402 
2403   for (const auto& testcase : kTests) {
2404     SCOPED_TRACE(testcase.crlset);
2405     scoped_refptr<CRLSet> crl_set;
2406     std::string crl_set_bytes;
2407     EXPECT_TRUE(base::ReadFileToString(
2408         GetTestCertsDirectory().AppendASCII(testcase.crlset), &crl_set_bytes));
2409     ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
2410 
2411     SetUpCertVerifyProc(crl_set);
2412     int flags = 0;
2413     CertVerifyResult verify_result;
2414     int error = Verify(cert.get(), "127.0.0.1", flags, &verify_result);
2415 
2416     if (!testcase.expect_valid) {
2417       EXPECT_NE(OK, error);
2418       EXPECT_NE(0U, verify_result.cert_status);
2419       continue;
2420     }
2421 
2422     ASSERT_THAT(error, IsOk());
2423     ASSERT_EQ(0U, verify_result.cert_status);
2424     ASSERT_TRUE(verify_result.verified_cert.get());
2425 
2426     if (!testcase.expected_intermediate)
2427       continue;
2428 
2429     const auto& verified_intermediates =
2430         verify_result.verified_cert->intermediate_buffers();
2431     ASSERT_EQ(3U, verified_intermediates.size());
2432 
2433     scoped_refptr<X509Certificate> intermediate =
2434         X509Certificate::CreateFromBuffer(
2435             bssl::UpRef(verified_intermediates[1].get()), {});
2436     ASSERT_TRUE(intermediate);
2437 
2438     EXPECT_TRUE(testcase.expected_intermediate->EqualsExcludingChain(
2439         intermediate.get()))
2440         << "Expected: " << testcase.expected_intermediate->subject().common_name
2441         << " issued by " << testcase.expected_intermediate->issuer().common_name
2442         << "; Got: " << intermediate->subject().common_name << " issued by "
2443         << intermediate->issuer().common_name;
2444   }
2445 }
2446 
TEST_P(CertVerifyProcInternalTest,ValidityDayPlus5MinutesBeforeNotBefore)2447 TEST_P(CertVerifyProcInternalTest, ValidityDayPlus5MinutesBeforeNotBefore) {
2448   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2449   base::Time not_before = base::Time::Now() + base::Days(1) + base::Minutes(5);
2450   base::Time not_after = base::Time::Now() + base::Days(30);
2451   leaf->SetValidity(not_before, not_after);
2452 
2453   // Trust the root and build a chain to verify that includes the intermediate.
2454   ScopedTestRoot scoped_root(root->GetX509Certificate());
2455   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2456   ASSERT_TRUE(chain.get());
2457 
2458   int flags = 0;
2459   CertVerifyResult verify_result;
2460   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2461   // Current time is before certificate's notBefore. Verification should fail.
2462   EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
2463   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
2464 }
2465 
TEST_P(CertVerifyProcInternalTest,ValidityDayBeforeNotBefore)2466 TEST_P(CertVerifyProcInternalTest, ValidityDayBeforeNotBefore) {
2467   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2468   base::Time not_before = base::Time::Now() + base::Days(1);
2469   base::Time not_after = base::Time::Now() + base::Days(30);
2470   leaf->SetValidity(not_before, not_after);
2471 
2472   // Trust the root and build a chain to verify that includes the intermediate.
2473   ScopedTestRoot scoped_root(root->GetX509Certificate());
2474   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2475   ASSERT_TRUE(chain.get());
2476 
2477   int flags = 0;
2478   CertVerifyResult verify_result;
2479   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2480   // Current time is before certificate's notBefore. Verification should fail.
2481   EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
2482   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
2483 }
2484 
TEST_P(CertVerifyProcInternalTest,ValidityJustBeforeNotBefore)2485 TEST_P(CertVerifyProcInternalTest, ValidityJustBeforeNotBefore) {
2486   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2487   base::Time not_before = base::Time::Now() + base::Minutes(5);
2488   base::Time not_after = base::Time::Now() + base::Days(30);
2489   leaf->SetValidity(not_before, not_after);
2490 
2491   // Trust the root and build a chain to verify that includes the intermediate.
2492   ScopedTestRoot scoped_root(root->GetX509Certificate());
2493   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2494   ASSERT_TRUE(chain.get());
2495 
2496   int flags = 0;
2497   CertVerifyResult verify_result;
2498   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2499   // Current time is before certificate's notBefore. Verification should fail.
2500   EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
2501   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
2502 }
2503 
TEST_P(CertVerifyProcInternalTest,ValidityJustAfterNotBefore)2504 TEST_P(CertVerifyProcInternalTest, ValidityJustAfterNotBefore) {
2505   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2506   base::Time not_before = base::Time::Now() - base::Seconds(1);
2507   base::Time not_after = base::Time::Now() + base::Days(30);
2508   leaf->SetValidity(not_before, not_after);
2509 
2510   // Trust the root and build a chain to verify that includes the intermediate.
2511   ScopedTestRoot scoped_root(root->GetX509Certificate());
2512   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2513   ASSERT_TRUE(chain.get());
2514 
2515   int flags = 0;
2516   CertVerifyResult verify_result;
2517   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2518   // Current time is between notBefore and notAfter. Verification should
2519   // succeed.
2520   EXPECT_THAT(error, IsOk());
2521 }
2522 
TEST_P(CertVerifyProcInternalTest,ValidityJustBeforeNotAfter)2523 TEST_P(CertVerifyProcInternalTest, ValidityJustBeforeNotAfter) {
2524   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2525   base::Time not_before = base::Time::Now() - base::Days(30);
2526   base::Time not_after = base::Time::Now() + base::Minutes(5);
2527   leaf->SetValidity(not_before, not_after);
2528 
2529   // Trust the root and build a chain to verify that includes the intermediate.
2530   ScopedTestRoot scoped_root(root->GetX509Certificate());
2531   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2532   ASSERT_TRUE(chain.get());
2533 
2534   int flags = 0;
2535   CertVerifyResult verify_result;
2536   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2537   // Current time is between notBefore and notAfter. Verification should
2538   // succeed.
2539   EXPECT_THAT(error, IsOk());
2540 }
2541 
TEST_P(CertVerifyProcInternalTest,ValidityJustAfterNotAfter)2542 TEST_P(CertVerifyProcInternalTest, ValidityJustAfterNotAfter) {
2543   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2544   base::Time not_before = base::Time::Now() - base::Days(30);
2545   base::Time not_after = base::Time::Now() - base::Seconds(1);
2546   leaf->SetValidity(not_before, not_after);
2547 
2548   // Trust the root and build a chain to verify that includes the intermediate.
2549   ScopedTestRoot scoped_root(root->GetX509Certificate());
2550   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
2551   ASSERT_TRUE(chain.get());
2552 
2553   int flags = 0;
2554   CertVerifyResult verify_result;
2555   int error = Verify(chain.get(), "www.example.com", flags, &verify_result);
2556   // Current time is after certificate's notAfter. Verification should fail.
2557   EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
2558   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
2559 }
2560 
TEST_P(CertVerifyProcInternalTest,FailedIntermediateSignatureValidation)2561 TEST_P(CertVerifyProcInternalTest, FailedIntermediateSignatureValidation) {
2562   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2563 
2564   // Intermediate has no authorityKeyIdentifier. Also remove
2565   // subjectKeyIdentifier from root for good measure.
2566   intermediate->EraseExtension(
2567       bssl::der::Input(bssl::kAuthorityKeyIdentifierOid));
2568   root->EraseExtension(bssl::der::Input(bssl::kSubjectKeyIdentifierOid));
2569 
2570   // Get the chain with the leaf and the intermediate signed by the original
2571   // key of |root|.
2572   scoped_refptr<X509Certificate> cert = leaf->GetX509CertificateChain();
2573 
2574   // Generate a new key for root.
2575   root->GenerateECKey();
2576 
2577   // Trust the new root certificate.
2578   ScopedTestRoot scoped_root(root->GetX509Certificate());
2579 
2580   int flags = 0;
2581   CertVerifyResult verify_result;
2582   int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
2583 
2584   // The intermediate was signed by a different root with a different key but
2585   // with the same name as the trusted one, and the intermediate has no
2586   // authorityKeyIdentifier, so the verifier must try verifying the signature.
2587   // Should fail with AUTHORITY_INVALID.
2588   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_AUTHORITY_INVALID);
2589   EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
2590 }
2591 
TEST_P(CertVerifyProcInternalTest,FailedTargetSignatureValidation)2592 TEST_P(CertVerifyProcInternalTest, FailedTargetSignatureValidation) {
2593   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2594 
2595   // Leaf has no authorityKeyIdentifier. Also remove subjectKeyIdentifier from
2596   // intermediate for good measure.
2597   leaf->EraseExtension(bssl::der::Input(bssl::kAuthorityKeyIdentifierOid));
2598   intermediate->EraseExtension(
2599       bssl::der::Input(bssl::kSubjectKeyIdentifierOid));
2600 
2601   // Get a copy of the leaf signed by the original key of intermediate.
2602   bssl::UniquePtr<CRYPTO_BUFFER> leaf_wrong_signature = leaf->DupCertBuffer();
2603 
2604   // Generate a new key for intermediate.
2605   intermediate->GenerateECKey();
2606 
2607   // Make a chain that includes the original leaf with the wrong signature and
2608   // the new intermediate.
2609   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
2610   intermediates.push_back(intermediate->DupCertBuffer());
2611 
2612   scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
2613       bssl::UpRef(leaf_wrong_signature), std::move(intermediates));
2614   ASSERT_TRUE(cert.get());
2615 
2616   // Trust the root certificate.
2617   ScopedTestRoot scoped_root(root->GetX509Certificate());
2618 
2619   int flags = 0;
2620   CertVerifyResult verify_result;
2621   int error = Verify(cert.get(), "www.example.com", flags, &verify_result);
2622 
2623   // The leaf was signed by a different intermediate with a different key but
2624   // with the same name as the one in the chain, and the leaf has no
2625   // authorityKeyIdentifier, so the verifier must try verifying the signature.
2626   // Should fail with AUTHORITY_INVALID.
2627   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_AUTHORITY_INVALID);
2628   EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
2629 }
2630 
2631 class CertVerifyProcNameNormalizationTest : public CertVerifyProcInternalTest {
2632  protected:
HistogramName() const2633   std::string HistogramName() const {
2634     std::string prefix("Net.CertVerifier.NameNormalizationPrivateRoots.");
2635     switch (verify_proc_type()) {
2636       case CERT_VERIFY_PROC_ANDROID:
2637         return prefix + "Android";
2638       case CERT_VERIFY_PROC_IOS:
2639         return prefix + "IOS";
2640       case CERT_VERIFY_PROC_BUILTIN:
2641       case CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS:
2642         return prefix + "Builtin";
2643     }
2644   }
2645 
ExpectNormalizationHistogram(int verify_error)2646   void ExpectNormalizationHistogram(int verify_error) {
2647     if (verify_error == OK) {
2648       histograms_.ExpectUniqueSample(
2649           HistogramName(), CertVerifyProc::NameNormalizationResult::kNormalized,
2650           1);
2651     } else {
2652       histograms_.ExpectTotalCount(HistogramName(), 0);
2653     }
2654   }
2655 
ExpectByteEqualHistogram()2656   void ExpectByteEqualHistogram() {
2657     histograms_.ExpectUniqueSample(
2658         HistogramName(), CertVerifyProc::NameNormalizationResult::kByteEqual,
2659         1);
2660   }
2661 
2662  private:
2663   base::HistogramTester histograms_;
2664 };
2665 
2666 INSTANTIATE_TEST_SUITE_P(All,
2667                          CertVerifyProcNameNormalizationTest,
2668                          testing::ValuesIn(kAllCertVerifiers),
2669                          VerifyProcTypeToName);
2670 
2671 // Tries to verify a chain where the leaf's issuer CN is PrintableString, while
2672 // the intermediate's subject CN is UTF8String, and verifies the proper
2673 // histogram is logged.
TEST_P(CertVerifyProcNameNormalizationTest,StringType)2674 TEST_P(CertVerifyProcNameNormalizationTest, StringType) {
2675   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2676 
2677   std::string issuer_cn = CertBuilder::MakeRandomHexString(12);
2678   leaf->SetIssuerTLV(CertBuilder::BuildNameWithCommonNameOfType(
2679       issuer_cn, CBS_ASN1_PRINTABLESTRING));
2680   intermediate->SetSubjectTLV(CertBuilder::BuildNameWithCommonNameOfType(
2681       issuer_cn, CBS_ASN1_UTF8STRING));
2682 
2683   ScopedTestRoot scoped_root(root->GetX509Certificate());
2684 
2685   int flags = 0;
2686   CertVerifyResult verify_result;
2687   int error = Verify(leaf->GetX509CertificateChain().get(), "www.example.com",
2688                      flags, &verify_result);
2689 
2690   switch (verify_proc_type()) {
2691     case CERT_VERIFY_PROC_IOS:
2692       EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
2693       break;
2694     case CERT_VERIFY_PROC_ANDROID:
2695     case CERT_VERIFY_PROC_BUILTIN:
2696     case CERT_VERIFY_PROC_BUILTIN_CHROME_ROOTS:
2697       EXPECT_THAT(error, IsOk());
2698       break;
2699   }
2700 
2701   ExpectNormalizationHistogram(error);
2702 }
2703 
2704 // Tries to verify a chain where the leaf's issuer CN and intermediate's
2705 // subject CN are both PrintableString but have differing case on the first
2706 // character, and verifies the proper histogram is logged.
TEST_P(CertVerifyProcNameNormalizationTest,CaseFolding)2707 TEST_P(CertVerifyProcNameNormalizationTest, CaseFolding) {
2708   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2709 
2710   std::string issuer_hex = CertBuilder::MakeRandomHexString(12);
2711   leaf->SetIssuerTLV(CertBuilder::BuildNameWithCommonNameOfType(
2712       "Z" + issuer_hex, CBS_ASN1_PRINTABLESTRING));
2713   intermediate->SetSubjectTLV(CertBuilder::BuildNameWithCommonNameOfType(
2714       "z" + issuer_hex, CBS_ASN1_PRINTABLESTRING));
2715 
2716   ScopedTestRoot scoped_root(root->GetX509Certificate());
2717 
2718   int flags = 0;
2719   CertVerifyResult verify_result;
2720   int error = Verify(leaf->GetX509CertificateChain().get(), "www.example.com",
2721                      flags, &verify_result);
2722 
2723   EXPECT_THAT(error, IsOk());
2724   ExpectNormalizationHistogram(error);
2725 }
2726 
2727 // Confirms that a chain generated by the same pattern as the other
2728 // NameNormalizationTest cases which does not require normalization validates
2729 // ok, and that the ByteEqual histogram is logged.
TEST_P(CertVerifyProcNameNormalizationTest,ByteEqual)2730 TEST_P(CertVerifyProcNameNormalizationTest, ByteEqual) {
2731   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2732 
2733   std::string issuer_hex = CertBuilder::MakeRandomHexString(12);
2734   leaf->SetIssuerTLV(CertBuilder::BuildNameWithCommonNameOfType(
2735       issuer_hex, CBS_ASN1_PRINTABLESTRING));
2736   intermediate->SetSubjectTLV(CertBuilder::BuildNameWithCommonNameOfType(
2737       issuer_hex, CBS_ASN1_PRINTABLESTRING));
2738 
2739   ScopedTestRoot scoped_root(root->GetX509Certificate());
2740 
2741   int flags = 0;
2742   CertVerifyResult verify_result;
2743   int error = Verify(leaf->GetX509CertificateChain().get(), "www.example.com",
2744                      flags, &verify_result);
2745 
2746   EXPECT_THAT(error, IsOk());
2747   ExpectByteEqualHistogram();
2748 }
2749 
Md5WithRSAEncryption()2750 std::string Md5WithRSAEncryption() {
2751   const uint8_t kMd5WithRSAEncryption[] = {0x30, 0x0d, 0x06, 0x09, 0x2a,
2752                                            0x86, 0x48, 0x86, 0xf7, 0x0d,
2753                                            0x01, 0x01, 0x04, 0x05, 0x00};
2754   return std::string(std::begin(kMd5WithRSAEncryption),
2755                      std::end(kMd5WithRSAEncryption));
2756 }
2757 
2758 // This is the same as CertVerifyProcInternalTest, but it additionally sets up
2759 // networking capabilities for the cert verifiers, and a test server that can be
2760 // used to serve mock responses for AIA/OCSP/CRL.
2761 //
2762 // An actual HTTP test server is used rather than simply mocking the network
2763 // layer, since the certificate fetching networking layer is not mockable for
2764 // all of the cert verifier implementations.
2765 //
2766 // The approach taken in this test fixture is to generate certificates
2767 // on the fly so they use randomly chosen URLs, subjects, and serial
2768 // numbers, in order to defeat global caching effects from the platform
2769 // verifiers. Moreover, the AIA needs to be chosen dynamically since the
2770 // test server's port number cannot be known statically.
2771 class CertVerifyProcInternalWithNetFetchingTest
2772     : public CertVerifyProcInternalTest {
2773  protected:
CertVerifyProcInternalWithNetFetchingTest()2774   CertVerifyProcInternalWithNetFetchingTest()
2775       : task_environment_(
2776             base::test::TaskEnvironment::MainThreadType::DEFAULT) {}
2777 
SetUp()2778   void SetUp() override {
2779     // Create a network thread to be used for network fetches, and wait for
2780     // initialization to complete on that thread.
2781     base::Thread::Options options(base::MessagePumpType::IO, 0);
2782     network_thread_ = std::make_unique<base::Thread>("network_thread");
2783     CHECK(network_thread_->StartWithOptions(std::move(options)));
2784 
2785     base::WaitableEvent initialization_complete_event(
2786         base::WaitableEvent::ResetPolicy::MANUAL,
2787         base::WaitableEvent::InitialState::NOT_SIGNALED);
2788     network_thread_->task_runner()->PostTask(
2789         FROM_HERE,
2790         base::BindOnce(&SetUpOnNetworkThread, &context_, &cert_net_fetcher_,
2791                        &initialization_complete_event));
2792     initialization_complete_event.Wait();
2793     EXPECT_TRUE(cert_net_fetcher_);
2794 
2795     CertVerifyProcInternalTest::SetUp();
2796 
2797     EXPECT_FALSE(test_server_.Started());
2798 
2799     // Register a single request handler with the EmbeddedTestServer, that in
2800     // turn dispatches to the internally managed registry of request handlers.
2801     //
2802     // This allows registering subsequent handlers dynamically during the course
2803     // of the test, since EmbeddedTestServer requires its handlers be registered
2804     // prior to Start().
2805     test_server_.RegisterRequestHandler(base::BindRepeating(
2806         &CertVerifyProcInternalWithNetFetchingTest::DispatchToRequestHandler,
2807         base::Unretained(this)));
2808     EXPECT_TRUE(test_server_.Start());
2809   }
2810 
SetUpCertVerifyProc(scoped_refptr<CRLSet> crl_set)2811   void SetUpCertVerifyProc(scoped_refptr<CRLSet> crl_set) override {
2812     EXPECT_TRUE(cert_net_fetcher_);
2813     SetUpWithCertNetFetcher(cert_net_fetcher_, std::move(crl_set),
2814                             /*additional_trust_anchors=*/{},
2815                             /*additional_untrusted_authorities=*/{});
2816   }
2817 
TearDown()2818   void TearDown() override {
2819     // Do cleanup on network thread.
2820     network_thread_->task_runner()->PostTask(
2821         FROM_HERE, base::BindOnce(&ShutdownOnNetworkThread, &context_,
2822                                   &cert_net_fetcher_));
2823     network_thread_->Stop();
2824     network_thread_.reset();
2825 
2826     CertVerifyProcInternalTest::TearDown();
2827   }
2828 
2829   // Registers a handler with the test server that responds with the given
2830   // Content-Type, HTTP status code, and response body, for GET requests
2831   // to |path|.
2832   // Returns the full URL to |path| for the current test server.
RegisterSimpleTestServerHandler(std::string path,HttpStatusCode status_code,std::string content_type,std::string content)2833   GURL RegisterSimpleTestServerHandler(std::string path,
2834                                        HttpStatusCode status_code,
2835                                        std::string content_type,
2836                                        std::string content) {
2837     GURL handler_url(GetTestServerAbsoluteUrl(path));
2838     base::AutoLock lock(request_handlers_lock_);
2839     request_handlers_.push_back(base::BindRepeating(
2840         &SimpleTestServerHandler, std::move(path), status_code,
2841         std::move(content_type), std::move(content)));
2842     return handler_url;
2843   }
2844 
2845   // Returns a random URL path (starting with /) that has the given suffix.
MakeRandomPath(base::StringPiece suffix)2846   static std::string MakeRandomPath(base::StringPiece suffix) {
2847     return "/" + MakeRandomHexString(12) + std::string(suffix);
2848   }
2849 
2850   // Returns a URL to |path| for the current test server.
GetTestServerAbsoluteUrl(const std::string & path)2851   GURL GetTestServerAbsoluteUrl(const std::string& path) {
2852     return test_server_.GetURL(path);
2853   }
2854 
2855   // Creates a certificate chain for www.example.com, where the leaf certificate
2856   // has an AIA URL pointing to the test server.
CreateSimpleChainWithAIA(scoped_refptr<X509Certificate> * out_leaf,std::string * ca_issuers_path,bssl::UniquePtr<CRYPTO_BUFFER> * out_intermediate,scoped_refptr<X509Certificate> * out_root)2857   void CreateSimpleChainWithAIA(
2858       scoped_refptr<X509Certificate>* out_leaf,
2859       std::string* ca_issuers_path,
2860       bssl::UniquePtr<CRYPTO_BUFFER>* out_intermediate,
2861       scoped_refptr<X509Certificate>* out_root) {
2862     auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
2863 
2864     // Make the leaf certificate have an AIA (CA Issuers) that points to the
2865     // embedded test server. This uses a random URL for predictable behavior in
2866     // the presence of global caching.
2867     *ca_issuers_path = MakeRandomPath(".cer");
2868     GURL ca_issuers_url = GetTestServerAbsoluteUrl(*ca_issuers_path);
2869     leaf->SetCaIssuersUrl(ca_issuers_url);
2870 
2871     // The chain being verified is solely the leaf certificate (missing the
2872     // intermediate and root).
2873     *out_leaf = leaf->GetX509Certificate();
2874     *out_root = root->GetX509Certificate();
2875     *out_intermediate = intermediate->DupCertBuffer();
2876   }
2877 
2878   // Creates a CRL issued and signed by |crl_issuer|, marking |revoked_serials|
2879   // as revoked, and registers it to be served by the test server.
2880   // Returns the full URL to retrieve the CRL from the test server.
CreateAndServeCrl(CertBuilder * crl_issuer,const std::vector<uint64_t> & revoked_serials,absl::optional<bssl::SignatureAlgorithm> signature_algorithm=absl::nullopt)2881   GURL CreateAndServeCrl(CertBuilder* crl_issuer,
2882                          const std::vector<uint64_t>& revoked_serials,
2883                          absl::optional<bssl::SignatureAlgorithm>
2884                              signature_algorithm = absl::nullopt) {
2885     std::string crl = BuildCrl(crl_issuer->GetSubject(), crl_issuer->GetKey(),
2886                                revoked_serials, signature_algorithm);
2887     std::string crl_path = MakeRandomPath(".crl");
2888     return RegisterSimpleTestServerHandler(crl_path, HTTP_OK,
2889                                            "application/pkix-crl", crl);
2890   }
2891 
CreateAndServeCrlWithAlgorithmTlvAndDigest(CertBuilder * crl_issuer,const std::vector<uint64_t> & revoked_serials,const std::string & signature_algorithm_tlv,const EVP_MD * digest)2892   GURL CreateAndServeCrlWithAlgorithmTlvAndDigest(
2893       CertBuilder* crl_issuer,
2894       const std::vector<uint64_t>& revoked_serials,
2895       const std::string& signature_algorithm_tlv,
2896       const EVP_MD* digest) {
2897     std::string crl = BuildCrlWithAlgorithmTlvAndDigest(
2898         crl_issuer->GetSubject(), crl_issuer->GetKey(), revoked_serials,
2899         signature_algorithm_tlv, digest);
2900     std::string crl_path = MakeRandomPath(".crl");
2901     return RegisterSimpleTestServerHandler(crl_path, HTTP_OK,
2902                                            "application/pkix-crl", crl);
2903   }
2904 
2905  private:
DispatchToRequestHandler(const test_server::HttpRequest & request)2906   std::unique_ptr<test_server::HttpResponse> DispatchToRequestHandler(
2907       const test_server::HttpRequest& request) {
2908     // Called on the embedded test server's IO thread.
2909     base::AutoLock lock(request_handlers_lock_);
2910     for (const auto& handler : request_handlers_) {
2911       auto response = handler.Run(request);
2912       if (response)
2913         return response;
2914     }
2915 
2916     return nullptr;
2917   }
2918 
2919   // Serves (|status_code|, |content_type|, |content|) in response to GET
2920   // requests for |path|.
SimpleTestServerHandler(const std::string & path,HttpStatusCode status_code,const std::string & content_type,const std::string & content,const test_server::HttpRequest & request)2921   static std::unique_ptr<test_server::HttpResponse> SimpleTestServerHandler(
2922       const std::string& path,
2923       HttpStatusCode status_code,
2924       const std::string& content_type,
2925       const std::string& content,
2926       const test_server::HttpRequest& request) {
2927     if (request.relative_url != path)
2928       return nullptr;
2929 
2930     auto http_response = std::make_unique<test_server::BasicHttpResponse>();
2931 
2932     http_response->set_code(status_code);
2933     http_response->set_content_type(content_type);
2934     http_response->set_content(content);
2935     return http_response;
2936   }
2937 
SetUpOnNetworkThread(std::unique_ptr<URLRequestContext> * context,scoped_refptr<CertNetFetcherURLRequest> * cert_net_fetcher,base::WaitableEvent * initialization_complete_event)2938   static void SetUpOnNetworkThread(
2939       std::unique_ptr<URLRequestContext>* context,
2940       scoped_refptr<CertNetFetcherURLRequest>* cert_net_fetcher,
2941       base::WaitableEvent* initialization_complete_event) {
2942     URLRequestContextBuilder url_request_context_builder;
2943     url_request_context_builder.set_user_agent("cert_verify_proc_unittest/0.1");
2944     url_request_context_builder.set_proxy_config_service(
2945         std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation()));
2946     *context = url_request_context_builder.Build();
2947 
2948     *cert_net_fetcher = base::MakeRefCounted<net::CertNetFetcherURLRequest>();
2949     (*cert_net_fetcher)->SetURLRequestContext(context->get());
2950     initialization_complete_event->Signal();
2951   }
2952 
ShutdownOnNetworkThread(std::unique_ptr<URLRequestContext> * context,scoped_refptr<net::CertNetFetcherURLRequest> * cert_net_fetcher)2953   static void ShutdownOnNetworkThread(
2954       std::unique_ptr<URLRequestContext>* context,
2955       scoped_refptr<net::CertNetFetcherURLRequest>* cert_net_fetcher) {
2956     (*cert_net_fetcher)->Shutdown();
2957     cert_net_fetcher->reset();
2958     context->reset();
2959   }
2960 
2961   base::test::TaskEnvironment task_environment_;
2962 
2963   std::unique_ptr<base::Thread> network_thread_;
2964 
2965   // Owned by this thread, but initialized, used, and shutdown on the network
2966   // thread.
2967   std::unique_ptr<URLRequestContext> context_;
2968   scoped_refptr<CertNetFetcherURLRequest> cert_net_fetcher_;
2969 
2970   EmbeddedTestServer test_server_;
2971 
2972   // The list of registered handlers. Can only be accessed when the lock is
2973   // held, as this data is shared between the embedded server's IO thread, and
2974   // the test main thread.
2975   base::Lock request_handlers_lock_;
2976   std::vector<test_server::EmbeddedTestServer::HandleRequestCallback>
2977       request_handlers_;
2978 };
2979 
2980 INSTANTIATE_TEST_SUITE_P(All,
2981                          CertVerifyProcInternalWithNetFetchingTest,
2982                          testing::ValuesIn(kAllCertVerifiers),
2983                          VerifyProcTypeToName);
2984 
2985 // Tries verifying a certificate chain that is missing an intermediate. The
2986 // intermediate is available via AIA, however the server responds with a 404.
2987 //
2988 // NOTE: This test is separate from IntermediateFromAia200 as a different URL
2989 // needs to be used to avoid having the result depend on globally cached success
2990 // or failure of the fetch.
2991 // Test is flaky on iOS crbug.com/860189
2992 #if BUILDFLAG(IS_IOS)
2993 #define MAYBE_IntermediateFromAia404 DISABLED_IntermediateFromAia404
2994 #else
2995 #define MAYBE_IntermediateFromAia404 IntermediateFromAia404
2996 #endif
TEST_P(CertVerifyProcInternalWithNetFetchingTest,MAYBE_IntermediateFromAia404)2997 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
2998        MAYBE_IntermediateFromAia404) {
2999   const char kHostname[] = "www.example.com";
3000 
3001   // Create a chain where the leaf has an AIA that points to test server.
3002   scoped_refptr<X509Certificate> leaf;
3003   std::string ca_issuers_path;
3004   bssl::UniquePtr<CRYPTO_BUFFER> intermediate;
3005   scoped_refptr<X509Certificate> root;
3006   CreateSimpleChainWithAIA(&leaf, &ca_issuers_path, &intermediate, &root);
3007 
3008   // Serve a 404 for the AIA url.
3009   RegisterSimpleTestServerHandler(ca_issuers_path, HTTP_NOT_FOUND, "text/plain",
3010                                   "Not Found");
3011 
3012   // Trust the root certificate.
3013   ScopedTestRoot scoped_root(root);
3014 
3015   // The chain being verified is solely the leaf certificate (missing the
3016   // intermediate and root).
3017   ASSERT_EQ(0u, leaf->intermediate_buffers().size());
3018 
3019   const int flags = 0;
3020   int error;
3021   CertVerifyResult verify_result;
3022 
3023   // Verifying the chain should fail as the intermediate is missing, and
3024   // cannot be fetched via AIA.
3025   error = Verify(leaf.get(), kHostname, flags, &verify_result);
3026   EXPECT_NE(OK, error);
3027 
3028   EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
3029 }
3030 #undef MAYBE_IntermediateFromAia404
3031 
3032 // Tries verifying a certificate chain that is missing an intermediate. The
3033 // intermediate is available via AIA.
3034 // TODO(crbug.com/860189): Failing on iOS
3035 #if BUILDFLAG(IS_IOS)
3036 #define MAYBE_IntermediateFromAia200Der DISABLED_IntermediateFromAia200Der
3037 #else
3038 #define MAYBE_IntermediateFromAia200Der IntermediateFromAia200Der
3039 #endif
TEST_P(CertVerifyProcInternalWithNetFetchingTest,MAYBE_IntermediateFromAia200Der)3040 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3041        MAYBE_IntermediateFromAia200Der) {
3042   const char kHostname[] = "www.example.com";
3043 
3044   // Create a chain where the leaf has an AIA that points to test server.
3045   scoped_refptr<X509Certificate> leaf;
3046   std::string ca_issuers_path;
3047   bssl::UniquePtr<CRYPTO_BUFFER> intermediate;
3048   scoped_refptr<X509Certificate> root;
3049   CreateSimpleChainWithAIA(&leaf, &ca_issuers_path, &intermediate, &root);
3050 
3051   // Setup the test server to reply with the correct intermediate.
3052   RegisterSimpleTestServerHandler(
3053       ca_issuers_path, HTTP_OK, "application/pkix-cert",
3054       std::string(x509_util::CryptoBufferAsStringPiece(intermediate.get())));
3055 
3056   // Trust the root certificate.
3057   ScopedTestRoot scoped_root(root);
3058 
3059   // The chain being verified is solely the leaf certificate (missing the
3060   // intermediate and root).
3061   ASSERT_EQ(0u, leaf->intermediate_buffers().size());
3062 
3063   // VERIFY_DISABLE_NETWORK_FETCHES flag is not implemented in
3064   // CertVerifyProcIOS, only test it on other verifiers.
3065   if (verify_proc_type() != CERT_VERIFY_PROC_IOS) {
3066     CertVerifyResult verify_result;
3067     // If VERIFY_DISABLE_NETWORK_FETCHES is specified, AIA should not be
3068     // attempted and verifying the chain should fail since the intermediate
3069     // can't be found.
3070     int error =
3071         Verify(leaf.get(), kHostname,
3072                CertVerifyProc::VERIFY_DISABLE_NETWORK_FETCHES, &verify_result);
3073     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
3074     EXPECT_EQ(0u, verify_result.verified_cert->intermediate_buffers().size());
3075   }
3076 
3077   {
3078     CertVerifyResult verify_result;
3079     // Verifying the chain should succeed as the missing intermediate can be
3080     // fetched via AIA.
3081     int error = Verify(leaf.get(), kHostname, /*flags=*/0, &verify_result);
3082     EXPECT_THAT(error, IsOk());
3083   }
3084 }
3085 
3086 // This test is the same as IntermediateFromAia200Der, except the certificate is
3087 // served as PEM rather than DER.
3088 //
3089 // Tries verifying a certificate chain that is missing an intermediate. The
3090 // intermediate is available via AIA, however is served as a PEM file rather
3091 // than DER.
3092 // TODO(crbug.com/860189): Failing on iOS
3093 #if BUILDFLAG(IS_IOS)
3094 #define MAYBE_IntermediateFromAia200Pem DISABLED_IntermediateFromAia200Pem
3095 #else
3096 #define MAYBE_IntermediateFromAia200Pem IntermediateFromAia200Pem
3097 #endif
TEST_P(CertVerifyProcInternalWithNetFetchingTest,MAYBE_IntermediateFromAia200Pem)3098 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3099        MAYBE_IntermediateFromAia200Pem) {
3100   const char kHostname[] = "www.example.com";
3101 
3102   // Create a chain where the leaf has an AIA that points to test server.
3103   scoped_refptr<X509Certificate> leaf;
3104   std::string ca_issuers_path;
3105   bssl::UniquePtr<CRYPTO_BUFFER> intermediate;
3106   scoped_refptr<X509Certificate> root;
3107   CreateSimpleChainWithAIA(&leaf, &ca_issuers_path, &intermediate, &root);
3108 
3109   std::string intermediate_pem;
3110   ASSERT_TRUE(
3111       X509Certificate::GetPEMEncoded(intermediate.get(), &intermediate_pem));
3112 
3113   // Setup the test server to reply with the correct intermediate.
3114   RegisterSimpleTestServerHandler(
3115       ca_issuers_path, HTTP_OK, "application/x-x509-ca-cert", intermediate_pem);
3116 
3117   // Trust the root certificate.
3118   ScopedTestRoot scoped_root(root);
3119 
3120   // The chain being verified is solely the leaf certificate (missing the
3121   // intermediate and root).
3122   ASSERT_EQ(0u, leaf->intermediate_buffers().size());
3123 
3124   const int flags = 0;
3125   int error;
3126   CertVerifyResult verify_result;
3127 
3128   // Verifying the chain should succeed as the missing intermediate can be
3129   // fetched via AIA.
3130   error = Verify(leaf.get(), kHostname, flags, &verify_result);
3131 
3132   if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
3133     // Android doesn't support PEM - https://crbug.com/725180
3134     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
3135   } else {
3136     EXPECT_THAT(error, IsOk());
3137   }
3138 
3139 }
3140 
3141 // This test is the same as IntermediateFromAia200Pem, but with a different
3142 // formatting on the PEM data.
3143 //
3144 // TODO(crbug.com/860189): Failing on iOS
3145 #if BUILDFLAG(IS_IOS)
3146 #define MAYBE_IntermediateFromAia200Pem2 DISABLED_IntermediateFromAia200Pem2
3147 #else
3148 #define MAYBE_IntermediateFromAia200Pem2 IntermediateFromAia200Pem2
3149 #endif
TEST_P(CertVerifyProcInternalWithNetFetchingTest,MAYBE_IntermediateFromAia200Pem2)3150 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3151        MAYBE_IntermediateFromAia200Pem2) {
3152   const char kHostname[] = "www.example.com";
3153 
3154   // Create a chain where the leaf has an AIA that points to test server.
3155   scoped_refptr<X509Certificate> leaf;
3156   std::string ca_issuers_path;
3157   bssl::UniquePtr<CRYPTO_BUFFER> intermediate;
3158   scoped_refptr<X509Certificate> root;
3159   CreateSimpleChainWithAIA(&leaf, &ca_issuers_path, &intermediate, &root);
3160 
3161   std::string intermediate_pem;
3162   ASSERT_TRUE(
3163       X509Certificate::GetPEMEncoded(intermediate.get(), &intermediate_pem));
3164   intermediate_pem = "Text at start of file\n" + intermediate_pem;
3165 
3166   // Setup the test server to reply with the correct intermediate.
3167   RegisterSimpleTestServerHandler(
3168       ca_issuers_path, HTTP_OK, "application/x-x509-ca-cert", intermediate_pem);
3169 
3170   // Trust the root certificate.
3171   ScopedTestRoot scoped_root(root);
3172 
3173   // The chain being verified is solely the leaf certificate (missing the
3174   // intermediate and root).
3175   ASSERT_EQ(0u, leaf->intermediate_buffers().size());
3176 
3177   const int flags = 0;
3178   int error;
3179   CertVerifyResult verify_result;
3180 
3181   // Verifying the chain should succeed as the missing intermediate can be
3182   // fetched via AIA.
3183   error = Verify(leaf.get(), kHostname, flags, &verify_result);
3184 
3185   if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
3186     // Android doesn't support PEM - https://crbug.com/725180
3187     EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
3188   } else {
3189     EXPECT_THAT(error, IsOk());
3190   }
3191 }
3192 
3193 // Tries verifying a certificate chain that uses a SHA1 intermediate,
3194 // however, chasing the AIA can discover a SHA256 version of the intermediate.
3195 //
3196 // Path building should discover the stronger intermediate and use it.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,Sha1IntermediateButAIAHasSha256)3197 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3198        Sha1IntermediateButAIAHasSha256) {
3199   const char kHostname[] = "www.example.com";
3200 
3201   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3202 
3203   // Make the leaf certificate have an AIA (CA Issuers) that points to the
3204   // embedded test server. This uses a random URL for predictable behavior in
3205   // the presence of global caching.
3206   std::string ca_issuers_path = MakeRandomPath(".cer");
3207   GURL ca_issuers_url = GetTestServerAbsoluteUrl(ca_issuers_path);
3208   leaf->SetCaIssuersUrl(ca_issuers_url);
3209   leaf->SetSubjectAltName(kHostname);
3210 
3211   // Make two versions of the intermediate - one that is SHA256 signed, and one
3212   // that is SHA1 signed. Note that the subjectKeyIdentifier for `intermediate`
3213   // is intentionally not changed, so that path building will consider both
3214   // certificate paths.
3215   intermediate->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha256);
3216   intermediate->SetRandomSerialNumber();
3217   auto intermediate_sha256 = intermediate->DupCertBuffer();
3218 
3219   intermediate->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha1);
3220   intermediate->SetRandomSerialNumber();
3221   auto intermediate_sha1 = intermediate->DupCertBuffer();
3222 
3223   // Trust the root certificate.
3224   auto root_cert = root->GetX509Certificate();
3225   ScopedTestRoot scoped_root(root_cert);
3226 
3227   // Setup the test server to reply with the SHA256 intermediate.
3228   RegisterSimpleTestServerHandler(
3229       ca_issuers_path, HTTP_OK, "application/pkix-cert",
3230       std::string(
3231           x509_util::CryptoBufferAsStringPiece(intermediate_sha256.get())));
3232 
3233   // Build a chain to verify that includes the SHA1 intermediate.
3234   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
3235   intermediates.push_back(bssl::UpRef(intermediate_sha1.get()));
3236   scoped_refptr<X509Certificate> chain_sha1 = X509Certificate::CreateFromBuffer(
3237       leaf->DupCertBuffer(), std::move(intermediates));
3238   ASSERT_TRUE(chain_sha1.get());
3239 
3240   const int flags = 0;
3241   CertVerifyResult verify_result;
3242   int error = Verify(chain_sha1.get(), kHostname, flags, &verify_result);
3243 
3244   if (VerifyProcTypeIsBuiltin()) {
3245     // Should have built a chain through the SHA256 intermediate. This was only
3246     // available via AIA, and not the (SHA1) one provided directly to path
3247     // building.
3248     ASSERT_EQ(2u, verify_result.verified_cert->intermediate_buffers().size());
3249     EXPECT_TRUE(x509_util::CryptoBufferEqual(
3250         verify_result.verified_cert->intermediate_buffers()[0].get(),
3251         intermediate_sha256.get()));
3252     ASSERT_EQ(2u, verify_result.verified_cert->intermediate_buffers().size());
3253 
3254     EXPECT_FALSE(verify_result.has_sha1);
3255     EXPECT_THAT(error, IsOk());
3256   } else {
3257     EXPECT_NE(OK, error);
3258     if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID &&
3259         error == ERR_CERT_AUTHORITY_INVALID) {
3260       // Newer Android versions reject the chain due to the SHA1 intermediate,
3261       // but do not build the correct chain by AIA. Since only the partial
3262       // chain is returned, CertVerifyProc does not mark it as SHA1 as it does
3263       // not examine the last cert in the chain. Therefore, if
3264       // ERR_CERT_AUTHORITY_INVALID is returned, don't check the rest of the
3265       // statuses. See https://crbug.com/1191795.
3266       return;
3267     }
3268     EXPECT_TRUE(verify_result.cert_status &
3269                 CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
3270     EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
3271     EXPECT_TRUE(verify_result.has_sha1);
3272   }
3273 }
3274 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailNoCrls)3275 TEST_P(CertVerifyProcInternalWithNetFetchingTest, RevocationHardFailNoCrls) {
3276   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3277     LOG(INFO) << "Skipping test as verifier doesn't support "
3278                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3279     return;
3280   }
3281 
3282   // Create certs which have no AIA or CRL distribution points.
3283   const char kHostname[] = "www.example.com";
3284   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3285 
3286   // Trust the root and build a chain to verify that includes the intermediate.
3287   ScopedTestRoot scoped_root(root->GetX509Certificate());
3288   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3289   ASSERT_TRUE(chain.get());
3290 
3291   // Verify with hard-fail revocation checking for local anchors.
3292   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3293   CertVerifyResult verify_result;
3294   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3295 
3296   EXPECT_THAT(error, IsError(ERR_CERT_NO_REVOCATION_MECHANISM));
3297   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3298 }
3299 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailNoCrlsDisableNetworkFetches)3300 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3301        RevocationHardFailNoCrlsDisableNetworkFetches) {
3302   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3303     LOG(INFO) << "Skipping test as verifier doesn't support "
3304                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3305     return;
3306   }
3307 
3308   // Create certs which have no AIA or CRL distribution points.
3309   const char kHostname[] = "www.example.com";
3310   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3311 
3312   // Trust the root and build a chain to verify that includes the intermediate.
3313   ScopedTestRoot scoped_root(root->GetX509Certificate());
3314   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3315   ASSERT_TRUE(chain.get());
3316 
3317   // Verify with flags for both hard-fail revocation checking for local anchors
3318   // and disabling network fetches.
3319   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS |
3320                     CertVerifyProc::VERIFY_DISABLE_NETWORK_FETCHES;
3321   CertVerifyResult verify_result;
3322   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3323 
3324   // Should succeed, VERIFY_DISABLE_NETWORK_FETCHES takes priority.
3325   EXPECT_THAT(error, IsOk());
3326   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3327 }
3328 
3329 // CRL hard fail test where both leaf and intermediate are covered by valid
3330 // CRLs which have empty (non-present) revokedCertificates list. Verification
3331 // should succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailCrlGoodNoRevokedCertificates)3332 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3333        RevocationHardFailCrlGoodNoRevokedCertificates) {
3334   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3335     LOG(INFO) << "Skipping test as verifier doesn't support "
3336                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3337     return;
3338   }
3339 
3340   const char kHostname[] = "www.example.com";
3341   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3342 
3343   // Serve a root-issued CRL which does not revoke intermediate.
3344   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3345 
3346   // Serve an intermediate-issued CRL which does not revoke leaf.
3347   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3348 
3349   // Trust the root and build a chain to verify that includes the intermediate.
3350   ScopedTestRoot scoped_root(root->GetX509Certificate());
3351   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3352   ASSERT_TRUE(chain.get());
3353 
3354   // Verify with hard-fail revocation checking for local anchors.
3355   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3356   CertVerifyResult verify_result;
3357   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3358 
3359   // Should pass, leaf and intermediate were covered by CRLs and were not
3360   // revoked.
3361   EXPECT_THAT(error, IsOk());
3362   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3363 }
3364 
3365 // CRL hard fail test where both leaf and intermediate are covered by valid
3366 // CRLs which have revokedCertificates lists that revoke other irrelevant
3367 // serial numbers. Verification should succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailCrlGoodIrrelevantSerialsRevoked)3368 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3369        RevocationHardFailCrlGoodIrrelevantSerialsRevoked) {
3370   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3371     LOG(INFO) << "Skipping test as verifier doesn't support "
3372                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3373     return;
3374   }
3375 
3376   const char kHostname[] = "www.example.com";
3377   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3378 
3379   // Root-issued CRL revokes leaf's serial number. This is irrelevant.
3380   intermediate->SetCrlDistributionPointUrl(
3381       CreateAndServeCrl(root.get(), {leaf->GetSerialNumber()}));
3382 
3383   // Intermediate-issued CRL revokes intermediates's serial number. This is
3384   // irrelevant.
3385   leaf->SetCrlDistributionPointUrl(
3386       CreateAndServeCrl(intermediate.get(), {intermediate->GetSerialNumber()}));
3387 
3388   // Trust the root and build a chain to verify that includes the intermediate.
3389   ScopedTestRoot scoped_root(root->GetX509Certificate());
3390   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3391   ASSERT_TRUE(chain.get());
3392 
3393   // Verify with hard-fail revocation checking for local anchors.
3394   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3395   CertVerifyResult verify_result;
3396   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3397 
3398   // Should pass, leaf and intermediate were covered by CRLs and were not
3399   // revoked.
3400   EXPECT_THAT(error, IsOk());
3401   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3402 }
3403 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailLeafRevokedByCrl)3404 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3405        RevocationHardFailLeafRevokedByCrl) {
3406   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3407     LOG(INFO) << "Skipping test as verifier doesn't support "
3408                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3409     return;
3410   }
3411 
3412   const char kHostname[] = "www.example.com";
3413   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3414 
3415   // Root-issued CRL which does not revoke intermediate.
3416   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3417 
3418   // Leaf is revoked by intermediate issued CRL.
3419   leaf->SetCrlDistributionPointUrl(
3420       CreateAndServeCrl(intermediate.get(), {leaf->GetSerialNumber()}));
3421 
3422   // Trust the root and build a chain to verify that includes the intermediate.
3423   ScopedTestRoot scoped_root(root->GetX509Certificate());
3424   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3425   ASSERT_TRUE(chain.get());
3426 
3427   // Verify with hard-fail revocation checking for local anchors.
3428   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3429   CertVerifyResult verify_result;
3430   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3431 
3432   // Should fail, leaf is revoked.
3433   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
3434   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3435 }
3436 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailIntermediateRevokedByCrl)3437 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3438        RevocationHardFailIntermediateRevokedByCrl) {
3439   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3440     LOG(INFO) << "Skipping test as verifier doesn't support "
3441                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3442     return;
3443   }
3444 
3445   const char kHostname[] = "www.example.com";
3446   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3447 
3448   // Intermediate is revoked by root issued CRL.
3449   intermediate->SetCrlDistributionPointUrl(
3450       CreateAndServeCrl(root.get(), {intermediate->GetSerialNumber()}));
3451 
3452   // Intermediate-issued CRL which does not revoke leaf.
3453   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3454 
3455   // Trust the root and build a chain to verify that includes the intermediate.
3456   ScopedTestRoot scoped_root(root->GetX509Certificate());
3457   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3458   ASSERT_TRUE(chain.get());
3459 
3460   // Verify with hard-fail revocation checking for local anchors.
3461   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3462   CertVerifyResult verify_result;
3463   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3464 
3465   // Should fail, intermediate is revoked.
3466   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
3467   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3468 }
3469 
3470 // CRL hard fail test where the intermediate certificate has a good CRL, but
3471 // the leaf's distribution point returns an http error. Verification should
3472 // fail.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailLeafCrlDpHttpError)3473 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3474        RevocationHardFailLeafCrlDpHttpError) {
3475   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3476     LOG(INFO) << "Skipping test as verifier doesn't support "
3477                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3478     return;
3479   }
3480 
3481   const char kHostname[] = "www.example.com";
3482   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3483 
3484   // Serve a root-issued CRL which does not revoke intermediate.
3485   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3486 
3487   // Serve a 404 for the intermediate-issued CRL distribution point url.
3488   leaf->SetCrlDistributionPointUrl(RegisterSimpleTestServerHandler(
3489       MakeRandomPath(".crl"), HTTP_NOT_FOUND, "text/plain", "Not Found"));
3490 
3491   // Trust the root and build a chain to verify that includes the intermediate.
3492   ScopedTestRoot scoped_root(root->GetX509Certificate());
3493   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3494   ASSERT_TRUE(chain.get());
3495 
3496   // Verify with hard-fail revocation checking for local anchors.
3497   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3498   CertVerifyResult verify_result;
3499   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3500 
3501   // Should fail since no revocation information was available for the leaf.
3502   EXPECT_THAT(error, IsError(ERR_CERT_UNABLE_TO_CHECK_REVOCATION));
3503   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3504 }
3505 
3506 // CRL hard fail test where the leaf certificate has a good CRL, but
3507 // the intermediate's distribution point returns an http error. Verification
3508 // should fail.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationHardFailIntermediateCrlDpHttpError)3509 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3510        RevocationHardFailIntermediateCrlDpHttpError) {
3511   if (!SupportsRevCheckingRequiredLocalAnchors()) {
3512     LOG(INFO) << "Skipping test as verifier doesn't support "
3513                  "VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS";
3514     return;
3515   }
3516 
3517   const char kHostname[] = "www.example.com";
3518   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3519 
3520   // Serve a 404 for the root-issued CRL distribution point url.
3521   intermediate->SetCrlDistributionPointUrl(RegisterSimpleTestServerHandler(
3522       MakeRandomPath(".crl"), HTTP_NOT_FOUND, "text/plain", "Not Found"));
3523 
3524   // Serve an intermediate-issued CRL which does not revoke leaf.
3525   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3526 
3527   // Trust the root and build a chain to verify that includes the intermediate.
3528   ScopedTestRoot scoped_root(root->GetX509Certificate());
3529   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3530   ASSERT_TRUE(chain.get());
3531 
3532   // Verify with hard-fail revocation checking for local anchors.
3533   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3534   CertVerifyResult verify_result;
3535   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3536 
3537   // Should fail since no revocation information was available for the
3538   // intermediate.
3539   EXPECT_THAT(error, IsError(ERR_CERT_UNABLE_TO_CHECK_REVOCATION));
3540   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3541 }
3542 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailNoCrls)3543 TEST_P(CertVerifyProcInternalWithNetFetchingTest, RevocationSoftFailNoCrls) {
3544   if (!SupportsSoftFailRevChecking()) {
3545     LOG(INFO) << "Skipping test as verifier doesn't support "
3546                  "VERIFY_REV_CHECKING_ENABLED";
3547     return;
3548   }
3549 
3550   // Create certs which have no AIA or CRL distribution points.
3551   const char kHostname[] = "www.example.com";
3552   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3553 
3554   // Trust the root and build a chain to verify that includes the intermediate.
3555   ScopedTestRoot scoped_root(root->GetX509Certificate());
3556   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3557   ASSERT_TRUE(chain.get());
3558 
3559   // Verify with soft-fail revocation checking.
3560   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3561   CertVerifyResult verify_result;
3562   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3563 
3564   EXPECT_THAT(error, IsOk());
3565   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_NO_REVOCATION_MECHANISM);
3566   EXPECT_FALSE(verify_result.cert_status &
3567                CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
3568   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3569 }
3570 
3571 // CRL soft fail test where both leaf and intermediate are covered by valid
3572 // CRLs which have empty (non-present) revokedCertificates list. Verification
3573 // should succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailCrlGoodNoRevokedCertificates)3574 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3575        RevocationSoftFailCrlGoodNoRevokedCertificates) {
3576   if (!SupportsSoftFailRevChecking()) {
3577     LOG(INFO) << "Skipping test as verifier doesn't support "
3578                  "VERIFY_REV_CHECKING_ENABLED";
3579     return;
3580   }
3581 
3582   const char kHostname[] = "www.example.com";
3583   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3584 
3585   // Serve a root-issued CRL which does not revoke intermediate.
3586   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3587 
3588   // Serve an intermediate-issued CRL which does not revoke leaf.
3589   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3590 
3591   // Trust the root and build a chain to verify that includes the intermediate.
3592   ScopedTestRoot scoped_root(root->GetX509Certificate());
3593   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3594   ASSERT_TRUE(chain.get());
3595 
3596   // Verify with soft-fail revocation checking.
3597   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3598   CertVerifyResult verify_result;
3599   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3600 
3601   EXPECT_THAT(error, IsOk());
3602   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3603 }
3604 
3605 // CRL soft fail test where both leaf and intermediate are covered by valid
3606 // CRLs which have revokedCertificates lists that revoke other irrelevant
3607 // serial numbers. Verification should succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailCrlGoodIrrelevantSerialsRevoked)3608 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3609        RevocationSoftFailCrlGoodIrrelevantSerialsRevoked) {
3610   if (!SupportsSoftFailRevChecking()) {
3611     LOG(INFO) << "Skipping test as verifier doesn't support "
3612                  "VERIFY_REV_CHECKING_ENABLED";
3613     return;
3614   }
3615 
3616   const char kHostname[] = "www.example.com";
3617   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3618 
3619   // Root-issued CRL revokes leaf's serial number. This is irrelevant.
3620   intermediate->SetCrlDistributionPointUrl(
3621       CreateAndServeCrl(root.get(), {leaf->GetSerialNumber()}));
3622 
3623   // Intermediate-issued CRL revokes intermediates's serial number. This is
3624   // irrelevant.
3625   leaf->SetCrlDistributionPointUrl(
3626       CreateAndServeCrl(intermediate.get(), {intermediate->GetSerialNumber()}));
3627 
3628   // Trust the root and build a chain to verify that includes the intermediate.
3629   ScopedTestRoot scoped_root(root->GetX509Certificate());
3630   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3631   ASSERT_TRUE(chain.get());
3632 
3633   // Verify with soft-fail revocation checking.
3634   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3635   CertVerifyResult verify_result;
3636   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3637 
3638   EXPECT_THAT(error, IsOk());
3639   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3640 }
3641 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailLeafRevokedByCrl)3642 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3643        RevocationSoftFailLeafRevokedByCrl) {
3644   if (!SupportsSoftFailRevChecking()) {
3645     LOG(INFO) << "Skipping test as verifier doesn't support "
3646                  "VERIFY_REV_CHECKING_ENABLED";
3647     return;
3648   }
3649 
3650   const char kHostname[] = "www.example.com";
3651   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3652 
3653   // Root-issued CRL which does not revoke intermediate.
3654   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3655 
3656   // Leaf is revoked by intermediate issued CRL.
3657   leaf->SetCrlDistributionPointUrl(
3658       CreateAndServeCrl(intermediate.get(), {leaf->GetSerialNumber()}));
3659 
3660   // Trust the root and build a chain to verify that includes the intermediate.
3661   ScopedTestRoot scoped_root(root->GetX509Certificate());
3662   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3663   ASSERT_TRUE(chain.get());
3664 
3665   // Verify with soft-fail revocation checking.
3666   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3667   CertVerifyResult verify_result;
3668   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3669 
3670   // Should fail, leaf is revoked.
3671   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
3672   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3673 }
3674 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailLeafRevokedByCrlDisableNetworkFetches)3675 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3676        RevocationSoftFailLeafRevokedByCrlDisableNetworkFetches) {
3677   if (!SupportsSoftFailRevChecking()) {
3678     LOG(INFO) << "Skipping test as verifier doesn't support "
3679                  "VERIFY_REV_CHECKING_ENABLED";
3680     return;
3681   }
3682 
3683   const char kHostname[] = "www.example.com";
3684   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3685 
3686   // Root-issued CRL which does not revoke intermediate.
3687   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3688 
3689   // Leaf is revoked by intermediate issued CRL.
3690   leaf->SetCrlDistributionPointUrl(
3691       CreateAndServeCrl(intermediate.get(), {leaf->GetSerialNumber()}));
3692 
3693   // Trust the root and build a chain to verify that includes the intermediate.
3694   ScopedTestRoot scoped_root(root->GetX509Certificate());
3695   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3696   ASSERT_TRUE(chain.get());
3697 
3698   // Verify with flags for both soft-fail revocation checking and disabling
3699   // network fetches.
3700   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED |
3701                     CertVerifyProc::VERIFY_DISABLE_NETWORK_FETCHES;
3702   CertVerifyResult verify_result;
3703   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3704 
3705   // Should succeed, VERIFY_DISABLE_NETWORK_FETCHES takes priority.
3706   EXPECT_THAT(error, IsOk());
3707   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3708 }
3709 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailIntermediateRevokedByCrl)3710 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3711        RevocationSoftFailIntermediateRevokedByCrl) {
3712   if (!SupportsSoftFailRevChecking()) {
3713     LOG(INFO) << "Skipping test as verifier doesn't support "
3714                  "VERIFY_REV_CHECKING_ENABLED";
3715     return;
3716   }
3717 
3718   const char kHostname[] = "www.example.com";
3719   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3720 
3721   // Intermediate is revoked by root issued CRL.
3722   intermediate->SetCrlDistributionPointUrl(
3723       CreateAndServeCrl(root.get(), {intermediate->GetSerialNumber()}));
3724 
3725   // Intermediate-issued CRL which does not revoke leaf.
3726   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3727 
3728   // Trust the root and build a chain to verify that includes the intermediate.
3729   ScopedTestRoot scoped_root(root->GetX509Certificate());
3730   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3731   ASSERT_TRUE(chain.get());
3732 
3733   // Verify with soft-fail revocation checking.
3734   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3735   CertVerifyResult verify_result;
3736   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3737 
3738   // Should fail, intermediate is revoked.
3739   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
3740   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3741 }
3742 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailLeafRevokedBySha1Crl)3743 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3744        RevocationSoftFailLeafRevokedBySha1Crl) {
3745   if (!SupportsSoftFailRevChecking()) {
3746     LOG(INFO) << "Skipping test as verifier doesn't support "
3747                  "VERIFY_REV_CHECKING_ENABLED";
3748     return;
3749   }
3750 
3751   const char kHostname[] = "www.example.com";
3752   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3753 
3754   // Root-issued CRL which does not revoke intermediate.
3755   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3756 
3757   // Leaf is revoked by intermediate issued CRL which is signed with
3758   // ecdsaWithSha256.
3759   leaf->SetCrlDistributionPointUrl(
3760       CreateAndServeCrl(intermediate.get(), {leaf->GetSerialNumber()},
3761                         bssl::SignatureAlgorithm::kEcdsaSha1));
3762 
3763   // Trust the root and build a chain to verify that includes the intermediate.
3764   ScopedTestRoot scoped_root(root->GetX509Certificate());
3765   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3766   ASSERT_TRUE(chain.get());
3767 
3768   // Verify with soft-fail revocation checking.
3769   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3770   CertVerifyResult verify_result;
3771   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3772 
3773   // Should fail, leaf is revoked.
3774   EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
3775   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3776 }
3777 
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailLeafRevokedByMd5Crl)3778 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3779        RevocationSoftFailLeafRevokedByMd5Crl) {
3780   if (!SupportsSoftFailRevChecking()) {
3781     LOG(INFO) << "Skipping test as verifier doesn't support "
3782                  "VERIFY_REV_CHECKING_ENABLED";
3783     return;
3784   }
3785 
3786   const char kHostname[] = "www.example.com";
3787   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3788 
3789   // Root-issued CRL which does not revoke intermediate.
3790   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3791   // This test wants to check handling of MD5 CRLs, but ecdsa-with-md5
3792   // signatureAlgorithm does not exist. Use an RSA private key for intermediate
3793   // so that the CRL will be signed with the md5WithRSAEncryption algorithm.
3794   ASSERT_TRUE(intermediate->UseKeyFromFile(
3795       GetTestCertsDirectory().AppendASCII("rsa-2048-1.key")));
3796   leaf->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kRsaPkcs1Sha256);
3797 
3798   // Leaf is revoked by intermediate issued CRL which is signed with
3799   // md5WithRSAEncryption.
3800   leaf->SetCrlDistributionPointUrl(CreateAndServeCrlWithAlgorithmTlvAndDigest(
3801       intermediate.get(), {leaf->GetSerialNumber()}, Md5WithRSAEncryption(),
3802       EVP_md5()));
3803 
3804   // Trust the root and build a chain to verify that includes the intermediate.
3805   ScopedTestRoot scoped_root(root->GetX509Certificate());
3806   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3807   ASSERT_TRUE(chain.get());
3808 
3809   // Verify with soft-fail revocation checking.
3810   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3811   CertVerifyResult verify_result;
3812   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3813 
3814   // Verification should succeed: MD5 signature algorithm is not supported
3815   // and soft-fail checking will ignore the inability to get revocation
3816   // status.
3817   EXPECT_THAT(error, IsOk());
3818   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3819 }
3820 
3821 // CRL soft fail test where the intermediate certificate has a good CRL, but
3822 // the leaf's distribution point returns an http error. Verification should
3823 // succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailLeafCrlDpHttpError)3824 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3825        RevocationSoftFailLeafCrlDpHttpError) {
3826   if (!SupportsSoftFailRevChecking()) {
3827     LOG(INFO) << "Skipping test as verifier doesn't support "
3828                  "VERIFY_REV_CHECKING_ENABLED";
3829     return;
3830   }
3831 
3832   const char kHostname[] = "www.example.com";
3833   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3834 
3835   // Serve a root-issued CRL which does not revoke intermediate.
3836   intermediate->SetCrlDistributionPointUrl(CreateAndServeCrl(root.get(), {}));
3837 
3838   // Serve a 404 for the intermediate-issued CRL distribution point url.
3839   leaf->SetCrlDistributionPointUrl(RegisterSimpleTestServerHandler(
3840       MakeRandomPath(".crl"), HTTP_NOT_FOUND, "text/plain", "Not Found"));
3841 
3842   // Trust the root and build a chain to verify that includes the intermediate.
3843   ScopedTestRoot scoped_root(root->GetX509Certificate());
3844   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3845   ASSERT_TRUE(chain.get());
3846 
3847   // Verify with soft-fail revocation checking.
3848   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3849   CertVerifyResult verify_result;
3850   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3851 
3852   // Should succeed due to soft-fail revocation checking.
3853   EXPECT_THAT(error, IsOk());
3854   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3855 }
3856 
3857 // CRL soft fail test where the leaf certificate has a good CRL, but
3858 // the intermediate's distribution point returns an http error. Verification
3859 // should succeed.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,RevocationSoftFailIntermediateCrlDpHttpError)3860 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3861        RevocationSoftFailIntermediateCrlDpHttpError) {
3862   if (!SupportsSoftFailRevChecking()) {
3863     LOG(INFO) << "Skipping test as verifier doesn't support "
3864                  "VERIFY_REV_CHECKING_ENABLED";
3865     return;
3866   }
3867 
3868   const char kHostname[] = "www.example.com";
3869   auto [leaf, intermediate, root] = CertBuilder::CreateSimpleChain3();
3870 
3871   // Serve a 404 for the root-issued CRL distribution point url.
3872   intermediate->SetCrlDistributionPointUrl(RegisterSimpleTestServerHandler(
3873       MakeRandomPath(".crl"), HTTP_NOT_FOUND, "text/plain", "Not Found"));
3874 
3875   // Serve an intermediate-issued CRL which does not revoke leaf.
3876   leaf->SetCrlDistributionPointUrl(CreateAndServeCrl(intermediate.get(), {}));
3877 
3878   // Trust the root and build a chain to verify that includes the intermediate.
3879   ScopedTestRoot scoped_root(root->GetX509Certificate());
3880   scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
3881   ASSERT_TRUE(chain.get());
3882 
3883   // Verify with soft-fail revocation checking.
3884   const int flags = CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
3885   CertVerifyResult verify_result;
3886   int error = Verify(chain.get(), kHostname, flags, &verify_result);
3887 
3888   // Should succeed due to soft-fail revocation checking.
3889   EXPECT_THAT(error, IsOk());
3890   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3891 }
3892 
3893 // Tests that an EV cert verification with successful online OCSP revocation
3894 // checks is marked as CERT_STATUS_IS_EV.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,EVOnlineOCSPRevocationCheckingGood)3895 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3896        EVOnlineOCSPRevocationCheckingGood) {
3897   if (!SupportsEV()) {
3898     LOG(INFO) << "Skipping test as EV verification is not yet supported";
3899     return;
3900   }
3901 
3902   const char kEVTestCertPolicy[] = "1.2.3.4";
3903   EmbeddedTestServer::ServerCertificateConfig cert_config;
3904   cert_config.policy_oids = {kEVTestCertPolicy};
3905   cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
3906       {{bssl::OCSPRevocationStatus::GOOD,
3907         EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
3908 
3909   EmbeddedTestServer ocsp_test_server(EmbeddedTestServer::TYPE_HTTPS);
3910   ocsp_test_server.SetSSLConfig(cert_config);
3911   EXPECT_TRUE(ocsp_test_server.Start());
3912 
3913   scoped_refptr<X509Certificate> root =
3914       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
3915   ASSERT_TRUE(root.get());
3916 
3917   scoped_refptr<X509Certificate> chain = ocsp_test_server.GetCertificate();
3918   ASSERT_TRUE(chain.get());
3919 
3920   // Consider the root of the test chain a valid EV root for the test policy.
3921   ScopedTestEVPolicy scoped_test_ev_policy(
3922       EVRootCAMetadata::GetInstance(),
3923       X509Certificate::CalculateFingerprint256(root->cert_buffer()),
3924       kEVTestCertPolicy);
3925 
3926   CertVerifyResult verify_result;
3927   int flags = 0;
3928   int error = Verify(chain.get(), ocsp_test_server.host_port_pair().host(),
3929                      flags, &verify_result);
3930   EXPECT_THAT(error, IsOk());
3931   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
3932   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3933 }
3934 
3935 // Tests that an EV cert verification with that could not retrieve online OCSP
3936 // revocation information is verified but still marked as CERT_STATUS_IS_EV.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,EVOnlineOCSPRevocationCheckingSoftFail)3937 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3938        EVOnlineOCSPRevocationCheckingSoftFail) {
3939   if (!SupportsEV()) {
3940     LOG(INFO) << "Skipping test as EV verification is not yet supported";
3941     return;
3942   }
3943 
3944   const char kEVTestCertPolicy[] = "1.2.3.4";
3945   EmbeddedTestServer::ServerCertificateConfig cert_config;
3946   cert_config.policy_oids = {kEVTestCertPolicy};
3947   // Retrieving OCSP status returns an error.
3948   cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
3949       EmbeddedTestServer::OCSPConfig::ResponseType::kInternalError);
3950 
3951   EmbeddedTestServer ocsp_test_server(EmbeddedTestServer::TYPE_HTTPS);
3952   ocsp_test_server.SetSSLConfig(cert_config);
3953   EXPECT_TRUE(ocsp_test_server.Start());
3954 
3955   scoped_refptr<X509Certificate> root =
3956       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
3957   ASSERT_TRUE(root.get());
3958 
3959   scoped_refptr<X509Certificate> chain = ocsp_test_server.GetCertificate();
3960   ASSERT_TRUE(chain.get());
3961 
3962   // Consider the root of the test chain a valid EV root for the test policy.
3963   ScopedTestEVPolicy scoped_test_ev_policy(
3964       EVRootCAMetadata::GetInstance(),
3965       X509Certificate::CalculateFingerprint256(root->cert_buffer()),
3966       kEVTestCertPolicy);
3967 
3968   CertVerifyResult verify_result;
3969   int flags = 0;
3970   int error = Verify(chain.get(), ocsp_test_server.host_port_pair().host(),
3971                      flags, &verify_result);
3972   EXPECT_THAT(error, IsOk());
3973   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
3974   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
3975 }
3976 
3977 // Tests that an EV cert verification with online OCSP returning affirmatively
3978 // revoked is marked as CERT_STATUS_IS_EV.
TEST_P(CertVerifyProcInternalWithNetFetchingTest,EVOnlineOCSPRevocationCheckingRevoked)3979 TEST_P(CertVerifyProcInternalWithNetFetchingTest,
3980        EVOnlineOCSPRevocationCheckingRevoked) {
3981   if (!SupportsEV()) {
3982     LOG(INFO) << "Skipping test as EV verification is not yet supported";
3983     return;
3984   }
3985 
3986   const char kEVTestCertPolicy[] = "1.2.3.4";
3987   EmbeddedTestServer::ServerCertificateConfig cert_config;
3988   cert_config.policy_oids = {kEVTestCertPolicy};
3989   cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
3990       {{bssl::OCSPRevocationStatus::REVOKED,
3991         EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
3992 
3993   EmbeddedTestServer ocsp_test_server(EmbeddedTestServer::TYPE_HTTPS);
3994   ocsp_test_server.SetSSLConfig(cert_config);
3995   EXPECT_TRUE(ocsp_test_server.Start());
3996 
3997   scoped_refptr<X509Certificate> root =
3998       ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
3999   ASSERT_TRUE(root.get());
4000 
4001   scoped_refptr<X509Certificate> chain = ocsp_test_server.GetCertificate();
4002   ASSERT_TRUE(chain.get());
4003 
4004   // Consider the root of the test chain a valid EV root for the test policy.
4005   ScopedTestEVPolicy scoped_test_ev_policy(
4006       EVRootCAMetadata::GetInstance(),
4007       X509Certificate::CalculateFingerprint256(root->cert_buffer()),
4008       kEVTestCertPolicy);
4009 
4010   CertVerifyResult verify_result;
4011   int flags = 0;
4012   int error = Verify(chain.get(), ocsp_test_server.host_port_pair().host(),
4013                      flags, &verify_result);
4014   EXPECT_THAT(error, IsOk());
4015   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
4016   EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4017 }
4018 
4019 // A set of tests that check how various constraints are enforced when they
4020 // appear at different points in the chain, such as on the trust anchor versus
4021 // on intermediates.
4022 class CertVerifyProcConstraintsTest : public CertVerifyProcInternalTest {
4023  protected:
SetUp()4024   void SetUp() override {
4025     CertVerifyProcInternalTest::SetUp();
4026 
4027     chain_ = CertBuilder::CreateSimpleChain(/*chain_length=*/4);
4028   }
4029 
VerifyWithTrust(bssl::CertificateTrust trust)4030   int VerifyWithTrust(bssl::CertificateTrust trust) {
4031     ScopedTestRoot test_root(chain_.back()->GetX509Certificate(), trust);
4032     CertVerifyResult verify_result;
4033     int flags = 0;
4034     return CertVerifyProcInternalTest::Verify(
4035         chain_.front()->GetX509CertificateChain().get(), "www.example.com",
4036         flags, &verify_result);
4037   }
4038 
Verify()4039   int Verify() {
4040     return VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor());
4041   }
4042 
VerifyWithExpiryAndConstraints()4043   int VerifyWithExpiryAndConstraints() {
4044     return VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor()
4045                                .WithEnforceAnchorExpiry()
4046                                .WithEnforceAnchorConstraints());
4047   }
4048 
VerifyWithExpiryAndFullConstraints()4049   int VerifyWithExpiryAndFullConstraints() {
4050     return VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor()
4051                                .WithEnforceAnchorExpiry()
4052                                .WithEnforceAnchorConstraints()
4053                                .WithRequireAnchorBasicConstraints());
4054   }
4055 
ExpectedIntermediateConstraintError()4056   int ExpectedIntermediateConstraintError() {
4057     if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID)
4058       return ERR_CERT_AUTHORITY_INVALID;
4059     return ERR_CERT_INVALID;
4060   }
4061 
4062   std::vector<std::unique_ptr<CertBuilder>> chain_;
4063 };
4064 
4065 INSTANTIATE_TEST_SUITE_P(All,
4066                          CertVerifyProcConstraintsTest,
4067                          testing::ValuesIn(kAllCertVerifiers),
4068                          VerifyProcTypeToName);
4069 
TEST_P(CertVerifyProcConstraintsTest,BaseCase)4070 TEST_P(CertVerifyProcConstraintsTest, BaseCase) {
4071   // Without changing anything on the test chain, it should validate
4072   // successfully. If this is not true then the rest of the tests in this class
4073   // are unlikely to be useful.
4074   EXPECT_THAT(Verify(), IsOk());
4075   if (VerifyProcTypeIsBuiltin()) {
4076     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4077     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(), IsOk());
4078     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()),
4079                 IsOk());
4080     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()),
4081                 IsError(ERR_CERT_AUTHORITY_INVALID));
4082   }
4083 }
4084 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotCaRoot)4085 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotCaRoot) {
4086   chain_[3]->SetBasicConstraints(/*is_ca=*/false, /*path_len=*/-1);
4087 
4088   if (VerifyProcTypeIsBuiltin()) {
4089     EXPECT_THAT(Verify(), IsOk());
4090     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4091     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4092                 IsError(ERR_CERT_INVALID));
4093   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4094     EXPECT_THAT(Verify(), IsOk());
4095   } else {
4096     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4097   }
4098 }
4099 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotCaIntermediate)4100 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotCaIntermediate) {
4101   chain_[2]->SetBasicConstraints(/*is_ca=*/false, /*path_len=*/-1);
4102 
4103   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4104 }
4105 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsIsCaLeaf)4106 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsIsCaLeaf) {
4107   for (bool has_key_usage_cert_sign : {false, true}) {
4108     chain_[0]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/-1);
4109 
4110     if (has_key_usage_cert_sign) {
4111       chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
4112                                bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
4113     } else {
4114       chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
4115     }
4116     EXPECT_THAT(Verify(), IsOk());
4117   }
4118 }
4119 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen0Root)4120 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsPathlen0Root) {
4121   chain_[3]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/0);
4122 
4123   if (VerifyProcTypeIsBuiltin()) {
4124     EXPECT_THAT(Verify(), IsOk());
4125     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4126   } else if (VerifyProcTypeIsIOSAtMostOS14() ||
4127              verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4128     EXPECT_THAT(Verify(), IsOk());
4129   } else {
4130     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4131   }
4132 }
4133 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen1Root)4134 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsPathlen1Root) {
4135   chain_[3]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/1);
4136 
4137   if (VerifyProcTypeIsBuiltin()) {
4138     EXPECT_THAT(Verify(), IsOk());
4139     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4140   } else if (VerifyProcTypeIsIOSAtMostOS14() ||
4141              verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4142     EXPECT_THAT(Verify(), IsOk());
4143   } else {
4144     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4145   }
4146 }
4147 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen2Root)4148 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsPathlen2Root) {
4149   chain_[3]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/2);
4150 
4151   EXPECT_THAT(Verify(), IsOk());
4152   if (VerifyProcTypeIsBuiltin()) {
4153     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4154   }
4155 }
4156 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen0IntermediateParent)4157 TEST_P(CertVerifyProcConstraintsTest,
4158        BasicConstraintsPathlen0IntermediateParent) {
4159   chain_[2]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/0);
4160 
4161   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4162 }
4163 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen1IntermediateParent)4164 TEST_P(CertVerifyProcConstraintsTest,
4165        BasicConstraintsPathlen1IntermediateParent) {
4166   chain_[2]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/1);
4167 
4168   EXPECT_THAT(Verify(), IsOk());
4169 }
4170 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsPathlen0IntermediateChild)4171 TEST_P(CertVerifyProcConstraintsTest,
4172        BasicConstraintsPathlen0IntermediateChild) {
4173   chain_[1]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/0);
4174 
4175   EXPECT_THAT(Verify(), IsOk());
4176 }
4177 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotPresentRoot)4178 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotPresentRoot) {
4179   chain_[3]->EraseExtension(bssl::der::Input(bssl::kBasicConstraintsOid));
4180 
4181   if (VerifyProcTypeIsBuiltin()) {
4182     EXPECT_THAT(Verify(), IsOk());
4183     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4184     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4185                 IsError(ERR_CERT_INVALID));
4186   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4187     EXPECT_THAT(Verify(), IsOk());
4188   } else {
4189     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4190   }
4191 }
4192 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotPresentRootX509V1)4193 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotPresentRootX509V1) {
4194   chain_[3]->SetCertificateVersion(bssl::CertificateVersion::V1);
4195   chain_[3]->ClearExtensions();
4196 
4197   EXPECT_THAT(Verify(), IsOk());
4198   if (VerifyProcTypeIsBuiltin()) {
4199     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4200     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(), IsOk());
4201   }
4202 }
4203 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotPresentIntermediate)4204 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotPresentIntermediate) {
4205   chain_[2]->EraseExtension(bssl::der::Input(bssl::kBasicConstraintsOid));
4206 
4207   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4208 }
4209 
TEST_P(CertVerifyProcConstraintsTest,BasicConstraintsNotPresentLeaf)4210 TEST_P(CertVerifyProcConstraintsTest, BasicConstraintsNotPresentLeaf) {
4211   chain_[0]->EraseExtension(bssl::der::Input(bssl::kBasicConstraintsOid));
4212 
4213   EXPECT_THAT(Verify(), IsOk());
4214 }
4215 
TEST_P(CertVerifyProcConstraintsTest,NameConstraintsNotMatchingRoot)4216 TEST_P(CertVerifyProcConstraintsTest, NameConstraintsNotMatchingRoot) {
4217   chain_[3]->SetNameConstraintsDnsNames(/*permitted_dns_names=*/{"example.org"},
4218                                         /*excluded_dns_names=*/{});
4219 
4220   if (VerifyProcTypeIsBuiltin()) {
4221     EXPECT_THAT(Verify(), IsOk());
4222     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4223   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4224     EXPECT_THAT(Verify(), IsOk());
4225   } else {
4226     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4227   }
4228 }
4229 
TEST_P(CertVerifyProcConstraintsTest,NameConstraintsNotMatchingIntermediate)4230 TEST_P(CertVerifyProcConstraintsTest, NameConstraintsNotMatchingIntermediate) {
4231   chain_[2]->SetNameConstraintsDnsNames(
4232       /*permitted_dns_names=*/{"example.org"},
4233       /*excluded_dns_names=*/{});
4234 
4235   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4236 }
4237 
TEST_P(CertVerifyProcConstraintsTest,NameConstraintsMatchingRoot)4238 TEST_P(CertVerifyProcConstraintsTest, NameConstraintsMatchingRoot) {
4239   chain_[3]->SetNameConstraintsDnsNames(/*permitted_dns_names=*/{"example.com"},
4240                                         /*excluded_dns_names=*/{});
4241 
4242   EXPECT_THAT(Verify(), IsOk());
4243   if (VerifyProcTypeIsBuiltin()) {
4244     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4245   }
4246 }
4247 
TEST_P(CertVerifyProcConstraintsTest,NameConstraintsMatchingIntermediate)4248 TEST_P(CertVerifyProcConstraintsTest, NameConstraintsMatchingIntermediate) {
4249   chain_[2]->SetNameConstraintsDnsNames(
4250       /*permitted_dns_names=*/{"example.com"},
4251       /*excluded_dns_names=*/{});
4252 
4253   EXPECT_THAT(Verify(), IsOk());
4254 }
4255 
TEST_P(CertVerifyProcConstraintsTest,NameConstraintsOnLeaf)4256 TEST_P(CertVerifyProcConstraintsTest, NameConstraintsOnLeaf) {
4257   chain_[0]->SetNameConstraintsDnsNames(
4258       /*permitted_dns_names=*/{"example.com"},
4259       /*excluded_dns_names=*/{});
4260 
4261   // TODO(mattm): this should be an error
4262   // RFC 5280 4.2.1.10 says: "The name constraints extension, which MUST be
4263   // used only in a CA certificate, ..."
4264   EXPECT_THAT(Verify(), IsOk());
4265 }
4266 
TEST_P(CertVerifyProcConstraintsTest,ValidityExpiredRoot)4267 TEST_P(CertVerifyProcConstraintsTest, ValidityExpiredRoot) {
4268   chain_[3]->SetValidity(base::Time::Now() - base::Days(14),
4269                          base::Time::Now() - base::Days(7));
4270 
4271   if (VerifyProcTypeIsBuiltin()) {
4272     EXPECT_THAT(Verify(), IsOk());
4273     EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4274                 IsError(ERR_CERT_DATE_INVALID));
4275     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4276                 IsError(ERR_CERT_DATE_INVALID));
4277   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4278     EXPECT_THAT(Verify(), IsOk());
4279   } else {
4280     EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
4281   }
4282 }
4283 
TEST_P(CertVerifyProcConstraintsTest,ValidityNotYetValidRoot)4284 TEST_P(CertVerifyProcConstraintsTest, ValidityNotYetValidRoot) {
4285   chain_[3]->SetValidity(base::Time::Now() + base::Days(7),
4286                          base::Time::Now() + base::Days(14));
4287 
4288   if (VerifyProcTypeIsBuiltin()) {
4289     EXPECT_THAT(Verify(), IsOk());
4290     EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4291                 IsError(ERR_CERT_DATE_INVALID));
4292     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4293                 IsError(ERR_CERT_DATE_INVALID));
4294   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4295     EXPECT_THAT(Verify(), IsOk());
4296   } else {
4297     EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
4298   }
4299 }
4300 
TEST_P(CertVerifyProcConstraintsTest,ValidityExpiredIntermediate)4301 TEST_P(CertVerifyProcConstraintsTest, ValidityExpiredIntermediate) {
4302   chain_[2]->SetValidity(base::Time::Now() - base::Days(14),
4303                          base::Time::Now() - base::Days(7));
4304 
4305   if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4306     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
4307   } else {
4308     EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
4309   }
4310 }
4311 
TEST_P(CertVerifyProcConstraintsTest,ValidityNotYetValidIntermediate)4312 TEST_P(CertVerifyProcConstraintsTest, ValidityNotYetValidIntermediate) {
4313   chain_[2]->SetValidity(base::Time::Now() + base::Days(7),
4314                          base::Time::Now() + base::Days(14));
4315 
4316   if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4317     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
4318   } else {
4319     EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
4320   }
4321 }
4322 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints0Root)4323 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints0Root) {
4324   for (bool leaf_has_policy : {false, true}) {
4325     SCOPED_TRACE(leaf_has_policy);
4326 
4327     static const char kPolicy1[] = "1.2.3.4";
4328     static const char kPolicy2[] = "1.2.3.4.5";
4329     static const char kPolicy3[] = "1.2.3.5";
4330     chain_[3]->SetPolicyConstraints(
4331         /*require_explicit_policy=*/0,
4332         /*inhibit_policy_mapping=*/absl::nullopt);
4333     chain_[3]->SetCertificatePolicies({kPolicy1, kPolicy2});
4334     chain_[2]->SetCertificatePolicies({kPolicy3, kPolicy1});
4335     chain_[1]->SetCertificatePolicies({kPolicy1});
4336 
4337     if (leaf_has_policy) {
4338       chain_[0]->SetCertificatePolicies({kPolicy1});
4339       EXPECT_THAT(Verify(), IsOk());
4340       if (VerifyProcTypeIsBuiltin()) {
4341         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4342       }
4343     } else {
4344       chain_[0]->SetCertificatePolicies({});
4345       if (VerifyProcTypeIsBuiltin()) {
4346         EXPECT_THAT(Verify(), IsOk());
4347         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4348                     IsError(ERR_CERT_INVALID));
4349       } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4350                  verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4351         EXPECT_THAT(Verify(), IsOk());
4352       } else {
4353         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4354       }
4355     }
4356   }
4357 }
4358 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints4Root)4359 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints4Root) {
4360   // Explicit policy is required after 4 certs. Since the chain is 4 certs
4361   // long, an explicit policy is never required.
4362   chain_[3]->SetPolicyConstraints(
4363       /*require_explicit_policy=*/4,
4364       /*inhibit_policy_mapping=*/absl::nullopt);
4365 
4366   EXPECT_THAT(Verify(), IsOk());
4367   if (VerifyProcTypeIsBuiltin()) {
4368     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4369   }
4370 }
4371 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints3Root)4372 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints3Root) {
4373   // Explicit policy is required after 3 certs. Since the chain is 4 certs
4374   // long, an explicit policy is required and the chain should fail if anchor
4375   // constraints are enforced.
4376   chain_[3]->SetPolicyConstraints(
4377       /*require_explicit_policy=*/3,
4378       /*inhibit_policy_mapping=*/absl::nullopt);
4379 
4380   if (VerifyProcTypeIsBuiltin()) {
4381     EXPECT_THAT(Verify(), IsOk());
4382     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4383   } else {
4384     // Windows seems to have an off-by-one error in how it enforces
4385     // requireExplicitPolicy.
4386     // (The mac/android verifiers are Ok here since they don't enforce
4387     // policyConstraints on anchors.)
4388     EXPECT_THAT(Verify(), IsOk());
4389   }
4390 }
4391 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints2Root)4392 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints2Root) {
4393   // Explicit policy is required after 2 certs. Since the chain is 4 certs
4394   // long, an explicit policy is required and the chain should fail if anchor
4395   // constraints are enforced.
4396   chain_[3]->SetPolicyConstraints(
4397       /*require_explicit_policy=*/2,
4398       /*inhibit_policy_mapping=*/absl::nullopt);
4399 
4400   if (VerifyProcTypeIsBuiltin()) {
4401     EXPECT_THAT(Verify(), IsOk());
4402     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4403   } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4404              verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4405     EXPECT_THAT(Verify(), IsOk());
4406   } else {
4407     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4408   }
4409 }
4410 
4411 // This is also a regression test for https://crbug.com/31497: If an
4412 // intermediate has requireExplicitPolicy in its policyConstraints extension,
4413 // verification should still succeed as long as some policy is valid for the
4414 // chain, since Chrome does not specify any required policy as an input to
4415 // certificate verification (allows anyPolicy).
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints0Intermediate)4416 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints0Intermediate) {
4417   for (bool leaf_has_policy : {false, true}) {
4418     SCOPED_TRACE(leaf_has_policy);
4419 
4420     static const char kPolicy1[] = "1.2.3.4";
4421     static const char kPolicy2[] = "1.2.3.4.5";
4422     static const char kPolicy3[] = "1.2.3.5";
4423     chain_[2]->SetPolicyConstraints(
4424         /*require_explicit_policy=*/0,
4425         /*inhibit_policy_mapping=*/absl::nullopt);
4426     chain_[2]->SetCertificatePolicies({kPolicy1, kPolicy2});
4427     chain_[1]->SetCertificatePolicies({kPolicy3, kPolicy1});
4428 
4429     if (leaf_has_policy) {
4430       chain_[0]->SetCertificatePolicies({kPolicy1});
4431       EXPECT_THAT(Verify(), IsOk());
4432       if (VerifyProcTypeIsBuiltin()) {
4433         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4434       }
4435     } else {
4436       chain_[0]->SetCertificatePolicies({});
4437       EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4438       if (VerifyProcTypeIsBuiltin()) {
4439         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4440                     IsError(ERR_CERT_INVALID));
4441       }
4442     }
4443   }
4444 }
4445 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints3Intermediate)4446 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints3Intermediate) {
4447   // Explicit policy is required after 3 certs. Since the chain up to
4448   // |chain_[2]| is 3 certs long, an explicit policy is never required.
4449   chain_[2]->SetPolicyConstraints(
4450       /*require_explicit_policy=*/3,
4451       /*inhibit_policy_mapping=*/absl::nullopt);
4452 
4453   EXPECT_THAT(Verify(), IsOk());
4454   if (VerifyProcTypeIsBuiltin()) {
4455     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4456   }
4457 }
4458 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints2Intermediate)4459 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints2Intermediate) {
4460   // Explicit policy is required after 2 certs. Since the chain up to
4461   // |chain_[2]| is 3 certs long, an explicit policy will be required and this
4462   // should fail to verify.
4463   chain_[2]->SetPolicyConstraints(
4464       /*require_explicit_policy=*/2,
4465       /*inhibit_policy_mapping=*/absl::nullopt);
4466 
4467     EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4468     if (VerifyProcTypeIsBuiltin()) {
4469       EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4470     }
4471 }
4472 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints1Intermediate)4473 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints1Intermediate) {
4474   // Explicit policy is required after 1 cert. Since the chain up to
4475   // |chain_[2]| is 3 certs long, an explicit policy will be required and this
4476   // should fail to verify.
4477   chain_[2]->SetPolicyConstraints(
4478       /*require_explicit_policy=*/1,
4479       /*inhibit_policy_mapping=*/absl::nullopt);
4480 
4481   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4482   if (VerifyProcTypeIsBuiltin()) {
4483     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4484   }
4485 }
4486 
TEST_P(CertVerifyProcConstraintsTest,PolicyConstraints0Leaf)4487 TEST_P(CertVerifyProcConstraintsTest, PolicyConstraints0Leaf) {
4488   // Setting requireExplicitPolicy to 0 on the target certificate should make
4489   // an explicit policy required for the chain. (Ref: RFC 5280 section 6.1.5.b
4490   // and the final paragraph of 6.1.5)
4491   chain_[0]->SetPolicyConstraints(
4492       /*require_explicit_policy=*/0,
4493       /*inhibit_policy_mapping=*/absl::nullopt);
4494 
4495   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4496 }
4497 
TEST_P(CertVerifyProcConstraintsTest,InhibitPolicyMapping0Root)4498 TEST_P(CertVerifyProcConstraintsTest, InhibitPolicyMapping0Root) {
4499   static const char kPolicy1[] = "1.2.3.4";
4500   static const char kPolicy2[] = "1.2.3.5";
4501 
4502   // Root inhibits policy mapping immediately.
4503   chain_[3]->SetPolicyConstraints(
4504       /*require_explicit_policy=*/absl::nullopt,
4505       /*inhibit_policy_mapping=*/0);
4506 
4507   // Policy constraints are specified on an intermediate so that an explicit
4508   // policy will be required regardless if root constraints are applied.
4509   chain_[2]->SetPolicyConstraints(
4510       /*require_explicit_policy=*/0,
4511       /*inhibit_policy_mapping=*/absl::nullopt);
4512 
4513   // Intermediate uses policy mappings. This should not be allowed if the root
4514   // constraints were enforced.
4515   chain_[2]->SetCertificatePolicies({kPolicy1});
4516   chain_[2]->SetPolicyMappings({{kPolicy1, kPolicy2}});
4517 
4518   // Children require the policy mapping to have a valid policy.
4519   chain_[1]->SetCertificatePolicies({kPolicy2});
4520   chain_[0]->SetCertificatePolicies({kPolicy2});
4521 
4522   if (VerifyProcTypeIsBuiltin()) {
4523     EXPECT_THAT(Verify(), IsOk());
4524     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4525   } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4526              verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4527     EXPECT_THAT(Verify(), IsOk());
4528   } else {
4529     // Windows enforces inhibitPolicyMapping on the root.
4530     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4531   }
4532 }
4533 
TEST_P(CertVerifyProcConstraintsTest,InhibitPolicyMapping1Root)4534 TEST_P(CertVerifyProcConstraintsTest, InhibitPolicyMapping1Root) {
4535   static const char kPolicy1[] = "1.2.3.4";
4536   static const char kPolicy2[] = "1.2.3.5";
4537 
4538   // Root inhibits policy mapping after 1 cert.
4539   chain_[3]->SetPolicyConstraints(
4540       /*require_explicit_policy=*/absl::nullopt,
4541       /*inhibit_policy_mapping=*/1);
4542 
4543   // Policy constraints are specified on an intermediate so that an explicit
4544   // policy will be required regardless if root constraints are applied.
4545   chain_[2]->SetPolicyConstraints(
4546       /*require_explicit_policy=*/0,
4547       /*inhibit_policy_mapping=*/absl::nullopt);
4548 
4549   // Intermediate uses policy mappings. This should be allowed even if the root
4550   // constraints were enforced, since policy mapping was allowed for 1 cert
4551   // following the root.
4552   chain_[2]->SetCertificatePolicies({kPolicy1});
4553   chain_[2]->SetPolicyMappings({{kPolicy1, kPolicy2}});
4554 
4555   // Children require the policy mapping to have a valid policy.
4556   chain_[1]->SetCertificatePolicies({kPolicy2});
4557   chain_[0]->SetCertificatePolicies({kPolicy2});
4558 
4559   EXPECT_THAT(Verify(), IsOk());
4560   if (VerifyProcTypeIsBuiltin()) {
4561     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4562   }
4563 }
4564 
TEST_P(CertVerifyProcConstraintsTest,InhibitAnyPolicy0Root)4565 TEST_P(CertVerifyProcConstraintsTest, InhibitAnyPolicy0Root) {
4566   static const char kAnyPolicy[] = "2.5.29.32.0";
4567   static const char kPolicy1[] = "1.2.3.4";
4568 
4569   // Since inhibitAnyPolicy is 0, anyPolicy should not be allow for any certs
4570   // after the root.
4571   chain_[3]->SetInhibitAnyPolicy(0);
4572   chain_[3]->SetCertificatePolicies({kAnyPolicy});
4573 
4574   // Policy constraints are specified on an intermediate so that an explicit
4575   // policy will be required regardless if root constraints are applied.
4576   chain_[2]->SetPolicyConstraints(
4577       /*require_explicit_policy=*/0,
4578       /*inhibit_policy_mapping=*/absl::nullopt);
4579 
4580   // This intermediate only asserts anyPolicy, so this chain should
4581   // be invalid if policyConstraints from the root cert are enforced.
4582   chain_[2]->SetCertificatePolicies({kAnyPolicy});
4583 
4584   chain_[1]->SetCertificatePolicies({kPolicy1});
4585   chain_[0]->SetCertificatePolicies({kPolicy1});
4586 
4587   if (VerifyProcTypeIsBuiltin()) {
4588     EXPECT_THAT(Verify(), IsOk());
4589     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4590   } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4591              verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4592     EXPECT_THAT(Verify(), IsOk());
4593   } else {
4594     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4595   }
4596 }
4597 
TEST_P(CertVerifyProcConstraintsTest,InhibitAnyPolicy1Root)4598 TEST_P(CertVerifyProcConstraintsTest, InhibitAnyPolicy1Root) {
4599   for (bool chain_1_has_any_policy : {false, true}) {
4600     SCOPED_TRACE(chain_1_has_any_policy);
4601 
4602     static const char kAnyPolicy[] = "2.5.29.32.0";
4603     static const char kPolicy1[] = "1.2.3.4";
4604 
4605     // Since inhibitAnyPolicy is 1, anyPolicy should be allowed for the root's
4606     // immediate child, but not after that.
4607     chain_[3]->SetInhibitAnyPolicy(1);
4608     chain_[3]->SetCertificatePolicies({kAnyPolicy});
4609 
4610     // Policy constraints are specified on an intermediate so that an explicit
4611     // policy will be required regardless if root constraints are applied.
4612     chain_[2]->SetPolicyConstraints(
4613         /*require_explicit_policy=*/0,
4614         /*inhibit_policy_mapping=*/absl::nullopt);
4615 
4616     // AnyPolicy should be allowed in this cert.
4617     chain_[2]->SetCertificatePolicies({kAnyPolicy});
4618 
4619     chain_[0]->SetCertificatePolicies({kPolicy1});
4620 
4621     if (chain_1_has_any_policy) {
4622       // AnyPolicy should not be allowed in this cert if the inhibitAnyPolicy
4623       // constraint from the root is honored.
4624       chain_[1]->SetCertificatePolicies({kAnyPolicy});
4625 
4626       if (VerifyProcTypeIsBuiltin()) {
4627         EXPECT_THAT(Verify(), IsOk());
4628         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4629                     IsError(ERR_CERT_INVALID));
4630       } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4631                  verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4632         EXPECT_THAT(Verify(), IsOk());
4633       } else {
4634         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4635       }
4636     } else {
4637       chain_[1]->SetCertificatePolicies({kPolicy1});
4638 
4639       EXPECT_THAT(Verify(), IsOk());
4640       if (VerifyProcTypeIsBuiltin()) {
4641         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4642       }
4643     }
4644   }
4645 }
4646 
TEST_P(CertVerifyProcConstraintsTest,InhibitAnyPolicy0Intermediate)4647 TEST_P(CertVerifyProcConstraintsTest, InhibitAnyPolicy0Intermediate) {
4648   static const char kAnyPolicy[] = "2.5.29.32.0";
4649   static const char kPolicy1[] = "1.2.3.4";
4650 
4651   chain_[2]->SetInhibitAnyPolicy(0);
4652   chain_[2]->SetPolicyConstraints(
4653       /*require_explicit_policy=*/0,
4654       /*inhibit_policy_mapping=*/absl::nullopt);
4655 
4656   chain_[2]->SetCertificatePolicies({kAnyPolicy});
4657   // This shouldn't be allowed as the parent cert set inhibitAnyPolicy=0.
4658   chain_[1]->SetCertificatePolicies({kAnyPolicy});
4659   chain_[0]->SetCertificatePolicies({kPolicy1});
4660 
4661   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4662 }
4663 
TEST_P(CertVerifyProcConstraintsTest,InhibitAnyPolicy1Intermediate)4664 TEST_P(CertVerifyProcConstraintsTest, InhibitAnyPolicy1Intermediate) {
4665   static const char kAnyPolicy[] = "2.5.29.32.0";
4666   static const char kPolicy1[] = "1.2.3.4";
4667 
4668   chain_[2]->SetInhibitAnyPolicy(1);
4669   chain_[2]->SetPolicyConstraints(
4670       /*require_explicit_policy=*/0,
4671       /*inhibit_policy_mapping=*/absl::nullopt);
4672 
4673   chain_[2]->SetCertificatePolicies({kAnyPolicy});
4674   // This is okay as the parent cert set inhibitAnyPolicy=1.
4675   chain_[1]->SetCertificatePolicies({kAnyPolicy});
4676   chain_[0]->SetCertificatePolicies({kPolicy1});
4677 
4678   EXPECT_THAT(Verify(), IsOk());
4679 }
4680 
TEST_P(CertVerifyProcConstraintsTest,PoliciesRoot)4681 TEST_P(CertVerifyProcConstraintsTest, PoliciesRoot) {
4682   static const char kPolicy1[] = "1.2.3.4";
4683   static const char kPolicy2[] = "1.2.3.5";
4684 
4685   for (bool root_has_matching_policy : {false, true}) {
4686     SCOPED_TRACE(root_has_matching_policy);
4687 
4688     if (root_has_matching_policy) {
4689       // This chain should be valid whether or not policies from the root are
4690       // processed.
4691       chain_[3]->SetCertificatePolicies({kPolicy1});
4692     } else {
4693       // If the policies from the root are processed, this chain will not be
4694       // valid for any policy.
4695       chain_[3]->SetCertificatePolicies({kPolicy2});
4696     }
4697 
4698     // Policy constraints are specified on an intermediate so that an explicit
4699     // policy will be required regardless if root constraints are applied.
4700     chain_[2]->SetPolicyConstraints(
4701         /*require_explicit_policy=*/0,
4702         /*inhibit_policy_mapping=*/absl::nullopt);
4703 
4704     chain_[2]->SetCertificatePolicies({kPolicy1});
4705     chain_[1]->SetCertificatePolicies({kPolicy1});
4706     chain_[0]->SetCertificatePolicies({kPolicy1});
4707 
4708     if (root_has_matching_policy) {
4709       EXPECT_THAT(Verify(), IsOk());
4710       if (VerifyProcTypeIsBuiltin()) {
4711         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4712       }
4713     } else {
4714       if (VerifyProcTypeIsBuiltin()) {
4715         EXPECT_THAT(Verify(), IsOk());
4716         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4717                     IsError(ERR_CERT_INVALID));
4718       } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4719                  verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4720         EXPECT_THAT(Verify(), IsOk());
4721       } else {
4722         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4723       }
4724     }
4725   }
4726 }
4727 
TEST_P(CertVerifyProcConstraintsTest,PolicyMappingsRoot)4728 TEST_P(CertVerifyProcConstraintsTest, PolicyMappingsRoot) {
4729   static const char kPolicy1[] = "1.2.3.4";
4730   static const char kPolicy2[] = "1.2.3.5";
4731   static const char kPolicy3[] = "1.2.3.6";
4732 
4733   for (bool root_has_matching_policy_mapping : {false, true}) {
4734     SCOPED_TRACE(root_has_matching_policy_mapping);
4735 
4736     if (root_has_matching_policy_mapping) {
4737       // This chain should be valid if the policies and policy mapping on the
4738       // root are processed, or if neither is processed. It will not be valid
4739       // if the policies were processed and the policyMappings were not.
4740       chain_[3]->SetCertificatePolicies({kPolicy1});
4741       chain_[3]->SetPolicyMappings({{kPolicy1, kPolicy2}});
4742     } else {
4743       // This chain should not be valid if the policies and policyMappings on
4744       // the root were processed. It will be valid if the policies were
4745       // processed and policyMappings were not.
4746       chain_[3]->SetCertificatePolicies({kPolicy2});
4747       chain_[3]->SetPolicyMappings({{kPolicy2, kPolicy3}});
4748     }
4749 
4750     // Policy constraints are specified on an intermediate so that an explicit
4751     // policy will be required regardless if root constraints are applied.
4752     chain_[2]->SetPolicyConstraints(
4753         /*require_explicit_policy=*/0,
4754         /*inhibit_policy_mapping=*/absl::nullopt);
4755 
4756     chain_[2]->SetCertificatePolicies({kPolicy2});
4757     chain_[1]->SetCertificatePolicies({kPolicy2});
4758     chain_[0]->SetCertificatePolicies({kPolicy2});
4759 
4760     if (root_has_matching_policy_mapping) {
4761       EXPECT_THAT(Verify(), IsOk());
4762       if (VerifyProcTypeIsBuiltin()) {
4763         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4764       }
4765     } else {
4766       if (VerifyProcTypeIsBuiltin()) {
4767         EXPECT_THAT(Verify(), IsOk());
4768         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4769                     IsError(ERR_CERT_INVALID));
4770       } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4771                  verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4772         EXPECT_THAT(Verify(), IsOk());
4773       } else {
4774         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4775       }
4776     }
4777   }
4778 }
4779 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNoCertSignRoot)4780 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNoCertSignRoot) {
4781   chain_[3]->SetKeyUsages({bssl::KEY_USAGE_BIT_CRL_SIGN});
4782 
4783   if (VerifyProcTypeIsBuiltin()) {
4784     EXPECT_THAT(Verify(), IsOk());
4785     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4786     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4787                 IsError(ERR_CERT_INVALID));
4788   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4789     EXPECT_THAT(Verify(), IsOk());
4790   } else {
4791     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4792   }
4793 }
4794 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNotPresentRoot)4795 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNotPresentRoot) {
4796   chain_[3]->EraseExtension(bssl::der::Input(bssl::kKeyUsageOid));
4797 
4798   EXPECT_THAT(Verify(), IsOk());
4799   if (VerifyProcTypeIsBuiltin()) {
4800     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4801     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(), IsOk());
4802   }
4803 }
4804 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNoCertSignIntermediate)4805 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNoCertSignIntermediate) {
4806   chain_[2]->SetKeyUsages({bssl::KEY_USAGE_BIT_CRL_SIGN});
4807 
4808   EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4809 }
4810 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNotPresentIntermediate)4811 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNotPresentIntermediate) {
4812   chain_[2]->EraseExtension(bssl::der::Input(bssl::kKeyUsageOid));
4813 
4814   EXPECT_THAT(Verify(), IsOk());
4815 }
4816 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNoDigitalSignatureLeaf)4817 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNoDigitalSignatureLeaf) {
4818   // This test is mostly uninteresting since keyUsage on the end-entity is only
4819   // checked at the TLS layer, not during cert verification.
4820   chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_CRL_SIGN});
4821 
4822   EXPECT_THAT(Verify(), IsOk());
4823 }
4824 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageNotPresentLeaf)4825 TEST_P(CertVerifyProcConstraintsTest, KeyUsageNotPresentLeaf) {
4826   // This test is mostly uninteresting since keyUsage on the end-entity is only
4827   // checked at the TLS layer, not during cert verification.
4828   chain_[0]->EraseExtension(bssl::der::Input(bssl::kKeyUsageOid));
4829 
4830   EXPECT_THAT(Verify(), IsOk());
4831 }
4832 
TEST_P(CertVerifyProcConstraintsTest,KeyUsageCertSignLeaf)4833 TEST_P(CertVerifyProcConstraintsTest, KeyUsageCertSignLeaf) {
4834   // Test a leaf that has keyUsage asserting keyCertSign and basicConstraints
4835   // asserting CA=false. This should be an error according to 5280 section
4836   // 4.2.1.3 and 4.2.1.9, however most implementations seem to allow it.
4837   // Perhaps because 5280 section 6 does not explicitly say to enforce this on
4838   // the target cert.
4839   chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
4840                            bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
4841 
4842   EXPECT_THAT(Verify(), IsOk());
4843   if (VerifyProcTypeIsBuiltin()) {
4844     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4845     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(), IsOk());
4846   }
4847 }
4848 
TEST_P(CertVerifyProcConstraintsTest,ExtendedKeyUsageNoServerAuthRoot)4849 TEST_P(CertVerifyProcConstraintsTest, ExtendedKeyUsageNoServerAuthRoot) {
4850   chain_[3]->SetExtendedKeyUsages({bssl::der::Input(bssl::kCodeSigning)});
4851 
4852   if (VerifyProcTypeIsBuiltin()) {
4853     EXPECT_THAT(Verify(), IsOk());
4854     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsError(ERR_CERT_INVALID));
4855     EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4856                 IsError(ERR_CERT_INVALID));
4857   } else if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID ||
4858              verify_proc_type() == CERT_VERIFY_PROC_IOS) {
4859     EXPECT_THAT(Verify(), IsOk());
4860   } else {
4861     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4862   }
4863 }
4864 
TEST_P(CertVerifyProcConstraintsTest,ExtendedKeyUsageServerAuthRoot)4865 TEST_P(CertVerifyProcConstraintsTest, ExtendedKeyUsageServerAuthRoot) {
4866   chain_[3]->SetExtendedKeyUsages({bssl::der::Input(bssl::kServerAuth)});
4867 
4868   EXPECT_THAT(Verify(), IsOk());
4869   if (VerifyProcTypeIsBuiltin()) {
4870     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4871   }
4872 }
4873 
TEST_P(CertVerifyProcConstraintsTest,ExtendedKeyUsageNoServerAuthIntermediate)4874 TEST_P(CertVerifyProcConstraintsTest,
4875        ExtendedKeyUsageNoServerAuthIntermediate) {
4876   chain_[2]->SetExtendedKeyUsages({bssl::der::Input(bssl::kCodeSigning)});
4877 
4878   if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID ||
4879       VerifyProcTypeIsIOSAtMostOS15()) {
4880     EXPECT_THAT(Verify(), IsOk());
4881   } else {
4882     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4883   }
4884 }
4885 
TEST_P(CertVerifyProcConstraintsTest,ExtendedKeyUsageServerAuthIntermediate)4886 TEST_P(CertVerifyProcConstraintsTest, ExtendedKeyUsageServerAuthIntermediate) {
4887   chain_[2]->SetExtendedKeyUsages({bssl::der::Input(bssl::kServerAuth)});
4888 
4889   EXPECT_THAT(Verify(), IsOk());
4890 }
4891 
TEST_P(CertVerifyProcConstraintsTest,ExtendedKeyUsageNoServerAuthLeaf)4892 TEST_P(CertVerifyProcConstraintsTest, ExtendedKeyUsageNoServerAuthLeaf) {
4893   chain_[0]->SetExtendedKeyUsages({bssl::der::Input(bssl::kCodeSigning)});
4894 
4895   EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4896 }
4897 
TEST_P(CertVerifyProcConstraintsTest,UnknownSignatureAlgorithmRoot)4898 TEST_P(CertVerifyProcConstraintsTest, UnknownSignatureAlgorithmRoot) {
4899   chain_[3]->SetSignatureAlgorithmTLV(TestOid0SignatureAlgorithmTLV());
4900 
4901   EXPECT_THAT(Verify(), IsOk());
4902   if (VerifyProcTypeIsBuiltin()) {
4903     EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4904   }
4905 }
4906 
TEST_P(CertVerifyProcConstraintsTest,UnknownSignatureAlgorithmIntermediate)4907 TEST_P(CertVerifyProcConstraintsTest, UnknownSignatureAlgorithmIntermediate) {
4908   chain_[2]->SetSignatureAlgorithmTLV(TestOid0SignatureAlgorithmTLV());
4909 
4910   if (verify_proc_type() == CERT_VERIFY_PROC_IOS) {
4911     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
4912   } else {
4913     EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4914   }
4915 }
4916 
TEST_P(CertVerifyProcConstraintsTest,UnknownSignatureAlgorithmLeaf)4917 TEST_P(CertVerifyProcConstraintsTest, UnknownSignatureAlgorithmLeaf) {
4918   chain_[0]->SetSignatureAlgorithmTLV(TestOid0SignatureAlgorithmTLV());
4919 
4920   if (verify_proc_type() == CERT_VERIFY_PROC_IOS) {
4921     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
4922   } else {
4923     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4924   }
4925 }
4926 
TEST_P(CertVerifyProcConstraintsTest,UnknownExtensionRoot)4927 TEST_P(CertVerifyProcConstraintsTest, UnknownExtensionRoot) {
4928   for (bool critical : {true, false}) {
4929     SCOPED_TRACE(critical);
4930     chain_[3]->SetExtension(TestOid0(), "hello world", critical);
4931 
4932     if (critical) {
4933       if (VerifyProcTypeIsBuiltin()) {
4934         EXPECT_THAT(Verify(), IsOk());
4935         EXPECT_THAT(VerifyWithExpiryAndConstraints(),
4936                     IsError(ERR_CERT_INVALID));
4937         EXPECT_THAT(VerifyWithExpiryAndFullConstraints(),
4938                     IsError(ERR_CERT_INVALID));
4939       } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS ||
4940                  verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
4941         EXPECT_THAT(Verify(), IsOk());
4942       } else {
4943         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
4944       }
4945     } else {
4946       EXPECT_THAT(Verify(), IsOk());
4947       if (VerifyProcTypeIsBuiltin()) {
4948         EXPECT_THAT(VerifyWithExpiryAndConstraints(), IsOk());
4949       }
4950     }
4951   }
4952 }
4953 
TEST_P(CertVerifyProcConstraintsTest,UnknownExtensionIntermediate)4954 TEST_P(CertVerifyProcConstraintsTest, UnknownExtensionIntermediate) {
4955   for (bool critical : {true, false}) {
4956     SCOPED_TRACE(critical);
4957     chain_[2]->SetExtension(TestOid0(), "hello world", critical);
4958 
4959     if (critical) {
4960       EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4961     } else {
4962       EXPECT_THAT(Verify(), IsOk());
4963     }
4964   }
4965 }
4966 
TEST_P(CertVerifyProcConstraintsTest,UnknownExtensionLeaf)4967 TEST_P(CertVerifyProcConstraintsTest, UnknownExtensionLeaf) {
4968   for (bool critical : {true, false}) {
4969     SCOPED_TRACE(critical);
4970     chain_[0]->SetExtension(TestOid0(), "hello world", critical);
4971 
4972     if (critical) {
4973       EXPECT_THAT(Verify(), IsError(ExpectedIntermediateConstraintError()));
4974     } else {
4975       EXPECT_THAT(Verify(), IsOk());
4976     }
4977   }
4978 }
4979 
4980 // A set of tests that check how various constraints are enforced when they
4981 // are applied to a directly trusted non-self-signed leaf certificate.
4982 class CertVerifyProcConstraintsTrustedLeafTest
4983     : public CertVerifyProcInternalTest {
4984  protected:
SetUp()4985   void SetUp() override {
4986     CertVerifyProcInternalTest::SetUp();
4987 
4988     chain_ = CertBuilder::CreateSimpleChain(/*chain_length=*/2);
4989   }
4990 
VerifyWithTrust(bssl::CertificateTrust trust)4991   int VerifyWithTrust(bssl::CertificateTrust trust) {
4992     ScopedTestRoot test_root(chain_[0]->GetX509Certificate(), trust);
4993     CertVerifyResult verify_result;
4994     int flags = 0;
4995     return CertVerifyProcInternalTest::Verify(
4996         chain_.front()->GetX509Certificate().get(), "www.example.com", flags,
4997         &verify_result);
4998   }
4999 
Verify()5000   int Verify() {
5001     return VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor());
5002   }
5003 
VerifyAsTrustedLeaf()5004   int VerifyAsTrustedLeaf() {
5005     return VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf());
5006   }
5007 
5008   std::vector<std::unique_ptr<CertBuilder>> chain_;
5009 };
5010 
5011 INSTANTIATE_TEST_SUITE_P(All,
5012                          CertVerifyProcConstraintsTrustedLeafTest,
5013                          testing::ValuesIn(kAllCertVerifiers),
5014                          VerifyProcTypeToName);
5015 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,BaseCase)5016 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, BaseCase) {
5017   // Without changing anything on the test chain, it should validate
5018   // successfully. If this is not true then the rest of the tests in this class
5019   // are unlikely to be useful.
5020   if (VerifyProcTypeIsBuiltin()) {
5021     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5022     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5023     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()),
5024                 IsOk());
5025     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()
5026                                     .WithRequireLeafSelfSigned()),
5027                 IsError(ERR_CERT_AUTHORITY_INVALID));
5028     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5029                                     .WithRequireLeafSelfSigned()),
5030                 IsError(ERR_CERT_AUTHORITY_INVALID));
5031   } else {
5032     EXPECT_THAT(Verify(), IsOk());
5033   }
5034 }
5035 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,RootAlsoTrusted)5036 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, RootAlsoTrusted) {
5037   // Test verifying a chain where both the leaf and the root are marked as
5038   // trusted.
5039   // (Repeating the ScopedTestRoot before each call is due to the limitation
5040   // with destroying any ScopedTestRoot removing all test roots.)
5041   {
5042     ScopedTestRoot test_root(chain_[1]->GetX509Certificate());
5043     EXPECT_THAT(Verify(), IsOk());
5044   }
5045 
5046   if (VerifyProcTypeIsBuiltin()) {
5047     {
5048       ScopedTestRoot test_root1(chain_[1]->GetX509Certificate());
5049       // An explicit trust entry for the leaf with a value of Unspecified
5050       // should be no different than the leaf not being in the trust store at
5051       // all.
5052       EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForUnspecified()),
5053                   IsOk());
5054     }
5055     {
5056       ScopedTestRoot test_root1(chain_[1]->GetX509Certificate());
5057       // If the leaf is explicitly distrusted, verification should fail even if
5058       // the root is trusted.
5059       EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForDistrusted()),
5060                   IsError(ERR_CERT_AUTHORITY_INVALID));
5061     }
5062     {
5063       ScopedTestRoot test_root(chain_[1]->GetX509Certificate());
5064       EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5065     }
5066     {
5067       ScopedTestRoot test_root(chain_[1]->GetX509Certificate());
5068       EXPECT_THAT(
5069           VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()),
5070           IsOk());
5071     }
5072     {
5073       ScopedTestRoot test_root(chain_[1]->GetX509Certificate());
5074       EXPECT_THAT(
5075           VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()),
5076           IsOk());
5077     }
5078     {
5079       ScopedTestRoot test_root(chain_[1]->GetX509Certificate());
5080       EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5081                                       .WithRequireLeafSelfSigned()),
5082                   IsOk());
5083     }
5084   }
5085 }
5086 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,BasicConstraintsIsCa)5087 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, BasicConstraintsIsCa) {
5088   for (bool has_key_usage_cert_sign : {false, true}) {
5089     chain_[0]->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/-1);
5090 
5091     if (has_key_usage_cert_sign) {
5092       chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
5093                                bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5094     } else {
5095       chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5096     }
5097 
5098     if (VerifyProcTypeIsBuiltin()) {
5099       EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5100       EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5101     } else {
5102       EXPECT_THAT(Verify(), IsOk());
5103     }
5104   }
5105 }
5106 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,BasicConstraintsPathlen)5107 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, BasicConstraintsPathlen) {
5108   chain_[0]->SetBasicConstraints(/*is_ca=*/false, /*path_len=*/0);
5109 
5110   if (VerifyProcTypeIsBuiltin()) {
5111     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5112   } else {
5113     EXPECT_THAT(Verify(), IsOk());
5114   }
5115 }
5116 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,BasicConstraintsMissing)5117 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, BasicConstraintsMissing) {
5118   chain_[0]->EraseExtension(bssl::der::Input(bssl::kBasicConstraintsOid));
5119 
5120   if (VerifyProcTypeIsBuiltin()) {
5121     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5122     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5123   } else {
5124     EXPECT_THAT(Verify(), IsOk());
5125   }
5126 }
5127 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,NameConstraintsNotMatching)5128 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, NameConstraintsNotMatching) {
5129   chain_[0]->SetNameConstraintsDnsNames(/*permitted_dns_names=*/{"example.org"},
5130                                         /*excluded_dns_names=*/{});
5131 
5132   if (VerifyProcTypeIsBuiltin()) {
5133     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5134   } else {
5135     EXPECT_THAT(Verify(), IsOk());
5136   }
5137 }
5138 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,ValidityExpired)5139 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, ValidityExpired) {
5140   chain_[0]->SetValidity(base::Time::Now() - base::Days(14),
5141                          base::Time::Now() - base::Days(7));
5142 
5143   if (VerifyProcTypeIsBuiltin()) {
5144     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5145     EXPECT_THAT(VerifyAsTrustedLeaf(), IsError(ERR_CERT_DATE_INVALID));
5146   } else {
5147     EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
5148   }
5149 }
5150 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,PolicyConstraints)5151 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, PolicyConstraints) {
5152   static const char kPolicy1[] = "1.2.3.4";
5153 
5154   for (bool leaf_has_policy : {false, true}) {
5155     SCOPED_TRACE(leaf_has_policy);
5156 
5157     chain_[0]->SetPolicyConstraints(
5158         /*require_explicit_policy=*/0,
5159         /*inhibit_policy_mapping=*/absl::nullopt);
5160     if (leaf_has_policy) {
5161       chain_[0]->SetCertificatePolicies({kPolicy1});
5162     } else {
5163       chain_[0]->SetCertificatePolicies({});
5164     }
5165 
5166     if (VerifyProcTypeIsBuiltin()) {
5167       EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5168       EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5169     } else {
5170       // Succeeds since the ios/android verifiers appear to not enforce
5171       // this constraint in the "directly trusted leaf" case.
5172       EXPECT_THAT(Verify(), IsOk());
5173     }
5174   }
5175 }
5176 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,InhibitAnyPolicy)5177 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, InhibitAnyPolicy) {
5178   static const char kAnyPolicy[] = "2.5.29.32.0";
5179   chain_[0]->SetPolicyConstraints(
5180       /*require_explicit_policy=*/0,
5181       /*inhibit_policy_mapping=*/absl::nullopt);
5182   chain_[0]->SetInhibitAnyPolicy(0);
5183   chain_[0]->SetCertificatePolicies({kAnyPolicy});
5184 
5185   if (VerifyProcTypeIsBuiltin()) {
5186     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5187     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5188   } else {
5189     EXPECT_THAT(Verify(), IsOk());
5190   }
5191 }
5192 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,KeyUsageNoDigitalSignature)5193 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, KeyUsageNoDigitalSignature) {
5194   // This test is mostly uninteresting since keyUsage on the end-entity is only
5195   // checked at the TLS layer, not during cert verification.
5196   chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_CRL_SIGN});
5197 
5198   if (VerifyProcTypeIsBuiltin()) {
5199     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5200     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5201   } else {
5202     EXPECT_THAT(Verify(), IsOk());
5203   }
5204 }
5205 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,KeyUsageCertSignLeaf)5206 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, KeyUsageCertSignLeaf) {
5207   // Test a leaf that has keyUsage asserting keyCertSign with basicConstraints
5208   // CA=false, which is an error according to 5280 (4.2.1.3 and 4.2.1.9).
5209   chain_[0]->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
5210                            bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5211 
5212   if (VerifyProcTypeIsBuiltin()) {
5213     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5214     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5215   } else {
5216     EXPECT_THAT(Verify(), IsOk());
5217   }
5218 }
5219 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,ExtendedKeyUsageNoServerAuth)5220 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, ExtendedKeyUsageNoServerAuth) {
5221   chain_[0]->SetExtendedKeyUsages({bssl::der::Input(bssl::kCodeSigning)});
5222 
5223   if (VerifyProcTypeIsBuiltin()) {
5224     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5225     EXPECT_THAT(VerifyAsTrustedLeaf(), IsError(ERR_CERT_INVALID));
5226   } else {
5227     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5228   }
5229 }
5230 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,UnknownSignatureAlgorithm)5231 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, UnknownSignatureAlgorithm) {
5232   chain_[0]->SetSignatureAlgorithmTLV(TestOid0SignatureAlgorithmTLV());
5233 
5234   if (VerifyProcTypeIsBuiltin()) {
5235     // Since no chain is found, signature is not checked, fails with generic
5236     // error for untrusted chain.
5237     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5238     // Valid since signature on directly trusted leaf is not checked.
5239     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5240   } else {
5241     EXPECT_THAT(Verify(), IsOk());
5242   }
5243 }
5244 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,WeakSignatureAlgorithm)5245 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, WeakSignatureAlgorithm) {
5246   chain_[0]->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha1);
5247 
5248   if (VerifyProcTypeIsBuiltin()) {
5249     // Since no chain is found, signature is not checked, fails with generic
5250     // error for untrusted chain.
5251     EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5252 
5253     // Valid since signature on directly trusted leaf is not checked.
5254     EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5255 
5256     // Cert is not self-signed so directly trusted leaf with
5257     // require_leaf_selfsigned should fail.
5258     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()
5259                                     .WithRequireLeafSelfSigned()),
5260                 IsError(ERR_CERT_AUTHORITY_INVALID));
5261   } else if (verify_proc_type() == CERT_VERIFY_PROC_IOS) {
5262     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5263   } else {
5264     EXPECT_THAT(Verify(), IsOk());
5265   }
5266 }
5267 
TEST_P(CertVerifyProcConstraintsTrustedLeafTest,UnknownExtension)5268 TEST_P(CertVerifyProcConstraintsTrustedLeafTest, UnknownExtension) {
5269   for (bool critical : {true, false}) {
5270     SCOPED_TRACE(critical);
5271     chain_[0]->SetExtension(TestOid0(), "hello world", critical);
5272 
5273     if (VerifyProcTypeIsBuiltin()) {
5274       EXPECT_THAT(Verify(), IsError(ERR_CERT_AUTHORITY_INVALID));
5275       if (critical) {
5276         EXPECT_THAT(VerifyAsTrustedLeaf(), IsError(ERR_CERT_INVALID));
5277       } else {
5278         EXPECT_THAT(VerifyAsTrustedLeaf(), IsOk());
5279       }
5280     } else {
5281       EXPECT_THAT(Verify(), IsOk());
5282     }
5283   }
5284 }
5285 
5286 // A set of tests that check how various constraints are enforced when they
5287 // are applied to a directly trusted self-signed leaf certificate.
5288 class CertVerifyProcConstraintsTrustedSelfSignedTest
5289     : public CertVerifyProcInternalTest {
5290  protected:
SetUp()5291   void SetUp() override {
5292     CertVerifyProcInternalTest::SetUp();
5293 
5294     cert_ = std::move(CertBuilder::CreateSimpleChain(/*chain_length=*/1)[0]);
5295   }
5296 
VerifyWithTrust(bssl::CertificateTrust trust)5297   int VerifyWithTrust(bssl::CertificateTrust trust) {
5298     ScopedTestRoot test_root(cert_->GetX509Certificate(), trust);
5299     CertVerifyResult verify_result;
5300     int flags = 0;
5301     return CertVerifyProcInternalTest::Verify(cert_->GetX509Certificate().get(),
5302                                               "www.example.com", flags,
5303                                               &verify_result);
5304   }
5305 
Verify()5306   int Verify() {
5307     return VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor());
5308   }
5309 
VerifyAsTrustedSelfSignedLeaf()5310   int VerifyAsTrustedSelfSignedLeaf() {
5311     return VerifyWithTrust(
5312         bssl::CertificateTrust::ForTrustedLeaf().WithRequireLeafSelfSigned());
5313   }
5314 
5315   std::unique_ptr<CertBuilder> cert_;
5316 };
5317 
5318 INSTANTIATE_TEST_SUITE_P(All,
5319                          CertVerifyProcConstraintsTrustedSelfSignedTest,
5320                          testing::ValuesIn(kAllCertVerifiers),
5321                          VerifyProcTypeToName);
5322 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,BaseCase)5323 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, BaseCase) {
5324   // Without changing anything on the test cert, it should validate
5325   // successfully. If this is not true then the rest of the tests in this class
5326   // are unlikely to be useful.
5327   if (VerifyProcTypeIsBuiltin()) {
5328     // Should succeed when verified as a trusted leaf.
5329     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5330     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()),
5331                 IsOk());
5332     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()),
5333                 IsOk());
5334 
5335     // Should also be allowed by verifying as anchor for itself.
5336     EXPECT_THAT(Verify(), IsOk());
5337 
5338     // Should fail if verified as anchor of itself with constraints enabled,
5339     // enforcing the basicConstraints on the anchor will fail since the cert
5340     // has CA=false.
5341     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor()
5342                                     .WithEnforceAnchorConstraints()),
5343                 IsError(ERR_CERT_INVALID));
5344 
5345     // Should be allowed since it will be evaluated as a trusted leaf, so
5346     // anchor constraints being enabled doesn't matter.
5347     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5348                                     .WithEnforceAnchorConstraints()),
5349                 IsOk());
5350   } else {
5351     EXPECT_THAT(Verify(), IsOk());
5352   }
5353 }
5354 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,BasicConstraintsIsCa)5355 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, BasicConstraintsIsCa) {
5356   for (bool has_key_usage_cert_sign : {false, true}) {
5357     cert_->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/-1);
5358 
5359     if (has_key_usage_cert_sign) {
5360       cert_->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
5361                            bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5362     } else {
5363       cert_->SetKeyUsages({bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5364     }
5365     EXPECT_THAT(Verify(), IsOk());
5366     if (VerifyProcTypeIsBuiltin()) {
5367       EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5368     }
5369   }
5370 }
5371 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,BasicConstraintsNotCaPathlen)5372 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5373        BasicConstraintsNotCaPathlen) {
5374   cert_->SetBasicConstraints(/*is_ca=*/false, /*path_len=*/0);
5375 
5376   EXPECT_THAT(Verify(), IsOk());
5377   if (VerifyProcTypeIsBuiltin()) {
5378     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5379   }
5380 }
5381 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,BasicConstraintsIsCaPathlen)5382 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5383        BasicConstraintsIsCaPathlen) {
5384   cert_->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/0);
5385 
5386   EXPECT_THAT(Verify(), IsOk());
5387   if (VerifyProcTypeIsBuiltin()) {
5388     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5389   }
5390 }
5391 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,BasicConstraintsMissing)5392 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5393        BasicConstraintsMissing) {
5394   cert_->EraseExtension(bssl::der::Input(bssl::kBasicConstraintsOid));
5395 
5396   EXPECT_THAT(Verify(), IsOk());
5397   if (VerifyProcTypeIsBuiltin()) {
5398     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5399   }
5400 }
5401 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,NameConstraintsNotMatching)5402 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5403        NameConstraintsNotMatching) {
5404   cert_->SetNameConstraintsDnsNames(/*permitted_dns_names=*/{"example.org"},
5405                                     /*excluded_dns_names=*/{});
5406 
5407   EXPECT_THAT(Verify(), IsOk());
5408   if (VerifyProcTypeIsBuiltin()) {
5409     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5410   }
5411 }
5412 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,ValidityExpired)5413 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, ValidityExpired) {
5414   cert_->SetValidity(base::Time::Now() - base::Days(14),
5415                      base::Time::Now() - base::Days(7));
5416 
5417   EXPECT_THAT(Verify(), IsError(ERR_CERT_DATE_INVALID));
5418   if (VerifyProcTypeIsBuiltin()) {
5419     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(),
5420                 IsError(ERR_CERT_DATE_INVALID));
5421   }
5422 }
5423 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,PolicyConstraints)5424 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, PolicyConstraints) {
5425   static const char kPolicy1[] = "1.2.3.4";
5426 
5427   for (bool leaf_has_policy : {false, true}) {
5428     SCOPED_TRACE(leaf_has_policy);
5429 
5430     cert_->SetPolicyConstraints(
5431         /*require_explicit_policy=*/0,
5432         /*inhibit_policy_mapping=*/absl::nullopt);
5433     if (leaf_has_policy) {
5434       cert_->SetCertificatePolicies({kPolicy1});
5435 
5436       EXPECT_THAT(Verify(), IsOk());
5437     } else {
5438       cert_->SetCertificatePolicies({});
5439 
5440       if (VerifyProcTypeIsBuiltin()) {
5441         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5442         EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5443       } else {
5444         EXPECT_THAT(Verify(), IsOk());
5445       }
5446     }
5447   }
5448 }
5449 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,InhibitAnyPolicy)5450 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, InhibitAnyPolicy) {
5451   static const char kAnyPolicy[] = "2.5.29.32.0";
5452   cert_->SetPolicyConstraints(
5453       /*require_explicit_policy=*/0,
5454       /*inhibit_policy_mapping=*/absl::nullopt);
5455   cert_->SetInhibitAnyPolicy(0);
5456   cert_->SetCertificatePolicies({kAnyPolicy});
5457 
5458   EXPECT_THAT(Verify(), IsOk());
5459   if (VerifyProcTypeIsBuiltin()) {
5460     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5461   }
5462 }
5463 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,KeyUsageNoDigitalSignature)5464 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5465        KeyUsageNoDigitalSignature) {
5466   // This test is mostly uninteresting since keyUsage on the end-entity is only
5467   // checked at the TLS layer, not during cert verification.
5468   cert_->SetKeyUsages({bssl::KEY_USAGE_BIT_CRL_SIGN});
5469 
5470   EXPECT_THAT(Verify(), IsOk());
5471   if (VerifyProcTypeIsBuiltin()) {
5472     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5473   }
5474 }
5475 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,KeyUsageCertSignLeaf)5476 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, KeyUsageCertSignLeaf) {
5477   // Test a leaf that has keyUsage asserting keyCertSign with basicConstraints
5478   // CA=false, which is an error according to 5280 (4.2.1.3 and 4.2.1.9).
5479   cert_->SetKeyUsages({bssl::KEY_USAGE_BIT_KEY_CERT_SIGN,
5480                        bssl::KEY_USAGE_BIT_DIGITAL_SIGNATURE});
5481 
5482   EXPECT_THAT(Verify(), IsOk());
5483   if (VerifyProcTypeIsBuiltin()) {
5484     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchor()
5485                                     .WithEnforceAnchorConstraints()),
5486                 IsError(ERR_CERT_INVALID));
5487     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5488     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5489                                     .WithEnforceAnchorConstraints()
5490                                     .WithRequireLeafSelfSigned()),
5491                 IsOk());
5492   }
5493 }
5494 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,ExtendedKeyUsageNoServerAuth)5495 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5496        ExtendedKeyUsageNoServerAuth) {
5497   cert_->SetExtendedKeyUsages({bssl::der::Input(bssl::kCodeSigning)});
5498 
5499   EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5500   if (VerifyProcTypeIsBuiltin()) {
5501     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsError(ERR_CERT_INVALID));
5502   }
5503 }
5504 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,UnknownSignatureAlgorithm)5505 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,
5506        UnknownSignatureAlgorithm) {
5507   cert_->SetSignatureAlgorithmTLV(TestOid0SignatureAlgorithmTLV());
5508   if (VerifyProcTypeIsBuiltin()) {
5509     // Attempts to verify as anchor of itself, which fails when verifying the
5510     // signature.
5511     EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5512 
5513     // Signature not checked when verified as a directly trusted leaf without
5514     // require_leaf_selfsigned.
5515     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()),
5516                 IsOk());
5517 
5518     // PathBuilder override ignores require_leaf_selfsigned due to the
5519     // self-signed check returning false (due to the invalid signature
5520     // algorithm), thus this fails with AUTHORITY_INVALID due to failing to
5521     // find a chain to another root.
5522     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(),
5523                 IsError(ERR_CERT_AUTHORITY_INVALID));
5524 
5525     // PathBuilder override ignores require_leaf_selfsigned due to the invalid
5526     // signature algorithm, thus this tries to verify as anchor of itself,
5527     // which fails when verifying the signature.
5528     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5529                                     .WithRequireLeafSelfSigned()),
5530                 IsError(ERR_CERT_INVALID));
5531   } else {
5532     EXPECT_THAT(Verify(), IsOk());
5533   }
5534 }
5535 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,WeakSignatureAlgorithm)5536 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, WeakSignatureAlgorithm) {
5537   cert_->SetSignatureAlgorithm(bssl::SignatureAlgorithm::kEcdsaSha1);
5538   if (VerifyProcTypeIsBuiltin()) {
5539     // Attempts to verify as anchor of itself, which fails due to the weak
5540     // signature algorithm.
5541     EXPECT_THAT(Verify(), IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
5542 
5543     // Signature not checked when verified as a directly trusted leaf without
5544     // require_leaf_selfsigned.
5545     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustedLeaf()),
5546                 IsOk());
5547 
5548     // require_leaf_selfsigned allows any supported signature algorithm when
5549     // doing the self-signed check, so this is okay.
5550     EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5551     EXPECT_THAT(VerifyWithTrust(bssl::CertificateTrust::ForTrustAnchorOrLeaf()
5552                                     .WithRequireLeafSelfSigned()),
5553                 IsOk());
5554   } else {
5555     EXPECT_THAT(Verify(), IsOk());
5556   }
5557 }
5558 
TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest,UnknownExtension)5559 TEST_P(CertVerifyProcConstraintsTrustedSelfSignedTest, UnknownExtension) {
5560   for (bool critical : {true, false}) {
5561     SCOPED_TRACE(critical);
5562     cert_->SetExtension(TestOid0(), "hello world", critical);
5563 
5564     if (VerifyProcTypeIsBuiltin()) {
5565       if (critical) {
5566         EXPECT_THAT(Verify(), IsError(ERR_CERT_INVALID));
5567         EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsError(ERR_CERT_INVALID));
5568       } else {
5569         EXPECT_THAT(Verify(), IsOk());
5570         EXPECT_THAT(VerifyAsTrustedSelfSignedLeaf(), IsOk());
5571       }
5572     } else {
5573       EXPECT_THAT(Verify(), IsOk());
5574     }
5575   }
5576 }
5577 
TEST(CertVerifyProcTest,RejectsPublicSHA1)5578 TEST(CertVerifyProcTest, RejectsPublicSHA1) {
5579   scoped_refptr<X509Certificate> cert(
5580       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
5581   ASSERT_TRUE(cert);
5582 
5583   CertVerifyResult result;
5584   result.has_sha1 = true;
5585   result.is_issued_by_known_root = true;
5586   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
5587 
5588   int flags = 0;
5589   CertVerifyResult verify_result;
5590   int error = verify_proc->Verify(
5591       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5592       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5593   EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
5594   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
5595 
5596   // VERIFY_ENABLE_SHA1_LOCAL_ANCHORS should not impact this.
5597   flags = CertVerifyProc::VERIFY_ENABLE_SHA1_LOCAL_ANCHORS;
5598   verify_result.Reset();
5599   error = verify_proc->Verify(
5600       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5601       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5602   EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
5603   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
5604 }
5605 
TEST(CertVerifyProcTest,RejectsPrivateSHA1UnlessFlag)5606 TEST(CertVerifyProcTest, RejectsPrivateSHA1UnlessFlag) {
5607   scoped_refptr<X509Certificate> cert(
5608       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
5609   ASSERT_TRUE(cert);
5610 
5611   CertVerifyResult result;
5612   result.has_sha1 = true;
5613   result.is_issued_by_known_root = false;
5614   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
5615 
5616   // SHA-1 should be rejected by default for private roots...
5617   int flags = 0;
5618   CertVerifyResult verify_result;
5619   int error = verify_proc->Verify(
5620       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5621       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5622   EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
5623   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
5624 
5625   // ... unless VERIFY_ENABLE_SHA1_LOCAL_ANCHORS was supplied.
5626   flags = CertVerifyProc::VERIFY_ENABLE_SHA1_LOCAL_ANCHORS;
5627   verify_result.Reset();
5628   error = verify_proc->Verify(
5629       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5630       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5631   EXPECT_THAT(error, IsOk());
5632   EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
5633 }
5634 
5635 enum ExpectedAlgorithms {
5636   EXPECT_SHA1 = 1 << 0,
5637   EXPECT_STATUS_INVALID = 1 << 1,
5638 };
5639 
5640 struct WeakDigestTestData {
5641   const char* root_cert_filename;
5642   const char* intermediate_cert_filename;
5643   const char* ee_cert_filename;
5644   int expected_algorithms;
5645 };
5646 
StringOrDefault(const char * str,const char * default_value)5647 const char* StringOrDefault(const char* str, const char* default_value) {
5648   if (!str)
5649     return default_value;
5650   return str;
5651 }
5652 
5653 // GTest 'magic' pretty-printer, so that if/when a test fails, it knows how
5654 // to output the parameter that was passed. Without this, it will simply
5655 // attempt to print out the first twenty bytes of the object, which depending
5656 // on platform and alignment, may result in an invalid read.
PrintTo(const WeakDigestTestData & data,std::ostream * os)5657 void PrintTo(const WeakDigestTestData& data, std::ostream* os) {
5658   *os << "root: " << StringOrDefault(data.root_cert_filename, "none")
5659       << "; intermediate: "
5660       << StringOrDefault(data.intermediate_cert_filename, "none")
5661       << "; end-entity: " << data.ee_cert_filename;
5662 }
5663 
5664 class CertVerifyProcWeakDigestTest
5665     : public testing::TestWithParam<WeakDigestTestData> {
5666  public:
5667   CertVerifyProcWeakDigestTest() = default;
5668   ~CertVerifyProcWeakDigestTest() override = default;
5669 };
5670 
5671 // Tests that the CertVerifyProc::Verify() properly surfaces the (weak) hash
5672 // algorithms used in the chain.
TEST_P(CertVerifyProcWeakDigestTest,VerifyDetectsAlgorithm)5673 TEST_P(CertVerifyProcWeakDigestTest, VerifyDetectsAlgorithm) {
5674   WeakDigestTestData data = GetParam();
5675   base::FilePath certs_dir = GetTestCertsDirectory();
5676 
5677   // Build |intermediates| as the full chain (including trust anchor).
5678   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
5679 
5680   if (data.intermediate_cert_filename) {
5681     scoped_refptr<X509Certificate> intermediate_cert =
5682         ImportCertFromFile(certs_dir, data.intermediate_cert_filename);
5683     ASSERT_TRUE(intermediate_cert);
5684     intermediates.push_back(bssl::UpRef(intermediate_cert->cert_buffer()));
5685   }
5686 
5687   if (data.root_cert_filename) {
5688     scoped_refptr<X509Certificate> root_cert =
5689         ImportCertFromFile(certs_dir, data.root_cert_filename);
5690     ASSERT_TRUE(root_cert);
5691     intermediates.push_back(bssl::UpRef(root_cert->cert_buffer()));
5692   }
5693 
5694   scoped_refptr<X509Certificate> ee_cert =
5695       ImportCertFromFile(certs_dir, data.ee_cert_filename);
5696   ASSERT_TRUE(ee_cert);
5697 
5698   scoped_refptr<X509Certificate> ee_chain = X509Certificate::CreateFromBuffer(
5699       bssl::UpRef(ee_cert->cert_buffer()), std::move(intermediates));
5700   ASSERT_TRUE(ee_chain);
5701 
5702   int flags = 0;
5703   CertVerifyResult verify_result;
5704 
5705   // Use a mock CertVerifyProc that returns success with a verified_cert of
5706   // |ee_chain|.
5707   //
5708   // This is sufficient for the purposes of this test, as the checking for weak
5709   // hash algorithms is done by CertVerifyProc::Verify().
5710   auto proc = base::MakeRefCounted<MockCertVerifyProc>(CertVerifyResult());
5711   int error = proc->Verify(ee_chain.get(), "127.0.0.1",
5712                            /*ocsp_response=*/std::string(),
5713                            /*sct_list=*/std::string(), flags, &verify_result,
5714                            NetLogWithSource());
5715   EXPECT_EQ(!!(data.expected_algorithms & EXPECT_SHA1), verify_result.has_sha1);
5716   EXPECT_EQ(!!(data.expected_algorithms & EXPECT_STATUS_INVALID),
5717             !!(verify_result.cert_status & CERT_STATUS_INVALID));
5718   EXPECT_EQ(!!(data.expected_algorithms & EXPECT_STATUS_INVALID),
5719             error == ERR_CERT_INVALID);
5720 }
5721 
5722 // The signature algorithm of the root CA should not matter.
5723 const WeakDigestTestData kVerifyRootCATestData[] = {
5724     {"weak_digest_md5_root.pem", "weak_digest_sha1_intermediate.pem",
5725      "weak_digest_sha1_ee.pem", EXPECT_SHA1},
5726     {"weak_digest_md4_root.pem", "weak_digest_sha1_intermediate.pem",
5727      "weak_digest_sha1_ee.pem", EXPECT_SHA1},
5728     {"weak_digest_md2_root.pem", "weak_digest_sha1_intermediate.pem",
5729      "weak_digest_sha1_ee.pem", EXPECT_SHA1},
5730 };
5731 INSTANTIATE_TEST_SUITE_P(VerifyRoot,
5732                          CertVerifyProcWeakDigestTest,
5733                          testing::ValuesIn(kVerifyRootCATestData));
5734 
5735 // The signature algorithm of intermediates should be properly detected.
5736 const WeakDigestTestData kVerifyIntermediateCATestData[] = {
5737     {"weak_digest_sha1_root.pem", "weak_digest_md5_intermediate.pem",
5738      "weak_digest_sha1_ee.pem", EXPECT_STATUS_INVALID | EXPECT_SHA1},
5739     {"weak_digest_sha1_root.pem", "weak_digest_md4_intermediate.pem",
5740      "weak_digest_sha1_ee.pem", EXPECT_STATUS_INVALID | EXPECT_SHA1},
5741     {"weak_digest_sha1_root.pem", "weak_digest_md2_intermediate.pem",
5742      "weak_digest_sha1_ee.pem", EXPECT_STATUS_INVALID | EXPECT_SHA1},
5743 };
5744 
5745 INSTANTIATE_TEST_SUITE_P(VerifyIntermediate,
5746                          CertVerifyProcWeakDigestTest,
5747                          testing::ValuesIn(kVerifyIntermediateCATestData));
5748 
5749 // The signature algorithm of end-entity should be properly detected.
5750 const WeakDigestTestData kVerifyEndEntityTestData[] = {
5751     {"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
5752      "weak_digest_md5_ee.pem", EXPECT_STATUS_INVALID},
5753     {"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
5754      "weak_digest_md4_ee.pem", EXPECT_STATUS_INVALID},
5755     {"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
5756      "weak_digest_md2_ee.pem", EXPECT_STATUS_INVALID},
5757 };
5758 
5759 INSTANTIATE_TEST_SUITE_P(VerifyEndEntity,
5760                          CertVerifyProcWeakDigestTest,
5761                          testing::ValuesIn(kVerifyEndEntityTestData));
5762 
5763 // Incomplete chains do not report the status of the intermediate.
5764 // Note: really each of these tests should also expect the digest algorithm of
5765 // the intermediate (included as a comment). However CertVerifyProc::Verify() is
5766 // unable to distinguish that this is an intermediate and not a trust anchor, so
5767 // this intermediate is treated like a trust anchor.
5768 const WeakDigestTestData kVerifyIncompleteIntermediateTestData[] = {
5769     {nullptr, "weak_digest_md5_intermediate.pem", "weak_digest_sha1_ee.pem",
5770      EXPECT_SHA1},
5771     {nullptr, "weak_digest_md4_intermediate.pem", "weak_digest_sha1_ee.pem",
5772      EXPECT_SHA1},
5773     {nullptr, "weak_digest_md2_intermediate.pem", "weak_digest_sha1_ee.pem",
5774      EXPECT_SHA1},
5775 };
5776 
5777 INSTANTIATE_TEST_SUITE_P(
5778     MAYBE_VerifyIncompleteIntermediate,
5779     CertVerifyProcWeakDigestTest,
5780     testing::ValuesIn(kVerifyIncompleteIntermediateTestData));
5781 
5782 // Incomplete chains should report the status of the end-entity.
5783 // since the intermediate is treated as a trust anchor these should
5784 // be still simply be invalid.
5785 const WeakDigestTestData kVerifyIncompleteEETestData[] = {
5786     {nullptr, "weak_digest_sha1_intermediate.pem", "weak_digest_md5_ee.pem",
5787      EXPECT_STATUS_INVALID},
5788     {nullptr, "weak_digest_sha1_intermediate.pem", "weak_digest_md4_ee.pem",
5789      EXPECT_STATUS_INVALID},
5790     {nullptr, "weak_digest_sha1_intermediate.pem", "weak_digest_md2_ee.pem",
5791      EXPECT_STATUS_INVALID},
5792 };
5793 
5794 INSTANTIATE_TEST_SUITE_P(VerifyIncompleteEndEntity,
5795                          CertVerifyProcWeakDigestTest,
5796                          testing::ValuesIn(kVerifyIncompleteEETestData));
5797 
5798 // Md2, Md4, and Md5 are all considered invalid.
5799 const WeakDigestTestData kVerifyMixedTestData[] = {
5800     {"weak_digest_sha1_root.pem", "weak_digest_md5_intermediate.pem",
5801      "weak_digest_md2_ee.pem", EXPECT_STATUS_INVALID},
5802     {"weak_digest_sha1_root.pem", "weak_digest_md2_intermediate.pem",
5803      "weak_digest_md5_ee.pem", EXPECT_STATUS_INVALID},
5804     {"weak_digest_sha1_root.pem", "weak_digest_md4_intermediate.pem",
5805      "weak_digest_md2_ee.pem", EXPECT_STATUS_INVALID},
5806 };
5807 
5808 INSTANTIATE_TEST_SUITE_P(VerifyMixed,
5809                          CertVerifyProcWeakDigestTest,
5810                          testing::ValuesIn(kVerifyMixedTestData));
5811 
5812 // The EE is a trusted certificate. Even though it uses weak hashes, these
5813 // should not be reported.
5814 const WeakDigestTestData kVerifyTrustedEETestData[] = {
5815     {nullptr, nullptr, "weak_digest_md5_ee.pem", 0},
5816     {nullptr, nullptr, "weak_digest_md4_ee.pem", 0},
5817     {nullptr, nullptr, "weak_digest_md2_ee.pem", 0},
5818     {nullptr, nullptr, "weak_digest_sha1_ee.pem", 0},
5819 };
5820 
5821 INSTANTIATE_TEST_SUITE_P(VerifyTrustedEE,
5822                          CertVerifyProcWeakDigestTest,
5823                          testing::ValuesIn(kVerifyTrustedEETestData));
5824 
5825 // Test fixture for verifying certificate names.
5826 class CertVerifyProcNameTest : public ::testing::Test {
5827  protected:
VerifyCertName(const char * hostname,bool valid)5828   void VerifyCertName(const char* hostname, bool valid) {
5829     scoped_refptr<X509Certificate> cert(ImportCertFromFile(
5830         GetTestCertsDirectory(), "subjectAltName_sanity_check.pem"));
5831     ASSERT_TRUE(cert);
5832     CertVerifyResult result;
5833     result.is_issued_by_known_root = false;
5834     auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
5835 
5836     CertVerifyResult verify_result;
5837     int error = verify_proc->Verify(
5838         cert.get(), hostname, /*ocsp_response=*/std::string(),
5839         /*sct_list=*/std::string(), 0, &verify_result, NetLogWithSource());
5840     if (valid) {
5841       EXPECT_THAT(error, IsOk());
5842       EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
5843     } else {
5844       EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
5845       EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
5846     }
5847   }
5848 };
5849 
5850 // Don't match the common name
TEST_F(CertVerifyProcNameTest,DontMatchCommonName)5851 TEST_F(CertVerifyProcNameTest, DontMatchCommonName) {
5852   VerifyCertName("127.0.0.1", false);
5853 }
5854 
5855 // Matches the iPAddress SAN (IPv4)
TEST_F(CertVerifyProcNameTest,MatchesIpSanIpv4)5856 TEST_F(CertVerifyProcNameTest, MatchesIpSanIpv4) {
5857   VerifyCertName("127.0.0.2", true);
5858 }
5859 
5860 // Matches the iPAddress SAN (IPv6)
TEST_F(CertVerifyProcNameTest,MatchesIpSanIpv6)5861 TEST_F(CertVerifyProcNameTest, MatchesIpSanIpv6) {
5862   VerifyCertName("FE80:0:0:0:0:0:0:1", true);
5863 }
5864 
5865 // Should not match the iPAddress SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchIpSanIpv6)5866 TEST_F(CertVerifyProcNameTest, DoesntMatchIpSanIpv6) {
5867   VerifyCertName("[FE80:0:0:0:0:0:0:1]", false);
5868 }
5869 
5870 // Compressed form matches the iPAddress SAN (IPv6)
TEST_F(CertVerifyProcNameTest,MatchesIpSanCompressedIpv6)5871 TEST_F(CertVerifyProcNameTest, MatchesIpSanCompressedIpv6) {
5872   VerifyCertName("FE80::1", true);
5873 }
5874 
5875 // IPv6 mapped form should NOT match iPAddress SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchIpSanIPv6Mapped)5876 TEST_F(CertVerifyProcNameTest, DoesntMatchIpSanIPv6Mapped) {
5877   VerifyCertName("::127.0.0.2", false);
5878 }
5879 
5880 // Matches the dNSName SAN
TEST_F(CertVerifyProcNameTest,MatchesDnsSan)5881 TEST_F(CertVerifyProcNameTest, MatchesDnsSan) {
5882   VerifyCertName("test.example", true);
5883 }
5884 
5885 // Matches the dNSName SAN (trailing . ignored)
TEST_F(CertVerifyProcNameTest,MatchesDnsSanTrailingDot)5886 TEST_F(CertVerifyProcNameTest, MatchesDnsSanTrailingDot) {
5887   VerifyCertName("test.example.", true);
5888 }
5889 
5890 // Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchDnsSan)5891 TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSan) {
5892   VerifyCertName("www.test.example", false);
5893 }
5894 
5895 // Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchDnsSanInvalid)5896 TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanInvalid) {
5897   VerifyCertName("test..example", false);
5898 }
5899 
5900 // Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchDnsSanTwoTrailingDots)5901 TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanTwoTrailingDots) {
5902   VerifyCertName("test.example..", false);
5903 }
5904 
5905 // Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchDnsSanLeadingAndTrailingDot)5906 TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanLeadingAndTrailingDot) {
5907   VerifyCertName(".test.example.", false);
5908 }
5909 
5910 // Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest,DoesntMatchDnsSanTrailingDot)5911 TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanTrailingDot) {
5912   VerifyCertName(".test.example", false);
5913 }
5914 
5915 // Test that trust anchors are appropriately recorded via UMA.
TEST(CertVerifyProcTest,HasTrustAnchorVerifyUMA)5916 TEST(CertVerifyProcTest, HasTrustAnchorVerifyUMA) {
5917   base::HistogramTester histograms;
5918   scoped_refptr<X509Certificate> cert(
5919       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
5920   ASSERT_TRUE(cert);
5921 
5922   CertVerifyResult result;
5923 
5924   // Simulate a certificate chain issued by "C=US, O=Google Trust Services LLC,
5925   // CN=GTS Root R4". This publicly-trusted root was chosen as it was included
5926   // in 2017 and is not anticipated to be removed from all supported platforms
5927   // for a few decades.
5928   // Note: The actual cert in |cert| does not matter for this testing, so long
5929   // as it's not violating any CertVerifyProc::Verify() policies.
5930   SHA256HashValue leaf_hash = {{0}};
5931   SHA256HashValue intermediate_hash = {{1}};
5932   SHA256HashValue root_hash = {
5933       {0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
5934        0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
5935        0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
5936   result.public_key_hashes.push_back(HashValue(leaf_hash));
5937   result.public_key_hashes.push_back(HashValue(intermediate_hash));
5938   result.public_key_hashes.push_back(HashValue(root_hash));
5939 
5940   const base::HistogramBase::Sample kGTSRootR4HistogramID = 486;
5941 
5942   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
5943 
5944   histograms.ExpectTotalCount(kTrustAnchorVerifyHistogram, 0);
5945 
5946   int flags = 0;
5947   CertVerifyResult verify_result;
5948   int error = verify_proc->Verify(
5949       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5950       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5951   EXPECT_EQ(OK, error);
5952   histograms.ExpectUniqueSample(kTrustAnchorVerifyHistogram,
5953                                 kGTSRootR4HistogramID, 1);
5954 }
5955 
5956 // Test that certificates with multiple trust anchors present result in
5957 // only a single trust anchor being recorded, and that being the most specific
5958 // trust anchor.
TEST(CertVerifyProcTest,LogsOnlyMostSpecificTrustAnchorUMA)5959 TEST(CertVerifyProcTest, LogsOnlyMostSpecificTrustAnchorUMA) {
5960   base::HistogramTester histograms;
5961   scoped_refptr<X509Certificate> cert(
5962       ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
5963   ASSERT_TRUE(cert);
5964 
5965   CertVerifyResult result;
5966 
5967   // Simulate a chain of "C=US, O=Google Trust Services LLC, CN=GTS Root R4"
5968   // signing "C=US, O=Google Trust Services LLC, CN=GTS Root R3" signing an
5969   // intermediate and a leaf.
5970   // Note: The actual cert in |cert| does not matter for this testing, so long
5971   // as it's not violating any CertVerifyProc::Verify() policies.
5972   SHA256HashValue leaf_hash = {{0}};
5973   SHA256HashValue intermediate_hash = {{1}};
5974   SHA256HashValue gts_root_r3_hash = {
5975       {0x41, 0x79, 0xed, 0xd9, 0x81, 0xef, 0x74, 0x74, 0x77, 0xb4, 0x96,
5976        0x26, 0x40, 0x8a, 0xf4, 0x3d, 0xaa, 0x2c, 0xa7, 0xab, 0x7f, 0x9e,
5977        0x08, 0x2c, 0x10, 0x60, 0xf8, 0x40, 0x96, 0x77, 0x43, 0x48}};
5978   SHA256HashValue gts_root_r4_hash = {
5979       {0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
5980        0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
5981        0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
5982   result.public_key_hashes.push_back(HashValue(leaf_hash));
5983   result.public_key_hashes.push_back(HashValue(intermediate_hash));
5984   result.public_key_hashes.push_back(HashValue(gts_root_r3_hash));
5985   result.public_key_hashes.push_back(HashValue(gts_root_r4_hash));
5986 
5987   const base::HistogramBase::Sample kGTSRootR3HistogramID = 485;
5988 
5989   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
5990 
5991   histograms.ExpectTotalCount(kTrustAnchorVerifyHistogram, 0);
5992 
5993   int flags = 0;
5994   CertVerifyResult verify_result;
5995   int error = verify_proc->Verify(
5996       cert.get(), "127.0.0.1", /*ocsp_response=*/std::string(),
5997       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
5998   EXPECT_EQ(OK, error);
5999 
6000   // Only GTS Root R3 should be recorded.
6001   histograms.ExpectUniqueSample(kTrustAnchorVerifyHistogram,
6002                                 kGTSRootR3HistogramID, 1);
6003 }
6004 
6005 // Test that trust anchors histograms record whether or not
6006 // is_issued_by_known_root was derived from the OS.
TEST(CertVerifyProcTest,HasTrustAnchorVerifyOutOfDateUMA)6007 TEST(CertVerifyProcTest, HasTrustAnchorVerifyOutOfDateUMA) {
6008   base::HistogramTester histograms;
6009   // Since we are setting is_issued_by_known_root=true, the certificate to be
6010   // verified needs to have a validity period that satisfies
6011   // HasTooLongValidity.
6012   auto [leaf, root] = CertBuilder::CreateSimpleChain2();
6013 
6014   CertVerifyResult result;
6015 
6016   // Simulate a certificate chain that is recognized as trusted (from a known
6017   // root), but no certificates in the chain are tracked as known trust
6018   // anchors.
6019   SHA256HashValue leaf_hash = {{0}};
6020   SHA256HashValue intermediate_hash = {{1}};
6021   SHA256HashValue root_hash = {{2}};
6022   result.public_key_hashes.push_back(HashValue(leaf_hash));
6023   result.public_key_hashes.push_back(HashValue(intermediate_hash));
6024   result.public_key_hashes.push_back(HashValue(root_hash));
6025   result.is_issued_by_known_root = true;
6026 
6027   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
6028 
6029   histograms.ExpectTotalCount(kTrustAnchorVerifyHistogram, 0);
6030   histograms.ExpectTotalCount(kTrustAnchorVerifyOutOfDateHistogram, 0);
6031 
6032   int flags = 0;
6033   CertVerifyResult verify_result;
6034   int error = verify_proc->Verify(
6035       leaf->GetX509Certificate().get(), "www.example.com",
6036       /*ocsp_response=*/std::string(),
6037       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
6038   EXPECT_EQ(OK, error);
6039   const base::HistogramBase::Sample kUnknownRootHistogramID = 0;
6040   histograms.ExpectUniqueSample(kTrustAnchorVerifyHistogram,
6041                                 kUnknownRootHistogramID, 1);
6042   histograms.ExpectUniqueSample(kTrustAnchorVerifyOutOfDateHistogram, true, 1);
6043 }
6044 
6045 // If the CertVerifyProc::VerifyInternal implementation calculated the stapled
6046 // OCSP results in the CertVerifyResult, CertVerifyProc::Verify should not
6047 // re-calculate them.
TEST(CertVerifyProcTest,DoesNotRecalculateStapledOCSPResult)6048 TEST(CertVerifyProcTest, DoesNotRecalculateStapledOCSPResult) {
6049   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
6050       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
6051       X509Certificate::FORMAT_AUTO);
6052   ASSERT_TRUE(cert);
6053   ASSERT_EQ(1U, cert->intermediate_buffers().size());
6054 
6055   CertVerifyResult result;
6056 
6057   result.ocsp_result.response_status = bssl::OCSPVerifyResult::PROVIDED;
6058   result.ocsp_result.revocation_status = bssl::OCSPRevocationStatus::GOOD;
6059 
6060   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
6061 
6062   int flags = 0;
6063   CertVerifyResult verify_result;
6064   int error = verify_proc->Verify(cert.get(), "127.0.0.1",
6065                                   /*ocsp_response=*/"invalid OCSP data",
6066                                   /*sct_list=*/std::string(), flags,
6067                                   &verify_result, NetLogWithSource());
6068   EXPECT_EQ(OK, error);
6069 
6070   EXPECT_EQ(bssl::OCSPVerifyResult::PROVIDED,
6071             verify_result.ocsp_result.response_status);
6072   EXPECT_EQ(bssl::OCSPRevocationStatus::GOOD,
6073             verify_result.ocsp_result.revocation_status);
6074 }
6075 
TEST(CertVerifyProcTest,CalculateStapledOCSPResultIfNotAlreadyDone)6076 TEST(CertVerifyProcTest, CalculateStapledOCSPResultIfNotAlreadyDone) {
6077   scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
6078       GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
6079       X509Certificate::FORMAT_AUTO);
6080   ASSERT_TRUE(cert);
6081   ASSERT_EQ(1U, cert->intermediate_buffers().size());
6082 
6083   CertVerifyResult result;
6084 
6085   // Confirm the default-constructed values are as expected.
6086   EXPECT_EQ(bssl::OCSPVerifyResult::NOT_CHECKED,
6087             result.ocsp_result.response_status);
6088   EXPECT_EQ(bssl::OCSPRevocationStatus::UNKNOWN,
6089             result.ocsp_result.revocation_status);
6090 
6091   auto verify_proc = base::MakeRefCounted<MockCertVerifyProc>(result);
6092 
6093   int flags = 0;
6094   CertVerifyResult verify_result;
6095   int error = verify_proc->Verify(
6096       cert.get(), "127.0.0.1", /*ocsp_response=*/"invalid OCSP data",
6097       /*sct_list=*/std::string(), flags, &verify_result, NetLogWithSource());
6098   EXPECT_EQ(OK, error);
6099 
6100   EXPECT_EQ(bssl::OCSPVerifyResult::PARSE_RESPONSE_ERROR,
6101             verify_result.ocsp_result.response_status);
6102   EXPECT_EQ(bssl::OCSPRevocationStatus::UNKNOWN,
6103             verify_result.ocsp_result.revocation_status);
6104 }
6105 
6106 }  // namespace net
6107