-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathgenerate.py
More file actions
executable file
·2270 lines (2073 loc) · 88.1 KB
/
generate.py
File metadata and controls
executable file
·2270 lines (2073 loc) · 88.1 KB
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
#!/usr/bin/env python3
"""
Generates test cases that aim to validate name constraints and other
name-related parts of webpki.
Run this script from tests/. It edits the bottom part of some .rs files and
drops testcase data into subdirectories as required.
"""
import argparse
import enum
import os
from typing import TextIO, Optional, Union, Any, Callable, Iterable, List
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, ec, ed25519, padding
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from cryptography.hazmat.backends import default_backend
from cryptography.x509.oid import NameOID
import ipaddress
import datetime
import subprocess
ROOT_PRIVATE_KEY: rsa.RSAPrivateKey = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
ROOT_PUBLIC_KEY: rsa.RSAPublicKey = ROOT_PRIVATE_KEY.public_key()
NOT_BEFORE: datetime.datetime = datetime.datetime.utcfromtimestamp(0x1FEDF00D - 30)
NOT_AFTER: datetime.datetime = datetime.datetime.utcfromtimestamp(0x1FEDF00D + 30)
ANY_PRIV_KEY = Union[
ed25519.Ed25519PrivateKey | ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey
]
ANY_PUB_KEY = Union[
ed25519.Ed25519PublicKey | ec.EllipticCurvePublicKey | rsa.RSAPublicKey
]
SIGNER = Callable[
[Any, bytes], Any
] # Note: a bit loosey-goosey here but good enough for tests.
def trim_top(file_name: str) -> TextIO:
"""
Reads `file_name`, then writes lines up to a particular comment (the "top"
of the file) back to it and returns the file object for further writing.
"""
with open(file_name, "r") as f:
top = f.readlines()
top = top[: top.index("// DO NOT EDIT BELOW: generated by tests/generate.py\n") + 1]
output = open(file_name, "w")
for line in top:
output.write(line)
return output
def key_or_generate(key: Optional[ANY_PRIV_KEY] = None) -> ANY_PRIV_KEY:
return (
key
if key is not None
else rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend(),
)
)
def write_der(path: str, content: bytes, force: bool) -> None:
# Avoid churn from regenerating existing on-disk resources unless force is enabled.
out_path = Path(path)
if out_path.exists() and not force:
return None
with out_path.open("wb") as f:
f.write(content)
def end_entity_cert(
*,
subject_name: x509.Name,
issuer_name: x509.Name,
issuer_key: Optional[ANY_PRIV_KEY] = None,
subject_key: Optional[ANY_PRIV_KEY] = None,
sans: Optional[Iterable[x509.GeneralName]] = None,
ekus: Optional[Iterable[x509.ObjectIdentifier]] = None,
serial: Optional[int] = None,
cert_dps: Optional[x509.DistributionPoint] = None,
) -> x509.Certificate:
subject_priv_key = key_or_generate(subject_key)
subject_key_pub: ANY_PUB_KEY = subject_priv_key.public_key()
ee_builder: x509.CertificateBuilder = x509.CertificateBuilder()
ee_builder = ee_builder.subject_name(subject_name)
ee_builder = ee_builder.issuer_name(issuer_name)
ee_builder = ee_builder.not_valid_before(NOT_BEFORE)
ee_builder = ee_builder.not_valid_after(NOT_AFTER)
ee_builder = ee_builder.serial_number(
x509.random_serial_number() if serial is None else serial
)
ee_builder = ee_builder.public_key(subject_key_pub)
if sans:
ee_builder = ee_builder.add_extension(
x509.SubjectAlternativeName(sans), critical=False
)
if ekus:
ee_builder = ee_builder.add_extension(
x509.ExtendedKeyUsage(ekus), critical=False
)
if cert_dps:
ee_builder = ee_builder.add_extension(
x509.CRLDistributionPoints([cert_dps]), critical=False
)
ee_builder = ee_builder.add_extension(
x509.BasicConstraints(ca=False, path_length=None),
critical=True,
)
return ee_builder.sign(
private_key=issuer_key if issuer_key is not None else ROOT_PRIVATE_KEY,
algorithm=hashes.SHA256(),
backend=default_backend(),
)
def subject_name_for_test(subject_cn: str, test_name: str) -> x509.Name:
return x509.Name(
[
x509.NameAttribute(NameOID.COMMON_NAME, subject_cn),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, test_name),
]
)
def issuer_name_for_test(test_name: str) -> x509.Name:
return x509.Name(
[
x509.NameAttribute(NameOID.COMMON_NAME, "issuer.example.com"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, test_name),
]
)
def ca_cert(
*,
subject_name: x509.Name,
subject_key: Optional[ANY_PRIV_KEY] = None,
issuer_name: Optional[x509.Name] = None,
issuer_key: Optional[ANY_PRIV_KEY] = None,
permitted_subtrees: Optional[Iterable[x509.GeneralName]] = None,
excluded_subtrees: Optional[Iterable[x509.GeneralName]] = None,
key_usage: Optional[x509.KeyUsage] = None,
cert_dps: Optional[x509.DistributionPoint] = None,
) -> x509.Certificate:
subject_priv_key = key_or_generate(subject_key)
subject_key_pub: ANY_PUB_KEY = subject_priv_key.public_key()
ca_builder: x509.CertificateBuilder = x509.CertificateBuilder()
ca_builder = ca_builder.subject_name(subject_name)
ca_builder = ca_builder.issuer_name(issuer_name if issuer_name else subject_name)
ca_builder = ca_builder.not_valid_before(NOT_BEFORE)
ca_builder = ca_builder.not_valid_after(NOT_AFTER)
ca_builder = ca_builder.serial_number(x509.random_serial_number())
ca_builder = ca_builder.public_key(subject_key_pub)
ca_builder = ca_builder.add_extension(
x509.BasicConstraints(ca=True, path_length=None),
critical=True,
)
if permitted_subtrees is not None or excluded_subtrees is not None:
ca_builder = ca_builder.add_extension(
x509.NameConstraints(permitted_subtrees, excluded_subtrees), critical=True
)
if key_usage is not None:
ca_builder = ca_builder.add_extension(
key_usage,
critical=True,
)
if cert_dps:
ca_builder = ca_builder.add_extension(
x509.CRLDistributionPoints([cert_dps]), critical=False
)
return ca_builder.sign(
private_key=issuer_key if issuer_key else subject_priv_key,
algorithm=hashes.SHA256(),
backend=default_backend(),
)
def generate_tls_server_cert_test(
output: TextIO,
test_name: str,
expected_error: Optional[str] = None,
subject_common_name: Optional[str] = None,
extra_subject_names: Optional[List[x509.NameAttribute]] = None,
valid_names: Optional[List[str]] = None,
invalid_names: Optional[List[str]] = None,
sans: Optional[Iterable[x509.GeneralName]] = None,
permitted_subtrees: Optional[Iterable[x509.GeneralName]] = None,
excluded_subtrees: Optional[Iterable[x509.GeneralName]] = None,
force: bool = False,
) -> None:
"""
Generate a test case, writing a rust '#[test]' function into
tls_server_certs.rs, and writing supporting files into the current
directory.
- `test_name`: name of the test, must be a rust identifier.
- `expected_error`: item in `webpki::Error` enum, expected error from
webpki `verify_for_usage()` function. Leave absent to
expect success.
- `subject_common_name`: optional string to put in end-entity certificate
subject common name.
- `extra_subject_names`: optional sequence of `x509.NameAttributes` to add
to end-entity certificate subject.
- `valid_names`: optional sequence of valid names that the end-entity
certificate is expected to pass `verify_is_valid_for_subject_name` for.
- `invalid_names`: optional sequence of invalid names that the end-entity
certificate is expected to fail `verify_is_valid_for_subject_name` with
`CertNotValidForName`.
- `sans`: optional sequence of `x509.GeneralName`s that are the contents of
the subjectAltNames extension. If empty or not provided the end-entity
certificate does not have a subjectAltName extension.
- `permitted_subtrees`: optional sequence of `x509.GeneralName`s that are
the `permittedSubtrees` contents of the `nameConstraints` extension.
If this and `excluded_subtrees` are empty/absent then the end-entity
certificate does not have a `nameConstraints` extension.
- `excluded_subtrees`: optional sequence of `x509.GeneralName`s that are
the `excludedSubtrees` contents of the `nameConstraints` extension.
If this and `permitted_subtrees` are both empty/absent then the
end-entity certificate does not have a `nameConstraints` extension.
"""
if invalid_names is None:
invalid_names = []
if valid_names is None:
valid_names = []
if extra_subject_names is None:
extra_subject_names = []
issuer_name: x509.Name = issuer_name_for_test(test_name)
# end-entity
ee_subject = x509.Name(
(
[x509.NameAttribute(NameOID.COMMON_NAME, subject_common_name)]
if subject_common_name
else []
)
+ [x509.NameAttribute(NameOID.ORGANIZATION_NAME, test_name)]
+ extra_subject_names
)
ee_certificate: x509.Certificate = end_entity_cert(
subject_name=ee_subject,
issuer_name=issuer_name,
sans=sans,
)
output_dir: str = "tls_server_certs"
ee_cert_path: str = os.path.join(output_dir, f"{test_name}.ee.der")
ca_cert_path: str = os.path.join(output_dir, f"{test_name}.ca.der")
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
write_der(ee_cert_path, ee_certificate.public_bytes(Encoding.DER), force)
# issuer
ca: x509.Certificate = ca_cert(
subject_name=issuer_name,
subject_key=ROOT_PRIVATE_KEY,
permitted_subtrees=permitted_subtrees,
excluded_subtrees=excluded_subtrees,
)
write_der(ca_cert_path, ca.public_bytes(Encoding.DER), force)
expected: str = ""
if expected_error is None:
expected = "Ok(())"
else:
expected = "Err(webpki::Error::" + expected_error + ")"
valid_names_str: str = ", ".join('"' + name + '"' for name in valid_names)
invalid_names_str: str = ", ".join('"' + name + '"' for name in invalid_names)
presented_names_str: str = ""
for san in sans if sans is not None else []:
if presented_names_str:
presented_names_str += ", "
if isinstance(san, x509.DNSName):
presented_names_str += f'"DnsName(\\"{san.value}\\")"'
elif isinstance(san, x509.IPAddress):
presented_names_str += f'"IpAddress({san.value})"'
ip_addr_sans = all(isinstance(san, x509.IPAddress) for san in (sans or []))
print(
"""
#[test]
fn %(test_name)s() {
let ee = include_bytes!("%(ee_cert_path)s");
let ca = include_bytes!("%(ca_cert_path)s");
assert_eq!(
check_cert(ee, ca, &[%(valid_names_str)s], &[%(invalid_names_str)s], &[%(presented_names_str)s]),
%(expected)s
);
}"""
% locals(),
file=output,
)
def tls_server_certs(force: bool) -> None:
with trim_top("tls_server_certs.rs") as output:
generate_tls_server_cert_test(
output,
"no_name_constraints",
subject_common_name="subject.example.com",
valid_names=["dns.example.com"],
invalid_names=["subject.example.com"],
sans=[x509.DNSName("dns.example.com")],
)
generate_tls_server_cert_test(
output,
"additional_dns_labels",
subject_common_name="subject.example.com",
valid_names=["host1.example.com", "host2.example.com"],
invalid_names=["subject.example.com"],
sans=[x509.DNSName("host1.example.com"), x509.DNSName("host2.example.com")],
permitted_subtrees=[x509.DNSName(".example.com")],
)
generate_tls_server_cert_test(
output,
"disallow_dns_san",
expected_error="NameConstraintViolation",
sans=[x509.DNSName("disallowed.example.com")],
excluded_subtrees=[x509.DNSName("disallowed.example.com")],
)
generate_tls_server_cert_test(
output,
"allow_subject_common_name",
subject_common_name="allowed.example.com",
invalid_names=["allowed.example.com"],
permitted_subtrees=[x509.DNSName("allowed.example.com")],
)
generate_tls_server_cert_test(
output,
"allow_dns_san",
valid_names=["allowed.example.com"],
sans=[x509.DNSName("allowed.example.com")],
permitted_subtrees=[x509.DNSName("allowed.example.com")],
)
generate_tls_server_cert_test(
output,
"allow_dns_san_and_subject_common_name",
valid_names=["allowed-san.example.com"],
invalid_names=["allowed-cn.example.com"],
sans=[x509.DNSName("allowed-san.example.com")],
subject_common_name="allowed-cn.example.com",
permitted_subtrees=[
x509.DNSName("allowed-san.example.com"),
x509.DNSName("allowed-cn.example.com"),
],
)
generate_tls_server_cert_test(
output,
"disallow_dns_san_and_allow_subject_common_name",
expected_error="NameConstraintViolation",
sans=[
x509.DNSName("allowed-san.example.com"),
x509.DNSName("disallowed-san.example.com"),
],
subject_common_name="allowed-cn.example.com",
permitted_subtrees=[
x509.DNSName("allowed-san.example.com"),
x509.DNSName("allowed-cn.example.com"),
],
excluded_subtrees=[x509.DNSName("disallowed-san.example.com")],
)
# XXX: ideally this test case would be a negative one, because the name constraints
# should apply to the subject name.
# however, because we don't look at email addresses in subjects, it is accepted.
generate_tls_server_cert_test(
output,
"we_incorrectly_ignore_name_constraints_on_name_in_subject",
extra_subject_names=[
x509.NameAttribute(NameOID.EMAIL_ADDRESS, "joe@notexample.com")
],
permitted_subtrees=[x509.RFC822Name("example.com")],
)
# this does work, however, because we process all SANs
generate_tls_server_cert_test(
output,
"reject_constraints_on_unimplemented_names",
expected_error="NameConstraintViolation",
sans=[x509.RFC822Name("joe@example.com")],
permitted_subtrees=[x509.RFC822Name("example.com")],
)
# RFC5280 4.2.1.10:
# "If no name of the type is in the certificate,
# the certificate is acceptable."
generate_tls_server_cert_test(
output,
"we_ignore_constraints_on_names_that_do_not_appear_in_cert",
sans=[x509.DNSName("notexample.com")],
valid_names=["notexample.com"],
invalid_names=["example.com"],
permitted_subtrees=[x509.RFC822Name("example.com")],
)
generate_tls_server_cert_test(
output,
"wildcard_san_accepted_if_in_subtree",
sans=[x509.DNSName("*.example.com")],
valid_names=["bob.example.com", "jane.example.com"],
invalid_names=["example.com", "uh.oh.example.com"],
permitted_subtrees=[x509.DNSName("example.com")],
)
generate_tls_server_cert_test(
output,
"wildcard_san_rejected_if_in_excluded_subtree",
expected_error="NameConstraintViolation",
sans=[x509.DNSName("*.example.com")],
excluded_subtrees=[x509.DNSName("example.com")],
)
generate_tls_server_cert_test(
output,
"ip4_address_san_rejected_if_in_excluded_subtree",
expected_error="NameConstraintViolation",
sans=[x509.IPAddress(ipaddress.ip_address("12.34.56.78"))],
excluded_subtrees=[x509.IPAddress(ipaddress.ip_network("12.34.56.0/24"))],
)
generate_tls_server_cert_test(
output,
"ip4_address_san_allowed_if_outside_excluded_subtree",
valid_names=["12.34.56.78"],
sans=[x509.IPAddress(ipaddress.ip_address("12.34.56.78"))],
excluded_subtrees=[x509.IPAddress(ipaddress.ip_network("12.34.56.252/30"))],
)
sparse_net_addr = ipaddress.ip_network("12.34.56.78/24", strict=False)
sparse_net_addr.netmask = ipaddress.ip_address("255.255.255.1")
generate_tls_server_cert_test(
output,
"ip4_address_san_rejected_if_excluded_is_sparse_cidr_mask",
expected_error="InvalidNetworkMaskConstraint",
sans=[
# inside excluded network, if netmask is allowed to be sparse
x509.IPAddress(ipaddress.ip_address("12.34.56.79")),
],
excluded_subtrees=[x509.IPAddress(sparse_net_addr)],
)
generate_tls_server_cert_test(
output,
"ip4_address_san_allowed",
valid_names=["12.34.56.78"],
invalid_names=[
"12.34.56.77",
"12.34.56.79",
"0000:0000:0000:0000:0000:ffff:0c22:384e",
],
sans=[x509.IPAddress(ipaddress.ip_address("12.34.56.78"))],
permitted_subtrees=[x509.IPAddress(ipaddress.ip_network("12.34.56.0/24"))],
)
generate_tls_server_cert_test(
output,
"ip6_address_san_rejected_if_in_excluded_subtree",
expected_error="NameConstraintViolation",
sans=[x509.IPAddress(ipaddress.ip_address("2001:db8::1"))],
excluded_subtrees=[x509.IPAddress(ipaddress.ip_network("2001:db8::/48"))],
)
generate_tls_server_cert_test(
output,
"ip6_address_san_allowed_if_outside_excluded_subtree",
valid_names=["2001:0db9:0000:0000:0000:0000:0000:0001"],
sans=[x509.IPAddress(ipaddress.ip_address("2001:db9::1"))],
excluded_subtrees=[x509.IPAddress(ipaddress.ip_network("2001:db8::/48"))],
)
generate_tls_server_cert_test(
output,
"ip6_address_san_allowed",
valid_names=["2001:0db9:0000:0000:0000:0000:0000:0001"],
invalid_names=["12.34.56.78"],
sans=[x509.IPAddress(ipaddress.ip_address("2001:db9::1"))],
permitted_subtrees=[x509.IPAddress(ipaddress.ip_network("2001:db9::/48"))],
)
generate_tls_server_cert_test(
output,
"ip46_mixed_address_san_allowed",
valid_names=["12.34.56.78", "2001:0db9:0000:0000:0000:0000:0000:0001"],
invalid_names=[
"12.34.56.77",
"12.34.56.79",
"0000:0000:0000:0000:0000:ffff:0c22:384e",
],
sans=[
x509.IPAddress(ipaddress.ip_address("12.34.56.78")),
x509.IPAddress(ipaddress.ip_address("2001:db9::1")),
],
permitted_subtrees=[
x509.IPAddress(ipaddress.ip_network("12.34.56.0/24")),
x509.IPAddress(ipaddress.ip_network("2001:db9::/48")),
],
)
generate_tls_server_cert_test(
output,
"permit_directory_name_not_implemented",
expected_error="NameConstraintViolation",
permitted_subtrees=[
x509.DirectoryName(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "CN")])
)
],
)
generate_tls_server_cert_test(
output,
"exclude_directory_name_not_implemented",
expected_error="NameConstraintViolation",
excluded_subtrees=[
x509.DirectoryName(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "CN")])
)
],
)
generate_tls_server_cert_test(
output,
"invalid_dns_name_matching",
valid_names=["dns.example.com"],
subject_common_name="subject.example.com",
sans=[
x509.DNSName("{invalid}.example.com"),
x509.DNSName("dns.example.com"),
],
)
def signatures(force: bool) -> None:
rsa_pub_exponent: int = 0x10001
backend: Any = default_backend()
all_key_types: dict[str, ANY_PRIV_KEY] = {
"ed25519": ed25519.Ed25519PrivateKey.generate(),
"ecdsa_p256": ec.generate_private_key(ec.SECP256R1(), backend),
"ecdsa_p384": ec.generate_private_key(ec.SECP384R1(), backend),
"ecdsa_p521": ec.generate_private_key(ec.SECP521R1(), backend),
"rsa_1024_not_supported": rsa.generate_private_key(
rsa_pub_exponent, 1024, backend
),
"rsa_2048": rsa.generate_private_key(rsa_pub_exponent, 2048, backend),
"rsa_3072": rsa.generate_private_key(rsa_pub_exponent, 3072, backend),
"rsa_4096": rsa.generate_private_key(rsa_pub_exponent, 4096, backend),
}
feature_gates = {
"ECDSA_P521_SHA256": 'all(not(feature = "ring"), feature = "aws-lc-rs")',
"ECDSA_P521_SHA384": 'all(not(feature = "ring"), feature = "aws-lc-rs")',
"ECDSA_P521_SHA512": 'all(not(feature = "ring"), feature = "aws-lc-rs")',
}
rsa_types: list[str] = [
"RSA_PKCS1_2048_8192_SHA256",
"RSA_PKCS1_2048_8192_SHA384",
"RSA_PKCS1_2048_8192_SHA512",
"RSA_PSS_2048_8192_SHA256_LEGACY_KEY",
"RSA_PSS_2048_8192_SHA384_LEGACY_KEY",
"RSA_PSS_2048_8192_SHA512_LEGACY_KEY",
]
webpki_algs: dict[str, Iterable[str]] = {
"ed25519": ["ED25519"],
"ecdsa_p256": ["ECDSA_P256_SHA384", "ECDSA_P256_SHA256"],
"ecdsa_p384": ["ECDSA_P384_SHA384", "ECDSA_P384_SHA256"],
"ecdsa_p521": ["ECDSA_P521_SHA512", "ECDSA_P521_SHA256", "ECDSA_P521_SHA384"],
"rsa_2048": rsa_types,
"rsa_3072": rsa_types + ["RSA_PKCS1_3072_8192_SHA384"],
"rsa_4096": rsa_types + ["RSA_PKCS1_3072_8192_SHA384"],
}
pss_sha256: padding.PSS = padding.PSS(
mgf=padding.MGF1(hashes.SHA256()), salt_length=32
)
pss_sha384: padding.PSS = padding.PSS(
mgf=padding.MGF1(hashes.SHA384()), salt_length=48
)
pss_sha512: padding.PSS = padding.PSS(
mgf=padding.MGF1(hashes.SHA512()), salt_length=64
)
how_to_sign: dict[str, SIGNER] = {
"ED25519": lambda key, message: key.sign(message),
"ECDSA_P256_SHA256": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA256())
),
"ECDSA_P256_SHA384": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA384())
),
"ECDSA_P384_SHA256": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA256())
),
"ECDSA_P384_SHA384": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA384())
),
"ECDSA_P521_SHA256": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA256())
),
"ECDSA_P521_SHA384": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA384())
),
"ECDSA_P521_SHA512": lambda key, message: key.sign(
message, ec.ECDSA(hashes.SHA512())
),
"RSA_PKCS1_2048_8192_SHA256": lambda key, message: key.sign(
message, padding.PKCS1v15(), hashes.SHA256()
),
"RSA_PKCS1_2048_8192_SHA384": lambda key, message: key.sign(
message, padding.PKCS1v15(), hashes.SHA384()
),
"RSA_PKCS1_2048_8192_SHA512": lambda key, message: key.sign(
message, padding.PKCS1v15(), hashes.SHA512()
),
"RSA_PKCS1_3072_8192_SHA384": lambda key, message: key.sign(
message, padding.PKCS1v15(), hashes.SHA384()
),
"RSA_PSS_2048_8192_SHA256_LEGACY_KEY": lambda key, message: key.sign(
message, pss_sha256, hashes.SHA256()
),
"RSA_PSS_2048_8192_SHA384_LEGACY_KEY": lambda key, message: key.sign(
message, pss_sha384, hashes.SHA384()
),
"RSA_PSS_2048_8192_SHA512_LEGACY_KEY": lambda key, message: key.sign(
message, pss_sha512, hashes.SHA512()
),
}
output_dir: str = "signatures"
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
message = b"hello world!"
message_path: str = os.path.join(output_dir, "message.bin")
write_der(message_path, message, force)
def _cert_path(cert_type: str) -> str:
return os.path.join(output_dir, f"{cert_type}.ee.der")
def _rpk_path(rpk_type: str) -> str:
return os.path.join(output_dir, f"{rpk_type}.spki.der")
for name, private_key in all_key_types.items():
ee_subject = x509.Name(
[x509.NameAttribute(NameOID.ORGANIZATION_NAME, name + " test")]
)
issuer_subject = x509.Name(
[x509.NameAttribute(NameOID.ORGANIZATION_NAME, name + " issuer")]
)
certificate: x509.Certificate = end_entity_cert(
subject_name=ee_subject,
subject_key=private_key,
issuer_name=issuer_subject,
)
rpk_pub_key = private_key.public_key().public_bytes(
Encoding.DER, PublicFormat.SubjectPublicKeyInfo
)
write_der(_rpk_path(name), rpk_pub_key, force)
write_der(_cert_path(name), certificate.public_bytes(Encoding.DER), force)
def _test(
test_name: str, cert_type: str, algorithm: str, signature: bytes, expected: str
) -> None:
nonlocal message_path # noqa: F824
cert_path: str = _cert_path(cert_type)
rpk_path: str = _rpk_path(cert_type)
lower_test_name: str = test_name.lower()
sig_path: str = os.path.join(output_dir, f"{lower_test_name}.sig.bin")
write_der(sig_path, signature, force)
feature_gate: str = feature_gates.get(algorithm, "")
if feature_gate:
feature_gate = f"#[cfg({feature_gate})]\n"
print(
"""
#[test]
%(feature_gate)sfn %(lower_test_name)s() {
let ee = include_bytes!("%(cert_path)s");
let message = include_bytes!("%(message_path)s");
let signature = include_bytes!("%(sig_path)s");
assert_eq!(
check_sig(ee, %(algorithm)s, message, signature),
%(expected)s
);
}"""
% locals(),
file=output,
)
print(
"""
#[test]
%(feature_gate)sfn %(lower_test_name)s_rpk() {
let rpk = include_bytes!("%(rpk_path)s");
let message = include_bytes!("%(message_path)s");
let signature = include_bytes!("%(sig_path)s");
assert_eq!(
check_sig_rpk(rpk, %(algorithm)s, message, signature),
%(expected)s
);
}"""
% locals(),
file=output,
)
def good_signature(
test_name: str, cert_type: str, algorithm: str, signer: SIGNER
) -> None:
signature: bytes = signer(all_key_types[cert_type], message)
_test(test_name, cert_type, algorithm, signature, expected="Ok(())")
def good_signature_but_rejected(
test_name: str, cert_type: str, algorithm: str, signer: SIGNER
) -> None:
signature: bytes = signer(all_key_types[cert_type], message)
_test(
test_name,
cert_type,
algorithm,
signature,
expected="Err(webpki::Error::InvalidSignatureForPublicKey)",
)
def bad_signature(
test_name: str, cert_type: str, algorithm: str, signer: SIGNER
) -> None:
signature: bytes = signer(all_key_types[cert_type], message + b"?")
_test(
test_name,
cert_type,
algorithm,
signature,
expected="Err(webpki::Error::InvalidSignatureForPublicKey)",
)
def bad_algorithms_for_key(
test_name: str, cert_type: str, unusable_algs: set[str]
) -> None:
cert_path: str = _cert_path(cert_type)
test_name_lower: str = test_name.lower()
unusable_algs_str: str = ", ".join(alg for alg in sorted(unusable_algs))
print(
"""
#[test]
fn %(test_name_lower)s() {
let ee = include_bytes!("%(cert_path)s");
for algorithm in &[ %(unusable_algs_str)s ] {
assert_eq!(
check_sig(ee, *algorithm, b"", b""),
Err(webpki::Error::UnsupportedSignatureAlgorithmForPublicKey)
);
}
}"""
% locals(),
file=output,
)
with trim_top("signatures.rs") as output:
# compute all webpki algorithms covered by these tests
all_webpki_algs: set[str] = set(
[item for algs in webpki_algs.values() for item in algs]
)
for type, algs in webpki_algs.items():
for alg in algs:
signer: SIGNER = how_to_sign[alg]
good_signature(
type + "_key_and_" + alg + "_good_signature",
cert_type=type,
algorithm=alg,
signer=signer,
)
bad_signature(
type + "_key_and_" + alg + "_detects_bad_signature",
cert_type=type,
algorithm=alg,
signer=signer,
)
unusable_algs = set(all_webpki_algs)
for alg in algs:
unusable_algs.remove(alg)
# special case: tested separately below
if type == "rsa_2048":
unusable_algs.remove("RSA_PKCS1_3072_8192_SHA384")
unusable_algs = {
(
"#[cfg(%s)] %s" % (feature_gates[alg], alg)
if alg in feature_gates
else alg
)
for alg in unusable_algs
}
bad_algorithms_for_key(
type + "_key_rejected_by_other_algorithms",
cert_type=type,
unusable_algs=unusable_algs,
)
good_signature_but_rejected(
"rsa_2048_key_rejected_by_RSA_PKCS1_3072_8192_SHA384",
cert_type="rsa_2048",
algorithm="RSA_PKCS1_3072_8192_SHA384",
signer=signer,
)
def client_auth_revocation(force: bool) -> None:
output_dir: str = "client_auth_revocation"
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
# KeyUsage for a CA that sets crl_sign.
crl_sign_ku = x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=True, # NB: crl_sign set.
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
)
# KeyUsage for a CA that omits crl_sign.
no_crl_sign_ku = x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=False, # NB: no crl_sign.
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
)
# Cert CRL distribution point. Contains at least one URI full name matching the valid_crl_idp.
valid_cert_crl_dp = x509.DistributionPoint(
full_name=[
x509.DNSName("example.com"),
x509.UniformResourceIdentifier("http://example.com/another.crl"),
x509.UniformResourceIdentifier("http://example.com/valid.crl"),
],
crl_issuer=None,
relative_name=None,
reasons=None,
)
# CRL issuing distribution point, contains at least one URI full name matching the valid_cert_crl_dp.
valid_crl_idp = x509.IssuingDistributionPoint(
full_name=[
x509.UniformResourceIdentifier("http://example.com/yet.another.crl"),
x509.UniformResourceIdentifier("http://example.com/valid.crl"),
],
indirect_crl=False,
only_contains_user_certs=False,
only_contains_ca_certs=False,
only_contains_attribute_certs=False,
only_some_reasons=None,
relative_name=None,
)
class ChainDepth(enum.Enum):
END_ENTITY = enum.auto()
CHAIN = enum.auto()
class StatusRequirement(enum.Enum):
ALLOW_UNKNOWN = enum.auto()
FORBID_UNKNOWN = enum.auto()
class ExpirationPolicy(enum.Enum):
ENFORCE = enum.auto()
IGNORE = enum.auto()
def _chain(
*,
chain_name: str,
key_usage: Optional[x509.KeyUsage],
cert_dps: Optional[x509.DistributionPoint],
) -> list[tuple[x509.Certificate, str, ANY_PRIV_KEY]]:
"""
Generate a short test certificate chain:
ee -> intermediate -> root.
:param chain_name: the name of the certificate chain. Used to generate subject/issuer names and to
choose the filename to write DER contents to disk.
:param key_usage: the KeyUsage to include in the issuer certificates (both the intermediate and the root).
:param cert_dps: an optional CRL distribution point to include in each certificate.
:return: Return a list comprising the chain starting from the end entity and ending at the root trust anchor.
Each entry in the list is a tuple of three values: the x509.Certificate object, the path the DER encoding
was written to, and lastly the corresponding private key.
"""
ee_subj: x509.Name = subject_name_for_test("test.example.com", chain_name)
int_a_subj: x509.Name = issuer_name_for_test(f"int.a.{chain_name}")
int_b_subj: x509.Name = issuer_name_for_test(f"int.b.{chain_name}")
ca_subj: x509.Name = issuer_name_for_test(f"ca.{chain_name}")
ee_key: ec.EllipticCurvePrivateKey = ec.generate_private_key(
ec.SECP256R1(), default_backend()
)
int_a_key: ec.EllipticCurvePrivateKey = ec.generate_private_key(
ec.SECP256R1(), default_backend()
)
int_b_key: ec.EllipticCurvePrivateKey = ec.generate_private_key(
ec.SECP256R1(), default_backend()
)
root_key: ec.EllipticCurvePrivateKey = ec.generate_private_key(
ec.SECP256R1(), default_backend()
)
# EE cert issued by intermediate.
ee_cert: x509.Certificate = end_entity_cert(
subject_name=ee_subj,
issuer_name=int_a_subj,
issuer_key=int_a_key,
cert_dps=cert_dps,
)
ee_cert_path: str = os.path.join(output_dir, f"{chain_name}.ee.der")
write_der(ee_cert_path, ee_cert.public_bytes(Encoding.DER), force)
# Second EE cert issued by intermediate, with top-bit set in serial.
ee_cert_topbit: x509.Certificate = end_entity_cert(
subject_name=ee_subj,
issuer_name=int_a_subj,
issuer_key=int_a_key,
serial=0x80DEADBEEFF00D,
cert_dps=cert_dps,
)
ee_cert_topbit_path: str = os.path.join(
output_dir, f"{chain_name}.topbit.ee.der"
)
write_der(ee_cert_topbit_path, ee_cert_topbit.public_bytes(Encoding.DER), force)
# intermediate a cert issued by intermediate b.
int_a_cert: x509.Certificate = ca_cert(
subject_name=int_a_subj,
subject_key=int_a_key,
issuer_name=int_b_subj,
issuer_key=int_b_key,
key_usage=key_usage,
cert_dps=cert_dps,
)
int_a_cert_path: str = os.path.join(output_dir, f"{chain_name}.int.a.ca.der")
write_der(int_a_cert_path, int_a_cert.public_bytes(Encoding.DER), force)
# intermediate b cert issued by root cert.
int_b_cert: x509.Certificate = ca_cert(
subject_name=int_b_subj,
subject_key=int_b_key,
issuer_name=ca_subj,
issuer_key=root_key,
key_usage=key_usage,
cert_dps=cert_dps,
)
int_b_cert_path: str = os.path.join(output_dir, f"{chain_name}.int.b.ca.der")
write_der(int_b_cert_path, int_b_cert.public_bytes(Encoding.DER), force)
# root cert issued by itself.
root_cert: x509.Certificate = ca_cert(
subject_name=ca_subj,
subject_key=root_key,
key_usage=key_usage,
cert_dps=cert_dps,
)
root_cert_path: str = os.path.join(output_dir, f"{chain_name}.root.ca.der")
write_der(root_cert_path, root_cert.public_bytes(Encoding.DER), force)