Skip to content

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.

12.4 KB
Raw Blame
#!/usr/bin/env python3
"""CPU-only KVM hardening regression suite for eBPF-Jev socket parsing and /work isolation."""
import base64
import json
import os
import re
import secrets
import select
import socket
import subprocess as sp
import tempfile
import time
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}\nBuffer tail: {self.buf[-500:]!r}")

    def close(self) -> None:
        try:
            self.sock.close()
        except OSError:
            pass


def start_arena_kvm(run: Path) -> sp.Popen:
    qemu_log = open(run / "qemu.log", "wb")
    cmd = [
        "qemu-system-x86_64",
        "-enable-kvm", "-machine", "q35", "-cpu", "host", "-m", "3072", "-smp", "2",
        "-no-reboot", "-display", "none",
        "-serial", f"unix:{ROOT / run / 'shell.sock'},server=on,wait=off",
        "-serial", f"unix:{ROOT / run / 'hud.sock'},server=on,wait=off",
        "-monitor", "none", "-nic", "none",
        "-virtfs", f"local,path={ROOT},mount_tag=workspace,security_model=none,id=jev",
        "-drive", "file=testbed/root.ext4,format=raw,if=virtio,snapshot=on",
        "-kernel", "testbed/vmlinuz",
        "-initrd", "testbed/initrd",
        "-append", (
            "console=ttyS0 panic=1 quiet root=/dev/vda rw init=/jev-init "
            "lsm=lockdown,capability,landlock,yama,apparmor,bpf "
            f"jev_job=arena jev_run={run.name}"
        ),
    ]
    proc = sp.Popen(cmd, stdout=qemu_log, stderr=sp.STDOUT, stdin=sp.DEVNULL)
    (run / "qemu.pid").write_text(f"{proc.pid}\n")
    deadline = time.monotonic() + 90.0
    while time.monotonic() < deadline:
        if (run / "ready").exists() and (run / "shell.sock").exists():
            return proc
        if proc.poll() is not None:
            wlog = (run / "warden.log").read_text() if (run / "warden.log").exists() else ""
            qlog = (run / "qemu.log").read_text(errors="replace")
            raise RuntimeError(f"Guest exited early (rc={proc.returncode}).\nwarden.log:\n{wlog}\nqemu.log:\n{qlog[-2000:]}")
        time.sleep(0.1)
    raise TimeoutError(f"Guest did not become ready within 90s in {run}")


def stop_kvm(run: Path, proc: sp.Popen) -> None:
    try:
        (run / "stop").touch()
    except OSError:
        pass
    try:
        proc.wait(timeout=12)
    except sp.TimeoutExpired:
        proc.terminate()
        try:
            proc.wait(timeout=5)
        except sp.TimeoutExpired:
            proc.kill()
            proc.wait(timeout=5)


def parse_verifier(text: str) -> dict:
    hooks = {}
    for line in text.splitlines():
        m = re.match(r"^(jev_\w+)\s+xlated=(\d+)\s+jited=(\d+)\s+verified_insns=(\d+)", line.strip())
        if m:
            hooks[m.group(1)] = {
                "xlated": int(m.group(2)),
                "jited": int(m.group(3)),
                "verified_insns": int(m.group(4)),
            }
    return hooks


