From 4e8828ca724b98d9ffca8f11fcdaf3da2d91056b Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:20:37 +0100 Subject: [PATCH] Never read a damaged or blind lifecycle capture as contained O02 of the leak-testing plan, for the lifecycle VM's capture reader. run.sh passes a contained scenario when egress.py --hits prints 0, and egress.py printed 0 for an empty pcap, a short header, and silently dropped truncated records, VLAN frames and unknown EtherTypes. It also read ports from the payload of non-first IPv4 fragments and stopped at the first IPv6 extension header. egress.py now raises Inconclusive (stderr INCONCLUSIVE: , exit 2) for any damage, for a frame snapped below its addresses and for layouts it does not parse; QEMU's intentional 128-byte snap still gives a verdict. --require-control demands the guest's own SSH packets in the window, so a capture of replies only or of nothing is blind, not clean. run.sh records an inconclusive capture as a failed scenario with the reason, and sends a control beacon (an SSH round trip) inside the c0-control and s1-session windows; the other windows already carry SSH traffic. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 11 ++ docs/security/leak-testing-plan.md | 2 +- docs/web/how-to/vm-testing.md | 6 + docs/web/release-notes/changelog.md | 11 ++ scripts/vm/lifecycle/egress.py | 198 +++++++++++++++++++---- scripts/vm/lifecycle/run.sh | 42 ++++- tests/test_lifecycle_egress.py | 233 ++++++++++++++++++++++++++++ 7 files changed, 462 insertions(+), 41 deletions(-) create mode 100644 tests/test_lifecycle_egress.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 026eb11..451d619 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Tests +- The lifecycle VM's capture reader (`scripts/vm/lifecycle/egress.py`) no longer + reports a capture it cannot vouch for as clean. An empty or cut-short pcap + used to read as "0 probe packets", which `run.sh` passed as contained; it is + now inconclusive, as is a non-Ethernet file, a frame snapped below its + addresses and any layout the reader does not parse (a VLAN tag, an unknown + EtherType). Every scenario must also show the guest's own SSH traffic in the + same window, so a window of replies only, or of nothing, fails instead of + passing. Non-first IPv4 fragments no longer have a port read from their + payload, and IPv6 extension headers are walked to the transport header + (O02 of the leak-testing plan). + - The zero-leak suite builds every probe on NSE 2.4.0's stimuli instead of scripts it wrote itself; the `nse` extra now requires `network-sandbox-engine>=2.4.0`. Each probe carries a probe ID, so the diff --git a/docs/security/leak-testing-plan.md b/docs/security/leak-testing-plan.md index ccd250a..66d5bd1 100644 --- a/docs/security/leak-testing-plan.md +++ b/docs/security/leak-testing-plan.md @@ -164,7 +164,7 @@ runtime leak blocks the affected release regardless of its original priority. | ID / priority | Extend | Experiment | Required evidence / calibration | | :--- | :--- | :--- | :--- | | O01 / P0 | DNS oracle and unit tests | Deliver a direct DNS request to a receiver that drops replies or returns error rcodes; add unrelated concurrent redirected DNS | External packet still means leak; timeout/error/counter alone stays inconclusive; old inference fails the regression | -| O02 / P0 | Capture readers and classifier tests | Empty, reply-only, truncated and corrupt capture; wrong NIC; absent stimulus; hidden IP family; unsupported Ethernet/IPv6 layout | No false clean verdict. Distinguish intentional snap length from missing required bytes; correct stimulus is detected in the control | +| O02 / P0 | Capture readers and classifier tests (lifecycle reader: [tests](../../tests/test_lifecycle_egress.py)) | Empty, reply-only, truncated and corrupt capture; wrong NIC; absent stimulus; hidden IP family; unsupported Ethernet/IPv6 layout | No false clean verdict. Distinguish intentional snap length from missing required bytes; correct stimulus is detected in the control | | D01 / P1 | NSE DNS + controlled integration | UDP/TCP 53 to public and LAN resolvers, port rewrites and competing DNAT priorities, IPv4/IPv6 | Unique query/flow observed externally when unprotected; blocked or attributed to Tor when protected; mutate the relevant safeguard | | D02 / P1 | DNS overlay / resolved integration | After managed Tor has bootstrapped, disable non-Tor resolver paths and clear caches; request fresh names through libc, direct DNS and resolved IPC | Permitted resolution still works through Tor, or documented failure is contained; restored alternative path is a calibrated leak control | | D03 / P1 | DNS functional tests | A/AAAA/PTR and unsupported TXT/MX/DNSKEY; UDP/TCP requests; explicit per-link DNSSEC policy | Separate supported answers from safe refusal and connectivity loss; verify DNSSEC preflight refusal happens before network changes | diff --git a/docs/web/how-to/vm-testing.md b/docs/web/how-to/vm-testing.md index 36c8a8c..d9380bf 100644 --- a/docs/web/how-to/vm-testing.md +++ b/docs/web/how-to/vm-testing.md @@ -104,6 +104,12 @@ the distribution's published checksum list; the list's signature is not checked) installs TTP from the working tree, and writes `results.txt`, one capture per phase and state snapshots into `$VM_WORK`. `scripts/vm/lifecycle/egress.py ` summarises a capture by destination; it streams the file, so size is not a concern. +A capture it cannot vouch for is never summarised as clean: an empty, cut-short or +non-Ethernet file, a frame snapped below its addresses, or a layout it does not parse +(a VLAN tag, an unknown EtherType) prints `INCONCLUSIVE: ` and exits 2. Each +scenario also requires the guest's own SSH traffic in the same window +(`--require-control`), so a window that saw only replies, or nothing, fails as +inconclusive instead of passing as contained. Transient download errors receive up to three retries. Downloads remain bounded by connection/transfer timeouts; checksum mismatches still fail the run. Guest readiness requires successful `cloud-init` completion. A timeout or error diff --git a/docs/web/release-notes/changelog.md b/docs/web/release-notes/changelog.md index 8cd645d..2dabcb8 100644 --- a/docs/web/release-notes/changelog.md +++ b/docs/web/release-notes/changelog.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Tests +- The lifecycle VM's capture reader (`scripts/vm/lifecycle/egress.py`) no longer + reports a capture it cannot vouch for as clean. An empty or cut-short pcap + used to read as "0 probe packets", which `run.sh` passed as contained; it is + now inconclusive, as is a non-Ethernet file, a frame snapped below its + addresses and any layout the reader does not parse (a VLAN tag, an unknown + EtherType). Every scenario must also show the guest's own SSH traffic in the + same window, so a window of replies only, or of nothing, fails instead of + passing. Non-first IPv4 fragments no longer have a port read from their + payload, and IPv6 extension headers are walked to the transport header + (O02 of the leak-testing plan). + - The zero-leak suite builds every probe on NSE 2.4.0's stimuli instead of scripts it wrote itself; the `nse` extra now requires `network-sandbox-engine>=2.4.0`. Each probe carries a probe ID, so the diff --git a/scripts/vm/lifecycle/egress.py b/scripts/vm/lifecycle/egress.py index 4910da2..9a365b0 100644 --- a/scripts/vm/lifecycle/egress.py +++ b/scripts/vm/lifecycle/egress.py @@ -7,9 +7,28 @@ whole capture with scapy's rdpcap and exhausted the host's memory; nothing here may hold more than one packet at once. -Usage: egress.py [--net 10.0.2.0/24] [--hits ADDR] +Usage: egress.py [--net 10.0.2.0/24] [--hits ADDR] [--require-control] Prints one line per (destination, protocol, port) with a packet count, then a -total. The SSH control channel (guest tcp/22 to the QEMU gateway) is excluded. +total. The SSH control channel (guest tcp/22 to the QEMU gateway) is counted +separately, not as egress. + +A capture that cannot support a verdict is never summarised as clean. The +script prints ``INCONCLUSIVE: `` on stderr and exits 2 when: + +* the file is empty, its header is short or corrupt, or it is not Ethernet; +* a record or its frame is cut short, or its lengths are impossible; +* a frame was snapped (QEMU's ``maxlen``) below the bytes that name its + destination, or is too short or malformed to read them; +* a frame uses a layout this reader does not parse (a VLAN tag, an unknown + EtherType): a probe could be hiding in it; +* with ``--require-control``, no guest-originated SSH control packet is in the + capture, so it is not known to see the guest's egress at all (an empty + window, a capture of replies only, the wrong NIC). + +Snapping above those bytes is intentional (``vm_capture_start`` keeps 128 +bytes per frame) and is not a reason: the destination address is all a +verdict needs. A port that lies beyond the snap, or in a non-first fragment, +is reported as ``-``. There is deliberately no time filter: QEMU stamps records with its own clock, which was an hour off the host's in practice, so phases are separated by @@ -24,12 +43,27 @@ import struct import sys from collections.abc import Iterator +from dataclasses import dataclass # QEMU user networking numbers a subnet the same way every time: the gateway is # .2, its DNS forwarder .3 and the guest's lease .15. --net selects the subnet. GATEWAY = "10.0.2.2" GUEST_V4 = "10.0.2.15" +LINKTYPE_ETHERNET = 1 +ETHERTYPE_IPV4, ETHERTYPE_IPV6, ETHERTYPE_ARP = 0x0800, 0x86DD, 0x0806 + +#: IPv6 extension headers walked to reach the transport header. A Fragment +#: header (44) is walked too; Authentication (51) counts its length in 4-byte +#: units rather than 8. +_IPV6_EXTENSIONS = {0, 43, 44, 51, 60} + +_MAGIC = {0xA1B2C3D4: ("<", False), 0xD4C3B2A1: (">", False), 0xA1B23C4D: ("<", True), 0x4D3CB2A1: (">", True)} + + +class Inconclusive(Exception): + """The capture cannot support a verdict; the message says why.""" + def use_subnet(cidr: str) -> None: global GATEWAY, GUEST_V4 @@ -50,43 +84,131 @@ def sent_by_guest(src: str) -> bool: def records(path: str) -> Iterator[tuple[float, bytes]]: - with open(path, "rb") as f: + """Yield (timestamp, frame) for every record; raise Inconclusive on any damage.""" + try: + f = open(path, "rb") # noqa: SIM115 - closed below, the generator owns it + except OSError as exc: + raise Inconclusive(f"{path}: cannot be read ({exc.strerror})") from None + with f: header = f.read(24) if len(header) < 24: - return + raise Inconclusive( + f"{path}: {'empty' if not header else 'truncated'} file header ({len(header)} of 24 bytes)" + ) magic = struct.unpack("", 0xA1B23C4D: "<", 0x4D3CB2A1: ">"}.get(magic) - if endian is None: - raise SystemExit(f"{path}: not a pcap file (magic {magic:#x})") - nano = magic in (0xA1B23C4D, 0x4D3CB2A1) + if magic not in _MAGIC: + raise Inconclusive(f"{path}: not a pcap file (magic {magic:#x})") + endian, nano = _MAGIC[magic] + major, minor, _zone, _sigfigs, snaplen, linktype = struct.unpack(endian + "HHiIII", header[4:]) + if (major, minor) != (2, 4): + raise Inconclusive(f"{path}: unsupported pcap version {major}.{minor}") + if linktype != LINKTYPE_ETHERNET: + raise Inconclusive(f"{path}: link type {linktype}, not Ethernet") + index = 0 while True: rec = f.read(16) - if len(rec) < 16: + if not rec: return - sec, frac, incl, _orig = struct.unpack(endian + "IIII", rec) - yield sec + frac / (1e9 if nano else 1e6), f.read(incl) + index += 1 + if len(rec) < 16: + raise Inconclusive(f"{path}: record {index} header cut short ({len(rec)} of 16 bytes)") + sec, frac, incl, orig = struct.unpack(endian + "IIII", rec) + if incl > orig or (snaplen and incl > snaplen): + raise Inconclusive(f"{path}: record {index} claims {incl} bytes of {orig} (snap length {snaplen})") + frame = f.read(incl) + if len(frame) < incl: + raise Inconclusive(f"{path}: record {index} frame cut short ({len(frame)} of {incl} bytes)") + yield sec + frac / (1e9 if nano else 1e6), frame + + +@dataclass(frozen=True) +class Packet: + src: str + dst: str + proto: str + sport: int | None + dport: int | None + + +_NAMES = {6: "tcp", 17: "udp", 1: "icmp", 58: "icmpv6"} + + +def _ports(proto: int, l4: bytes) -> tuple[int | None, int | None]: + if proto in (6, 17) and len(l4) >= 4: + sport, dport = struct.unpack("!HH", l4[:4]) + return sport, dport + return None, None -def parse(frame: bytes) -> tuple[str, str, str, int | None] | None: - """(src, dst, proto, dport) for an IPv4/IPv6 frame, else None.""" +def parse(frame: bytes) -> Packet | None: + """The addresses, protocol and ports of an IP frame; None for ARP. + + Raises Inconclusive for anything that could carry an IP packet this reader + cannot read: a frame too short for its destination, a malformed header, a + VLAN tag or an EtherType it does not know. + """ if len(frame) < 14: - return None + raise Inconclusive(f"a {len(frame)}-byte frame has no complete Ethernet header") ethertype = struct.unpack("!H", frame[12:14])[0] ip = frame[14:] - if ethertype == 0x0800 and len(ip) >= 20: + if ethertype == ETHERTYPE_ARP: + return None + if ethertype == ETHERTYPE_IPV4: + if len(ip) < 20: + raise Inconclusive(f"an IPv4 frame was captured with {len(ip)} of the 20 header bytes") ihl = (ip[0] & 0x0F) * 4 - proto, src, dst, l4 = ip[9], ip[12:16], ip[16:20], ip[ihl:] - elif ethertype == 0x86DD and len(ip) >= 40: - proto, src, dst, l4 = ip[6], ip[8:24], ip[24:40], ip[40:] + if ip[0] >> 4 != 4 or ihl < 20: + raise Inconclusive(f"a malformed IPv4 header (version {ip[0] >> 4}, header length {ihl})") + proto, src, dst = ip[9], ip[12:16], ip[16:20] + first_fragment = struct.unpack("!H", ip[6:8])[0] & 0x1FFF == 0 + sport, dport = _ports(proto, ip[ihl:]) if first_fragment else (None, None) + elif ethertype == ETHERTYPE_IPV6: + if len(ip) < 40: + raise Inconclusive(f"an IPv6 frame was captured with {len(ip)} of the 40 header bytes") + proto, src, dst = ip[6], ip[8:24], ip[24:40] + offset, first_fragment = 40, True + while proto in _IPV6_EXTENSIONS and len(ip) >= offset + 8: + ext = ip[offset : offset + 8] + if proto == 44: + first_fragment = first_fragment and struct.unpack("!H", ext[2:4])[0] >> 3 == 0 + length = 8 + else: + length = (ext[1] + 2) * 4 if proto == 51 else (ext[1] + 1) * 8 + proto, offset = ext[0], offset + length + # An extension chain cut by the snap length leaves the transport unknown; + # the destination, which is all a verdict needs, is already read. + if proto in _IPV6_EXTENSIONS or not first_fragment: + sport, dport = None, None + else: + sport, dport = _ports(proto, ip[offset:]) else: - return None - name = {6: "tcp", 17: "udp", 1: "icmp", 58: "icmpv6"}.get(proto, f"proto{proto}") - dport = struct.unpack("!H", l4[2:4])[0] if proto in (6, 17) and len(l4) >= 4 else None - sport = struct.unpack("!H", l4[0:2])[0] if proto in (6, 17) and len(l4) >= 4 else None - s, d = str(ipaddress.ip_address(src)), str(ipaddress.ip_address(dst)) - if name == "tcp" and sport == 22 and d == GATEWAY: - return None # our own SSH control channel - return s, d, name, dport + kind = "a VLAN-tagged frame" if ethertype in (0x8100, 0x88A8) else f"EtherType {ethertype:#06x}" + raise Inconclusive(f"{kind} is not parsed by this reader and could carry a probe") + name = _NAMES.get(proto, f"proto{proto}") + return Packet(str(ipaddress.ip_address(src)), str(ipaddress.ip_address(dst)), name, sport, dport) + + +def is_control(packet: Packet) -> bool: + """The guest's side of our own SSH control channel.""" + return packet.proto == "tcp" and packet.sport == 22 and packet.dst == GATEWAY + + +def summarise(path: str) -> tuple[collections.Counter[tuple[str, str, int | None]], int]: + """Guest-originated flows and the number of guest SSH control packets.""" + flows: collections.Counter[tuple[str, str, int | None]] = collections.Counter() + control = 0 + for index, (_ts, frame) in enumerate(records(path), start=1): + try: + packet = parse(frame) + except Inconclusive as exc: + raise Inconclusive(f"{path}: record {index}: {exc}") from None + if packet is None or not sent_by_guest(packet.src): + continue + if is_control(packet): + control += 1 + continue + flows[(packet.dst, packet.proto, packet.dport)] += 1 + return flows, control def main() -> int: @@ -94,16 +216,24 @@ def main() -> int: ap.add_argument("pcap") ap.add_argument("--net", default="10.0.2.0/24", help="the QEMU user-network subnet of this capture") ap.add_argument("--hits", metavar="ADDR", help="print only how many guest packets went to ADDR") + ap.add_argument( + "--require-control", + action="store_true", + help="inconclusive unless the guest's SSH control channel appears in the capture", + ) args = ap.parse_args() use_subnet(args.net) - flows: collections.Counter[tuple[str, str, int | None]] = collections.Counter() - for _ts, frame in records(args.pcap): - parsed = parse(frame) - if parsed is None or not sent_by_guest(parsed[0]): - continue - _src, dst, proto, dport = parsed - flows[(dst, proto, dport)] += 1 + try: + flows, control = summarise(args.pcap) + if args.require_control and not control: + raise Inconclusive( + f"{args.pcap}: no guest-originated SSH control packet, so the capture is not " + f"known to see the guest's egress (empty window, replies only, or the wrong NIC)" + ) + except Inconclusive as exc: + print(f"INCONCLUSIVE: {exc}", file=sys.stderr) + return 2 if args.hits: print(sum(n for (dst, _proto, _dport), n in flows.items() if dst == args.hits)) @@ -111,7 +241,7 @@ def main() -> int: for (dst, proto, dport), n in sorted(flows.items(), key=lambda kv: -kv[1]): print(f"{n:6} {proto:7} {dst}:{dport if dport is not None else '-'}") - print(f"total {sum(flows.values())} guest-originated packet(s)") + print(f"total {sum(flows.values())} guest-originated packet(s), {control} SSH control packet(s)") return 0 diff --git a/scripts/vm/lifecycle/run.sh b/scripts/vm/lifecycle/run.sh index 1956191..1361bdc 100755 --- a/scripts/vm/lifecycle/run.sh +++ b/scripts/vm/lifecycle/run.sh @@ -33,7 +33,25 @@ check() { # check [ "$2" = pass ] || FAILED=1 } -hits() { python3 "$HERE/egress.py" "$VM_WORK/$1.pcap" --net "${2:-10.0.2.0/24}" --hits "$PROBE_DST"; } +# Probe packets in capture $1, or "inconclusive" when the capture cannot support a +# verdict: empty, cut short, unparseable, or without the guest's own SSH control +# traffic. egress.py's reason is kept in $1.egress.err and quoted by inconclusive(). +hits() { + python3 "$HERE/egress.py" "$VM_WORK/$1.pcap" --net "${2:-10.0.2.0/24}" --hits "$PROBE_DST" \ + --require-control 2>"$VM_WORK/$1.egress.err" || echo inconclusive +} + +# Fail scenario $3 when capture $1 was inconclusive. Never a pass: a capture that +# saw nothing is exactly what containment looks like. +inconclusive() { # inconclusive + [ "$2" = inconclusive ] || return 1 + check "$3" fail "capture inconclusive: $(tr '\n' ' ' <"$VM_WORK/$1.egress.err")" +} + +# Guest-originated traffic inside the capture window that TTP never touches (the +# reply side of our own SSH session), so egress.py --require-control can tell a +# capture that sees the guest from one that sees nothing. +control_beacon() { vm_ssh true; } probe_start() { # the probe runs as the unprivileged, non-bypassed login user vm_ssh "sudo systemd-run --quiet --uid=ttp --unit=ttp-probe python3 /usr/local/lib/ttp-probe.py" @@ -73,9 +91,12 @@ vm_ssh 'sudo tee /usr/local/lib/ttp-probe.py >/dev/null' <"$HERE/probe.py" probe_start vm_capture_start c0-control sleep 5 +control_beacon vm_capture_stop n="$(hits c0-control)" -if [ "$n" -gt 0 ]; then +if inconclusive c0-control "$n" "positive control (no TTP)"; then + exit 1 +elif [ "$n" -gt 0 ]; then check "positive control (no TTP)" pass "$n probe packet(s) seen" else check "positive control (no TTP)" fail "0 probe packets: the capture is not measuring, nothing below means anything" @@ -86,9 +107,12 @@ fi ttp_start vm_capture_start s1-session sleep 10 +control_beacon vm_capture_stop n="$(hits s1-session)" -if [ "$n" -eq 0 ]; then +if inconclusive s1-session "$n" "active session"; then + : +elif [ "$n" -eq 0 ]; then check "active session" pass "0 probe packets" else check "active session" fail "$n probe packet(s) escaped" @@ -99,7 +123,9 @@ vm_capture_start s2-poweroff vm_ssh 'sudo systemctl poweroff' || true vm_wait_exit 180 n="$(hits s2-poweroff)" -if [ "$n" -eq 0 ]; then +if inconclusive s2-poweroff "$n" "poweroff with active session"; then + : +elif [ "$n" -eq 0 ]; then check "poweroff with active session" pass "0 probe packets until power-off" else check "poweroff with active session" fail "$n probe packet(s) escaped while shutting down" @@ -129,7 +155,9 @@ else check "reboot leaves one defined state" fail "partial session state after reboot, see state-after-reboot.txt" fi n="$(hits s3-reboot)" -if [ "$n" -gt 0 ]; then +if inconclusive s3-reboot "$n" "after reboot the host is in cleartext"; then + : +elif [ "$n" -gt 0 ]; then check "after reboot the host is in cleartext" pass "$n probe packet(s): expected, recorded" else check "after reboot the host is in cleartext" fail "0 probe packets after reboot: capture not measuring" @@ -148,7 +176,9 @@ sleep 15 vm_capture_stop snapshot after-resume n="$(hits s4-resume-newnet 192.168.77.0/24)" -if [ "$n" -eq 0 ]; then +if inconclusive s4-resume-newnet "$n" "resume onto a new network"; then + : +elif [ "$n" -eq 0 ]; then check "resume onto a new network" pass "0 probe packets" else check "resume onto a new network" fail "$n probe packet(s) escaped after resume" diff --git a/tests/test_lifecycle_egress.py b/tests/test_lifecycle_egress.py new file mode 100644 index 0000000..9703a99 --- /dev/null +++ b/tests/test_lifecycle_egress.py @@ -0,0 +1,233 @@ +# Copyright (c) 2026 onyks-os +# SPDX-License-Identifier: MIT + +"""O02 for the lifecycle VM's capture reader: no damaged capture reads as clean. + +``scripts/vm/lifecycle/run.sh`` passes a contained scenario when +``egress.py --hits`` prints 0. Every case below is a capture that would once +have printed 0 -- or a wrong port -- without having seen what the verdict is +about, and must now be inconclusive or parsed correctly instead. + +The pcaps are built here byte by byte: the reader uses only the standard +library, and so does its test. +""" + +from __future__ import annotations + +import ipaddress +import struct + +import pytest + +from scripts.vm.lifecycle import egress + +PROBE = "198.51.100.7" +GUEST, GATEWAY = "10.0.2.15", "10.0.2.2" +GUEST_V6 = "fec0::5054:ff:fe12:3456" + + +@pytest.fixture(autouse=True) +def _default_subnet(): + egress.use_subnet("10.0.2.0/24") + + +def ether(ethertype: int, payload: bytes) -> bytes: + return b"\x52\x55\x0a\x00\x02\x02" + b"\x52\x54\x00\x12\x34\x56" + struct.pack("!H", ethertype) + payload + + +def ipv4(src: str, dst: str, proto: int, l4: bytes, *, fragment_offset: int = 0) -> bytes: + header = struct.pack( + "!BBHHHBBH4s4s", + 0x45, + 0, + 20 + len(l4), + 1, + fragment_offset, + 64, + proto, + 0, + ipaddress.ip_address(src).packed, + ipaddress.ip_address(dst).packed, + ) + return ether(0x0800, header + l4) + + +def ipv6(src: str, dst: str, next_header: int, rest: bytes) -> bytes: + header = struct.pack("!IHBB", 6 << 28, len(rest), next_header, 64) + return ether(0x86DD, header + ipaddress.ip_address(src).packed + ipaddress.ip_address(dst).packed + rest) + + +def ports(sport: int, dport: int) -> bytes: + return struct.pack("!HH", sport, dport) + bytes(16) + + +def probe_udp() -> bytes: + return ipv4(GUEST, PROBE, 17, ports(40000, 53)) + + +def ssh_control() -> bytes: + return ipv4(GUEST, GATEWAY, 6, ports(22, 50000)) + + +def pcap(frames, *, snaplen: int = 65535, linktype: int = 1, cut: int = 0, orig_extra: int = 0) -> bytes: + data = struct.pack(" str: + path = tmp_path / "phase.pcap" + path.write_bytes(data) + return str(path) + + +def run(monkeypatch, capsys, path: str, *args: str) -> tuple[int, str, str]: + monkeypatch.setattr("sys.argv", ["egress.py", path, *args]) + code = egress.main() + out, err = capsys.readouterr() + return code, out.strip(), err.strip() + + +# --------------------------------------------------------------------------- +# Healthy captures still give a verdict +# --------------------------------------------------------------------------- + + +def test_a_contained_window_with_control_traffic_reports_zero(tmp_path, monkeypatch, capsys) -> None: + path = write(tmp_path, pcap([ssh_control(), ipv4(GUEST, "93.184.216.34", 6, ports(41000, 443))])) + assert run(monkeypatch, capsys, path, "--hits", PROBE, "--require-control") == (0, "0", "") + + +def test_a_leaking_window_counts_the_probe(tmp_path, monkeypatch, capsys) -> None: + path = write(tmp_path, pcap([ssh_control(), probe_udp(), probe_udp()])) + assert run(monkeypatch, capsys, path, "--hits", PROBE, "--require-control") == (0, "2", "") + + +def test_an_intentional_snap_length_keeps_the_verdict(tmp_path, monkeypatch, capsys) -> None: + """vm_capture_start keeps 128 bytes: shorter than the frame, longer than its addresses.""" + big = ipv4(GUEST, PROBE, 17, ports(40000, 53) + bytes(1400)) + path = write(tmp_path, pcap([ssh_control(), big], snaplen=128)) + assert run(monkeypatch, capsys, path, "--hits", PROBE, "--require-control") == (0, "1", "") + + +def test_arp_is_not_a_reason_to_doubt_the_capture(tmp_path, monkeypatch, capsys) -> None: + path = write(tmp_path, pcap([ether(0x0806, bytes(28)), ssh_control()])) + assert run(monkeypatch, capsys, path, "--hits", PROBE, "--require-control") == (0, "0", "") + + +# --------------------------------------------------------------------------- +# Damaged files are inconclusive, never zero +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("data", "reason"), + [ + pytest.param(b"", "empty file header", id="empty-file"), + pytest.param(pcap([])[:10], "truncated file header", id="short-header"), + pytest.param(b"\x00" * 24, "not a pcap file", id="bad-magic"), + pytest.param(pcap([ssh_control()], linktype=113), "not Ethernet", id="linux-cooked"), + pytest.param(pcap([ssh_control(), probe_udp()], cut=30), "frame cut short", id="truncated-frame"), + pytest.param(pcap([ssh_control()]) + b"\x01\x00\x00", "record 2 header cut short", id="truncated-record"), + pytest.param(pcap([ssh_control()], orig_extra=-10), "claims", id="incl-above-orig"), + ], +) +def test_a_damaged_capture_is_inconclusive(tmp_path, monkeypatch, capsys, data: bytes, reason: str) -> None: + code, out, err = run(monkeypatch, capsys, write(tmp_path, data), "--hits", PROBE) + assert code == 2 + assert out == "", "an inconclusive capture must not print a count run.sh could read" + assert err.startswith("INCONCLUSIVE:") and reason in err + + +def test_a_missing_capture_is_inconclusive(tmp_path, monkeypatch, capsys) -> None: + code, out, err = run(monkeypatch, capsys, str(tmp_path / "absent.pcap"), "--hits", PROBE) + assert (code, out) == (2, "") and "cannot be read" in err + + +# --------------------------------------------------------------------------- +# Blind windows: a valid file that does not show the guest's egress +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "frames", + [ + pytest.param([], id="header-only"), + pytest.param([ipv4("93.184.216.34", GUEST, 6, ports(443, 41000))], id="replies-only"), + pytest.param([ipv4("10.0.3.15", PROBE, 17, ports(40000, 53))], id="another-guest-or-wrong-nic"), + ], +) +def test_a_window_without_guest_control_traffic_is_inconclusive(tmp_path, monkeypatch, capsys, frames) -> None: + code, out, err = run(monkeypatch, capsys, write(tmp_path, pcap(frames)), "--hits", PROBE, "--require-control") + assert (code, out) == (2, "") + assert "no guest-originated SSH control packet" in err + + +def test_the_control_requirement_is_opt_in(tmp_path, monkeypatch, capsys) -> None: + """Without --require-control the old summary still works for manual inspection.""" + assert run(monkeypatch, capsys, write(tmp_path, pcap([])), "--hits", PROBE) == (0, "0", "") + + +# --------------------------------------------------------------------------- +# Layouts the reader cannot see into are inconclusive +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("frame", "reason"), + [ + pytest.param(ether(0x8100, b"\x00\x01\x08\x00" + probe_udp()[14:]), "VLAN-tagged", id="vlan"), + pytest.param(ether(0x88B5, bytes(40)), "EtherType 0x88b5", id="unknown-ethertype"), + pytest.param(probe_udp()[: 14 + 12], "IPv4 frame was captured with 12", id="snapped-below-destination"), + pytest.param(ether(0x0800, b"\x65" + bytes(19)), "malformed IPv4", id="ipv6-in-ipv4-ethertype"), + pytest.param(ether(0x86DD, bytes(30)), "IPv6 frame was captured with 30", id="short-ipv6"), + pytest.param(b"\x00" * 10, "no complete Ethernet header", id="runt"), + ], +) +def test_an_unreadable_frame_makes_the_capture_inconclusive(tmp_path, monkeypatch, capsys, frame, reason) -> None: + data = pcap([ssh_control(), frame, ssh_control()]) + code, out, err = run(monkeypatch, capsys, write(tmp_path, data), "--hits", PROBE, "--require-control") + assert (code, out) == (2, "") + assert "record 2" in err and reason in err + + +# --------------------------------------------------------------------------- +# Hidden families and transport layouts are parsed, not misread +# --------------------------------------------------------------------------- + + +def test_a_non_first_ipv4_fragment_has_no_port() -> None: + """Its first bytes are payload; reading them as ports invents a destination port.""" + frame = ipv4(GUEST, PROBE, 17, struct.pack("!HH", 1234, 53) + bytes(16), fragment_offset=185) + packet = egress.parse(frame) + assert packet is not None and (packet.dst, packet.dport) == (PROBE, None) + + +def test_ipv6_extension_headers_are_walked_to_the_ports() -> None: + hop_by_hop = bytes([17, 0]) + bytes(6) # next header UDP, 8 bytes + destination_options = bytes([0, 0]) + bytes(6) # next header hop-by-hop + frame = ipv6(GUEST_V6, "2001:db8::7", 60, destination_options + hop_by_hop + ports(40000, 443)) + packet = egress.parse(frame) + assert packet is not None and (packet.proto, packet.dport) == ("udp", 443) + + +def test_an_ipv6_non_first_fragment_has_no_port() -> None: + fragment = bytes([17, 0]) + struct.pack("!H", 185 << 3) + bytes(4) + packet = egress.parse(ipv6(GUEST_V6, "2001:db8::7", 44, fragment + ports(1234, 53))) + assert packet is not None and (packet.proto, packet.dport) == ("udp", None) + + +def test_an_extension_chain_cut_by_the_snap_keeps_the_destination() -> None: + hop_by_hop = bytes([60, 0]) + bytes(6) + packet = egress.parse(ipv6(GUEST_V6, "2001:db8::7", 0, hop_by_hop)) + assert packet is not None and packet.dst == "2001:db8::7" and packet.dport is None + + +def test_guest_ipv6_egress_is_summarised(tmp_path, monkeypatch, capsys) -> None: + frames = [ssh_control(), ipv6(GUEST_V6, "2001:db8::7", 17, ports(40000, 53))] + code, out, _ = run(monkeypatch, capsys, write(tmp_path, pcap(frames)), "--require-control") + assert code == 0 + assert "udp 2001:db8::7:53" in out + assert out.endswith("total 1 guest-originated packet(s), 1 SSH control packet(s)")