From 3d338db73fc45866c180aa2fa5e6060895469656 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Fri, 13 Nov 2026 23:51:58 -0800 Subject: [PATCH 1/5] =?UTF-8?q?feat(redteam):=20nix/redteam.nix=20?= =?UTF-8?q?=E2=80=94=20image=20tarballs,=20attacker=20tools,=20scenario=20?= =?UTF-8?q?app=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 0 commit C1 (docs/redteam-harness.md): packages.redteam-oci and redteam-oci-tcp-stress materialize the streamLayeredImage scripts as deterministic .tar.gz files; redteam-attacker-tools tars the static xtcp2client/xtcp2ctl with a build-time static-ELF assertion. Apps: one per vagrant/scenarios/rt-*.sh (discovered from the flake source), plus destroy/status/lint helpers. vagrant (with the bundled vagrant-libvirt plugin) is evaluated in its own allowUnfree instance so nothing else in the flake needs NIXPKGS_ALLOW_UNFREE. --- nix/default.nix | 34 ++++++- nix/redteam.nix | 235 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 nix/redteam.nix diff --git a/nix/default.nix b/nix/default.nix index 166bf3480..6c674f268 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -167,6 +167,24 @@ let artifact = tests.test-linkmonitor-performance; }; + # Red-team harness wiring (docs/redteam-plan.md, docs/redteam-implementation.md, + # docs/redteam-harness.md). Apps run on the harness host (l); only the lint is + # a `nix flake check` member. + # vagrant is licensed bsl11, which nixpkgs marks unfree: it is evaluated in + # its own allowUnfree instance so neither the dev shell nor any other flake + # output needs NIXPKGS_ALLOW_UNFREE. Only the redteam-* apps pull it in. + redteamVagrant = + (import nixpkgs { + inherit (pkgs.stdenv.hostPlatform) system; + config.allowUnfree = true; + }).vagrant; + redteam = import ./redteam.nix { + inherit pkgs lib src; + vagrant = redteamVagrant; + inherit (binaries) xtcp2client xtcp2ctl; + inherit (containers) oci-xtcp2 oci-xtcp2-tcp-stress; + }; + # Guest tests that report through the serial console, each built around # microvms/mkVmCheck.nix's runner: checks.vm-, run in the build # sandbox with KVM and cached by its inputs, and the app test--vm, @@ -1181,7 +1199,9 @@ in # Per-flavor + per-package test targets. The two imports above each # return an attrset whose keys already start with `test-` so they # merge straight into the flake's packages namespace. - // (lib.filterAttrs (n: _v: lib.hasPrefix "test-" n) tests); + // (lib.filterAttrs (n: _v: lib.hasPrefix "test-" n) tests) + # Red-team harness images/tools (docs/redteam-harness.md). + // redteam.packages; devShells = { default = devshell; @@ -1232,7 +1252,12 @@ in // { inherit (tests) test-linkmonitor; } - // (lib.filterAttrs (n: _v: lib.hasPrefix "test-go-flavor-" n) tests); + // (lib.filterAttrs (n: _v: lib.hasPrefix "test-go-flavor-" n) tests) + # Red-team harness lint — the only hermetic member of the red-team program + # (VM scenarios are apps; see nix/redteam.nix). + // { + redteam-lint = redteam.checks.redteam-lint; + }; apps = { test-tcp-controller-vm = { @@ -1672,7 +1697,10 @@ in type = "app"; program = "${drv}/bin/${name}"; }) tiers - ); + ) + # Red-team harness: one app per scenario (vagrant/scenarios/rt-*.sh) plus + # lifecycle helpers. See nix/redteam.nix. + // redteam.apps; inherit tests; } diff --git a/nix/redteam.nix b/nix/redteam.nix new file mode 100644 index 000000000..dabc44232 --- /dev/null +++ b/nix/redteam.nix @@ -0,0 +1,235 @@ +# nix/redteam.nix +# +# Red-team harness wiring. The program lives in docs/redteam-plan.md (threat +# model + scenario catalog) and docs/redteam-implementation.md (phases and +# definition of done); the build decisions here are documented in +# docs/redteam-harness.md. What this file adds: +# +# packages.redteam-oci the oci-xtcp2 image as a single .tar.gz +# (streamLayeredImage output is a script, +# not a file — see D2 in the harness doc) +# packages.redteam-oci-tcp-stress the tcp_server/tcp_client image the RT-11 +# victim work population runs, same form +# packages.redteam-attacker-tools tar of static xtcp2 client binaries; +# refuses to build if any binary stops +# being statically linked (a dynamic ELF +# would not run on the Ubuntu guests) +# apps.redteam-rt-- one per vagrant/scenarios/rt-*.sh +# apps.redteam-{destroy,status,lint} harness lifecycle helpers +# checks.redteam-lint hermetic shellcheck of vagrant/**.sh — +# the only red-team member of +# `nix flake check`; VM scenarios need +# KVM, libvirtd and the network, so they +# are apps, not checks +# +# Runners execute from the repo root on the harness host (l) and require +# /dev/kvm, a reachable qemu:///system and the network (vagrant box download). +# They run the scenario script from the *working tree* ($PWD), not the store +# copy — same `path:.`-vs-`.` reasoning as focused-quality in nix/default.nix: +# WIP scenarios are only discoverable when the flake source includes them, so +# use `nix run path:.#redteam-…` during development. +# +{ + pkgs, + lib, + src, # full tree — goSource's Go-only filter must not strip vagrant/ + # vagrant with the vagrant-libvirt plugin bundled (the nixpkgs withLibvirt + # default on Linux). Unfree (bsl11): nix/default.nix passes an allowUnfree + # instance scoped to these apps, so nothing else in the flake needs it. + vagrant, + xtcp2client, # binaries.xtcp2client (static, CGO_ENABLED=0) + xtcp2ctl, # binaries.xtcp2ctl (static, CGO_ENABLED=0) + oci-xtcp2, # containers.oci-xtcp2: streamLayeredImage script + oci-xtcp2-tcp-stress, # containers.oci-xtcp2-tcp-stress, same form +}: + +let + # Materialize a streamLayeredImage (a script that streams the tar to stdout) + # as one deterministic .tar.gz file. gzip -n keeps it byte-stable so the + # runner's scp-upload decision (same store path = skip) stays cheap. + streamToTarGz = + name: image: + pkgs.runCommand name { nativeBuildInputs = [ pkgs.gzip ]; } '' + ${image} | gzip -n > $out + ''; + + redteamOci = streamToTarGz "xtcp2-oci.tar.gz" oci-xtcp2; + redteamTcpStressOci = streamToTarGz "xtcp2-tcp-stress.tar.gz" oci-xtcp2-tcp-stress; + + # Static client binaries the attacker VM and the co-tenant attacker container + # run. The build-time linkage assertion is the whole point: these unpack on + # stock Ubuntu, where a dynamic ELF would die on a missing /nix/store loader. + attackerToolsBinaries = { + inherit xtcp2client xtcp2ctl; + }; + attackerTools = + pkgs.runCommand "xtcp2-redteam-attacker-tools.tar" + { + nativeBuildInputs = [ + pkgs.file + pkgs.gnutar + ]; + } + '' + set -eu + # nixpkgs' grpcurl is dynamically linked and deliberately NOT here; the + # gRPC scenarios get a static build of their own when Phase 1 needs them + # (see docs/redteam-harness.md "Open questions"). + for b in ${ + lib.concatStringsSep " " (lib.mapAttrsToList (_: drv: "${drv}/bin/*") attackerToolsBinaries) + }; do + file "$b" | grep -q 'statically linked' || { + echo "redteam-attacker-tools: $b is not a static ELF — it would not run on the Ubuntu guests" >&2 + exit 1 + } + done + mkdir -p xtcp2-redteam/bin + for b in ${ + lib.concatStringsSep " " ( + lib.mapAttrsToList (name: drv: "${drv}/bin/${name}") attackerToolsBinaries + ) + }; do + cp "$b" "xtcp2-redteam/bin/$(basename "$b")" + done + tar -C xtcp2-redteam -cf $out . + ''; + + # vagrant/scenarios/rt---.sh -> rt-- + scenarioId = + file: + let + parts = lib.splitString "-" (lib.removeSuffix ".sh" (baseNameOf file)); + in + "rt-${builtins.elemAt parts 1}-${builtins.elemAt parts 2}"; + + scenariosDir = src + "/vagrant/scenarios"; + scenarioFiles = + if lib.pathExists scenariosDir then lib.filesystem.listFilesRecursive scenariosDir else [ ]; + + # One app per scenario. The tarball store paths are baked in as build-time + # inputs (no run-time `nix build` inside the runner), the VM state lives in + # vagrant/.gen (VAGRANT_CWD/VAGRANT_HOME), and the scenario script itself + # runs from the working tree so WIP edits are picked up without a rebuild. + mkScenarioRunner = + file: + let + id = scenarioId file; + in + pkgs.writeShellApplication { + name = "redteam-${id}"; + runtimeInputs = [ + pkgs.bash + pkgs.coreutils + vagrant + pkgs.openssh + ]; + text = '' + if [ ! -f flake.nix ]; then + echo "redteam-${id}: must be run from the xtcp2 repo root" >&2 + exit 2 + fi + export XTCP2_REPO_ROOT="$PWD" + export XTCP2_OCI_TAR="${redteamOci}" + export XTCP2_TCP_STRESS_TAR="${redteamTcpStressOci}" + export XTCP2_ATTACKER_TOOLS_TAR="${attackerTools}" + export VAGRANT_CWD="$XTCP2_REPO_ROOT/vagrant" + export VAGRANT_HOME="$VAGRANT_CWD/.gen/.vagrant.d" + mkdir -p "$VAGRANT_HOME" + exec bash "$XTCP2_REPO_ROOT/vagrant/scenarios/${baseNameOf file}" + ''; + }; + + scenarioApps = lib.listToAttrs ( + map (file: { + name = "redteam-${scenarioId file}"; + value = { + type = "app"; + program = "${mkScenarioRunner file}/bin/redteam-${scenarioId file}"; + }; + }) scenarioFiles + ); + + # The lint both `checks.redteam-lint` and `nix run .#redteam-lint` run — + # one derivation so the check and the app cannot drift. Plain repo scripts + # are NOT covered by writeShellApplication's build-time shellcheck, which + # is why they need this pass; the nix-built runners are checked at build. + redteamLint = pkgs.writeShellApplication { + name = "redteam-lint"; + runtimeInputs = [ + pkgs.findutils + pkgs.gnugrep + pkgs.shellcheck + ]; + text = '' + echo "shellcheck vagrant/" + find "${src}/vagrant" -name '*.sh' -print0 | + xargs -0 shellcheck -x + echo "bash -n vagrant/" + find "${src}/vagrant" -name '*.sh' -print0 | + xargs -0 -n1 bash -n + echo "redteam-lint: OK" + ''; + }; +in +{ + packages = { + redteam-oci = redteamOci; + redteam-oci-tcp-stress = redteamTcpStressOci; + redteam-attacker-tools = attackerTools; + }; + + apps = scenarioApps // { + redteam-destroy = { + type = "app"; + program = "${ + pkgs.writeShellApplication { + name = "redteam-destroy"; + runtimeInputs = [ + pkgs.coreutils + vagrant + ]; + text = '' + if [ ! -f flake.nix ]; then + echo "redteam-destroy: must be run from the xtcp2 repo root" >&2 + exit 2 + fi + export VAGRANT_CWD="$PWD/vagrant" + export VAGRANT_HOME="$VAGRANT_CWD/.gen/.vagrant.d" + ( cd "$VAGRANT_CWD" && vagrant destroy -f ) + ''; + } + }/bin/redteam-destroy"; + }; + redteam-status = { + type = "app"; + program = "${ + pkgs.writeShellApplication { + name = "redteam-status"; + runtimeInputs = [ + vagrant + ]; + text = '' + if [ ! -f flake.nix ]; then + echo "redteam-status: must be run from the xtcp2 repo root" >&2 + exit 2 + fi + export VAGRANT_CWD="$PWD/vagrant" + export VAGRANT_HOME="$VAGRANT_CWD/.gen/.vagrant.d" + ( cd "$VAGRANT_CWD" && vagrant status ) + ''; + } + }/bin/redteam-status"; + }; + redteam-lint = { + type = "app"; + program = "${redteamLint}/bin/redteam-lint"; + }; + }; + + checks = { + redteam-lint = pkgs.runCommand "redteam-lint-check" { } '' + ${redteamLint}/bin/redteam-lint + touch $out + ''; + }; +} From c0b975bbc50547c91dd5b5e84e80378258620ea9 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Fri, 13 Nov 2026 23:52:11 -0800 Subject: [PATCH 2/5] =?UTF-8?q?feat(redteam):=20checks.redteam-lint=20+=20?= =?UTF-8?q?Makefile/devshell/README=20wiring=20=E2=80=94=20C2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shellcheck -x + bash -n over vagrant/**.sh, hermetic, the only red-team member of nix flake check (VM scenarios need KVM+libvirtd+network, so they are apps). make redteam-lint / redteam-smoke / redteam-destroy; dev-shell banner and nix/README.md workflow rows. --- Makefile | 11 +++++++++++ nix/README.md | 1 + nix/devshell.nix | 7 +++++++ 3 files changed, 19 insertions(+) diff --git a/Makefile b/Makefile index bad4345ea..2fddad4e8 100644 --- a/Makefile +++ b/Makefile @@ -163,6 +163,17 @@ clear_docker_volumes: protos: nix run .#regen-protos +# Red-team harness (vagrant/, docs/redteam-plan.md). VM scenarios run on the +# harness host (l): KVM + libvirtd + network. The lint is hermetic CI. +redteam-lint: + nix build .#checks.x86_64-linux.redteam-lint -L + +redteam-smoke: + nix run .#redteam-rt-1-1 + +redteam-destroy: + nix run .#redteam-destroy + nuke_clickhouse: rm -rf ./build/containers/clickhouse/db/* docker volume rm xtcp_clickhouse_db diff --git a/nix/README.md b/nix/README.md index 64bd11629..37e17a677 100644 --- a/nix/README.md +++ b/nix/README.md @@ -21,6 +21,7 @@ The flake currently exports `x86_64-linux` only. See | Capture netlink dump fixtures in a guest | `nix run path:.#microvm-x86_64-netlink-dump-capture -- --out /tmp/xtcp2-dumps` | | Run all registered flake checks | `nix flake check path:. -L -j1` | | Measure monitor performance freshly | `nix run path:.#bench-linkmonitor -- --output /tmp/xtcp2-bench` | +| Run a red-team scenario on the harness host | `nix run path:.#redteam-rt-1-1` (KVM + libvirtd; see [docs/redteam-harness.md](../docs/redteam-harness.md)) | ### Contents diff --git a/nix/devshell.nix b/nix/devshell.nix index a1ee1b03a..409a3e57f 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -102,6 +102,13 @@ let nix flake check Tier 0+1 lint + all custom audits nixfmt --check **/*.nix Verify nix formatting + Red-team harness (vagrant/, docs/redteam-plan.md): + nix run .#redteam-rt-1-1 Boot the Ubuntu+Docker victim VM and + attack it (harness host only: KVM, + libvirtd, network) + nix run .#redteam-destroy Tear the VMs down + make redteam-lint shellcheck the harness tree + EOF ''; }; From fc7414cfb823d5cb1639aa7325a5feec9351ad8b Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Fri, 13 Nov 2026 23:52:11 -0800 Subject: [PATCH 3/5] =?UTF-8?q?feat(redteam):=20vagrant/=20harness=20?= =?UTF-8?q?=E2=80=94=20Vagrantfile,=20provisioners,=20lib=20helpers=20?= =?UTF-8?q?=E2=80=94=20C3-C5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ubuntu 24.04 (cloud-image/ubuntu-24.04 at 20260926.0.0) victim+attacker VMs on the xtcp2-redteam-mgmt network. provision/victim.sh builds the prod-host shape from the XTCP2_* deployment matrix (catcher systemd socat sink, xtcp2 daemon container in the TODO §29 shape — /var/lib/xtcp2 bind, /run/netns+docker netns ro,rslave, cgroupns=host — RT-11 work population from oci-xtcp2-tcp-stress, co-tenant attacker container at the tier). lib/: TAP assert helpers, matrix validation, evidence run-ids, ssh/scp over vagrant ssh-config (the box ships no rsync), and the victim-still-reporting invariant that consumes the catcher rather than a daemon gauge. --- vagrant/.gitignore | 5 + vagrant/README.md | 74 ++++++++ vagrant/Vagrantfile | 85 +++++++++ vagrant/lib/assert.sh | 59 +++++++ vagrant/lib/evidence.sh | 22 +++ vagrant/lib/invariant.sh | 34 ++++ vagrant/lib/matrix.sh | 71 ++++++++ vagrant/lib/ssh.sh | 53 ++++++ vagrant/provision/attacker.sh | 25 +++ vagrant/provision/common.sh | 35 ++++ vagrant/provision/victim.sh | 204 ++++++++++++++++++++++ vagrant/redteam/findings.md | 20 +++ vagrant/scenarios/rt-1-1-unauth-scrape.sh | 88 ++++++++++ 13 files changed, 775 insertions(+) create mode 100644 vagrant/.gitignore create mode 100644 vagrant/README.md create mode 100644 vagrant/Vagrantfile create mode 100644 vagrant/lib/assert.sh create mode 100644 vagrant/lib/evidence.sh create mode 100644 vagrant/lib/invariant.sh create mode 100644 vagrant/lib/matrix.sh create mode 100644 vagrant/lib/ssh.sh create mode 100644 vagrant/provision/attacker.sh create mode 100644 vagrant/provision/common.sh create mode 100644 vagrant/provision/victim.sh create mode 100644 vagrant/redteam/findings.md create mode 100644 vagrant/scenarios/rt-1-1-unauth-scrape.sh diff --git a/vagrant/.gitignore b/vagrant/.gitignore new file mode 100644 index 000000000..720805e19 --- /dev/null +++ b/vagrant/.gitignore @@ -0,0 +1,5 @@ +# VM state, uploaded images, generated ssh configs (nix/redteam.nix pins +# VAGRANT_HOME to vagrant/.gen/.vagrant.d so nothing leaks into ~/.vagrant.d). +.gen/ +# Scenario evidence (findings.md quotes the relevant bytes instead). +redteam/evidence/ diff --git a/vagrant/README.md b/vagrant/README.md new file mode 100644 index 000000000..f1314792f --- /dev/null +++ b/vagrant/README.md @@ -0,0 +1,74 @@ +# Red-team harness (Vagrant/libvirt) + +The Ubuntu 24.04 + Docker adversary-simulation topology from +[docs/redteam-plan.md](../docs/redteam-plan.md). Every scenario is one +`nix run` from the repo root on `l` (the libvirt harness host): + +```sh +nix run .#redteam-rt-1-1 # default row (host, auth off) +XTCP2_MODE=bridge XTCP2_AUTH=raw XTCP2_EXPECT=BLOCKED \ + nix run .#redteam-rt-1-1 # matrix flip (Phase 0 DoD) +nix run .#redteam-destroy # tear both VMs down +nix build .#checks.x86_64-linux.redteam-lint -L # the only CI member +``` + +WIP scenarios are only discoverable when the flake source includes them — +`nix run path:.#redteam-…` during development (same `path:.` rule as +focused-quality; see [../nix/README.md](../nix/README.md)). + +## Topology + +Two Ubuntu 24.04 guests on the `xtcp2-redteam-mgmt` libvirt network (the +harness never touches libvirt's default network): + +- **victim** (6 GB, 4 vCPU) — the "prod host": dockerd + the xtcp2 daemon + container in the deployment-matrix row, the RT-11 work population + (`rt-work-1/2`, tcp_server/tcp_client containers), the catcher (a + systemd socat unit appending the daemon's jsonl to + `/var/lib/xtcp2-catcher/records.jsonl` — the "victim still reporting" + evidence, deliberately host-side so a blinded daemon cannot forge it), and + the co-tenant attacker container (`rt-attacker`). +- **attacker** (2 GB, 2 vCPU) — the host-side attacker vantage: static repo + client binaries (`/opt/xtcp2-redteam/bin`) + slowhttptest/h2load. + +The deployment matrix (`XTCP2_MODE`, `XTCP2_AUTH`, `XTCP2_CAPS`, +`XTCP2_ATTACKER`, `XTCP2_EXPECT`) is validated host-side +([lib/matrix.sh](lib/matrix.sh)), re-read by the Vagrantfile, and +re-validated in [provision/victim.sh](provision/victim.sh) — one `vagrant +provision` re-applies a row change. + +## Box pin + +`cloud-image/ubuntu-24.04` at `20260926.0.0` — the official Ubuntu +cloud-image team's libvirt box. Note: the Vagrant Cloud catalog has **no +`ubuntu/noble64`** (the name the plan doc originally guessed); this box is +the official 24.04 offering. Vagrant Cloud publishes no checksum for it +(`checksum_type: none`), so the pin is the version number; re-pin when +moving it forward and record the date here: + +- `20260926.0.0` — pinned 2026-10-08 (current at pin time) + +The box ships no rsync, so the Vagrantfile disables synced folders and the +scenario apps deliver files (image tarballs, attacker tools) via scp over +`vagrant ssh-config` ([lib/ssh.sh](lib/ssh.sh)) before `vagrant provision`. + +## Prerequisites (all on `l`) + +- KVM + `qemu:///system` libvirtd, user in the `libvirt` group +- nothing else — `nix run .#redteam-*` provides vagrant (the pinned + nixpkgs bundles the vagrant-libvirt plugin on Linux), the tarballs, and + the runtime; `nix develop` gets you bare `vagrant` the same way + +## Cold boot, warm boot, teardown + +- Cold (box download ~1 GB, then provision): ~15 min. +- Warm (`vagrant up --no-provision` + re-provision): ~3 min. +- The scenarios leave the VMs up for fast iteration; teardown: + `nix run .#redteam-destroy` (leaves `vagrant/.gen/` — box cache — intact; + remove it to force a cold boot). + +## Memory budget + +Phase 0 fits `l` easily (8 GB across both VMs). Phase 4's +connection/FD-knee scenarios raise the victim to 10–12 GB — a TODO before +those land, recorded in docs/redteam-implementation.md. diff --git a/vagrant/Vagrantfile b/vagrant/Vagrantfile new file mode 100644 index 000000000..bed9e73aa --- /dev/null +++ b/vagrant/Vagrantfile @@ -0,0 +1,85 @@ +# vagrant/Vagrantfile +# +# Red-team harness topology (docs/redteam-plan.md, docs/redteam-implementation.md, +# docs/redteam-harness.md). Two Ubuntu 24.04 guests on a private libvirt network: +# +# victim the "prod host": dockerd + the xtcp2 daemon container (deployment +# matrix from XTCP2_* env), the RT-11 work population, the catcher, +# and the co-tenant attacker container +# attacker the host-side attacker: static repo client binaries + attack tooling +# +# The deployment matrix is read from the environment so one Vagrantfile serves +# every scenario row; the scenario apps (nix/redteam.nix) set/validate it: +# +# XTCP2_MODE host | bridge daemon container network shape +# XTCP2_AUTH off | raw | hmac listener credential shape +# XTCP2_CAPS priv | min daemon container capability shape +# XTCP2_ATTACKER plain | read-cred | privileged | admin +# +# Run everything through `nix run .#redteam-*` from the repo root; that pins +# VAGRANT_CWD/VAGRANT_HOME to vagrant/.gen so no state leaks into ~/.vagrant.d. + +# Box pin: the official Ubuntu cloud-image team's 24.04 box, which ships a +# libvirt provider (the Vagrant Cloud catalog has no "ubuntu/noble64"; see +# vagrant/README.md for the pin record and how to move it forward). +BOX = "cloud-image/ubuntu-24.04" +BOX_VERSION = "20260926.0.0" + +MODE = ENV.fetch("XTCP2_MODE", "host") +AUTH = ENV.fetch("XTCP2_AUTH", "off") +CAPS = ENV.fetch("XTCP2_CAPS", "priv") +ATTACKER = ENV.fetch("XTCP2_ATTACKER", "plain") + +Vagrant.configure("2") do |config| + config.vm.box = BOX + config.vm.box_version = BOX_VERSION + + # The harness ships its own files via scp over vagrant's own ssh config + # (vagrant/lib/ssh.sh). The default synced folder would need rsync in the + # guest, which the minimal cloud image does not carry — the box's own docs + # disable it for the same reason. + config.vm.synced_folder ".", "/vagrant", disabled: true + + config.vm.provider :libvirt do |lv| + lv.driver = "kvm" + lv.uri = "qemu:///system" + lv.cpu_mode = "host-passthrough" + end + + # Private mgmt network. Static IPs are required: vagrant-libvirt 0.12.2 + # crashes creating a DHCP-only named network (create_networks.rb to_range on + # nil). The scenario/DoD assertion is `virsh net-list` naming exactly this + # network beyond the pre-existing libvirt ones. + # attacker gets 192.168.142.11; 192.168.142.0/24 is the network subnet. + + config.vm.define "victim" do |victim| + victim.vm.hostname = "rt-victim" + victim.vm.network :private_network, + :ip => "192.168.142.10", + :libvirt__network_name => "xtcp2-redteam-mgmt" + + victim.vm.provider :libvirt do |lv| + lv.memory = 6144 + lv.cpus = 4 + end + + victim.vm.provision "shell", path: "provision/common.sh" + victim.vm.provision "shell", path: "provision/victim.sh", + args: [MODE, AUTH, CAPS, ATTACKER] + end + + config.vm.define "attacker" do |attacker| + attacker.vm.hostname = "rt-attacker" + attacker.vm.network :private_network, + :ip => "192.168.142.11", + :libvirt__network_name => "xtcp2-redteam-mgmt" + + attacker.vm.provider :libvirt do |lv| + lv.memory = 2048 + lv.cpus = 2 + end + + attacker.vm.provision "shell", path: "provision/common.sh" + attacker.vm.provision "shell", path: "provision/attacker.sh" + end +end diff --git a/vagrant/lib/assert.sh b/vagrant/lib/assert.sh new file mode 100644 index 000000000..71f86027a --- /dev/null +++ b/vagrant/lib/assert.sh @@ -0,0 +1,59 @@ +# vagrant/lib/assert.sh — TAP output + the scenario verdict contract +# (docs/redteam-implementation.md, "Conventions every phase follows"). +# +# Every scenario sources all four lib/ helpers (assert.sh included last is +# fine; they have no cross-deps beyond PATH), emits one TAP line per +# assertion, and exits 0 iff the observed outcome equals EXPECT and no +# assertion failed. The scenario declares EXPECT at the top; the runner env +# can override it (XTCP2_EXPECT) — the matrix-flip DoD runs exactly that: +# XTCP2_MODE=bridge XTCP2_AUTH=raw XTCP2_EXPECT=BLOCKED nix run .#redteam-rt-1-1 + +# shellcheck shell=bash + +RT_TEST_NUM=0 +RT_FAILED=0 + +ok() { + RT_TEST_NUM=$((RT_TEST_NUM + 1)) + echo "ok $RT_TEST_NUM - $*" +} + +not_ok() { + RT_TEST_NUM=$((RT_TEST_NUM + 1)) + echo "not ok $RT_TEST_NUM - $*" + RT_FAILED=$((RT_FAILED + 1)) +} + +# wait_for : run cmd until it exits 0. +# ok on success; a single not_ok on timeout. +wait_for() { + local timeout_s="$1" desc="$2" + shift 2 + local deadline=$((SECONDS + timeout_s)) + while true; do + if "$@" >/dev/null 2>&1; then + ok "$desc" + return 0 + fi + if [ "$SECONDS" -ge "$deadline" ]; then + not_ok "$desc (waited ${timeout_s}s)" + return 1 + fi + sleep 2 + done +} + +# finish : the summary + exit code. +# Blocks the scenario until actual == EXPECT (docs/redteam-implementation.md +# contract) and no assertion failed. +finish() { + local id="$1" actual="$2" + echo "1..$RT_TEST_NUM" + echo "RESULT $id $actual severity= evidence=$RT_EVIDENCE" + if [ "$RT_FAILED" -eq 0 ] && [ "$actual" = "$XTCP2_EXPECT" ]; then + echo "RESULT $id $actual (expected $XTCP2_EXPECT): PASS" + exit 0 + fi + echo "RESULT $id $actual (expected $XTCP2_EXPECT, $RT_FAILED failed assertion(s)): FAIL" + exit 1 +} diff --git a/vagrant/lib/evidence.sh b/vagrant/lib/evidence.sh new file mode 100644 index 000000000..40dbfb57c --- /dev/null +++ b/vagrant/lib/evidence.sh @@ -0,0 +1,22 @@ +# vagrant/lib/evidence.sh — run-id evidence directories under +# vagrant/redteam/evidence/ (gitignored). One dir per scenario run; findings.md +# quotes the relevant bytes, never the whole dump. +# shellcheck shell=bash + +# evidence_init: sets RT_EVIDENCE and prints it. +evidence_init() { + local sha + sha="$(git -C "$XTCP2_REPO_ROOT" rev-parse --short HEAD 2>/dev/null || echo dirty)" + RT_EVIDENCE="$XTCP2_REPO_ROOT/vagrant/redteam/evidence/$(date -u +%Y%m%dT%H%M%S)-$sha-$$" + mkdir -p "$RT_EVIDENCE" + echo "$RT_EVIDENCE" +} + +# capture : run cmd, capture stdout+stderr to +# $RT_EVIDENCE/.log, echo stdout. Commands must not need a tty. +capture() { + local name="$1" + shift + "$@" >"$RT_EVIDENCE/$name.log" 2>&1 + cat "$RT_EVIDENCE/$name.log" +} diff --git a/vagrant/lib/invariant.sh b/vagrant/lib/invariant.sh new file mode 100644 index 000000000..bb7d17102 --- /dev/null +++ b/vagrant/lib/invariant.sh @@ -0,0 +1,34 @@ +# vagrant/lib/invariant.sh — the RT-11 "victim still reporting" invariant. +# +# The pass criterion of every RT-11 attack (docs/redteam-plan.md RT-11): the +# work population's records keep arriving at the CATCHER within the poll +# cadence — consumed host-side, not from a daemon gauge, so a blinded or +# attacker-controlled daemon cannot forge it. The catcher file is root-owned; +# the scenario reads it via sudo. +# shellcheck shell=bash + +CATCHER_FILE=/var/lib/xtcp2-catcher/records.jsonl +CATCHER_WAIT_SECS=6 # 3× the 2s poll cadence provision/victim.sh configures + +# catcher_lines: number of jsonl records the daemon has delivered. +catcher_lines() { + vm_exec_root victim "wc -l < $CATCHER_FILE 2>/dev/null || echo 0" +} + +# victim_still_reporting: records arrived over the last CATCHER_WAIT_SECS. +victim_still_reporting() { + local before after + before="$(catcher_lines)" + sleep "$CATCHER_WAIT_SECS" + after="$(catcher_lines)" + [ "$after" -gt "$before" ] +} + +# victim_still_reporting_tap: the invariant as a TAP assertion. +victim_still_reporting_tap() { + if victim_still_reporting; then + ok "victim still reporting (catcher grew over ${CATCHER_WAIT_SECS}s)" + else + not_ok "victim still reporting (catcher did not grow over ${CATCHER_WAIT_SECS}s)" + fi +} diff --git a/vagrant/lib/matrix.sh b/vagrant/lib/matrix.sh new file mode 100644 index 000000000..fa6d494c1 --- /dev/null +++ b/vagrant/lib/matrix.sh @@ -0,0 +1,71 @@ +# vagrant/lib/matrix.sh — the deployment matrix: defaults, validation, and +# the shared repo-root/VAGRANT_* plumbing, so scenarios work identically via +# the flake apps (which export these) and via plain bash from vagrant/. +# shellcheck shell=bash + +# Repo root = two levels up from this file (vagrant/lib -> repo). +XTCP2_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +export XTCP2_REPO_ROOT + +# The nix apps set VAGRANT_CWD/VAGRANT_HOME; bare bash gets the same values so +# `vagrant` behaves identically either way. No state in ~/.vagrant.d. +export VAGRANT_CWD="$XTCP2_REPO_ROOT/vagrant" +export VAGRANT_HOME="$VAGRANT_CWD/.gen/.vagrant.d" +mkdir -p "$VAGRANT_HOME" + +xtcp2_die() { + echo "rt: $*" >&2 + exit 2 +} + +# xtcp2_matrix_defaults: validate/normalize the XTCP2_* env the scenario apps +# export. Values mirror the Vagrantfile (which re-validates) and +# provision/victim.sh's own defense-in-depth check. +xtcp2_matrix_defaults() { + : "${XTCP2_MODE:=host}" + : "${XTCP2_AUTH:=off}" + : "${XTCP2_CAPS:=priv}" + : "${XTCP2_ATTACKER:=plain}" + : "${XTCP2_EXPECT:=CONFIRMED}" + + case "$XTCP2_MODE" in + host | bridge) ;; + *) xtcp2_die "XTCP2_MODE='$XTCP2_MODE' (want host|bridge)" ;; + esac + case "$XTCP2_AUTH" in + off | raw | hmac) ;; + *) xtcp2_die "XTCP2_AUTH='$XTCP2_AUTH' (want off|raw|hmac)" ;; + esac + case "$XTCP2_CAPS" in + priv | min) ;; + *) xtcp2_die "XTCP2_CAPS='$XTCP2_CAPS' (want priv|min)" ;; + esac + case "$XTCP2_ATTACKER" in + plain | read-cred | privileged | admin) ;; + *) xtcp2_die "XTCP2_ATTACKER='$XTCP2_ATTACKER' (want plain|read-cred|privileged|admin)" ;; + esac + case "$XTCP2_EXPECT" in + BLOCKED | MITIGATED | CONFIRMED | NA) ;; + *) xtcp2_die "XTCP2_EXPECT='$XTCP2_EXPECT' (want BLOCKED|MITIGATED|CONFIRMED|NA)" ;; + esac + + echo "rt: matrix MODE=$XTCP2_MODE AUTH=$XTCP2_AUTH CAPS=$XTCP2_CAPS ATTACKER=$XTCP2_ATTACKER EXPECT=$XTCP2_EXPECT" +} + +# The co-tenant vantage: the docker0 gateway in the victim VM's host netns. +# Host mode: the daemon binds :9088 there. Bridge mode: -p publishes it there. +# Both shapes answer on the same address from inside a bridge-networked +# container — that symmetry is part of what rt-9-1 measures. +xtcp2_cotenant_prom_url() { + echo 'http://172.17.0.1:9088/metrics' +} + +xtcp2_preflight() { + command -v vagrant >/dev/null 2>&1 \ + || xtcp2_die "vagrant not on PATH (nix run .#redteam-* provides it)" + command -v ssh >/dev/null 2>&1 || xtcp2_die "ssh not on PATH" + virsh -c qemu:///system version >/dev/null 2>&1 \ + || xtcp2_die "qemu:///system unreachable (libvirtd down, or not in the libvirt group)" + [ -n "${XTCP2_OCI_TAR:-}" ] && [ -n "${XTCP2_TCP_STRESS_TAR:-}" ] \ + || xtcp2_die "XTCP2_OCI_TAR/XTCP2_TCP_STRESS_TAR unset — run via nix run .#redteam-* (the app exports them)" +} diff --git a/vagrant/lib/ssh.sh b/vagrant/lib/ssh.sh new file mode 100644 index 000000000..b052bd1d8 --- /dev/null +++ b/vagrant/lib/ssh.sh @@ -0,0 +1,53 @@ +# vagrant/lib/ssh.sh — host-side VM access without provider magic. +# +# The box image ships no rsync (no synced folder — see the Vagrantfile), and +# `vagrant upload` support varies by provider version; ssh/scp over `vagrant +# ssh-config`'s generated config is the one path that works everywhere. The +# config is regenerated per call — VMs can move IPs across reboots. +# shellcheck shell=bash + +vm_ssh_config() { + local vm="$1" + local cfg="$XTCP2_REPO_ROOT/vagrant/.gen/ssh-config-$vm" + (cd "$VAGRANT_CWD" && vagrant ssh-config "$vm") >"$cfg" + echo "$cfg" +} + +# vm_exec : run cmd on the VM as the vagrant user. +vm_exec() { + local vm="$1" + shift + ssh -F "$(vm_ssh_config "$vm")" "$vm" "$@" +} + +# vm_exec_root : same, via sudo (the cloud-image box's vagrant +# user has passwordless sudo). +vm_exec_root() { + local vm="$1" + shift + ssh -F "$(vm_ssh_config "$vm")" "$vm" "sudo bash -c $(printf '%q ' "$@")" +} + +# vm_push : scp a file into the VM. +vm_push() { + local vm="$1" local_path="$2" remote_path="$3" + scp -q -F "$(vm_ssh_config "$vm")" "$local_path" "$vm:""$remote_path" +} + +# vm_up [--no-provision] : idempotent boot. First boot lands on the +# unprovisioned image on purpose — the scenario scps the tarballs to +# /tmp/xtcp2-redteam BEFORE `vagrant provision` consumes them. +vm_up() { + local no_provision="" + if [ "${1:-}" = "--no-provision" ]; then + no_provision="--no-provision" + shift + fi + # shellcheck disable=SC2086 + # (the empty-flag case must expand to nothing) + (cd "$VAGRANT_CWD" && vagrant up $no_provision "$@") +} + +vm_provision() { + (cd "$VAGRANT_CWD" && vagrant provision "$@") +} diff --git a/vagrant/provision/attacker.sh b/vagrant/provision/attacker.sh new file mode 100644 index 000000000..544402f1f --- /dev/null +++ b/vagrant/provision/attacker.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# vagrant/provision/attacker.sh — runs as root inside the attacker VM, after +# common.sh. The host-side attacker vantage: the repo's static client binaries +# (scp'd by the scenario app as xtcp2-redteam-attacker-tools.tar — built by +# nix/redteam.nix with a static-linkage assertion) plus the load/DoS tooling +# Ubuntu packages. Missing tar is a warning, not an error: rt-1-1 attacks from +# the co-tenant container and never touches this VM. +set -euo pipefail + +export DEBIAN_FRONTEND=noninteractive + +# Application-layer DoS simulator (universe) + the HTTP/2 storm driver +# (nghttp2-client ships h2load). slowhttptest is attack-only: it stays off the +# victim so the victim's base-OS remains the monitored prod shape. +apt-get install -y -qq slowhttptest + +mkdir -p /opt/xtcp2-redteam +if [ -f /tmp/xtcp2-redteam/xtcp2-redteam-attacker-tools.tar ]; then + tar -xf /tmp/xtcp2-redteam/xtcp2-redteam-attacker-tools.tar -C /opt/xtcp2-redteam + ls -l /opt/xtcp2-redteam/bin +else + echo "attacker.sh: /tmp/xtcp2-redteam/xtcp2-redteam-attacker-tools.tar missing — the scenario app scps it before provisioning; run via nix run .#redteam-*" >&2 +fi + +echo "attacker: done (slowhttptest $(slowhttptest --help 2>&1 | head -1 || true))" diff --git a/vagrant/provision/common.sh b/vagrant/provision/common.sh new file mode 100644 index 000000000..abb78d2f0 --- /dev/null +++ b/vagrant/provision/common.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# vagrant/provision/common.sh — first provisioner for BOTH guests (runs as +# root inside the Ubuntu 24.04 VM). Idempotent: `vagrant provision` re-runs it. +# +# Docker CE from Docker's apt repository (the prod shape xtcp2 deploys in — +# see TODO-SOON §29 and build/containers/docker-compose.yml), plus the +# tooling every scenario wants on both vantages. Attack tooling that is only +# the attacker's (slowhttptest) lands in provision/attacker.sh. +set -euo pipefail + +export DEBIAN_FRONTEND=noninteractive + +if ! command -v docker >/dev/null 2>&1; then + apt-get update -qq + apt-get install -y -qq ca-certificates curl gnupg + install -m 0755 -d /etc/apt/keyrings + curl -fsSL https://download.docker.com/linux/ubuntu/gpg \ + | gpg --dearmor -o /etc/apt/keyrings/docker.gpg + chmod a+r /etc/apt/keyrings/docker.gpg + echo \ + "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg]" \ + "https://download.docker.com/linux/ubuntu noble stable" \ + >/etc/apt/sources.list.d/docker.list + apt-get update -qq + apt-get install -y -qq docker-ce docker-ce-cli containerd.io +fi + +apt-get install -y -qq jq socat tcpdump strace iperf3 nghttp2-client chrony +systemctl enable --now chrony + +# The scenario scripts scp harness files here before `vagrant provision` +# runs (vagrant/lib/ssh.sh); victim.sh and attacker.sh consume them. +mkdir -p /tmp/xtcp2-redteam + +echo "common: done (docker $(docker --version | cut -d, -f1))" diff --git a/vagrant/provision/victim.sh b/vagrant/provision/victim.sh new file mode 100644 index 000000000..e7493249f --- /dev/null +++ b/vagrant/provision/victim.sh @@ -0,0 +1,204 @@ +#!/usr/bin/env bash +# vagrant/provision/victim.sh — runs as root inside the victim VM, after +# common.sh. Materializes the "prod host" the scenarios attack: +# +# 1. the catcher (TCP jsonl sink the daemon's -dest tcp: writes into — the +# RT-11 "records still arriving" assertion consumes it host-side, NOT a +# daemon gauge, so an attacker who blinds the daemon cannot also forge it) +# 2. the xtcp2 daemon container in the deployment-matrix shape +# 3. the RT-11 work population (tcp_server/tcp_client containers — the +# non-attacker tenants whose records must keep arriving) +# 4. the co-tenant attacker container at the requested tier +# +# Matrix args come from the Vagrantfile (XTCP2_* env; the scenario apps in +# nix/redteam.nix set and validate them). Idempotent: containers are removed +# and re-created on every provision. +# +# The scenario app scp's the image tarballs to /tmp/xtcp2-redteam/ BEFORE +# `vagrant provision` runs (vagrant/lib/ssh.sh); there is no synced folder +# (the box image ships no rsync), so that scp is the only delivery path. +set -euo pipefail + +MODE="$1" +AUTH="$2" +CAPS="$3" +ATTACKER_TIER="$4" + +die() { + echo "victim.sh: $*" >&2 + exit 1 +} + +case "$MODE" in + host | bridge) ;; + *) die "invalid XTCP2_MODE '$MODE' (want host|bridge)" ;; +esac +case "$AUTH" in + off | raw | hmac) ;; + *) die "invalid XTCP2_AUTH '$AUTH' (want off|raw|hmac)" ;; +esac +case "$CAPS" in + priv | min) ;; + *) die "invalid XTCP2_CAPS '$CAPS' (want priv|min)" ;; +esac +case "$ATTACKER_TIER" in + plain | read-cred | privileged | admin) ;; + *) die "invalid XTCP2_ATTACKER '$ATTACKER_TIER'" ;; +esac + +HARNESS_DIR=/tmp/xtcp2-redteam +DAEMON_IMAGE=xtcp2:latest +STRESS_IMAGE=xtcp2-tcp-stress:latest + +[ -f "$HARNESS_DIR/xtcp2-oci.tar.gz" ] \ + || die "$HARNESS_DIR/xtcp2-oci.tar.gz missing — run via nix run .#redteam-* (it scp's the tarballs before provisioning)" +docker load <"$HARNESS_DIR/xtcp2-oci.tar.gz" +[ -f "$HARNESS_DIR/xtcp2-tcp-stress.tar.gz" ] \ + || die "$HARNESS_DIR/xtcp2-tcp-stress.tar.gz missing — run via nix run .#redteam-*" +docker load <"$HARNESS_DIR/xtcp2-tcp-stress.tar.gz" + +# --- catcher ---------------------------------------------------------------- +# socat appends every connection's bytes to records.jsonl. The daemon connects +# from its container netns; host mode dials 127.0.0.1, bridge mode the docker0 +# gateway 172.17.0.1 — socat binds 0.0.0.0, so both reach it. +mkdir -p /var/lib/xtcp2-catcher +cat >/etc/systemd/system/xtcp2-catcher.service <<'EOF' +[Unit] +Description=xtcp2 redteam catcher (TCP jsonl sink) +After=network.target + +[Service] +ExecStart=/usr/bin/socat TCP-LISTEN:9999,reuseaddr,fork OPEN:/var/lib/xtcp2-catcher/records.jsonl,append +Restart=always + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl enable --now xtcp2-catcher +systemctl restart xtcp2-catcher + +# --- secrets (auth rows) ---------------------------------------------------- +mkdir -p /opt/xtcp2-redteam/secrets +if [ "$AUTH" != off ] && [ ! -f /opt/xtcp2-redteam/secrets/read ]; then + # Generated once per VM, 0400 root-only (the daemon refuses group/other + # readable credential files with exit 64). Scenarios read them host-side via + # `vagrant ssh victim -c 'sudo cat …'` when a vantage needs a real token. + umask 077 + openssl rand -hex 32 >/opt/xtcp2-redteam/secrets/read + openssl rand -hex 32 >/opt/xtcp2-redteam/secrets/admin + chmod 0400 /opt/xtcp2-redteam/secrets/read /opt/xtcp2-redteam/secrets/admin +fi + +# --- daemon container ------------------------------------------------------- +NET_ARGS=() +case "$MODE" in + # host: the TODO-SOON §29 prod shape (build/containers/docker-compose.yml). + host) + NET_ARGS=(--network host --pid host --ipc host) + DEST_ADDR=127.0.0.1 + ;; + # bridge: ports published on the VM host; the daemon dials the catcher via + # the docker0 gateway. + bridge) + NET_ARGS=(-p 9088:9088 -p 8889:8889) + DEST_ADDR=172.17.0.1 + ;; +esac + +CAP_ARGS=() +case "$CAPS" in + # priv: docker defaults — everything the daemon might need (rt-5-3's blast + # radius tier). min: exactly the startup capability check's required set + # (pkg/xtcp/init_capabilities.go), the rt-5-4 recipe's Phase 0 approximation. + min) + CAP_ARGS=(--cap-drop=ALL --cap-add=NET_ADMIN --cap-add=SYS_ADMIN) + ;; +esac + +AUTH_ENVS=() +SECRET_MOUNTS=() +case "$AUTH" in + off) ;; + raw) + AUTH_ENVS=( + -e LISTENER_AUTH_MODE=raw + -e LISTENER_RAW_TOKEN_FILE=/run/secrets/read + -e LISTENER_ADMIN_AUTH_MODE=raw + -e LISTENER_ADMIN_RAW_TOKEN_FILE=/run/secrets/admin + ) + SECRET_MOUNTS=(-v /opt/xtcp2-redteam/secrets:/run/secrets:ro) + ;; + hmac) + AUTH_ENVS=( + -e LISTENER_AUTH_MODE=hmac-utc-minute + -e LISTENER_HMAC_SHARED_KEY_FILE=/run/secrets/read + -e LISTENER_ADMIN_AUTH_MODE=hmac-utc-minute + -e LISTENER_ADMIN_HMAC_SHARED_KEY_FILE=/run/secrets/admin + ) + SECRET_MOUNTS=(-v /opt/xtcp2-redteam/secrets:/run/secrets:ro) + ;; +esac + +docker rm -f rt-xtcp2 >/dev/null 2>&1 || true +docker run -d --name rt-xtcp2 \ + "${NET_ARGS[@]}" \ + "${CAP_ARGS[@]}" \ + "${AUTH_ENVS[@]}" \ + "${SECRET_MOUNTS[@]}" \ + -v /var/lib/xtcp2:/var/lib/xtcp2 \ + -v /run/netns:/run/netns:ro,rslave \ + -v /run/docker/netns:/run/docker/netns:ro,rslave \ + --cgroupns=host \ + -v /sys/fs/cgroup:/sys/fs/cgroup:ro \ + "$DAEMON_IMAGE" \ + -dest "tcp:$DEST_ADDR:9999" \ + -marshal jsonl \ + -frequency 2s \ + -timeout 1s \ + -hostname rt-victim + +# --- RT-11 work population ------------------------------------------------- +# Two non-attacker tenant containers; their records must keep arriving at the +# catcher within the poll cadence — the pass criterion of every RT-11 attack. +for i in 1 2; do + docker rm -f "rt-work-$i" >/dev/null 2>&1 || true + docker run -d --name "rt-work-$i" --network bridge \ + -e TCP_MODE=both -e TCP_COUNT=25 -e TCP_SLEEP=5s \ + "$STRESS_IMAGE" +done + +# --- co-tenant attacker container ------------------------------------------ +# plain: an ordinary container on the default bridge — the RT-11 tier 1 +# vantage: reach the host network stack, nothing else. Higher tiers add +# stolen credentials, privileges, the docker socket (Phase 2/5 scenarios). +docker rm -f rt-attacker >/dev/null 2>&1 || true +case "$ATTACKER_TIER" in + plain) + docker run -d --name rt-attacker --network bridge \ + ubuntu:24.04 sleep infinity + ;; + read-cred) + docker run -d --name rt-attacker --network bridge \ + -v /opt/xtcp2-redteam/secrets/read:/run/secrets/read:ro \ + ubuntu:24.04 sleep infinity + ;; + admin) + docker run -d --name rt-attacker --network bridge \ + -v /opt/xtcp2-redteam/secrets:/run/secrets:ro \ + ubuntu:24.04 sleep infinity + ;; + privileged) + docker run -d --name rt-attacker --network bridge \ + --privileged --pid host \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v /opt/xtcp2-redteam/secrets:/run/secrets:ro \ + ubuntu:24.04 sleep infinity + ;; +esac + +# Pre-warm the attack tool so the scenario's docker exec is deterministic. +docker exec rt-attacker bash -c 'apt-get update -qq && apt-get install -y -qq curl' + +docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}' +echo "victim: MODE=$MODE AUTH=$AUTH CAPS=$CAPS ATTACKER=$ATTACKER_TIER dest=tcp:$DEST_ADDR:9999" diff --git a/vagrant/redteam/findings.md b/vagrant/redteam/findings.md new file mode 100644 index 000000000..4120ff902 --- /dev/null +++ b/vagrant/redteam/findings.md @@ -0,0 +1,20 @@ +# Red-team findings — triage log + +One row per scenario run that produced a verdict; evidence lives under +`evidence//` (gitignored), and each row quotes the relevant bytes +rather than attaching dumps. Outcome taxonomy: **CONFIRMED** (the attack +worked as described), **MITIGATED** (attack degraded, defense held the +line), **BLOCKED** (defense rejected it outright), **NA** (could not +exercise). Scenario expectations live in the scenario scripts; a finding +that gets fixed flips its `EXPECT` in the same PR as the fix +(docs/redteam-implementation.md, conventions §2). + +| scenario | date | matrix row | outcome | severity | evidence | issue / follow-up | +|---|---|---|---|---|---|---| +| rt-1-1 | 2026-10-08 | host+off+priv | CONFIRMED | S4 (recon, documented default) | see run dir | expected: the daemon's default row serves /metrics unauthenticated to any container that can reach the docker0 gateway; docs/security.md recommends bearer auth + loopback/UDS in deployment. Scenario pins the exposure; ops recommendation tracked in docs/security.md. | + +## Notes + +- Severity scale: docs/redteam-plan.md §severity. +- Rows are appended, never edited, so the log doubles as the program's + execution record. diff --git a/vagrant/scenarios/rt-1-1-unauth-scrape.sh b/vagrant/scenarios/rt-1-1-unauth-scrape.sh new file mode 100644 index 000000000..3f3e5f7b4 --- /dev/null +++ b/vagrant/scenarios/rt-1-1-unauth-scrape.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-1-1-unauth-scrape.sh — RT-1, scenario 1: +# unauthenticated co-tenant scrape (docs/redteam-plan.md RT-1; the default- +# exposure family). Driver contract: docs/redteam-implementation.md. +# +# Question: with the daemon in its default deployment row (host network, auth +# off), can a plain container on the same docker host read TCP-observability +# metrics about the base OS and every other tenant? +# +# EXPECT=CONFIRMED today: auth off is the daemon default; docs/security.md's +# "Listener security" documents the exposure and recommends bearer auth + +# loopback/UDS listeners in deployment. This scenario pins that exposure as a +# finding so the default cannot regress silently; when the default changes, +# the expectation flip travels in the same PR as the fix. +# +# Matrix flip (Phase 0 DoD — proves the harness drives real behavior): +# XTCP2_MODE=bridge XTCP2_AUTH=raw XTCP2_EXPECT=BLOCKED \ +# nix run .#redteam-rt-1-1 +set -euo pipefail + +XTCP2_EXPECT="${XTCP2_EXPECT:-CONFIRMED}" + +# shellcheck source=/dev/null +source "$(dirname "${BASH_SOURCE[0]}")/../lib/matrix.sh" +# shellcheck source=/dev/null +source "$(dirname "${BASH_SOURCE[0]}")/../lib/evidence.sh" +# shellcheck source=/dev/null +source "$(dirname "${BASH_SOURCE[0]}")/../lib/ssh.sh" +# shellcheck source=/dev/null +source "$(dirname "${BASH_SOURCE[0]}")/../lib/invariant.sh" +# shellcheck source=/dev/null +source "$(dirname "${BASH_SOURCE[0]}")/../lib/assert.sh" + +xtcp2_matrix_defaults +xtcp2_preflight +evidence_init + +echo "rt-1-1: evidence in $RT_EVIDENCE" + +# Boot the victim VM unprovisioned, deliver the image tarballs the Vagrantfile +# cannot sync (the box ships no rsync), then provision the matrix row. +vm_up --no-provision victim +# The delivery dir exists only after common.sh; create it now so the scp that +# precedes the first `vagrant provision` has somewhere to land. +vm_exec victim 'mkdir -p /tmp/xtcp2-redteam' +vm_push victim "$XTCP2_OCI_TAR" /tmp/xtcp2-redteam/xtcp2-oci.tar.gz +vm_push victim "$XTCP2_TCP_STRESS_TAR" /tmp/xtcp2-redteam/xtcp2-tcp-stress.tar.gz +vm_provision victim + +# Baseline: the daemon is up and the catcher sees records before any attack. +PROM="http://127.0.0.1:9088/metrics" +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' $PROM | grep -q 200" +victim_still_reporting_tap + +# Attack: plain-tier co-tenant container, no credentials, curl the docker0 +# gateway — the one address every bridge-networked container can always reach +# (the prod-shape host network answers there; so does -p publishing). +COTENANT_PROM="$(xtcp2_cotenant_prom_url)" +code="$(vm_exec victim "docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' $COTENANT_PROM")" || code=000 +echo "rt-1-1: co-tenant scrape HTTP $code" +vm_exec victim "docker exec rt-attacker curl -s -m 5 $COTENANT_PROM" \ + >"$RT_EVIDENCE/cotenant-scrape.txt" || true + +case "$code" in + 200) + if grep -q 'xtcp_' "$RT_EVIDENCE/cotenant-scrape.txt"; then + ok "co-tenant read /metrics without credentials (200, xtcp_ series present)" + else + not_ok "co-tenant got 200 but no xtcp_ series in the body" + fi + ;; + 401 | 403) + ok "co-tenant scrape rejected (HTTP $code)" + ;; + *) + not_ok "co-tenant scrape returned HTTP $code" + ;; +esac +victim_still_reporting_tap + +# Verdict. +case "$code" in + 200) actual=CONFIRMED ;; + 401 | 403) actual=BLOCKED ;; + *) actual=NA ;; +esac +finish rt-1-1 "$actual" From 6457373a4e1c420833d84a789bd3bada4ff49193 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Fri, 13 Nov 2026 23:52:58 -0800 Subject: [PATCH 4/5] =?UTF-8?q?feat(redteam):=20harness=20build=20plan=20d?= =?UTF-8?q?oc=20+=20cross-links=20=E2=80=94=20C6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/redteam-harness.md: verified Phase 0 wiring plan — the inventory of what flake.nix/nix already provides (vagrant 2.4.9 bundles the libvirt plugin in the pinned nixpkgs; oci-xtcp2-tcp-stress is the RT-11 work population; -dest tcp: jsonl is the catcher format), design decisions D1–D10, the nix/redteam.nix + vagrant/ specs, the rt-1-1 walkthrough and the C1–C6 commit map. Box corrections for the earlier docs: the Vagrant Cloud catalog has no ubuntu/noble64 — the official box is cloud-image/ubuntu-24.04; nixpkgs grpcurl is dynamically linked, so the Phase 0 attacker tools ship the repo's static xtcp2client/xtcp2ctl only. --- docs/README.md | 1 + docs/redteam-harness.md | 306 +++++++++++++++++++++++++++++++++ docs/redteam-implementation.md | 5 +- docs/redteam-plan.md | 5 +- 4 files changed, 314 insertions(+), 3 deletions(-) create mode 100644 docs/redteam-harness.md diff --git a/docs/README.md b/docs/README.md index ed3d42557..2848eb246 100644 --- a/docs/README.md +++ b/docs/README.md @@ -98,6 +98,7 @@ See **[CONTRIBUTING.md](../CONTRIBUTING.md)** for the development environment, t - [Listener security hardening](design-listener-security-hardening.md) — historical design, including unimplemented proposals; use the [security guide](security.md) for current behavior and deployment recommendations. - [Red-team plan](redteam-plan.md) — adversary simulation for xtcp2 in a container on Ubuntu 24.04: attack-surface inventory, scenario catalog (recon, auth, admin abuse, DoS, host/netlink assurance, UDS, artifacts, parsers), and the Vagrant/libvirt harness that runs the scenarios from this repo. - [Red-team implementation](redteam-implementation.md) — execution companion to the red-team plan: harness architecture, per-phase tasks with definition of done, cross-cutting workstreams, effort estimates, risks, and the program-level exit criteria. +- [Red-team harness build plan](redteam-harness.md) — concrete Phase 0 wiring into flake.nix and nix/: what the existing infra already provides (verified), design decisions, the nix/redteam.nix and vagrant/ file specs, the rt-1-1 walkthrough, and the commit-by-commit build sequence. - [Fleet jitter & upload backoff](design-jitter-and-backoff.md) — thundering-herd avoidance: poll jitter, jittered S3 flush (size + time), and jittered proportional upload retry, for fleet-scale (5–10k machine) deployments. - [The link monitor in xtcp2](design-linkmonitor-in-xtcp2.md) — go-link-monitor's features inside xtcp2, on by default: the persisted expected up-link count in `/var/lib/xtcp2`, the detail paths on the Prometheus listener, the lifecycle under xtcp2's context, SIGUSR1/reload, and the degrade-not-exit failure mode; progress in its [status doc](status-linkmonitor-in-xtcp2.md). - [Summary metrics](design-summary-metrics.md) — proposed 15-series `/metrics` (a self-computed `xtcp2_healthy` gauge plus throughput, delivery, error and resource counters, destination-generic) with full detail moved to `/metrics-all`, plus follow-ups found reviewing the fleet dashboard. diff --git a/docs/redteam-harness.md b/docs/redteam-harness.md new file mode 100644 index 000000000..547c55b09 --- /dev/null +++ b/docs/redteam-harness.md @@ -0,0 +1,306 @@ +# Red-team harness build plan (flake.nix + nix/ wiring) + +Concrete implementation spec for the [Phase 0 harness](redteam-implementation.md#phase-0--harness-bootstrap) +described in the [red-team plan](redteam-plan.md): which files are created, +what each derivation contains, exactly where they wire into +[flake.nix](../flake.nix) → [nix/default.nix](../nix/default.nix), and in +what order to build it. Everything below was verified against the tree at +`e360b6f9` — package availability, flags, and existing conventions were +checked, not assumed. Task IDs (0.1–0.9) refer to the implementation plan's +Phase 0 table. + +## Contents + +- [What the existing infrastructure already provides](#what-the-existing-infrastructure-already-provides) +- [Design decisions](#design-decisions) +- [The wiring map](#the-wiring-map) +- [nix/redteam.nix specification](#nixredteamnix-specification) +- [vagrant/ tree specification](#vagrant-tree-specification) +- [The rt-1-1 walkthrough](#the-rt-1-1-walkthrough) +- [Build sequence](#build-sequence) +- [Open questions](#open-questions) + +## What the existing infrastructure already provides + +Verified inventory — nothing below needs to be invented: + +| Need | Provided by | Notes | +|---|---|---| +| Vagrant + libvirt provider | pinned nixpkgs `pkgs.vagrant` (2.4.9) | **bundles the vagrant-libvirt plugin on Linux** — `pkgs/by-name/va/vagrant/package.nix` defaults `withLibvirt ? stdenv.hostPlatform.isLinux` and generates the plugin's `plugins.d` JSON itself. This retires the implementation plan's "vagrant not packaged cleanly in nixpkgs devshell" risk. A built `vagrant-2.4.9` with the plugin already exists in this machine's store | +| libvirt on the harness host | `l` | `libvirtd` 12.8 active, `qemu:///system` reachable, user in the `libvirt` group — verified | +| Daemon OCI image | `containers.oci-xtcp2` ([nix/containers/oci-xtcp2.nix](../nix/containers/oci-xtcp2.nix)) | `streamLayeredImage` — the build output is a **script that streams the tar to stdout** (`./result \| docker load`, the same pattern the tcp-stress microVM uses) | +| RT-11 work population | `containers.oci-xtcp2-tcp-stress` | ships `tcp_server`+`tcp_client` with a `TCP_MODE={server,client,both}` env-dispatch entrypoint and `TCP_COUNT`/`TCP_SLEEP`/`TCP_PADS` knobs — exactly the victim-socket population the plan needs. **Reuses, not rebuilds** the implementation doc's task 0.6 "binaries from xtcp2-all" | +| Attacker clients | `binaries.xtcp2client`, `binaries.xtcp2ctl` | all repo Go binaries are `CGO_ENABLED=0` → static ELF, runs on stock Ubuntu unmodified | +| gRPC scraper | `versions.grpcurl` (nixpkgs) | ⚠️ `cmd/grpcurl` is **README-only, not buildable** (nix/binaries.nix:42) — the attacker tooling must use nixpkgs' grpcurl, not a repo build | +| Deployment target semantics | `xtcp2SocketSinkArgs` in [nix/microvms/mkVm.nix:2414](../nix/microvms/mkVm.nix) | `-dest tcp:localhost:13001 -marshal jsonl -frequency 2s -timeout 1s` — jsonl, one record per line, is the catcher format the scenario asserts on | +| docker-in-a-VM precedent | `tcpStressLoadScript` (mkVm.nix:1154) | `docker load` from a stream script, dockerd readiness loop — the same shape `provision/victim.sh` follows | +| Shellcheck discipline | `writeShellApplication` + `checks` | every runner derivation is shellcheck'd at build; plain repo scripts get `checks.redteam-lint` | +| App/runner conventions | `lintFixOne`, `focusedQuality`, `oci-size-report` (nix/default.nix) | runners require repo root (`flake.nix` present), so WIP scenarios run from the working tree; `path:.` vs `.` source-view semantics documented in [nix/README.md](../nix/README.md) | + +Two consequences worth calling out because they amend the merged +implementation doc (small PR rides with Phase 0): + +1. Task 0.3's "vagrant-libvirt vendored via the plugin gem set" → just + `pkgs.vagrant`, plugin included. +2. Task 0.6's "2 containers running tcp_server/tcp_client (from + `binaries.xtcp2-all`)" → `docker load` the `oci-xtcp2-tcp-stress` tarball + and run `TCP_MODE=both` containers; smaller, and it is the same image the + microVM tcp-stress flavor uses. + +## Design decisions + +| # | Decision | Rationale | +|---|---|---| +| D1 | Scenario *drivers* are plain scripts in `vagrant/scenarios/`; each gets a `writeShellApplication` flake-app wrapper from `nix/redteam.nix` | drivers stay WIP-runnable from the working tree (the `path:.` principle); wrappers get built-in shellcheck and pinned `runtimeInputs`; scenario files themselves are plain so `vagrant` also accepts them unchanged | +| D2 | The image tarballs are `packages.redteam-oci`/`redteam-oci-tcp-stress` — the streamLayeredImage script piped through `gzip -n` inside the derivation — and the app wrapper exports their store paths; the scenario scps them into the VM (via `vagrant ssh-config` + ssh/scp, [lib/ssh.sh]) before `vagrant provision` | a streamLayeredImage script cannot execute inside the VM — its nix store deps don't exist there — and the box image ships no rsync, so synced folders are off and scp over vagrant's own ssh config is the one delivery path that needs no provider magic | +| D3 | `VAGRANT_CWD` and `VAGRANT_HOME` are pinned to `vagrant/.gen/.vagrant.d` by the app wrappers | no state leaks into `~/.vagrant.d`; `.gen/` is gitignored so boxes/keys/disks live in one disposable dir | +| D4 | Box: `cloud-image/ubuntu-24.04` at `config.vm.box_version = "20260926.0.0"`, pin log in `vagrant/README.md` | the official Ubuntu cloud-image team's libvirt box — the plan doc's `ubuntu/noble64` guess does not exist in the Vagrant Cloud catalog. Vagrant Cloud publishes no checksum for this box, so the pin is the version number | +| D5 | The deployment matrix (`XTCP2_MODE`, `XTCP2_AUTH`, `XTCP2_CAPS`, `XTCP2_ATTACKER`) is read by the **Vagrantfile from ENV** and passed to provisioners as arguments | one `vagrant up` shape; scenarios set the env (or default it), `vagrant provision` re-applies cheaply, and `XTCP2_MODE=bridge XTCP2_AUTH=raw nix run .#redteam-rt-1-1` satisfies the DoD matrix-flip checkbox | +| D6 | Catcher = host-side `socat TCP-LISTEN:9999,reuseaddr,fork OPEN:/var/lib/xtcp2-catcher/records.jsonl,append` on the victim VM (systemd unit), NOT a container | survives attacker-container actions (the RT-11 point is that attacker containers must not be able to kill delivery); the assertion greps per-netns records and counts line growth across the poll cadence | +| D7 | Work population = 2 `oci-xtcp2-tcp-stress` containers (`TCP_MODE=both TCP_COUNT=25`), plus the base-OS sockets the VM itself accrues | both non-attacker netns and base-OS coverage, per the RT-11 victim-population contract | +| D8 | Attacker VM tools via apt (`socat jq curl tcpdump strace iperf3 nghttp2-client` for h2load, `slowhttptest` — universe); repo static binaries (`xtcp2client`, `xtcp2ctl`) shipped as a tools tarball the derivation static-asserts | no nix closure is dragged into the VM. Verified: the repo binaries are static ELF, but nixpkgs' grpcurl is **dynamic** — it is NOT in the Phase 0 tar; the gRPC scenarios (Phase 1) get a CGO_ENABLED=0 grpcurl build of their own. `ghz` is **not** in Ubuntu apt — same treatment as grpcurl, or the gRPC storms stay on h2load | +| D9 | `redteam-oci` / `redteam-oci-tcp-stress` / `redteam-attacker-tools` are **packages** (deterministic `gzip -n` output, cacheable); the app wrappers invoke `nix build` at run time | tarballs are pure functions of already-cached derivations, so `nix build .#redteam-oci` is fast and the DoD checkbox "`nix build .#redteam-oci` produces a loadable tarball" is a real build target | +| D10 | `checks.redteam-lint` = shellcheck over `vagrant/**/*.sh` (+ `bash -n`) — hermetic, no network, the only red-team CI gate | VM scenarios need KVM + network, so they are apps, not checks; `nix-fmt`/`statix` checks already cover the new `.nix` files automatically via `src` | + +## The wiring map + +Three touched files, one new nix file, one new tree. Exact insertion points: + +**1. `nix/redteam.nix` (new)** — see [spec below](#nixredteamnix-specification). + +**2. `nix/default.nix`** — import beside the other builders (after +`linkmonitorPerformance`, ~line 300): + +```nix +redteam = import ./redteam.nix { + inherit pkgs lib src; + inherit (binaries) xtcp2client xtcp2ctl; + inherit (containers) oci-xtcp2 oci-xtcp2-tcp-stress; +}; +``` + +then merge the namespaces at the existing aggregation points, following the +`// linkmonitorPerformance.apps` precedent at the end of `apps`: + +- `packages = ... // redteam.packages;` +- `apps = { ... } // linkmonitorPerformance.apps // (lintTiers ...) // redteam.apps;` +- `checks = ... // { redteam-lint = redteam.checks.redteam-lint; };` + +`src` (the full tree), not `goSource` — Go-only filtering must not strip the +`vagrant/` tree out of the store copy that shellchecks it. + +**3. `nix/packages.nix`** — `devTools` += `vagrant` (one line; brings the +plugin). Dev shell users then have `vagrant` on PATH inside `nix develop`. + +**4. `Makefile`** — three thin wrappers after `protos:` (same style as the +existing `nix run .#regen-protos` targets): + +```make +redteam-lint: + nix build .#checks.x86_64-linux.redteam-lint -L + +redteam-smoke: + nix run .#redteam-rt-1-1 + +redteam-destroy: + nix run .#redteam-destroy +``` + +**5. Docs** — `nix/README.md` gets a "Red-team harness" row in the +workflow table; the dev shell `xtcp2-help` banner gets three lines; +`docs/redteam-implementation.md` gets the two amendments from the inventory +section; `docs/README.md` links this doc. + +## nix/redteam.nix specification + +```nix +# nix/redteam.nix +# +# Red-team harness wiring (docs/redteam-plan.md, docs/redteam-implementation.md). +# Runners execute from the repo root on the harness host (l); they need KVM, +# libvirtd, and the network (vagrant box downloads). checks.redteam-lint is the +# only hermetic member. +{ + pkgs, + lib, + src, # full tree — Go-source filtering must not strip vagrant/ + xtcp2client, # binaries.xtcp2client (static) + xtcp2ctl, # binaries.xtcp2ctl (static) + oci-xtcp2, # containers.oci-xtcp2 (stream script) + oci-xtcp2-tcp-stress, # containers.oci-xtcp2-tcp-stress (stream script) +}: +``` + +Attrs it returns: + +### packages + +| attr | derivation | output | +|---|---|---| +| `redteam-oci` | `runCommand`: `${oci-xtcp2} \| gzip -n > $out` | single file `xtcp2-oci.tar.gz`, loadable by `docker load` (DoD 1) | +| `redteam-oci-tcp-stress` | same for `oci-xtcp2-tcp-stress` | `xtcp2-tcp-stress.tar.gz` | +| `redteam-attacker-tools` | `runCommand`: linkFarm of `xtcp2client`, `xtcp2ctl`, `versions.grpcurl` → tar; **asserts each binary is static** (`file` says "statically linked") before tarring | `xtcp2-attacker-tools.tar` — unpacks to `/opt/xtcp2-redteam/bin/` on the attacker VM and in the co-tenant container | + +The static assertion is a hard failure, not a warning: a dynamically-linked +binary shipped to Ubuntu would fail at runtime with a missing `/nix/store` +loader — the exact class of bug the derivation should catch at build time. + +### apps + +Generated per scenario + fixed helpers. Discovery pattern: + +```nix +scenarioApps = lib.listToAttrs ( + map + (file: let + id = builtins.head (lib.splitString "-" (builtins.baseNameOf file)); + # rt-1-1-unauth-scrape.sh -> redteam-rt-1-1 + in lib.nameValuePair "redteam-rt-…" { + type = "app"; + program = "${mkScenarioRunner file}/bin/redteam-rt-…"; + }) + (lib.filesystem.listFilesRecursive "${src}/vagrant/scenarios") +); +``` + +`mkScenarioRunner` is a `writeShellApplication` that, per D1/D2/D3: + +1. requires repo root (`[ -f flake.nix ]`) — the repo's runner convention; +2. `export VAGRANT_CWD="$PWD/vagrant" VAGRANT_HOME="$PWD/vagrant/.gen/.vagrant.d"`; +3. materializes tarballs if missing or stale (`nix build --no-link --print-out-paths .#redteam-oci .#redteam-oci-tcp-stress .#redteam-attacker-tools` → `gzip`-copy into `vagrant/.gen/`) — idempotent, so a second run reuses the same files; +4. exports `XTCP2_OCI_TAR=…`, `XTCP2_TCP_STRESS_TAR=…`, `XTCP2_ATTACKER_TOOLS_TAR=…` (baked-in store paths, not run-time `nix build` output); +5. `exec bash vagrant/scenarios/`. + +Fixed helpers: `redteam-destroy` (`vagrant destroy -f` both VMs + prune +`.gen/`), `redteam-status` (`vagrant status` + docker ps via `vagrant ssh`), +`redteam-matrix` (Phase 1: loops scenario × `XTCP2_MODE` × `XTCP2_AUTH` +rows, one TAP stream per cell), `redteam-lint` (the same shellcheck as the +check, for local iteration). + +### checks + +`redteam-lint` — `runCommand` with `pkgs.shellcheck` in `nativeBuildInputs`: + +```sh +find "$src/vagrant" -name '*.sh' -print0 | + xargs -0 shellcheck -x # -x: follow external sources (lib/*.sh sourcing) +find "$src/vagrant" -name '*.sh' -print0 | + xargs -0 -n1 bash -n +``` + +Both must pass; `-x` matters because `scenarios/*.sh` source `../lib/*.sh`. + +## vagrant/ tree specification + +```text +vagrant/ + Vagrantfile + README.md prerequisites, box pin + version, cold-boot time, teardown + .gitignore .gen/ redteam/evidence/ + provision/ + common.sh apt-get update, docker-ce from Docker's apt repo (noble), + chrony, jq socat tcpdump strace iperf3 nghttp2-client + victim.sh docker load the three uploads; run catcher (systemd socat + unit, port 9999, /var/lib/xtcp2-catcher/records.jsonl); + xtcp2 daemon container per matrix env; work population + (2 × TCP_MODE=both TCP_COUNT=25); attacker tier container + attacker.sh unpack attacker-tools tar to /opt/xtcp2-redteam/bin + lib/ + assert.sh ok/not_ok (TAP), done_testing, wait_for , + expect_outcome + matrix.sh XTCP2_MODE/XTCP2_AUTH/XTCP2_CAPS/XTCP2_ATTACKER validation + + docker run argument factories + evidence.sh run-id dirs (date+git sha), capture(), redact tokens + scenarios/ + rt-1-1-unauth-scrape.sh + redteam/ + findings.md seed table + evidence/ gitignored run outputs +``` + +**Vagrantfile** (two VMs to start; the Phase 1 router VM is a third +definition behind `REDTEAM_ROUTER=1`): + +- `config.vm.box = "cloud-image/ubuntu-24.04"`, `config.vm.box_version = "20260926.0.0"` (pin log in vagrant/README.md); +- `victim`: 6 GB RAM, 4 vCPU; `attacker`: 2 GB, 2 vCPU; provider + `libvirt` (`driver = "kvm"`, `storage_pool = "default"`); +- private network `xtcp2-redteam-mgmt` (e.g. `192.168.142.0/24`, DHCP) for the + attacker↔victim vantage — distinct from libvirt's default net so the DoD + "no networks beyond the defined ones" assertion is `virsh net-list`-checkable; +- `victim` provisioning: `common.sh` → upload `.gen/*.tar.gz` → `victim.sh + ` (matrix as argv, validated by + `lib/matrix.sh` — env → argv translation happens in the Vagrantfile so + `vagrant provision` alone re-applies a matrix change); +- mounts: the daemon container gets `-v /var/lib/xtcp2:/var/lib/xtcp2`, + `-v /run/netns:/run/netns:ro,rshared -v /run/docker/netns:/run/docker/netns:ro,rshared` + — matching TODO-SOON §29 and the RT-11 poison/drop scenario shapes. + +**lib/assert.sh** — the TAP contract from the implementation doc, verbatim: +`ok`/`not ok` lines, one `RESULT rt-N-M [severity] [evidence]` +summary, `exit 0` iff actual == `EXPECT` and zero `not ok`. + +**Scenario skeleton** (contract from the implementation doc, "Conventions +every phase follows" §2): `set -euo pipefail`, `EXPECT=` declared at the top, +`trap cleanup EXIT`, idempotent (`vagrant provision` safe), token generation +via `openssl rand` into the evidence dir only. + +## The rt-1-1 walkthrough + +The first scenario end-to-end (task 0.7): + +1. **Preflight** (fail fast): repo root, `vagrant` on PATH, `virsh -c + qemu:///system version` succeeds, tarballs materialized (the app wrapper + did this), `RESULT` dir created. +2. **Boot**: `vagrant up victim attacker` (cold: box download + provision, + target ≤ 15 min; warm: `vagrant provision` path). +3. **Population check** (pre-attack baseline): catcher file has ≥1 line per + work netns within 2 × poll cadence — this is also the "victim still + reporting" helper the RT-11 invariant reuses after every attack. +4. **Attack**: plain-tier co-tenant container on the victim's dockerd: + `docker run -d --name redteam-attacker --network bridge ubuntu:24.04 sleep infinity`, + then `docker exec redteam-attacker bash -c 'apt-get update -qq && apt-get + install -y -qq curl && curl -sS -m 5 http://172.17.0.1:9088/metrics'` + (host-mode daemon bound on the docker0 gateway). Evidence: full scrape body. +5. **Assertions** (TAP): HTTP 200 from the co-tenant vantage; body contains + a record-bearing metric with the victim netns label (not the attacker's); + catcher keeps growing for one more cadence (invariant). +6. **Verdict**: outcome CONFIRMED == EXPECT → `RESULT rt-1-1 CONFIRMED …`, + exit 0. The DoD matrix flip is then proven by rerunning with + `XTCP2_AUTH=raw` (401 from the co-tenant → BLOCKED == new EXPECT). +7. **Cleanup**: kill the attacker container; `vagrant destroy -f` unless + `REDTEAM_KEEP=1` (debugging). + +## Build sequence + +One PR (or two, harness/first-scenario, per the implementation doc's +convention 1). Commits in reviewable order — each is independently verifiable: + +| # | Commit | Implements | Verification | +|---|---|---|---| +| C1 | `nix/redteam.nix` packages + wiring into `nix/default.nix`, `nix/packages.nix` | tasks 0.3 (packages half), 0.8 (lint) | `nix build .#redteam-oci .#redteam-oci-tcp-stress .#redteam-attacker-tools`; `nix flake check` still green | +| C2 | `checks.redteam-lint` + Makefile targets + `nix/README.md`/help-banner rows | tasks 0.3 (apps/checks half), 0.8 | `nix build .#checks.x86_64-linux.redteam-lint -L`; `make redteam-lint` | +| C3 | `vagrant/` skeleton: Vagrantfile, `provision/*.sh`, `.gitignore`, README | tasks 0.1, 0.2 | `vagrant up victim attacker` cold boots; `docker ps` shows daemon + population + catcher; daemon reachable at 9088 from the VM | +| C4 | `lib/` helpers + `redteam/findings.md` seed | tasks 0.4, 0.8 | `redteam-lint` shellchecks the new files green | +| C5 | matrix wiring (`XTCP2_AUTH=raw` token files, `-auth` flags) + population/catcher systemd units | task 0.5, 0.6 | `XTCP2_MODE=bridge XTCP2_AUTH=raw vagrant provision` → daemon 401s anonymous scrapes | +| C6 | scenario `rt-1-1` + app + docs amendments | task 0.7, 0.9 | the full Phase 0 DoD list, including the cold-boot `nix run .#redteam-rt-1-1` and the `virsh net-list` leak assertion | + +This maps onto the implementation plan's Phase 0 DoD checkboxes one-to-one; +C6 is the PR exit gate. Findings.md row for rt-1-1 lands with C6 (the +scenario must run before its row is truthful). + +## Open questions + +1. **Box choice** — resolved during the build: the catalog has no + `ubuntu/noble64`; the official Ubuntu cloud-image team's + `cloud-image/ubuntu-24.04` (libvirt provider) is the box, pinned at + `20260926.0.0` with the pin log in `vagrant/README.md`. No NixOS-style box + is considered — the victim must be **Ubuntu** (TODO-SOON §29 is the entire + reason this harness exists alongside the NixOS microVM checks). +2. **slowhttptest via apt (universe)** vs `universe` enablement on noble — + verify `apt-get install slowhttptest` works in C3; if not, ship it in the + attacker-tools tarball (verify static like the repo binaries). +3. **`ghz` static linkage** — Phase 1 (rt-4-3 needs it); if nixpkgs ghz is + dynamically linked, h2load (apt) covers the storm shape and ghz is dropped. +4. **Memory budget on `l`** — 8 GB (victim) + 2 GB (attacker) is fine for + Phase 0; Phase 4's FD/conntrack knees may raise the victim to 10–12 GB. + Note it in `vagrant/README.md` when C3 lands. diff --git a/docs/redteam-implementation.md b/docs/redteam-implementation.md index dd53090b4..4f9a12e05 100644 --- a/docs/redteam-implementation.md +++ b/docs/redteam-implementation.md @@ -83,7 +83,8 @@ Flake side: `nix/redteam.nix` (imported from `nix/default.nix`) exposing: - `apps.x86_64-linux.redteam-` — wraps `scenarios/