Supporters update.
[dcpomatic.git] / hacks / certtool
1 #!/usr/bin/python3
2
3 import argparse
4 import os
5 from pathlib import Path
6 import subprocess
7 import sys
8 import tempfile
9
10
11 parser = argparse.ArgumentParser()
12 parser.add_argument('-c', '--check', help='check a .dom settings export file on stdin', action='store_true')
13 parser.add_argument('-s', '--split', help='split certificates and private keys from stdin', action='store_true')
14 parser.add_argument('-p', '--prefix', help='output filename prefix when doing --split', type=Path, default='./')
15 args = parser.parse_args()
16
17 cert = None
18 certs = []
19 private_key = None
20
21 for line in sys.stdin.readlines():
22     if line.find('BEGIN CERTIFICATE') != -1:
23         cert = line
24     elif line.find('END CERTIFICATE') != -1:
25         cert += line
26         certs.append(cert)
27         cert = None
28     elif cert:
29         cert += line
30     elif line.find('BEGIN RSA PRIVATE KEY') != -1:
31         private_key = line
32     elif line.find('END RSA PRIVATE') != -1:
33         private_key += line
34     elif private_key:
35         private_key += line
36
37 if len(certs) != 3:
38     print(f'Expected 3 certificates but found {len(certs)}.', file=sys.stderr)
39     exit(1)
40
41 if args.check:
42     if private_key is None:
43         print('Found no private key', file=sys.stderr)
44         exit(1)
45
46     leaf_cert_modulus = None
47     with tempfile.NamedTemporaryFile(mode='w', delete=False) as leaf:
48         print(certs[2], file=leaf)
49         leaf.close()
50         process = subprocess.run(['openssl', 'x509', '-modulus', '-noout', '-in', leaf.name], capture_output=True)
51         leaf_cert_modulus = process.stdout
52
53     leaf_key_modulus = None
54     with tempfile.NamedTemporaryFile('w', delete=False) as key:
55         print(private_key, file=key)
56         key.close()
57         process = subprocess.run(['openssl', 'rsa', '-modulus', '-noout', '-in', key.name], capture_output=True, check=True)
58         leaf_key_modulus = process.stdout
59
60     if leaf_cert_modulus != leaf_key_modulus:
61         print('Leaf certificate and private key don''t match.', file=sys.stderr)
62         exit(1)
63     else:
64         print('Leaf certificates and private key match.')
65
66 elif args.split:
67
68     for index, cert in enumerate(certs):
69         with open(f'{args.prefix.name}cert_{index}.pem', 'w') as output:
70             print(cert, file=output)
71
72     if private_key:
73         with open(f'{args.prefix.name}private_key.pem', 'w') as output:
74             print(private_key, file=output)
75