Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Tests

- The `nse` extra requires `network-sandbox-engine>=2.9.0`. In 2.9.0 a
stimulus's verdict can no longer be taken from another packet that reused its
kernel trace id. The VM observers use what NSE 2.8.0 added for observers
outside the sandbox, and lose their own copies of it:
- the agents are NSE's files (`stimulus-agent.py`, `beacon-agent.py`) and
their plans come from `agent_plan()`, not from positions in an argv;
- packets are placed between two beacons by frame (`CaptureReport.between`),
not by timestamp, which QEMU records to the microsecond;
- the chaos sweep reads the guest's MAC from its beacon report, and the guest
no longer writes a token or a MAC of its own.

## [0.5.2] - 2026-12-03

Maintenance, mostly for packagers and `ttp.service`. The packages depend on
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.7.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`) |
| **Zero-leak ruleset suite.** TTP's real ruleset in a network namespace (NSE 2.9.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 |
Expand Down
6 changes: 4 additions & 2 deletions docs/web/explanation/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,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.6.0,<3`. The floor is not a preference.
`network-sandbox-engine>=2.9.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
Expand Down Expand Up @@ -167,7 +167,9 @@ process's own packets meet, with readiness proven by a canary's own trace. Befor
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. Before 2.6.0 nothing NSE could read judged a phase inside a
VM. A green result from an engine below
VM. Before 2.9.0 a stimulus's verdict could be taken from another packet: the
kernel derives a trace id from the packet buffer's address, which is soon
reused, so another packet's `DROP` could be counted as the stimulus's. 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
Expand Down
2 changes: 1 addition & 1 deletion docs/web/how-to/continuous-fault-evidence.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ variants. `--injection kill_tor` selects a single fault for local reproduction.
The wrapper's exit status requires both recovery audits and external evidence
to succeed. It retains `chaos.pcap`, `chaos.log`, `chaos-boundary/events.jsonl`,
each stream's log in `chaos-boundary/` and `chaos-boundary-report.json`; CI
uploads them. The host needs `network-sandbox-engine>=2.7.0` in `NSE_PYTHON`.
uploads them. The host needs `network-sandbox-engine>=2.9.0` in `NSE_PYTHON`.
Captures may include unrelated guest/Tor traffic and are diagnostic artifacts.

These tests cover the stated synthetic actor, interface and packet shapes.
Expand Down
2 changes: 1 addition & 1 deletion docs/web/how-to/vm-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ 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`, `curl` and a
host Python with `network-sandbox-engine>=2.7.0` (`NSE_PYTHON`, default `python3`),
host Python with `network-sandbox-engine>=2.9.0` (`NSE_PYTHON`, default `python3`),
and no root:

