#!/usr/bin/env python3 """Independent replay of CAIN-45 ZoD evidence (CAIN-42 Evolution #7, Phases 23-24). No CAIN imports. Given only a published evidence bundle, rebuild every ZoD's history from its signed evidence entries and check that the recorded transitions are exactly what the rules produce: STATE replay the ZoD state machine from its own copy of the transition table: every TRANSITION must start from the replayed state and be legal. Nothing is taken from the recorded 'from' field. TRAJECTORY recompute every trajectory head: head_k = sha256(canon({"prev": head_k-1, "step": step_k})), with head_0 = the ZoD's trajectory_id and each step rebuilt from the evidence (tool name + args hash, or argv hash + return code). Each must equal the head the hypervisor recorded. EFFECTS no tool call or code execution (requested, started or completed) outside RUNNING, and none before an AUTHORIZED transition that carries a cluster sequence FINAL the replayed final trajectory head and final state equal the ZoD record's The first mismatch is reported as REPLAY_DIVERGENCE with the evidence seq, what the rules expected and what was recorded. Replay checks meaning, not integrity: run the bundle's own verifier for signatures and quorum. python3 verify_zod_replay.py [--json] """ from __future__ import annotations import hashlib import json import sys import urllib.request from pathlib import Path LEGAL = {"CREATED": {"ATTESTING", "REVOKED", "TERMINATING"}, "ATTESTING": {"VERIFIED", "REVOKED", "TERMINATING"}, "VERIFIED": {"AUTHORIZING", "REVOKED", "TERMINATING"}, "AUTHORIZING": {"AUTHORIZED", "VERIFIED", "REVOKED", "TERMINATING"}, "AUTHORIZED": {"RUNNING", "SUSPENDED", "REVOKED", "TERMINATING"}, "RUNNING": {"SUSPENDED", "QUARANTINED", "TERMINATING", "REVOKED"}, "SUSPENDED": {"REVALIDATING", "QUARANTINED", "TERMINATING", "REVOKED"}, "REVALIDATING": {"RUNNING", "AUTHORIZED", "QUARANTINED", "TERMINATING", "REVOKED"}, "QUARANTINED": {"RECOVERING", "TERMINATING", "REVOKED"}, "RECOVERING": {"REVALIDATING", "TERMINATING", "REVOKED"}, "TERMINATING": {"TERMINATED"}, "TERMINATED": set(), "REVOKED": {"TERMINATING"}} EFFECTS = {"TOOL_CALL_REQUESTED", "TOOL_RESULT", "EXECUTION_REQUESTED", "EXECUTION_STARTED", "EXECUTION_RESULT"} def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def h(o): return hashlib.sha256(canon(o)).hexdigest() def load(base, name): if base.startswith("http"): try: with urllib.request.urlopen(base.rstrip("/") + "/" + name, timeout=30) as r: return json.loads(r.read()) except Exception: return None p = Path(base) / name return json.loads(p.read_text()) if p.exists() else None def bundle(base): """(list of (label, zod record, chain, self_reported)) for the three published bundle shapes.""" out = [] lease = load(base, "LEASE_RUN.json") if lease: chains = load(base, "EVIDENCE_CHAINS.json") selfrep = {r["condition"] for r in lease.get("results", []) if r.get("source") == "SELF-REPORTED"} for name, zd in lease["zods"].items(): ch = chains.get(name) if ch is None: # a parent recorded alongside its child's chain ch = next((c for c in chains.values() if any(e["zod_id"] == zd["zod_id"] for e in c)), []) out.append((name, zd, ch, name in selfrep)) return out for runfile in ("SECCOMP_RUN.json", "ZOD_RUN.json"): run = load(base, runfile) if run: chain = load(base, "EVIDENCE_CHAIN.json") zods = run.get("zods") or [run["zod"]] return [(zd["zod_id"], zd, chain, False) for zd in zods] raise SystemExit("no ZoD evidence bundle found at " + base) def replay(zd, chain, self_reported=False): zid, state, head, authorized, argv = zd["zod_id"], None, zd["trajectory_id"], False, {} steps = 0 for e in chain: if e["zod_id"] != zid: continue ev, d, seq = e["event"], e["data"], e["seq"] if ev == "ZOD_CREATED": if state is not None: return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": "one creation", "recorded": "second ZOD_CREATED"} state = "CREATED" elif ev == "TRANSITION": if state is None or d["to"] not in LEGAL.get(state, set()): return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": f"a legal transition out of {state}", "recorded": f"{d.get('from')} -> {d['to']}"} if d.get("from") != state: return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": f"from {state}", "recorded": f"from {d.get('from')}"} state = d["to"] if state == "AUTHORIZED" and d.get("sequence") is not None: authorized = True elif ev in EFFECTS: if state != "RUNNING" or not authorized: return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": "effects only while RUNNING under a cluster-sequenced authorization", "recorded": f"{ev} while {state} (authorized={authorized})"} if ev in ("EXECUTION_REQUESTED", "EXECUTION_STARTED"): argv[d["grant_id"]] = d["argv_hash"] elif ev == "EXECUTION_RESULT": want = h({"prev": head, "step": {"op": "run", "argv_hash": argv.get(d["grant_id"]), "rc": d["returncode"]}}) if want != d.get("trajectory_head"): return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": want, "recorded": d.get("trajectory_head")} head, steps = want, steps + 1 elif ev == "TOOL_RESULT": want = h({"prev": head, "step": {"op": "tool", "tool": d["tool"], "args_hash": d["args_hash"]}}) if want != d.get("trajectory_head"): return {"result": "REPLAY_DIVERGENCE", "seq": seq, "expected": want, "recorded": d.get("trajectory_head")} head, steps = want, steps + 1 recorded_head = zd.get("trajectory_head") or zd["trajectory_id"] if head != recorded_head: return {"result": "REPLAY_DIVERGENCE", "seq": None, "expected": head, "recorded": recorded_head, "note": "final trajectory head" + (" (self-reported case: chain is the pre-deletion copy)" if self_reported else "")} if not self_reported and zd.get("state") and zd["state"] != state: return {"result": "REPLAY_DIVERGENCE", "seq": None, "expected": f"final state {state}", "recorded": zd["state"], "note": "final state"} return {"result": "REPLAY_OK", "final_state_replayed": state, "trajectory_steps": steps, "final_head": head, "authorized_by_cluster": authorized} def main(argv): if not argv or argv[0].startswith("-"): print(__doc__) return 2 rows = [] for label, zd, chain, selfrep in bundle(argv[0]): r = replay(zd, chain, selfrep) rows.append({"zod": label, **r}) if "--json" in argv: print(json.dumps(rows, indent=1, sort_keys=True)) else: for r in rows: if r["result"] == "REPLAY_OK": print(f"[REPLAY_OK] {r['zod'][:52]:52s} final {r['final_state_replayed']}, {r['trajectory_steps']} step(s) recomputed") else: print(f"[REPLAY_DIVERGENCE] {r['zod'][:52]:52s} at seq {r['seq']}: expected {str(r['expected'])[:60]}, recorded {str(r['recorded'])[:60]}") ok = all(r["result"] == "REPLAY_OK" for r in rows) print(f"\n{sum(r['result'] == 'REPLAY_OK' for r in rows)}/{len(rows)} ZoDs replayed identically") print("REPLAY MATCHES" if ok else "REPLAY DIVERGENCE") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))