"""Bind the compiled receipt call to the real wake-result and owner gates.""" from pathlib import Path import hashlib import importlib.util import json import re import shutil import subprocess import sys import tempfile machine_path = Path(__file__).with_name('k2100-aarch64-admission-machine.py') spec = importlib.util.spec_from_file_location('admission_machine', machine_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) Machine = module.AdmissionMachine out = Path(tempfile.mkdtemp(prefix='K2100-process-stale-gates-proof-', dir='reports/os-implementation')) shutil.copyfile(__file__, out / 'harness.py.txt') shutil.copyfile(machine_path, out / 'machine.py.txt') def art(p): p = Path(p) return dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) try: prepath = Path(sys.argv[1]) pre = json.loads(prepath.read_text()) for a in pre['artifacts'].values(): assert art(a['path'])['sha256'] == a['sha256'] image = Path(pre['artifacts']['image']['path']).read_bytes() rows = [] for line in Path(pre['artifacts']['nm']['path']).read_text().splitlines(): a = line.split() if len(a) == 4: rows.append(dict(address=int(a[0], 16), size=int(a[1], 16), name=a[3])) def pick(fragment): found = [r for r in rows if fragment in r['name'] and r['size'] and not r['name'].startswith('_RNC')] assert len(found) == 1, (fragment, len(found)) return found[0] body = pick('__os_k2100_process_round_body') wake = pick('12wake_process') receipt = pick('8duration5stale') base = next(r['address'] for r in rows if r['name'] == '_image_start') sysroot = subprocess.check_output(['rustc', '--print', 'sysroot'], text=True).strip() host = next(l[6:] for l in subprocess.check_output(['rustc', '-vV'], text=True).splitlines() if l.startswith('host: ')) objdump = sysroot + '/lib/rustlib/' + host + '/bin/llvm-objdump' text = subprocess.check_output([objdump, '-d', '--start-address=' + str(body['address']), '--stop-address=' + str(body['address'] + body['size']), pre['artifacts']['elf']['path']], text=True) (out / 'body.txt').write_text(text) instructions = {} for line in text.splitlines(): m = re.match(r'^\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(\S+)(.*)$', line) if m: pc, raw = int(m[1], 16), int(m[2], 16) assert raw == int.from_bytes(image[pc - base:pc - base + 4], 'little') instructions[pc] = (m[3], re.sub(r'<[^>]*>', '', m[4].split('//', 1)[0]).strip()) assert len(instructions) * 4 == body['size'] wake_calls = [pc for pc, (op, arg) in instructions.items() if op == 'bl' and int(arg, 0) == wake['address']] receipt_calls = [pc for pc, (op, arg) in instructions.items() if op == 'bl' and int(arg, 0) == receipt['address']] assert len(wake_calls) == 2 and len(receipt_calls) == 1 first, second = wake_calls target = receipt_calls[0] assert first < target < second graph = {} conditional = {} for pc, (op, arg) in instructions.items(): assert op not in ('br', 'blr'), 'indirect body control transfer needs a separate proof' if op == 'ret': successors = [] elif op == 'b': destination = int(arg, 0) successors = [destination] if destination in instructions else [] if not successors: assert any(r['address'] == destination and r['size'] for r in rows) elif op.startswith('b.') or op in ('cbz', 'cbnz', 'tbz', 'tbnz'): destination = int(arg.split(',')[-1].strip(), 0) assert destination in instructions successors = [destination, pc + 4] conditional[pc] = successors else: successors = [pc + 4] assert all(s in instructions for s in successors) graph[pc] = successors def reaches(start, destination, removed=None): seen, pending = set(), [start] while pending: pc = pending.pop() if pc == removed or pc in seen: continue if pc == destination: return True seen.add(pc) pending.extend(graph[pc]) return False assert reaches(body['address'], target) assert not reaches(body['address'], target, removed=first), 'old real wake dominates receipt construction' assert not reaches(body['address'], second, removed=target), 'receipt construction dominates current real wake' gates = [] for pc, successors in conditional.items(): if not first < pc < target: continue paths = [reaches(s, target) for s in successors] if paths.count(True) == 1 and not reaches(body['address'], target, removed=pc): gates.append(dict(address=pc, instruction=instructions[pc], acceptedSuccessor=successors[paths.index(True)], refusedSuccessor=successors[paths.index(False)])) # Nineteen selected branches cover the wake discriminants, returned wait, # process record/snapshot, frame store and complete authority audit gates. assert len(gates) == 19, len(gates) gate_addresses = {g['address'] for g in gates} # Bind each predicate's actual decoding before executing its exact selected # instruction slice with independent matching/mismatching owner fixtures. assert instructions[first + 4] == ('ldr', 'x8, [sp, #0x15f8]') assert instructions[first + 12][0] == 'b.eq' and first + 12 in gate_addresses assert instructions[first + 16] == ('cmp', 'x8, #0x2') assert instructions[first + 20][0] == 'b.ne' and first + 20 in gate_addresses assert instructions[first + 24] == ('ldrb', 'w8, [x23, #0x28]') assert instructions[first + 40][0] == 'b.ne' and first + 40 in gate_addresses stack = 0x70000000 predicate_cases = [] def evaluate(label, start, stop, memory, registers, expected_refusal): m = Machine(instructions, [(stack, bytes(65536))], {}) m.sp = stack for offset, value, size in memory: m.write(stack + offset, size, value) for reg, value in registers.items(): m.assign(reg, value) m.run(start, stop) op, args = instructions[stop] assert op in ('b.ne', 'b.eq') taken = m.condition(op[2:]) branch_target = int(args, 0) successor = branch_target if taken else stop + 4 refusal = not reaches(successor, target) assert refusal == expected_refusal, label predicate_cases.append(dict(label=label, start=start, branch=stop, refused=refusal)) for tag in [0, 1, 2, (1 << 64) - 1]: evaluate('wake Ok tag ' + str(tag), first + 4, first + 12, [(0x15f8, tag, 8)], {}, tag == (1 << 64) - 1) evaluate('wake Before tag ' + str(tag), first + 16, first + 20, [], {'x8': tag}, tag != 2) for error in range(14): evaluate('wake error variant ' + str(error), first + 24, first + 40, [(0x15f8 + 0x28, error, 1)], {'x23': stack + 0x15f8}, error != 3) # Complete seven-word central Audit equality before unsafe receipt creation. final_gate = gates[-1]['address'] assert instructions[final_gate][0] == 'b.ne' audit_start = final_gate - 76 audit_ops = [instructions[pc][0] for pc in range(audit_start, final_gate, 4)] assert audit_ops.count('cmp') == 1 and audit_ops.count('ccmp') == 6 pairs = [(0x5b28, 0x40), (0x5b30, 0x38), (0x5b38, 0x30), (0x5b40, 0x28), (0x5b48, 0x20), (0x5b50, 0x18), (0x5b58, 0x48)] for changed in [-1, *range(7)]: memory = [] for i, (after, before) in enumerate(pairs): memory.extend([(before, 100 + i, 8), (after, 100 + i + (i == changed), 8)]) evaluate('central Audit field ' + str(changed), audit_start, final_gate, memory, {}, changed >= 0) # Current process snapshot's four words must all remain unchanged. snapshot_gates = [g for g in gates if instructions.get(g['address'] - 4) == ('cmp', 'x8, x9') and instructions.get(g['address'] - 8, ('', ''))[0] == 'ldr' and instructions.get(g['address'] - 12, ('', ''))[0] == 'ldr'] assert len(snapshot_gates) == 4 for i, gate in enumerate(snapshot_gates): pc = gate['address'] offsets = [int(re.search(r'#(0x[0-9a-f]+)', instructions[pc - delta][1])[1], 16) for delta in [12, 8]] for different in [False, True]: evaluate('process snapshot %d drift %s' % (i, different), pc - 12, pc, [(offsets[0], 55, 8), (offsets[1], 55 + different, 8)], {}, different) report = dict(status='PROCESS_STALE_COMPILED_GATES_PASSED', guestAccepted=False, productAccepted=False, scope='The actual process-round body CFG requires the old real wake call before receipt construction and receipt construction before the current wake. Selected dominating branches require Before(Stale), unchanged process snapshot and all seven central Audit words. Exact selected instruction slices reject differing host fixtures. Callee semantics, other owner comparisons and actual hardware behavior remain separate obligations; this is not whole-kernel verification or guest acceptance.', preflight=art(prepath), image=pre['artifacts']['image'], function=body, wakeCalls=wake_calls, receiptCall=target, dominatingGates=gates, predicateCases=predicate_cases, bodyDisassembly=art(out / 'body.txt'), harness=art(out / 'harness.py.txt'), interpreter=art(out / 'machine.py.txt')) (out / 'report.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(dict(status=report['status'], report=str(out / 'report.json'), gates=len(gates), predicateCases=len(predicate_cases)))) except BaseException: import traceback detail = traceback.format_exc() (out / 'report.json').write_text(json.dumps(dict(status='PROCESS_STALE_COMPILED_GATES_FAILED', guestAccepted=False, productAccepted=False, error=detail), indent=2) + '\n') print(str(out / 'report.json'), file=sys.stderr) print(detail, file=sys.stderr) sys.exit(1)