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.

10.0 KB
Raw Blame
#!/usr/bin/env python3
"""Live TUI HUD for eBPF-Jev Offline Simulated-Egress Arena (events.jsonl + egress_state.json)."""
import argparse
import curses
import json
import textwrap
from collections import deque
from pathlib import Path

WHITE, GOLD, CYAN, BLUE, GREEN, RED = range(1, 7)


class EgressStream:
    def __init__(self, run: Path):
        self.run = run
        self.events: deque[dict] = deque(maxlen=600)
        self.file = None
        self.gen = None
        self.total_events = 0
        self.deny_connect = 0
        self.deny_sendmsg = 0
        self.allow_net = 0
        self.taint_opens = 0
        self.hook_ns_sum = 0.0
        self.hook_ns_count = 0
        self.hook_ns_max = 0.0
        self.latest_net = None
        self.egress_state: dict = {}

    def poll(self) -> None:
        ev_path = self.run / "events.jsonl"
        if self.file is None and ev_path.exists():
            self.file = ev_path.open(encoding="utf-8", errors="replace")
        if self.file:
            while True:
                pos = self.file.tell()
                line = self.file.readline()
                if not line.endswith("\n"):
                    self.file.seek(pos)
                    break
                s = line.strip()
                if not s or not s.endswith("}"):
                    continue
                try:
                    e = json.loads(s)
                except json.JSONDecodeError:
                    continue
                kind = e.get("type")
                if kind == "model":
                    self.gen = e.get("gen")
                    continue
                self.total_events += 1
                hns = e.get("hook_ns")
                if isinstance(hns, (int, float)):
                    self.hook_ns_sum += float(hns)
                    self.hook_ns_count += 1
                    if float(hns) > self.hook_ns_max:
                        self.hook_ns_max = float(hns)
                verdict = str(e.get("verdict", ""))
                if kind == "file_open":
                    if e.get("name") == ".env" or (e.get("x") and len(e["x"]) > 1 and e["x"][1] >= 85):
                        self.taint_opens += 1
                        self.events.append(e)
                    elif e.get("name") == "config.yaml":
                        self.events.append(e)
                elif kind in ("connect", "sendmsg"):
                    if "DENY" in verdict:
                        if kind == "connect":
                            self.deny_connect += 1
                        else:
                            self.deny_sendmsg += 1
                    elif verdict == "ALLOW":
                        self.allow_net += 1
                    self.latest_net = e
                    self.events.append(e)
                elif kind == "task_alloc" and e.get("inherited"):
                    self.events.append(e)

        st_path = self.run / "egress_state.json"
        if st_path.exists():
            try:
                self.egress_state = json.loads(st_path.read_text(encoding="utf-8"))
            except (OSError, json.JSONDecodeError):
                pass


def fmt_lsm_event(e: dict) -> tuple[int, str]:
    kind = e.get("type", "?")
    pid = e.get("pid", 0)
    comm = e.get("comm", "?")
    us = float(e.get("hook_ns", 0)) / 1000.0
    if kind == "file_open":
        badge = "TAINT" if e.get("opens") else "CFG"
        return GOLD, f"[open] pid={pid} {comm} {e.get('name', '')} [{badge}] {us:.1f}us"
    if kind == "task_alloc":
        return CYAN, f"[fork] {e.get('ppid', 0)}->{pid} {comm} h[32] INHERITED {us:.1f}us"
    verdict = str(e.get("verdict", ""))
    allowed = verdict == "ALLOW"
    color = GREEN if allowed else RED
    tag = "ALLOW" if allowed else "DENY(-EPERM)"
    scores = e.get("scores") or [0, 0, 0, 0]
    exf = scores[0] / 255.0
    return color, f"[{kind}] {tag} pid={pid} {comm} :{e.get('port', 0)} exf={exf:.0%} {us:.1f}us"


