From 4887c2f996d20e0277cd084d0441a967965a8430 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:02:43 +0100 Subject: [PATCH 01/28] [skip ci] test(winebot): add bounded public Freeciv surrogate workflow --- .../surrogate-freeciv-observatory.yml | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 .github/workflows/surrogate-freeciv-observatory.yml diff --git a/.github/workflows/surrogate-freeciv-observatory.yml b/.github/workflows/surrogate-freeciv-observatory.yml new file mode 100644 index 00000000..e38e73b6 --- /dev/null +++ b/.github/workflows/surrogate-freeciv-observatory.yml @@ -0,0 +1,57 @@ +name: Freeciv native-surrogate observatory qualification +on: + pull_request: + paths: + - '.github/workflows/surrogate-freeciv-observatory.yml' + - 'qualification/surrogates/freeciv/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: surrogate-freeciv-${{ github.ref }} + cancel-in-progress: true + +jobs: + native-source-known: + runs-on: ubuntu-24.04 + timeout-minutes: 12 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + seed: [42, 43] + steps: + - name: Checkout isolated public source without persisted credentials + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + + - name: Offline synthetic contract negatives + run: python3 qualification/surrogates/freeciv/test_contract.py -v + + - name: Install game and sensors on disposable runner + env: + DEBIAN_FRONTEND: noninteractive + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends freeciv-server=3.1.0+ds-1build5 strace + /usr/games/freeciv-server --version + + - name: Real Freeciv process, memory, socket, file and save transaction + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/surrogate-public" + python3 qualification/surrogates/freeciv/probe.py \ + --seed "${{ matrix.seed }}" --output "$RUNNER_TEMP/surrogate-public/freeciv-native-${{ matrix.seed }}.json" + + - name: Emit sanitized source-known evidence only + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: freeciv-native-surrogate-public-v1-seed-${{ matrix.seed }} + path: ${{ runner.temp }}/surrogate-public/*.json + if-no-files-found: ignore + retention-days: 3 From 405655b991c5a9d360ffa86026c327513b358d07 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:02:57 +0100 Subject: [PATCH 02/28] [skip ci] docs: record Freeciv surrogate scope and acceptance --- qualification/surrogates/freeciv/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 qualification/surrogates/freeciv/README.md diff --git a/qualification/surrogates/freeciv/README.md b/qualification/surrogates/freeciv/README.md new file mode 100644 index 00000000..4dbd8c2b --- /dev/null +++ b/qualification/surrogates/freeciv/README.md @@ -0,0 +1,19 @@ +# Freeciv source-known surrogate qualification (public-safe) + +**Purpose:** exercise a *real* freely licensed turn-based-strategy executable instead of fabricating original-SMAC parity. This is a bounded native Linux Freeciv server pilot, NOT a Wine, QEMU, 1999 Freeciv binary, Ghidra-native or Alpha Centauri oracle. + +**Owner and DLE:** `mark-e-deyoung/ghidra-tools#4` (cross-target observatory), `mark-e-deyoung/reverse-smac#37` (SMAC acceptance and owner-deferred game work). This public WineBot runner-side implementation is independent from private `ghidra-tools` candidate code; no private source has been transferred to public CI. + +**Target:** Ubuntu 24.04 official `freeciv-server` apt package (a current descendant of a 1990s turn-based Civilization-style game). Requires package and binary digest in each receipt; do not confuse with 1999 Freeciv 1.9.0, for which source archives exist. License: GPL-2.0-or-later. + +**Vantage points:** source-known ELF identity, native live process and Linux memory-map region count/RSS, loopback TCP listen/connect, `strace` file/IPC/network/process operations, real in-game `save` command and on-disk output digest, clean termination/cleanup. Sensor data is aggregated into a minimal, no-private-bytes JSON receipt. A positive receipt is a qualified native process/I/O sensor chain, *not* a validated game turn or semantic game-state equivalence. + +**Execution:** disposable public `ubuntu-24.04` GitHub-hosted job. Build/runtime dependencies installed only inside that ephemeral runner; game binds `127.0.0.1` and does not announce itself; non-loopback IPv4 connect observations fail; process is timed out and all raw syscall paths/logs/saves are disposed. Public artifact contains only source-known version, hashes and aggregate counts; no raw game files, process memory, private paths, credentials or runtime captures. + +**Local synthetic regression:** `python3 qualification/surrogates/freeciv/test_contract.py`. + +**Native runner:** `python3 qualification/surrogates/freeciv/probe.py --seed 42 --output "$RUNNER_TEMP/freeciv42.json"` after installing `freeciv-server strace` in an Ubuntu 24.04 ephemeral environment. It intentionally exits nonzero if game startup, loopback, memory sensing, syscall trace, save, or clean shutdown cannot be proven. Check GitHub Actions artifacts/receipts before claiming success; do not silently mark failed native probes green. + +**Next independent experiment:** add a real client to generate packet payloads and UI observations; qualify Ghidra headless mapping of source-matched ELF; migrate from native Linux to Wine/PE as a separate differential workcell. Do not execute licensed SMAC/SMAX or Windows 98 binaries until `reverse-smac#37` authorizes that phase. + +**Independent batches:** the public workflow qualifies seeds 42 and 43 as two separate jobs in parallel, with independent disposable process state and evidence. Their outputs are not byte-for-byte parity claims. From 7a5e9e14e1f96d928dbdcf1fd944814f932714ba Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:03:14 +0100 Subject: [PATCH 03/28] [skip ci] test: bounded real Freeciv process and I/O observer --- qualification/surrogates/freeciv/probe.py | 235 ++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 qualification/surrogates/freeciv/probe.py diff --git a/qualification/surrogates/freeciv/probe.py b/qualification/surrogates/freeciv/probe.py new file mode 100644 index 00000000..033b0df5 --- /dev/null +++ b/qualification/surrogates/freeciv/probe.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Bounded public-source Freeciv *real process* observation, never SMAC parity. + +Deliberately independent of private observatory code. Requires an ephemeral +Linux runner with Freeciv and strace installed. Output is a public-safe manifest; +raw strace, server logs and saves remain on ephemeral scratch and are deleted. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time + +SCHEMA = "freeciv-surrogate-native/v0.1" +REQUIRED_SIGNALS = ("server_started", "loopback_tcp", "memory_maps", "file_syscalls", "save_created", "clean_stop", "no_external_ipv4_connect") + + +def digest(p): + h = hashlib.sha256() + with Path(p).open("rb") as f: + for block in iter(lambda: f.read(65536), b""): + h.update(block) + return h.hexdigest() + + +def proc_descendant_pids(ppid): + """Return process IDs belonging to the trace process's child tree.""" + queue = [ppid] + result = [] + seen = set() + while queue: + current = queue.pop(0) + if current in seen: + continue + seen.add(current) + children = Path(f"/proc/{current}/task/{current}/children") + try: + raw = children.read_text(encoding="ascii") + except (OSError, ValueError): + continue + for child in raw.split(): + try: + pid = int(child) + except ValueError: + continue + result.append(pid) + queue.append(pid) + return result + + +def safe_proc_snapshot(trace_pid): + """Counts only. Never export raw addresses, maps, env, fds, or command lines.""" + for pid in proc_descendant_pids(trace_pid): + try: + comm = Path(f"/proc/{pid}/comm").read_text().strip() + if "freeciv" not in comm.lower() and "civserver" not in comm.lower(): + continue + lines = Path(f"/proc/{pid}/maps").read_text().splitlines() + status = Path(f"/proc/{pid}/status").read_text() + rss = re.search(r"^VmRSS:\s*(\d+) kB$", status, re.M) + return {"observed": True, "map_regions": len(lines), "rss_kib": int(rss.group(1)) if rss else None} + except (FileNotFoundError, ProcessLookupError, PermissionError): + continue + return {"observed": False, "map_regions": 0, "rss_kib": None} + + +def loopback_ready(port, deadline=4): + expiry = time.monotonic() + deadline + while time.monotonic() < expiry: + try: + with socket.create_connection(("127.0.0.1", port), timeout=.2): + return True + except OSError: + time.sleep(.1) + return False + + +def send(proc, line): + if proc.poll() is not None or proc.stdin is None: + return False + try: + proc.stdin.write((line + "\n").encode("ascii")) + proc.stdin.flush() + return True + except (BrokenPipeError, OSError, ValueError): + return False + + +def trace_classification(folder): + """Minimal privacy-safe counts; no raw syscalls or file paths retained.""" + counts = {"file_syscalls": 0, "network_syscalls": 0, "process_syscalls": 0} + unexpected_external = 0 + for p in Path(folder).glob("syscalls.*"): + text = p.read_text(errors="replace") + for line in text.splitlines(): + if "connect(" in line and "AF_INET" in line and "inet_addr(" in line: + m = re.search(r'inet_addr\("([0-9.]+)"\)', line) + if m and not m.group(1).startswith("127."): + unexpected_external += 1 + counts["file_syscalls"] += sum(text.count(x) for x in ("openat(", "statx(", "newfstatat(", "readlink(")) + counts["network_syscalls"] += sum(text.count(x) for x in ("socket(", "bind(", "listen(", "connect(", "accept(")) + counts["process_syscalls"] += sum(text.count(x) for x in ("clone(", "execve(", "fork(")) + counts["non_loopback_ipv4_connects"] = unexpected_external + return counts + + +def inspect_saves(folder): + manifests = [] + for p in sorted(Path(folder).rglob("*")): + if p.is_file() and "surrogate" in p.name and p.suffix.lower() in (".sav", ".gz", ".bz2", ".xz", ".zst"): + manifests.append({"bytes": p.stat().st_size, "sha256": digest(p)}) + return manifests + + +def run_native(scratch, seed, port=5557): + server = shutil.which("freeciv-server") or ("/usr/games/freeciv-server" if Path("/usr/games/freeciv-server").is_file() else None) + trace = shutil.which("strace") + if not server or not trace: + raise RuntimeError("FREECIV_OR_STRACE_MISSING") + root = Path(scratch) + root.mkdir(parents=True, exist_ok=True) + saves = root / "saves" + saves.mkdir() + args = [server, "--bind", "127.0.0.1", "--Announce", "none", + "--port", str(port), "--saves", str(saves)] + # The package-installed executable must be real and nonempty. + binary = Path(server).resolve() + version = subprocess.check_output([server, "--version"], timeout=6, text=True).strip().splitlines()[:3] + trace_cmd = [trace, "-ff", "-qq", "-s", "96", "-o", str(root / "syscalls"), + "-e", "trace=%file,%network,%process"] + args + log_path = root / "server.log" + observed = {"server_started": False, "loopback_tcp": False, "memory_maps": False, + "file_syscalls": False, "save_created": False, "clean_stop": False, + "no_external_ipv4_connect": False} + snapshots = [] + trace_info = {} + exit_code = None + started = time.monotonic() + with log_path.open("wb") as log: + proc = subprocess.Popen(trace_cmd, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + cwd=root, start_new_session=True, + env={**os.environ, "HOME": str(root), "LANG": "C.UTF-8", "TZ": "UTC"}) + try: + observed["server_started"] = loopback_ready(port) + snap = safe_proc_snapshot(proc.pid) + observed["memory_maps"] = snap["observed"] and snap["map_regions"] > 0 + snapshots.append(snap) + for cmd in ("set minplayers 0", "set aifill 2", f"set gameseed {seed}", + f"set mapseed {seed}", "set timeout 1", "create Caesar", + "aitoggle Caesar", "start"): + if not send(proc, cmd): + break + time.sleep(.06) + # The AI game runs for bounded time; neither an internet connection nor GUI is required. + time.sleep(3) + send(proc, "save surrogate-a") + time.sleep(1) + send(proc, "save surrogate-b") + time.sleep(1) + send(proc, "quit") + try: + exit_code = proc.wait(timeout=9) + except subprocess.TimeoutExpired: + proc.terminate() + try: + exit_code = proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + exit_code = proc.wait(timeout=3) + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=3) + if proc.stdin: + proc.stdin.close() + trace_info = trace_classification(root) + observed["file_syscalls"] = trace_info["file_syscalls"] > 0 + observed["no_external_ipv4_connect"] = trace_info["non_loopback_ipv4_connects"] == 0 + save_info = inspect_saves(saves) + observed["save_created"] = any(x["bytes"] >= 128 for x in save_info) + observed["loopback_tcp"] = observed["server_started"] + observed["clean_stop"] = exit_code == 0 + return { + "schema": SCHEMA, "status": "PASS" if all(observed.get(k, False) for k in REQUIRED_SIGNALS) else "FAIL", + "execution_class": "REAL_OPEN_SOURCE_NATIVE_ELF_NOT_SMAC_ORACLE", + "source": "https://github.com/freeciv/freeciv", + "license": "GPL-2.0-or-later", + "binary_sha256": digest(binary), + "version": version, + "seed": seed, + "loopback_only": observed["no_external_ipv4_connect"], + "signals": observed, + "trace_counts": trace_info, + "memory": snapshots, + "save_digests": save_info, + "elapsed_s": round(time.monotonic() - started, 2), + "exit_code": exit_code, + "limitations": [ + "No source-matched symbol binding or original-1999 binary parity", + "No Ghidra/Trace RMI, Wine, UI pixels, or full packet payload capture", + "Kernel/file/network syscall counts are not semantic game-state proof", + "No proprietary game/OS files or private observatory source were used", + ], + } + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--output", required=True, help="Public-safe JSON result file") + ap.add_argument("--seed", type=int, choices=(42, 43), default=42) + args = ap.parse_args(argv) + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="freeciv-observatory-") as temp: + try: + result = run_native(temp, args.seed) + except (OSError, RuntimeError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: + result = {"schema": SCHEMA, "status": "ERROR", "error_code": type(exc).__name__, + "error_class": str(exc) if isinstance(exc, RuntimeError) else "NATIVE_PROBE_FAILURE", + "execution_class": "NOT_QUALIFIED", "seed": args.seed} + output.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n") + print(json.dumps({"status": result["status"], "signals": result.get("signals", {}), + "seed": args.seed, "out": str(output)}, sort_keys=True)) + return 0 if result["status"] == "PASS" else 1 + + +if __name__ == "__main__": + sys.exit(main()) From 3160a208f29b853e450a23d35707e2eb413e7999 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:03:27 +0100 Subject: [PATCH 04/28] [skip ci] test: add source-neutral Freeciv observer negative controls --- .../surrogates/freeciv/test_contract.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 qualification/surrogates/freeciv/test_contract.py diff --git a/qualification/surrogates/freeciv/test_contract.py b/qualification/surrogates/freeciv/test_contract.py new file mode 100644 index 00000000..8d77d5d3 --- /dev/null +++ b/qualification/surrogates/freeciv/test_contract.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Source-neutral offline tests, independent of Freeciv and private source.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("freeciv_probe", Path(__file__).with_name("probe.py")) +probe = importlib.util.module_from_spec(spec) +spec.loader.exec_module(probe) + + +class ContractTests(unittest.TestCase): + def test_required_signal_contract(self): + self.assertEqual(len(probe.REQUIRED_SIGNALS), 7) + self.assertEqual(len(set(probe.REQUIRED_SIGNALS)), len(probe.REQUIRED_SIGNALS)) + + def test_digest_mutation(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) / "f.bin" + p.write_bytes(b"hello") + h = probe.digest(p) + self.assertEqual(len(h), 64) + p.write_bytes(b"jello") + self.assertNotEqual(probe.digest(p), h) + + def test_trace_classification_does_not_exfiltrate_content(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) / "syscalls.99" + p.write_text('openat(123, "/secret/private/something")\n' + 'socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)\n' + 'bind(4,...)\n') + counts = probe.trace_classification(td) + self.assertEqual(counts["file_syscalls"], 1) + self.assertEqual(counts["network_syscalls"], 2) + self.assertNotIn("secret", str(counts)) + + def test_save_scrub(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) / "surrogate-a.sav.xz" + p.write_bytes(b"this is a synthetic save") + saves = probe.inspect_saves(td) + self.assertEqual(len(saves), 1) + self.assertEqual(set(saves[0]), {"bytes", "sha256"}) + self.assertNotIn("surrogate-a", str(saves)) + + def test_external_connect_does_not_pass_egress_guard(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td)/"syscalls.1" + p.write_text('connect(4, {sa_family=AF_INET, sin_port=htons(443), sin_addr=inet_addr("8.8.8.8")}, 16)\n') + counts = probe.trace_classification(td) + self.assertEqual(counts["non_loopback_ipv4_connects"], 1) + + def test_non_save_exclusion(self): + with tempfile.TemporaryDirectory() as td: + Path(td,"metadata.json").write_text("{}") + Path(td,"surrogate-a.log").write_text("private") + self.assertEqual(probe.inspect_saves(td), []) + + def test_socket_failure_is_not_success(self): + self.assertFalse(probe.loopback_ready(1, deadline=.05)) + + +if __name__ == "__main__": + unittest.main() From 7adf120e418743c27080d386396d2e9d9a2111df Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:04:15 +0100 Subject: [PATCH 05/28] docs(winebot): distinguish source-local preflight from public Freeciv native qualification --- qualification/surrogates/freeciv/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/qualification/surrogates/freeciv/README.md b/qualification/surrogates/freeciv/README.md index 4dbd8c2b..49811a11 100644 --- a/qualification/surrogates/freeciv/README.md +++ b/qualification/surrogates/freeciv/README.md @@ -17,3 +17,5 @@ **Next independent experiment:** add a real client to generate packet payloads and UI observations; qualify Ghidra headless mapping of source-matched ELF; migrate from native Linux to Wine/PE as a separate differential workcell. Do not execute licensed SMAC/SMAX or Windows 98 binaries until `reverse-smac#37` authorizes that phase. **Independent batches:** the public workflow qualifies seeds 42 and 43 as two separate jobs in parallel, with independent disposable process state and evidence. Their outputs are not byte-for-byte parity claims. + +**Qualification status at admission:** seven offline source-neutral contract tests passed in a disposable session; GitHub native game execution is **NOT_RUN until the public PR jobs report terminal evidence**. Neither runner selection nor a dispatched workflow alone establishes gameplay or observatory integration. From 49e1f5fbefc94e6f144e89cb8b324be57466f7bd Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:08:32 +0100 Subject: [PATCH 06/28] [skip ci] fix(freeciv): capture version from stderr and fail on missing provenance --- qualification/surrogates/freeciv/probe.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/probe.py b/qualification/surrogates/freeciv/probe.py index 033b0df5..3c3bb36e 100644 --- a/qualification/surrogates/freeciv/probe.py +++ b/qualification/surrogates/freeciv/probe.py @@ -119,6 +119,16 @@ def inspect_saves(folder): return manifests +def capture_version(executable): + """Freeciv 3.x writes --version to stderr on some builds.""" + result = subprocess.run([executable, "--version"], stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, timeout=6, check=True) + lines = result.stdout.strip().splitlines() + if not lines: + raise RuntimeError("FREECIV_VERSION_UNOBSERVED") + return lines[:3] + + def run_native(scratch, seed, port=5557): server = shutil.which("freeciv-server") or ("/usr/games/freeciv-server" if Path("/usr/games/freeciv-server").is_file() else None) trace = shutil.which("strace") @@ -132,7 +142,7 @@ def run_native(scratch, seed, port=5557): "--port", str(port), "--saves", str(saves)] # The package-installed executable must be real and nonempty. binary = Path(server).resolve() - version = subprocess.check_output([server, "--version"], timeout=6, text=True).strip().splitlines()[:3] + version = capture_version(server) trace_cmd = [trace, "-ff", "-qq", "-s", "96", "-o", str(root / "syscalls"), "-e", "trace=%file,%network,%process"] + args log_path = root / "server.log" From 33bbeb339228d892424067a9ae4e0d357fedbb69 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:09:14 +0100 Subject: [PATCH 07/28] test(winebot): independently reject missing Freeciv version and read stderr provenance --- qualification/surrogates/freeciv/test_contract.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/qualification/surrogates/freeciv/test_contract.py b/qualification/surrogates/freeciv/test_contract.py index 8d77d5d3..e049541f 100644 --- a/qualification/surrogates/freeciv/test_contract.py +++ b/qualification/surrogates/freeciv/test_contract.py @@ -51,6 +51,21 @@ def test_external_connect_does_not_pass_egress_guard(self): counts = probe.trace_classification(td) self.assertEqual(counts["non_loopback_ipv4_connects"], 1) + def test_version_collected_from_stderr(self): + with tempfile.TemporaryDirectory() as td: + script = Path(td) / "version-script" + script.write_text('#!/bin/sh\nprintf "Version 3.1.0\\n" >&2\n') + script.chmod(0o700) + self.assertEqual(probe.capture_version(str(script)), ["Version 3.1.0"]) + + def test_blank_version_rejected(self): + with tempfile.TemporaryDirectory() as td: + script = Path(td) / "blank-version-script" + script.write_text('#!/bin/sh\nexit 0\n') + script.chmod(0o700) + with self.assertRaisesRegex(RuntimeError, "FREECIV_VERSION_UNOBSERVED"): + probe.capture_version(str(script)) + def test_non_save_exclusion(self): with tempfile.TemporaryDirectory() as td: Path(td,"metadata.json").write_text("{}") From 62b82d1738278fcf73d7870a47b7390b57d07f1d Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:11:29 +0100 Subject: [PATCH 08/28] [skip ci] style(freeciv): align observer imports with project lint rules --- qualification/surrogates/freeciv/probe.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/probe.py b/qualification/surrogates/freeciv/probe.py index 3c3bb36e..304d4449 100644 --- a/qualification/surrogates/freeciv/probe.py +++ b/qualification/surrogates/freeciv/probe.py @@ -9,7 +9,6 @@ import hashlib import json import os -from pathlib import Path import re import shutil import socket @@ -17,6 +16,7 @@ import sys import tempfile import time +from pathlib import Path SCHEMA = "freeciv-surrogate-native/v0.1" REQUIRED_SIGNALS = ("server_started", "loopback_tcp", "memory_maps", "file_syscalls", "save_created", "clean_stop", "no_external_ipv4_connect") From c322e168d5181adbd5ac098806d50a05a4632098 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:11:43 +0100 Subject: [PATCH 09/28] style(winebot): satisfy Ruff import contract for real-game surrogate --- qualification/surrogates/freeciv/test_contract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/test_contract.py b/qualification/surrogates/freeciv/test_contract.py index e049541f..05429acb 100644 --- a/qualification/surrogates/freeciv/test_contract.py +++ b/qualification/surrogates/freeciv/test_contract.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """Source-neutral offline tests, independent of Freeciv and private source.""" import importlib.util -from pathlib import Path import tempfile import unittest +from pathlib import Path spec = importlib.util.spec_from_file_location("freeciv_probe", Path(__file__).with_name("probe.py")) probe = importlib.util.module_from_spec(spec) From 214f907912f629ae8e7aae33562d245472152b2a Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:16:54 +0100 Subject: [PATCH 10/28] test(freeciv): source-known ELF to live maps identity observer [skip ci] --- .../surrogates/freeciv/elf_map_probe.py | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 qualification/surrogates/freeciv/elf_map_probe.py diff --git a/qualification/surrogates/freeciv/elf_map_probe.py b/qualification/surrogates/freeciv/elf_map_probe.py new file mode 100644 index 00000000..78e65cf6 --- /dev/null +++ b/qualification/surrogates/freeciv/elf_map_probe.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Public-safe, read-only ELF->live-/proc maps correlation for source-known native surrogate. + +This is an ELF segment/load-map identity check, NOT PC sampling, instruction +coverage, Ghidra function attribution, or original-game semantic proof. +No raw addresses, paths, maps, memory, or executable content are emitted. +""" +from __future__ import annotations + +import hashlib +import os +import re +import struct +from pathlib import Path + +MAX_PROGRAM_HEADERS = 256 +MAX_MAP_BYTES = 1 << 20 +MAP_PATTERN = re.compile(r"^([0-9a-f]+)-([0-9a-f]+)\\s+(\\S{4})\\s+([0-9a-f]+)\\s+([0-9a-f]+):([0-9a-f]+)\\s+(\\d+)(?:\\s|$)") + + +class CorrelationError(ValueError): + """Non-sensitive, stable type for fail-closed correlation.""" + + +def file_digest(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def elf_segments(path): + """Extract bounded little-endian ELF64 PT_LOAD file-backed segments.""" + with open(path, "rb") as fh: + hdr = fh.read(64) + if len(hdr) < 64 or hdr[:4] != b"\\x7fELF" or hdr[4] != 2 or hdr[5] != 1: + raise CorrelationError("ELF64_LITTLE_ENDIAN_REQUIRED") + fields = struct.unpack_from(" limit or phcount * phsize > limit - phoff: + raise CorrelationError("ELF_PROGRAM_HEADERS_OUT_OF_BOUNDS") + fh.seek(phoff) + segments = [] + for _ in range(phcount): + raw = fh.read(phsize) + if len(raw) != phsize: + raise CorrelationError("ELF_PROGRAM_HEADERS_TRUNCATED") + typ, flags, offset, vaddr, _paddr, filesz, memsz, _align = struct.unpack(" memsz or offset > limit or filesz > limit - offset: + if filesz: + raise CorrelationError("ELF_LOAD_SEGMENT_INVALID") + continue + segments.append((offset, vaddr, filesz, flags)) + if not segments: + raise CorrelationError("ELF_FILE_BACKED_LOAD_SEGMENTS_MISSING") + return kind, segments + + +def map_rows(text, device, inode): + """Select only matching file identities; avoid matching on spoofable paths.""" + result = [] + for line in text.splitlines(): + match = MAP_PATTERN.match(line) + if not match: + continue + lo, hi, perm, off, maj, minor, ino = match.groups() + if int(ino) != inode or (int(maj, 16), int(minor, 16)) != device: + continue + low, high = int(lo, 16), int(hi, 16) + if high <= low or perm[0] != "r": + continue + result.append((low, high, int(off, 16), perm)) + return result + + +def correlate_map_text(text, segments, device, inode, kind, page_size=4096): + if page_size <= 0 or page_size & (page_size - 1): + raise CorrelationError("PAGE_SIZE_INVALID") + rows = map_rows(text, device, inode) + if not rows: + raise CorrelationError("NO_EXACT_INODE_DEVICE_EXECUTABLE_MAPPING") + votes = {} + for index, (start, end, mapoff, perms) in enumerate(rows): + for off, vaddr, filesz, _flags in segments: + seg_start = off & ~(page_size - 1) + seg_end = (off + filesz + page_size - 1) & ~(page_size - 1) + if not (seg_start <= mapoff < seg_end): + continue + # Linux file VMA: start = load_bias + (p_vaddr-p_offset) + mapoff. + bias = start - (vaddr - off + mapoff) + if bias < 0 or bias % page_size or (kind == 2 and bias != 0): + continue + votes.setdefault(bias, set()).add(index) + if not votes: + raise CorrelationError("NO_CONSISTENT_LOAD_BIAS") + best = max(len(v) for v in votes.values()) + winners = [bias for bias, support in votes.items() if len(support) == best] + if len(winners) != 1 or best < 2: + raise CorrelationError("ELF_LOAD_BIAS_AMBIGUOUS_OR_INSUFFICIENT") + chosen = winners[0] + matched = votes[chosen] + exec_matched = {index for index in matched if "x" in rows[index][3]} + if not exec_matched: + raise CorrelationError("NO_EXECUTABLE_PT_LOAD_MATCH") + # All readable executable-file mappings must cohere with one inferred bias. + if len(matched) != len(rows): + raise CorrelationError("ELF_MAPS_INCONSISTENT_WITH_LOAD_BIAS") + return {"status": "CORRELATED_ELF_LOAD_MAP_NOT_PC", "matching_file_maps": len(rows), + "matched_load_maps": len(matched), "executable_maps": len(exec_matched), + "file_backed_segments": len(segments), "one_load_bias": True, + "raw_addresses_exported": False, "pc_observed": False} + + +def observe_pid(pid, executable, expected_sha256): + """Read-only PID and exact ELF identity, fail closed without publicizing paths.""" + executable = Path(executable) + st = executable.stat() + pst = Path(f"/proc/{int(pid)}/exe").stat() + if (st.st_dev, st.st_ino) != (pst.st_dev, pst.st_ino): + raise CorrelationError("PROCESS_EXECUTABLE_IDENTITY_MISMATCH") + if file_digest(executable) != expected_sha256: + raise CorrelationError("EXECUTABLE_SHA256_MISMATCH") + kind, segments = elf_segments(executable) + map_path = Path(f"/proc/{int(pid)}/maps") + with map_path.open("rb") as fh: + data = fh.read(MAX_MAP_BYTES + 1) + if len(data) > MAX_MAP_BYTES: + raise CorrelationError("PROC_MAPS_CAPACITY_EXCEEDED") + return correlate_map_text(data.decode("ascii", errors="replace"), segments, + (os.major(st.st_dev), os.minor(st.st_dev)), st.st_ino, + kind, os.sysconf("SC_PAGE_SIZE")) From 43d0f67481b8484ca647161f7c9ff985cddfffc9 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:17:30 +0100 Subject: [PATCH 11/28] fix(freeciv): preserve source-verified Python regex/ELF escape literals [skip ci] --- qualification/surrogates/freeciv/elf_map_probe.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/qualification/surrogates/freeciv/elf_map_probe.py b/qualification/surrogates/freeciv/elf_map_probe.py index 78e65cf6..ea102513 100644 --- a/qualification/surrogates/freeciv/elf_map_probe.py +++ b/qualification/surrogates/freeciv/elf_map_probe.py @@ -15,7 +15,7 @@ MAX_PROGRAM_HEADERS = 256 MAX_MAP_BYTES = 1 << 20 -MAP_PATTERN = re.compile(r"^([0-9a-f]+)-([0-9a-f]+)\\s+(\\S{4})\\s+([0-9a-f]+)\\s+([0-9a-f]+):([0-9a-f]+)\\s+(\\d+)(?:\\s|$)") +MAP_PATTERN = re.compile(r"^([0-9a-f]+)-([0-9a-f]+)\s+(\S{4})\s+([0-9a-f]+)\s+([0-9a-f]+):([0-9a-f]+)\s+(\d+)(?:\s|$)") class CorrelationError(ValueError): @@ -34,7 +34,7 @@ def elf_segments(path): """Extract bounded little-endian ELF64 PT_LOAD file-backed segments.""" with open(path, "rb") as fh: hdr = fh.read(64) - if len(hdr) < 64 or hdr[:4] != b"\\x7fELF" or hdr[4] != 2 or hdr[5] != 1: + if len(hdr) < 64 or hdr[:4] != b"\x7fELF" or hdr[4] != 2 or hdr[5] != 1: raise CorrelationError("ELF64_LITTLE_ENDIAN_REQUIRED") fields = struct.unpack_from(" Date: Mon, 16 Nov 2026 18:17:58 +0100 Subject: [PATCH 12/28] test(freeciv): real ELF pid/maps identity and ASLR negatives [skip ci] --- .../surrogates/freeciv/test_elf_map_probe.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 qualification/surrogates/freeciv/test_elf_map_probe.py diff --git a/qualification/surrogates/freeciv/test_elf_map_probe.py b/qualification/surrogates/freeciv/test_elf_map_probe.py new file mode 100644 index 00000000..4aa9e327 --- /dev/null +++ b/qualification/surrogates/freeciv/test_elf_map_probe.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""No Freeciv or private source required; tests include real public /bin/sleep.""" +import importlib.util +import pathlib +import subprocess +import unittest + +spec = importlib.util.spec_from_file_location("elf_map_probe", pathlib.Path(__file__).with_name("elf_map_probe.py")) +probe = importlib.util.module_from_spec(spec) +spec.loader.exec_module(probe) + + +class LoadMapTests(unittest.TestCase): + def test_live_sleep_elf_and_maps(self): + exe = "/usr/bin/sleep" if pathlib.Path("/usr/bin/sleep").exists() else "/bin/sleep" + child = subprocess.Popen([exe, "2"]) + try: + record = probe.observe_pid(child.pid, exe, probe.file_digest(exe)) + self.assertEqual(record["status"], "CORRELATED_ELF_LOAD_MAP_NOT_PC") + self.assertGreaterEqual(record["matching_file_maps"], 2) + self.assertFalse(record["pc_observed"]) + self.assertFalse(record["raw_addresses_exported"]) + finally: + child.terminate() + child.wait(timeout=4) + + def test_wrong_hash_refuses_real_pid(self): + exe = "/usr/bin/sleep" if pathlib.Path("/usr/bin/sleep").exists() else "/bin/sleep" + child = subprocess.Popen([exe, "2"]) + try: + with self.assertRaisesRegex(probe.CorrelationError, "EXECUTABLE_SHA256_MISMATCH"): + probe.observe_pid(child.pid, exe, "0" * 64) + finally: + child.terminate() + child.wait(timeout=4) + + def test_identity_negative(self): + with self.assertRaisesRegex(probe.CorrelationError, "NO_EXACT_INODE"): + probe.correlate_map_text("1000-2000 r-xp 00000000 00:01 77 /a\n", [(0,0,4096,5)], (0,1), 78, 3) + + def test_synthetic_aslr_and_wrong_offset(self): + segment = [(0,0,8192,5)] + base = 0x55000000 + text = (f"{base:08x}-{base+4096:08x} r--p 00000000 08:02 42 /a\n" + f"{base+4096:08x}-{base+8192:08x} r-xp 00001000 08:02 42 /a\n") + record = probe.correlate_map_text(text, segment, (8,2), 42, 3) + self.assertEqual(record["matched_load_maps"], 2) + bad = text.replace("00001000", "00003000") + with self.assertRaises(probe.CorrelationError): + probe.correlate_map_text(bad, segment, (8,2), 42, 3) + + def test_bad_elf_refuses(self): + with self.assertRaisesRegex(probe.CorrelationError, "ELF64"): + import tempfile + with tempfile.NamedTemporaryFile() as f: + f.write(b"not an elf"); f.flush() + probe.elf_segments(f.name) + + def test_bad_page_size_refuses(self): + with self.assertRaisesRegex(probe.CorrelationError, "PAGE_SIZE_INVALID"): + probe.correlate_map_text("", [], (0,0), 0, 3, 1234) + + +if __name__ == "__main__": + unittest.main() From 57a00a62599b82067e14384be13dc72574536354 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:18:56 +0100 Subject: [PATCH 13/28] docs(test): qualify eight Freeciv native sensor signals including ELF load map [skip ci] --- qualification/surrogates/freeciv/test_contract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/test_contract.py b/qualification/surrogates/freeciv/test_contract.py index 05429acb..3f09569e 100644 --- a/qualification/surrogates/freeciv/test_contract.py +++ b/qualification/surrogates/freeciv/test_contract.py @@ -12,7 +12,7 @@ class ContractTests(unittest.TestCase): def test_required_signal_contract(self): - self.assertEqual(len(probe.REQUIRED_SIGNALS), 7) + self.assertEqual(len(probe.REQUIRED_SIGNALS), 8) self.assertEqual(len(set(probe.REQUIRED_SIGNALS)), len(probe.REQUIRED_SIGNALS)) def test_digest_mutation(self): From 05108b359794f2b0f333ec7dcbc59cef9882eb5d Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:19:03 +0100 Subject: [PATCH 14/28] docs(test): qualify eight Freeciv native sensor signals including ELF load map [skip ci] --- qualification/surrogates/freeciv/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/README.md b/qualification/surrogates/freeciv/README.md index 49811a11..222b5ac8 100644 --- a/qualification/surrogates/freeciv/README.md +++ b/qualification/surrogates/freeciv/README.md @@ -6,7 +6,7 @@ **Target:** Ubuntu 24.04 official `freeciv-server` apt package (a current descendant of a 1990s turn-based Civilization-style game). Requires package and binary digest in each receipt; do not confuse with 1999 Freeciv 1.9.0, for which source archives exist. License: GPL-2.0-or-later. -**Vantage points:** source-known ELF identity, native live process and Linux memory-map region count/RSS, loopback TCP listen/connect, `strace` file/IPC/network/process operations, real in-game `save` command and on-disk output digest, clean termination/cleanup. Sensor data is aggregated into a minimal, no-private-bytes JSON receipt. A positive receipt is a qualified native process/I/O sensor chain, *not* a validated game turn or semantic game-state equivalence. +**Vantage points:** source-known ELF identity, **ELF64 PT_LOAD segments correlated to actual Linux file-backed /proc/PID/maps by exact executable SHA256 and device/inode, one unambiguous ASLR load bias** (sanitized metadata only; no PC observed), native live process and Linux memory-map region count/RSS, loopback TCP listen/connect, `strace` file/IPC/network/process operations, real in-game `save` command and on-disk output digest, clean termination/cleanup. Sensor data is aggregated into a minimal, no-private-bytes JSON receipt. A positive receipt is a qualified native process/I/O sensor chain, *not* a validated game turn or semantic game-state equivalence. **Execution:** disposable public `ubuntu-24.04` GitHub-hosted job. Build/runtime dependencies installed only inside that ephemeral runner; game binds `127.0.0.1` and does not announce itself; non-loopback IPv4 connect observations fail; process is timed out and all raw syscall paths/logs/saves are disposed. Public artifact contains only source-known version, hashes and aggregate counts; no raw game files, process memory, private paths, credentials or runtime captures. @@ -14,6 +14,8 @@ **Native runner:** `python3 qualification/surrogates/freeciv/probe.py --seed 42 --output "$RUNNER_TEMP/freeciv42.json"` after installing `freeciv-server strace` in an Ubuntu 24.04 ephemeral environment. It intentionally exits nonzero if game startup, loopback, memory sensing, syscall trace, save, or clean shutdown cannot be proven. Check GitHub Actions artifacts/receipts before claiming success; do not silently mark failed native probes green. +**ELF load-map qualification:** `python3 qualification/surrogates/freeciv/test_elf_map_probe.py -v` runs six offline/public-safe tests including a real `/usr/bin/sleep` process, wrong-hash/device-inode, ASLR and malformed-ELF negatives. Success on a live Freeciv job proves the loader's file-backed mappings agree with the observed ELF; it does **not** prove program-counter sensing, Ghidra function provenance, source-line coverage, or same-era/SMAC parity. Public receipts include only status and counts, not raw addresses or paths. An ambiguous or missing map fails the native signal. + **Next independent experiment:** add a real client to generate packet payloads and UI observations; qualify Ghidra headless mapping of source-matched ELF; migrate from native Linux to Wine/PE as a separate differential workcell. Do not execute licensed SMAC/SMAX or Windows 98 binaries until `reverse-smac#37` authorizes that phase. **Independent batches:** the public workflow qualifies seeds 42 and 43 as two separate jobs in parallel, with independent disposable process state and evidence. Their outputs are not byte-for-byte parity claims. From 08e1ef790beccfb580c2e7822ae99479c3546b44 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:19:41 +0100 Subject: [PATCH 15/28] feat(freeciv): require SHA/inode-backed live ELF load-map coherence [skip ci] --- qualification/surrogates/freeciv/probe.py | 27 ++++++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/qualification/surrogates/freeciv/probe.py b/qualification/surrogates/freeciv/probe.py index 304d4449..7897836e 100644 --- a/qualification/surrogates/freeciv/probe.py +++ b/qualification/surrogates/freeciv/probe.py @@ -18,8 +18,10 @@ import time from pathlib import Path +import elf_map_probe + SCHEMA = "freeciv-surrogate-native/v0.1" -REQUIRED_SIGNALS = ("server_started", "loopback_tcp", "memory_maps", "file_syscalls", "save_created", "clean_stop", "no_external_ipv4_connect") +REQUIRED_SIGNALS = ("server_started", "loopback_tcp", "memory_maps", "elf_load_map", "file_syscalls", "save_created", "clean_stop", "no_external_ipv4_connect") def digest(p): @@ -55,7 +57,7 @@ def proc_descendant_pids(ppid): return result -def safe_proc_snapshot(trace_pid): +def safe_proc_snapshot(trace_pid, executable, expected_sha256): """Counts only. Never export raw addresses, maps, env, fds, or command lines.""" for pid in proc_descendant_pids(trace_pid): try: @@ -65,10 +67,19 @@ def safe_proc_snapshot(trace_pid): lines = Path(f"/proc/{pid}/maps").read_text().splitlines() status = Path(f"/proc/{pid}/status").read_text() rss = re.search(r"^VmRSS:\s*(\d+) kB$", status, re.M) - return {"observed": True, "map_regions": len(lines), "rss_kib": int(rss.group(1)) if rss else None} + try: + correlation = elf_map_probe.observe_pid(pid, executable, expected_sha256) + except (OSError, ValueError) as exc: + # Never export process map/address/path detail or exception strings. + correlation = {"status": "NOT_CORRELATED", "reason_type": type(exc).__name__, + "raw_addresses_exported": False, "pc_observed": False} + return {"observed": True, "map_regions": len(lines), + "rss_kib": int(rss.group(1)) if rss else None, + "elf_load_map": correlation} except (FileNotFoundError, ProcessLookupError, PermissionError): continue - return {"observed": False, "map_regions": 0, "rss_kib": None} + return {"observed": False, "map_regions": 0, "rss_kib": None, + "elf_load_map": {"status": "TARGET_NOT_OBSERVED", "raw_addresses_exported": False, "pc_observed": False}} def loopback_ready(port, deadline=4): @@ -143,10 +154,12 @@ def run_native(scratch, seed, port=5557): # The package-installed executable must be real and nonempty. binary = Path(server).resolve() version = capture_version(server) + binary_sha256 = digest(binary) trace_cmd = [trace, "-ff", "-qq", "-s", "96", "-o", str(root / "syscalls"), "-e", "trace=%file,%network,%process"] + args log_path = root / "server.log" observed = {"server_started": False, "loopback_tcp": False, "memory_maps": False, + "elf_load_map": False, "file_syscalls": False, "save_created": False, "clean_stop": False, "no_external_ipv4_connect": False} snapshots = [] @@ -159,8 +172,9 @@ def run_native(scratch, seed, port=5557): env={**os.environ, "HOME": str(root), "LANG": "C.UTF-8", "TZ": "UTC"}) try: observed["server_started"] = loopback_ready(port) - snap = safe_proc_snapshot(proc.pid) + snap = safe_proc_snapshot(proc.pid, binary, binary_sha256) observed["memory_maps"] = snap["observed"] and snap["map_regions"] > 0 + observed["elf_load_map"] = snap["elf_load_map"]["status"] == "CORRELATED_ELF_LOAD_MAP_NOT_PC" snapshots.append(snap) for cmd in ("set minplayers 0", "set aifill 2", f"set gameseed {seed}", f"set mapseed {seed}", "set timeout 1", "create Caesar", @@ -202,7 +216,7 @@ def run_native(scratch, seed, port=5557): "execution_class": "REAL_OPEN_SOURCE_NATIVE_ELF_NOT_SMAC_ORACLE", "source": "https://github.com/freeciv/freeciv", "license": "GPL-2.0-or-later", - "binary_sha256": digest(binary), + "binary_sha256": binary_sha256, "version": version, "seed": seed, "loopback_only": observed["no_external_ipv4_connect"], @@ -214,6 +228,7 @@ def run_native(scratch, seed, port=5557): "exit_code": exit_code, "limitations": [ "No source-matched symbol binding or original-1999 binary parity", + "ELF load-map correlation is source identity, not program-counter or Ghidra function attribution", "No Ghidra/Trace RMI, Wine, UI pixels, or full packet payload capture", "Kernel/file/network syscall counts are not semantic game-state proof", "No proprietary game/OS files or private observatory source were used", From 7188b5a3035b0dcdb7c9e4d26ff787a8d915ec1f Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:19:55 +0100 Subject: [PATCH 16/28] test(freeciv): public native two-seed ELF load-map qualification --- .github/workflows/surrogate-freeciv-observatory.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/surrogate-freeciv-observatory.yml b/.github/workflows/surrogate-freeciv-observatory.yml index e38e73b6..f22b61ca 100644 --- a/.github/workflows/surrogate-freeciv-observatory.yml +++ b/.github/workflows/surrogate-freeciv-observatory.yml @@ -28,8 +28,10 @@ jobs: with: persist-credentials: false - - name: Offline synthetic contract negatives - run: python3 qualification/surrogates/freeciv/test_contract.py -v + - name: Offline synthetic contract and actual ELF mapping negatives + run: | + python3 qualification/surrogates/freeciv/test_contract.py -v + python3 qualification/surrogates/freeciv/test_elf_map_probe.py -v - name: Install game and sensors on disposable runner env: From 248d153662fd27f7875ed6c315ef406942d9c887 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:22:04 +0100 Subject: [PATCH 17/28] fix(freeciv): remove unused native load-map loop bindings [skip ci] --- qualification/surrogates/freeciv/elf_map_probe.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/elf_map_probe.py b/qualification/surrogates/freeciv/elf_map_probe.py index ea102513..770145cf 100644 --- a/qualification/surrogates/freeciv/elf_map_probe.py +++ b/qualification/surrogates/freeciv/elf_map_probe.py @@ -86,7 +86,7 @@ def correlate_map_text(text, segments, device, inode, kind, page_size=4096): if not rows: raise CorrelationError("NO_EXACT_INODE_DEVICE_EXECUTABLE_MAPPING") votes = {} - for index, (start, end, mapoff, perms) in enumerate(rows): + for index, (start, _end, mapoff, _perms) in enumerate(rows): for off, vaddr, filesz, _flags in segments: seg_start = off & ~(page_size - 1) seg_end = (off + filesz + page_size - 1) & ~(page_size - 1) From c14a06674504c742983d7fd50f6246be5e034fe9 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:22:09 +0100 Subject: [PATCH 18/28] test(freeciv): conform ELF fixture to repository lint policy --- qualification/surrogates/freeciv/test_elf_map_probe.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/test_elf_map_probe.py b/qualification/surrogates/freeciv/test_elf_map_probe.py index 4aa9e327..d3097b5a 100644 --- a/qualification/surrogates/freeciv/test_elf_map_probe.py +++ b/qualification/surrogates/freeciv/test_elf_map_probe.py @@ -53,7 +53,8 @@ def test_bad_elf_refuses(self): with self.assertRaisesRegex(probe.CorrelationError, "ELF64"): import tempfile with tempfile.NamedTemporaryFile() as f: - f.write(b"not an elf"); f.flush() + f.write(b"not an elf") + f.flush() probe.elf_segments(f.name) def test_bad_page_size_refuses(self): From 5e4387bef382357a158275e3ffd852e127c8b117 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:23:40 +0100 Subject: [PATCH 19/28] test(r050): source-known Freeciv save/reload semantic oracle with negatives --- .../surrogate-freeciv-observatory.yml | 7 + qualification/surrogates/freeciv/README.md | 19 ++ .../surrogates/freeciv/save_oracle.py | 227 ++++++++++++++++++ .../surrogates/freeciv/test_save_oracle.py | 91 +++++++ 4 files changed, 344 insertions(+) create mode 100644 qualification/surrogates/freeciv/save_oracle.py create mode 100644 qualification/surrogates/freeciv/test_save_oracle.py diff --git a/.github/workflows/surrogate-freeciv-observatory.yml b/.github/workflows/surrogate-freeciv-observatory.yml index f22b61ca..bc0a0587 100644 --- a/.github/workflows/surrogate-freeciv-observatory.yml +++ b/.github/workflows/surrogate-freeciv-observatory.yml @@ -32,6 +32,7 @@ jobs: run: | python3 qualification/surrogates/freeciv/test_contract.py -v python3 qualification/surrogates/freeciv/test_elf_map_probe.py -v + python3 qualification/surrogates/freeciv/test_save_oracle.py -v - name: Install game and sensors on disposable runner env: @@ -49,6 +50,12 @@ jobs: python3 qualification/surrogates/freeciv/probe.py \ --seed "${{ matrix.seed }}" --output "$RUNNER_TEMP/surrogate-public/freeciv-native-${{ matrix.seed }}.json" + - name: Real Freeciv save reload and source-defined state-field oracle + run: | + set -euo pipefail + python3 qualification/surrogates/freeciv/save_oracle.py \ + --seed "${{ matrix.seed }}" --output "$RUNNER_TEMP/surrogate-public/freeciv-save-reload-${{ matrix.seed }}.json" + - name: Emit sanitized source-known evidence only if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 diff --git a/qualification/surrogates/freeciv/README.md b/qualification/surrogates/freeciv/README.md index 222b5ac8..05064d57 100644 --- a/qualification/surrogates/freeciv/README.md +++ b/qualification/surrogates/freeciv/README.md @@ -21,3 +21,22 @@ **Independent batches:** the public workflow qualifies seeds 42 and 43 as two separate jobs in parallel, with independent disposable process state and evidence. Their outputs are not byte-for-byte parity claims. **Qualification status at admission:** seven offline source-neutral contract tests passed in a disposable session; GitHub native game execution is **NOT_RUN until the public PR jobs report terminal evidence**. Neither runner selection nor a dispatched workflow alone establishes gameplay or observatory integration. + +## R050 state-reload semantic qualification — candidate + +Alongside source-known Linux syscall tests, a separate process-level test drives +Freeciv's documented `--file` save reload path. It parses only bounded, source-defined +`[game]` fields `turn`, `year`, `phase`, `server_state`, `save_players` and +counts `[playerN]` sections; the reloaded server is required to serialize the same +semantic fingerprint. The control deliberately does not publish raw game saves, +full in-memory state, player identities, logs or filenames. Input bounds, compressed +save expansion limits and duplicate-section/key refusal are tested separately. + +This proves only save/reload equality for these fields if **both real runner jobs +PASS**; it does not establish a completed new turn, map/AI identity, full binary +behavior or Windows/SMAC parity. A failed native step is `UNQUALIFIED`, not a +synthetic fixture success. Do not relax the test to match a surprising output; +classify the first concrete failure and adapt only with source-grounded evidence. + +`python3 qualification/surrogates/freeciv/test_save_oracle.py -v` is safe offline +and is no substitute for the native Freeciv server workcell. diff --git a/qualification/surrogates/freeciv/save_oracle.py b/qualification/surrogates/freeciv/save_oracle.py new file mode 100644 index 00000000..0749a7e3 --- /dev/null +++ b/qualification/surrogates/freeciv/save_oracle.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Freeciv save/reload semantic oracle. Source-known, public-safe, not SMAC parity. + +Only bounded derived fields leave the disposable runner. No game files or logs +are published. This is a separate real-game control from the strace pilot. +""" + +import argparse +import bz2 +import gzip +import hashlib +import json +import lzma +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +SCHEMA = "freeciv-save-reload/v0.1" +MAX_COMPRESSED = 8 * 1024 * 1024 +MAX_EXPANDED = 32 * 1024 * 1024 +FIELDS = ("turn", "year", "phase", "server_state", "save_players") +SAFE_STATES = {"S_S_INITIAL", "S_S_RUNNING", "S_S_OVER"} +EXPECTED_FAILURES = { + "INVALID_SAVE_BOUNDARY", "SAVE_EXPANSION_EXCEEDS_BUDGET", + "DUPLICATE_GAME_FIELD", "MISSING_OR_DUPLICATE_GAME_SECTION_FIELD", + "NONINTEGER_GAME_STATE", "GAME_STATE_OUT_OF_BOUNDS", "INVALID_GAME_STATE_ENUM", + "FREECIV_BINARY_MISSING", "SERVER_EXITED_BEFORE_COMMAND", + "SERVER_LOOPBACK_NOT_READY", "SERVER_QUIT_TIMEOUT", "SERVER_EXIT_NONZERO", + "SAVEFILE_COUNT_UNEXPECTED", +} + + +def sha256(path): + h = hashlib.sha256() + with Path(path).open("rb") as fh: + for data in iter(lambda: fh.read(65536), b""): + h.update(data) + return h.hexdigest() + + +def bounded_save_text(path): + path = Path(path) + if path.is_symlink() or not path.is_file() or not (0 < path.stat().st_size <= MAX_COMPRESSED): + raise ValueError("INVALID_SAVE_BOUNDARY") + openers = {".xz": lzma.open, ".gz": gzip.open, ".bz2": bz2.open} + with openers.get(path.suffix.lower(), open)(path, "rb") as inp: + contents = inp.read(MAX_EXPANDED + 1) + if len(contents) > MAX_EXPANDED: + raise ValueError("SAVE_EXPANSION_EXCEEDS_BUDGET") + return contents.decode("utf-8", errors="replace") + + +def game_fingerprint(text): + """Parse exactly one [game] section, detecting ambiguous/missing fields. + + This deliberately avoids exporting arbitrary game data and does NOT + purport to be a complete Freeciv save parser. + """ + game_sections = 0 + in_game = False + fields = {} + players = set() + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith(("#", ";")): + continue + m = re.fullmatch(r"\[([A-Za-z0-9_]+)\]", line) + if m: + name = m.group(1) + if name == "game": + game_sections += 1 + in_game = name == "game" + if re.fullmatch(r"player[0-9]+", name): + players.add(name) + continue + if in_game: + k = re.fullmatch(r"([A-Za-z0-9_]+)\s*=\s*(.*?)", line) + if k and k.group(1) in FIELDS: + key, value = k.groups() + if key in fields: + raise ValueError("DUPLICATE_GAME_FIELD") + fields[key] = value.strip().strip('"') + if game_sections != 1 or any(k not in fields for k in FIELDS): + raise ValueError("MISSING_OR_DUPLICATE_GAME_SECTION_FIELD") + try: + ints = {key: int(fields[key]) for key in ("turn", "year", "phase")} + except ValueError as exc: + raise ValueError("NONINTEGER_GAME_STATE") from exc + if not (0 <= ints["turn"] < 100000 and -100000 < ints["year"] < 100000 and 0 <= ints["phase"] < 10000): + raise ValueError("GAME_STATE_OUT_OF_BOUNDS") + if fields["server_state"] not in SAFE_STATES or fields["save_players"].upper() not in ("TRUE", "FALSE"): + raise ValueError("INVALID_GAME_STATE_ENUM") + return {**ints, "server_state": fields["server_state"], + "save_players": fields["save_players"].upper() == "TRUE", "player_sections": len(players)} + + +def compare_fingerprints(original, restored): + # Same fields must roundtrip; timestamps and binary hashes are deliberately + # excluded because Freeciv can update save metadata on every write. + keys = ("turn", "year", "phase", "server_state", "save_players", "player_sections") + return all(original.get(key) == restored.get(key) for key in keys) + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def ready(port, seconds=7): + until = time.monotonic() + seconds + while time.monotonic() < until: + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.3): + return True + except OSError: + time.sleep(0.1) + return False + + +def emit(proc, command): + if proc.poll() is not None or proc.stdin is None: + raise RuntimeError("SERVER_EXITED_BEFORE_COMMAND") + proc.stdin.write(command + "\n") + proc.stdin.flush() + time.sleep(0.15) + + +def server_transaction(executable, root, name, commands, load_file=None): + root = Path(root) + port = free_port() + saves = root / (name + "-saves") + saves.mkdir() + argv = [executable, "--bind", "127.0.0.1", "--Announce", "none", "--port", str(port), "--saves", str(saves)] + if load_file: + argv += ["--file", str(load_file)] + log = root / (name + ".log") + with log.open("wb") as log_fh: + proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=log_fh, + stderr=subprocess.STDOUT, text=True, cwd=root, + start_new_session=True, + env={**os.environ, "HOME": str(root), "TZ": "UTC", "LANG": "C.UTF-8"}) + try: + if not ready(port): + raise RuntimeError("SERVER_LOOPBACK_NOT_READY") + for cmd in commands: + emit(proc, cmd) + time.sleep(1.6) + emit(proc, "quit") + try: + exit_code = proc.wait(timeout=12) + except subprocess.TimeoutExpired as exc: + raise RuntimeError("SERVER_QUIT_TIMEOUT") from exc + if exit_code != 0: + raise RuntimeError("SERVER_EXIT_NONZERO") + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=4) + if proc.stdin: + proc.stdin.close() + candidates = [p for p in saves.iterdir() if p.is_file() and p.name.startswith(name + "-") + and (".sav" in p.name)] + if len(candidates) != 1: + raise RuntimeError("SAVEFILE_COUNT_UNEXPECTED") + return candidates[0] + + +def qualify(root, seed): + executable = shutil.which("freeciv-server") or "/usr/games/freeciv-server" + if not Path(executable).is_file(): + raise RuntimeError("FREECIV_BINARY_MISSING") + commands = ("set minplayers 0", "set aifill 2", f"set gameseed {seed}", + f"set mapseed {seed}", "set timeout 1", "create Caesar", + "aitoggle Caesar", "start", "save baseline-first") + before_save = server_transaction(executable, root, "baseline", commands) + first = game_fingerprint(bounded_save_text(before_save)) + # Explicitly create a *new* server process. No game data is taken from the + # first live process; restart with Freeciv's documented --file interface. + after_save = server_transaction(executable, root, "reloaded", ("save reloaded-first",), load_file=before_save) + second = game_fingerprint(bounded_save_text(after_save)) + return { + "schema": SCHEMA, + "status": "PASS" if compare_fingerprints(first, second) and first["save_players"] and first["player_sections"] >= 2 else "FAIL", + "execution_class": "REAL_OPEN_SOURCE_FREECIV_SAVE_RELOAD_FIELDS_ONLY", + "seed": seed, + "binary_sha256": sha256(executable), + "stage_digests": {"original": sha256(before_save), "reloaded": sha256(after_save)}, + "fingerprints": {"original": first, "reloaded": second}, + "signals": {"save_reloaded_in_second_process": True, + "semantic_fields_match": compare_fingerprints(first, second), + "players_present": first["player_sections"] >= 2 and first["save_players"]}, + "limitations": ["Only bounded save-file semantics are checked, not native Ghidra execution or whole-game parity", + "No proof of turn advancement or equivalence of unsampled game state", + "No proprietary SMAC bytes or private observatory implementation present"], + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--seed", type=int, choices=(42, 43), required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args(argv) + target = Path(args.output) + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="freeciv-semantic-") as scratch: + try: + result = qualify(scratch, args.seed) + except (OSError, ValueError, RuntimeError, EOFError, lzma.LZMAError, subprocess.SubprocessError) as exc: + code = str(exc) if isinstance(exc, (ValueError, RuntimeError)) else "" + if code not in EXPECTED_FAILURES: + code = "BOUNDED_NATIVE_ORACLE_FAILURE" + result = {"schema": SCHEMA, "seed": args.seed, "status": "UNQUALIFIED", + "execution_class": "SAVE_RELOAD_NOT_VERIFIED", "error_code": code} + target.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"schema": SCHEMA, "seed": args.seed, "status": result["status"]}, sort_keys=True)) + return 0 if result["status"] == "PASS" else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/qualification/surrogates/freeciv/test_save_oracle.py b/qualification/surrogates/freeciv/test_save_oracle.py new file mode 100644 index 00000000..f969bc37 --- /dev/null +++ b/qualification/surrogates/freeciv/test_save_oracle.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Adversarial source-neutral save-transaction contract tests.""" + +import bz2 +import gzip +import importlib.util +import lzma +import tempfile +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location("freeciv_save_oracle", Path(__file__).with_name("save_oracle.py")) +oracle = importlib.util.module_from_spec(spec) +spec.loader.exec_module(oracle) + + +def fixture(turn=4, year=-3000, phase=0, state="S_S_RUNNING", players=2): + result = ("[savefile]\nformat=" + '"3"' + "\n[game]\n" + + f'turn={turn}\nyear={year}\nphase={phase}\nserver_state="{state}"\nsave_players=TRUE\n') + for n in range(players): + result += f"[player{n}]\nname=\"source-known-test\"\n" + return result + + +class SaveOracleContracts(unittest.TestCase): + def test_extract_known_fields_without_sensitive_details(self): + data = oracle.game_fingerprint(fixture()) + self.assertEqual(data["turn"], 4) + self.assertEqual(data["year"], -3000) + self.assertEqual(data["player_sections"], 2) + self.assertNotIn("name", data) + + def test_roundtrip_equivalent_fields(self): + self.assertTrue(oracle.compare_fingerprints(oracle.game_fingerprint(fixture()), + oracle.game_fingerprint(fixture()))) + + def test_roundtrip_turn_change_rejected(self): + self.assertFalse(oracle.compare_fingerprints(oracle.game_fingerprint(fixture()), + oracle.game_fingerprint(fixture(turn=5)))) + + def test_roundtrip_player_loss_rejected(self): + self.assertFalse(oracle.compare_fingerprints(oracle.game_fingerprint(fixture()), + oracle.game_fingerprint(fixture(players=1)))) + + def test_duplicate_state_field_rejected(self): + with self.assertRaisesRegex(ValueError, "DUPLICATE_GAME_FIELD"): + oracle.game_fingerprint(fixture() + "[game]\nturn=9\n") + + def test_missing_game_state_rejected(self): + with self.assertRaises(ValueError): + oracle.game_fingerprint("[game]\nturn=1\n") + + def test_invalid_integer_rejected(self): + with self.assertRaisesRegex(ValueError, "NONINTEGER_GAME_STATE"): + oracle.game_fingerprint(fixture(turn="injected")) + + def test_invalid_state_enum_rejected(self): + with self.assertRaisesRegex(ValueError, "INVALID_GAME_STATE_ENUM"): + oracle.game_fingerprint(fixture(state="FORGED")) + + def test_xz_gzip_bz2_bounded_decoders(self): + with tempfile.TemporaryDirectory() as d: + raw = fixture().encode() + for extension, compress in (("xz", lzma.compress), ("bz2", bz2.compress), ("gz", gzip.compress)): + p = Path(d, "test.sav." + extension) + p.write_bytes(compress(raw)) + self.assertEqual(oracle.bounded_save_text(p), fixture()) + + def test_expanded_size_limit(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d, "zipbomb.sav.xz") + p.write_bytes(lzma.compress(b"a" * (oracle.MAX_EXPANDED + 1))) + with self.assertRaisesRegex(ValueError, "SAVE_EXPANSION_EXCEEDS_BUDGET"): + oracle.bounded_save_text(p) + + def test_symlink_rejected(self): + with tempfile.TemporaryDirectory() as d: + real = Path(d, "real.sav") + real.write_text(fixture()) + link = Path(d, "linked.sav") + link.symlink_to(real) + with self.assertRaisesRegex(ValueError, "INVALID_SAVE_BOUNDARY"): + oracle.bounded_save_text(link) + + def test_invalid_duplicate_game_section_rejected(self): + with self.assertRaises(ValueError): + oracle.game_fingerprint(fixture() + "[game]\n") + + +if __name__ == "__main__": + unittest.main() From a134a5efadb39719a6ed45e4c7e8a0976fd5d918 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:25:13 +0100 Subject: [PATCH 20/28] rdte(freeciv): source-known AI turn advance and reload oracle [public-safe] --- .../surrogate-freeciv-observatory.yml | 7 + qualification/surrogates/freeciv/README.md | 6 + .../surrogates/freeciv/test_turn_oracle.py | 62 +++++++++ .../surrogates/freeciv/turn_oracle.py | 128 ++++++++++++++++++ 4 files changed, 203 insertions(+) create mode 100644 qualification/surrogates/freeciv/test_turn_oracle.py create mode 100644 qualification/surrogates/freeciv/turn_oracle.py diff --git a/.github/workflows/surrogate-freeciv-observatory.yml b/.github/workflows/surrogate-freeciv-observatory.yml index bc0a0587..25e8a49e 100644 --- a/.github/workflows/surrogate-freeciv-observatory.yml +++ b/.github/workflows/surrogate-freeciv-observatory.yml @@ -33,6 +33,7 @@ jobs: python3 qualification/surrogates/freeciv/test_contract.py -v python3 qualification/surrogates/freeciv/test_elf_map_probe.py -v python3 qualification/surrogates/freeciv/test_save_oracle.py -v + python3 qualification/surrogates/freeciv/test_turn_oracle.py -v - name: Install game and sensors on disposable runner env: @@ -56,6 +57,12 @@ jobs: python3 qualification/surrogates/freeciv/save_oracle.py \ --seed "${{ matrix.seed }}" --output "$RUNNER_TEMP/surrogate-public/freeciv-save-reload-${{ matrix.seed }}.json" + - name: Real Freeciv AI-only turn advancement and save reload oracle + run: | + set -euo pipefail + python3 qualification/surrogates/freeciv/turn_oracle.py \ + --seed "${{ matrix.seed }}" --output "$RUNNER_TEMP/surrogate-public/freeciv-ai-turn-${{ matrix.seed }}.json" + - name: Emit sanitized source-known evidence only if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 diff --git a/qualification/surrogates/freeciv/README.md b/qualification/surrogates/freeciv/README.md index 05064d57..1f993ff0 100644 --- a/qualification/surrogates/freeciv/README.md +++ b/qualification/surrogates/freeciv/README.md @@ -40,3 +40,9 @@ classify the first concrete failure and adapt only with source-grounded evidence `python3 qualification/surrogates/freeciv/test_save_oracle.py -v` is safe offline and is no substitute for the native Freeciv server workcell. + +## R051 — Independent AI-only turn-state transition (candidate, requires native evidence) + +A separate public-safe, stdlib-only `turn_oracle.py` starts a **new native Freeciv server** with two AI participants, bounded timeout and seeded map/game inputs. It samples actual serialized `[game] turn/year/phase/state` before and after AI progression, then independently starts a **second native process** to reload the later save and verifies selected semantic fields. No private observatory code is present. + +This is scored independently from source-known process/load-map and selected save/reload baselines. If the real server does not advance, the new step fails and writes a **minimal `UNQUALIFIED` receipt** rather than inventing turn success. The current candidate has **9 source-neutral/offline tests**, but no native turn-advancement evidence until an exact-head runner reports. A positive test proves only selected AI turn progression plus reload stability, not full game-world equivalence, Ghidra PC attribution, Windows 98 or SMAC parity. Default CI has an upload-always allowlisted JSON receipt and retains both independent seeds. diff --git a/qualification/surrogates/freeciv/test_turn_oracle.py b/qualification/surrogates/freeciv/test_turn_oracle.py new file mode 100644 index 00000000..48a96b01 --- /dev/null +++ b/qualification/surrogates/freeciv/test_turn_oracle.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Source-neutral failure and success controls for AI-turn qualification.""" + +import importlib.util +import pathlib +import sys +import tempfile +import unittest + +root = pathlib.Path(__file__).parent +sys.path.insert(0, str(root)) +spec = importlib.util.spec_from_file_location("freeciv_turn_oracle", root / "turn_oracle.py") +oracle = importlib.util.module_from_spec(spec) +spec.loader.exec_module(oracle) + + +def state(turn=1, year=-4000, players=2, running=True): + return {"turn": turn, "year": year, "phase": 0, + "server_state": "S_S_RUNNING" if running else "S_S_INITIAL", + "save_players": True, "player_sections": players} + + +class TurnOracleContracts(unittest.TestCase): + def test_turn_and_year_advance_and_reload(self): + self.assertTrue(oracle.is_advanced(state(), state(2, -3900), state(2, -3900))) + + def test_same_turn_rejected(self): + self.assertFalse(oracle.is_advanced(state(), state(), state())) + + def test_regressed_turn_rejected(self): + self.assertFalse(oracle.is_advanced(state(turn=3), state(2), state(2))) + + def test_regressed_year_rejected(self): + self.assertFalse(oracle.is_advanced(state(), state(2, -4100), state(2, -4100))) + + def test_reload_altered_phase_rejected(self): + later = state(2, -3900) + restored = dict(later) + restored["phase"] += 1 + self.assertFalse(oracle.is_advanced(state(), later, restored)) + + def test_missing_players_rejected(self): + self.assertFalse(oracle.is_advanced(state(), state(2, -3900, 0), state(2, -3900, 0))) + + def test_missing_save_is_not_silent_success(self): + with tempfile.TemporaryDirectory() as d: + with self.assertRaisesRegex(RuntimeError, "TURN_SAVE_COUNT_UNEXPECTED"): + oracle.only_save(d, "before-turn") + + def test_multiple_save_candidates_are_rejected(self): + with tempfile.TemporaryDirectory() as d: + (pathlib.Path(d) / "before-turn.sav.xz").write_bytes(b"one") + (pathlib.Path(d) / "before-turn.sav.gz").write_bytes(b"two") + with self.assertRaisesRegex(RuntimeError, "TURN_SAVE_COUNT_UNEXPECTED"): + oracle.only_save(d, "before-turn") + + def test_running_state_required(self): + self.assertFalse(oracle.is_advanced(state(), state(2, -3900, running=False), state(2, -3900, running=False))) + + +if __name__ == "__main__": + unittest.main() diff --git a/qualification/surrogates/freeciv/turn_oracle.py b/qualification/surrogates/freeciv/turn_oracle.py new file mode 100644 index 00000000..24356674 --- /dev/null +++ b/qualification/surrogates/freeciv/turn_oracle.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Bounded real Freeciv AI turn-transition + save/reload oracle. + +This is a separately scored source-known game-control probe. It does not use +licensed SMAC bytes, guest virtualization, or private observatory source. +""" + +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import save_oracle as common + +SCHEMA = "freeciv-ai-turn-reload/v0.1" +KNOWN_FAILURES = common.EXPECTED_FAILURES | {"TURN_SAVE_COUNT_UNEXPECTED"} + + +def is_advanced(before, after, restored): + """Require genuine increasing in-game turn, then serialized reload parity.""" + return ( + before["server_state"] == "S_S_RUNNING" + and after["server_state"] == "S_S_RUNNING" + and restored["server_state"] == "S_S_RUNNING" + and after["turn"] > before["turn"] + and after["year"] >= before["year"] + and after["save_players"] + and after["player_sections"] >= 2 + and common.compare_fingerprints(after, restored) + ) + + +def only_save(folder, stem): + files = [p for p in Path(folder).iterdir() if p.is_file() and p.name.startswith(stem) + and ".sav" in p.name] + if len(files) != 1: + raise RuntimeError("TURN_SAVE_COUNT_UNEXPECTED") + return files[0] + + +def advance_game(root, seed): + binary = shutil.which("freeciv-server") or "/usr/games/freeciv-server" + if not Path(binary).is_file(): + raise RuntimeError("FREECIV_BINARY_MISSING") + root = Path(root) + saves = root / "turn-saves" + saves.mkdir() + port = common.free_port() + argv = [binary, "--bind", "127.0.0.1", "--Announce", "none", + "--port", str(port), "--saves", str(saves)] + with (root / "ai-turn.log").open("wb") as log: + proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=log, + stderr=subprocess.STDOUT, text=True, cwd=root, + start_new_session=True, + env={**os.environ, "HOME": str(root), "LANG": "C.UTF-8", "TZ": "UTC"}) + try: + if not common.ready(port): + raise RuntimeError("SERVER_LOOPBACK_NOT_READY") + for cmd in ("set minplayers 0", "set aifill 2", f"set gameseed {seed}", + f"set mapseed {seed}", "set timeout 3", "hard", + "create Caesar", "start"): + common.emit(proc, cmd) + common.emit(proc, "save before-turn") + time.sleep(2) + before_file = only_save(saves, "before-turn") + before = common.game_fingerprint(common.bounded_save_text(before_file)) + time.sleep(9) + common.emit(proc, "save after-turn") + time.sleep(2) + after_file = only_save(saves, "after-turn") + after = common.game_fingerprint(common.bounded_save_text(after_file)) + common.emit(proc, "quit") + if proc.wait(timeout=12) != 0: + raise RuntimeError("SERVER_EXIT_NONZERO") + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=4) + if proc.stdin: + proc.stdin.close() + reloaded_file = common.server_transaction(binary, root, "turnreload", + ("save turnreload-first",), load_file=after_file) + restored = common.game_fingerprint(common.bounded_save_text(reloaded_file)) + qualified = is_advanced(before, after, restored) + return { + "schema": SCHEMA, + "status": "PASS" if qualified else "UNQUALIFIED", + "execution_class": "REAL_OPEN_SOURCE_FREECIV_AI_TURN_AND_SELECTED_RELOAD_FIELDS", + "binary_sha256": common.sha256(binary), + "seed": seed, + "game_states": {"before": before, "after": after, "reloaded": restored}, + "signals": {"turn_advanced": after["turn"] > before["turn"], + "year_nonregressing": after["year"] >= before["year"], + "semantic_reload_match": common.compare_fingerprints(after, restored), + "game_running": before["server_state"] == after["server_state"] == "S_S_RUNNING"}, + "limitations": ["Turn advancement under AI-only Freeciv is not SMAC original-binary parity", + "Only selected save fields checked; no unit/city/map equivalence or PC witness"], + } + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--seed", type=int, required=True, choices=(42, 43)) + ap.add_argument("--output", required=True) + args = ap.parse_args(argv) + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="freeciv-turn-oracle-") as scratch: + try: + result = advance_game(scratch, args.seed) + except (OSError, ValueError, RuntimeError, EOFError, subprocess.SubprocessError) as exc: + code = str(exc) if isinstance(exc, (ValueError, RuntimeError)) else "" + if code not in KNOWN_FAILURES: + code = "NATIVE_TURN_PROBE_FAILURE" + result = {"schema": SCHEMA, "seed": args.seed, "status": "UNQUALIFIED", + "execution_class": "TURN_ORACLE_NOT_VERIFIED", "error_code": code} + output.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"seed": args.seed, "status": result["status"], "schema": SCHEMA}, sort_keys=True)) + return 0 if result["status"] == "PASS" else 1 + + +if __name__ == "__main__": + sys.exit(main()) From b021857a731a1381994d0c68d610784a10b9a7d4 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:29:01 +0100 Subject: [PATCH 21/28] test(freeciv): resolve R051 SIM117 lint without relaxing turn oracle --- qualification/surrogates/freeciv/test_turn_oracle.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/qualification/surrogates/freeciv/test_turn_oracle.py b/qualification/surrogates/freeciv/test_turn_oracle.py index 48a96b01..fdc9ddd7 100644 --- a/qualification/surrogates/freeciv/test_turn_oracle.py +++ b/qualification/surrogates/freeciv/test_turn_oracle.py @@ -43,9 +43,8 @@ def test_missing_players_rejected(self): self.assertFalse(oracle.is_advanced(state(), state(2, -3900, 0), state(2, -3900, 0))) def test_missing_save_is_not_silent_success(self): - with tempfile.TemporaryDirectory() as d: - with self.assertRaisesRegex(RuntimeError, "TURN_SAVE_COUNT_UNEXPECTED"): - oracle.only_save(d, "before-turn") + with tempfile.TemporaryDirectory() as d, self.assertRaisesRegex(RuntimeError, "TURN_SAVE_COUNT_UNEXPECTED"): + oracle.only_save(d, "before-turn") def test_multiple_save_candidates_are_rejected(self): with tempfile.TemporaryDirectory() as d: From 2b8508dbd297dd123184176692f7f6597813ed4a Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:39:46 +0100 Subject: [PATCH 22/28] rdte(freeciv): native Ghidra 12.2 static function witness on public runner --- .../workflows/surrogate-freeciv-ghidra.yml | 66 ++++++++++++++++++ .../freeciv/ghidra/PublicFreecivWitness.java | 62 +++++++++++++++++ .../surrogates/freeciv/ghidra/README.md | 22 ++++++ .../freeciv/ghidra/test_validate.py | 64 ++++++++++++++++++ .../surrogates/freeciv/ghidra/validate.py | 67 +++++++++++++++++++ 5 files changed, 281 insertions(+) create mode 100644 .github/workflows/surrogate-freeciv-ghidra.yml create mode 100644 qualification/surrogates/freeciv/ghidra/PublicFreecivWitness.java create mode 100644 qualification/surrogates/freeciv/ghidra/README.md create mode 100644 qualification/surrogates/freeciv/ghidra/test_validate.py create mode 100644 qualification/surrogates/freeciv/ghidra/validate.py diff --git a/.github/workflows/surrogate-freeciv-ghidra.yml b/.github/workflows/surrogate-freeciv-ghidra.yml new file mode 100644 index 00000000..c00f6631 --- /dev/null +++ b/.github/workflows/surrogate-freeciv-ghidra.yml @@ -0,0 +1,66 @@ +name: Freeciv real Ghidra static analysis source-known qualification +on: + pull_request: + paths: + - '.github/workflows/surrogate-freeciv-ghidra.yml' + - 'qualification/surrogates/freeciv/ghidra/**' + +permissions: + contents: read + +jobs: + ghidra-native-static: + runs-on: ubuntu-24.04 + timeout-minutes: 18 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 + with: + distribution: temurin + java-version: '25' + - name: Validate independent source-neutral Ghidra witness negatives + run: python3 qualification/surrogates/freeciv/ghidra/test_validate.py -v + - name: Obtain open-source game and pinned official Ghidra release + env: + DEBIAN_FRONTEND: noninteractive + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends freeciv-server=3.1.0+ds-1build5 unzip curl + echo '33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472 /usr/games/freeciv-server' | sha256sum -c - + curl -fLSs --retry 2 --connect-timeout 15 --max-time 230 \ + 'https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.2_build/ghidra_12.2_PUBLIC_20261016.zip' \ + -o "$RUNNER_TEMP/ghidra.zip" + printf '%s %s\n' '2c2cd776db3c1f6a097ba418922378ac3649cadd5e844a6f5f088ae628a7be67' "$RUNNER_TEMP/ghidra.zip" | sha256sum -c - + mkdir -p "$RUNNER_TEMP/ghidra" + unzip -q "$RUNNER_TEMP/ghidra.zip" -d "$RUNNER_TEMP/ghidra" + - name: Native Ghidra headless program analysis and typed verification + run: | + set -euo pipefail + analyzer=$(find "$RUNNER_TEMP/ghidra" -type f -path '*/support/analyzeHeadless' -print -quit) + test -n "$analyzer" + mkdir -p "$RUNNER_TEMP/ghidra-projects" "$RUNNER_TEMP/private-observe" "$RUNNER_TEMP/public-safe" + # Raw Ghidra logs stay in disposable runner scratch, never artifacts. + "$analyzer" "$RUNNER_TEMP/ghidra-projects" FreecivSurrogate \ + -import /usr/games/freeciv-server \ + -scriptPath "$GITHUB_WORKSPACE/qualification/surrogates/freeciv/ghidra" \ + -postScript PublicFreecivWitness.java \ + 33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472 \ + "$RUNNER_TEMP/private-observe/ghidra.json" \ + -analysisTimeoutPerFile 180 -max-cpu 2 -deleteProject \ + > "$RUNNER_TEMP/private-observe/ghidra.log" 2>&1 + test -s "$RUNNER_TEMP/private-observe/ghidra.json" || { echo 'GHIDRA_WITNESS_ABSENT'; exit 1; } + python3 qualification/surrogates/freeciv/ghidra/validate.py \ + --input "$RUNNER_TEMP/private-observe/ghidra.json" \ + --binary /usr/games/freeciv-server \ + --output "$RUNNER_TEMP/public-safe/ghidra-static.json" + - name: Upload only allowlisted static witness + if: success() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: freeciv-ghidra-static-public + path: ${{ runner.temp }}/public-safe/ghidra-static.json + if-no-files-found: error + retention-days: 3 diff --git a/qualification/surrogates/freeciv/ghidra/PublicFreecivWitness.java b/qualification/surrogates/freeciv/ghidra/PublicFreecivWitness.java new file mode 100644 index 00000000..ada0681b --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/PublicFreecivWitness.java @@ -0,0 +1,62 @@ +// Public-source Ghidra headless witness. No private binary bytes or addresses exported. +// @category Freeciv.Surrogate +import ghidra.app.script.GhidraScript; +import ghidra.program.model.address.AddressRange; +import ghidra.program.model.address.AddressRangeIterator; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.FunctionIterator; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Locale; + +public class PublicFreecivWitness extends GhidraScript { + @Override + public void run() throws Exception { + String[] args = getScriptArgs(); + if (args.length != 2 || !args[0].matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("GHIDRA_WITNESS_ARGUMENTS_INVALID"); + } + if (currentProgram == null) { + throw new IllegalStateException("GHIDRA_PROGRAM_NOT_LOADED"); + } + String imageHash = currentProgram.getExecutableSHA256(); + if (imageHash == null || !args[0].equals(imageHash.toLowerCase(Locale.ROOT))) { + throw new IllegalStateException("GHIDRA_IMPORTED_ARTIFACT_DIGEST_MISMATCH"); + } + long functionCount = 0L; + long intervalCount = 0L; + FunctionIterator iterator = currentProgram.getFunctionManager().getFunctions(true); + while (iterator.hasNext()) { + Function function = iterator.next(); + functionCount++; + AddressRangeIterator ranges = function.getBody().getAddressRanges(); + long bodyRanges = 0L; + while (ranges.hasNext()) { + AddressRange range = ranges.next(); + if (range.getMinAddress().compareTo(range.getMaxAddress()) > 0) { + throw new IllegalStateException("GHIDRA_INVALID_FUNCTION_INTERVAL"); + } + bodyRanges++; + intervalCount++; + } + if (bodyRanges == 0L) { + throw new IllegalStateException("GHIDRA_EMPTY_FUNCTION_BODY"); + } + } + if (functionCount < 100L || intervalCount < functionCount) { + throw new IllegalStateException("GHIDRA_FUNCTION_DISCOVERY_INSUFFICIENT"); + } + Path output = Paths.get(args[1]).toAbsolutePath(); + Files.createDirectories(output.getParent()); + String json = "{\"schema\":\"freeciv-ghidra-static/v0.1\"," + + "\"execution_class\":\"REAL_GHIDRA_SOURCE_KNOWN_STATIC_ONLY\"," + + "\"artifact_sha256\":\"" + imageHash.toLowerCase(Locale.ROOT) + "\"," + + "\"function_count\":" + functionCount + "," + + "\"interval_count\":" + intervalCount + "," + + "\"pc_correlated\":false}"; + Files.write(output, json.getBytes(StandardCharsets.UTF_8)); + println("PUBLIC_GHIDRA_STATIC_WITNESS_COMPLETE"); + } +} diff --git a/qualification/surrogates/freeciv/ghidra/README.md b/qualification/surrogates/freeciv/ghidra/README.md new file mode 100644 index 00000000..70f6fac0 --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/README.md @@ -0,0 +1,22 @@ +# R052 — source-known Ghidra 12.2 static-analysis workcell (public RDTE) + +This qualification uses a **real Ghidra headless analyzer** on the publicly packaged Freeciv 3.1.0 Ubuntu 24.04 Linux ELF. It exercises the *static-tool* side of the Reversing observatory without publishing private framework code or game assets. + +## Inputs and authority + +- Official Ghidra **12.2** release (October 16, 2026) asset `ghidra_12.2_PUBLIC_20261016.zip`, SHA-256 `2c2cd776db3c1f6a097ba418922378ac3649cadd5e844a6f5f088ae628a7be67` as reported by the upstream GitHub release API. +- **JDK 25**, required by Ghidra 12.2, provided by an explicit pinned `actions/setup-java` step. +- Ubuntu 24.04 package `freeciv-server=3.1.0+ds-1build5`, executable SHA-256 `33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472` accepted from previous R048–R051 real native workcells. +- Source and status owned by `SemperSupra/WineBot` draft PR #157. Reusable observability contracts owned by private `mark-e-deyoung/ghidra-tools#4`, original SMAC authority by private `mark-e-deyoung/reverse-smac#37`. No cross-publishing or rights expansion. + +## Independent observation + +Run `analyzeHeadless` in disposable runner scratch with `PublicFreecivWitness.java` as the post-analysis script. It checks the program's original imported SHA-256, iterates FunctionManager functions and **disjoint** AddressSet body intervals, then writes a tiny JSON witness. `validate.py` independently verifies the game executable's raw SHA and the output's exact schema/capacity constraints. Only an allowlisted report containing digest, counts, and `pc_correlated=false` may be uploaded; original ELF, disassembly, functions, addresses, scripts' raw logs and game state never leave the runner as artifacts. + +The stand-in tests exercise malformed/forged reports and wrong digest. They **do not authenticate a native Ghidra run**; the exact-head Actions job, checksum gates, script execution, and reviewed provenance are required. Native result remains `NOT_RUN` until the Actions job actually completes. + +## Truth boundary and next experiment + +A pass would prove a genuine Ghidra 12.2 analysis of the source-known ELF with original-asset identity and a bounded function/range inventory. It would **not** mean a Freeciv instruction pointer was observed or mapped to a particular Ghidra function; the current output explicitly asserts `pc_correlated=false`. The next independent workcell must observe an **actual runtime PC** under a source-known debugger, authenticate the PIE/ASLR module mapping and match it to a non-overlapping Ghidra function interval; wrong digest, wrong ASLR base, unmapped PC and ambiguous function bodies are required adversarial tests. + +No licensed SMAC executable, Win98 guest, public private-source copy, private hosted GitHub Actions, merge, release or production deployment is authorized by this experiment. diff --git a/qualification/surrogates/freeciv/ghidra/test_validate.py b/qualification/surrogates/freeciv/ghidra/test_validate.py new file mode 100644 index 00000000..a4bf28e5 --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/test_validate.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Negative controls for source-known static Ghidra witness classification.""" + +import hashlib +import json +import unittest + +import validate as target + +BINARY = b"source-known-native-elf-placeholder" + + +def payload(**changes): + doc = {"schema": target.SCHEMA, + "execution_class": "REAL_GHIDRA_SOURCE_KNOWN_STATIC_ONLY", + "artifact_sha256": hashlib.sha256(BINARY).hexdigest(), + "function_count": 300, "interval_count": 320, + "pc_correlated": False} + doc.update(changes) + return json.dumps(doc).encode() + + +class GhidraContractTests(unittest.TestCase): + def test_valid_static_is_not_pc_witness(self): + result = target.validate(payload(), BINARY) + self.assertEqual(result["status"], "PASS") + self.assertIs(result["pc_correlated"], False) + + def test_wrong_elf_rejected(self): + with self.assertRaisesRegex(ValueError, "IDENTITY"): + target.validate(payload(), b"different-binary") + + def test_pc_claim_rejected(self): + with self.assertRaisesRegex(ValueError, "PC_CLAIM"): + target.validate(payload(pc_correlated=True), BINARY) + + def test_ambiguous_intervals_rejected(self): + with self.assertRaisesRegex(ValueError, "FUNCTION_INTERVALS"): + target.validate(payload(function_count=320, interval_count=300), BINARY) + + def test_unknown_field_rejected(self): + with self.assertRaisesRegex(ValueError, "FIELDS"): + target.validate(payload(addresses=[1, 2, 3]), BINARY) + + def test_duplicate_key_rejected(self): + malformed = payload().decode().replace('"function_count": 300', '"function_count": 300, "function_count": 300') + with self.assertRaisesRegex(ValueError, "DUPLICATE"): + target.validate(malformed.encode(), BINARY) + + def test_boolean_disguised_as_count_rejected(self): + with self.assertRaisesRegex(ValueError, "FUNCTION_INTERVALS"): + target.validate(payload(function_count=True), BINARY) + + def test_short_digest_rejected(self): + with self.assertRaisesRegex(ValueError, "DIGEST"): + target.validate(payload(artifact_sha256="abcd"), BINARY) + + def test_large_report_rejected(self): + with self.assertRaisesRegex(ValueError, "SIZE"): + target.validate(payload() + b" " * target.MAX_REPORT_BYTES, BINARY) + + +if __name__ == "__main__": + unittest.main() diff --git a/qualification/surrogates/freeciv/ghidra/validate.py b/qualification/surrogates/freeciv/ghidra/validate.py new file mode 100644 index 00000000..0a556f01 --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/validate.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Fail-closed validation of the public Freeciv Ghidra static witness.""" + +import argparse +import hashlib +import json +import re +from pathlib import Path + +SCHEMA = "freeciv-ghidra-static/v0.1" +EXPECTED_FIELDS = {"schema", "execution_class", "artifact_sha256", "function_count", + "interval_count", "pc_correlated"} +MAX_REPORT_BYTES = 4096 + + +def no_duplicate_keys(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("DUPLICATE_WITNESS_KEY") + result[key] = value + return result + + +def validate(raw, binary): + if not (0 < len(raw) <= MAX_REPORT_BYTES): + raise ValueError("WITNESS_SIZE_INVALID") + try: + report = json.loads(raw, object_pairs_hook=no_duplicate_keys) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError("WITNESS_JSON_INVALID") from exc + if not isinstance(report, dict) or set(report) != EXPECTED_FIELDS: + raise ValueError("WITNESS_FIELDS_INVALID") + if (report["schema"] != SCHEMA or report["execution_class"] != + "REAL_GHIDRA_SOURCE_KNOWN_STATIC_ONLY"): + raise ValueError("WITNESS_CLASS_INVALID") + digest = report["artifact_sha256"] + if not isinstance(digest, str) or not re.fullmatch("[0-9a-f]{64}", digest): + raise ValueError("WITNESS_DIGEST_INVALID") + if hashlib.sha256(binary).hexdigest() != digest: + raise ValueError("WITNESS_BINARY_IDENTITY_MISMATCH") + functions, intervals = report["function_count"], report["interval_count"] + if type(functions) is not int or type(intervals) is not int or not (100 <= functions <= intervals <= 10000000): + raise ValueError("WITNESS_FUNCTION_INTERVALS_INVALID") + if report["pc_correlated"] is not False: + raise ValueError("WITNESS_PC_CLAIM_NOT_ACCEPTED") + return {"schema": SCHEMA, "status": "PASS", "artifact_sha256": digest, + "functions": functions, "intervals": intervals, + "evidence_class": "REAL_GHIDRA_STATIC_INDEX_ONLY", "pc_correlated": False} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--input", required=True) + ap.add_argument("--binary", required=True) + ap.add_argument("--output", required=True) + args = ap.parse_args() + original = Path(args.binary) + if original.is_symlink() or not original.is_file(): + raise SystemExit("GHIDRA_BINARY_BOUNDARY_INVALID") + result = validate(Path(args.input).read_bytes(), original.read_bytes()) + Path(args.output).write_text(json.dumps(result, sort_keys=True) + "\n", encoding="utf-8") + print("PUBLIC_GHIDRA_STATIC_WITNESS_ACCEPTED") + + +if __name__ == "__main__": + main() From 3b7af6db7f7ee8d0d48015816e854aa91c06ed3c Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:12:03 +0100 Subject: [PATCH 23/28] exp(reversing): bounded Freeciv I/O boundary trace and multimodal CPU critic interviews --- .../workflows/surrogate-critic-interview.yml | 68 ++++++ .../surrogate-freeciv-boundary-io.yml | 53 +++++ .../freeciv/BOUNDARY_OBSERVABILITY.md | 27 +++ .../surrogates/freeciv/critics/README.md | 21 ++ .../surrogates/freeciv/critics/interview.py | 223 ++++++++++++++++++ .../freeciv/critics/test_interview.py | 48 ++++ .../surrogates/freeciv/io_boundary.py | 134 +++++++++++ .../surrogates/freeciv/run_io_native.py | 100 ++++++++ .../surrogates/freeciv/test_io_boundary.py | 81 +++++++ 9 files changed, 755 insertions(+) create mode 100644 .github/workflows/surrogate-critic-interview.yml create mode 100644 .github/workflows/surrogate-freeciv-boundary-io.yml create mode 100644 qualification/surrogates/freeciv/BOUNDARY_OBSERVABILITY.md create mode 100644 qualification/surrogates/freeciv/critics/README.md create mode 100644 qualification/surrogates/freeciv/critics/interview.py create mode 100644 qualification/surrogates/freeciv/critics/test_interview.py create mode 100644 qualification/surrogates/freeciv/io_boundary.py create mode 100644 qualification/surrogates/freeciv/run_io_native.py create mode 100644 qualification/surrogates/freeciv/test_io_boundary.py diff --git a/.github/workflows/surrogate-critic-interview.yml b/.github/workflows/surrogate-critic-interview.yml new file mode 100644 index 00000000..51018b1a --- /dev/null +++ b/.github/workflows/surrogate-critic-interview.yml @@ -0,0 +1,68 @@ +name: Reversing observatory public-safe CPU critic interviews +on: + pull_request: + paths: + - '.github/workflows/surrogate-critic-interview.yml' + - 'qualification/surrogates/freeciv/critics/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: reversing-critic-${{ github.ref }} + cancel-in-progress: true + +jobs: + critic-interview: + name: Source-neutral ${{ matrix.task_class }} CPU interview + runs-on: ubuntu-24.04 + timeout-minutes: 25 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + task_class: [reasoning, vision, audio] + env: + HF_HUB_DISABLE_TELEMETRY: '1' + HF_HUB_DISABLE_XET: '1' + TRANSFORMERS_NO_TF: '1' + OMP_NUM_THREADS: '2' + MKL_NUM_THREADS: '2' + TOKENIZERS_PARALLELISM: 'false' + steps: + - name: Checkout public workcell with no persisted credentials + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: Deterministic admission and red-team tests + run: | + set -euo pipefail + python3 qualification/surrogates/freeciv/critics/test_interview.py -v + python3 -m py_compile qualification/surrogates/freeciv/critics/interview.py + - name: Install CPU-only inference runtime and optional speech synthesizer + run: | + set -euo pipefail + python3 -m pip install --disable-pip-version-check --no-cache-dir --index-url https://download.pytorch.org/whl/cpu 'torch==2.6.0' + python3 -m pip install --disable-pip-version-check --no-cache-dir \ + 'transformers==4.56.2' 'huggingface_hub==0.35.3' \ + 'Pillow==11.3.0' 'numpy==2.1.3' 'soundfile==0.13.1' 'scipy==1.15.3' + if [ '${{ matrix.task_class }}' = audio ]; then + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends espeak-ng + fi + - name: Run actual open-weight model on bounded generated fixtures + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/public-critic" + timeout 800s python3 qualification/surrogates/freeciv/critics/interview.py \ + --class '${{ matrix.task_class }}' \ + --output "$RUNNER_TEMP/public-critic/critic-${{ matrix.task_class }}.json" + - name: Upload allowlisted critic interview receipt only + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: public-observatory-critic-${{ matrix.task_class }} + path: ${{ runner.temp }}/public-critic/*.json + if-no-files-found: ignore + retention-days: 3 diff --git a/.github/workflows/surrogate-freeciv-boundary-io.yml b/.github/workflows/surrogate-freeciv-boundary-io.yml new file mode 100644 index 00000000..bf2858d9 --- /dev/null +++ b/.github/workflows/surrogate-freeciv-boundary-io.yml @@ -0,0 +1,53 @@ +name: Freeciv native read-write-map boundary qualification +on: + pull_request: + paths: + - '.github/workflows/surrogate-freeciv-boundary-io.yml' + - 'qualification/surrogates/freeciv/io_boundary.py' + - 'qualification/surrogates/freeciv/test_io_boundary.py' + - 'qualification/surrogates/freeciv/run_io_native.py' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: freeciv-io-boundary-${{ github.ref }} + cancel-in-progress: true +jobs: + native-io: + runs-on: ubuntu-24.04 + timeout-minutes: 12 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + seed: [42, 43] + steps: + - name: Checkout public-only workcell without credential persistence + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: Offline adversarial trace tests + run: | + python3 qualification/surrogates/freeciv/test_io_boundary.py -v + python3 -m py_compile qualification/surrogates/freeciv/run_io_native.py + - name: Install open-source Freeciv and syscall observer + env: + DEBIAN_FRONTEND: noninteractive + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends freeciv-server=3.1.0+ds-1build5 strace + - name: Actual source-known Freeciv file reads, writes and mmaps + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/freeciv-io-public" + timeout 100s python3 qualification/surrogates/freeciv/run_io_native.py \ + --seed '${{ matrix.seed }}' --output "$RUNNER_TEMP/freeciv-io-public/receipt-${{ matrix.seed }}.json" + - name: Upload only bounded aggregate JSON + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: freeciv-io-boundary-public-${{ matrix.seed }} + path: ${{ runner.temp }}/freeciv-io-public/*.json + if-no-files-found: ignore + retention-days: 3 diff --git a/qualification/surrogates/freeciv/BOUNDARY_OBSERVABILITY.md b/qualification/surrogates/freeciv/BOUNDARY_OBSERVABILITY.md new file mode 100644 index 00000000..b923f54b --- /dev/null +++ b/qualification/surrogates/freeciv/BOUNDARY_OBSERVABILITY.md @@ -0,0 +1,27 @@ +# Boundary-first game observability (public qualification candidate) + +Scope: reverse engineer application behavior by connecting *resource operations* to meaningful objects; no private binary, dump, original SMAC, secret, unreviewed capture or host access is authorized. This workcell is a source-known Freeciv **Linux server** control. It does not exercise GDI, DirectDraw, Win32 input, mouse, controllers, video or sound; dedicated WineBot/OpenTTD/SDL/legacy Windows workcells are required for those modalities. + +## Inventory, topology, and sensor contracts + +1. Discover executable/imports/loaded modules and probable framework/resource boundaries with `readelf`, static Ghidra, ELF load maps and library signatures. Use direct evidence: import/symbol, source-defined callsite or observed stack, not a guessed engine label. On Windows: PE imports/DelayLoad, COM/DirectX/Winsock registrations; on Wine: Win32 relay and host syscall correlation. On native Linux: VFS/glibc/SDL/GL/EGL/OpenAL entry points. Unknown library → `UNKNOWN`, not inferred from a screenshot. +2. Capture file `openat/read/pread64/readv/write/pwrite64/writev/mmap/lseek/close`, archive/decoder hook, engine virtual-resource manager, serializer and game object usage. FD/handle identity must include process lifetime/generation to avoid reuse. Preserve read/write byte span and exact offset **only when observed** (e.g. `pread64`), not inferred from a bare `read`. Distinguish memory-mapped clean/dirtied pages from read/write and append metadata; `strace -yy` path decoration is a hint, not authenticated object identity. +3. Capture input raw hardware events → OS/window/SDL/DirectInput messages → hit testing → intent/command → game state. Preserve device class, scan code/binding, modifier, focus ownership, control mode and allowed action/postcondition. No blind coordinate clicking acceptance. +4. Capture audio buffers (creation, decode, queue, play/stop, mixer, output callback) and frames/graphics (surface/texture creation, draw primitive, source/destination rectangles, transforms, clip, shader/ROP/blit, framebuffer evidence). Correlate decoded asset hash to object-pointer lifetime and eventual output. A draw call may batch many objects; one object may generate many calls. Claims remain hypotheses until controlled perturbation and independent pixel/resource oracle. +5. For each event, distinguish **intended application state** (memory/logic), **presented state** (pixels/audio/UI) and **externalized state** (file/network/device). Use `experiment_id`, `run_id`, module/build hash, process/thread/generation, resource FD/handle, correlation/causal parent, vantage, clock-domain and uncertainty. Raw evidence stays private/ephemeral as required; sanitized digest/counters only in public CI. + +## Executable file-I/O control + +`io_boundary.py` aggregates annotated `strace -ff -yy` file I/O call classes and counts, rejecting absent, oversized or unsafe traces. `run_io_native.py` runs an actual public Freeciv ELF with scripted AI/game/save commands, observes native I/O metadata and output save, then deletes raw syscall logs/save bytes with the ephemeral runner. This is a producer for evidence classes, not a byte-format decoder. Keep raw source-to-sink provenance inside an authorized private workcell if actual asset bytes are involved. + +`python3 qualification/surrogates/freeciv/test_io_boundary.py -v` covers raw-path leak prevention, FD unknown, success vs failed syscall, mmap metadata, bounded traces, invalid/missing files and hostile symlinks. A native PASS can show syscall boundary observability, not game asset format inference or exact byte offsets. + +## Automated critique, learning and lower human toil + +Treat each inference as a falsifiable claim `{subject, predicate, object, evidence_refs, method, uncertainty, counterevidence, next_action}`. Deterministic oracles reject impossible offsets, corrupt archive lengths, wrong hashes, enum/clock/FD collisions and stale state; statistical critics flag drift/inter-run instability; model critics infer likely formats, decoder libraries, command semantics, draw groups and next experiment, citing *present* evidence refs. An experiment controller chooses a high-information, authorized one-variable change, reruns independent sensors, tests the hypothesis, and converts only verified findings into durable format schemas, signatures, regression tests and Ghidra annotations. Models may suggest and prioritize; they never confer execution, DLE promotion or release rights. + +Cross-validation should include reversed control (no action), changed one input/asset, intentionally wrong binary/offset/frame order, repeat across Wine/QEMU/native where eligible, and comparison to source-known Freeciv ground truth. Do not imply a synthetic SDL frame, empty audio baseline or screen classifier is proof of legacy SMAC behavior. + +## Current gate + +Public Freeciv source-known GHA may execute. Private `ghidra-tools` prototype remains unmerged and not admitted to public runners. Original SMAC/SMAX binary and local/sovereign workcells are deferred under `mark-e-deyoung/reverse-smac#37`. Sidecar/Pandora caller admission is not established. No arbitrary script MCP, public tunnel, private hosted minutes, merge or release. diff --git a/qualification/surrogates/freeciv/critics/README.md b/qualification/surrogates/freeciv/critics/README.md new file mode 100644 index 00000000..2bbc0442 --- /dev/null +++ b/qualification/surrogates/freeciv/critics/README.md @@ -0,0 +1,21 @@ +# Reversing observatory — public-safe critic candidate interviews + +This folder is a source-neutral qualification fixture, **not** a deployed agent or a route to private game/runtime sources. The public GitHub Actions matrix must use CPU-only ephemeral runners, with no account tokens, credentials, private checkout, licensed game assets, raw customer/game captures, external listening ports or model-generated code execution. + +## Previously adopted candidate interview protocol + +Unit of qualification: `task × harness × model × configuration × tool permissions × compute substrate`. A candidate passes a **specific bounded task**, never a general benchmark or self-granted authority. Preflight requires exact source/model revision, license, resource envelope and independent ground truth. Execute against matched positive/negative and contradictory controls; perform repeat/crossover tests, report accuracy, false-positive/hallucination, latency, memory, reproducibility, first failure and limitations. Compare deterministic oracles alongside each model. Preserve failing candidates in DLE rather than turning unknown into green. + +| task | candidate | expected use | exact acceptance limit | +| --- | --- | --- | --- | +| Evidence reasoning | `Qwen/Qwen2.5-Coder-0.5B-Instruct` revision `ea3f247` | rank next authorized observation, not permit actions | strict JSON + all cited evidence from fixture; fabricated references/actions fail | +| Frame/video VLM | `HuggingFaceTB/SmolVLM2-256M-Video-Instruct` revision `e62441b82f8a003a40e89eee6005489a0e9c0598` | compare controlled object motion across two source-known frames | left/right opposite controls; reported word must be unambiguous | +| Speech/audio critic | `openai/whisper-tiny` revision `169d4a4` | speech transcription on source-known synthetic sample | spoken "save the game" versus silence; silence hallucination fails | + +**Not yet represented by a model here:** generic non-speech game SFX classification, frame-by-frame pixel segmentation, object ID attribution, full video event detection, multilingual speech/noise robustness, source-code repair autonomy or an actual integrated reasoning agent. Future candidates include AudioSet AST for environmental sound classification; Whisper is a speech model, not a sound-effect detector. Each requires separate matched datasets, threat-model and resource qualification. A failed CPU inference or unavailable published artifact remains `UNQUALIFIED` with typed failure, never a fabricated model score. + +## Why this is not a Cloudflare MCP bridge + +The candidate workflow runs short, bounded one-shot evaluations and uploads sanitized summary JSON. It does **not** expose an HTTP server. An ephemeral Cloudflare Quick Tunnel can expose a workcell endpoint, but a random hostname is not authentication; a public tunnel can be called by anyone who knows its URL and lasts only while the underlying process remains active. Before a ChatGPT/agent connection is eligible, require a registered client supporting streamable HTTP MCP, scoped authentication, per-tool authorization, TLS, signed immutable workset identity, read-only default, denied hidden-tool calls, expiry and revocation, origin/cross-tenant isolation, replay/idempotency, cancellation and cleanup. A successful tunnel GET or public Actions workflow is not proof of an admitted ChatGPT tool connector. The existing Pandora denial and SMAC original-binary hold remain unchanged. + +All model outputs are **ADVISORY_NOT_RUNTIME_EVIDENCE**, cannot authorize write/manipulation, and must be challenged by independent deterministic evidence before any publication or acceptance. Do not copy private `ghidra-tools` code into public jobs. diff --git a/qualification/surrogates/freeciv/critics/interview.py b/qualification/surrogates/freeciv/critics/interview.py new file mode 100644 index 00000000..51a954ac --- /dev/null +++ b/qualification/surrogates/freeciv/critics/interview.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Bounded, public-safe critic interview. No real/private runtime data or actuation. + +One candidate = task x harness x model x configuration x substrate. Scores are +advisory; they never authorize writes or promote game evidence classes. +""" +import argparse +import json +import math +import subprocess +import time +import wave +from pathlib import Path + +MODEL = { + "reasoning": ("Qwen/Qwen2.5-Coder-0.5B-Instruct", "ea3f247"), + "vision": ("HuggingFaceTB/SmolVLM2-256M-Video-Instruct", "e62441b82f8a003a40e89eee6005489a0e9c0598"), + "audio": ("openai/whisper-tiny", "169d4a4"), +} +SCHEMA = "reversing-critic-interview/v0.1" + + +def admit(model_class): + if model_class not in MODEL: + raise ValueError("CANDIDATE_NOT_ALLOWLISTED") + return MODEL[model_class] + + +def evaluate_reasoning_reply(answer, expected, refs): + """A strict, bounded response gate; never treat verbose prose as proof.""" + try: + value = json.loads(answer.strip()) + except (ValueError, TypeError): + return False + if type(value) is not dict or set(value) != {"verdict", "evidence_refs", "next_action"}: + return False + if value["verdict"] != expected or value["next_action"] != "collect_more_evidence": + return False + return value["evidence_refs"] == refs + + +def summarize(class_name, model_id, revision, tests, elapsed, source_sha): + if not tests or any(not isinstance(v, bool) for v in tests.values()): + raise ValueError("INVALID_TEST_RESULTS") + passes = sum(tests.values()) + return { + "schema": SCHEMA, + "status": "PASS" if passes == len(tests) else "UNQUALIFIED", + "evidence_class": "PUBLIC_SYNTHETIC_MODEL_INTERVIEW_ONLY", + "candidate": {"task_class": class_name, "model_id": model_id, + "model_revision_requested": revision, + "model_revision_resolved": source_sha, "substrate": "gha-ubuntu-24.04-cpu"}, + "tests": tests, + "pass_count": passes, + "test_count": len(tests), + "duration_seconds": round(elapsed, 3), + "limitations": ["Synthetic fixture only; not independent game or model acceptance", + "Model cannot promote evidence or authorize any action", + "No private raw frames, audio, binaries, observations or model weights uploaded"], + } + + +def classify_motion(reply): + # Deliberately conservative: fail if both alternatives are asserted. + words = set(reply.lower().replace(".", " ").replace(",", " ").split()) + if "right" in words and "left" not in words: + return "right" + if "left" in words and "right" not in words: + return "left" + return "unknown" + + +def reasoning(): + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + model_id, revision = admit("reasoning") + tok = AutoTokenizer.from_pretrained(model_id, revision=revision) + mod = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, + torch_dtype=torch.float32).eval() + cases = [ + ("sha-mismatch", "Observed game executable SHA differs from Ghidra import digest. " + "Evidence ref=fixture:sha. Do we accept runtime function identity?", "REJECT", ["fixture:sha"]), + ("clock-domain", "Two probes measure events in unrelated clock domains with no " + "synchronization. Evidence ref=fixture:clock. Is causal ordering proven?", "REJECT", ["fixture:clock"]), + ("known-evidence", "The only observation is two identical synthetic save headers. " + "Evidence ref=fixture:save. Is full game-state equivalence proven?", "REJECT", ["fixture:save"]), + ] + output = {} + for testid, q, want, refs in cases: + messages = [{"role": "system", "content": "You are an evidence critic. Return ONLY compact JSON " + "with exactly verdict (REJECT or ACCEPT), evidence_refs (array), next_action " + "(collect_more_evidence). Never authorize a write."}, + {"role": "user", "content": q}] + inp = tok.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, + return_tensors="pt") + with torch.no_grad(): + pred = mod.generate(inp, do_sample=False, max_new_tokens=100, + pad_token_id=tok.eos_token_id) + text = tok.decode(pred[0][inp.shape[-1]:], skip_special_tokens=True) + output[testid] = evaluate_reasoning_reply(text, want, refs) + return output, mod.config._name_or_path + + +def synth_frame(x): + from PIL import Image, ImageDraw + image = Image.new("RGB", (256, 160), (25, 25, 30)) + draw = ImageDraw.Draw(image) + draw.rectangle((x, 58, x + 48, 104), fill=(0, 90, 240)) + return image + + +def vision(): + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + model_id, revision = admit("vision") + proc = AutoProcessor.from_pretrained(model_id, revision=revision) + mod = AutoModelForImageTextToText.from_pretrained(model_id, revision=revision, + torch_dtype=torch.float32).eval() + output = {} + for name, pair, target in [ + ("moves-right", (synth_frame(16), synth_frame(173)), "right"), + ("moves-left", (synth_frame(173), synth_frame(16)), "left"), + ]: + content = [{"type": "image", "image": pair[0]}, + {"type": "image", "image": pair[1]}, + {"type": "text", "text": "Compare frame one and frame two. " + "In which direction did the BLUE rectangle move, left or right? " + "Answer exactly one word: left OR right."}] + inputs = proc.apply_chat_template([{"role":"user","content":content}], + add_generation_prompt=True, tokenize=True, + return_dict=True, return_tensors="pt") + with torch.no_grad(): + ids = mod.generate(**inputs, do_sample=False, max_new_tokens=20) + result = proc.decode(ids[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True) + output[name] = classify_motion(result) == target + return output, mod.config._name_or_path + + +def synthetic_wav(path, mode): + """Test audio is original generated tones/silence; never use copyrighted sounds.""" + frequency = 440 + count = 16000 * 2 + with wave.open(str(path), "wb") as h: + h.setnchannels(1) + h.setsampwidth(2) + h.setframerate(16000) + import struct + for i in range(count): + sample = 0 if mode == "silence" else int(12000 * math.sin(2*math.pi*frequency*i/16000)) + h.writeframesraw(struct.pack(" 1: + data = data.mean(axis=1) + # espeak normally outputs 22050 Hz; use scipy for exact conversion. + if sr != 16000: + from scipy.signal import resample_poly + import math as stdmath + g = stdmath.gcd(sr, 16000) + data = resample_poly(data, 16000 // g, sr // g) + inp = proc(data.astype(np.float32), sampling_rate=16000, return_tensors="pt") + with torch.no_grad(): + ids = mod.generate(**inp, max_new_tokens=40, language="en", task="transcribe") + text = proc.batch_decode(ids, skip_special_tokens=True)[0].strip().lower() + if name == "speech": + output[name] = "save" in text and "game" in text + else: + output[name] = not text + return output, mod.config._name_or_path + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--class", dest="class_name", choices=tuple(MODEL), required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + model_id, revision = admit(args.class_name) + begin = time.monotonic() + try: + tests, _ = {"reasoning": reasoning, "vision": vision, + "audio": audio}[args.class_name]() + from huggingface_hub import model_info + resolved = model_info(model_id, revision=revision).sha + result = summarize(args.class_name, model_id, revision, tests, + time.monotonic()-begin, resolved) + except Exception as error: # Controlled classification, never publish raw traces. + result = {"schema": SCHEMA, "status": "UNQUALIFIED", + "evidence_class": "MODEL_NOT_QUALIFIED", + "candidate": {"task_class":args.class_name,"model_id":model_id, + "model_revision_requested":revision}, + "error_class": type(error).__name__} + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(result,sort_keys=True,indent=2)+"\n",encoding="utf-8") + print(json.dumps({"status":result["status"], "class":args.class_name, + "passed":result.get("pass_count",0), + "tested":result.get("test_count",0)},sort_keys=True)) + return 0 if result["status"]=="PASS" else 1 + + +if __name__=="__main__": + raise SystemExit(main()) diff --git a/qualification/surrogates/freeciv/critics/test_interview.py b/qualification/surrogates/freeciv/critics/test_interview.py new file mode 100644 index 00000000..caf21451 --- /dev/null +++ b/qualification/surrogates/freeciv/critics/test_interview.py @@ -0,0 +1,48 @@ +"""Offline model-interview scoring / negative checks (zero model downloads).""" +import importlib.util +import json +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location("reversing_model_interview", Path(__file__).with_name("interview.py")) +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) + + +class Tests(unittest.TestCase): + def test_allowlist(self): + self.assertEqual(set(m.MODEL), {"reasoning", "vision", "audio"}) + with self.assertRaises(ValueError): + m.admit("arbitrary-api") + + def test_reasoning_strict_evidence(self): + value = json.dumps({"verdict":"REJECT","evidence_refs":["fixture:clock"], + "next_action":"collect_more_evidence"}) + self.assertTrue(m.evaluate_reasoning_reply(value, "REJECT",["fixture:clock"])) + self.assertFalse(m.evaluate_reasoning_reply(value, "ACCEPT",["fixture:clock"])) + self.assertFalse(m.evaluate_reasoning_reply(value, "REJECT",["fixture:fake"])) + + def test_model_fabricated_authorization_rejected(self): + value = json.dumps({"verdict":"REJECT","evidence_refs":["fixture:clock"], + "next_action":"collect_more_evidence", "authorize":"write"}) + self.assertFalse(m.evaluate_reasoning_reply(value, "REJECT",["fixture:clock"])) + + def test_non_json_fail_closed(self): + self.assertFalse(m.evaluate_reasoning_reply("Sure, looks fine", "REJECT",["fixture:clock"])) + + def test_visual_ambiguous_fail_closed(self): + self.assertEqual(m.classify_motion("left and right"), "unknown") + self.assertEqual(m.classify_motion("right"), "right") + self.assertEqual(m.classify_motion("I cannot tell"), "unknown") + + def test_summary_requires_bools(self): + with self.assertRaises(ValueError): + m.summarize("x","y","z",{"ok":1},1,"sha") + + def test_partial_does_not_pass(self): + x=m.summarize("vision","m","r",{"positive":True,"negative":False},1,"hash") + self.assertEqual(x["status"],"UNQUALIFIED") + + +if __name__=="__main__": + unittest.main() diff --git a/qualification/surrogates/freeciv/io_boundary.py b/qualification/surrogates/freeciv/io_boundary.py new file mode 100644 index 00000000..c13834ac --- /dev/null +++ b/qualification/surrogates/freeciv/io_boundary.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Public-safe syscall boundary classification: local paths/data never leave workcell. + +Do not interpret syscall counts as decoder/engine semantics. The underlying +source-neutral event relationship is (process,fd,path-class,operation,bytes). +Raw per-event traces remain ephemeral; output contains aggregate counts only. +""" +import argparse +import json +import re +from collections import Counter +from pathlib import Path + +SCHEMA = "freeciv-io-boundaries/v0.1" +MAX_FILE_BYTES = 32 * 1024 * 1024 +MAX_LINES = 300_000 +FN = re.compile(r"^(?:[0-9]+(?:\.[0-9]+)?\s+)?(openat2?|read|pread64|readv|write|pwrite64|writev|mmap|mmap2|lseek|close)\(") +FD = re.compile(r"(?\n]{1,2048})>") +RET = re.compile(r"\)\s+=\s+(-?[0-9]+)(?:\s|$|<)") +MAP_RET = re.compile(r"\)\s+=\s+0x[0-9a-fA-F]+(?:\s|$)") +NATIVE_PATH = re.compile(r"(?:^|/)\.\.(?:/|$)") + + +def file_category(path): + p = path.lower() + if NATIVE_PATH.search(p): + return "other" + # No path names, hashes, data bytes or filesystem identities are exported. + if any(x in p for x in (".sav", "/save/", "/saves/")): + return "save_candidate" + if any(p.endswith(x) for x in (".so", ".so.0", ".so.1", ".dll")) or ".so." in p: + return "library_candidate" + if p.endswith((".ini", ".cfg", ".conf", ".json", ".xml")): + return "config_candidate" + if p.endswith((".png", ".bmp", ".wav", ".ogg", ".zip", ".pak", ".dat")): + return "asset_candidate" + return "other" + + +def parse_trace(folder): + """Require complete bounded traces; never emit raw trace lines/paths.""" + folder = Path(folder) + files = sorted(folder.glob("syscalls.*")) + if not files: + raise ValueError("TRACE_FILES_ABSENT") + counters = Counter() + per_kind = Counter() + total_size = 0 + line_count = 0 + for trace in files: + if not trace.is_file() or trace.is_symlink(): + raise ValueError("TRACE_FILE_UNSAFE") + size = trace.stat().st_size + total_size += size + if total_size > MAX_FILE_BYTES: + raise ValueError("TRACE_BUDGET_EXCEEDED") + with trace.open("r", encoding="utf-8", errors="replace") as handle: + for line in handle: + line_count += 1 + if line_count > MAX_LINES: + raise ValueError("TRACE_LINE_BUDGET_EXCEEDED") + m = FN.match(line) + if not m: + continue + name = m.group(1) + r = RET.search(line) + if name in ("mmap", "mmap2") and MAP_RET.search(line): + counters["mapping_calls"] += 1 + details = FD.search(line) + kind = file_category(details.group(2)) if details else "unknown_fd" + per_kind[(kind, "mapping_calls")] += 1 + continue + # Unlike strace output payloads, numeric returns are safe to use. + if r is None: + counters["unparsed_returns"] += 1 + continue + value = int(r.group(1)) + if value < 0: + counters["failed_calls"] += 1 + continue + counters["successful_calls"] += 1 + details = FD.search(line) + kind = file_category(details.group(2)) if details else "unknown_fd" + if name in ("read", "pread64", "readv"): + counters["read_calls"] += 1 + counters["bytes_read"] += value + per_kind[(kind, "read_calls")] += 1 + elif name in ("write", "pwrite64", "writev"): + counters["write_calls"] += 1 + counters["bytes_written"] += value + per_kind[(kind, "write_calls")] += 1 + elif name in ("mmap", "mmap2"): + counters["mapping_calls_numeric"] += 1 + elif name in ("openat", "openat2"): + counters["open_calls"] += 1 + per_kind[(kind, "open_calls")] += 1 + elif name == "lseek": + counters["seek_calls"] += 1 + # Avoid falsely concluding no mmap use: strace prints hex address returns. + status = "PASS" if counters["read_calls"] and counters["write_calls"] else "UNQUALIFIED" + return { + "schema": SCHEMA, + "status": status, + "evidence_class": "REAL_SYSCALL_METADATA_NOT_GAME_OBJECT_SEMANTICS", + "trace_files": len(files), + "lines_examined": line_count, + "counters": {k: int(v) for k, v in sorted(counters.items())}, + "file_category_counts": {f"{kind}.{operation}": int(v) + for (kind, operation), v in sorted(per_kind.items())}, + "limitations": [ + "FD path decoration is a best-effort Linux strace observation", + "read/write offsets are not proven without separate pread/lseek/open-file-description state", + "mmap page dirtiness and decoder semantics are not observed", + "No user paths, memory data, raw traces or game assets are exported", + ], + } + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--trace-dir", required=True) + p.add_argument("--output", required=True) + opts = p.parse_args() + try: + result = parse_trace(opts.trace_dir) + except (OSError, ValueError): + result = {"schema": SCHEMA, "status": "UNQUALIFIED", + "evidence_class": "NO_VALID_IO_TRACE"} + Path(opts.output).write_text(json.dumps(result, sort_keys=True, indent=2) + "\n", encoding="utf-8") + return 0 if result["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/qualification/surrogates/freeciv/run_io_native.py b/qualification/surrogates/freeciv/run_io_native.py new file mode 100644 index 00000000..32070bd5 --- /dev/null +++ b/qualification/surrogates/freeciv/run_io_native.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Actual Freeciv file-read/write/mapping boundary smoke; public-safe evidence only.""" +import argparse +import json +import os +import shutil +import subprocess +import tempfile +import time +from pathlib import Path + +import io_boundary +import probe + +SCHEMA = "freeciv-io-native/v0.1" + + +def run(seed, scratch): + server = shutil.which("freeciv-server") or "/usr/games/freeciv-server" + tracer = shutil.which("strace") + if not tracer or not Path(server).is_file(): + raise RuntimeError("NATIVE_DEPENDENCY_MISSING") + root = Path(scratch) + saves = root / "saves" + saves.mkdir() + port = 5601 + argv = [tracer, "-ff", "-qq", "-yy", "-s", "0", "-o", str(root / "syscalls"), + "-e", "trace=%file,%network,%process,read,write,pread64,pwrite64,mmap,lseek", + server, "--bind", "127.0.0.1", "--Announce", "none", "--port", str(port), + "--saves", str(saves)] + started = time.monotonic() + logfile = root / "server.log" + with logfile.open("wb") as handle: + proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=handle, stderr=subprocess.STDOUT, + cwd=root, start_new_session=True, + env={**os.environ, "HOME": str(root), "TZ":"UTC", "LANG":"C.UTF-8"}) + try: + if not probe.loopback_ready(port, deadline=7): + raise RuntimeError("SERVER_NOT_READY") + for cmd in ("set minplayers 0", "set aifill 2", f"set gameseed {seed}", + f"set mapseed {seed}", "set timeout 1", "create Caesar", + "aitoggle Caesar", "start"): + if not probe.send(proc, cmd): + raise RuntimeError("SERVER_COMMAND_REJECTED") + time.sleep(.08) + time.sleep(1.5) + if not probe.send(proc, "save surrogate-boundary"): + raise RuntimeError("SAVE_COMMAND_FAILED") + time.sleep(1) + if not probe.send(proc, "quit"): + raise RuntimeError("QUIT_COMMAND_FAILED") + rc = proc.wait(timeout=12) + if rc != 0: + raise RuntimeError("SERVER_EXIT_NONZERO") + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=3) + if proc.stdin: + proc.stdin.close() + classified = io_boundary.parse_trace(root) + saves_seen = probe.inspect_saves(saves) + files = classified["file_category_counts"] + signals = { + "real_game_process_exited_cleanly": True, + "traced_reads": classified["counters"].get("read_calls",0)>0, + "traced_writes": classified["counters"].get("write_calls",0)>0, + "mapped_file_backings": classified["counters"].get("mapping_calls",0)>0, + "save_file_observed": bool(saves_seen), + "save_candidate_write_calls": files.get("save_candidate.write_calls",0)>0, + } + return {"schema":SCHEMA, "status":"PASS" if all(signals.values()) else "UNQUALIFIED", + "evidence_class":"REAL_OPEN_SOURCE_FREECIV_IO_BOUNDARY_METADATA_ONLY", + "binary_sha256": probe.digest(Path(server).resolve()), + "seed":seed, "signals":signals, "io_summary": classified, + "elapsed_seconds":round(time.monotonic()-started,2), + "limitations":["No call stacks, buffer payloads, byte-accurate implicit offsets or decoder labels", + "No draw/audio/input surface; this is a headless server", + "No private or proprietary game content; external egress not independently firewalled"]} + + +def main(): + p=argparse.ArgumentParser() + p.add_argument("--seed",type=int,choices=(42,43),required=True) + p.add_argument("--output",required=True) + a=p.parse_args() + try: + with tempfile.TemporaryDirectory(prefix="freeciv-boundary-") as tmp: + result=run(a.seed,tmp) + except (OSError,ValueError,RuntimeError,subprocess.SubprocessError): + result={"schema":SCHEMA,"status":"UNQUALIFIED", "seed":a.seed, + "evidence_class":"NATIVE_IO_BOUNDARY_NOT_VERIFIED"} + path=Path(a.output) + path.parent.mkdir(parents=True,exist_ok=True) + path.write_text(json.dumps(result,sort_keys=True,indent=2)+"\n",encoding="utf-8") + print(json.dumps({"schema":SCHEMA,"seed":a.seed,"status":result["status"]})) + return 0 if result["status"]=="PASS" else 1 + +if __name__=="__main__": + raise SystemExit(main()) diff --git a/qualification/surrogates/freeciv/test_io_boundary.py b/qualification/surrogates/freeciv/test_io_boundary.py new file mode 100644 index 00000000..1959b4af --- /dev/null +++ b/qualification/surrogates/freeciv/test_io_boundary.py @@ -0,0 +1,81 @@ +"""Fail-closed I/O trace semantics, synthetic source-neutral fixtures.""" +import importlib.util +import tempfile +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location("freeciv_io_boundary", Path(__file__).with_name("io_boundary.py")) +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + + +class IOTests(unittest.TestCase): + def test_realistic_read_write_without_data_leak(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "syscalls.1").write_text( + 'openat(AT_FDCWD, "/tmp/private-alpha.sav", O_RDONLY) = 3\n' + 'read(3, "SECRET", 6) = 6\n' + 'write(4, "SECRET", 6) = 6\n') + r = mod.parse_trace(d) + self.assertEqual(r["status"], "PASS") + self.assertEqual(r["counters"]["bytes_read"], 6) + self.assertEqual(r["counters"]["bytes_written"], 6) + self.assertEqual(r["file_category_counts"]["save_candidate.read_calls"], 1) + self.assertNotIn("SECRET", str(r)) + self.assertNotIn("private-alpha", str(r)) + + def test_memory_mapping_metadata(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "syscalls.4").write_text( + 'mmap(NULL, 8192, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fffff000000\n' + 'read(3, "", 2) = 2\n' + 'write(4, "", 2) = 2\n') + result = mod.parse_trace(d) + self.assertEqual(result["counters"]["mapping_calls"], 1) + self.assertEqual(result["file_category_counts"]["asset_candidate.mapping_calls"], 1) + + def test_failed_call_does_not_count(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "syscalls.2").write_text('read(3, "", 10) = -1 EBADF\n') + r = mod.parse_trace(d) + self.assertEqual(r["status"], "UNQUALIFIED") + self.assertEqual(r["counters"]["failed_calls"], 1) + + def test_missing_trace_refused(self): + with tempfile.TemporaryDirectory() as d: + with self.assertRaisesRegex(ValueError, "ABSENT"): + mod.parse_trace(d) + + def test_symlink_trace_refused(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "actual").write_text("not trusted") + Path(d, "syscalls.1").symlink_to(Path(d, "actual")) + with self.assertRaisesRegex(ValueError, "UNSAFE"): + mod.parse_trace(d) + + def test_unsafe_budget(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "syscalls.1").write_bytes(b"x" * 64) + old = mod.MAX_FILE_BYTES + try: + mod.MAX_FILE_BYTES = 40 + with self.assertRaisesRegex(ValueError, "BUDGET"): + mod.parse_trace(d) + finally: + mod.MAX_FILE_BYTES = old + + def test_no_path_publication(self): + self.assertEqual(mod.file_category("/srv/secret/unit.png"), "asset_candidate") + self.assertEqual(mod.file_category("/srv/secret/settings.ini"), "config_candidate") + self.assertEqual(mod.file_category("/srv/secret/libengine.so.23"), "library_candidate") + self.assertEqual(mod.file_category("/srv/foo/../secret"), "other") + + def test_unmapped_descriptor_is_explicit(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "syscalls.1").write_text('read(3, "x", 1) = 1\nwrite(4, "y", 1) = 1\n') + r = mod.parse_trace(d) + self.assertEqual(r["file_category_counts"]["unknown_fd.read_calls"], 1) + + +if __name__ == "__main__": + unittest.main() From 25778dbedbe55c41791344f77bbd1b15891ef805 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:23:52 +0100 Subject: [PATCH 24/28] exp(reversing): source-known ptrace RIP to Ghidra interval bridge; repair CI lint --- .../workflows/surrogate-freeciv-ghidra-pc.yml | 72 +++++ .../surrogates/freeciv/critics/interview.py | 3 +- .../surrogates/freeciv/ghidra/PC_BRIDGE.md | 49 ++++ .../ghidra/PublicFreecivPcIntervals.java | 70 +++++ .../surrogates/freeciv/ghidra/pc_bridge.py | 275 ++++++++++++++++++ .../freeciv/ghidra/test_pc_bridge.py | 127 ++++++++ .../surrogates/freeciv/test_io_boundary.py | 5 +- 7 files changed, 597 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/surrogate-freeciv-ghidra-pc.yml create mode 100644 qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md create mode 100644 qualification/surrogates/freeciv/ghidra/PublicFreecivPcIntervals.java create mode 100644 qualification/surrogates/freeciv/ghidra/pc_bridge.py create mode 100644 qualification/surrogates/freeciv/ghidra/test_pc_bridge.py diff --git a/.github/workflows/surrogate-freeciv-ghidra-pc.yml b/.github/workflows/surrogate-freeciv-ghidra-pc.yml new file mode 100644 index 00000000..86d2b132 --- /dev/null +++ b/.github/workflows/surrogate-freeciv-ghidra-pc.yml @@ -0,0 +1,72 @@ +name: Freeciv source-known native PC to Ghidra interval qualification +on: + pull_request: + paths: + - '.github/workflows/surrogate-freeciv-ghidra-pc.yml' + - 'qualification/surrogates/freeciv/ghidra/PublicFreecivPcIntervals.java' + - 'qualification/surrogates/freeciv/ghidra/pc_bridge.py' + - 'qualification/surrogates/freeciv/ghidra/test_pc_bridge.py' + - 'qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md' + +permissions: + contents: read + +jobs: + source-known-runtime-pc: + runs-on: ubuntu-24.04 + timeout-minutes: 18 + steps: + - name: Checkout public-only fixture without persisted credentials + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: JDK25 for pinned upstream Ghidra + uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 + with: + distribution: temurin + java-version: '25' + - name: Bounded deterministic and live source-known ptrace negatives + run: | + set -euo pipefail + python3 qualification/surrogates/freeciv/ghidra/test_pc_bridge.py -v + - name: Install pinned open-source Freeciv and pinned official Ghidra 12.2 + env: + DEBIAN_FRONTEND: noninteractive + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends freeciv-server=3.1.0+ds-1build5 curl unzip + echo '33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472 /usr/games/freeciv-server' | sha256sum -c - + curl -fLSs --retry 2 --connect-timeout 15 --max-time 230 \ + 'https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.2_build/ghidra_12.2_PUBLIC_20261016.zip' \ + -o "$RUNNER_TEMP/ghidra.zip" + printf '%s %s\n' '2c2cd776db3c1f6a097ba418922378ac3649cadd5e844a6f5f088ae628a7be67' "$RUNNER_TEMP/ghidra.zip" | sha256sum -c - + mkdir -p "$RUNNER_TEMP/ghidra" + unzip -q "$RUNNER_TEMP/ghidra.zip" -d "$RUNNER_TEMP/ghidra" + - name: Native Ghidra body intervals and actual Linux x86-64 instruction pointers + run: | + set -euo pipefail + analyzer=$(find "$RUNNER_TEMP/ghidra" -type f -path '*/support/analyzeHeadless' -print -quit) + test -n "$analyzer" + mkdir -p "$RUNNER_TEMP/ghidra-projects" "$RUNNER_TEMP/private-pc" "$RUNNER_TEMP/public-safe" + "$analyzer" "$RUNNER_TEMP/ghidra-projects" FreecivPcSurrogate \ + -import /usr/games/freeciv-server \ + -scriptPath "$GITHUB_WORKSPACE/qualification/surrogates/freeciv/ghidra" \ + -postScript PublicFreecivPcIntervals.java \ + 33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472 \ + "$RUNNER_TEMP/private-pc/ghidra-intervals.json" \ + -analysisTimeoutPerFile 180 -max-cpu 2 -deleteProject \ + > "$RUNNER_TEMP/private-pc/ghidra.log" 2>&1 + test -s "$RUNNER_TEMP/private-pc/ghidra-intervals.json" || { echo GHIDRA_EPHEMERAL_RANGES_ABSENT; exit 1; } + python3 qualification/surrogates/freeciv/ghidra/pc_bridge.py \ + --intervals "$RUNNER_TEMP/private-pc/ghidra-intervals.json" \ + --output "$RUNNER_TEMP/public-safe/freeciv-pc-bridge.json" \ + --rounds 180 + - name: Upload only bounded PC/function-match counts + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: freeciv-pc-ghidra-source-known-public + path: ${{ runner.temp }}/public-safe/freeciv-pc-bridge.json + if-no-files-found: ignore + retention-days: 3 diff --git a/qualification/surrogates/freeciv/critics/interview.py b/qualification/surrogates/freeciv/critics/interview.py index 51a954ac..1d8f8577 100644 --- a/qualification/surrogates/freeciv/critics/interview.py +++ b/qualification/surrogates/freeciv/critics/interview.py @@ -175,8 +175,9 @@ def audio(): data = data.mean(axis=1) # espeak normally outputs 22050 Hz; use scipy for exact conversion. if sr != 16000: - from scipy.signal import resample_poly import math as stdmath + + from scipy.signal import resample_poly g = stdmath.gcd(sr, 16000) data = resample_poly(data, 16000 // g, sr // g) inp = proc(data.astype(np.float32), sampling_rate=16000, return_tensors="pt") diff --git a/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md new file mode 100644 index 00000000..338ad47b --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md @@ -0,0 +1,49 @@ +# Source-known Freeciv real instruction-pointer → Ghidra interval bridge + +This independent *public-source* R054 RDTE probe extends the already qualified +Freeciv 3.1.0 real-game and Ghidra 12.2 controls. It cannot access private +Reversing/SMAC source, game binaries, licenses, or user workcells. + +## One independently proven coordinate system + +1. Pin the actual Ubuntu 24.04 Freeciv ELF SHA and independently pin the + original Ghidra release ZIP SHA. The Ghidra headless script exports a **private + ephemeral** list of half-open *relative virtual address* function body intervals, + with an exact SHA and image base; the interval list never becomes a public + artifact. Its entries can be non-contiguous and overlapping; preserve ambiguity. +2. Launch a Freeciv server as an unprivileged *direct child* of a disposable + public Linux x86-64 runner. Use `ptrace(PTRACE_ATTACH/GETREGS/DETACH)` for + **read-only** RIP sampling. Never patch code, set registers, or alter child memory. +3. Independently verify `/proc/PID/exe` identity by device/inode, executable + content SHA and coherent ELF PT_LOAD-to-`/proc/PID/maps` load bias. Convert + actual RIP to ELF virtual address by subtracting that verified bias. +4. Distinguish RIP in the executable and inside precisely one Ghidra function body, + RIP inside executable but outside recovered functions, RIP outside the main + executable, and ambiguous body overlap. Require at least one *actual* unambiguous + function match and no ambiguous ones for a positive acceptance. Do **not** + mistake a file-backed memory mapping or a static Ghidra function count for PC + evidence. +5. Discard real PC values, function positions, names, memory layouts, process logs, + raw Ghidra intervals and other paths. Publish *only* counts, exact public ELF + digest, typed classification, and limitations. No raw code/images/game content. + +## Negative and operational gates + +`test_pc_bridge.py` proves wrong SHA, deliberately wrong load bias, outside-body +and ambiguous-overlap cases, malformed duplicate JSON keys, bool/integer type +confusion and unsafe interval path. On a Linux x86-64 with gcc it also samples a +real *source-known self-built* disposable C child to qualify ptrace separately. + +If Ghidra's ELF virtual coordinate base differs from our documented ELF PT_LOAD +coordinate, or if sampled RIPs do not land in a uniquely mapped function body, +report `UNQUALIFIED` with the first failure. Do not artificially rebase results, +create a fabricated function match, or weaken any negative control to obtain green. + +Inputs: exact public Freeciv ELF and official release Ghidra 12.2, official Ubuntu +public hosted runner, same existing public WineBot DRAFT #157. Run consumes no +private hosted Actions minutes. No production deploy, merge or original game. + +Authority: `mark-e-deyoung/ghidra-tools#4` generic evidence semantics, +`SemperSupra/WineBot#157` runtime/surrogate receipt, +`mark-e-deyoung/reverse-smac#37` owner-held SMAC R3/R4. This is a source-known +public experimental probe and does not authorize original SMAC execution. diff --git a/qualification/surrogates/freeciv/ghidra/PublicFreecivPcIntervals.java b/qualification/surrogates/freeciv/ghidra/PublicFreecivPcIntervals.java new file mode 100644 index 00000000..565baf11 --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/PublicFreecivPcIntervals.java @@ -0,0 +1,70 @@ +// Ephemeral function-body interval export for public source-known Freeciv only. +// @category Freeciv.Surrogate +import ghidra.app.script.GhidraScript; +import ghidra.program.model.address.AddressRange; +import ghidra.program.model.address.AddressRangeIterator; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.FunctionIterator; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Locale; + +public class PublicFreecivPcIntervals extends GhidraScript { + @Override + public void run() throws Exception { + String[] args = getScriptArgs(); + if (args.length != 2 || !args[0].matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("GHIDRA_PC_ARGS_INVALID"); + } + if (currentProgram == null) { + throw new IllegalStateException("GHIDRA_PC_NO_PROGRAM"); + } + String actual = currentProgram.getExecutableSHA256(); + if (actual == null || !actual.toLowerCase(Locale.ROOT).equals(args[0])) { + throw new IllegalStateException("GHIDRA_PC_DIGEST_MISMATCH"); + } + long imageBase = currentProgram.getImageBase().getOffset(); + if (imageBase < 0) { + throw new IllegalStateException("GHIDRA_PC_IMAGE_BASE_INVALID"); + } + long count = 0; + long intervalCount = 0; + StringBuilder data = new StringBuilder(720000); + data.append("{\"schema\":\"freeciv-ghidra-pc-intervals/v0.1\",\"artifact_sha256\":\"") + .append(actual.toLowerCase(Locale.ROOT)) + .append("\",\"image_base\":").append(imageBase) + .append(",\"intervals\":["); + FunctionIterator functions = currentProgram.getFunctionManager().getFunctions(true); + while (functions.hasNext()) { + Function function = functions.next(); + count++; + if (count > 200000) throw new IllegalStateException("GHIDRA_PC_FUNCTION_BUDGET"); + AddressRangeIterator ranges = function.getBody().getAddressRanges(); + boolean hasBody = false; + while (ranges.hasNext()) { + AddressRange range = ranges.next(); + long start = Math.subtractExact(range.getMinAddress().getOffset(), imageBase); + long end = Math.addExact(Math.subtractExact(range.getMaxAddress().getOffset(), imageBase), 1); + if (start < 0 || end <= start) throw new IllegalStateException("GHIDRA_PC_RANGE_INVALID"); + if (intervalCount != 0) data.append(','); + // Include a function ordinal, not a name, to preserve ambiguous interval provenance. + data.append('[').append(start).append(',').append(end).append(',').append(count).append(']'); + intervalCount++; + if (intervalCount > 2000000 || data.length() > 48000000) + throw new IllegalStateException("GHIDRA_PC_INTERVAL_BUDGET"); + hasBody = true; + } + if (!hasBody) throw new IllegalStateException("GHIDRA_PC_EMPTY_BODY"); + } + if (count < 100 || intervalCount < count) { + throw new IllegalStateException("GHIDRA_PC_DISCOVERY_TOO_SMALL"); + } + data.append("],\"function_count\":").append(count).append('}'); + Path dest = Paths.get(args[1]).toAbsolutePath(); + Files.createDirectories(dest.getParent()); + Files.write(dest, data.toString().getBytes(StandardCharsets.UTF_8)); + println("EPHEMERAL_GHIDRA_PC_INTERVAL_EXPORT_COMPLETE"); + } +} diff --git a/qualification/surrogates/freeciv/ghidra/pc_bridge.py b/qualification/surrogates/freeciv/ghidra/pc_bridge.py new file mode 100644 index 00000000..7730ccbd --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/pc_bridge.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Read-only native Freeciv PC -> ephemeral Ghidra function interval correlation. + +Only bounded counts/typed evidence may leave disposable public runner. No raw +addresses, function labels, paths, process memory or game saves are published. +""" +from __future__ import annotations + +import argparse +import bisect +import ctypes +import hashlib +import json +import os +import platform +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import elf_map_probe # noqa: E402 -- sibling's audited public source, no private dependency + +SCHEMA = "freeciv-pc-ghidra-bridge/v0.1" +INTERVAL_SCHEMA = "freeciv-ghidra-pc-intervals/v0.1" +MAX_INTERVAL_FILE = 36 * 1024 * 1024 +ELF_SHA256 = "33a15db1dc9a250c7ecf215c3fe6d50c34409301f4bb783914a6b16f3b3e8472" +PTRACE_ATTACH = 16 +PTRACE_DETACH = 17 +PTRACE_GETREGS = 12 + + +class PCError(ValueError): + """Non-sensitive, stable rejection code.""" + + +def strict_object(pairs): + o = {} + for key, value in pairs: + if key in o: + raise PCError("DUPLICATE_WITNESS_KEY") + o[key] = value + return o + + +def load_intervals(path, expected_sha256): + path = Path(path) + if path.is_symlink() or not path.is_file() or not (0 < path.stat().st_size <= MAX_INTERVAL_FILE): + raise PCError("GHIDRA_INTERVAL_FILE_INVALID") + try: + x = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=strict_object) + except (UnicodeError, json.JSONDecodeError) as exc: + raise PCError("GHIDRA_INTERVAL_JSON_INVALID") from exc + if not isinstance(x, dict) or set(x) != {"schema", "artifact_sha256", "image_base", "intervals", "function_count"}: + raise PCError("GHIDRA_INTERVAL_SCHEMA_INVALID") + if x["schema"] != INTERVAL_SCHEMA or x["artifact_sha256"] != expected_sha256: + raise PCError("GHIDRA_INTERVAL_IDENTITY_MISMATCH") + if type(x["image_base"]) is not int or x["image_base"] < 0: + raise PCError("GHIDRA_IMAGE_BASE_INVALID") + if type(x["function_count"]) is not int or not (100 <= x["function_count"] <= 200000): + raise PCError("GHIDRA_FUNCTION_COUNT_INVALID") + arr = x["intervals"] + if not isinstance(arr, list) or not (x["function_count"] <= len(arr) <= 2000000): + raise PCError("GHIDRA_INTERVAL_COUNT_INVALID") + triples = [] + for y in arr: + if (not isinstance(y, list) or len(y) != 3 or + any(type(n) is not int for n in y) or not (0 <= y[0] < y[1] <= 2**63) or + not (1 <= y[2] <= x["function_count"])): + raise PCError("GHIDRA_RANGE_INVALID") + triples.append(tuple(y)) + return sorted(triples) + + +def classify_elf_pc(pc, bias, ranges, executable_segments): + """Return exactly one of executable-body / ambiguous / executable-unmapped / outside-image.""" + if type(pc) is not int or type(bias) is not int or pc <= 0 or bias < 0 or pc < bias: + return "OUTSIDE_IMAGE" + rva = pc - bias + in_exec = any(vaddr <= rva < vaddr + filesz and flags & 1 + for _off, vaddr, filesz, flags in executable_segments) + if not in_exec: + return "OUTSIDE_IMAGE" + # A binary search on sorted starts retains exact tie/overlap behavior; + # a scan of adjoining intervals is acceptable at this size (< 2m). + starts = [r[0] for r in ranges] + right = bisect.bisect_right(starts, rva) + # The intervals are Ghidra function *bodies*, possibly non-contiguous. + matches = [r for r in ranges[:right] if r[1] > rva] + if len(matches) > 1: + return "AMBIGUOUS_FUNCTION" + return "FUNCTION_MATCH" if matches else "EXECUTABLE_NOT_IN_FUNCTION" + + +def derive_verified_load_bias(pid, binary, sha256): + """Verify device/inode/hash and all maps, then derive one unique ASLR bias.""" + _receipt = elf_map_probe.observe_pid(pid, binary, sha256) + path = Path(binary) + kind, segments = elf_map_probe.elf_segments(path) + st = path.stat() + text = Path(f"/proc/{pid}/maps").read_text(encoding="ascii", errors="replace") + rows = elf_map_probe.map_rows(text, (os.major(st.st_dev), os.minor(st.st_dev)), st.st_ino) + page = os.sysconf("SC_PAGE_SIZE") + votes = {} + for idx, (start, _end, offset, _perm) in enumerate(rows): + for soff, va, size, _flags in segments: + seg_start = soff & ~(page - 1) + seg_end = (soff + size + page - 1) & ~(page - 1) + if seg_start <= offset < seg_end: + bias = start - (va - soff + offset) + if bias >= 0 and bias % page == 0 and (kind != 2 or bias == 0): + votes.setdefault(bias, set()).add(idx) + if not votes: + raise PCError("NO_LOAD_BIAS") + best = max(map(len, votes.values())) + winners = [v for v, indexes in votes.items() if len(indexes) == best] + if len(winners) != 1 or best != len(rows): + raise PCError("LOAD_BIAS_INCONSISTENT") + return winners[0], segments + + +# Linux x86-64 kernel user_regs_struct, used only by a direct parent of this +# disposable workcell's own unprivileged child process. +_REGS_FIELDS = "r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs eflags rsp ss fs_base gs_base ds es fs gs".split() + + +class UserRegs(ctypes.Structure): + _fields_ = [(field, ctypes.c_ulonglong) for field in _REGS_FIELDS] + + +def sample_pc_once(pid): + """Parent-only ptrace attach/register read/detach, never mutate target memory.""" + libc = ctypes.CDLL(None, use_errno=True) + ptrace = libc.ptrace + ptrace.restype = ctypes.c_long + if ptrace(PTRACE_ATTACH, pid, None, None) != 0: + raise PCError("PTRACE_ATTACH_NOT_ADMITTED") + stopped = False + try: + got, status = os.waitpid(pid, 0) + stopped = got == pid and os.WIFSTOPPED(status) + if not stopped: + raise PCError("PTRACE_TARGET_NOT_STOPPED") + registers = UserRegs() + if ptrace(PTRACE_GETREGS, pid, None, ctypes.byref(registers)) != 0: + raise PCError("PTRACE_GETREGS_FAILED") + if not registers.rip: + raise PCError("PTRACE_NO_INSTRUCTION_POINTER") + return registers.rip + finally: + # A failed attach is never followed by detach; a successful attach + # always attempts to resume the child even if register inspection fails. + if ptrace(PTRACE_DETACH, pid, None, None) != 0 and stopped: + raise PCError("PTRACE_DETACH_FAILED") + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def wait_ready(port, proc, deadline_s=8): + deadline = time.monotonic() + deadline_s + while time.monotonic() < deadline: + if proc.poll() is not None: + return False + try: + with socket.create_connection(("127.0.0.1", port), timeout=.2): + return True + except OSError: + time.sleep(.1) + return False + + +def native_probe(interval_path, binary= "/usr/games/freeciv-server", rounds=140): + if platform.machine() != "x86_64" or sys.platform != "linux": + raise PCError("LINUX_X86_64_REQUIRED") + if not Path(binary).is_file() or elf_map_probe.file_digest(binary) != ELF_SHA256: + raise PCError("FREECIV_BINARY_DIGEST_MISMATCH") + ranges = load_intervals(interval_path, ELF_SHA256) + port = free_port() + with tempfile.TemporaryDirectory(prefix="freeciv-pc-") as d: + root = Path(d) + # The local server is not announced; the only network use is localhost. + args = [binary, "--bind", "127.0.0.1", "--Announce", "none", "--port", str(port), + "--saves", str(root / "saves")] + (root / "saves").mkdir() + with (root / "server.log").open("wb") as logs: + proc = subprocess.Popen(args, cwd=root, stdin=subprocess.PIPE, stdout=logs, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + env={**os.environ, "HOME": str(root), "LANG": "C.UTF-8", "TZ": "UTC"}) + try: + if not wait_ready(port, proc): + raise PCError("FREECIV_SERVER_NOT_READY") + bias, segments = derive_verified_load_bias(proc.pid, binary, ELF_SHA256) + commands = ("set minplayers 0", "set aifill 2", "set timeout 1", "hard", + "create Caesar", "aitoggle Caesar", "start") + for cmd in commands: + if proc.poll() is not None: + raise PCError("FREECIV_EXITED_EARLY") + proc.stdin.write(cmd + "\n") + proc.stdin.flush() + time.sleep(.05) + counts = {k: 0 for k in ("FUNCTION_MATCH", "AMBIGUOUS_FUNCTION", + "EXECUTABLE_NOT_IN_FUNCTION", "OUTSIDE_IMAGE")} + sampled = 0 + for _ in range(rounds): + if proc.poll() is not None: + break + try: + pc = sample_pc_once(proc.pid) + except PCError as exc: + if str(exc) == "PTRACE_ATTACH_NOT_ADMITTED": + raise + # Fail closed for any other debugger or lifecycle fault. + raise PCError("PTRACE_SAMPLE_INTERRUPTED") from exc + counts[classify_elf_pc(pc, bias, ranges, segments)] += 1 + sampled += 1 + time.sleep(.025) + # Verify exact process file/map identity again after sampling. + derive_verified_load_bias(proc.pid, binary, ELF_SHA256) + result = { + "schema": SCHEMA, + "evidence_class": "REAL_FREECIV_PTRACE_GHIDRA_FUNCTION_IF_MATCHED", + "artifact_sha256": ELF_SHA256, + "ptrace_registers_observed": sampled > 0, + "one_verified_load_bias": True, + "ghidra_interval_count": len(ranges), + "sample_count": sampled, + "classification_counts": counts, + "function_pc_correlated": counts["FUNCTION_MATCH"] > 0 and counts["AMBIGUOUS_FUNCTION"] == 0, + "no_raw_addresses_uploaded": True, + } + result["status"] = "PASS" if result["function_pc_correlated"] else "UNQUALIFIED" + return result + finally: + if proc.poll() is None: + try: + proc.stdin.write("quit\n") + proc.stdin.flush() + proc.wait(timeout=4) + except (OSError, subprocess.TimeoutExpired): + proc.kill() + proc.wait(timeout=3) + if proc.stdin: + proc.stdin.close() + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--intervals", required=True) + ap.add_argument("--output", required=True) + ap.add_argument("--rounds", type=int, default=140) + opts = ap.parse_args(argv) + dest = Path(opts.output) + dest.parent.mkdir(parents=True, exist_ok=True) + try: + if not 1 <= opts.rounds <= 240: + raise PCError("ROUND_BUDGET_INVALID") + report = native_probe(opts.intervals, rounds=opts.rounds) + except (PCError, OSError, ValueError) as exc: + report = {"schema": SCHEMA, "status": "UNQUALIFIED", "evidence_class": "RUNTIME_PC_NOT_QUALIFIED", + "error_code": str(exc) if isinstance(exc, PCError) else "NATIVE_RUNTIME_FAILURE"} + dest.write_text(json.dumps(report, sort_keys=True) + "\n") + print(json.dumps({"schema": SCHEMA, "status": report["status"], "error_code": report.get("error_code")}, sort_keys=True)) + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py new file mode 100644 index 00000000..b80b1d51 --- /dev/null +++ b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Adversarial source-neutral pointer mapping tests; no original game required.""" +import importlib.util +import json +import sys +import types +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +# The live runner provides the sibling ELF module. Local isolated unit tests +# use a no-op import stub because only the native integration calls that helper. +if not (Path(__file__).resolve().parent.parent / "elf_map_probe.py").exists(): + sys.modules["elf_map_probe"] = types.ModuleType("elf_map_probe") +spec = importlib.util.spec_from_file_location("pc_bridge", Path(__file__).with_name("pc_bridge.py")) +bridge = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bridge) + + +def fixture(path, digest="a" * 64, ranges=None, functions=100): + if ranges is None: + ranges = [[4096 + j * 16, 4104 + j * 16, j + 1] for j in range(functions)] + x = {"schema": bridge.INTERVAL_SCHEMA, "artifact_sha256": digest, "image_base": 1048576, + "function_count": functions, "intervals": ranges} + Path(path).write_text(json.dumps(x), encoding="utf-8") + + +class PcBridgeContracts(unittest.TestCase): + def test_exact_schema_and_correct_identity(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + arr = bridge.load_intervals(path, "a" * 64) + self.assertEqual(len(arr), 100) + self.assertEqual(bridge.classify_elf_pc(0x71000000 + 4097, 0x71000000, arr, + [(0, 4096, 2000, 5)]), "FUNCTION_MATCH") + + def test_wrong_hash_cannot_match(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + with self.assertRaisesRegex(bridge.PCError, "IDENTITY_MISMATCH"): + bridge.load_intervals(path, "b" * 64) + + def test_deliberately_wrong_bias_rejected(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + intervals = bridge.load_intervals(path, "a" * 64) + self.assertEqual(bridge.classify_elf_pc(0x71000000 + 4097, 0x71002000, intervals, + [(0, 4096, 2000, 5)]), "OUTSIDE_IMAGE") + + def test_outside_function_not_promoted(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + intervals = bridge.load_intervals(path, "a" * 64) + self.assertEqual(bridge.classify_elf_pc(0x71000000 + 4108, 0x71000000, intervals, + [(0, 4096, 2000, 5)]), "EXECUTABLE_NOT_IN_FUNCTION") + + def test_ambiguity_rejected(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + spans = [[4096 + j * 16, 4104 + j * 16, j + 1] for j in range(100)] + spans[1] = [4096, 4105, 2] + fixture(path, ranges=spans) + intervals = bridge.load_intervals(path, "a" * 64) + self.assertEqual(bridge.classify_elf_pc(0x71000000 + 4097, 0x71000000, intervals, + [(0, 4096, 2000, 5)]), "AMBIGUOUS_FUNCTION") + + def test_duplicate_json_keys_rejected(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + text = path.read_text() + path.write_text(text.replace('"image_base":', '"image_base": 4, "image_base":', 1)) + with self.assertRaisesRegex(bridge.PCError, "DUPLICATE_WITNESS_KEY"): + bridge.load_intervals(path, "a" * 64) + + def test_boolean_integer_rejected(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + j = json.loads(path.read_text()) + j["intervals"][0][1] = True + path.write_text(json.dumps(j)) + with self.assertRaisesRegex(bridge.PCError, "RANGE_INVALID"): + bridge.load_intervals(path, "a" * 64) + + def test_oversized_and_symlink_rejected(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d, "functions.json") + fixture(path) + link = Path(d, "link.json") + link.symlink_to(path) + with self.assertRaisesRegex(bridge.PCError, "FILE_INVALID"): + bridge.load_intervals(link, "a" * 64) + with self.assertRaisesRegex(bridge.PCError, "FILE_INVALID"): + bridge.load_intervals(Path(d, "not-there"), "a" * 64) + + def test_actual_process_ptrace_read_only(self): + # A real Linux x86_64 controlled C child; fail closed when unavailable, + # but do not silently accept any Ghidra/Freeciv claim from this test. + if shutil.which("gcc") is None: + self.skipTest("gcc unavailable in this local test environment") + with tempfile.TemporaryDirectory() as d: + src = Path(d, "busy.c") + dest = Path(d, "busy") + src.write_text('#include \nint main(void){volatile unsigned long i=0; ' + 'while(i<6000000000UL){i++;} return 0;}\n') + subprocess.run(["gcc", "-O0", "-fPIE", "-pie", str(src), "-o", str(dest)], + check=True, stdout=subprocess.DEVNULL) + proc = subprocess.Popen([str(dest)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + try: + pc = bridge.sample_pc_once(proc.pid) + self.assertGreater(pc, 0) + self.assertIsInstance(pc, int) + finally: + proc.kill() + proc.wait(timeout=3) + + +if __name__ == "__main__": + unittest.main() diff --git a/qualification/surrogates/freeciv/test_io_boundary.py b/qualification/surrogates/freeciv/test_io_boundary.py index 1959b4af..70378376 100644 --- a/qualification/surrogates/freeciv/test_io_boundary.py +++ b/qualification/surrogates/freeciv/test_io_boundary.py @@ -42,9 +42,8 @@ def test_failed_call_does_not_count(self): self.assertEqual(r["counters"]["failed_calls"], 1) def test_missing_trace_refused(self): - with tempfile.TemporaryDirectory() as d: - with self.assertRaisesRegex(ValueError, "ABSENT"): - mod.parse_trace(d) + with tempfile.TemporaryDirectory() as d, self.assertRaisesRegex(ValueError, "ABSENT"): + mod.parse_trace(d) def test_symlink_trace_refused(self): with tempfile.TemporaryDirectory() as d: From f846524188410c65ccc965e2fda1ff660ff622a2 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:32:55 +0100 Subject: [PATCH 25/28] exp(reversing): bounded RIP single-step after idle-loop negative control --- .../surrogates/freeciv/ghidra/PC_BRIDGE.md | 16 ++++ .../surrogates/freeciv/ghidra/pc_bridge.py | 95 ++++++++++++++++++- .../freeciv/ghidra/test_pc_bridge.py | 32 ++++++- 3 files changed, 136 insertions(+), 7 deletions(-) diff --git a/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md index 338ad47b..e8c5e345 100644 --- a/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md +++ b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md @@ -47,3 +47,19 @@ Authority: `mark-e-deyoung/ghidra-tools#4` generic evidence semantics, `SemperSupra/WineBot#157` runtime/surrogate receipt, `mark-e-deyoung/reverse-smac#37` owner-held SMAC R3/R4. This is a source-known public experimental probe and does not authorize original SMAC execution. + +## R054 follow-on: idle-loop counterexample and targeted correction + +The first real Freeciv head produced **180 read-only RIP register samples**, +all classified `OUTSIDE_IMAGE`, despite verified SHA/inode/mapping and a real +Ghidra interval index. Do not promote this negative to a function match. +The source-known, test-only corrective experiment may attach to its **own** +unprivileged Freeciv child and perform at most 2400 single-step instructions, +while posting one bounded command to wake the event loop. This modifies +execution **timing** but never writes code, memory, registers or files outside +scratch. The runner records passive and targeted classes separately and refuses +any ambiguous or absent match. A ten-test synthetic/native ptrace qualification +covers live attach and single-step/detach on a self-built test ELF. + +This is not a timing-faithful observational baseline; compare passive and +stepped experiments and treat instrumentation perturbations as material. diff --git a/qualification/surrogates/freeciv/ghidra/pc_bridge.py b/qualification/surrogates/freeciv/ghidra/pc_bridge.py index 7730ccbd..1475d28f 100644 --- a/qualification/surrogates/freeciv/ghidra/pc_bridge.py +++ b/qualification/surrogates/freeciv/ghidra/pc_bridge.py @@ -9,12 +9,10 @@ import argparse import bisect import ctypes -import hashlib import json import os +import signal import platform -import re -import shutil import socket import subprocess import sys @@ -32,6 +30,7 @@ PTRACE_ATTACH = 16 PTRACE_DETACH = 17 PTRACE_GETREGS = 12 +PTRACE_SINGLESTEP = 9 class PCError(ValueError): @@ -125,7 +124,7 @@ def derive_verified_load_bias(pid, binary, sha256): # Linux x86-64 kernel user_regs_struct, used only by a direct parent of this # disposable workcell's own unprivileged child process. -_REGS_FIELDS = "r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs eflags rsp ss fs_base gs_base ds es fs gs".split() +_REGS_FIELDS = ["r15", "r14", "r13", "r12", "rbp", "rbx", "r11", "r10", "r9", "r8", "rax", "rcx", "rdx", "rsi", "rdi", "orig_rax", "rip", "cs", "eflags", "rsp", "ss", "fs_base", "gs_base", "ds", "es", "fs", "gs"] class UserRegs(ctypes.Structure): @@ -158,6 +157,76 @@ def sample_pc_once(pid): raise PCError("PTRACE_DETACH_FAILED") + +def wait_stopped(pid, seconds=3): + """Bounded wait for a trace stop, protecting the runner from blocked syscalls.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + got, status = os.waitpid(pid, os.WNOHANG) + if got == pid: + if not os.WIFSTOPPED(status): + raise PCError("TRACE_CHILD_EXIT_OR_SIGNAL") + return status + time.sleep(.003) + # Stop the child before releasing debugger ownership; never leave a hung + # native workcell accidentally under ptrace control. + try: + os.kill(pid, signal.SIGSTOP) + os.waitpid(pid, 0) + except (ProcessLookupError, ChildProcessError): + pass + raise PCError("PTRACE_STEP_TIMEOUT") + + +def step_until_function(pid, classifier, wake=None, max_steps=2000): + """Read-only bounded instruction stepping, then detach and resume target. + + The debugger controls the child's execution timing (not target memory) and + samples real, executed RIP values. A mapping is only valid if the classifier + independently checked ELF identity and a unique Ghidra function interval. + """ + if not (1 <= max_steps <= 5000): + raise PCError("PTRACE_STEP_BUDGET_INVALID") + libc = ctypes.CDLL(None, use_errno=True) + ptrace = libc.ptrace + ptrace.restype = ctypes.c_long + if ptrace(PTRACE_ATTACH, pid, None, None) != 0: + raise PCError("PTRACE_ATTACH_NOT_ADMITTED") + stopped = False + counts = {k: 0 for k in ("FUNCTION_MATCH", "AMBIGUOUS_FUNCTION", + "EXECUTABLE_NOT_IN_FUNCTION", "OUTSIDE_IMAGE")} + steps = 0 + try: + wait_stopped(pid) + stopped = True + if wake is not None: + wake() + while True: + regs = UserRegs() + if ptrace(PTRACE_GETREGS, pid, None, ctypes.byref(regs)) != 0: + raise PCError("PTRACE_GETREGS_FAILED") + if not regs.rip: + raise PCError("PTRACE_NO_INSTRUCTION_POINTER") + label = classifier(regs.rip) + if label not in counts: + raise PCError("INTERNAL_CLASSIFIER_INVALID") + counts[label] += 1 + if label in ("FUNCTION_MATCH", "AMBIGUOUS_FUNCTION") or steps >= max_steps: + break + if ptrace(PTRACE_SINGLESTEP, pid, None, None) != 0: + raise PCError("PTRACE_SINGLESTEP_FAILED") + stopped = False + status = wait_stopped(pid) + stopped = True + if os.WSTOPSIG(status) != signal.SIGTRAP: + raise PCError("PTRACE_UNEXPECTED_SIGNAL") + steps += 1 + finally: + if stopped and ptrace(PTRACE_DETACH, pid, None, None) != 0: + raise PCError("PTRACE_DETACH_FAILED") + return {"steps_executed": steps, "classifications": counts} + + def free_port(): with socket.socket() as s: s.bind(("127.0.0.1", 0)) @@ -222,8 +291,23 @@ def native_probe(interval_path, binary= "/usr/games/freeciv-server", rounds=140) counts[classify_elf_pc(pc, bias, ranges, segments)] += 1 sampled += 1 time.sleep(.025) + # The server may be idle in libc poll(): passive samples then + # provide a truthful OUTSIDE_IMAGE negative. Bounded single-step + # follows *actual executed instructions* back into executable + # code, while one input command wakes the server's event loop. + targeted = None + if counts["FUNCTION_MATCH"] == 0: + def wake_server(): + proc.stdin.write("save pc-wakeup\n") + proc.stdin.flush() + targeted = step_until_function( + proc.pid, lambda pc: classify_elf_pc(pc, bias, ranges, segments), + wake=wake_server, max_steps=2400) # Verify exact process file/map identity again after sampling. derive_verified_load_bias(proc.pid, binary, ELF_SHA256) + targeted_counts = targeted["classifications"] if targeted is not None else {} + real_function_hits = counts["FUNCTION_MATCH"] + targeted_counts.get("FUNCTION_MATCH", 0) + ambiguous_hits = counts["AMBIGUOUS_FUNCTION"] + targeted_counts.get("AMBIGUOUS_FUNCTION", 0) result = { "schema": SCHEMA, "evidence_class": "REAL_FREECIV_PTRACE_GHIDRA_FUNCTION_IF_MATCHED", @@ -233,7 +317,8 @@ def native_probe(interval_path, binary= "/usr/games/freeciv-server", rounds=140) "ghidra_interval_count": len(ranges), "sample_count": sampled, "classification_counts": counts, - "function_pc_correlated": counts["FUNCTION_MATCH"] > 0 and counts["AMBIGUOUS_FUNCTION"] == 0, + "targeted_single_step": targeted, + "function_pc_correlated": real_function_hits > 0 and ambiguous_hits == 0, "no_raw_addresses_uploaded": True, } result["status"] = "PASS" if result["function_pc_correlated"] else "UNQUALIFIED" diff --git a/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py index b80b1d51..d71e9f69 100644 --- a/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py +++ b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py @@ -2,11 +2,11 @@ """Adversarial source-neutral pointer mapping tests; no original game required.""" import importlib.util import json -import sys -import types import shutil import subprocess +import sys import tempfile +import types import unittest from pathlib import Path @@ -100,6 +100,34 @@ def test_oversized_and_symlink_rejected(self): with self.assertRaisesRegex(bridge.PCError, "FILE_INVALID"): bridge.load_intervals(Path(d, "not-there"), "a" * 64) + def test_actual_process_single_step_and_restore(self): + if shutil.which("gcc") is None: + self.skipTest("gcc unavailable in this local test environment") + with tempfile.TemporaryDirectory() as d: + source = Path(d, "spin.c") + program = Path(d, "spin") + source.write_text('#include \nint main(void){volatile unsigned long i=0; ' + 'while(i<6000000000UL){i++;} return 0;}\n') + subprocess.run(["gcc", "-O0", "-fPIE", "-pie", str(source), "-o", str(program)], + check=True, stdout=subprocess.DEVNULL) + proc = subprocess.Popen([str(program)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + try: + observed = [] + + def classify(pc): + observed.append(pc) + return "FUNCTION_MATCH" if len(observed) == 5 else "OUTSIDE_IMAGE" + + result = bridge.step_until_function(proc.pid, classify, max_steps=15) + self.assertEqual(result["steps_executed"], 4) + self.assertEqual(result["classifications"]["FUNCTION_MATCH"], 1) + self.assertEqual(len(observed), 5) + self.assertIsNone(proc.poll()) # debugger detached; process resumed + finally: + proc.kill() + proc.wait(timeout=3) + def test_actual_process_ptrace_read_only(self): # A real Linux x86_64 controlled C child; fail closed when unavailable, # but do not silently accept any Ghidra/Freeciv claim from this test. From 29a34a736ffb1da21966e1a4b328e64c7261f370 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:44:40 +0100 Subject: [PATCH 26/28] chore(reversing): preserve RIP repeatability and fail-closed step-budget negatives --- .../surrogates/freeciv/ghidra/PC_BRIDGE.md | 15 ++++++++++++ .../surrogates/freeciv/ghidra/pc_bridge.py | 2 +- .../freeciv/ghidra/test_pc_bridge.py | 23 +++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md index e8c5e345..0d637641 100644 --- a/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md +++ b/qualification/surrogates/freeciv/ghidra/PC_BRIDGE.md @@ -63,3 +63,18 @@ covers live attach and single-step/detach on a self-built test ELF. This is not a timing-faithful observational baseline; compare passive and stepped experiments and treat instrumentation perturbations as material. + +### Repeatability and limitations + +The same exact public Ghidra/Freeciv R055 commit passed **two** separate +Actions job attempts: each saw 1 unambiguous function match among 180 actual +RIP samples, with no ambiguous hits. Both public evidence artifacts remain in +GitHub; those runs did **not** invoke the single-step fallback. A separate +source-known *local idle stdin-read* test attempted up to 2400 debugger steps +but did not reach the application text segment; this is a useful warning that +single-stepping a blocking runtime call does not ensure bounded progress into +application code. Do not claim targeted stepping is a native Freeciv success. +The deterministic bounded-abstention test therefore verifies that no function +hit is manufactured when the step budget expires. Use stronger explicit +application-event breakpoints/triggered sampling, independently qualified, +if a future scenario demands guaranteed code-path observation. diff --git a/qualification/surrogates/freeciv/ghidra/pc_bridge.py b/qualification/surrogates/freeciv/ghidra/pc_bridge.py index 1475d28f..f2f6b19b 100644 --- a/qualification/surrogates/freeciv/ghidra/pc_bridge.py +++ b/qualification/surrogates/freeciv/ghidra/pc_bridge.py @@ -11,8 +11,8 @@ import ctypes import json import os -import signal import platform +import signal import socket import subprocess import sys diff --git a/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py index d71e9f69..cbab608a 100644 --- a/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py +++ b/qualification/surrogates/freeciv/ghidra/test_pc_bridge.py @@ -100,6 +100,29 @@ def test_oversized_and_symlink_rejected(self): with self.assertRaisesRegex(bridge.PCError, "FILE_INVALID"): bridge.load_intervals(Path(d, "not-there"), "a" * 64) + def test_single_step_budget_abstains_without_function_match(self): + if shutil.which("gcc") is None: + self.skipTest("gcc unavailable in this local test environment") + with tempfile.TemporaryDirectory() as d: + source = Path(d, "spin.c") + program = Path(d, "spin") + source.write_text('#include \nint main(void){volatile unsigned long i=0; ' + 'while(i<6000000000UL){i++;} return 0;}\n') + subprocess.run(["gcc", "-O0", "-fPIE", "-pie", str(source), "-o", str(program)], + check=True, stdout=subprocess.DEVNULL) + proc = subprocess.Popen([str(program)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + try: + result = bridge.step_until_function( + proc.pid, lambda _pc: "OUTSIDE_IMAGE", max_steps=4) + self.assertEqual(result["steps_executed"], 4) + self.assertEqual(result["classifications"]["FUNCTION_MATCH"], 0) + self.assertEqual(result["classifications"]["OUTSIDE_IMAGE"], 5) + self.assertIsNone(proc.poll()) + finally: + proc.kill() + proc.wait(timeout=3) + def test_actual_process_single_step_and_restore(self): if shutil.which("gcc") is None: self.skipTest("gcc unavailable in this local test environment") From edc9cbff3d05c1543e01cd76c6ca7d3e3847afd6 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:39:47 +0100 Subject: [PATCH 27/28] exp(observatory): qualify source-known child breakpoints and state checkpoints --- .../surrogate-checkpoint-breakpoint.yml | 53 ++++ .../surrogates/freeciv/checkpoint/README.md | 25 ++ .../surrogates/freeciv/checkpoint/bridge.py | 226 ++++++++++++++++++ .../surrogates/freeciv/checkpoint/fixture.c | 26 ++ .../freeciv/checkpoint/test_bridge.py | 89 +++++++ 5 files changed, 419 insertions(+) create mode 100644 .github/workflows/surrogate-checkpoint-breakpoint.yml create mode 100644 qualification/surrogates/freeciv/checkpoint/README.md create mode 100644 qualification/surrogates/freeciv/checkpoint/bridge.py create mode 100644 qualification/surrogates/freeciv/checkpoint/fixture.c create mode 100644 qualification/surrogates/freeciv/checkpoint/test_bridge.py diff --git a/.github/workflows/surrogate-checkpoint-breakpoint.yml b/.github/workflows/surrogate-checkpoint-breakpoint.yml new file mode 100644 index 00000000..86e1aae3 --- /dev/null +++ b/.github/workflows/surrogate-checkpoint-breakpoint.yml @@ -0,0 +1,53 @@ +name: Public source-known breakpoint and checkpoint qualification +on: + pull_request: + paths: + - '.github/workflows/surrogate-checkpoint-breakpoint.yml' + - 'qualification/surrogates/freeciv/checkpoint/**' + +permissions: + contents: read + +concurrency: + group: source-known-breakpoint-${{ github.ref }} + cancel-in-progress: true + +jobs: + external-child-breakpoint: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Checkout public fixture without persisted credentials + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: Native direct-child breakpoint and deterministic negative controls + run: | + set -euo pipefail + ulimit -c 0 + cd qualification/surrogates/freeciv/checkpoint + python3 -W error test_bridge.py -v + gcc -std=c11 -O0 -fno-pie -no-pie -fno-omit-frame-pointer \ + -Wall -Wextra -Werror fixture.c -o "$RUNNER_TEMP/checkpoint-fixture" + sha=$(sha256sum "$RUNNER_TEMP/checkpoint-fixture" | cut -d ' ' -f1) + mkdir -p "$RUNNER_TEMP/checkpoint-public" + timeout 30s python3 bridge.py \ + --binary "$RUNNER_TEMP/checkpoint-fixture" --expected-sha "$sha" \ + --output "$RUNNER_TEMP/checkpoint-public/result.json" + python3 - "$RUNNER_TEMP/checkpoint-public/result.json" <<'PY' + import json,sys + x=json.load(open(sys.argv[1],encoding='utf-8')) + assert x['status']=='PASS' and x['breakpoint_hits']==2 + assert x['breakpoint_original_bytes_restored'] and x['child_clean_exit'] + assert x['state_transition_observed'] and len(x['checkpoint_digests'])==2 + assert not any(key in x for key in ('rip','address','memory','pid','maps')) + print('PUBLIC_SOURCE_KNOWN_BREAKPOINT_CHECKPOINT_PASS') + PY + - name: Upload only allowlisted fixture checkpoint receipt + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: source-known-external-breakpoint-checkpoints + path: ${{ runner.temp }}/checkpoint-public/result.json + if-no-files-found: ignore + retention-days: 3 diff --git a/qualification/surrogates/freeciv/checkpoint/README.md b/qualification/surrogates/freeciv/checkpoint/README.md new file mode 100644 index 00000000..dd59eaa1 --- /dev/null +++ b/qualification/surrogates/freeciv/checkpoint/README.md @@ -0,0 +1,25 @@ +# R056 — source-known breakpoint + checkpoint proof (public, disposable) + +**Owning runtime:** SemperSupra/WineBot draft PR #157. **Shared evidence authority:** mark-e-deyoung/ghidra-tools#4. **SMAC acceptance:** mark-e-deyoung/reverse-smac#37 (original game R3/R4 remains held). This adds no private source, proprietary assets or actual original game execution. + +## What this specifically proves + +The native Linux x86_64 direct-child ptrace workcell compiles a public C fixture under `-fno-pie -no-pie`, pins the ELF SHA256 and verifies the live `/proc/PID/exe` identity. It plants two software breakpoints (`INT3`) at fixed source-known functions and captures read-only snapshots of one watched 8-byte value **at each stop**. It restores the original instruction word at each hit, rewinds `RIP` by one to execute the genuine instruction and checks clean exit. Two separate launches produce the same baseline and post-action digests. Non-PIE ELF type is verified; a PIE with unknown load bias fails closed. + +The tool handles only a process it spawns itself and only three symbol names from the fixture. It has no general-purpose write API or external PID control. All state and machine addresses remain ephemeral. Uploaded metadata is a small allowlisted JSON; no raw trace, registers, payloads, screenshots, file contents, maps, paths, game binaries or source-byte patches. The software breakpoint temporarily changes **fixture** executable text and perturbs scheduling; it is not passive. + +This is a **two-value state checkpoint**, not a full-process snapshot or VM restore. An actual VM checkpoint must capture coherent RAM, disk and device state; a savegame checkpoint must verify serialization and reload separately. The current Freeciv turn/save/reload RDTE provides separate proof of the latter. Do not represent a pair of hashes as a complete checkpoint or replay proof. + +## External, internal and hypervisor boundaries + +- **Internal process hooks:** Wine/Win32 debugger callbacks, Frida Interceptor, Ghidra/GDB attach, game engine assertions, serializer/draw/audio API boundary probes. Require explicit process custody and bounded code mutation approval. +- **External process debugger:** GDB or `ptrace` software or hardware breakpoints; hardware memory watchpoints (`rwatch`, `awatch`, `watch` if supported), loader identity and ASLR controls; snapshots of selected state and exact clock domains. Current fixture exercises **software execution breakpoints** only, no data watchpoints. +- **External VM:** QEMU gdbstub break/watchpoints, QMP lifecycle and VM snapshots; PANDA/QEMU record-replay for reverse stepping if supported by the selected machine/configuration. A QEMU breakpoint must be placed in **guest** coordinates, not the host address of `qemu-system-*`. Check RAM+disk coherence, vCPU race, virtual devices and guest symbol/module load identity. + +## Native qualification and falsification + +`python3 -W error test_bridge.py -v` compiles real native ELF fixtures and tests: two genuine breakpoints and state digests; repeatability across launches; wrong exact SHA; symlink input; PIE without proven load bias; changed game state; absent symbol. An unqualified case must never be promoted to a pass. The `surrogate-checkpoint-breakpoint.yml` public workflow additionally runs the standalone CLI and inspects its final scrubbed receipt. No private hosted Actions minutes, privileged service, remote MCP exposure, secret, owner host, merger or release authority is needed. + +**Next real Freeciv step after source-native acceptance:** Select a function target from public Freeciv/Ghidra intervals using source-backed save/turn cross-references; arm a single per-process breakpoint at the independently verified actual load bias + RVA; execute one command, capture bounded RIP/stack/function event; restore original bytes and restart from known game save in an independent process; correlate event with actual save-file/turn change. Add wrong SHA, wrong bias, thread-hit, missed breakpoint, resource-budget, accidental re-entry and readback negatives before calling action attribution verified. The R055 passive 1/180 function hit remains historical evidence, not proof that a particular function caused a game event. + +**Do not attach to original SMAC / Windows 98, publish private observatory source to public CI, or expose raw GDB/QMP/Frida endpoints via a public tunnel without separate explicit authority.** diff --git a/qualification/surrogates/freeciv/checkpoint/bridge.py b/qualification/surrogates/freeciv/checkpoint/bridge.py new file mode 100644 index 00000000..3f08f501 --- /dev/null +++ b/qualification/surrogates/freeciv/checkpoint/bridge.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Isolated direct-child external breakpoints with scoped state checkpoints. + +Linux x86_64 only. This is deliberately NOT a general-purpose memory patch API. +The only executable accepted is the fixed, source-built fixture, with SHA256 +checked before launch and against /proc/PID/exe after the first trace stop. +""" +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import json +import os +import platform +import re +import signal +import subprocess +import sys +import time +from pathlib import Path + +SCHEMA = "reversing-public-breakpoint-checkpoint/v0.1" +TRACEME = 0 +PEEKTEXT = 1 +PEEKDATA = 2 +POKETEXT = 4 +CONT = 7 +GETREGS = 12 +SETREGS = 13 +WORD_BYTES = ctypes.sizeof(ctypes.c_long) +MAX_WALL_S = 12.0 +SYMBOLS = ("apply_action", "observe_after", "controlled_state") + + +class WitnessError(RuntimeError): + pass + + +class UserRegs(ctypes.Structure): + _fields_ = [(k, ctypes.c_ulonglong) for k in ( + "r15", "r14", "r13", "r12", "rbp", "rbx", "r11", "r10", "r9", "r8", "rax", + "rcx", "rdx", "rsi", "rdi", "orig_rax", "rip", "cs", "eflags", "rsp", "ss", + "fs_base", "gs_base", "ds", "es", "fs", "gs")] + + +LIBC = ctypes.CDLL(None, use_errno=True) +LIBC.ptrace.argtypes = [ctypes.c_uint, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] +LIBC.ptrace.restype = ctypes.c_long + + +def ptrace(cmd, pid, addr=0, data=0): + ctypes.set_errno(0) + val = LIBC.ptrace(cmd, pid, ctypes.c_void_p(addr), ctypes.c_void_p(data)) + err = ctypes.get_errno() + if val == -1 and err: + raise WitnessError("PTRACE_OPERATION_FAILED") + return val + + +def digest(path): + with Path(path).open("rb") as fh: + return hashlib.file_digest(fh, "sha256").hexdigest() + + +def symbols(binary): + out = subprocess.run(["nm", "-n", "--defined-only", str(binary)], check=True, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=4).stdout + matched = {} + for line in out.splitlines(): + m = re.fullmatch(r"([0-9a-fA-F]+)\s+([A-Za-z])\s+(\S+)", line) + if not m or m.group(3) not in SYMBOLS: + continue + name = m.group(3) + if name in matched or m.group(2) not in ("T", "D"): + raise WitnessError("AMBIGUOUS_FIXTURE_SYMBOL") + matched[name] = int(m.group(1), 16) + if set(matched) != set(SYMBOLS): + raise WitnessError("MISSING_FIXTURE_SYMBOL") + return matched + + +def wait_child(pid, deadline): + while time.monotonic() < deadline: + got, status = os.waitpid(pid, os.WNOHANG) + if got == pid: + return status + time.sleep(0.005) + raise WitnessError("CHILD_TIMEOUT") + + +def require_stop(status, signum): + if not os.WIFSTOPPED(status) or os.WSTOPSIG(status) != signum: + raise WitnessError("UNEXPECTED_TRACE_STOP") + + +def word(pid, addr): + return ptrace(PEEKTEXT, pid, addr) & ((1 << (WORD_BYTES * 8)) - 1) + + +def peek_state(pid, addr): + return ptrace(PEEKDATA, pid, addr) & ((1 << (WORD_BYTES * 8)) - 1) + + +def getregs(pid): + reg = UserRegs() + ptrace(GETREGS, pid, 0, ctypes.addressof(reg)) + return reg + + +def putregs(pid, reg): + ptrace(SETREGS, pid, 0, ctypes.addressof(reg)) + + +def run(binary, expected_sha): + if platform.system() != "Linux" or platform.machine() != "x86_64" or WORD_BYTES != 8: + raise WitnessError("LINUX_X86_64_REQUIRED") + user_path = Path(binary) + if user_path.is_symlink(): + raise WitnessError("INVALID_SOURCE_IDENTITY") + binary = user_path.resolve() + if not binary.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_sha): + raise WitnessError("INVALID_SOURCE_IDENTITY") + if digest(binary) != expected_sha: + raise WitnessError("BINARY_DIGEST_MISMATCH") + with binary.open("rb") as header_fh: + header = header_fh.read(20) + if (len(header) != 20 or header[:6] != b"\x7fELF\x02\x01" or + int.from_bytes(header[16:18], "little") != 2 or + int.from_bytes(header[18:20], "little") != 62): + raise WitnessError("NON_PIE_X86_64_ELF_REQUIRED") + sym = symbols(binary) + if sym["apply_action"] == sym["observe_after"] or not sym["controlled_state"]: + raise WitnessError("INVALID_SYMBOL_MAP") + # Only a direct child created for this disposable experiment may be traced. + child = subprocess.Popen([str(binary)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + deadline = time.monotonic() + MAX_WALL_S + active = False + restored = 0 + data = [] + old_words = {} + try: + require_stop(wait_child(child.pid, deadline), signal.SIGSTOP) + active = True + if digest(f"/proc/{child.pid}/exe") != expected_sha: + raise WitnessError("LIVE_EXECUTABLE_CHANGED") + # e_type=ET_EXEC has already been validated. For PIE experiments, + # derive the load bias independently before using symbol addresses. + if peek_state(child.pid, sym["controlled_state"]) != 42: + raise WitnessError("INITIAL_CHECKPOINT_MISMATCH") + for name in SYMBOLS[:2]: + addr = sym[name] + orig = word(child.pid, addr) + if orig & 0xFF == 0xCC: + raise WitnessError("PREEXISTING_BREAKPOINT") + old_words[addr] = orig + ptrace(POKETEXT, child.pid, addr, (orig & ~0xFF) | 0xCC) + ptrace(CONT, child.pid) + for expected_name, expected_value in (("apply_action", 42), ("observe_after", 43)): + require_stop(wait_child(child.pid, deadline), signal.SIGTRAP) + regs = getregs(child.pid) + addr = sym[expected_name] + if regs.rip - 1 != addr: + raise WitnessError("BREAKPOINT_LOCATION_MISMATCH") + state = peek_state(child.pid, sym["controlled_state"]) + if state != expected_value: + raise WitnessError("CHECKPOINT_STATE_MISMATCH") + data.append(hashlib.sha256(state.to_bytes(8, "little")).hexdigest()) + # Undo INT3, rewind RIP to execute the original instruction. + ptrace(POKETEXT, child.pid, addr, old_words[addr]) + regs.rip = addr + putregs(child.pid, regs) + if word(child.pid, addr) != old_words[addr]: + raise WitnessError("BREAKPOINT_RESTORE_FAILED") + restored += 1 + ptrace(CONT, child.pid) + status = wait_child(child.pid, deadline) + active = False + if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0: + raise WitnessError("CHILD_TERMINATION_FAILED") + return { + "schema": SCHEMA, "status": "PASS", "evidence_class": "SOURCE_KNOWN_NATIVE_CHILD_BREAKPOINTS", + "binary_sha256": expected_sha, "breakpoint_hits": len(data), + "checkpoint_digests": data, "breakpoint_original_bytes_restored": restored == 2, + "state_transition_observed": data[0] != data[1], "child_clean_exit": True, + "limitations": ["Only source-known fixture and two selected state checkpoints", + "Not a complete process/VM checkpoint or runtime game function proof", + "INT3 temporarily changes fixture text; debugger perturbs scheduling"], + } + finally: + if active or child.poll() is None: + # On an unexpected breakpoint/timeout, terminate only the child + # launched by this workcell, never an arbitrary external PID. + try: + child.kill() + except ProcessLookupError: + pass + try: + child.wait(timeout=2) + except subprocess.TimeoutExpired: + child.kill() + child.wait(timeout=2) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--binary", required=True) + ap.add_argument("--expected-sha", required=True) + ap.add_argument("--output", required=True) + args = ap.parse_args(argv) + out = Path(args.output) + out.parent.mkdir(parents=True, exist_ok=True) + try: + report = run(args.binary, args.expected_sha) + except (WitnessError, OSError, subprocess.SubprocessError, ValueError) as exc: + code = str(exc) if isinstance(exc, WitnessError) else "FIXTURE_EXECUTION_ERROR" + report = {"schema": SCHEMA, "status": "UNQUALIFIED", "error_code": code} + out.write_text(json.dumps(report, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({"schema": SCHEMA, "status": report["status"], + "error_code": report.get("error_code")}, sort_keys=True)) + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/qualification/surrogates/freeciv/checkpoint/fixture.c b/qualification/surrogates/freeciv/checkpoint/fixture.c new file mode 100644 index 00000000..6aaee2dc --- /dev/null +++ b/qualification/surrogates/freeciv/checkpoint/fixture.c @@ -0,0 +1,26 @@ +/* Public-safe source-known x86_64/Linux breakpoint checkpoint fixture. + * The debugger is its direct parent. No network, game data, or private assets. + */ +#define _GNU_SOURCE +#include +#include +#include + +volatile unsigned long long controlled_state = 42ULL; + +__attribute__((noinline)) void apply_action(void) { + controlled_state += 1; + __asm__ __volatile__("" ::: "memory"); +} + +__attribute__((noinline)) void observe_after(void) { + __asm__ __volatile__("" ::: "memory"); +} + +int main(void) { + if (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) return 70; + raise(SIGSTOP); + apply_action(); + observe_after(); + return controlled_state == 43ULL ? 0 : 71; +} diff --git a/qualification/surrogates/freeciv/checkpoint/test_bridge.py b/qualification/surrogates/freeciv/checkpoint/test_bridge.py new file mode 100644 index 00000000..eef39913 --- /dev/null +++ b/qualification/surrogates/freeciv/checkpoint/test_bridge.py @@ -0,0 +1,89 @@ +"""Native and negative qualification for source-known checkpoint/breakpoint witness.""" + +import importlib.util +import json +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).parent +spec = importlib.util.spec_from_file_location("checkpoint_bridge", HERE / "bridge.py") +bridge = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bridge) + + +class BreakpointNativeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not shutil.which("gcc") or not shutil.which("nm"): + raise unittest.SkipTest("GCC_AND_NM_REQUIRED") + cls.tmp = tempfile.TemporaryDirectory(prefix="checkpoint-fixture-") + cls.bin = Path(cls.tmp.name) / "fixture" + cls.compile(HERE / "fixture.c", cls.bin) + cls.sha = bridge.digest(cls.bin) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "tmp"): + cls.tmp.cleanup() + + @staticmethod + def compile(src, output, pie=False): + flags = ["-fpie", "-pie"] if pie else ["-fno-pie", "-no-pie"] + subprocess.run(["gcc", "-std=c11", "-O0", "-fno-omit-frame-pointer", "-Wall", + "-Wextra", "-Werror", *flags, str(src), "-o", str(output)], + check=True, capture_output=True, timeout=10) + + def test_two_actual_external_breakpoints_with_pre_and_post_checkpoints(self): + report = bridge.run(self.bin, self.sha) + self.assertEqual(report["status"], "PASS") + self.assertEqual(report["breakpoint_hits"], 2) + self.assertTrue(report["child_clean_exit"]) + self.assertTrue(report["breakpoint_original_bytes_restored"]) + self.assertTrue(report["state_transition_observed"]) + self.assertNotIn("addresses", json.dumps(report).lower()) + + def test_repeated_native_process_has_same_expected_state_digests(self): + first = bridge.run(self.bin, self.sha) + second = bridge.run(self.bin, self.sha) + self.assertEqual(first["checkpoint_digests"], second["checkpoint_digests"]) + + def test_wrong_sha_fails_closed_before_execution(self): + with self.assertRaisesRegex(bridge.WitnessError, "BINARY_DIGEST_MISMATCH"): + bridge.run(self.bin, "0" * 64) + + def test_symlink_input_rejected(self): + link = Path(self.tmp.name) / "symlink" + link.symlink_to(self.bin) + with self.assertRaisesRegex(bridge.WitnessError, "INVALID_SOURCE_IDENTITY"): + bridge.run(link, self.sha) + + def test_pie_without_proven_bias_refused(self): + path = Path(self.tmp.name) / "fixture-pie" + self.compile(HERE / "fixture.c", path, pie=True) + with self.assertRaisesRegex(bridge.WitnessError, "NON_PIE_X86_64_ELF_REQUIRED"): + bridge.run(path, bridge.digest(path)) + + def test_wrong_actual_state_not_promoted(self): + code = (HERE / "fixture.c").read_text().replace("controlled_state += 1;", "controlled_state += 2;") + src = Path(self.tmp.name) / "wrong.c" + src.write_text(code) + wrong = Path(self.tmp.name) / "wrong" + self.compile(src, wrong) + with self.assertRaisesRegex(bridge.WitnessError, "CHECKPOINT_STATE_MISMATCH"): + bridge.run(wrong, bridge.digest(wrong)) + + def test_missing_known_symbol_fails_closed(self): + code = (HERE / "fixture.c").read_text().replace("observe_after", "missing_expected_function") + src = Path(self.tmp.name) / "missing.c" + src.write_text(code) + wrong = Path(self.tmp.name) / "missing" + self.compile(src, wrong) + with self.assertRaisesRegex(bridge.WitnessError, "MISSING_FIXTURE_SYMBOL"): + bridge.run(wrong, bridge.digest(wrong)) + + +if __name__ == "__main__": + unittest.main() From ca8fd314a3cff04b6021cd1a291207532ee934a4 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:42:09 +0100 Subject: [PATCH 28/28] fix(observatory): allow bounded public-runner symbol lookup preflight --- qualification/surrogates/freeciv/checkpoint/README.md | 4 ++++ qualification/surrogates/freeciv/checkpoint/bridge.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/qualification/surrogates/freeciv/checkpoint/README.md b/qualification/surrogates/freeciv/checkpoint/README.md index dd59eaa1..534e7fd7 100644 --- a/qualification/surrogates/freeciv/checkpoint/README.md +++ b/qualification/surrogates/freeciv/checkpoint/README.md @@ -23,3 +23,7 @@ This is a **two-value state checkpoint**, not a full-process snapshot or VM rest **Next real Freeciv step after source-native acceptance:** Select a function target from public Freeciv/Ghidra intervals using source-backed save/turn cross-references; arm a single per-process breakpoint at the independently verified actual load bias + RVA; execute one command, capture bounded RIP/stack/function event; restore original bytes and restart from known game save in an independent process; correlate event with actual save-file/turn change. Add wrong SHA, wrong bias, thread-hit, missed breakpoint, resource-budget, accidental re-entry and readback negatives before calling action attribution verified. The R055 passive 1/180 function hit remains historical evidence, not proof that a particular function caused a game event. **Do not attach to original SMAC / Windows 98, publish private observatory source to public CI, or expose raw GDB/QMP/Frida endpoints via a public tunnel without separate explicit authority.** + +## R056 initial public-runner negative + +The first cloud workflow attempt failed **during `nm` symbol discovery** because a 4-second subprocess budget expired on the public runner, before any breakpoint/trace fixture could execute. This is an execution-environment/timeout negative, not a ptrace validation or game observation. The next same-branch candidate extends only the symbol-preflight allowance to 20 seconds and preserves the exact fixture, address/ELF admission, two-breakpoint acceptance and all seven tests. No fail-open fallback has been added. Promote only after a new exact-commit public workflow reaches the native checkpoint step and passes. diff --git a/qualification/surrogates/freeciv/checkpoint/bridge.py b/qualification/surrogates/freeciv/checkpoint/bridge.py index 3f08f501..2119249b 100644 --- a/qualification/surrogates/freeciv/checkpoint/bridge.py +++ b/qualification/surrogates/freeciv/checkpoint/bridge.py @@ -65,7 +65,7 @@ def digest(path): def symbols(binary): out = subprocess.run(["nm", "-n", "--defined-only", str(binary)], check=True, - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=4).stdout + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=20).stdout matched = {} for line in out.splitlines(): m = re.fullmatch(r"([0-9a-fA-F]+)\s+([A-Za-z])\s+(\S+)", line)