/
ChainTests.cs
1361 lines (1180 loc) · 66.8 KB
/
ChainTests.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
[SkipOnPlatform(TestPlatforms.Browser, "Browser doesn't support X.509 certificates")]
public static class ChainTests
{
private static bool TrustsMicrosoftDotComRoot
{
get
{
// Verifies that the microsoft.com certs build with only the certificates in the root store
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
return chain.Build(microsoftDotCom);
}
}
}
[Fact]
public static void BuildChain()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
// Halfway between microsoftDotCom's NotBefore and NotAfter
// This isn't a boundary condition test.
chain.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Chain built validly");
// The chain should have 3 members
Assert.Equal(3, chain.ChainElements.Count);
// These are the three specific members.
Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void VerifyChainFromHandle()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Source chain built validly");
Assert.Equal(3, chain.ChainElements.Count);
using (var chainHolder2 = new ChainHolder(chain.ChainContext))
{
X509Chain chain2 = chainHolder2.Chain;
Assert.NotSame(chain, chain2);
Assert.Equal(chain.ChainContext, chain2.ChainContext);
Assert.Equal(3, chain2.ChainElements.Count);
Assert.NotSame(chain.ChainElements[0], chain2.ChainElements[0]);
Assert.NotSame(chain.ChainElements[1], chain2.ChainElements[1]);
Assert.NotSame(chain.ChainElements[2], chain2.ChainElements[2]);
Assert.Equal(microsoftDotCom, chain2.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain2.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain2.ChainElements[2].Certificate);
// ChainPolicy is not carried over from the Chain(IntPtr) constructor
Assert.NotEqual(chain.ChainPolicy.VerificationFlags, chain2.ChainPolicy.VerificationFlags);
Assert.NotEqual(chain.ChainPolicy.VerificationTime, chain2.ChainPolicy.VerificationTime);
Assert.NotEqual(chain.ChainPolicy.RevocationMode, chain2.ChainPolicy.RevocationMode);
Assert.Equal(X509VerificationFlags.NoFlag, chain2.ChainPolicy.VerificationFlags);
// Re-set the ChainPolicy properties
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain2.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain2.Build(microsoftDotCom);
Assert.True(valid, "Cloned chain built validly");
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void VerifyChainFromHandle_Unix()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero));
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void TestDispose()
{
X509Chain chain;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
chain = chainHolder.Chain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(microsoftDotCom);
Assert.NotEqual(IntPtr.Zero, chain.ChainContext);
}
// No exception thrown for accessing ChainContext on disposed chain
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
[ConditionalFact(typeof(SignatureSupport), nameof(SignatureSupport.SupportsX509Sha1Signatures))]
public static void TestResetMethod()
{
using (var sampleCert = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(sampleCert);
bool valid = chain.Build(sampleCert);
Assert.False(valid);
chainHolder.DisposeChainElements();
// This test checks that the verification flags do not get reset when the chain is reset,
// so we set AllowUnknownCertificateAuthority even on platforms that don't respect it.
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(sampleCert);
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain.Build(sampleCert);
Assert.True(valid, "Chain built validly");
Assert.Equal(1, chain.ChainElements.Count);
chainHolder.DisposeChainElements();
chain.Reset();
Assert.Equal(0, chain.ChainElements.Count);
// ChainPolicy did not reset (for .NET Framework compat)
Assert.Equal(X509VerificationFlags.AllowUnknownCertificateAuthority, chain.ChainPolicy.VerificationFlags);
valid = chain.Build(sampleCert);
Assert.Equal(1, chain.ChainElements.Count);
// This succeeds because ChainPolicy did not reset
Assert.True(valid, "Chain built validly after reset");
}
}
/// <summary>
/// Tests that when a certificate chain has a root certification which is not trusted by the trust provider,
/// Build returns false and a ChainStatus returns UntrustedRoot.
/// Android does not support the detailed status in this test. It always validates time
/// and trusted root. It will fail to build any chain if those are not valid.
/// </summary>
[Fact]
[OuterLoop]
[SkipOnPlatform(TestPlatforms.Android, "Not supported on Android.")]
public static void BuildChainExtraStoreUntrustedRoot()
{
using (var testCert = new X509Certificate2(TestFiles.ChainPfxFile, TestData.ChainPfxPassword))
using (ImportedCollection ic = Cert.Import(TestFiles.ChainPfxFile, TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet))
using (var chainHolder = new ChainHolder())
{
X509Certificate2Collection collection = ic.Collection;
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.AddRange(collection);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);
bool valid = chain.Build(testCert);
Assert.False(valid);
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
}
}
[Theory]
// Tests that the chain fails when a system trust certificate is added to the custom root trust, but its root isn't.
[InlineData(true)]
// Tests that the chain fails when no certificates are added to the custom root trust.
[InlineData(false)]
public static void SystemTrustCertificateWithCustomRootTrust(bool addCertificateToCustomRootTrust)
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var testCert = new X509Certificate2(TestFiles.ChainPfxFile, TestData.ChainPfxPassword))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = microsoftDotCom.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
if (addCertificateToCustomRootTrust)
{
chain.ChainPolicy.CustomTrustStore.Add(testCert);
}
if (PlatformDetection.IsAndroid)
{
// Android does not support an empty custom root trust
// Only self-issued certs are treated as trusted anchors, so building the chain
// should throw PNSE regardless of whether or not testCert is added to the store
Assert.Throws<PlatformNotSupportedException>(() => chain.Build(microsoftDotCom));
}
else
{
Assert.False(chain.Build(microsoftDotCom));
// Historically, Windows has not searched system stores when CustomRootTrust is enabled.
// That seems to have recently (as of 2021-07-09) changed.
Assert.InRange(chain.ChainElements.Count, 2, 3);
if (chain.ChainElements.Count < 3)
{
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
}
else
{
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.AllStatusFlags());
}
// Check some known conditions.
if (PlatformDetection.UsesAppleCrypto)
{
Assert.Equal(3, chain.ChainElements.Count);
}
else if (OperatingSystem.IsLinux())
{
Assert.Equal(2, chain.ChainElements.Count);
}
}
}
}
public enum BuildChainCustomTrustStoreTestArguments : int
{
TrustedIntermediateUntrustedRoot,
UntrustedIntermediateTrustedRoot,
TrustedIntermediateTrustedRoot,
MultipleCalls
}
public static IEnumerable<object[]> BuildChainCustomTrustStoreData()
{
if (!PlatformDetection.IsAndroid)
{
// Android doesn't support an empty custom root
X509ChainStatusFlags flags = X509ChainStatusFlags.UntrustedRoot;
if (!SignatureSupport.SupportsX509Sha1Signatures)
{
flags |= X509ChainStatusFlags.NotSignatureValid;
}
yield return new object[] { false, flags, BuildChainCustomTrustStoreTestArguments.TrustedIntermediateUntrustedRoot };
}
yield return new object[] { true, X509ChainStatusFlags.NoError, BuildChainCustomTrustStoreTestArguments.UntrustedIntermediateTrustedRoot };
yield return new object[] { true, X509ChainStatusFlags.NoError, BuildChainCustomTrustStoreTestArguments.TrustedIntermediateTrustedRoot };
yield return new object[] { true, X509ChainStatusFlags.NoError, BuildChainCustomTrustStoreTestArguments.MultipleCalls };
}
[Theory]
[MemberData(nameof(BuildChainCustomTrustStoreData))]
public static void BuildChainCustomTrustStore(
bool chainBuildsSuccessfully,
X509ChainStatusFlags chainFlags,
BuildChainCustomTrustStoreTestArguments testArguments)
{
using (var endCert = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var issuerCert = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var rootCert = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chainTest = chainHolder.Chain;
chainTest.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chainTest.ChainPolicy.VerificationTime = endCert.NotBefore.AddSeconds(1);
chainTest.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chainTest.ChainPolicy.ExtraStore.Add(issuerCert);
switch (testArguments)
{
case BuildChainCustomTrustStoreTestArguments.TrustedIntermediateUntrustedRoot:
chainTest.ChainPolicy.ExtraStore.Add(rootCert);
break;
case BuildChainCustomTrustStoreTestArguments.UntrustedIntermediateTrustedRoot:
chainTest.ChainPolicy.CustomTrustStore.Add(rootCert);
break;
case BuildChainCustomTrustStoreTestArguments.TrustedIntermediateTrustedRoot:
chainTest.ChainPolicy.CustomTrustStore.Add(rootCert);
break;
case BuildChainCustomTrustStoreTestArguments.MultipleCalls:
chainTest.ChainPolicy.CustomTrustStore.Add(rootCert);
chainTest.Build(endCert);
chainHolder.DisposeChainElements();
chainTest.ChainPolicy.CustomTrustStore.Remove(rootCert);
chainTest.ChainPolicy.TrustMode = X509ChainTrustMode.System;
break;
default:
throw new InvalidDataException();
}
Assert.Equal(chainBuildsSuccessfully, chainTest.Build(endCert));
Assert.Equal(3, chainTest.ChainElements.Count);
Assert.Equal(chainFlags, chainTest.AllStatusFlags());
}
}
[Fact]
public static void BuildChainWithSystemTrustAndCustomTrustCertificates()
{
using (var testCert = new X509Certificate2(TestFiles.ChainPfxFile, TestData.ChainPfxPassword))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = testCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2());
Assert.Throws<CryptographicException>(() => chain.Build(testCert));
}
}
[Fact]
public static void BuildChainWithCustomRootTrustAndInvalidCustomCertificates()
{
using (var testCert = new X509Certificate2(TestFiles.ChainPfxFile, TestData.ChainPfxPassword))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = testCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2());
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
Assert.Throws<CryptographicException>(() => chain.Build(testCert));
}
}
[Theory]
[InlineData(-1)]
[InlineData(2)]
public static void Invalidx509ChainTrustMode(int trustMode)
{
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
Assert.Throws<ArgumentException>(() => chain.ChainPolicy.TrustMode = (X509ChainTrustMode)trustMode);
}
}
public static IEnumerable<object[]> VerifyExpirationData()
{
// The test will be using the chain for TestData.MicrosoftDotComSslCertBytes
// The leaf cert (microsoft.com) is valid from 2020-08-28 22:17:02Z to 2021-08-28 22:17:02Z
DateTime[] validTimes =
{
// The NotBefore value
new DateTime(2020, 08, 28, 22, 17, 02, DateTimeKind.Utc),
// One second before the NotAfter value
new DateTime(2021, 08, 28, 22, 17, 01, DateTimeKind.Utc),
};
// The NotAfter value as a boundary condition differs on Windows and OpenSSL.
// Windows considers it valid (<= NotAfter).
// OpenSSL considers it invalid (< NotAfter), with a comment along the lines of
// "it'll be invalid in a millisecond, why bother with the <="
// So that boundary condition is not being tested.
DateTime[] invalidTimes =
{
// One second before the NotBefore time
new DateTime(2020, 08, 28, 22, 17, 01, DateTimeKind.Utc),
// One second after the NotAfter time
new DateTime(2021, 08, 28, 22, 17, 03, DateTimeKind.Utc),
};
List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3);
// Build (date, result, kind) tuples. The kind is used to help describe the test case.
// The DateTime format that xunit uses does show a difference in the DateTime itself, but
// having the Kind be a separate parameter just helps.
foreach (DateTime utcTime in validTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, true });
testCases.Add(new object[] { local, true });
testCases.Add(new object[] { unspecified, true });
}
foreach (DateTime utcTime in invalidTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, false });
testCases.Add(new object[] { local, false });
testCases.Add(new object[] { unspecified, false });
}
return testCases;
}
[Theory]
[MemberData(nameof(VerifyExpirationData))]
public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid)
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// Ignore anything except NotTimeValid
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = verificationTime;
bool builtSuccessfully = chain.Build(microsoftDotCom);
Assert.Equal(shouldBeValid, builtSuccessfully);
// If we failed to build the chain, validate the chain status
if (!shouldBeValid)
{
if (PlatformDetection.IsAndroid)
{
// Android always validates timestamp as part of building a path,
// so invalid time comes back as PartialChain with no elements
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
Assert.Equal(0, chain.ChainElements.Count);
}
else
{
// Ensure that NotTimeValid is one of the reasons.
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
}
}
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_Match()
{
using (var cert = new X509Certificate2(TestData.CertWithEnhancedKeyUsage))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(cert);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(cert);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.CertWithEnhancedKeyUsage))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Gibberish. (Code Signing + ".1")
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1"));
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(cert);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[ConditionalFact(typeof(SignatureSupport), nameof(SignatureSupport.SupportsX509Sha1Signatures))]
public static void BuildChain_WithCertificatePolicy_Match()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19"));
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(cert);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(cert);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999"));
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(cert);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[ConditionalFact(nameof(TrustsMicrosoftDotComRoot))]
public static void BuildChain_FailOnlyApplicationPolicy()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (ChainHolder holder = new ChainHolder())
{
holder.Chain.ChainPolicy.ApplicationPolicy.Add(new Oid("0.1.2.3.4", null));
holder.Chain.ChainPolicy.VerificationTime = microsoftDotCom.NotBefore.AddDays(1);
holder.Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
Assert.False(holder.Chain.Build(microsoftDotCom));
Assert.Equal(
X509ChainStatusFlags.NotValidForUsage,
holder.Chain.ChainStatus.Aggregate(
X509ChainStatusFlags.NoError,
(a, status) => a | status.Status));
Assert.Equal(3, holder.Chain.ChainElements.Count);
Assert.Equal(microsoftDotCom.RawData, holder.Chain.ChainElements[0].Certificate.RawData);
Assert.Equal(microsoftDotComRoot.RawData, holder.Chain.ChainElements[2].Certificate.RawData);
Assert.Equal(
X509ChainStatusFlags.NotValidForUsage,
holder.Chain.ChainElements[0].ChainElementStatus.Aggregate(
X509ChainStatusFlags.NoError,
(a, status) => a | status.Status));
Assert.Equal(
X509ChainStatusFlags.NotValidForUsage,
holder.Chain.ChainElements[1].ChainElementStatus.Aggregate(
X509ChainStatusFlags.NoError,
(a, status) => a | status.Status));
Assert.Equal(
X509ChainStatusFlags.NotValidForUsage,
holder.Chain.ChainElements[2].ChainElementStatus.Aggregate(
X509ChainStatusFlags.NoError,
(a, status) => a | status.Status));
}
}
[ConditionalFact(nameof(TrustsMicrosoftDotComRoot))]
[OuterLoop(/* Modifies user certificate store */)]
[SkipOnPlatform(PlatformSupport.MobileAppleCrypto, "Root certificate store is not accessible")]
public static void BuildChain_MicrosoftDotCom_WithRootCertInUserAndSystemRootCertStores()
{
// Verifies that when the same root cert is placed in both a user and machine root certificate store,
// any certs chain building to that root cert will build correctly
//
// We use a copy of the microsoft.com SSL certs and root certs to validate that the chain can build
// successfully
bool shouldInstallCertToUserStore = true;
bool installedCertToUserStore = false;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// Check that microsoft.com's root certificate IS installed in the machine root store as a sanity step
using (var machineRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
machineRootStore.Open(OpenFlags.ReadOnly);
bool foundCert = false;
foreach (var machineCert in machineRootStore.Certificates)
{
if (machineCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
machineCert.Dispose();
}
Assert.True(foundCert, string.Format("Did not find expected certificate with thumbprint '{0}' in the machine root store", microsoftDotComRoot.Thumbprint));
}
// Concievably at this point there could still be something wrong and we still don't chain build correctly - if that's
// the case, then there's likely something wrong with the machine. Validating that happy path is out of scope
// of this particular test.
// Check that microsoft.com's root certificate is NOT installed on in the user cert store as a sanity step
// We won't try to install the microsoft.com root cert into the user root store if it's already there
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
{
userRootStore.Open(OpenFlags.ReadOnly);
foreach (var userCert in userRootStore.Certificates)
{
bool foundCert = false;
if (userCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
userCert.Dispose();
if (foundCert)
{
shouldInstallCertToUserStore = false;
}
}
}
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
using (var chainHolder = new ChainHolder())
{
try
{
if (shouldInstallCertToUserStore)
{
try
{
userRootStore.Open(OpenFlags.ReadWrite);
}
catch (CryptographicException)
{
return;
}
userRootStore.Add(microsoftDotComRoot); // throws CryptographicException
installedCertToUserStore = true;
}
X509Chain chainValidator = chainHolder.Chain;
chainValidator.ChainPolicy.VerificationTime = new DateTime(2021, 02, 26, 12, 01, 01, DateTimeKind.Local);
chainValidator.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool chainBuildResult = chainValidator.Build(microsoftDotCom);
StringBuilder builder = new StringBuilder();
foreach (var status in chainValidator.ChainStatus)
{
builder.AppendLine($"{status.Status} {status.StatusInformation}");
}
Assert.True(chainBuildResult,
string.Format("Certificate chain build failed. ChainStatus is:{0}{1}", Environment.NewLine, builder.ToString()));
}
finally
{
if (installedCertToUserStore)
{
userRootStore.Remove(microsoftDotComRoot);
}
}
}
}
}
[Fact]
public static void Create()
{
using (var chain = X509Chain.Create())
Assert.NotNull(chain);
}
[Fact]
public static void BuildChainInvalidValues()
{
using (var chain = X509Chain.Create())
{
AssertExtensions.Throws<ArgumentException>("certificate", () => chain.Build(null));
AssertExtensions.Throws<ArgumentException>("certificate", () => chain.Build(new X509Certificate2()));
}
}
[Fact]
public static void InvalidSelfSignedSignature()
{
X509ChainStatusFlags expectedFlags;
if (OperatingSystem.IsWindows())
{
expectedFlags = X509ChainStatusFlags.NotSignatureValid;
}
else if (PlatformDetection.UsesAppleCrypto)
{
// For OSX alone expectedFlags here means OR instead of AND.
// Because the error code changed in 10.13.4 from UntrustedRoot to PartialChain
// and we handle that later in this test.
expectedFlags =
X509ChainStatusFlags.UntrustedRoot |
X509ChainStatusFlags.PartialChain;
}
else if (OperatingSystem.IsAndroid())
{
// Android always validates signature as part of building a path,
// so invalid signature comes back as PartialChain with no elements
expectedFlags = X509ChainStatusFlags.PartialChain;
}
else
{
expectedFlags =
X509ChainStatusFlags.NotSignatureValid |
X509ChainStatusFlags.UntrustedRoot;
}
byte[] certBytes = (byte[])TestData.MicrosoftDotComRootBytes.Clone();
// The signature goes up to the very last byte, so flip some bits in it.
certBytes[certBytes.Length - 1] ^= 0xFF;
using (var cert = new X509Certificate2(certBytes))
using (ChainHolder holder = new ChainHolder())
{
X509Chain chain = holder.Chain;
X509ChainPolicy policy = chain.ChainPolicy;
policy.VerificationTime = cert.NotBefore.AddDays(3);
policy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(cert);
X509ChainStatusFlags allFlags = chain.AllStatusFlags();
if (PlatformDetection.UsesAppleCrypto)
{
// If we're on 10.13.3 or older we get UntrustedRoot.
// If we're on 10.13.4 or newer we get PartialChain.
//
// So make the expectedValue be whichever of those two is set.
expectedFlags = (expectedFlags & allFlags);
// One of them has to be set.
Assert.NotEqual(X509ChainStatusFlags.NoError, expectedFlags);
// Continue executing now to ensure that no other unexpected flags were set.
}
Assert.Equal(expectedFlags, allFlags);
}
}
[Fact]
// Android does not support the detailed status in this test. It always validates time
// and trusted root. It will fail to build any chain if those are not valid.
[SkipOnPlatform(TestPlatforms.Android, "Not supported on Android.")]
public static void ChainErrorsAtMultipleLayers()
{
// These certificates were generated for this test using CertificateRequest
// but the netstandard(2.0) version of this test library doesn't have
// CertificateRequest available.
//
// These certificates have been hard-coded to enable the scenario on
// netstandard.
byte[] endEntityBytes = Encoding.ASCII.GetBytes(@"
-----BEGIN CERTIFICATE-----
MIIC6DCCAdCgAwIBAgIQAKjmD7+TWUwQN2ucajn9kTANBgkqhkiG9w0BAQsFADAXMRUwEwYDVQQD
EwxJbnRlcm1lZGlhdGUwHhcNMTkwMzAzMjM1NzA3WhcNMTkwNjAzMjM1NzA3WjAVMRMwEQYDVQQD
EwpFbmQtRW50aXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxTybBkpMdQ8IeL1C
jG755+ifQfqjNt4+Xhm3pbMi+nCRD68tym1xviUka1hQmx+I1mptswW0Laq1owur0r2KanKoIP2F
i2h6orOOdslMFPMWqCuNTU4C7cUxokaWah0R7FihwW+aBeWgxG948Cvt+ByQeR1ns9yo7wa8f8kT
IwzOUu0v1Yj5oW5bOn/cmIBE1C5CD5RivPMGUXX8mZ/myNh16dLQqJW5yQt/uvfr7lkNWC0qq+v7
Ely4+X27acwMTdtk4chcr5/bTS5FXV7HVqwhajOmm6WrzagPZBELWKRk2EaJkha/MLrBqNfHExs4
sx2ks+TTclrOrRzG+AUBuQIDAQABozIwMDAMBgNVHRMBAf8EAjAAMAsGA1UdDwQEAwIF4DATBgNV
HSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQsFAAOCAQEAbrEbiw4gpgWi3SJ+sGrfcWCAldpx
0735hkkYz94OsJjIwWfgQ03pYZwjcnIE4Ln0PU2E52D2ldsJlAE376hpNxdO0X4RLpZVZPEjKGTF
v2Rf+d0cpqha5J//mqcTTm7F58JRKyfEQn0pqfxx4VyXeLfEsqYbT3kY7ufK0km3Jst0DGw2AGue
MPmiZicaNlXPVO9vyW4s6J23+kol6X8K2rnVht9jagfnOQ990Ux2xXGyDGM4I0pvW1Zo4vid/eli
psHHsU9xg0o7L2WXD5qYhD2JCQIVWNRmRZCf1luWlKqUaqWWONMJ44hk8Md+ohxpyCRmbtLRZPzd
wlkQzPsc9A==
-----END CERTIFICATE-----");
byte[] intermediateBytes = Encoding.ASCII.GetBytes(@"
-----BEGIN CERTIFICATE-----
MIIC1DCCAbygAwIBAgIPRoY1rB2tMVJeYB4GILkNMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNVBAMT
CVRlc3QgUm9vdDAeFw0xOTAyMTgyMzU3MDdaFw0yMDAyMTgyMzU3MDdaMBcxFTATBgNVBAMTDElu
dGVybWVkaWF0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALxYzEN6nYvQ0TOg/jOF
wdBGRUYhTiJpYGFBh9826X5vKlbCS1UAcjFRXmKtJ4WZ8v3peCBPxvVe/1KR38+MWNVtO4B1GBvr
qR2T9k1ewgn0lO3i6krnIAhJQ+F94xGcsRAfZjXBh7lOmTE9ZlDhDJWkehBIs5TteiBOfbGDml2S
v7x81cmm2o/sDoP1oVGhezOkFtI2/NdZYKxRthnjDywN3W4KFataJFATVv/yq+QjcLEWrXFRpzDE
rpVdYmj66kaAnu9D4sHhFqOk1SX3JvcB361stVuUPp2ri75MaaXakweH6X/Yb4nPNV6m1ENwMoDy
HqrZrHSK8SpzfhY9aB0CAwEAAaMgMB4wDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAYYwDQYJ
KoZIhvcNAQELBQADggEBAC4oJ2SH+Ov4QIMXo7mwGSrwONkdMuKyyM9shZiGEH+zIO9SVuPuvtQG
cePR2bijSz2DtjySi+ST8y3Ql7A3isfbXYPDFmnkzKP6hGvLkctc8eO8U1x7ny+QW1max0gm3UA8
CY0IMP8pCHUZH9OX/K0N9L+GItqlBK8G4grJ4o43da2x9L0hIrdauPadaGcJalf8k1ymhJ4VDj7t
ueuTl2qTtbBh015GuEld61EBXSBLIUqwOAeFYrNJbC4J2mXgnLTWC380cBf5KWeSdjLYgk2sZ1V4
FKKQecZIhxdlDGzMAbbmEV+2EqS+As2C7+y4dkpG4nnbQe/4AFr8vekHdrI=
-----END CERTIFICATE-----");
byte[] rootBytes = Encoding.ASCII.GetBytes(@"
-----BEGIN CERTIFICATE-----
MIICyjCCAbKgAwIBAgIIKKt3K3rRbvQwDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAxMJVGVzdCBS
b290MB4XDTE5MDIwNDIzNTcwN1oXDTIxMDIwNDIzNTcwN1owFDESMBAGA1UEAxMJVGVzdCBSb290
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiM7tv4YvqmWYGF1vbeM2cQWV1NVBxKU4
ZK5XEJHZirzE2HCiA0+hI/UD7xnfBrzGQRLsHnp9vfhBi/0wenSIKTckxcGGpuM+JzNoVF97uFSd
bKvfIwQZzbdRGyTF1eoQWCylsZsnZOXg8c/yoFhG2TJB38l09RYn+HkMkapQERFKSXPZ7taNVJNb
Sedp3l9jO0aVmh9rmJ7taBXBfWDmSWqhkxjkEcbiRxB7z5K8YxZBlHQCLqf43JiCbKIMBHdzTg+N
lEBkBGp6T2hoJ4/A1uwvhesjmyqagZrC2NnzOWOxUQ/WujIUfS62ii/yDkP4Jo3745lJ9XXoPbIw
AwvWYQIDAQABoyAwHjAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBhjANBgkqhkiG9w0BAQsF
AAOCAQEAA/pfswrUzcLP5UfmHgQDc1slJjh0btnkN+4dxCCTLcnteJCTumYw+/82qL+O4t1KlzlS
2Eqgyx0u48YmwDp/5jWAvT8RX8pvV3Prd7T8/dp/ucES7R9r3zF2Rmw5Me9iq1yaLAypGyBGqV1J
HAwJjH/eKZ5iuOMhFljs2R5Gh5rRsQjNVUCRsolCds4d1f+76fi2SGaKqkAA4gzg1c71SPTAaUPR
ythjxnoCBDVFmwV5opXZj9qIZoUdH92gCVFgMWkxWCYWzyH78uIUzV1oo+KNwK1SCTnfVHcfWRIL
tHP28fj0LUop/QFojSZPsaPAW6JvoQ0t4hd6WoyX6z7FsA==
-----END CERTIFICATE-----");
using (X509Certificate2 endEntityCert = new X509Certificate2(endEntityBytes))
using (X509Certificate2 intermediateCert = new X509Certificate2(intermediateBytes))
using (X509Certificate2 rootCert = new X509Certificate2(rootBytes))
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.ExtraStore.Add(intermediateCert);
chain.ChainPolicy.ExtraStore.Add(rootCert);
chain.ChainPolicy.VerificationTime = endEntityCert.NotAfter.AddDays(1);
Assert.False(chain.Build(endEntityCert));
Assert.Equal(3, chain.ChainElements.Count);
Assert.Equal(X509ChainStatusFlags.NotTimeValid, chain.ChainElements[0].AllStatusFlags());
Assert.Equal(X509ChainStatusFlags.NoError, chain.ChainElements[1].AllStatusFlags());
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainElements[2].AllStatusFlags());
Assert.Equal(
X509ChainStatusFlags.NotTimeValid | X509ChainStatusFlags.UntrustedRoot,
chain.AllStatusFlags());
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Android, "Chain building on Android fails with an empty subject")]
public static void ChainWithEmptySubject()
{
using (var cert = new X509Certificate2(TestData.EmptySubjectCertificate))
using (var issuer = new X509Certificate2(TestData.EmptySubjectIssuerCertificate))
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(issuer);
chain.ChainPolicy.ExtraStore.Add(issuer);
Assert.True(chain.Build(cert), "chain.Build(cert)");
Assert.Equal(2, chain.ChainElements.Count);
Assert.Equal(string.Empty, cert.Subject);
Assert.Equal(cert.RawData, chain.ChainElements[0].Certificate.RawData);
Assert.Equal(issuer.RawData, chain.ChainElements[1].Certificate.RawData);
}
}
[Fact]
public static void BuildInvalidSignatureTwice()
{
byte[] bytes = (byte[])TestData.MsCertificate.Clone();
bytes[bytes.Length - 1] ^= 0xFF;
using (X509Certificate2 microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (X509Certificate2 microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (X509Certificate2 cert = new X509Certificate2(bytes))
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(microsoftDotComRoot);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
int iter = 0;
void CheckChain()
{
iter++;
bool valid = chain.Build(cert);
X509ChainStatusFlags allFlags = chain.AllStatusFlags();
if (PlatformDetection.UsesAppleCrypto)
{
// OSX considers this to be valid because it doesn't report NotSignatureValid,
// just PartialChain ("I couldn't find an issuer that made the signature work"),
// and PartialChain + AllowUnknownCertificateAuthority == pass.
Assert.True(valid, $"Chain is valid on execution {iter}");
Assert.Equal(1, chain.ChainElements.Count);
Assert.Equal(
X509ChainStatusFlags.PartialChain,
allFlags);
}
else if (OperatingSystem.IsAndroid())
{
// Android always validates signature as part of building a path,
// so invalid signature comes back as PartialChain with no elements
Assert.Equal(X509ChainStatusFlags.PartialChain, allFlags);
Assert.Equal(0, chain.ChainElements.Count);