Files
LEAF/scripts/rotate-vyos-key.py

121 lines
4.7 KiB
Python
Raw Normal View History

2026-11-15 17:42:41 +01:00
#!/usr/bin/env python3
"""Rotate exactly one explicitly selected LEAF key. Never prints API bodies/keys.
Run on sensor: sudo python3 .../rotate-vyos-key.py --old-id <LEAF-owned-id>
Other applications' credentials are preserved. Retrying after retirement/save
failure requires inspecting router key IDs first; no blind mass-delete mode.
"""
import argparse
import os
from pathlib import Path
import re
import secrets
import string
import subprocess
import sys
import time
sys.path.insert(0, '/opt/leaf-controller/controller')
from leaf_controller.config import load_config, read_key_env
from leaf_controller.vyos_client import VyosClient, VyosApiError
ENV_PATH = '/etc/leaf-controller/env'
CFG_PATH = '/etc/leaf-controller/config.yaml'
SERVICE = 'leaf-controller.service'
KEYS_PATH = ['service', 'https', 'api', 'keys', 'id']
def atomic_env(text):
tmp=ENV_PATH+'.new'
fd=os.open(tmp, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0o600)
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'w') as f:
f.write(text); f.flush(); os.fsync(f.fileno())
os.replace(tmp, ENV_PATH)
fd=os.open(str(Path(ENV_PATH).parent), os.O_DIRECTORY)
try: os.fsync(fd)
finally: os.close(fd)
def restart_service():
subprocess.run(['systemctl','restart',SERVICE], check=True, capture_output=True)
subprocess.run(['systemctl','is-active','--quiet',SERVICE], check=True, capture_output=True)
def wait_auth(client, group, accepted=True, attempts=24):
for i in range(attempts):
try:
client.group_members(group)
if accepted: return
except VyosApiError as exc:
if not accepted and exc.status in (401,403): return
except Exception:
pass
if i+1<attempts: time.sleep(5)
raise RuntimeError('credential verification timed out')
def rotate(old, new, old_id, new_id, old_key, new_key, env_text, group):
body=old.retrieve('showConfig', KEYS_PATH[:-1])
ids=(body.get('data') or {}).get('id', {})
if old_id not in ids or ids[old_id].get('key') != old_key:
raise RuntimeError('selected key ID does not match the current controller credential')
if new_id in ids:
raise RuntimeError('candidate ID already exists')
swapped=False
installed=False
try:
# A timeout can still commit; rollback attempts candidate deletion either way.
installed=True
old.configure({'op':'set','path':KEYS_PATH+[new_id,'key',new_key]})
wait_auth(new, group)
# Persist both keys before the local switch; old credential remains a recovery path.
new.save_config()
out,n=re.subn(r'(?m)^LEAF_VYOS_KEY=.*$', "LEAF_VYOS_KEY='"+new_key+"'", env_text)
if n!=1: raise RuntimeError('expected exactly one credential assignment')
swapped=True
atomic_env(out)
restart_service()
wait_auth(new, group, attempts=2)
except BaseException:
# Restore the credential before restarting. If recovery fails, retain candidate.
if swapped:
atomic_env(env_text)
restart_service()
if installed:
old.configure({'op':'delete','path':KEYS_PATH+[new_id]})
old.save_config()
raise
# Retirement is a separate phase: rollback is unsafe after this commit.
new.configure({'op':'delete','path':KEYS_PATH+[old_id]})
new.save_config() # Failure is fatal; never claim persistence succeeded.
wait_auth(old, group, accepted=False)
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--old-id', required=True)
a=ap.parse_args()
if os.geteuid()!=0: ap.error('run as root on the sensor')
cfg=load_config(CFG_PATH)
if cfg.get('vyos.key_env','LEAF_VYOS_KEY')!='LEAF_VYOS_KEY':
ap.error('this tool requires the standard LEAF_VYOS_KEY assignment')
text=Path(ENV_PATH).read_text()
old_key=read_key_env(ENV_PATH)
new_key=''.join(secrets.choice(string.ascii_letters+string.digits) for _ in range(32))
new_id='leaf-'+str(time.time_ns())
def client(key):
return VyosClient(cfg.vyos_url(), key, cert_pin=cfg.get('vyos.tls_cert_pin') or None,
ca_bundle=cfg.get('vyos.ca_bundle'), tls_verify=cfg.get('vyos.tls_verify',True),
timeout=float(cfg.get('vyos.timeout',75)), retries=1)
try:
rotate(client(old_key),client(new_key),a.old_id,new_id,old_key,new_key,text,cfg.get('block_group'))
except BaseException:
# Deliberately omit exception details: router responses can contain secrets.
print('ROTATION FAILED. Inspect service and router key IDs before retrying. Candidate ID: '+new_id,
file=sys.stderr)
return 1
print('ROTATION COMPLETE: selected old ID retired, config persisted, new ID='+new_id)
return 0
if __name__=='__main__': raise SystemExit(main())