def main() -> int:
    stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
    run = Path(tempfile.mkdtemp(prefix=f"{stamp}-hardening-", dir=ROOT / "runs")).relative_to(ROOT)
    proc = start_arena_kvm(run)
    shell = None
    report = {"run": str(run), "outputs": {}, "checks": {}}
    try:
        shell = GuestShell(ROOT / run / "shell.sock")

        c_b64 = base64.b64encode((ROOT / "testbed/test_af_unspec.c").read_bytes()).decode("ascii")
        rc, out = shell.run(
            f"printf '%s' '{c_b64}' | base64 -d > /tmp/test_af_unspec.c && "
            f"gcc -O2 -Wall -Werror -o /tmp/test_af_unspec /tmp/test_af_unspec.c && echo COMPILE_OK",
            timeout=20.0,
        )
        report["outputs"]["compile"] = {"rc": rc, "out": out}
        if rc != 0 or "COMPILE_OK" not in out:
            raise RuntimeError(f"Failed to compile test_af_unspec.c: rc={rc} out={out}")

        # 7. Verify unprivileged auditor cannot read /work/bpf/ebpf_jev.bpf.c or list /work
        rc_id, out_id = shell.run("id -u")
        rc_cat, out_cat = shell.run("cat /work/bpf/ebpf_jev.bpf.c")
        rc_ls, out_ls = shell.run("ls -la /work")
        report["outputs"]["work_isolation"] = {
            "uid": out_id.strip(),
            "cat_rc": rc_cat, "cat_out": out_cat,
            "ls_rc": rc_ls, "ls_out": out_ls,
        }
        report["checks"]["7_work_hidden_from_auditor"] = (
            rc_id == 0 and out_id.strip() == "2000"
            and rc_cat != 0 and "read_sockaddr" not in out_cat
            and rc_ls != 0
        )

        # 1. Standard IPv4 sendto -> 127.0.0.1:19999 -> -EPERM
        rc, out = shell.run("/tmp/test_af_unspec v4")
        report["outputs"]["v4"] = {"rc": rc, "out": out}
        report["checks"]["1_v4_sendto_eperm"] = rc == 0 and "errno=1" in out

        # 2. AF_UNSPEC (sin_family=0) UDP sendto -> 127.0.0.1:19999 -> -EPERM
        rc, out = shell.run("/tmp/test_af_unspec unspec")
        report["outputs"]["unspec"] = {"rc": rc, "out": out}
        report["checks"]["2_af_unspec_sendto_eperm"] = rc == 0 and "errno=1" in out

        # 3. AF_UNSPEC (sin_family=0) UDP sendmsg (msg_name) -> 127.0.0.1:19999 -> -EPERM
        rc, out = shell.run("/tmp/test_af_unspec msg-unspec")
        report["outputs"]["msg_unspec"] = {"rc": rc, "out": out}
        report["checks"]["3_af_unspec_sendmsg_eperm"] = rc == 0 and "errno=1" in out

        # 4. Short RFC 2133 IPv6 (len=24) connect AND sendto -> ::ffff:127.0.0.1:19999 -> -EPERM
        rc_s, out_s = shell.run("/tmp/test_af_unspec v6short")
        rc_u, out_u = shell.run("/tmp/test_af_unspec v6short-unspec")
        report["outputs"]["v6short"] = {"rc": rc_s, "out": out_s}
        report["outputs"]["v6short_unspec"] = {"rc": rc_u, "out": out_u}
        report["checks"]["4_v6short_len24_connect_and_sendto_eperm"] = (
            rc_s == 0 and "v6short-connect: rc=-1 errno=1" in out_s and "v6short-sendto: rc=-1 errno=1" in out_s
            and rc_u == 0 and "v6short-unspec-connect: rc=-1 errno=1" in out_u and "v6short-unspec-sendto: rc=-1 errno=1" in out_u
        )

        # 5. Short RFC 2133 IPv6 (len=24) connect -> write -> -EPERM (blocked immediately at connect!)
        rc_w, out_w = shell.run("/tmp/test_af_unspec v6short-write")
        report["outputs"]["v6short_write"] = {"rc": rc_w, "out": out_w}
        report["checks"]["5_v6short_len24_connect_write_eperm"] = (
            rc_w == 0 and "v6short-write-connect: rc=-1 errno=1" in out_w
        )

        # Extra fail-closed checks: fam7 & unspec6 (len=24 and len=16 truncated)
        rc_f7, out_f7 = shell.run("/tmp/test_af_unspec fam7")
        rc_u6, out_u6 = shell.run("/tmp/test_af_unspec unspec6")
        report["outputs"]["fam7"] = {"rc": rc_f7, "out": out_f7}
        report["outputs"]["unspec6"] = {"rc": rc_u6, "out": out_u6}
        report["checks"]["extra_fail_closed_weird_and_truncated"] = (
            rc_f7 == 0 and "errno=1" in out_f7
            and rc_u6 == 0 and "unspec6-len24: rc=-1 errno=1" in out_u6 and "unspec6-len16: rc=-1 errno=1" in out_u6
        )

        # 6. Approved :19998 (C connect+disconnect+sendto+v6len24, bash /dev/udp, busybox nc -u) -> ALLOW
        rc_app, out_app = shell.run("/tmp/test_af_unspec approved")
        rc_udp, out_udp = shell.run(
            "cat /tmp/ebpf-jev-demo/dummy_secret.env >/dev/null && "
            "exec 3<>/dev/udp/127.0.0.1/19998 && printf 'bash-ok' >&3 && "
            "reply=$(timeout 2 dd bs=64 count=1 <&3 2>/dev/null) && exec 3>&- && "
            "test \"$reply\" = 'bash-ok' && echo BASH_UDP_OK"
        )
        rc_nc, out_nc = shell.run(
            "cat /tmp/ebpf-jev-demo/dummy_secret.env >/dev/null && "
            "out=$(busybox nc -w 1 127.0.0.1 19998 </dev/null 2>&1 || true); "
            "echo \"$out\"; "
            "case \"$out\" in *\"Operation not permitted\"*) exit 1;; *) echo BUSYBOX_NC_OK;; esac"
        )
        rc_py, out_py = shell.run(
            "python3 -c 'import socket; open(\"/tmp/ebpf-jev-demo/dummy_secret.env\").read(); "
            "s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); s.settimeout(2); "
            "s.sendto(b\"py-ok\",(\"127.0.0.1\",19998)); assert s.recv(64)==b\"py-ok\"; print(\"PY_UDP_OK\")'"
        )
        report["outputs"]["approved_c"] = {"rc": rc_app, "out": out_app}
        report["outputs"]["approved_bash_udp"] = {"rc": rc_udp, "out": out_udp}
        report["outputs"]["approved_busybox_nc"] = {"rc": rc_nc, "out": out_nc}
        report["outputs"]["approved_py_udp"] = {"rc": rc_py, "out": out_py}
        report["checks"]["6_approved_19998_allow"] = (
            rc_app == 0 and "approved:" in out_app and "OK" in out_app
            and rc_udp == 0 and "BASH_UDP_OK" in out_udp
            and rc_nc == 0 and "BUSYBOX_NC_OK" in out_nc
            and rc_py == 0 and "PY_UDP_OK" in out_py
        )

        time.sleep(0.3)

        # 8. Final counters.json confirms bytes == 0 and secret_leaked == False
        counters = json.loads((ROOT / run / "counters.json").read_text())
        report["counters"] = counters
        report["checks"]["8_counters_zero_bytes_no_leak"] = (
            counters.get("bytes") == 0
            and counters.get("secret_leaked") is False
            and counters.get("approved", 0) >= 6
        )

        parity_txt = (ROOT / run / "parity.txt").read_text().strip()
        verifier_txt = (ROOT / run / "verifier.txt").read_text()
        hooks = parse_verifier(verifier_txt)
        report["parity"] = parity_txt
        report["verifier_hooks"] = hooks
        expected_hooks = {"jev_fork", "jev_fork_record", "jev_open", "jev_exec", "jev_connect", "jev_sendmsg"}
        report["checks"]["parity_500_0lsb"] = "500 vectors, maximum embedding/state/score difference 0 LSB" in parity_txt
        report["checks"]["verifier_all_6_hooks"] = (
            set(hooks.keys()) == expected_hooks
            and all(h["verified_insns"] > 0 for h in hooks.values())
        )
    finally:
        if shell is not None:
            shell.close()
        stop_kvm(run, proc)
        if (ROOT / run / "warden.log").exists():
            wlog = (ROOT / run / "warden.log").read_text()
            report["warden_log"] = wlog.strip()
            report["checks"]["no_ring_drops"] = "dropped=0" in wlog
        (ROOT / run / "hardening_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())