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