Debian Codegraph @

Lib/test/certdata/make_ssl_certs.py

raw
1 """Make the custom certificate and private key files used by test_ssl
2 and friends."""
3
4 import argparse
5 import os
6 import pprint
7 import shutil
8 import tempfile
9 from subprocess import *
10
11 startdate = "20180829142316Z"
12 enddate_default = "25251028142316Z"
13 days_default = "140000"
14
15 req_template = """
16 [ default ]
17 base_url = http://testca.pythontest.net/testca
18
19 [req]
20 distinguished_name = req_distinguished_name
21 prompt = no
22
23 [req_distinguished_name]
24 C = XY
25 L = Castle Anthrax
26 O = Python Software Foundation
27 CN = {hostname}
28
29 [req_x509_extensions_nosan]
30
31 [req_x509_extensions_simple]
32 subjectAltName = @san
33
34 [req_x509_extensions_full]
35 subjectAltName = @san
36 keyUsage = critical,keyEncipherment,digitalSignature
37 extendedKeyUsage = serverAuth,clientAuth
38 basicConstraints = critical,CA:false
39 subjectKeyIdentifier = hash
40 authorityKeyIdentifier = keyid:always,issuer:always
41 authorityInfoAccess = @issuer_ocsp_info
42 crlDistributionPoints = @crl_info
43
44 [ issuer_ocsp_info ]
45 caIssuers;URI.0 = $base_url/pycacert.cer
46 OCSP;URI.0 = $base_url/ocsp/
47
48 [ crl_info ]
49 URI.0 = $base_url/revocation.crl
50
51 [san]
52 DNS.1 = {hostname}
53 {extra_san}
54
55 [dir_sect]
56 C = XY
57 L = Castle Anthrax
58 O = Python Software Foundation
59 CN = dirname example
60
61 [princ_name]
62 realm = EXP:0, GeneralString:KERBEROS.REALM
63 principal_name = EXP:1, SEQUENCE:principal_seq
64
65 [principal_seq]
66 name_type = EXP:0, INTEGER:1
67 name_string = EXP:1, SEQUENCE:principals
68
69 [principals]
70 princ1 = GeneralString:username
71
72 [ ca ]
73 default_ca = CA_default
74
75 [ CA_default ]
76 dir = cadir
77 database = $dir/index.txt
78 crlnumber = $dir/crl.txt
79 default_md = sha256
80 startdate = {startdate}
81 default_startdate = {startdate}
82 enddate = {enddate}
83 default_enddate = {enddate}
84 default_days = {days}
85 default_crl_days = {days}
86 certificate = pycacert.pem
87 private_key = pycakey.pem
88 serial = $dir/serial
89 RANDFILE = $dir/.rand
90 policy = policy_match
91
92 [ policy_match ]
93 countryName = match
94 stateOrProvinceName = optional
95 organizationName = match
96 organizationalUnitName = optional
97 commonName = supplied
98 emailAddress = optional
99
100 [ policy_anything ]
101 countryName = optional
102 stateOrProvinceName = optional
103 localityName = optional
104 organizationName = optional
105 organizationalUnitName = optional
106 commonName = supplied
107 emailAddress = optional
108
109
110 [ v3_ca ]
111
112 subjectKeyIdentifier=hash
113 authorityKeyIdentifier=keyid:always,issuer
114 basicConstraints = critical, CA:true
115 keyUsage = critical, digitalSignature, keyCertSign, cRLSign
116
117 """
118
119 here = os.path.abspath(os.path.dirname(__file__))
120
121
122 def make_cert_key(cmdlineargs, hostname, sign=False, extra_san='',
123 ext='req_x509_extensions_full', key='rsa:3072'):
124 print("creating cert for " + hostname)
125 tempnames = []
126 for i in range(3):
127 with tempfile.NamedTemporaryFile(delete=False) as f:
128 tempnames.append(f.name)
129 req_file, cert_file, key_file = tempnames
130 try:
131 req = req_template.format(
132 hostname=hostname,
133 extra_san=extra_san,
134 startdate=startdate,
135 enddate=cmdlineargs.enddate,
136 days=cmdlineargs.days
137 )
138 with open(req_file, 'w') as f:
139 f.write(req)
140 args = ['req', '-new', '-nodes', '-days', cmdlineargs.days,
141 '-newkey', key, '-keyout', key_file,
142 '-config', req_file]
143 if sign:
144 with tempfile.NamedTemporaryFile(delete=False) as f:
145 tempnames.append(f.name)
146 reqfile = f.name
147 args += ['-out', reqfile ]
148
149 else:
150 args += ['-extensions', ext, '-x509', '-out', cert_file ]
151 check_call(['openssl'] + args)
152
153 if sign:
154 args = [
155 'ca',
156 '-config', req_file,
157 '-extensions', ext,
158 '-out', cert_file,
159 '-outdir', 'cadir',
160 '-policy', 'policy_anything',
161 '-batch', '-infiles', reqfile
162 ]
163 check_call(['openssl'] + args)
164
165
166 with open(cert_file, 'r') as f:
167 cert = f.read()
168 with open(key_file, 'r') as f:
169 key = f.read()
170 return cert, key
171 finally:
172 for name in tempnames:
173 os.remove(name)
174
175 TMP_CADIR = 'cadir'
176
177 def unmake_ca():
178 shutil.rmtree(TMP_CADIR)
179
180 def make_ca(cmdlineargs):
181 os.mkdir(TMP_CADIR)
182 with open(os.path.join('cadir','index.txt'),'a+') as f:
183 pass # empty file
184 with open(os.path.join('cadir','crl.txt'),'a+') as f:
185 f.write("00")
186 with open(os.path.join('cadir','index.txt.attr'),'w+') as f:
187 f.write('unique_subject = no')
188 # random start value for serial numbers
189 with open(os.path.join('cadir','serial'), 'w') as f:
190 f.write('CB2D80995A69525B\n')
191
192 with tempfile.NamedTemporaryFile("w") as t:
193 req = req_template.format(
194 hostname='our-ca-server',
195 extra_san='',
196 startdate=startdate,
197 enddate=cmdlineargs.enddate,
198 days=cmdlineargs.days
199 )
200 t.write(req)
201 t.flush()
202 with tempfile.NamedTemporaryFile() as f:
203 args = ['req', '-config', t.name, '-new',
204 '-nodes',
205 '-newkey', 'rsa:3072',
206 '-keyout', 'pycakey.pem',
207 '-out', f.name,
208 '-subj', '/C=XY/L=Castle Anthrax/O=Python Software Foundation CA/CN=our-ca-server']
209 check_call(['openssl'] + args)
210 args = ['ca', '-config', t.name,
211 '-out', 'pycacert.pem', '-batch', '-outdir', TMP_CADIR,
212 '-keyfile', 'pycakey.pem',
213 '-selfsign', '-extensions', 'v3_ca', '-infiles', f.name ]
214 check_call(['openssl'] + args)
215 args = ['ca', '-config', t.name, '-gencrl', '-out', 'revocation.crl']
216 check_call(['openssl'] + args)
217
218 # capath hashes depend on subject!
219 check_call([
220 'openssl', 'x509', '-in', 'pycacert.pem', '-out', 'capath/ceff1710.0'
221 ])
222 shutil.copy('capath/ceff1710.0', 'capath/b1930218.0')
223
224
225 def write_cert_reference(path):
226 import _ssl
227 refdata = pprint.pformat(_ssl._test_decode_cert(path))
228 print(refdata)
229 with open(path + '.reference', 'w') as f:
230 print(refdata, file=f)
231
232
233 if __name__ == '__main__':
234 parser = argparse.ArgumentParser(description='Make the custom certificate and private key files used by test_ssl and friends.')
235 parser.add_argument('--days', default=days_default)
236 parser.add_argument('--enddate', default=enddate_default)
237 cmdlineargs = parser.parse_args()
238
239 os.chdir(here)
240 cert, key = make_cert_key(cmdlineargs, 'localhost', ext='req_x509_extensions_simple')
241 with open('ssl_cert.pem', 'w') as f:
242 f.write(cert)
243 with open('ssl_key.pem', 'w') as f:
244 f.write(key)
245 print("password protecting ssl_key.pem in ssl_key.passwd.pem")
246 check_call(['openssl','pkey','-in','ssl_key.pem','-out','ssl_key.passwd.pem','-aes256','-passout','pass:somepass'])
247 check_call(['openssl','pkey','-in','ssl_key.pem','-out','keycert.passwd.pem','-aes256','-passout','pass:somepass'])
248
249 with open('keycert.pem', 'w') as f:
250 f.write(key)
251 f.write(cert)
252
253 with open('keycert.passwd.pem', 'a+') as f:
254 f.write(cert)
255
256 # For certificate matching tests
257 make_ca(cmdlineargs)
258 cert, key = make_cert_key(cmdlineargs, 'fakehostname', ext='req_x509_extensions_simple')
259 with open('keycert2.pem', 'w') as f:
260 f.write(key)
261 f.write(cert)
262
263 cert, key = make_cert_key(cmdlineargs, 'localhost', sign=True)
264 with open('keycert3.pem', 'w') as f:
265 f.write(key)
266 f.write(cert)
267
268 check_call(['openssl', 'x509', '-outform', 'pem', '-in', 'keycert3.pem', '-out', 'cert3.pem'])
269
270 cert, key = make_cert_key(cmdlineargs, 'fakehostname', sign=True)
271 with open('keycert4.pem', 'w') as f:
272 f.write(key)
273 f.write(cert)
274
275 cert, key = make_cert_key(
276 cmdlineargs, 'localhost-ecc', sign=True, key='param:secp384r1.pem'
277 )
278 with open('keycertecc.pem', 'w') as f:
279 f.write(key)
280 f.write(cert)
281
282 extra_san = [
283 'otherName.1 = 1.2.3.4;UTF8:some other identifier',
284 'otherName.2 = 1.3.6.1.5.2.2;SEQUENCE:princ_name',
285 'email.1 = [email protected]',
286 'DNS.2 = www.example.org',
287 # GEN_X400
288 'dirName.1 = dir_sect',
289 # GEN_EDIPARTY
290 'URI.1 = https://www.python.org/',
291 'IP.1 = 127.0.0.1',
292 'IP.2 = ::1',
293 'RID.1 = 1.2.3.4.5',
294 ]
295
296 cert, key = make_cert_key(cmdlineargs, 'allsans', sign=True, extra_san='\n'.join(extra_san))
297 with open('allsans.pem', 'w') as f:
298 f.write(key)
299 f.write(cert)
300
301 extra_san = [
302 # könig (king)
303 'DNS.2 = xn--knig-5qa.idn.pythontest.net',
304 # königsgäßchen (king's alleyway)
305 'DNS.3 = xn--knigsgsschen-lcb0w.idna2003.pythontest.net',
306 'DNS.4 = xn--knigsgchen-b4a3dun.idna2008.pythontest.net',
307 # βόλοσ (marble)
308 'DNS.5 = xn--nxasmq6b.idna2003.pythontest.net',
309 'DNS.6 = xn--nxasmm1c.idna2008.pythontest.net',
310 ]
311
312 # IDN SANS, signed
313 cert, key = make_cert_key(cmdlineargs, 'idnsans', sign=True, extra_san='\n'.join(extra_san))
314 with open('idnsans.pem', 'w') as f:
315 f.write(key)
316 f.write(cert)
317
318 cert, key = make_cert_key(cmdlineargs, 'nosan', sign=True, ext='req_x509_extensions_nosan')
319 with open('nosan.pem', 'w') as f:
320 f.write(key)
321 f.write(cert)
322
323 unmake_ca()
324 print("Writing out reference data for Lib/test/test_ssl.py and Lib/test/test_asyncio/utils.py")
325 write_cert_reference('keycert.pem')
326 write_cert_reference('keycert3.pem')