def render(stream: EgressStream, width: int, height: int, scroll: int) -> tuple[list[tuple[int, str]], int]:
    inner = max(20, width - 4)
    header: list[tuple[int, str]] = []
    footer: list[tuple[int, str]] = []

    def rule(buf: list, title: str, first: bool = False) -> None:
        prefix = ("┌" if first else "├") + "─ " + title + " "
        buf.append((CYAN, prefix + "─" * max(0, width - len(prefix) - 1) + ("┐" if first else "┤")))

    def row(buf: list, msg: str = "", color: int = WHITE) -> None:
        buf.append((color, "│ " + msg[:inner].ljust(inner) + " │"))

    eg = stream.egress_state or {}
    counts = eg.get("counts") or {}
    leaked = bool(eg.get("canary_leaked", False))
    leak_channels = eg.get("leak_channels") or []
    leak_events = eg.get("leak_events") or []
    avg_us = (stream.hook_ns_sum / stream.hook_ns_count / 1000.0) if stream.hook_ns_count else 0.0
    max_us = stream.hook_ns_max / 1000.0
    total_denies = stream.deny_connect + stream.deny_sendmsg

    rule(header, f"eBPF-Jev EGRESS ARENA | gen #{stream.gen or '?'}", True)
    row(header, "Air-Gapped unshare -Urn | tap0 10.77.0.1 | dummy0 198.51.100.66 / 2001:db8:cafe::66", WHITE)

    if leaked:
        ch_str = ",".join(leak_channels)
        last_lk = leak_events[-1] if leak_events else {}
        detail = str(last_lk.get("detail", ""))
        mkind = str(last_lk.get("match_kind", ""))
        row(header, f"EGRESS STATUS: CANARY LEAK DETECTED! [{ch_str}]", RED)
        for part in textwrap.wrap(f"  Captured ({mkind}): {detail}", inner):
            row(header, part, RED)
    else:
        row(header, "EGRESS STATUS: CONTAINED (0 canary leaks detected across all channels)", GREEN)

    rule(header, "KERNEL BPF LSM TELEMETRY")
    row(
        header,
        f"Events: {stream.total_events} | avg={avg_us:.2f}us max={max_us:.1f}us | .env opens={stream.taint_opens}",
        WHITE,
    )
    row(
        header,
        f"-EPERM BLOCKS: {total_denies} (connect={stream.deny_connect}, sendmsg={stream.deny_sendmsg}) | ALLOW: {stream.allow_net}",
        RED if total_denies else GREEN,
    )

    rule(header, "ISOLATED-NETNS SERVICES")
    row(
        header,
        f"Corp API (:8080): {counts.get('corp_api', 0)} reqs (allow_ok={eg.get('corp_allow_ok', False)})",
        GREEN if eg.get("corp_allow_ok") else WHITE,
    )
    row(
        header,
        f"Corp Proxy (:3128): {counts.get('proxy_total', 0)} total | allow={counts.get('proxy_allowed', 0)} | 403={counts.get('proxy_blocked_403', 0)} | canary_403={counts.get('proxy_canary_blocked', 0)}",
        GOLD if counts.get("proxy_blocked_403", 0) else WHITE,
    )
    dns_leaks = counts.get("dns_canary_leaks", 0)
    row(
        header,
        f"Corp DNS (:53): {counts.get('dns_queries', 0)} queries | ext={counts.get('dns_external_queries', 0)} | CANARY_LEAKS={dns_leaks}",
        RED if dns_leaks else CYAN,
    )
    ext_pkts = counts.get("external_sink_packets", 0)
    ext_bytes = counts.get("external_sink_bytes", 0)
    row(
        header,
        f"External Sink (198.51.100.66/v6): {ext_pkts} pkts / {ext_bytes} B "
        f"(tcp={counts.get('external_tcp', 0)} udp={counts.get('external_udp', 0)} v6={counts.get('external_ipv6', 0)} icmp={counts.get('external_icmp_raw', 0)})",
        RED if ext_pkts else GREEN,
    )

    rule(header, "LATEST DNS QUERIES (10.77.0.1:53)")
    recent_dns = (eg.get("recent_dns") or [])[-5:]
    if recent_dns:
        for d in recent_dns:
            c = RED if d.get("canary_detected") else WHITE
            tag = " [LEAK!]" if d.get("canary_detected") else ""
            row(header, f"{d.get('proto', 'udp'):3s} {d.get('qtype', 'A'):4s} {d.get('qname', '')} -> {d.get('answer', '')}{tag}", c)
    else:
        row(header, "(no DNS queries yet)", WHITE)

    rule(header, "LIVE KERNEL LSM FEED" if not scroll else f"LSM FEED HISTORY (up {scroll})")

    footer.append((CYAN, "├" + "─" * (width - 2) + "┤"))
    row(footer, "Up/Down scroll | End follow | Ctrl-b d detach | testbed/stop_pi_egress.sh", WHITE)
    footer.append((CYAN, "└" + "─" * (width - 2) + "┘"))

    slots = max(2, height - len(header) - len(footer))
    feed: list[tuple[int, str]] = []
    for ev in stream.events:
        color, msg = fmt_lsm_event(ev)
        for part in textwrap.wrap(msg, inner, subsequent_indent="  "):
            feed.append((color, "│ " + part.ljust(inner) + " │"))

    scroll = min(scroll, max(0, len(feed) - slots))
    end = len(feed) - scroll
    visible = feed[max(0, end - slots) : end]
    empty = (WHITE, "│ " + " " * inner + " │")
    return header + [empty] * (slots - len(visible)) + visible + footer, scroll


def live(screen, stream: EgressStream) -> None:
    curses.curs_set(0)
    curses.start_color()
    curses.use_default_colors()
    for i, color in enumerate((7, 3, 6, 4, 2, 1), 1):
        curses.init_pair(i, color, -1)
    screen.timeout(200)
    scroll = 0
    while True:
        stream.poll()
        height, width = screen.getmaxyx()
        frame, scroll = render(stream, max(24, width), max(16, height), scroll)
        for y, (color, text) in enumerate(frame[:height]):
            try:
                screen.addnstr(y, 0, text, width, curses.color_pair(color) | (curses.A_BOLD if color != WHITE else 0))
            except curses.error:
                pass
        screen.refresh()
        key = screen.getch()
        if key in (curses.KEY_UP, curses.KEY_PPAGE):
            scroll += 1 if key == curses.KEY_UP else 8
        elif key in (curses.KEY_DOWN, curses.KEY_NPAGE):
            scroll = max(0, scroll - (1 if key == curses.KEY_DOWN else 8))
        elif key in (curses.KEY_END, ord("G")):
            scroll = 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("run", type=Path)
    ap.add_argument("--snapshot", action="store_true")
    ap.add_argument("--width", type=int, default=110)
    ap.add_argument("--height", type=int, default=42)
    args = ap.parse_args()

    stream = EgressStream(args.run)
    if args.snapshot:
        stream.poll()
        frame, _ = render(stream, args.width, args.height, 0)
        print("\n".join(line for _, line in frame))
        return 0
    curses.wrapper(live, stream)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())