forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert_verify_proc_unittest.cc
4796 lines (4105 loc) · 190 KB
/
cert_verify_proc_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/cert_verify_proc.h"
#include <memory>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/message_loop/message_pump_type.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "build/build_config.h"
#include "crypto/sha2.h"
#include "net/base/net_errors.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_net_fetcher.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_proc_builtin.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/crl_set.h"
#include "net/cert/ev_root_ca_metadata.h"
#include "net/cert/internal/parse_certificate.h"
#include "net/cert/internal/signature_algorithm.h"
#include "net/cert/internal/system_trust_store.h"
#include "net/cert/pem.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/cert_net/cert_net_fetcher_url_request.h"
#include "net/der/input.h"
#include "net/der/parser.h"
#include "net/log/test_net_log.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/test/cert_builder.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/gtest_util.h"
#include "net/test/revocation_builder.h"
#include "net/test/test_certificate_data.h"
#include "net/test/test_data_directory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_context_getter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/boringssl/src/include/openssl/mem.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
#include "net/cert/cert_verify_proc_android.h"
#elif defined(OS_IOS)
#include "base/ios/ios_util.h"
#include "net/cert/cert_verify_proc_ios.h"
#elif defined(OS_MAC)
#include "base/mac/mac_util.h"
#include "net/cert/cert_verify_proc_mac.h"
#include "net/cert/internal/trust_store_mac.h"
#elif defined(OS_WIN)
#include "base/win/windows_version.h"
#include "net/cert/cert_verify_proc_win.h"
#endif
// TODO(crbug.com/649017): Add tests that only certificates with
// serverAuth are accepted.
using net::test::IsError;
using net::test::IsOk;
using base::HexEncode;
namespace net {
namespace {
const char kTLSFeatureExtensionHistogram[] =
"Net.Certificate.TLSFeatureExtensionWithPrivateRoot";
const char kTLSFeatureExtensionOCSPHistogram[] =
"Net.Certificate.TLSFeatureExtensionWithPrivateRootHasOCSP";
const char kTrustAnchorVerifyHistogram[] = "Net.Certificate.TrustAnchor.Verify";
const char kTrustAnchorVerifyOutOfDateHistogram[] =
"Net.Certificate.TrustAnchor.VerifyOutOfDate";
// Mock CertVerifyProc that sets the CertVerifyResult to a given value for
// all certificates that are Verify()'d
class MockCertVerifyProc : public CertVerifyProc {
public:
explicit MockCertVerifyProc(const CertVerifyResult& result)
: result_(result) {}
// CertVerifyProc implementation:
bool SupportsAdditionalTrustAnchors() const override { return false; }
protected:
~MockCertVerifyProc() override = default;
private:
int VerifyInternal(X509Certificate* cert,
const std::string& hostname,
const std::string& ocsp_response,
const std::string& sct_list,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result,
const NetLogWithSource& net_log) override;
const CertVerifyResult result_;
DISALLOW_COPY_AND_ASSIGN(MockCertVerifyProc);
};
int MockCertVerifyProc::VerifyInternal(
X509Certificate* cert,
const std::string& hostname,
const std::string& ocsp_response,
const std::string& sct_list,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result,
const NetLogWithSource& net_log) {
*verify_result = result_;
verify_result->verified_cert = cert;
return OK;
}
// This enum identifies a concrete implemenation of CertVerifyProc.
//
// The type is erased by CreateCertVerifyProc(), however needs to be known for
// some of the test expectations.
enum CertVerifyProcType {
CERT_VERIFY_PROC_ANDROID,
CERT_VERIFY_PROC_IOS,
CERT_VERIFY_PROC_MAC,
CERT_VERIFY_PROC_WIN,
CERT_VERIFY_PROC_BUILTIN,
};
// Wrapper for base::mac::IsAtLeastOS10_12() to avoid littering ifdefs.
bool IsMacAtLeastOS10_12() {
#if defined(OS_MAC)
return base::mac::IsAtLeastOS10_12();
#else
return false;
#endif
}
// Returns a textual description of the CertVerifyProc implementation
// that is being tested, used to give better names to parameterized
// tests.
std::string VerifyProcTypeToName(
const testing::TestParamInfo<CertVerifyProcType>& params) {
switch (params.param) {
case CERT_VERIFY_PROC_ANDROID:
return "CertVerifyProcAndroid";
case CERT_VERIFY_PROC_IOS:
return "CertVerifyProcIOS";
case CERT_VERIFY_PROC_MAC:
return "CertVerifyProcMac";
case CERT_VERIFY_PROC_WIN:
return "CertVerifyProcWin";
case CERT_VERIFY_PROC_BUILTIN:
return "CertVerifyProcBuiltin";
}
return nullptr;
}
scoped_refptr<CertVerifyProc> CreateCertVerifyProc(
CertVerifyProcType type,
scoped_refptr<CertNetFetcher> cert_net_fetcher) {
switch (type) {
#if defined(OS_ANDROID)
case CERT_VERIFY_PROC_ANDROID:
return new CertVerifyProcAndroid(std::move(cert_net_fetcher));
#elif defined(OS_IOS)
case CERT_VERIFY_PROC_IOS:
return new CertVerifyProcIOS();
#elif defined(OS_MAC)
case CERT_VERIFY_PROC_MAC:
return new CertVerifyProcMac();
#elif defined(OS_WIN)
case CERT_VERIFY_PROC_WIN:
return new CertVerifyProcWin();
#endif
case CERT_VERIFY_PROC_BUILTIN:
return CreateCertVerifyProcBuiltin(std::move(cert_net_fetcher),
CreateSslSystemTrustStore());
default:
return nullptr;
}
}
// The set of all CertVerifyProcTypes that tests should be parameterized on.
// This needs to be kept in sync with CertVerifyProc::CreateSystemVerifyProc()
// and the platforms where CreateSslSystemTrustStore() is not a dummy store.
// TODO(crbug.com/649017): Enable CERT_VERIFY_PROC_BUILTIN everywhere. Right
// now this is gated on having CertVerifyProcBuiltin understand the roots added
// via TestRootCerts.
const std::vector<CertVerifyProcType> kAllCertVerifiers = {
#if defined(OS_ANDROID)
CERT_VERIFY_PROC_ANDROID
#elif defined(OS_IOS)
CERT_VERIFY_PROC_IOS
#elif defined(OS_MAC)
CERT_VERIFY_PROC_MAC, CERT_VERIFY_PROC_BUILTIN
#elif defined(OS_WIN)
CERT_VERIFY_PROC_WIN
#elif defined(OS_FUCHSIA) || defined(OS_LINUX) || defined(OS_CHROMEOS)
CERT_VERIFY_PROC_BUILTIN
#else
#error Unsupported platform
#endif
}; // namespace
// Returns true if a test root added through ScopedTestRoot can verify
// successfully as a target certificate with chain of length 1 on the given
// CertVerifyProcType.
bool ScopedTestRootCanTrustTargetCert(CertVerifyProcType verify_proc_type) {
return verify_proc_type == CERT_VERIFY_PROC_MAC ||
verify_proc_type == CERT_VERIFY_PROC_IOS ||
verify_proc_type == CERT_VERIFY_PROC_ANDROID;
}
// Returns true if a non-self-signed CA certificate added through
// ScopedTestRoot can verify successfully as the root of a chain by the given
// CertVerifyProcType.
bool ScopedTestRootCanTrustIntermediateCert(
CertVerifyProcType verify_proc_type) {
return verify_proc_type == CERT_VERIFY_PROC_MAC ||
verify_proc_type == CERT_VERIFY_PROC_IOS ||
verify_proc_type == CERT_VERIFY_PROC_BUILTIN ||
verify_proc_type == CERT_VERIFY_PROC_ANDROID;
}
// TODO(crbug.com/649017): This is not parameterized by the CertVerifyProc
// because the CertVerifyProc::Verify() does this unconditionally based on the
// platform.
bool AreSHA1IntermediatesAllowed() {
#if defined(OS_WIN)
// TODO(rsleevi): Remove this once https://crbug.com/588789 is resolved
// for Windows 7/2008 users.
// Note: This must be kept in sync with cert_verify_proc.cc
return base::win::GetVersion() < base::win::Version::WIN8;
#else
return false;
#endif
}
std::string MakeRandomHexString(size_t num_bytes) {
std::vector<char> rand_bytes;
rand_bytes.resize(num_bytes);
base::RandBytes(rand_bytes.data(), rand_bytes.size());
return base::HexEncode(rand_bytes.data(), rand_bytes.size());
}
} // namespace
// This fixture is for tests that apply to concrete implementations of
// CertVerifyProc. It will be run for all of the concrete CertVerifyProc types.
//
// It is called "Internal" as it tests the internal methods like
// "VerifyInternal()".
class CertVerifyProcInternalTest
: public testing::TestWithParam<CertVerifyProcType> {
protected:
void SetUp() override { SetUpWithCertNetFetcher(nullptr); }
// CertNetFetcher may be initialized by subclasses that want to use net
// fetching by calling SetUpWithCertNetFetcher instead of SetUp.
void SetUpWithCertNetFetcher(scoped_refptr<CertNetFetcher> cert_net_fetcher) {
CertVerifyProcType type = verify_proc_type();
verify_proc_ = CreateCertVerifyProc(type, std::move(cert_net_fetcher));
ASSERT_TRUE(verify_proc_);
}
int Verify(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result,
const NetLogWithSource& net_log) {
return verify_proc_->Verify(cert, hostname, /*ocsp_response=*/std::string(),
/*sct_list=*/std::string(), flags, crl_set,
additional_trust_anchors, verify_result,
net_log);
}
int Verify(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) {
return Verify(cert, hostname, flags, crl_set, additional_trust_anchors,
verify_result, NetLogWithSource());
}
CertVerifyProcType verify_proc_type() const { return GetParam(); }
bool SupportsAdditionalTrustAnchors() const {
return verify_proc_->SupportsAdditionalTrustAnchors();
}
bool SupportsReturningVerifiedChain() const {
#if defined(OS_ANDROID)
// Before API level 17 (SDK_VERSION_JELLY_BEAN_MR1), Android does
// not expose the APIs necessary to get at the verified
// certificate chain.
if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID &&
base::android::BuildInfo::GetInstance()->sdk_int() <
base::android::SDK_VERSION_JELLY_BEAN_MR1)
return false;
#endif
return true;
}
// Returns true if the RSA/DSA keysize will be considered weak on the current
// platform. IsInvalidRsaDsaKeySize should be checked prior, since some very
// weak keys may be considered invalid.
bool IsWeakRsaDsaKeySize(int size) const {
#if defined(OS_IOS)
// Beginning with iOS 13, the minimum key size for RSA/DSA algorithms is
// 2048 bits. See https://support.apple.com/en-us/HT210176
if (verify_proc_type() == CERT_VERIFY_PROC_IOS &&
base::ios::IsRunningOnIOS13OrLater()) {
return size < 2048;
}
#elif defined(OS_MAC)
// Beginning with macOS 10.15, the minimum key size for RSA/DSA algorithms
// is 2048 bits. See https://support.apple.com/en-us/HT210176
if (verify_proc_type() == CERT_VERIFY_PROC_MAC &&
base::mac::IsAtLeastOS10_15()) {
return size < 2048;
}
#endif
return size < 1024;
}
// Returns true if the RSA/DSA keysize will be considered invalid on the
// current platform.
bool IsInvalidRsaDsaKeySize(int size) const {
#if defined(OS_IOS)
if (base::ios::IsRunningOnIOS12OrLater()) {
// On iOS using SecTrustEvaluateWithError it is not possible to
// distinguish between weak and invalid key sizes.
return IsWeakRsaDsaKeySize(size);
}
#elif defined(OS_MAC)
// Starting with Mac OS 10.12, certs with keys < 1024 are invalid.
if (verify_proc_type() == CERT_VERIFY_PROC_MAC &&
base::mac::IsAtLeastOS10_12()) {
return size < 1024;
}
#endif
// This platform does not mark certificates with weak keys as invalid.
return false;
}
static bool ParseKeyType(const std::string& key_type,
std::string* type,
int* size) {
size_t pos = key_type.find("-");
std::string size_str = key_type.substr(0, pos);
*type = key_type.substr(pos + 1);
return base::StringToInt(size_str, size);
}
// Some platforms may reject certificates with very weak keys as invalid.
bool IsInvalidKeyType(const std::string& key_type) const {
std::string type;
int size = 0;
if (!ParseKeyType(key_type, &type, &size))
return false;
if (type == "rsa" || type == "dsa")
return IsInvalidRsaDsaKeySize(size);
return false;
}
// Currently, only RSA and DSA keys are checked for weakness, and our example
// weak size is 768. These could change in the future.
//
// Note that this means there may be false negatives: keys for other
// algorithms and which are weak will pass this test.
//
// Also, IsInvalidKeyType should be checked prior, since some weak keys may be
// considered invalid.
bool IsWeakKeyType(const std::string& key_type) const {
std::string type;
int size = 0;
if (!ParseKeyType(key_type, &type, &size))
return false;
if (type == "rsa" || type == "dsa")
return IsWeakRsaDsaKeySize(size);
return false;
}
bool SupportsCRLSet() const {
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_MAC ||
verify_proc_type() == CERT_VERIFY_PROC_BUILTIN;
}
bool SupportsCRLSetsInPathBuilding() const {
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_BUILTIN;
}
bool SupportsEV() const {
// TODO(crbug.com/117478): Android and iOS do not support EV.
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_MAC ||
verify_proc_type() == CERT_VERIFY_PROC_BUILTIN;
}
bool SupportsSoftFailRevChecking() const {
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_MAC ||
verify_proc_type() == CERT_VERIFY_PROC_BUILTIN;
}
bool SupportsRevCheckingRequiredLocalAnchors() const {
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_BUILTIN;
}
CertVerifyProc* verify_proc() const { return verify_proc_.get(); }
private:
scoped_refptr<CertVerifyProc> verify_proc_;
};
INSTANTIATE_TEST_SUITE_P(All,
CertVerifyProcInternalTest,
testing::ValuesIn(kAllCertVerifiers),
VerifyProcTypeToName);
// Tests that a certificate is recognized as EV, when the valid EV policy OID
// for the trust anchor is the second candidate EV oid in the target
// certificate. This is a regression test for crbug.com/705285.
TEST_P(CertVerifyProcInternalTest, EVVerificationMultipleOID) {
if (!SupportsEV()) {
LOG(INFO) << "Skipping test as EV verification is not yet supported";
return;
}
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "ev-multi-oid.pem");
scoped_refptr<X509Certificate> root =
ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
ASSERT_TRUE(cert);
ASSERT_TRUE(root);
ScopedTestRoot test_root(root.get());
// Build a CRLSet that covers the target certificate.
//
// This way CRLSet coverage will be sufficient for EV revocation checking,
// so this test does not depend on online revocation checking.
base::StringPiece spki;
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(
x509_util::CryptoBufferAsStringPiece(root->cert_buffer()), &spki));
SHA256HashValue spki_sha256;
crypto::SHA256HashString(spki, spki_sha256.data, sizeof(spki_sha256.data));
scoped_refptr<CRLSet> crl_set(
CRLSet::ForTesting(false, &spki_sha256, "", "", {}));
// The policies that "ev-multi-oid.pem" target certificate asserts.
static const char kOtherTestCertPolicy[] = "2.23.140.1.1";
static const char kEVTestCertPolicy[] = "1.2.3.4";
// Consider the root of the test chain a valid EV root for the test policy.
ScopedTestEVPolicy scoped_test_ev_policy(
EVRootCAMetadata::GetInstance(),
X509Certificate::CalculateFingerprint256(root->cert_buffer()),
kEVTestCertPolicy);
ScopedTestEVPolicy scoped_test_other_policy(
EVRootCAMetadata::GetInstance(), SHA256HashValue(), kOtherTestCertPolicy);
CertVerifyResult verify_result;
int flags = 0;
int error = Verify(cert.get(), "127.0.0.1", flags, crl_set.get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
// Target cert has an EV policy, and verifies successfully, but has a chain of
// length 1 because the target cert was directly trusted in the trust store.
// Should verify OK but not with STATUS_IS_EV.
TEST_P(CertVerifyProcInternalTest, TrustedTargetCertWithEVPolicy) {
// The policy that "explicit-policy-chain.pem" target certificate asserts.
static const char kEVTestCertPolicy[] = "1.2.3.4";
ScopedTestEVPolicy scoped_test_ev_policy(
EVRootCAMetadata::GetInstance(), SHA256HashValue(), kEVTestCertPolicy);
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "explicit-policy-chain.pem");
ASSERT_TRUE(cert);
ScopedTestRoot scoped_test_root(cert.get());
CertVerifyResult verify_result;
int flags = 0;
int error =
Verify(cert.get(), "policy_test.example", flags,
CRLSet::BuiltinCRLSet().get(), CertificateList(), &verify_result);
if (ScopedTestRootCanTrustTargetCert(verify_proc_type())) {
EXPECT_THAT(error, IsOk());
ASSERT_TRUE(verify_result.verified_cert);
EXPECT_TRUE(verify_result.verified_cert->intermediate_buffers().empty());
} else {
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
}
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
// Target cert has an EV policy, and verifies successfully with a chain of
// length 1, and its fingerprint matches the cert fingerprint for that ev
// policy. This should never happen in reality, but just test that things don't
// explode if it does.
TEST_P(CertVerifyProcInternalTest,
TrustedTargetCertWithEVPolicyAndEVFingerprint) {
// The policy that "explicit-policy-chain.pem" target certificate asserts.
static const char kEVTestCertPolicy[] = "1.2.3.4";
// This the fingerprint of the "explicit-policy-chain.pem" target certificate.
// See net/data/ssl/certificates/explicit-policy-chain.pem
static const SHA256HashValue kEVTestCertFingerprint = {
{0x71, 0xac, 0xfa, 0x12, 0xa4, 0x42, 0x31, 0x3c, 0xff, 0x10, 0xd2,
0x9d, 0xb6, 0x1b, 0x4a, 0xe8, 0x25, 0x4e, 0x77, 0xd3, 0x9f, 0xa3,
0x2f, 0xb3, 0x19, 0x8d, 0x46, 0x9f, 0xb7, 0x73, 0x07, 0x30}};
ScopedTestEVPolicy scoped_test_ev_policy(EVRootCAMetadata::GetInstance(),
kEVTestCertFingerprint,
kEVTestCertPolicy);
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "explicit-policy-chain.pem");
ASSERT_TRUE(cert);
ScopedTestRoot scoped_test_root(cert.get());
CertVerifyResult verify_result;
int flags = 0;
int error =
Verify(cert.get(), "policy_test.example", flags,
CRLSet::BuiltinCRLSet().get(), CertificateList(), &verify_result);
if (ScopedTestRootCanTrustTargetCert(verify_proc_type())) {
EXPECT_THAT(error, IsOk());
ASSERT_TRUE(verify_result.verified_cert);
EXPECT_TRUE(verify_result.verified_cert->intermediate_buffers().empty());
} else {
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
}
// An EV Root certificate should never be used as an end-entity certificate.
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
// Target cert has an EV policy, and has a valid path to the EV root, but the
// intermediate has been trusted directly. Should stop building the path at the
// intermediate and verify OK but not with STATUS_IS_EV.
// See https://crbug.com/979801
TEST_P(CertVerifyProcInternalTest, TrustedIntermediateCertWithEVPolicy) {
if (!SupportsEV()) {
LOG(INFO) << "Skipping test as EV verification is not yet supported";
return;
}
if (!ScopedTestRootCanTrustIntermediateCert(verify_proc_type())) {
LOG(INFO) << "Skipping test as intermediate cert cannot be trusted";
return;
}
CertificateList orig_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "explicit-policy-chain.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, orig_certs.size());
for (bool trust_the_intermediate : {false, true}) {
// Need to build unique certs for each try otherwise caching can break
// things.
CertBuilder root(orig_certs[2]->cert_buffer(), nullptr);
CertBuilder intermediate(orig_certs[1]->cert_buffer(), &root);
CertBuilder leaf(orig_certs[0]->cert_buffer(), &intermediate);
// The policy that "explicit-policy-chain.pem" target certificate asserts.
static const char kEVTestCertPolicy[] = "1.2.3.4";
// Consider the root of the test chain a valid EV root for the test policy.
ScopedTestEVPolicy scoped_test_ev_policy(
EVRootCAMetadata::GetInstance(),
X509Certificate::CalculateFingerprint256(root.GetCertBuffer()),
kEVTestCertPolicy);
// CRLSet which covers the leaf.
base::StringPiece intermediate_spki;
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(
x509_util::CryptoBufferAsStringPiece(intermediate.GetCertBuffer()),
&intermediate_spki));
SHA256HashValue intermediate_spki_hash;
crypto::SHA256HashString(intermediate_spki, &intermediate_spki_hash,
sizeof(SHA256HashValue));
scoped_refptr<CRLSet> crl_set =
CRLSet::ForTesting(false, &intermediate_spki_hash, "", "", {});
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(bssl::UpRef(intermediate.GetCertBuffer()));
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
bssl::UpRef(leaf.GetCertBuffer()), std::move(intermediates));
ASSERT_TRUE(cert.get());
scoped_refptr<X509Certificate> intermediate_cert =
X509Certificate::CreateFromBuffer(
bssl::UpRef(intermediate.GetCertBuffer()), {});
ASSERT_TRUE(intermediate_cert.get());
scoped_refptr<X509Certificate> root_cert =
X509Certificate::CreateFromBuffer(bssl::UpRef(root.GetCertBuffer()),
{});
ASSERT_TRUE(root_cert.get());
if (!trust_the_intermediate) {
// First trust just the root. This verifies that the test setup is
// actually correct.
ScopedTestRoot scoped_test_root({root_cert});
CertVerifyResult verify_result;
int flags = 0;
int error = Verify(cert.get(), "policy_test.example", flags,
crl_set.get(), CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
ASSERT_TRUE(verify_result.verified_cert);
// Verified chain should include the intermediate and the root.
EXPECT_EQ(2U, verify_result.verified_cert->intermediate_buffers().size());
// Should be EV.
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
} else {
// Now try with trusting both the intermediate and the root.
ScopedTestRoot scoped_test_root({intermediate_cert, root_cert});
CertVerifyResult verify_result;
int flags = 0;
int error = Verify(cert.get(), "policy_test.example", flags,
crl_set.get(), CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
ASSERT_TRUE(verify_result.verified_cert);
// Verified chain should only go to the trusted intermediate, not the
// root.
EXPECT_EQ(1U, verify_result.verified_cert->intermediate_buffers().size());
// Should not be EV.
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
}
}
TEST_P(CertVerifyProcInternalTest, CertWithNullInCommonNameAndNoSAN) {
std::unique_ptr<CertBuilder> leaf, intermediate, root;
CertBuilder::CreateSimpleChain(&leaf, &intermediate, &root);
ASSERT_TRUE(leaf && intermediate && root);
leaf->EraseExtension(SubjectAltNameOid());
std::string common_name;
common_name += "www.fake.com";
common_name += '\0';
common_name += "a" + MakeRandomHexString(12) + ".example.com";
leaf->SetSubjectCommonName(common_name);
// Trust the root and build a chain to verify that includes the intermediate.
ScopedTestRoot scoped_root(root->GetX509Certificate().get());
scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
ASSERT_TRUE(chain.get());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(chain.get(), "www.fake.com", flags, CRLSet::BuiltinCRLSet().get(),
CertificateList(), &verify_result);
// This actually fails because Chrome only looks for hostnames in
// SubjectAltNames now and no SubjectAltName is present.
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
}
TEST_P(CertVerifyProcInternalTest, CertWithNullInCommonNameAndValidSAN) {
std::unique_ptr<CertBuilder> leaf, intermediate, root;
CertBuilder::CreateSimpleChain(&leaf, &intermediate, &root);
ASSERT_TRUE(leaf && intermediate && root);
leaf->SetSubjectAltName("www.fake.com");
std::string common_name;
common_name += "www.fake.com";
common_name += '\0';
common_name += "a" + MakeRandomHexString(12) + ".example.com";
leaf->SetSubjectCommonName(common_name);
// Trust the root and build a chain to verify that includes the intermediate.
ScopedTestRoot scoped_root(root->GetX509Certificate().get());
scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
ASSERT_TRUE(chain.get());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(chain.get(), "www.fake.com", flags, CRLSet::BuiltinCRLSet().get(),
CertificateList(), &verify_result);
// SubjectAltName is valid and Chrome does not use the common name.
EXPECT_THAT(error, IsOk());
}
TEST_P(CertVerifyProcInternalTest, CertWithNullInSAN) {
std::unique_ptr<CertBuilder> leaf, intermediate, root;
CertBuilder::CreateSimpleChain(&leaf, &intermediate, &root);
ASSERT_TRUE(leaf && intermediate && root);
std::string hostname;
hostname += "www.fake.com";
hostname += '\0';
hostname += "a" + MakeRandomHexString(12) + ".example.com";
leaf->SetSubjectAltName(hostname);
// Trust the root and build a chain to verify that includes the intermediate.
ScopedTestRoot scoped_root(root->GetX509Certificate().get());
scoped_refptr<X509Certificate> chain = leaf->GetX509CertificateChain();
ASSERT_TRUE(chain.get());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(chain.get(), "www.fake.com", flags, CRLSet::BuiltinCRLSet().get(),
CertificateList(), &verify_result);
// SubjectAltName is invalid.
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
}
// Tests the case where the target certificate is accepted by
// X509CertificateBytes, but has errors that should cause verification to fail.
TEST_P(CertVerifyProcInternalTest, InvalidTarget) {
base::FilePath certs_dir =
GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
scoped_refptr<X509Certificate> bad_cert =
ImportCertFromFile(certs_dir, "signature_algorithm_null.pem");
ASSERT_TRUE(bad_cert);
scoped_refptr<X509Certificate> ok_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(ok_cert);
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(bssl::UpRef(ok_cert->cert_buffer()));
scoped_refptr<X509Certificate> cert_with_bad_target(
X509Certificate::CreateFromBuffer(bssl::UpRef(bad_cert->cert_buffer()),
std::move(intermediates)));
ASSERT_TRUE(cert_with_bad_target);
EXPECT_EQ(1U, cert_with_bad_target->intermediate_buffers().size());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(cert_with_bad_target.get(), "127.0.0.1", flags,
CRLSet::BuiltinCRLSet().get(), CertificateList(), &verify_result);
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
}
// Tests the case where an intermediate certificate is accepted by
// X509CertificateBytes, but has errors that should prevent using it during
// verification. The verification should succeed, since the intermediate
// wasn't necessary.
TEST_P(CertVerifyProcInternalTest, UnnecessaryInvalidIntermediate) {
ScopedTestRoot test_root(
ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem").get());
base::FilePath certs_dir =
GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
bssl::UniquePtr<CRYPTO_BUFFER> bad_cert =
x509_util::CreateCryptoBuffer(base::StringPiece("invalid"));
ASSERT_TRUE(bad_cert);
scoped_refptr<X509Certificate> ok_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(ok_cert);
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(std::move(bad_cert));
scoped_refptr<X509Certificate> cert_with_bad_intermediate(
X509Certificate::CreateFromBuffer(bssl::UpRef(ok_cert->cert_buffer()),
std::move(intermediates)));
ASSERT_TRUE(cert_with_bad_intermediate);
EXPECT_EQ(1U, cert_with_bad_intermediate->intermediate_buffers().size());
RecordingNetLogObserver net_log_observer(NetLogCaptureMode::kDefault);
NetLogWithSource net_log(NetLogWithSource::Make(
net::NetLog::Get(), net::NetLogSourceType::CERT_VERIFIER_TASK));
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert_with_bad_intermediate.get(), "127.0.0.1", flags,
CRLSet::BuiltinCRLSet().get(), CertificateList(),
&verify_result, net_log);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0u, verify_result.cert_status);
auto events = net_log_observer.GetEntriesForSource(net_log.source());
EXPECT_FALSE(events.empty());
auto event = std::find_if(events.begin(), events.end(), [](const auto& e) {
return e.type == NetLogEventType::CERT_VERIFY_PROC;
});
ASSERT_NE(event, events.end());
EXPECT_EQ(net::NetLogEventPhase::BEGIN, event->phase);
ASSERT_TRUE(event->params.is_dict());
const std::string* host = event->params.FindStringKey("host");
ASSERT_TRUE(host);
EXPECT_EQ("127.0.0.1", *host);
if (verify_proc_type() == CERT_VERIFY_PROC_BUILTIN) {
event = std::find_if(events.begin(), events.end(), [](const auto& e) {
return e.type == NetLogEventType::CERT_VERIFY_PROC_INPUT_CERT;
});
ASSERT_NE(event, events.end());
EXPECT_EQ(net::NetLogEventPhase::NONE, event->phase);
ASSERT_TRUE(event->params.is_dict());
const std::string* errors = event->params.FindStringKey("errors");
ASSERT_TRUE(errors);
EXPECT_EQ(
"ERROR: Failed parsing Certificate SEQUENCE\nERROR: Failed parsing "
"Certificate\n",
*errors);
}
}
// A regression test for http://crbug.com/31497.
TEST_P(CertVerifyProcInternalTest, IntermediateCARequireExplicitPolicy) {
if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
// Disabled on Android, as the Android verification libraries require an
// explicit policy to be specified, even when anyPolicy is permitted.
LOG(INFO) << "Skipping test on Android";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "explicit-policy-chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
bssl::UpRef(certs[0]->cert_buffer()), std::move(intermediates));
ASSERT_TRUE(cert.get());
ScopedTestRoot scoped_root(certs[2].get());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(cert.get(), "policy_test.example", flags,
CRLSet::BuiltinCRLSet().get(), CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0u, verify_result.cert_status);
}
TEST_P(CertVerifyProcInternalTest, RejectExpiredCert) {
base::FilePath certs_dir = GetTestCertsDirectory();
// Load root_ca_cert.pem into the test root store.
ScopedTestRoot test_root(
ImportCertFromFile(certs_dir, "root_ca_cert.pem").get());
scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
certs_dir, "expired_cert.pem", X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
ASSERT_EQ(0U, cert->intermediate_buffers().size());
int flags = 0;
CertVerifyResult verify_result;
int error =
Verify(cert.get(), "127.0.0.1", flags, CRLSet::BuiltinCRLSet().get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
}
TEST_P(CertVerifyProcInternalTest, RejectWeakKeys) {
base::FilePath certs_dir = GetTestCertsDirectory();
typedef std::vector<std::string> Strings;
Strings key_types;
// generate-weak-test-chains.sh currently has:
// key_types="768-rsa 1024-rsa 2048-rsa prime256v1-ecdsa"
// We must use the same key types here. The filenames generated look like:
// 2048-rsa-ee-by-768-rsa-intermediate.pem
key_types.push_back("768-rsa");
key_types.push_back("1024-rsa");
key_types.push_back("2048-rsa");
key_types.push_back("prime256v1-ecdsa");
// Add the root that signed the intermediates for this test.
scoped_refptr<X509Certificate> root_cert =
ImportCertFromFile(certs_dir, "2048-rsa-root.pem");
ASSERT_NE(static_cast<X509Certificate*>(nullptr), root_cert.get());
ScopedTestRoot scoped_root(root_cert.get());
// Now test each chain.
for (Strings::const_iterator ee_type = key_types.begin();
ee_type != key_types.end(); ++ee_type) {
for (Strings::const_iterator signer_type = key_types.begin();
signer_type != key_types.end(); ++signer_type) {
std::string basename =
*ee_type + "-ee-by-" + *signer_type + "-intermediate.pem";
SCOPED_TRACE(basename);
scoped_refptr<X509Certificate> ee_cert =
ImportCertFromFile(certs_dir, basename);
ASSERT_NE(static_cast<X509Certificate*>(nullptr), ee_cert.get());
basename = *signer_type + "-intermediate.pem";
scoped_refptr<X509Certificate> intermediate =
ImportCertFromFile(certs_dir, basename);
ASSERT_NE(static_cast<X509Certificate*>(nullptr), intermediate.get());
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(bssl::UpRef(intermediate->cert_buffer()));
scoped_refptr<X509Certificate> cert_chain =
X509Certificate::CreateFromBuffer(bssl::UpRef(ee_cert->cert_buffer()),
std::move(intermediates));
ASSERT_TRUE(cert_chain);
CertVerifyResult verify_result;
int error = Verify(cert_chain.get(), "127.0.0.1", 0,
CRLSet::BuiltinCRLSet().get(), CertificateList(),
&verify_result);
if (IsInvalidKeyType(*ee_type) || IsInvalidKeyType(*signer_type)) {
EXPECT_NE(OK, error);
EXPECT_EQ(CERT_STATUS_INVALID,
verify_result.cert_status & CERT_STATUS_INVALID);
} else if (IsWeakKeyType(*ee_type) || IsWeakKeyType(*signer_type)) {
EXPECT_NE(OK, error);
EXPECT_EQ(CERT_STATUS_WEAK_KEY,
verify_result.cert_status & CERT_STATUS_WEAK_KEY);
EXPECT_EQ(0u, verify_result.cert_status & CERT_STATUS_INVALID);
} else {
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status & CERT_STATUS_WEAK_KEY);
}
}
}
}
// Regression test for http://crbug.com/108514.
TEST_P(CertVerifyProcInternalTest, ExtraneousMD5RootCert) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
if (verify_proc_type() == CERT_VERIFY_PROC_MAC) {
// Disabled on OS X - Security.framework doesn't ignore superflous
// certificates provided by servers.
// TODO(eroman): Is this still needed?
LOG(INFO) << "Skipping this test as Security.framework doesn't ignore "
"superflous certificates provided by servers.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "cross-signed-leaf.pem");
ASSERT_NE(static_cast<X509Certificate*>(nullptr), server_cert.get());
scoped_refptr<X509Certificate> extra_cert =
ImportCertFromFile(certs_dir, "cross-signed-root-md5.pem");
ASSERT_NE(static_cast<X509Certificate*>(nullptr), extra_cert.get());
scoped_refptr<X509Certificate> root_cert =
ImportCertFromFile(certs_dir, "cross-signed-root-sha256.pem");
ASSERT_NE(static_cast<X509Certificate*>(nullptr), root_cert.get());