#!/usr/bin/env python3 """Install the public CF certificate only after matching the server-held key and SANs.""" import argparse import os import pathlib import subprocess p = argparse.ArgumentParser() p.add_argument('domain', choices=['tomshell.online', 'tomtojapan.online']) p.add_argument('certificate', type=pathlib.Path) a = p.parse_args() os.umask(0o077) root = pathlib.Path('/etc/white-proxy-origin') / a.domain key = root / 'privatekey.pem' if not key.exists(): p.error('Generate the key and CSR on the white machine first') subprocess.run(['openssl', 'x509', '-in', str(a.certificate), '-checkend', '86400', '-noout'], check=True, capture_output=True) san = subprocess.check_output(['openssl', 'x509', '-in', str(a.certificate), '-noout', '-ext', 'subjectAltName'], text=True) if 'DNS:*.' + a.domain not in san or 'DNS:' + a.domain not in san: p.error('Certificate does not contain the expected root and wildcard names') cert_pub = subprocess.check_output(['openssl', 'x509', '-in', str(a.certificate), '-noout', '-pubkey']) key_pub = subprocess.check_output(['openssl', 'pkey', '-in', str(key), '-pubout']) if cert_pub.strip() != key_pub.strip(): p.error('Certificate public key differs from the server-held private key') target = root / 'fullchain.pem' if target.exists() and target.read_bytes() != a.certificate.read_bytes(): p.error('Different certificate already exists; take an explicit backup before replacement') temporary = root / 'fullchain.pem.new' temporary.write_bytes(a.certificate.read_bytes()) temporary.chmod(0o600) os.replace(temporary, target) print('Installed matching public origin certificate: ' + a.domain + '; private key retained on server')