Debian Codegraph @

crt/s2n/tests/pems/intent/cert_chain_generator.py

raw symbols SCIP
1 import datetime
2 from pathlib import Path
3 from cryptography import x509
4 from cryptography.hazmat.primitives.asymmetric import ec
5 from cryptography.hazmat.primitives import hashes
6 from cryptography.hazmat.primitives import serialization
7
8
9 class ExtensionConfig:
10 def __init__(self, extension: x509.ExtensionType, critical: bool = True):
11 self.extension = extension
12 self.critical = critical
13
14
15 class CertConfig:
16 def __init__(self, extensions: [ExtensionConfig] = []):
17 self.extensions = extensions
18 self.private_key = ec.generate_private_key(ec.SECP256R1())
19
20
21 class CertChainBuilder:
22 class _CertAndKey:
23 def __init__(self, name: str, cert: x509.Certificate, private_key: ec.EllipticCurvePrivateKey):
24 self.name = name
25 self.cert = cert
26 self.private_key = private_key
27
28 class _CertChain:
29 def __init__(self, cert_chain: ["CertChainBuilder._CertAndKey"]):
30 self.cert_chain = cert_chain
31
32 def write(self, cert_dir: str):
33 assert len(self.cert_chain) > 0
34 Path(cert_dir).mkdir(exist_ok=True)
35
36 # Write each individual certificate to its own pem. This allows the trust store to be
37 # customized with specific certificates.
38 for i, cert_and_key in enumerate(self.cert_chain):
39 with open(f"{cert_dir}/{cert_and_key.name}-cert.pem", "wb") as f:
40 f.write(cert_and_key.cert.public_bytes(encoding=serialization.Encoding.PEM))
41
42 # Write the certificate chain to be sent in the TLS handshake to a pem, which can omit
43 # the root certificate.
44 with open(f"{cert_dir}/cert-chain.pem", "wb") as f:
45 cert_chain_without_root = self.cert_chain[:-1]
46 for cert_and_key in cert_chain_without_root:
47 f.write(cert_and_key.cert.public_bytes(encoding=serialization.Encoding.PEM))
48
49 # Write the leaf private key to a pem.
50 leaf = self.cert_chain[0]
51 with open(f"{cert_dir}/{leaf.name}-key.pem", "wb") as f:
52 f.write(leaf.private_key.private_bytes(
53 encoding=serialization.Encoding.PEM,
54 format=serialization.PrivateFormat.TraditionalOpenSSL,
55 encryption_algorithm=serialization.NoEncryption(),
56 ))
57
58 def __init__(self):
59 self._configs: [CertConfig] = []
60
61 def add_cert(self, config: CertConfig):
62 self._configs.append(config)
63
64 def build(self) -> _CertChain:
65 assert len(self._configs) > 0
66
67 issuer_name = self._x509_name("root")
68 issuer_key = self._configs[0].private_key
69
70 cert_chain = []
71
72 # Build the chain from the root to the leaf.
73 for i, config in enumerate(reversed(self._configs)):
74 builder = x509.CertificateBuilder()
75
76 if i == 0:
77 name = "root"
78 elif i < len(self._configs) - 1:
79 name = f"intermediate_{i}"
80 else:
81 name = "leaf"
82 subject_name = self._x509_name(name)
83 builder = builder.subject_name(subject_name)
84
85 builder = builder.issuer_name(issuer_name)
86 builder = builder.public_key(config.private_key.public_key())
87 builder = builder.serial_number(x509.random_serial_number())
88 builder = builder.not_valid_before(datetime.datetime.now(datetime.timezone.utc))
89 builder = builder.not_valid_after(
90 datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=365*100)
91 )
92
93 # Add some extensions by default, to avoid specifying them in every ExtensionBuilder.
94 builder = builder.add_extension(
95 x509.SubjectKeyIdentifier.from_public_key(config.private_key.public_key()),
96 critical=False,
97 )
98 builder = builder.add_extension(
99 x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_key.public_key()),
100 critical=False,
101 )
102 if name == "leaf":
103 builder = builder.add_extension(
104 x509.SubjectAlternativeName([x509.DNSName("localhost")]),
105 critical=False,
106 )
107
108 for extension_config in config.extensions:
109 builder = builder.add_extension(extension_config.extension, extension_config.critical)
110
111 cert_and_key = self._CertAndKey(
112 name,
113 builder.sign(issuer_key, hashes.SHA256()),
114 config.private_key,
115 )
116 # Insert at the front of the list to allow the final certificate chain to start from
117 # the leaf and end at the root.
118 cert_chain.insert(0, cert_and_key)
119
120 issuer_name = subject_name
121 issuer_key = config.private_key
122
123 return self._CertChain(cert_chain)
124
125 @staticmethod
126 def _x509_name(common_name: str):
127 return x509.Name([
128 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, "US"),
129 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, "Massachusetts"),
130 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, "Boston"),
131 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, "s2n"),
132 x509.NameAttribute(x509.NameOID.COMMON_NAME, common_name),
133 ])
134
135
136 def key_usage_kwargs(**kwargs):
137 """
138 The cryptography.x509.KeyUsage constructor takes a mandatory argument for each KeyUsage field.
139 Rather than specify each field when creating each KeyUsage extension, have each field default
140 to False, and only specify fields that will be set to True.
141 """
142 kwargs_dict = {
143 "digital_signature": False,
144 "content_commitment": False,
145 "key_encipherment": False,
146 "data_encipherment": False,
147 "key_agreement": False,
148 "key_cert_sign": False,
149 "crl_sign": False,
150 "encipher_only": False,
151 "decipher_only": False,
152 }
153 for key in kwargs:
154 assert key in kwargs_dict
155
156 kwargs_dict.update(kwargs)
157 return kwargs_dict