#!/usr/bin/env python3 """Private per-generation CA database; public atomic trust/CRL bundles only.""" import json,os,re,secrets,shutil,subprocess from pathlib import Path ROOT=Path(__file__).resolve().parent.parent PKI=Path(os.environ.get('PKI_DIR',ROOT/'certs')).resolve() CA=Path(os.environ.get('CA_DIR',ROOT/'secrets/operator/ca')).resolve() ROLES=('lb','api','worker','db','minio','redis','client-api','openbao','otel-collector','collector','prometheus','tempo','loki','grafana','operator') def openssl(*args,data=None): p=subprocess.run(['openssl',*map(str,args)],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE) if p.returncode:raise RuntimeError('OpenSSL operation failed: '+str(args[0])+' (private command output withheld)') return p.stdout def atomic(path,data,mode=0o600): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) temp=path.with_name(path.name+'.tmp-'+secrets.token_hex(4)) fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,mode) try: with os.fdopen(fd,'wb') as f:f.write(data if isinstance(data,bytes) else data.encode());f.flush();os.fsync(f.fileno()) os.chmod(temp,mode);os.replace(temp,path) finally: if temp.exists():temp.unlink() def link(path,target): path=Path(path);temp=path.with_name(path.name+'.link-'+secrets.token_hex(4)) temp.symlink_to(target);os.replace(temp,path) def fingerprint(cert): return openssl('x509','-in',cert,'-noout','-fingerprint','-sha256').decode().strip().split('=')[1].replace(':','').lower() def config(directory): directory=Path(directory) return f'''[ca] default_ca=local [local] dir={directory} database=$dir/index.txt new_certs_dir=$dir/newcerts certificate=$dir/issuer.crt private_key=$dir/ca.key serial=$dir/serial crlnumber=$dir/crlnumber default_md=sha256 default_days=7 default_crl_days=7 policy=policy unique_subject=no [policy] commonName=supplied ''' def state(): path=CA/'rollover.json' return json.loads(path.read_text()) if path.exists() else None def save_state(s):atomic(CA/'rollover.json',json.dumps(s,indent=2)+'\n') def authority(identifier): assert re.fullmatch('[0-9a-f]{64}',identifier),'Invalid CA generation' return CA/'generations'/identifier def active():return (CA/'active').resolve(strict=True) def generate_crl(directory): directory=Path(directory) raw=openssl('ca','-gencrl','-config',directory/'openssl.cnf') atomic(directory/'ca.crl',raw,0o644) def ensure_layout(): """Called under the CA lock, after initial root creation in bootstrap-pki.""" CA.mkdir(parents=True,exist_ok=True);(CA/'generations').mkdir(exist_ok=True) (PKI/'trust').mkdir(parents=True,exist_ok=True);os.chmod(PKI/'trust',0o755) if not (CA/'active').exists(): root_cert=PKI/'ca.crt' certs=re.findall(rb'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\s*',root_cert.read_bytes(),re.S) assert len(certs)==1,'Initial migration needs exactly one root certificate' fp=fingerprint(root_cert);directory=authority(fp) directory.mkdir(mode=0o700,exist_ok=True) # Copy first; until the active pointer exists, the legacy CA remains intact. for pattern in ('ca.key','index.txt*','serial*','crlnumber*'): for src in CA.glob(pattern): if src.is_file() and not (directory/src.name).exists():shutil.copy2(src,directory/src.name) if not (directory/'newcerts').exists():shutil.copytree(CA/'newcerts',directory/'newcerts') atomic(directory/'issuer.crt',certs[0],0o644) atomic(directory/'openssl.cnf',config(directory)) crl=PKI/'ca.crl' if crl.exists():atomic(directory/'ca.crl',crl.read_bytes(),0o644) else:generate_crl(directory) link(CA/'active',Path('generations')/fp) # All signing paths resolve through one atomic generation pointer. for name,target in [('ca.key','ca.key'),('issuer.crt','issuer.crt'),('index.txt','index.txt'),('serial','serial'),('crlnumber','crlnumber'),('active.crl','ca.crl')]: link(CA/name,Path('active')/target) atomic(CA/'openssl.cnf',config(CA/'active')) for name in ('ca.crt','ca.crl'): path=PKI/name if path.exists() and not path.is_symlink() and not (PKI/'trust'/name).exists():atomic(PKI/'trust'/name,path.read_bytes(),0o644) link(path,Path('trust')/name) publish() def publish(): s=state() directories=[active()] if s and s['phase']=='retired': assert active().name==s['new'],'Refusing to restore a retired trust anchor' if s and s['phase'] in ('overlap','reissued'): directories=[authority(s['old']),authority(s['new'])] for directory in directories: if not (directory/'ca.crl').exists():generate_crl(directory) atomic(PKI/'trust/ca.crt',b''.join((d/'issuer.crt').read_bytes() for d in directories),0o644) atomic(PKI/'trust/ca.crl',b''.join((d/'ca.crl').read_bytes() for d in directories),0o644) if __name__=='__main__': import sys {'init':ensure_layout,'publish':publish}[sys.argv[1]]()