diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4bff55c..9298660 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -205,7 +205,7 @@ jobs: # excluded from the default pytest run. A claim nothing executes is not a # measurement. # - # Requires network-sandbox-engine >= 2.5.2. Below 2.1.0, the engine could + # Requires network-sandbox-engine >= 2.6.0, the floor of the whole nse extra. Below 2.1.0, the engine could # report a clean result from an oracle that observed nothing, so a green run # here would prove nothing about the firewall; below 2.1.2, its capture # filter hid routable ICMPv6; below 2.2.0, a capture could start before it diff --git a/.github/workflows/lifecycle.yml b/.github/workflows/lifecycle.yml index 030370d..1fe47a1 100644 --- a/.github/workflows/lifecycle.yml +++ b/.github/workflows/lifecycle.yml @@ -38,6 +38,7 @@ on: - "tests/leak/oracle.py" - "tests/test_chaos_capture.py" - "tests/test_automap_capture.py" + - "tests/test_lifecycle_observer.py" schedule: - cron: "17 4 * * 1" workflow_dispatch: @@ -108,10 +109,21 @@ jobs: sudo apt-get update -q sudo apt-get install -y -q --no-install-recommends qemu-system-x86 qemu-utils genisoimage + # The host-side observer (scripts/vm/lifecycle/observer.py) judges each + # phase with network-sandbox-engine, from the reviewed lock. + - name: Set up Python for the observer + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 + with: + python-version: "3.12" + + - name: Install the observer's locked dependencies + run: bash scripts/install_locked.sh python ci + - name: Run the lifecycle scenarios env: VM_WORK: ${{ runner.temp }}/vm VM_DISTRO: ${{ matrix.distro }} + NSE_PYTHON: python run: scripts/vm/lifecycle/run.sh - name: Upload captures, state and logs @@ -122,6 +134,7 @@ jobs: path: | ${{ runner.temp }}/vm/*.pcap ${{ runner.temp }}/vm/*.txt + ${{ runner.temp }}/vm/observer/ ${{ runner.temp }}/vm/cloud-init.json ${{ runner.temp }}/vm/*.log if-no-files-found: warn diff --git a/CHANGELOG.md b/CHANGELOG.md index ed4a5f9..1dd3866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Tests +- The lifecycle VM judges its phases with NSE 2.6.0, and the `nse` extra + requires `network-sandbox-engine>=2.6.0`. In the guest, NSE's stimulus streams + run as the non-bypassed user between two beacons that carry the guest's clocks. + `scripts/vm/lifecycle/observer.py` reads QEMU's capture. An attempt on the wire + always counts. An absence counts only when: + + - the capture is intact and holds both beacons; + - the beacons place every attempt inside it; + - each stream's log is complete; + - no time went untested, except a gap NSE measured as a suspend. + + The control, the active session and the reboot now share one continuous + capture. Previously each phase had its own file. The suspend/resume phase runs + its streams through the suspend. Before, nothing was measured until after the + move to the new network. `vm_swap_network` now hands the capture to the new + network before its NIC exists, after QEMU confirms the old NIC is gone. The + power-off phase stays on `egress.py`: a stream its machine kills never has a + complete log, so NSE cannot vouch for its absences. + [Tests](https://github.com/onyks-os/TransparentTorProxy/blob/main/tests/test_lifecycle_observer.py) + run the real agents against loopback and break one instrument at a time: a + missing beacon, a cut or joined capture, a killed stream, attempts outside the + beacons, a gap while the guest ran. Packets captured before a phase's opening + beacon are not read as its attempts. The first VM run counted an earlier + cleartext phase's packet as a leak, because NSE 2.6.0 matched it by a reused + source port although it carried another stream's probe ID. + - The `nse` extra requires `network-sandbox-engine>=2.5.2`. Each rule load in the zero-leak suite used to add another copy of NSE's trace rules to the namespace, so every traced packet repeated them once per load. The diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md index 7a73cdf..1ee695e 100644 --- a/DEPENDENCIES.md +++ b/DEPENDENCIES.md @@ -40,7 +40,7 @@ These are required only for building package distributions (`.deb`, `.rpm`, whee | [twine](https://pypi.org/project/twine/) | `dev` | `>=7.0.0` | Apache-2.0 | Checking and publishing distributions. 7.0.0 is the first to accept Metadata-Version 2.5. | | [bump-my-version](https://pypi.org/project/bump-my-version/) | `dev` | `>=1.4.1` | MIT | Version management tool to automate release numbering. | | [cyclonedx-python-lib](https://pypi.org/project/cyclonedx-python-lib/) | `dev` | `>=11.0.0` | Apache-2.0 | Validates each release SBOM against the official CycloneDX schema (`packaging/validate_sbom.py`). | -| [network-sandbox-engine](https://pypi.org/project/network-sandbox-engine/) | `nse` | `>=2.5.2,<3` | MIT | Isolated netns/Scapy nftables rules validation engine for `tests/test_nse_rules.py`. The floor is a correctness requirement, not a preference: see `pyproject.toml`. | +| [network-sandbox-engine](https://pypi.org/project/network-sandbox-engine/) | `nse` | `>=2.6.0,<3` | MIT | Isolated netns/Scapy nftables rules validation engine for `tests/test_nse_rules.py`. The floor is a correctness requirement, not a preference: see `pyproject.toml`. | | [pyroute2](https://pypi.org/project/pyroute2/) | `nse` | unpinned | Apache-2.0 | Netlink-based route management inside network namespaces (avoids `/sys` mount in Docker). | ### 1.2 System-Level Dependencies diff --git a/ROADMAP.md b/ROADMAP.md index 3ed79c1..974d046 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ What backs those claims, as of this release: | Evidence | Where it runs | | :------- | :------------ | -| **Zero-leak ruleset suite.** TTP's real ruleset in a network namespace (NSE 2.5.2, incomplete captures and windows without their closing beacon rejected, probes and canaries matched by probe ID, round trip answered by a logging receiver in an isolated host namespace), every containment test preceded by a positive control, alongside Docker-, ufw-, firewalld- and WireGuard-shaped competing rulesets. | CI, every push and PR (`make test-nse`) | +| **Zero-leak ruleset suite.** TTP's real ruleset in a network namespace (NSE 2.6.0, incomplete captures and windows without their closing beacon rejected, probes and canaries matched by probe ID, round trip answered by a logging receiver in an isolated host namespace), every containment test preceded by a positive control, alongside Docker-, ufw-, firewalld- and WireGuard-shaped competing rulesets. | CI, every push and PR (`make test-nse`) | | **Lifecycle transitions.** Shutdown, reboot and suspend/resume onto a new network, judged from a packet capture taken outside the guest, under systemd-networkd (Debian 13) and NetworkManager (Fedora 44, SELinux enforcing). | CI, in a VM, when firewall, lifecycle, DNS or watchdog code changes, and weekly | | **Watchdog chaos sweep.** Every fault once, each audit paired with a canary, TCP and UDP, in three variants. | CI, in a VM, same trigger | | **Required VPN gates.** Real Tor through WireGuard in a Debian 13 VM with an external observer: six IPv4/IPv6 topologies, a private obfs4 bridge, suspend/resume and reboot. ParrotOS Home 7.4 (AppArmor enforcing) qualified by hand on the release candidate. | CI, in a VM, when VPN, firewall or lifecycle code changes, and weekly | diff --git a/docs/security-assessment.md b/docs/security-assessment.md index 9f913a9..c346b6b 100644 --- a/docs/security-assessment.md +++ b/docs/security-assessment.md @@ -307,10 +307,14 @@ reader should not have to guess which. **Measured in a VM.** `scripts/vm/lifecycle/run.sh` boots a disposable guest - Debian 13, whose network is brought up by systemd-networkd, and Fedora 44, by NetworkManager - under QEMU and records every packet it sends with QEMU's `filter-dump`, outside -the guest and below TTP's own firewall. A probe inside the guest, running as an -ordinary non-bypassed user, keeps trying to reach `198.51.100.7` (TEST-NET-2, never a -Tor relay) over UDP/53 and TCP/80. A packet to that address in a capture is a leak, -and a capture with TTP stopped must contain the probe or the run is void. It runs in +the guest and below TTP's own firewall. Inside the guest, NSE stimulus streams +running as an ordinary non-bypassed user keep trying to reach `198.51.100.7` +(TEST-NET-2, never a Tor relay) over UDP/53 and TCP/80, between two beacons that +carry the guest's clocks. An attempt in a capture is a leak. An absence counts only +when the capture is intact, holds both beacons and covers every attempt, and no +time went untested except a measured suspend. With TTP stopped, every attempt must +be in the capture, or the run is void. Shutdown still uses a plain probe and a +stdlib reader, because a stream that its machine kills has no complete log. It runs in `.github/workflows/lifecycle.yml` when the firewall, lifecycle or DNS code changes, weekly, and on demand. diff --git a/docs/security/leak-testing-plan.md b/docs/security/leak-testing-plan.md index a71c5f5..350450f 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 (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 | +| O02 / P0 | Capture readers and classifier tests (lifecycle readers: [power-off reader tests](../../tests/test_lifecycle_egress.py), [NSE observer tests](../../tests/test_lifecycle_observer.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/explanation/verification.md b/docs/web/explanation/verification.md index 815e36b..7d034bf 100644 --- a/docs/web/explanation/verification.md +++ b/docs/web/explanation/verification.md @@ -121,7 +121,13 @@ code changes, and weekly: - **Lifecycle transitions**: shutdown, reboot and suspend/resume onto a new network, judged from a packet capture QEMU writes outside the guest, under - systemd-networkd and under NetworkManager. + systemd-networkd and under NetworkManager. Each phase runs NSE's stimulus + streams in the guest between two beacons that carry the guest's clocks. A + probe seen on the wire always counts. An absence counts only when the capture + is intact, holds both beacons, and covers every attempt, and when no stretch + of time went untested except a measured suspend. The power-off phase is still + judged by a stdlib reader, because a stream its machine kills never has a + complete log. - **The watchdog chaos sweep**: every fault once against a live session. Each audit is paired with a **canary**, a bypassed user audited the same way in the same pass, which must be seen - the same positive-control rule, applied to a running @@ -132,7 +138,7 @@ What they assert and what they found is in section 4.3 of the ## The dependency, and why it is pinned hard -`network-sandbox-engine>=2.5.2,<3`. The floor is not a preference. +`network-sandbox-engine>=2.6.0,<3`. The floor is not a preference. Before 2.1.0 the engine's own test runner reported PASSED when its oracle had observed nothing, and its kernel trace monitor could stop reading mid-run without @@ -160,7 +166,8 @@ so the DNAT positive controls require their own packet, and traces the rules a process's own packets meet, with readiness proven by a canary's own trace. Before 2.5.2 every rule load into a namespace added another copy of NSE's trace rules, so each traced packet repeated them, and a readiness that could not be proven -did not say why. A green result from an engine below +did not say why. Before 2.6.0 nothing NSE could read judged a phase inside a +VM. A green result from an engine below the floor would not have been evidence of anything - the same defect as the one described at the top of this page, one layer down. TTP refuses to run this suite against an older engine rather than diff --git a/docs/web/how-to/vm-testing.md b/docs/web/how-to/vm-testing.md index d9380bf..e5e5589 100644 --- a/docs/web/how-to/vm-testing.md +++ b/docs/web/how-to/vm-testing.md @@ -89,11 +89,12 @@ For full kernel-level, DNS mount, and `systemd` integration testing, use the pro `scripts/vm/lifecycle/run.sh` takes a TTP session through shutdown, reboot and suspend/resume onto a new network, and judges each from a packet capture QEMU writes -outside the guest. It needs KVM, `qemu-system-x86_64`, `genisoimage` and `curl`, and -no root: +outside the guest. It needs KVM, `qemu-system-x86_64`, `genisoimage`, `curl` and a +host Python with `network-sandbox-engine>=2.6.0` (`NSE_PYTHON`, default `python3`), +and no root: ```bash -VM_WORK=~/.cache/ttp-lifecycle-vm scripts/vm/lifecycle/run.sh +NSE_PYTHON=venv/bin/python VM_WORK=~/.cache/ttp-lifecycle-vm scripts/vm/lifecycle/run.sh # the same on a guest whose network is managed by NetworkManager VM_DISTRO=fedora VM_WORK=~/.cache/ttp-lifecycle-vm-fedora scripts/vm/lifecycle/run.sh ``` @@ -101,15 +102,36 @@ VM_DISTRO=fedora VM_WORK=~/.cache/ttp-lifecycle-vm-fedora scripts/vm/lifecycle/r `VM_DISTRO` is `debian` (default; Debian 13, systemd-networkd) or `fedora` (Fedora 44, NetworkManager, SELinux enforcing). It downloads that cloud image once (verified against 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. +installs TTP from the working tree, and writes `results.txt`, one capture per QEMU +process, state snapshots and the observer's files (`observer/`) into `$VM_WORK`. + +Each phase is observed with NSE's portable agents, run in the guest over SSH: +a clocked beacon, then a UDP and a TCP stimulus stream to `198.51.100.7` as the +unprivileged, non-bypassed user, then a second beacon once the streams have +stopped. `scripts/vm/lifecycle/observer.py` judges the phase once its capture is +closed. An attempt on the wire always counts. An absence counts only when all of +these hold: + +- the pcap is intact and holds both beacons; +- the beacons place every attempt on the capture's clock, so the capture was open + for all of them; +- each stream's log is complete; +- no stretch of time went untested, except a gap NSE measured as the guest being + suspended (`CLOCK_BOOTTIME` advancing while `CLOCK_MONOTONIC` stops). + +Anything else is inconclusive, which fails the check. When the guest moves to a new +network, `vm_swap_network` waits until QEMU no longer lists the old NIC, stops the +capture, and starts the next one on the new network before its NIC exists. The +observer joins the two files. + +The power-off phase is still judged by `scripts/vm/lifecycle/egress.py`, with +`probe.py`: a stream its machine kills never has a complete log, so NSE cannot vouch +for its absences. `egress.py ` summarises a capture by destination and +streams the file. 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. With `--require-control` it also needs the +guest's own SSH traffic in the window. 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/reference/dependencies.md b/docs/web/reference/dependencies.md index 2b79d69..305d891 100644 --- a/docs/web/reference/dependencies.md +++ b/docs/web/reference/dependencies.md @@ -26,7 +26,7 @@ the session starts. | Group | Package | Constraint | Purpose | |---|---|---|---| -| `nse` | [network-sandbox-engine](https://pypi.org/project/network-sandbox-engine/) | `>=2.5.2,<3` | Isolated network namespace testing & Scapy rule validation. | +| `nse` | [network-sandbox-engine](https://pypi.org/project/network-sandbox-engine/) | `>=2.6.0,<3` | Isolated network namespace testing & Scapy rule validation. | | `nse` | [pyroute2](https://pypi.org/project/pyroute2/) | unpinned | Netlink route & interface management inside sandbox namespaces. | | `dev` | [pytest](https://pypi.org/project/pytest/) | `>=9.1.1` | Unit & integration test runner. | | `dev` | [hypothesis](https://pypi.org/project/hypothesis/) | `>=6.0.0` | Property-based fuzz testing. | diff --git a/docs/web/release-notes/changelog.md b/docs/web/release-notes/changelog.md index ee1d1d9..27824a2 100644 --- a/docs/web/release-notes/changelog.md +++ b/docs/web/release-notes/changelog.md @@ -25,6 +25,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Tests +- The lifecycle VM judges its phases with NSE 2.6.0, and the `nse` extra + requires `network-sandbox-engine>=2.6.0`. In the guest, NSE's stimulus streams + run as the non-bypassed user between two beacons that carry the guest's clocks. + `scripts/vm/lifecycle/observer.py` reads QEMU's capture. An attempt on the wire + always counts. An absence counts only when: + + - the capture is intact and holds both beacons; + - the beacons place every attempt inside it; + - each stream's log is complete; + - no time went untested, except a gap NSE measured as a suspend. + + The control, the active session and the reboot now share one continuous + capture. Previously each phase had its own file. The suspend/resume phase runs + its streams through the suspend. Before, nothing was measured until after the + move to the new network. `vm_swap_network` now hands the capture to the new + network before its NIC exists, after QEMU confirms the old NIC is gone. The + power-off phase stays on `egress.py`: a stream its machine kills never has a + complete log, so NSE cannot vouch for its absences. + [Tests](https://github.com/onyks-os/TransparentTorProxy/blob/main/tests/test_lifecycle_observer.py) + run the real agents against loopback and break one instrument at a time: a + missing beacon, a cut or joined capture, a killed stream, attempts outside the + beacons, a gap while the guest ran. Packets captured before a phase's opening + beacon are not read as its attempts. The first VM run counted an earlier + cleartext phase's packet as a leak, because NSE 2.6.0 matched it by a reused + source port although it carried another stream's probe ID. + - The `nse` extra requires `network-sandbox-engine>=2.5.2`. Each rule load in the zero-leak suite used to add another copy of NSE's trace rules to the namespace, so every traced packet repeated them once per load. The diff --git a/pyproject.toml b/pyproject.toml index 2ee7f8c..17cee72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ dev = [ "cyclonedx-python-lib[json-validation]>=11.0.0", ] nse = [ - # 2.5.2 is the floor, not a preference. Before 2.1.0, the NSE runner reported + # 2.6.0 is the floor, not a preference. Before 2.1.0, the NSE runner reported # PASSED when its oracle observed nothing, and the trace monitor could stop # reading mid-run without saying so - which would make TTP's zero-leak suite # green against an instrument that was not measuring. Before 2.1.2, the @@ -66,9 +66,12 @@ nse = [ # longer matched its own probe ID, and tracing a process's own packets # needed a chain TTP added by hand. Before 2.5.2, every rule load added # another copy of NSE's trace rules to the namespace, and an untraced - # readiness gave no reason. The upper bound is a real bound: 2.0.0 already rewrote + # readiness gave no reason. Before 2.6.0, nothing NSE could read judged a + # phase inside a VM: no portable stream, no report for a pcap QEMU wrote, no + # beacon carrying the guest's clocks (scripts/vm/lifecycle/observer.py). + # The upper bound is a real bound: 2.0.0 already rewrote # run_test_pipeline's signature once. - "network-sandbox-engine>=2.5.2,<3", + "network-sandbox-engine>=2.6.0,<3", "pyroute2", ] diff --git a/requirements/ci.txt b/requirements/ci.txt index b9b2bbc..1fc1775 100644 --- a/requirements/ci.txt +++ b/requirements/ci.txt @@ -1078,9 +1078,9 @@ mypy-extensions==1.2.0 \ --hash=sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768 \ --hash=sha256:c6e275a07f1c2fc096b62940452d0eaa3f3af7de45d704787866240a7c6d5a51 # via mypy -network-sandbox-engine==2.5.2 \ - --hash=sha256:9945b2ec53b6c32a46484f5a3f874bb7e86b520ec36c63f0d3c69541d3e572f7 \ - --hash=sha256:da1f48a15b674f93ac0550d879407c5f4c4d0919ca67ef55eb4f0a672df4e4a2 +network-sandbox-engine==2.6.0 \ + --hash=sha256:36feef53e7268d067ade10297cdf9fcd095b743e433c751b7ae0dbe1db7a7169 \ + --hash=sha256:265d444c96cf682f7e14a0c00ddd167344426d59ff0da83c3da4cfd44031ea82 # via transparent-tor-proxy (pyproject.toml) nh3==0.3.8 \ --hash=sha256:088eddcb226811214be26cd8077e8aaee6b93561db9eb2c39dc1af29e9b9c4f6 \ diff --git a/scripts/vm/lifecycle/observer.py b/scripts/vm/lifecycle/observer.py new file mode 100644 index 0000000..8d442df --- /dev/null +++ b/scripts/vm/lifecycle/observer.py @@ -0,0 +1,265 @@ +# Copyright (c) 2026 onyks-os +# SPDX-License-Identifier: MIT +"""Host-side NSE observer for the lifecycle VM (#30). + +The guest runs NSE's portable agents over ssh: a UDP and a TCP stimulus +stream as the unprivileged, non-bypassed user, and clocked beacons as root. +QEMU writes the guest's traffic to a pcap below the guest's own firewall. +This script prepares the agents' command lines and, once a capture is closed, +judges one phase from the pcap, the streams' logs and the beacons: + + observer.py agents DIR + observer.py stream OBS NAME udp|tcp # prints the agent's plan, shell-quoted + observer.py beacon LABEL IFACE # prints the agent's plan, shell-quoted + observer.py check OBS PHASE --expect contained|cleartext [--allow-suspend] PCAP... + +A phase is ``-open`` (beacon), ``-udp`` and ``-tcp`` +(streams), ``-close`` (beacon). The beacons are sent before the +streams start and after they stop, so they bracket every attempt. + +``check`` prints one line and exits 0 (pass), 1 (fail) or 2 (inconclusive). +An attempt seen on the wire always counts, whatever the instruments' health. +An absence counts only when NSE can vouch for it: + +* the pcap is intact and both of the phase's beacons are in it + (``CaptureReport.window_complete``); +* every attempt is placed on the capture's clock by the phase's beacons + (``ClockMap``), so the capture was open for all of them; +* each stream's log is complete, and no stretch of time went uncovered. + With ``--allow-suspend`` a gap is accepted only when NSE measured it as + the guest being suspended (``Gap.suspended``): its ``CLOCK_MONOTONIC`` + length stays within the correlation's limit, so the guest was not running. + +Packets captured before the phase's opening beacon are not read as its +attempts: they predate the streams (see ``_from_opening``). + +Several PCAPs are one capture handed from a removed network to the next (see +``vm_swap_network``): each must be intact, and they are joined in order +before NSE reads them. No packet can leave between them, because the guest +has no NIC then. + +The power-off phase is not judged here: a stream its machine kills never +has a complete log, so NSE (2.6.0) cannot vouch for its absences. It stays +on egress.py. +""" + +from __future__ import annotations + +import argparse +import json +import shlex +import struct +import sys +from pathlib import Path + +from nse import CaptureReport, ClockMap, StimulusStream, StreamLog, correlate, stimuli +from nse.core import beacons +from nse.formats import pcap + +#: TEST-NET-2 (RFC 5737): never a Tor relay, and nothing on the guest talks to +#: it on its own. The same destination as probe.py. +PROBE_DST = "198.51.100.7" +PORTS = {"udp": 53, "tcp": 80} +PERIOD = 0.2 +#: A stretch longer than this many periods without an attempt is a gap. The +#: guest is a busy VM on a shared runner; one second is the resolution of the +#: verdict, not of the firewall. +MAX_GAP_PERIODS = 5.0 +#: QEMU's filter-dump keeps 128 bytes per frame (vm_capture_start). The probe's +#: marker ends well inside them. +REQUIRED_BYTES = 128 + +PASS, FAIL, INCONCLUSIVE = 0, 1, 2 + + +def stream_for(transport: str) -> StimulusStream: + """The stream a phase runs; rebuilt identically to parse its log.""" + if transport == "udp": + stimulus = stimuli.udp(PROBE_DST, PORTS["udp"]) + elif transport == "tcp": + stimulus = stimuli.tcp_connect(PROBE_DST, PORTS["tcp"]) + else: + raise ValueError(f"unknown transport {transport!r}") + return StimulusStream(stimulus, period=PERIOD) + + +def write_agents(directory: Path) -> None: + """The agents' sources, to copy into the guest and run as files. + + Run from a file rather than with ``-c``: ``systemd-run`` would otherwise + receive the whole source as one argument. + """ + directory.mkdir(parents=True, exist_ok=True) + (directory / "stream-agent.py").write_text(stream_for("udp").command()[0][4]) + (directory / "beacon-agent.py").write_text(beacons.agent_command("eth0", "agent")[0][4]) + + +def stream_plan(obs: Path, name: str, transport: str) -> str: + argv, stream_id = stream_for(transport).command() + obs.mkdir(parents=True, exist_ok=True) + (obs / f"{name}.stream.json").write_text(json.dumps({"stream_id": stream_id, "transport": transport})) + return shlex.quote(argv[5]) + + +def beacon_plan(label: str, iface: str) -> str: + return shlex.quote(beacons.agent_command(iface, label)[0][5]) + + +class Inconclusive(Exception): + """The instruments cannot support a verdict; the message says why.""" + + +_GLOBAL_HEADER = struct.Struct(" Path: + """One pcap from the capture files of one QEMU process, in order. + + Each file is checked on its own first, so damage at the end of one cannot + be read as records of the next. Their link type and snap length must agree. + """ + if len(paths) == 1: + return paths[0] + contents = [pcap.read(path) for path in paths] + for item in contents: + if item.error: + raise Inconclusive(f"{item.path}: {item.error}") + first = contents[0] + for item in contents[1:]: + if (item.link_type, item.snaplen, item.nanosecond) != (first.link_type, first.snaplen, first.nanosecond): + raise Inconclusive(f"{item.path}: link type or snap length differs from {first.path}") + scale = 10**9 if first.nanosecond else 10**6 + with out.open("wb") as stream: + magic = 0xA1B23C4D if first.nanosecond else 0xA1B2C3D4 + stream.write(_GLOBAL_HEADER.pack(magic, 2, 4, 0, 0, first.snaplen or 0, first.link_type or 0)) + for item in contents: + for record in item.records: + ticks = round(record.timestamp * scale) + seconds, fraction = divmod(ticks, scale) + stream.write( + _RECORD_HEADER.pack(seconds, fraction, len(record.data), record.original_length) + record.data + ) + return out + + +def _from_opening(packets: list, seen: list, opening: str) -> list: + """The packets captured from the phase's opening beacon on. + + The streams start after that beacon is on the wire, so nothing before it + is one of their attempts. Earlier phases' traffic is in the same capture, + and NSE (2.6.0) matches a request by source port alone, even when the + packet carries another stream's probe ID: a reused ephemeral port would + otherwise read an earlier cleartext phase as a leak. Without the beacon + in the capture nothing is dropped; the absences are unvouched then anyway. + """ + start = next((sighting.seen_at for sighting in seen if sighting.token == opening), None) + if start is None: + return packets + return [packet for packet in packets if float(packet.time) >= start] + + +def _brief(problems) -> str: + items = list(problems) + return "; ".join(items[:3]) + (f" (+{len(items) - 3} more)" if len(items) > 3 else "") + + +def judge(obs: Path, phase: str, expect: str, pcaps: list[Path], *, allow_suspend: bool) -> tuple[int, str]: + """The verdict for *phase* and a one-line reason.""" + try: + expected = [beacons.agent_report((obs / f"{phase}-{edge}.beacon").read_bytes()) for edge in ("open", "close")] + except (OSError, ValueError) as exc: + raise Inconclusive(f"beacon agent: {exc}") from None + source = joined(pcaps, obs / f"{phase}.joined.pcap") + report, packets = CaptureReport.from_pcap(source, required_bytes=REQUIRED_BYTES, expected_beacons=expected) + tokens = {beacon.token for beacon in expected} + ours = [seen for seen in report.beacons_seen if seen.token in tokens] + clock = ClockMap.from_beacons(ours) + packets = _from_opening(packets, ours, expected[0].token) + limit = MAX_GAP_PERIODS * PERIOD + + seen = ran = 0 + doubts: list[str] = [] + if not report.instrument_healthy or report.window_complete is not True: + doubts.append( + "the capture cannot vouch for an absence: " + + _brief([*report.errors, *(f"beacon {label} missing" for label in report.beacons_missing)]) + ) + for transport in ("udp", "tcp"): + name = f"{phase}-{transport}" + try: + meta = json.loads((obs / f"{name}.stream.json").read_text()) + output = (obs / f"{name}.log").read_bytes() + except (OSError, ValueError) as exc: + raise Inconclusive(f"{name}: {exc}") from None + log = StreamLog.parse(output, meta["stream_id"], final=True, stream=stream_for(meta["transport"])) + joined_ = correlate(log, packets, capture=report, max_gap_periods=MAX_GAP_PERIODS) + placed = correlate(log, packets, capture=report, max_gap_periods=MAX_GAP_PERIODS, clock=clock) + covering = [fate for fate in joined_.fates if fate.covers] + on_wire = joined_.with_status("on_wire", "received") + ran += len(covering) + seen += len(on_wire) + unexplained = [ + gap for gap in joined_.gaps if not (allow_suspend and gap.suspended > 0 and gap.end - gap.start <= limit) + ] + doubts += [f"{name}: {problem}" for problem in joined_.problems] + doubts += [f"{name}: {problem}" for problem in joined_.contradictions] + doubts += [f"{name}: {problem}" for problem in placed.problems if problem not in joined_.problems] + doubts += [f"{name}: {gap.seconds:.1f} s without an attempt after seq {gap.after_seq}" for gap in unexplained] + if not covering: + doubts.append(f"{name}: no attempt could run") + if expect == "cleartext": + missed = joined_.with_status("sent_not_seen") + if missed: + doubts.append(f"{name}: {len(missed)} attempt(s) left the socket and are not in the capture") + + if expect == "contained": + if seen: + return FAIL, f"{seen} of {ran} attempt(s) on the wire" + if doubts: + return INCONCLUSIVE, "inconclusive: " + _brief(doubts) + return PASS, f"0 of {ran} attempt(s) on the wire" + if doubts: + return INCONCLUSIVE, "inconclusive: " + _brief(doubts) + if seen < ran: + return FAIL, f"only {seen} of {ran} attempt(s) on the wire: the capture is not measuring" + return PASS, f"{seen} of {ran} attempt(s) on the wire: expected, recorded" + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = ap.add_subparsers(dest="command", required=True) + sub.add_parser("agents").add_argument("dir", type=Path) + stream = sub.add_parser("stream") + stream.add_argument("obs", type=Path) + stream.add_argument("name") + stream.add_argument("transport", choices=sorted(PORTS)) + beacon = sub.add_parser("beacon") + beacon.add_argument("label") + beacon.add_argument("iface") + check = sub.add_parser("check") + check.add_argument("obs", type=Path) + check.add_argument("phase") + check.add_argument("--expect", choices=("contained", "cleartext"), required=True) + check.add_argument("--allow-suspend", action="store_true") + check.add_argument("pcaps", type=Path, nargs="+") + args = ap.parse_args(argv) + + if args.command == "agents": + write_agents(args.dir) + elif args.command == "stream": + print(stream_plan(args.obs, args.name, args.transport)) + elif args.command == "beacon": + print(beacon_plan(args.label, args.iface)) + else: + try: + code, reason = judge(args.obs, args.phase, args.expect, args.pcaps, allow_suspend=args.allow_suspend) + except Inconclusive as exc: + code, reason = INCONCLUSIVE, f"inconclusive: {exc}" + print(reason) + return code + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vm/lifecycle/run.sh b/scripts/vm/lifecycle/run.sh index 1361bdc..3fc53ae 100755 --- a/scripts/vm/lifecycle/run.sh +++ b/scripts/vm/lifecycle/run.sh @@ -4,13 +4,23 @@ # # Lifecycle transitions of #30, measured in a disposable VM: shutdown with an # active session, reboot with an active session, suspend/resume onto a new -# network. Every verdict comes from a capture taken by QEMU outside the guest, -# of a probe that keeps trying to reach 198.51.100.7 in cleartext (probe.py). +# network. Every verdict comes from a capture taken by QEMU outside the guest. # -# VM_WORK=~/.cache/ttp-lifecycle-vm [VM_DISTRO=fedora] scripts/vm/lifecycle/run.sh +# Each phase runs NSE's stimulus streams in the guest (UDP and TCP to +# 198.51.100.7, as the unprivileged, non-bypassed user) between two clocked +# beacons, and observer.py judges it from the capture: an attempt on the wire +# always counts, an absence only when NSE can vouch for it. One capture runs +# per QEMU process, handed over when the guest changes network. The power-off +# phase still uses probe.py and egress.py: a stream its machine kills never has +# a complete log, so NSE cannot vouch for its absences. # -# Writes captures, state snapshots and results.txt into $VM_WORK; exits non-zero -# if any check fails. Needs KVM, qemu-system-x86_64, genisoimage and curl; no root. +# VM_WORK=~/.cache/ttp-lifecycle-vm [VM_DISTRO=fedora] [NSE_PYTHON=venv/bin/python] \ +# scripts/vm/lifecycle/run.sh +# +# Writes captures, state snapshots, the observer's files and results.txt into +# $VM_WORK; exits non-zero if any check fails. Needs KVM, qemu-system-x86_64, +# genisoimage, curl and a host Python with network-sandbox-engine >= 2.6.0 +# (NSE_PYTHON); no root. set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -22,9 +32,12 @@ source "$HERE/vm.sh" PROBE_DST=198.51.100.7 RESULTS="$VM_WORK/results.txt" +OBS="$VM_WORK/observer" # Outputs of an earlier run must not be read as this run's: a stale # ttp-start-failure.txt already misled once. rm -f "${VM_WORK:?}"/*.pcap "${VM_WORK:?}"/state-*.txt "${VM_WORK:?}/ttp-start-failure.txt" +rm -rf "${OBS:?}" +mkdir -p "$OBS" : >"$RESULTS" FAILED=0 @@ -48,28 +61,80 @@ inconclusive() { # inconclusive 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; } +# --- NSE observation ------------------------------------------------------------ +observer() { "${NSE_PYTHON:-python3}" "$HERE/observer.py" "$@"; } + +guest_iface() { vm_ssh "ip -o -4 route show default | awk '{print \$5; exit}'"; } + +# A clocked beacon on the guest's link, sent as root by NSE's agent. Its report +# is what the capture must contain; a failed send leaves an error the verdict +# reads as inconclusive. +beacon() { # beacon