"""Sensor-side helper for the bounded live proof. Never emits credentials.""" import argparse,json,sys,time,sqlite3,re,hashlib from pathlib import Path import yaml sys.path.insert(0,'/opt/leaf-controller/controller') from leaf_controller.vyos_client import VyosClient p=argparse.ArgumentParser();p.add_argument('command',choices=['status','short-ttl','restore','cleanup']);p.add_argument('--since',type=float,default=0) a=p.parse_args() config=Path('/etc/leaf-controller/config.yaml'); backup=Path('/run/leaf-e2e-config.original.yaml') if a.command=='short-ttl': if backup.exists(): raise SystemExit('Previous live test backup exists; restore it first') backup.write_bytes(config.read_bytes());backup.chmod(0o600) cfg=yaml.safe_load(config.read_text());cfg['policy']['ttl_seconds']=180; cfg['batch_delay']=3 config.write_text(yaml.safe_dump(cfg,sort_keys=False));print('temporary TTL=180, batching=3s');raise SystemExit if a.command=='restore': if backup.exists(): config.write_bytes(backup.read_bytes());backup.unlink() print('original controller configuration restored');raise SystemExit if a.command=='cleanup': con=sqlite3.connect('/var/lib/leaf-controller/state.sqlite',timeout=10) with con: con.execute("UPDATE blocks SET expires=? WHERE ip IN (?,?) AND first_seen>=?", (time.time(), '203.0.113.12', '192.0.2.202', a.since)) print('Requested expiry for this run only'); raise SystemExit from leaf_controller.config import load_config, read_key_env cfg=load_config(str(config)) key=read_key_env('/etc/leaf-controller/env', cfg.get('vyos.key_env', 'LEAF_VYOS_KEY')) c=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=75,retries=1) result={'now':time.time(),'members':c.group_members('IDS-BLOCK')} text=c._post('/show',{'op':'show','path':['firewall','ipv4','name','VEXLAN-MAOSPF-v4']}).get('data','') result['drop_counters']={} for line in text.splitlines(): match=re.match(r'^\s*([89])\s+drop\s+\S+\s+(\d+)\s+(\d+)',line) if match: result['drop_counters'][match[1]]=int(match[2]) text=c._post('/show',{'op':'show','path':['firewall','ipv4','forward','filter']}).get('data','') result['forward_destination_drops']=0 for line in text.splitlines(): match=re.match(r'^\s*10\s+drop\s+\S+\s+(\d+)\s+(\d+)',line) if match: result['forward_destination_drops']=int(match[1]) result['named_drop_counters']=dict(result['drop_counters']) result['drop_counters']['8']=result['drop_counters'].get('8',0)+result['forward_destination_drops'] con=sqlite3.connect('/var/lib/leaf-controller/state.sqlite') result['blocks']=[dict(zip(['ip','kind','expires','applied'],r)) for r in con.execute('select ip,kind,expires,applied from blocks')] result['audit']=[] for line in Path('/var/log/leaf-controller/decisions.jsonl').read_text().splitlines(): try: row=json.loads(line) except ValueError: continue if row.get('ts',0)>=a.since and row.get('ip') in ('203.0.113.12','192.0.2.202'): result['audit'].append(row) # The live EVE file is stats-only and can temporarily be absent during rename. # Detection evidence is the audit trail above; do not interpret no file alerts # as proof of no detections, or depend on stats-file availability for API status. result['alerts']=None result['alert_evidence']='controller audit; socket alerts are not journaled to EVE' result['protected_hashes']={} if a.since==0: for path in [['interfaces','ethernet','eth0'],['protocols','ospf'],['protocols','static']]: data=c.retrieve('showConfig',path).get('data') result['protected_hashes']['/'.join(path)]=hashlib.sha256(json.dumps(data,sort_keys=True).encode()).hexdigest() print(json.dumps(result))