Files
dpl/scripts/fuc-xb-launch/certificate-refresh.py
T

35 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""Observe the existing certificate. Never edits shared renewal hooks or keys."""
import fcntl,hashlib,json,os,pathlib,socket,ssl,subprocess,time
STATE=pathlib.Path('/var/lib/fuc-xb-node')
def run(args):
p=subprocess.run(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True,timeout=30)
if p.returncode:raise RuntimeError('FUC certificate check failed; original services untouched')
return p.stdout.strip()
def main():
os.umask(0o077)
lock=open('/run/lock/fuc-xb-node.lock','a')
try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:return
state=json.loads((STATE/'owner.json').read_text());assert state['owner']=='fuc-xb-launch-20261105'
row=state['node'];cert=row['certificate']
run(['openssl','x509','-in',cert,'-noout','-checkhost',row['sni']]);run(['openssl','x509','-in',cert,'-noout','-checkend','604800']);run(['openssl','verify','-untrusted',cert,cert])
assert run(['openssl','x509','-in',cert,'-pubkey','-noout'])==run(['openssl','pkey','-in',row['private_key'],'-pubout']),'Renewed certificate key mismatch'
current=run(['openssl','x509','-in',cert,'-noout','-fingerprint','-sha256'])
changed=current!=state['certificate_fingerprint']
if changed:
run(['systemctl','restart','fuc-xb-node']);assert run(['systemctl','is-active','fuc-xb-node'])=='active'
for _ in range(30):
pid=run(['systemctl','show','fuc-xb-node','-p','MainPID','--value'])
if 'pid='+pid+',' in run(['ss','-H','-ltnp','sport = :24445']):break
time.sleep(1)
else:raise RuntimeError('FUC did not own its listener after certificate refresh')
expected=bytes.fromhex(current.split('=',1)[1].replace(':',''))
with socket.create_connection(('127.0.0.1',24445),timeout=8)as raw:
with ssl.create_default_context().wrap_socket(raw,server_hostname=row['sni'])as tls:
assert hashlib.sha256(tls.getpeercert(binary_form=True)).digest()==expected,'FUC did not load renewed certificate'
state['certificate_fingerprint']=current
tmp=STATE/'owner.json.tmp';tmp.write_text(json.dumps(state,indent=2));tmp.replace(STATE/'owner.json')
print(json.dumps({'valid_over_7days':True,'certificate_changed':changed,'fuc_restarted':changed,'other_services_restarted':False}))
if __name__=='__main__':main()