184 lines
12 KiB
Python
184 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Three-phase root rollover. Offline mode is restricted to an isolated test PKI."""
|
|
import argparse,contextlib,fcntl,json,os,secrets,shutil,subprocess,time
|
|
from pathlib import Path
|
|
import pki_state as pki
|
|
from resilience_hooks import command,DC,ROOT
|
|
|
|
CANARIES=('client-api','api','grafana','prometheus','otel-collector')
|
|
ENDPOINTS=[
|
|
('lb',443,'lb','api','/health/ready'),
|
|
('api-tls',8443,'api','client-api','/health/ready'),('api2-tls',8443,'api','client-api','/health/ready'),
|
|
('minio',9000,'minio','api','/minio/health/live'),('openbao',8200,'openbao','api','/v1/sys/seal-status'),
|
|
('otel-collector',4318,'otel-collector','api','/v1/traces'),('otel-collector-tls',9464,'otel-collector','prometheus','/metrics'),
|
|
('loki-tls',3100,'loki','grafana','/ready'),('tempo-tls',4318,'tempo','otel-collector','/v1/traces'),
|
|
('tempo-tls',3200,'tempo','grafana','/ready'),('prometheus-tls',9090,'prometheus','grafana','/-/ready'),
|
|
('grafana-tls',3000,'grafana','api','/api/health')]
|
|
|
|
@contextlib.contextmanager
|
|
def ca_lock():
|
|
with (pki.CA/'ca.lock').open('a') as f:
|
|
fcntl.flock(f,fcntl.LOCK_EX);yield
|
|
|
|
def record(s,phase,details):
|
|
s.setdefault('events',[]).append({'phase':phase,'unix_time':time.time(),**details})
|
|
pki.save_state(s)
|
|
if not OFFLINE:
|
|
public={k:v for k,v in s.items() if k not in ('events',)}
|
|
public['events']=s['events']
|
|
pki.atomic(ROOT/'evidence/ca-rollover.json',json.dumps(public,indent=2)+'\n',0o644)
|
|
|
|
def verify_leaf(cert,root):
|
|
p=pki.openssl('verify','-no_check_time','-no-CApath','-no-CAstore','-CAfile',root,cert)
|
|
return p
|
|
|
|
def new_authority():
|
|
directory=pki.CA/'generations'/('.pending-'+secrets.token_hex(6));directory.mkdir(mode=0o700)
|
|
pki.openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',directory/'ca.key')
|
|
pki.openssl('req','-new','-x509','-sha256','-days','3650','-key',directory/'ca.key','-out',directory/'issuer.crt',
|
|
'-subj','/CN=Lab7-Root-CA-'+time.strftime('%Y%m%d%H%M%S',time.gmtime())+'-'+secrets.token_hex(3),
|
|
'-addext','basicConstraints=critical,CA:true','-addext','keyUsage=critical,keyCertSign,cRLSign')
|
|
fp=pki.fingerprint(directory/'issuer.crt');target=pki.authority(fp);os.replace(directory,target)
|
|
(target/'newcerts').mkdir();pki.atomic(target/'index.txt',b'')
|
|
pki.atomic(target/'serial',secrets.token_hex(8)+'\n');pki.atomic(target/'crlnumber','1000\n')
|
|
pki.atomic(target/'openssl.cnf',pki.config(target));pki.generate_crl(target)
|
|
return target
|
|
|
|
def canaries(directory):
|
|
for role in CANARIES:
|
|
out=directory/'canaries'/role;out.mkdir(parents=True,mode=0o700,exist_ok=True)
|
|
if (out/(role+'.crt')).exists():continue
|
|
pki.openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:2048','-out',out/(role+'.key'))
|
|
pki.openssl('req','-new','-key',out/(role+'.key'),'-subj','/CN=rollover-canary-'+role,'-out',out/'request.csr')
|
|
pki.atomic(out/'extensions.cnf',f'basicConstraints=critical,CA:false\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\nsubjectAltName=DNS:{role}\n')
|
|
pki.openssl('ca','-batch','-notext','-config',directory/'openssl.cnf','-extfile',out/'extensions.cnf','-in',out/'request.csr','-out',out/(role+'.crt'))
|
|
pki.generate_crl(directory)
|
|
|
|
def reload_stack(phase):
|
|
if OFFLINE:return
|
|
env=dict(os.environ,HOOK_EVIDENCE_FILE='evidence/ca-'+phase+'-restart.json')
|
|
p=subprocess.run([str(ROOT/'scripts/restart.sh')],cwd=ROOT,env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=110)
|
|
if p.returncode:raise RuntimeError('Rollover restart hook failed; dual trust is retained until recovery')
|
|
|
|
def client_directory(s,role,canary=False):
|
|
return pki.authority(s['new'])/'canaries'/role if canary else pki.PKI/role
|
|
|
|
def probe_args(ca,client,role):
|
|
return ['run','--rm','-T','--no-deps','-v',str(ca)+':/verify/ca.crt:ro','-v',str(client)+':/probe-client:ro','--entrypoint']
|
|
|
|
def http_probe(host,port,name,role,ca,client,path):
|
|
args=probe_args(ca,client,role)+['curl','api','--silent','--show-error','--connect-timeout','3','--max-time','8',
|
|
'--cacert','/verify/ca.crt','--cert','/probe-client/'+role+'.crt','--key','/probe-client/'+role+'.key',
|
|
'--connect-to',f'{name}:{port}:{host}:{port}','--output','/dev/null','--write-out','%{http_code}',f'https://{name}:{port}/'+path.lstrip('/')]
|
|
p=subprocess.run(DC+args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
|
|
if p.returncode or not p.stdout.strip().isdigit() or int(p.stdout.strip())==0:
|
|
raise RuntimeError('TLS endpoint verification failed: '+host+':'+str(port))
|
|
return {'endpoint':host+':'+str(port),'server_name':name,'http_status':int(p.stdout.strip())}
|
|
|
|
def protocol_probe(host,port,name,ca,client,postgres=False):
|
|
args=probe_args(ca,client,'api')+['/usr/bin/timeout','api','--kill-after=1s','4s','openssl','s_client','-quiet','-ign_eof',
|
|
'-connect',f'{host}:{port}','-servername',name,'-verify_hostname',name,'-verify_return_error','-CAfile','/verify/ca.crt',
|
|
'-cert','/probe-client/api.crt','-key','/probe-client/api.key']
|
|
if postgres:
|
|
import struct
|
|
args+=['-starttls','postgres'];body=b'user\0pki_probe\0database\0messenger\0\0'
|
|
payload=struct.pack('!II',len(body)+8,196608)+body
|
|
else:payload=b'PING\r\n'
|
|
p=subprocess.run(DC+args,input=payload,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=15)
|
|
accepted=(p.stdout.startswith(b'R') if postgres else b'NOAUTH' in p.stdout)
|
|
if p.returncode not in (0,124) or not accepted:
|
|
raise RuntimeError('TLS protocol/application response failed: '+host)
|
|
return {'endpoint':host+':'+str(port),'server_name':name,'application_response':'PostgreSQL Authentication' if postgres else 'Redis NOAUTH'}
|
|
|
|
def probes(s,new_only=False,canary=False):
|
|
if OFFLINE:return []
|
|
ca=pki.authority(s['new'])/'issuer.crt' if new_only else pki.PKI/'ca.crt'
|
|
result=[]
|
|
for host,port,name,role,path in ENDPOINTS:
|
|
result.append(http_probe(host,port,name,role,ca,client_directory(s,role,canary),path))
|
|
result.append(protocol_probe('db',5432,'db',ca,client_directory(s,'api',canary),True))
|
|
result.append(protocol_probe('redis',6379,'redis',ca,client_directory(s,'api',canary)))
|
|
return result
|
|
|
|
def old_client_probe(s,deny):
|
|
if OFFLINE:return
|
|
directory=pki.authority(s['old'])/'old-client-api'
|
|
for host in ('api-tls','api2-tls'):
|
|
args=probe_args(pki.PKI/'ca.crt',directory,'client-api')+['curl','api','--silent','--show-error','--fail','--connect-timeout','3','--max-time','8',
|
|
'--cacert','/verify/ca.crt','--cert','/probe-client/client-api.crt','--key','/probe-client/client-api.key',
|
|
'--connect-to',f'api:8443:{host}:8443','https://api:8443/health/ready']
|
|
p=subprocess.run(DC+args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
|
|
assert (p.returncode in (35,52,55,56)) if deny else p.returncode==0,host+' old-root identity verification'
|
|
|
|
def prepare():
|
|
with ca_lock():
|
|
pki.ensure_layout();s=pki.state()
|
|
if not s or s['phase']=='retired':
|
|
old=pki.active();new=new_authority();canaries(new)
|
|
saved=old/'old-client-api';saved.mkdir(mode=0o700,exist_ok=True)
|
|
for ext in ('crt','key'):shutil.copy2(pki.PKI/'client-api'/('client-api.'+ext),saved/('client-api.'+ext))
|
|
s={'old':old.name,'new':new.name,'phase':'overlap','trust_distributed':False,'offline_test':OFFLINE,'events':[]}
|
|
pki.save_state(s)
|
|
if s['phase']!='overlap':raise RuntimeError('prepare is only valid before leaf reissue')
|
|
pki.publish()
|
|
reload_stack('overlap')
|
|
checks=probes(s,canary=True);old_client_probe(s,False)
|
|
with ca_lock():
|
|
s['trust_distributed']=True;record(s,'overlap',{'trusted_roots':2,'new_root_client_checks':checks,'old_root_client':'accepted'})
|
|
print(('OFFLINE model' if OFFLINE else 'PASS')+': old and new roots trusted; old leaves retained; new-root client identities accepted',flush=True)
|
|
|
|
def reissue():
|
|
with ca_lock():
|
|
s=pki.state();assert s and s['phase'] in ('overlap','reissued') and s['trust_distributed'],'Distribute/verify dual trust first'
|
|
if pki.active().name!=s['new']:
|
|
assert pki.active().name==s['old'];pki.link(pki.CA/'active',Path('generations')/s['new'])
|
|
pki.publish()
|
|
for role in pki.ROLES:
|
|
cert=pki.PKI/role/(role+'.crt')
|
|
try:verify_leaf(cert,pki.authority(s['new'])/'issuer.crt')
|
|
except RuntimeError:
|
|
env=dict(os.environ,PKI_DIR=str(pki.PKI),CA_DIR=str(pki.CA))
|
|
p=subprocess.run([str(ROOT/'scripts/bootstrap-pki.sh'),role],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
|
if p.returncode:raise RuntimeError('Leaf reissue failed: '+role)
|
|
verify_leaf(cert,pki.authority(s['new'])/'issuer.crt')
|
|
with ca_lock():s['phase']='reissued';pki.save_state(s);pki.publish()
|
|
reload_stack('reissued');checks=probes(s,new_only=True);old_client_probe(s,False)
|
|
with ca_lock():record(s,'reissued',{'trusted_roots':2,'new_root_server_checks':checks,'old_root_client':'accepted during overlap','leaf_roles':list(pki.ROLES)})
|
|
print(('OFFLINE model' if OFFLINE else 'PASS')+': all leaf/server identities switched to the new CA; overlap still accepts old clients',flush=True)
|
|
|
|
def revoke(directory,certificate):
|
|
serial=pki.openssl('x509','-in',certificate,'-noout','-serial').decode().strip().split('=')[1]
|
|
rows=[r.split('\t') for r in (directory/'index.txt').read_text().splitlines()]
|
|
if not any(r[0]=='R' and r[3].upper()==serial.upper() for r in rows):
|
|
pki.openssl('ca','-config',directory/'openssl.cnf','-revoke',certificate)
|
|
|
|
def retire():
|
|
s=pki.state();assert s and s['phase'] in ('reissued','retired'),'Reissue every leaf before retirement'
|
|
for role in pki.ROLES:verify_leaf(pki.PKI/role/(role+'.crt'),pki.authority(s['new'])/'issuer.crt')
|
|
# Never remove old trust until every actual TLS endpoint proves its new chain.
|
|
checks=probes(s,new_only=True)
|
|
with ca_lock():
|
|
old=pki.authority(s['old']);new=pki.authority(s['new'])
|
|
for row in (old/'index.txt').read_text().splitlines():
|
|
parts=row.split('\t')
|
|
cert=old/'newcerts'/(parts[3]+'.pem')
|
|
if parts[0]=='V' and cert.exists():revoke(old,cert)
|
|
revoke(old,old/'issuer.crt');pki.generate_crl(old)
|
|
for role in CANARIES:revoke(new,new/'canaries'/role/(role+'.crt'))
|
|
pki.generate_crl(new)
|
|
s['phase']='retired';pki.save_state(s);pki.publish()
|
|
reload_stack('retired');checks=probes(s,new_only=True);old_client_probe(s,True)
|
|
with ca_lock():record(s,'retired',{'trusted_roots':1,'old_ca_revocation_recorded':True,'old_root_client':'rejected on both API replicas','new_root_server_checks':checks})
|
|
print(('OFFLINE model' if OFFLINE else 'PASS')+': old CA/leaf revocations recorded; old trust anchor removed; old identities rejected',flush=True)
|
|
|
|
if __name__=='__main__':
|
|
parser=argparse.ArgumentParser();parser.add_argument('phase',choices=['prepare','reissue','retire','all']);parser.add_argument('--offline',action='store_true');args=parser.parse_args()
|
|
OFFLINE=args.offline
|
|
assert not OFFLINE or (pki.PKI!=ROOT/'certs' and pki.CA!=ROOT/'secrets/operator/ca'),'Offline mode requires isolated test paths'
|
|
os.umask(0o077);pki.CA.mkdir(parents=True,exist_ok=True)
|
|
# Same operator lock as cron; each CA mutation also takes the signing DB lock.
|
|
with (pki.CA.parent/'pki.lock').open('a') as operator_lock:
|
|
fcntl.flock(operator_lock,fcntl.LOCK_EX)
|
|
if args.phase=='all':prepare();reissue();retire()
|
|
else:{'prepare':prepare,'reissue':reissue,'retire':retire}[args.phase]()
|