-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
DynamicChainTests.cs
1069 lines (941 loc) · 43.8 KB
/
DynamicChainTests.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.Formats.Asn1;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/57506", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoRuntime), nameof(PlatformDetection.IsMariner))]
public static class DynamicChainTests
{
private static X509Extension BasicConstraintsCA => new X509BasicConstraintsExtension(
certificateAuthority: true,
hasPathLengthConstraint: false,
pathLengthConstraint: 0,
critical: true);
private static X509Extension BasicConstraintsEndEntity => new X509BasicConstraintsExtension(
certificateAuthority: false,
hasPathLengthConstraint: false,
pathLengthConstraint: 0,
critical: true);
public static object[][] InvalidSignature3Cases { get; } =
new object[][]
{
new object[]
{
X509ChainStatusFlags.NotSignatureValid,
X509ChainStatusFlags.NoError,
X509ChainStatusFlags.UntrustedRoot,
},
new object[]
{
X509ChainStatusFlags.NoError,
X509ChainStatusFlags.NotSignatureValid,
X509ChainStatusFlags.UntrustedRoot,
},
new object[]
{
X509ChainStatusFlags.NoError,
X509ChainStatusFlags.NoError,
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.UntrustedRoot,
},
new object[]
{
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid,
X509ChainStatusFlags.NoError,
X509ChainStatusFlags.UntrustedRoot,
},
new object[]
{
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid,
X509ChainStatusFlags.NotTimeValid,
X509ChainStatusFlags.UntrustedRoot,
},
new object[]
{
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid,
X509ChainStatusFlags.NotTimeValid,
X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid,
},
};
[Theory]
[MemberData(nameof(InvalidSignature3Cases))]
public static void BuildInvalidSignatureTwice(
X509ChainStatusFlags endEntityErrors,
X509ChainStatusFlags intermediateErrors,
X509ChainStatusFlags rootErrors)
{
string testName = $"{nameof(BuildInvalidSignatureTwice)} {endEntityErrors} {intermediateErrors} {rootErrors}";
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
testName: testName);
X509Certificate2 TamperIfNeeded(X509Certificate2 input, X509ChainStatusFlags flags)
{
if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0)
{
X509Certificate2 tampered = TamperSignature(input);
input.Dispose();
return tampered;
}
return input;
}
DateTime RewindIfNeeded(DateTime input, X509Certificate2 cert, X509ChainStatusFlags flags)
{
if ((flags & X509ChainStatusFlags.NotTimeValid) != 0)
{
return cert.NotBefore.AddMinutes(-1);
}
return input;
}
int expectedCount = 3;
DateTime verificationTime = endEntityCert.NotBefore.AddMinutes(1);
verificationTime = RewindIfNeeded(verificationTime, endEntityCert, endEntityErrors);
verificationTime = RewindIfNeeded(verificationTime, intermediateCert, intermediateErrors);
verificationTime = RewindIfNeeded(verificationTime, rootCert, rootErrors);
// Replace the certs for the scenario.
endEntityCert = TamperIfNeeded(endEntityCert, endEntityErrors);
intermediateCert = TamperIfNeeded(intermediateCert, intermediateErrors);
rootCert = TamperIfNeeded(rootCert, rootErrors);
if (PlatformDetection.UsesAppleCrypto)
{
// For the lower levels, turn NotSignatureValid into PartialChain,
// and clear all errors at higher levels.
if ((endEntityErrors & X509ChainStatusFlags.NotSignatureValid) != 0)
{
expectedCount = 1;
endEntityErrors &= ~X509ChainStatusFlags.NotSignatureValid;
endEntityErrors |= X509ChainStatusFlags.PartialChain;
intermediateErrors = X509ChainStatusFlags.NoError;
rootErrors = X509ChainStatusFlags.NoError;
}
else if ((intermediateErrors & X509ChainStatusFlags.NotSignatureValid) != 0)
{
expectedCount = 2;
intermediateErrors &= ~X509ChainStatusFlags.NotSignatureValid;
intermediateErrors |= X509ChainStatusFlags.PartialChain;
rootErrors = X509ChainStatusFlags.NoError;
}
else if ((rootErrors & X509ChainStatusFlags.NotSignatureValid) != 0)
{
rootErrors &= ~X509ChainStatusFlags.NotSignatureValid;
// On 10.13+ it becomes PartialChain, and UntrustedRoot goes away.
if (PlatformDetection.UsesAppleCrypto)
{
rootErrors &= ~X509ChainStatusFlags.UntrustedRoot;
rootErrors |= 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
expectedCount = 0;
endEntityErrors = X509ChainStatusFlags.PartialChain;
intermediateErrors = X509ChainStatusFlags.PartialChain;
rootErrors = X509ChainStatusFlags.PartialChain;
}
else if (OperatingSystem.IsWindows())
{
// Windows only reports NotTimeValid on the start-of-chain (end-entity in this case)
// If it were possible in this suite to get only a higher-level cert as NotTimeValid
// without the lower one, that would have resulted in NotTimeNested.
intermediateErrors &= ~X509ChainStatusFlags.NotTimeValid;
rootErrors &= ~X509ChainStatusFlags.NotTimeValid;
}
X509ChainStatusFlags expectedAllErrors = endEntityErrors | intermediateErrors | rootErrors;
bool expectSuccess;
if (PlatformDetection.IsAndroid)
{
// Android always validates signature as part of building a path, so chain
// building is expected to fail
expectSuccess = false;
}
else
{
// If PartialChain or UntrustedRoot are the only remaining errors, the chain will succeed.
const X509ChainStatusFlags SuccessCodes =
X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain;
expectSuccess = (expectedAllErrors & ~SuccessCodes) == 0;
}
using (endEntityCert)
using (intermediateCert)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationTime = verificationTime;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ExtraStore.Add(intermediateCert);
chain.ChainPolicy.ExtraStore.Add(rootCert);
// Android doesn't respect AllowUnknownCertificateAuthority
if (!PlatformDetection.IsAndroid)
{
chain.ChainPolicy.VerificationFlags |=
X509VerificationFlags.AllowUnknownCertificateAuthority;
}
int i = 0;
void CheckChain()
{
i++;
bool valid = chain.Build(endEntityCert);
if (expectSuccess)
{
Assert.True(valid, $"Chain build on iteration {i}");
}
else
{
Assert.False(valid, $"Chain build on iteration {i}");
}
Assert.Equal(expectedCount, chain.ChainElements.Count);
Assert.Equal(expectedAllErrors, chain.AllStatusFlags());
if (expectedCount > 0)
{
Assert.Equal(endEntityErrors, chain.ChainElements[0].AllStatusFlags());
}
if (expectedCount > 2)
{
Assert.Equal(rootErrors, chain.ChainElements[2].AllStatusFlags());
}
if (expectedCount > 1)
{
Assert.Equal(intermediateErrors, chain.ChainElements[1].AllStatusFlags());
}
chainHolder.DisposeChainElements();
}
CheckChain();
CheckChain();
}
}
[Fact]
public static void BasicConstraints_ExceedMaximumPathLength()
{
X509Extension[] rootExtensions = new []
{
new X509BasicConstraintsExtension(
certificateAuthority: true,
hasPathLengthConstraint: true,
pathLengthConstraint: 0,
critical: true),
};
X509Extension[] intermediateExtensions = new []
{
new X509BasicConstraintsExtension(
certificateAuthority: true,
hasPathLengthConstraint: true,
pathLengthConstraint: 0,
critical: true),
};
TestDataGenerator.MakeTestChain4(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert1,
out X509Certificate2 intermediateCert2,
out X509Certificate2 rootCert,
rootExtensions: rootExtensions,
intermediateExtensions: intermediateExtensions);
using (endEntityCert)
using (intermediateCert1)
using (intermediateCert2)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(rootCert);
chain.ChainPolicy.ExtraStore.Add(intermediateCert1);
chain.ChainPolicy.ExtraStore.Add(intermediateCert2);
Assert.False(chain.Build(endEntityCert));
Assert.Equal(PlatformBasicConstraints(X509ChainStatusFlags.InvalidBasicConstraints), chain.AllStatusFlags());
}
}
[Fact]
public static void BasicConstraints_ViolatesCaFalse()
{
X509Extension[] intermediateExtensions = new []
{
new X509BasicConstraintsExtension(
certificateAuthority: false,
hasPathLengthConstraint: false,
pathLengthConstraint: 0,
critical: true)
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(
rootCert,
intermediateCert,
endEntityCert,
expectedFlags: PlatformBasicConstraints(X509ChainStatusFlags.InvalidBasicConstraints));
}
}
[Fact]
public static void TestLeafCertificateWithUnknownCriticalExtension()
{
using (RSA key = RSA.Create())
{
CertificateRequest certReq = new CertificateRequest(
new X500DistinguishedName("CN=Cert"),
key,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
const string PrecertificatePoisonExtensionOid = "1.3.6.1.4.1.11129.2.4.3";
certReq.CertificateExtensions.Add(new X509Extension(
new AsnEncodedData(
new Oid(PrecertificatePoisonExtensionOid),
new byte[] { 5, 0 }),
critical: true));
DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddDays(-1);
DateTimeOffset notAfter = notBefore.AddDays(30);
using (X509Certificate2 cert = certReq.CreateSelfSigned(notBefore, notAfter))
using (ChainHolder holder = new ChainHolder())
{
X509Chain chain = holder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
Assert.False(chain.Build(cert));
if (PlatformDetection.IsAndroid)
{
// Android always unsupported critical extensions as part of building a path,
// so errors comes back as PartialChain with no elements
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
Assert.Equal(0, chain.ChainElements.Count);
}
else
{
X509ChainElement certElement = chain.ChainElements.Single();
const X509ChainStatusFlags ExpectedFlag = X509ChainStatusFlags.HasNotSupportedCriticalExtension;
X509ChainStatusFlags actualFlags = certElement.AllStatusFlags();
Assert.True((actualFlags & ExpectedFlag) == ExpectedFlag, $"Has expected flag {ExpectedFlag} but was {actualFlags}");
}
}
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Android, "Android does not support AIA fetching")]
public static void TestInvalidAia()
{
using (RSA key = RSA.Create())
{
CertificateRequest rootReq = new CertificateRequest(
"CN=Root",
key,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
rootReq.CertificateExtensions.Add(BasicConstraintsCA);
CertificateRequest certReq = new CertificateRequest(
"CN=test",
key,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
certReq.CertificateExtensions.Add(BasicConstraintsEndEntity);
certReq.CertificateExtensions.Add(
new X509Extension(
"1.3.6.1.5.5.7.1.1",
new byte[] { 5 },
critical: false));
DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddDays(-1);
DateTimeOffset notAfter = notBefore.AddDays(30);
using (X509Certificate2 root = rootReq.CreateSelfSigned(notBefore, notAfter))
using (X509Certificate2 ee = certReq.Create(root, notBefore, notAfter, root.GetSerialNumber()))
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
Assert.False(chain.Build(ee));
Assert.Equal(1, chain.ChainElements.Count);
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
}
}
}
[Fact]
// macOS (10.14) will not load certificates with NumericString in their subject
// if the 0x12 (NumericString) is changed to 0x13 (PrintableString) then the cert
// import doesn't fail.
[SkipOnPlatform(TestPlatforms.OSX, "Not supported on OSX.")]
public static void VerifyNumericStringSubject()
{
X500DistinguishedName dn = new X500DistinguishedName(
"30283117301506052901020203120C313233203635342037383930310D300B0603550403130454657374".HexToByteArray());
using (RSA key = RSA.Create())
{
CertificateRequest req = new CertificateRequest(
dn,
key,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
DateTimeOffset now = DateTimeOffset.UtcNow;
using (X509Certificate2 cert = req.CreateSelfSigned(now.AddDays(-1), now.AddDays(1)))
{
Assert.Equal("CN=Test, OID.1.1.1.2.2.3=123 654 7890", cert.Subject);
}
}
}
[Theory]
// Test with intermediate certificates in CustomTrustStore
[InlineData(true, X509ChainStatusFlags.NoError)]
// Test with ExtraStore containing root certificate
[InlineData(false, X509ChainStatusFlags.UntrustedRoot)]
public static void CustomRootTrustDoesNotTrustIntermediates(
bool saveAllInCustomTrustStore,
X509ChainStatusFlags chainFlags)
{
string testName = $"{nameof(CustomRootTrustDoesNotTrustIntermediates)} {saveAllInCustomTrustStore} {chainFlags}";
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
testName: testName);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(intermediateCert);
if (saveAllInCustomTrustStore)
{
chain.ChainPolicy.CustomTrustStore.Add(rootCert);
}
else
{
chain.ChainPolicy.ExtraStore.Add(rootCert);
}
if (PlatformDetection.IsAndroid && !saveAllInCustomTrustStore)
{
// Android does not support an empty custom root trust
// Only self-issued certs are treated as trusted anchors, so building the chain
// should through PNSE even though the intermediate cert is added to the store
Assert.Throws<PlatformNotSupportedException>(() => chain.Build(endEntityCert));
}
else
{
Assert.Equal(saveAllInCustomTrustStore, chain.Build(endEntityCert));
Assert.Equal(3, chain.ChainElements.Count);
Assert.Equal(chainFlags, chain.AllStatusFlags());
}
}
}
[Fact]
public static void CustomTrustModeWithNoCustomTrustCerts()
{
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
if (PlatformDetection.IsAndroid)
{
// Android does not support an empty custom root trust
Assert.Throws<PlatformNotSupportedException>(() => chain.Build(endEntityCert));
}
else
{
Assert.False(chain.Build(endEntityCert));
Assert.Equal(1, chain.ChainElements.Count);
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
}
}
}
[Fact]
public static void NameConstraintViolation_PermittedTree_Dns()
{
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddDnsName("microsoft.com");
// permitted DNS name constraint for .example.com
string nameConstraints = "3012A010300E820C2E6578616D706C652E636F6D";
TestNameConstrainedChain(nameConstraints, builder, (bool result, X509Chain chain) => {
Assert.False(result, "chain.Build");
Assert.Equal(PlatformNameConstraints(X509ChainStatusFlags.HasNotPermittedNameConstraint), chain.AllStatusFlags());
});
}
[Fact]
public static void NameConstraintViolation_ExcludedTree_Dns()
{
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddDnsName("www.example.com");
// excluded DNS name constraint for .example.com.
string nameConstraints = "3012A110300E820C2E6578616D706C652E636F6D";
if (PlatformDetection.IsAndroid)
{
// Android does not consider the constraint as being violated when it has
// the leading period. It checks expects the period as part of the left-side
// labels and not the constraint when doing validation.
// Use an excluded DNS name constraint without the period: example.com
nameConstraints = "3011A10F300D820B6578616D706C652E636F6D";
}
TestNameConstrainedChain(nameConstraints, builder, (bool result, X509Chain chain) => {
Assert.False(result, "chain.Build");
Assert.Equal(PlatformNameConstraints(X509ChainStatusFlags.HasExcludedNameConstraint), chain.AllStatusFlags());
});
}
[Fact]
[SkipOnPlatform(PlatformSupport.AppleCrypto, "macOS appears to just completely ignore min/max.")]
public static void NameConstraintViolation_PermittedTree_HasMin()
{
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddDnsName("example.com");
// permitted DNS name constraint for example.com with a MIN of 9.
string nameConstraints = "3015A0133011820C2E6578616D706C652E636F6D800109";
TestNameConstrainedChain(nameConstraints, builder, (bool result, X509Chain chain) => {
Assert.False(result, "chain.Build");
Assert.Equal(PlatformNameConstraints(X509ChainStatusFlags.HasNotSupportedNameConstraint), chain.AllStatusFlags());
});
}
[Fact]
[SkipOnPlatform(TestPlatforms.Windows, "Windows seems to skip over nonsense GeneralNames.")]
[SkipOnPlatform(TestPlatforms.Android, "Android will check for a match. Since the permitted name does match the subject alt name, it succeeds.")]
public static void NameConstraintViolation_InvalidGeneralNames()
{
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddEmailAddress("///");
// permitted RFC822 name constraint with GeneralName of ///.
string nameConstraints = "3009A007300581032F2F2F";
TestNameConstrainedChain(nameConstraints, builder, (bool result, X509Chain chain) => {
Assert.False(result, "chain.Build");
Assert.Equal(PlatformNameConstraints(X509ChainStatusFlags.InvalidNameConstraints), chain.AllStatusFlags());
});
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/52976", TestPlatforms.Android)]
public static void MismatchKeyIdentifiers()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
new X509Extension(
"2.5.29.14",
"0414C7AC28EFB300F46F9406ED155628A123633E556F".HexToByteArray(),
critical: false),
};
X509Extension[] endEntityExtensions = new []
{
BasicConstraintsEndEntity,
new X509Extension(
"2.5.29.35",
"30168014A84A6A63047DDDBAE6D139B7A64565EFF3A8ECA1".HexToByteArray(),
critical: false),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(rootCert);
chain.ChainPolicy.ExtraStore.Add(intermediateCert);
if (OperatingSystem.IsLinux())
{
Assert.False(chain.Build(endEntityCert), "chain.Build");
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
}
else
{
Assert.True(chain.Build(endEntityCert), "chain.Build");
Assert.Equal(3, chain.ChainElements.Count);
}
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Linux, "Not supported on Linux.")]
public static void PolicyConstraints_RequireExplicitPolicy()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
BuildPolicyConstraints(requireExplicitPolicySkipCerts: 0),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(
rootCert,
intermediateCert,
endEntityCert,
expectedFlags: PlatformPolicyConstraints(X509ChainStatusFlags.NoIssuanceChainPolicy));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void PolicyConstraints_Malformed()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
// Nonsense ContextSpecific 3.
new X509Extension("2.5.29.36", "3003830102".HexToByteArray(), critical: true),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(
rootCert,
intermediateCert,
endEntityCert,
expectedFlags: X509ChainStatusFlags.InvalidPolicyConstraints);
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Linux, "Not supported on Linux.")]
public static void PolicyConstraints_Valid()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
BuildPolicyConstraints(requireExplicitPolicySkipCerts: 0),
BuildPolicyByIdentifiers("2.23.140.1.2.1"), // CABF DV OID
};
X509Extension[] endEntityExtensions = new []
{
BasicConstraintsEndEntity,
BuildPolicyByIdentifiers("2.23.140.1.2.1"), // CABF DV OID
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(rootCert, intermediateCert, endEntityCert);
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Linux, "Not supported on Linux.")]
public static void PolicyConstraints_Mismatch()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
BuildPolicyConstraints(requireExplicitPolicySkipCerts: 0),
BuildPolicyByIdentifiers("2.23.140.1.2.1"), // CABF DV OID
};
X509Extension[] endEntityExtensions = new []
{
BasicConstraintsEndEntity,
BuildPolicyByIdentifiers("1.2.3.4"),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(
rootCert,
intermediateCert,
endEntityCert,
expectedFlags: PlatformPolicyConstraints(X509ChainStatusFlags.NoIssuanceChainPolicy));
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Linux, "Not supported on Linux.")]
public static void PolicyConstraints_AnyPolicy()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
BuildPolicyConstraints(requireExplicitPolicySkipCerts: 0),
BuildPolicyByIdentifiers("2.5.29.32.0"), // anyPolicy special OID.
};
X509Extension[] endEntityExtensions = new []
{
BasicConstraintsEndEntity,
BuildPolicyByIdentifiers("1.2.3.4"),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(rootCert, intermediateCert, endEntityCert);
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Linux, "Not supported on Linux.")]
public static void PolicyConstraints_Mapped()
{
X509Extension[] intermediateExtensions = new []
{
BasicConstraintsCA,
BuildPolicyConstraints(requireExplicitPolicySkipCerts: 0),
BuildPolicyByIdentifiers("2.23.140.1.2.1"),
BuildPolicyMappings(("2.23.140.1.2.1", "1.2.3.4")),
};
X509Extension[] endEntityExtensions = new []
{
BasicConstraintsEndEntity,
BuildPolicyByIdentifiers("1.2.3.4"),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
{
TestChain3(rootCert, intermediateCert, endEntityCert);
}
}
private static X509ChainStatusFlags PlatformBasicConstraints(X509ChainStatusFlags flags)
{
if (OperatingSystem.IsAndroid())
{
// Android always validates basic constraints as part of building a path
// so violations comes back as PartialChain with no elements.
flags = X509ChainStatusFlags.PartialChain;
}
return flags;
}
private static X509ChainStatusFlags PlatformNameConstraints(X509ChainStatusFlags flags)
{
if (PlatformDetection.UsesAppleCrypto)
{
const X509ChainStatusFlags AnyNameConstraintFlags =
X509ChainStatusFlags.HasExcludedNameConstraint |
X509ChainStatusFlags.HasNotDefinedNameConstraint |
X509ChainStatusFlags.HasNotPermittedNameConstraint |
X509ChainStatusFlags.HasNotSupportedNameConstraint |
X509ChainStatusFlags.InvalidNameConstraints;
if ((flags & AnyNameConstraintFlags) != 0)
{
flags &= ~AnyNameConstraintFlags;
flags |= X509ChainStatusFlags.InvalidNameConstraints;
}
}
else if (OperatingSystem.IsAndroid())
{
// Android always validates name constraints as part of building a path
// so violations comes back as PartialChain with no elements.
flags = X509ChainStatusFlags.PartialChain;
}
return flags;
}
private static X509ChainStatusFlags PlatformPolicyConstraints(X509ChainStatusFlags flags)
{
if (PlatformDetection.UsesAppleCrypto)
{
const X509ChainStatusFlags AnyPolicyConstraintFlags =
X509ChainStatusFlags.NoIssuanceChainPolicy;
if ((flags & AnyPolicyConstraintFlags) != 0)
{
flags &= ~AnyPolicyConstraintFlags;
flags |= X509ChainStatusFlags.InvalidPolicyConstraints;
}
}
else if (OperatingSystem.IsAndroid())
{
// Android always validates policy constraints as part of building a path
// so violations comes back as PartialChain with no elements.
flags = X509ChainStatusFlags.PartialChain;
}
return flags;
}
private static void TestNameConstrainedChain(
string intermediateNameConstraints,
SubjectAlternativeNameBuilder endEntitySanBuilder,
Action<bool, X509Chain> body,
[CallerMemberName] string testName = null)
{
X509Extension[] endEntityExtensions = new []
{
new X509BasicConstraintsExtension(
certificateAuthority: false,
hasPathLengthConstraint: false,
pathLengthConstraint: 0,
critical: true),
endEntitySanBuilder.Build(),
};
X509Extension[] intermediateExtensions = new []
{
new X509BasicConstraintsExtension(
certificateAuthority: true,
hasPathLengthConstraint: false,
pathLengthConstraint: 0,
critical: true),
new X509Extension(
"2.5.29.30",
intermediateNameConstraints.HexToByteArray(),
critical: true),
};
TestDataGenerator.MakeTestChain3(
out X509Certificate2 endEntityCert,
out X509Certificate2 intermediateCert,
out X509Certificate2 rootCert,
intermediateExtensions: intermediateExtensions,
endEntityExtensions: endEntityExtensions,
testName: testName);
using (endEntityCert)
using (intermediateCert)
using (rootCert)
using (ChainHolder chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(rootCert);
chain.ChainPolicy.ExtraStore.Add(intermediateCert);
bool result = chain.Build(endEntityCert);
body(result, chain);
}
}
private static X509Certificate2 TamperSignature(X509Certificate2 input)
{
byte[] cert = input.RawData;
cert[cert.Length - 1] ^= 0xFF;
return new X509Certificate2(cert);
}
private static X509Extension BuildPolicyConstraints(
int? requireExplicitPolicySkipCerts = null,
int? inhibitPolicyMappingSkipCerts = null)
{
// RFC 5280 4.2.1.11
// id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 }
// PolicyConstraints ::= SEQUENCE {
// requireExplicitPolicy [0] SkipCerts OPTIONAL,
// inhibitPolicyMapping [1] SkipCerts OPTIONAL }
// SkipCerts ::= INTEGER (0..MAX)
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSequence())
{
if (requireExplicitPolicySkipCerts.HasValue)
{
Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 0);
writer.WriteInteger(requireExplicitPolicySkipCerts.Value, tag);
}
if (inhibitPolicyMappingSkipCerts.HasValue)
{
Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 1);
writer.WriteInteger(inhibitPolicyMappingSkipCerts.Value, tag);
}
}
// Conforming CAs MUST mark this extension as critical.
return new X509Extension("2.5.29.36", writer.Encode(), critical: true);
}
private static X509Extension BuildPolicyByIdentifiers(params string[] policyOids)
{
// id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 }
// anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 }
// CertificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
// PolicyInformation ::= SEQUENCE {
// policyIdentifier CertPolicyId,
// policyQualifiers SEQUENCE SIZE (1..MAX) OF
// PolicyQualifierInfo OPTIONAL }