```bash
Expand Down
13 changes: 13 additions & 0 deletions docs/web/release-notes/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Tests

- The `nse` extra requires `network-sandbox-engine>=2.9.0`. In 2.9.0 a
stimulus's verdict can no longer be taken from another packet that reused its
kernel trace id. The VM observers use what NSE 2.8.0 added for observers
outside the sandbox, and lose their own copies of it:
- the agents are NSE's files (`stimulus-agent.py`, `beacon-agent.py`) and
their plans come from `agent_plan()`, not from positions in an argv;
- packets are placed between two beacons by frame (`CaptureReport.between`),
not by timestamp, which QEMU records to the microsecond;
- the chaos sweep reads the guest's MAC from its beacon report, and the guest
no longer writes a token or a MAC of its own.

## [0.5.2] - 2026-12-03

Maintenance, mostly for packagers and `ttp.service`. The packages depend on
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ nse = [
# read whole into memory (the chaos sweep's full-frame captures).
# The upper bound is a real bound: 2.0.0 already rewrote
# run_test_pipeline's signature once.
"network-sandbox-engine>=2.7.0,<3",
"network-sandbox-engine>=2.9.0,<3",
"pyroute2",
]

Expand Down
11 changes: 7 additions & 4 deletions requirements/ci.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1063,10 +1063,12 @@ mypy==2.4.1 \
mypy-extensions==1.2.0 \
--hash=sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768 \
--hash=sha256:c6e275a07f1c2fc096b62940452d0eaa3f3af7de45d704787866240a7c6d5a51
# via mypy
network-sandbox-engine==2.7.0 \
--hash=sha256:62aab75a121b428fa0475f4bf0b819f3b7e7f20de87a451135827718111408cc \
--hash=sha256:9cbfa83ea58b7ba3cffe35369b40633f8cbdc666862131b154c252051b1772c7
# via
# librt
# mypy
network-sandbox-engine==2.9.0 \
--hash=sha256:31e814337d9fcb93c204759380e56e4a7dbd800333e9658b7d2afded0333ee3e \
--hash=sha256:3ee5992e4c4e884d9e89519fe5eb3f3475a3cd66fe7b50e9e586dbe0ab30c603
# via transparent-tor-proxy (pyproject.toml)
nh3==0.3.8 \
--hash=sha256:088eddcb226811214be26cd8077e8aaee6b93561db9eb2c39dc1af29e9b9c4f6 \
Expand Down Expand Up @@ -1720,6 +1722,7 @@ typing-extensions==4.16.0 \
# cyclonedx-python-lib
# httpx2
# mypy
# network-sandbox-engine
# pydantic
# pydantic-core
# pydantic-settings
Expand Down
2 changes: 1 addition & 1 deletion scripts/vm/lifecycle/chaos.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ vm_boot
vm_wait_ready 600
vm_install_ttp "$ROOT"
vm_ssh 'sudo install -d /usr/local/lib/ttp-nse'
for file in stream-agent.py beacon-agent.py chaos-streams.json; do
for file in stimulus-agent.py beacon-agent.py chaos-streams.json; do
vm_ssh "sudo tee /usr/local/lib/ttp-nse/$file >/dev/null" <"$OBS/$file"
done
VM_CAPTURE_MAXLEN=65535 vm_capture_start chaos
Expand Down
19 changes: 10 additions & 9 deletions scripts/vm/lifecycle/chaos_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ def plan(directory: Path) -> None:
write_agents(directory)
plans, ids = {}, {}
for name in STREAMS:
argv, ids[name] = stream_for(name).command()
plans[name] = argv[5]
plans[name], ids[name] = stream_for(name).agent_plan()
(directory / "chaos-streams.json").write_text(json.dumps(plans))
(directory / "stream-ids.json").write_text(json.dumps(ids))

Expand All @@ -94,7 +93,10 @@ def evaluate(capture: Path, directory: Path, stream_ids: dict[str, str], *, evid
sent = [beacons.agent_report(event["beacon"]) for event in events]
if [b.label for b in sent] != [event["kind"] for event in events]:
raise ValueError("A beacon does not carry its phase")
mac = events[0]["mac"]
# The beacon agent reports the guest's MAC (NSE 2.8.0); only its frames count.
mac = sent[0].mac
if mac is None:
raise ValueError("The capture-open beacon does not report the guest's MAC")
fixture = set(DESTINATIONS.values())

def keep(packet) -> bool:
Expand All @@ -107,19 +109,18 @@ def keep(packet) -> bool:
seen = {sighting.token: sighting.seen_at for sighting in report.beacons_seen}
at = [seen.get(b.token) for b in sent]

def escaped(start: float, end: float) -> list:
return [p for p in packets if start < float(p.time) < end]
def escaped(start, end) -> list:
# By frame between the two beacons; a beacon missing or seen twice brackets nothing.
return report.between(packets, start, end) or []

# Retain positively measured egress even if later evidence is lost. Only
# count packets bracketed by consecutive beacons of one fault.
for (event, start), (following, end) in pairwise(zip(events, at)):
for (event, start), (following, end) in pairwise(zip(events, sent, strict=True)):
if (
event["kind"] in FAULT_PHASES
and following["kind"] in FAULT_PHASES
and event["fault"] == following["fault"]
and FAULT_PHASES.index(event["kind"]) < FAULT_PHASES.index(following["kind"])
and start is not None
and end is not None
):
hits = escaped(start, end)
evidence["confirmed_fault_escaped_packets"] += len(hits)
Expand Down Expand Up @@ -191,7 +192,7 @@ def escaped(start: float, end: float) -> list:
worst = max(gap.seconds for gap in window.gaps)
raise ValueError(f"Stimulus gap exceeded {MAX_SAMPLE_GAP}s in {name}: {worst:.3f}s")
statuses.update(fate.attempt.result.outcome for fate in window.fates if fate.attempt)
hits, hold_hits = escaped(before[1], at[index]), escaped(hold[1], at[index])
hits, hold_hits = escaped(before[0], beacon), escaped(hold[0], beacon)
exposure_allowed = event["fault"] in ENFORCEMENT_FAULTS
windows.append(
{
Expand Down
39 changes: 13 additions & 26 deletions scripts/vm/lifecycle/observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@
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``).
Only packets read between the phase's two beacons are its attempts
(``CaptureReport.between``). Earlier phases' traffic is in the same capture,
and NSE matches a TCP SYN, which carries no probe ID, by source port alone: a
reused port would otherwise read an earlier cleartext phase as a leak. Without
both beacons every packet is read; the absences are unvouched then anyway.

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
Expand All @@ -52,7 +55,7 @@
import sys
from pathlib import Path

from nse import CaptureReport, ClockMap, StimulusStream, StreamLog, correlate, stimuli
from nse import CaptureReport, ClockMap, StimulusStream, StreamLog, agents, correlate, stimuli
from nse.core import beacons
from nse.formats import pcap

Expand Down Expand Up @@ -84,25 +87,24 @@ def stream_for(transport: str) -> StimulusStream:


def write_agents(directory: Path) -> None:
"""The agents' sources, to copy into the guest and run as files.
"""``stimulus-agent.py`` and ``beacon-agent.py``, 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])
agents.write_agents(directory)


def stream_plan(obs: Path, name: str, transport: str) -> str:
argv, stream_id = stream_for(transport).command()
plan, stream_id = stream_for(transport).agent_plan()
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])
return shlex.quote(plan)


def beacon_plan(label: str, iface: str) -> str:
return shlex.quote(beacons.agent_command(iface, label)[0][5])
return shlex.quote(beacons.agent_plan(iface, label)[0])


class Inconclusive(Exception):
Expand Down Expand Up @@ -143,22 +145,6 @@ def joined(paths: list[Path], out: Path) -> Path:
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 matches a TCP SYN, which carries no probe ID, by source port
alone: a reused port would otherwise read an earlier cleartext phase as a
leak. (Without a clock map, 2.7.0's ClockMap.not_before does not apply.) 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 "")
Expand All @@ -175,7 +161,8 @@ def judge(obs: Path, phase: str, expect: str, pcaps: list[Path], *, allow_suspen
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)
window = report.between(packets, *expected)
packets = packets if window is None else window
limit = MAX_GAP_PERIODS * PERIOD

seen = ran = 0
Expand Down
4 changes: 2 additions & 2 deletions scripts/vm/lifecycle/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ streams_start() { # streams_start <phase>
plan="$(observer stream "$OBS" "$name" "$t")"
vm_ssh "sudo systemd-run --quiet --uid=ttp --unit=ttp-stream-$name \
-p StandardOutput=truncate:/var/tmp/ttp-stream-$name.log \
python3 -I -S /usr/local/lib/ttp-nse/stream-agent.py $plan"
python3 -I -S /usr/local/lib/ttp-nse/stimulus-agent.py $plan"
done
}

Expand Down Expand Up @@ -153,7 +153,7 @@ vm_install_ttp "$ROOT"
vm_ssh 'sudo tee /usr/local/lib/ttp-probe.py >/dev/null' <"$HERE/probe.py"
observer agents "$OBS/agents"
vm_ssh 'sudo install -d /usr/local/lib/ttp-nse'
for agent in stream-agent.py beacon-agent.py; do
for agent in stimulus-agent.py beacon-agent.py; do
vm_ssh "sudo tee /usr/local/lib/ttp-nse/$agent >/dev/null" <"$OBS/agents/$agent"
done

Expand Down
9 changes: 4 additions & 5 deletions tests/chaos_observation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import ipaddress
import json
import pwd
import secrets
import socket
import struct
import subprocess
Expand Down Expand Up @@ -100,13 +99,13 @@ def __init__(self, directory: Path, interface: str, user: str):
self.events = (directory / "events.jsonl").open("w")
self.streams: dict[str, subprocess.Popen] = {}
# Before any stream starts, so every attempt lies between two beacons.
self.marker("capture-open", mac=self.mac)
self.marker("capture-open")
identity = pwd.getpwnam(user)
try:
for name, plan in json.loads((AGENTS / "chaos-streams.json").read_text()).items():
with (directory / f"{name}.log").open("wb") as log, (directory / f"{name}.err").open("wb") as err:
self.streams[name] = subprocess.Popen(
[sys.executable, "-I", "-S", str(AGENTS / "stream-agent.py"), plan],
[sys.executable, "-I", "-S", str(AGENTS / "stimulus-agent.py"), plan],
user=identity.pw_uid,
group=identity.pw_gid,
extra_groups=[],
Expand All @@ -130,8 +129,8 @@ def marker(self, kind: str, **fields):
self._beacon(kind, fields)

def _beacon(self, kind: str, fields: dict):
# NSE's beacon agent plan (nse.core.beacons.agent_command); the token is ours.
plan = json.dumps({"iface": self.interface, "label": kind, "token": secrets.token_hex(16)})
# NSE's beacon agent plan, a stable contract since 2.8.0; the agent draws the token.
plan = json.dumps({"iface": self.interface, "label": kind})
sent = subprocess.run(
[sys.executable, "-I", "-S", str(AGENTS / "beacon-agent.py"), plan],
capture_output=True,
Expand Down
13 changes: 3 additions & 10 deletions tests/test_chaos_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

pytest.importorskip("nse", minversion="2.7.0")

from nse.core import beacons
from nse.formats import pcap
from nse.formats.beacon import clocked_frame
from nse.models.stream import StreamLog
Expand Down Expand Up @@ -73,6 +72,7 @@ def beacon(self, kind: str, *, on_wire: bool = True, **fields) -> dict:
"label": kind,
"token": token,
"iface": "ens3",
"mac": MAC,
"sent_at": sent_at,
"boot_id": BOOT_ID,
"monotonic_before": mono_before / 1e9,
Expand All @@ -90,7 +90,7 @@ def beacon(self, kind: str, *, on_wire: bool = True, **fields) -> dict:
return {"mono": (mono_before / 1e9, mono_after / 1e9)}

def start(self) -> None:
self.beacon("capture-open", mac=MAC)
self.beacon("capture-open")
for name in chaos_observer.STREAMS:
argv, self.ids[name] = chaos_observer.stream_for(name).command(python=sys.executable)
self.streams[name] = subprocess.Popen(argv, stdout=subprocess.PIPE)
Expand Down Expand Up @@ -328,19 +328,12 @@ def test_a_cut_capture_keeps_the_egress_before_the_cut(tmp_path: Path) -> None:
assert report["confirmed_fault_escaped_packets"] > 0


def test_the_guest_writes_the_beacon_agents_plan() -> None:
"""chaos_observation.Recorder builds the beacon agent's plan without NSE."""
plan = json.loads(beacons.agent_command("ens3", "fault-before")[0][5])
assert set(plan) == {"iface", "label", "token"}
assert len(plan["token"]) == 32


def test_plan_writes_the_agents_and_one_plan_per_stream(tmp_path: Path) -> None:
chaos_observer.main(["plan", str(tmp_path)])
plans = json.loads((tmp_path / "chaos-streams.json").read_text())
ids = json.loads((tmp_path / "stream-ids.json").read_text())
assert set(plans) == set(ids) == {"dns4", "udp4", "tcp4", "dns6", "udp6", "tcp6"}
assert (tmp_path / "stream-agent.py").is_file() and (tmp_path / "beacon-agent.py").is_file()
assert (tmp_path / "stimulus-agent.py").is_file() and (tmp_path / "beacon-agent.py").is_file()


@pytest.mark.parametrize("state", ["ready", "tentative", "dadfailed", "linklocal", "unreachable"])
Expand Down
2 changes: 1 addition & 1 deletion tests/test_lifecycle_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def streams(self, seconds: float = 1.0, *, leak: tuple[str, ...] = (), kill: boo
name = f"{PHASE}-{transport}"
plan = observer.stream_plan(self.obs, name, transport)
meta = json.loads((self.obs / f"{name}.stream.json").read_text())
argv = [sys.executable, "-I", "-S", str(self.obs / "stream-agent.py"), *shlex.split(plan)]
argv = [sys.executable, "-I", "-S", str(self.obs / "stimulus-agent.py"), *shlex.split(plan)]
running[transport] = (name, meta, subprocess.Popen(argv, stdout=subprocess.PIPE))
time.sleep(seconds)
for transport, (name, meta, process) in running.items():
Expand Down
Loading