#!/usr/bin/env python3 """Operator-only PKI bootstrap. Never prints keys or secret values.""" import argparse, os, subprocess from pathlib import Path ROOT=Path(__file__).resolve().parents[1] BASE=ROOT/'secrets' def run(*args): subprocess.run(args,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE) def issue(name,renew=False): d=BASE/'tls'/name;d.mkdir(parents=True,exist_ok=True) if (d/'cert.crt').exists() and not renew:return ext=d/'extensions.cnf' sans=[name] if name in ('api1','api2'):sans+=['messenger-api'] if name in ('lb','grafana','openbao'):sans+=['localhost'] ext.write_text('basicConstraints=critical,CA:FALSE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName='+','.join('DNS:'+s for s in sans)+',IP:127.0.0.1\n') run('openssl','req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+name,'-keyout',str(d/'key.new'),'-out',str(d/'request.csr')) run('openssl','x509','-req','-in',str(d/'request.csr'),'-CA',str(BASE/'public/ca.crt'),'-CAkey',str(BASE/'operator/ca.key'),'-set_serial',str(int.from_bytes(os.urandom(16),'big')),'-days','7','-sha256','-extfile',str(ext),'-out',str(d/'cert.new')) for src,dst in [('key.new','key.key'),('cert.new','cert.crt')]: os.chmod(d/src,0o444);os.replace(d/src,d/dst) for f in ['request.csr','extensions.cnf']: (d/f).unlink() def main(): p=argparse.ArgumentParser();p.add_argument('--rotate');a=p.parse_args() os.umask(0o077) for x in ['operator','public','tls']: (BASE/x).mkdir(parents=True,exist_ok=True) if not (BASE/'operator/ca.key').exists(): run('openssl','req','-x509','-newkey','rsa:3072','-nodes','-days','365','-sha256','-subj','/CN=MTUSI Lab7 local CA','-keyout',str(BASE/'operator/ca.key'),'-out',str(BASE/'public/ca.crt'),'-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-addext','subjectKeyIdentifier=hash') os.chmod(BASE/'public/ca.crt',0o444) if not (BASE/'public/revoked-serials').exists(): (BASE/'public/revoked-serials').write_text('') os.chmod(BASE/'public/revoked-serials',0o444) roles=['lb','api1','api2','worker','dispatcher','cleanup','migrate','s3-init','postgres','redis','broker','s3','otel-collector','prometheus','loki','tempo','grafana','openbao','operator','outsider'] for role in roles:issue(role,a.rotate in (role,"all")) if a.rotate and a.rotate not in roles+["all"]:raise SystemExit('unknown identity') foreign=BASE/'tls/foreign';foreign.mkdir(exist_ok=True);foreign.chmod(0o755) if not (foreign/'cert.crt').exists(): run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','7','-subj','/CN=untrusted','-keyout',str(foreign/'key.key'),'-out',str(foreign/'cert.crt')) for f in foreign.iterdir():f.chmod(0o444) print('PKI ready; private CA remains operator-only.') if __name__=='__main__':main()