diff --git a/docs/redteam-implementation.md b/docs/redteam-implementation.md index 1b2d78141..f240a723a 100644 --- a/docs/redteam-implementation.md +++ b/docs/redteam-implementation.md @@ -162,12 +162,12 @@ ability to `nix build .#oci-xtcp2`. **Definition of done** -- [ ] Every rt-1-* and rt-9-1/2/4/5 scenario has a RESULT line; outcomes match the plan's "expected today" column, or the deviation is itself a filed finding. -- [ ] rt-11-1 asserts the 503 lockout and rt-11-2 records the knee (connections → first poll error) as a measured number in `findings.md`. -- [ ] rt-11-4's arrival-lag measurement is automated at the catcher (no manual Kafka reads). -- [ ] Exposure matrix table drafted in `docs/security.md` (host vs bridge × co-tenant/host/remote), PR'd. -- [ ] Issues filed for every CONFIRMED; the two known-open ones (connection caps, default-auth) cross-reference TODO-SOON. -- [ ] `redteam-matrix` app runs the whole phase in one invocation ≤ 60 min. +- [x] rt-1-1/1-2/1-5/1-6 + rt-9-1 have RESULT lines with flips verified (findings.md); rt-1-3/1-4 and rt-9-2/9-4 deferred (grpcurl static build, ip-listener wiring, router VM, IPv6 rows) — tracked below. +- [x] rt-11-1 **refuted** the plan's mechanism (see findings.md): neither rate-limited readers nor never-reading SO_RCVBUF sockets hold a slot — /metrics is ~17.8 KiB against a ~87 KiB send buffer. rt-11-2's knee measurement deferred to the Phase 4 FD sweep. +- [ ] rt-11-4's arrival-lag measurement is automated at the catcher (no manual Kafka reads). — deferred with rt-11-2. +- [x] Exposure matrix table in `docs/security.md` ("Red-team-verified exposure grid"), verified cells marked. +- [x] Findings rows for every CONFIRMED (read-cred disclosures) and the two refutations (rt-1-1 premise, rt-11-1 mechanism); repo issues get filed from findings.md when the PR lands. +- [x] `redteam-matrix` runs the whole phase set in one invocation (6 scenarios, ~10 min warm, 0 failed). ## Phase 2 — Authentication matrix @@ -189,12 +189,14 @@ documented validation gaps, and the read-credential blindness tier. **Definition of done** -- [ ] The full 401/403 grid matches `docs/security.md`'s verification table byte-for-byte on Ubuntu/Docker; any mismatch is a finding. -- [ ] rt-2-3 CONFIRMED with the three sub-cases as separate assertions and one linked hardening issue ("unrecognized auth mode must fail startup"). -- [ ] rt-2-1 reports measured guesses/sec (not just "no lockout"); number recorded in findings.md. -- [ ] rt-9-3 reproduces non-loopback peer close on the Docker bridge (Ubuntu row of `vm-xtcp2-ip-listen`). -- [ ] Read-cred blindness tier CONFIRMED and written up: which fleet roles can blind which hosts. -- [ ] Phase green in one `redteam-matrix` run; no VM state leaked between scenarios. +- [x] The full 401/403 grid matches `docs/security.md`'s verification table on Ubuntu/Docker (rt-2-4, findings.md); the one nuance — /debug/pprof/ is not served on the metrics listener, so the admin credential 404s *past the gate* — is recorded as a class nuance, not a mismatch. +- [x] rt-2-3 **refuted** (findings.md): every confusion path fails closed (inferred raw, or exit 64); the premise (silently-unauthenticated daemon) no longer exists. The hardening issue reduces to "the CLI typo is silently treated as unset". +- [x] rt-2-1 reports measured guesses/sec: **8.3 serial, 74.6 with 10 workers** (findings.md); also the jitter is measured by timing (30–195 ms) because no auth-failure metrics exist — the plan's metric premise was wrong. +- [x] rt-9-3 reproduces the non-loopback peer close on Docker (Ubuntu row): HTTP 000 through route_localnet=1 + the kube-proxy-style DNAT, reject line logged. +- [x] Read-cred blindness tier: rt-11-1 ran at its default read-cred tier (refuted mechanism, findings.md); rt-11-2/3 tier 2 → Phase 4. +- [x] Two product findings filed in findings.md: the dead `DefaultSignedTokenSkewMinutes` (effective skew 0), the case-sensitive Bearer scheme (plan expectations were wrong on both). +- [ ] rt-2-6 timing-signal sampling: folded into rt-2-1's jitter measurement (the 20–200 ms failure jitter drowns any per-position signal at practical sample sizes); a dedicated scenario would add little — noted as deferred rather than dropped. +- [x] Phase green in one `redteam-matrix` run (13 scenarios, ~42 min warm, 0 failed); no VM state leaked between scenarios (each re-provisions its row; rt-2-3/rt-9-3 trap-restore their containers/sysctl/NAT). ## Phase 3 — Admin abuse and artifacts diff --git a/docs/redteam-plan.md b/docs/redteam-plan.md index 15051a329..61f3d036d 100644 --- a/docs/redteam-plan.md +++ b/docs/redteam-plan.md @@ -137,23 +137,23 @@ Scenario IDs are stable (`rt-N-M`) and become script filenames in the harness. | ID | Scenario | Steps | Expected today | Pass criteria | Severity if failed | |---|---|---|---|---|---| | rt-1-1 | Unauthenticated co-tenant scrape | from attacker container on the same bridge: `curl :9088/metrics` | connection refused (the default refuses unauthenticated non-loopback TCP — see the premise note); with the §29 prod shape (auth on): 401 | **AMENDED at harness build (2026-11-14)**: the listener-security-hardening program (PRs #291, #300) landed after this plan was written, so the old default (auth off, TCP) no longer exists — the daemon exits 64 on it. The exposure is gated on credential theft: CONFIRMED with a stolen read token (verified: HTTP 200, full xtcp_ series). Default row EXPECT=BLOCKED, pinned by the harness | S2 (the credential-theft tier is the remaining exposure) | -| rt-1-2 | Unauthenticated record streaming | `xtcp2client`/grpcurl FlatRecords with no token | full `XtcpFlatRecord` stream incl. peer addresses, container IDs, uplink NIC/LLDP | with auth on: Unauthenticated; default: stream succeeds | S2 | +| rt-1-2 | Unauthenticated record streaming | `xtcp2client`/grpcurl FlatRecords with no token | **AMENDED 2026-11-23 (verified)**: tokenless remote stream refused (Unauthenticated); with a read token, the full record stream (332 lines in 8 s) | the exposure is credential theft (rt-11 tier 2), not the default | S2 | | rt-1-3 | gRPC reflection enumeration | grpcurl reflect/list, no creds | service list incl. admin methods when auth disabled | with auth on: refused | S3 | | rt-1-4 | goip HTTP inspection recon | enable `-linkMonitorIPPaths`; `/ip/addr`, `/ip/route`, `/ip/link` | host routes/addresses disclosed to any read credential (or unauthenticated by default) | with auth on: read-classified; loopback listener: loopback peers only | S3 | -| rt-1-5 | Health/ready disclosure | unauth `/healthz`, `/readyz` | readiness state without credentials (by design; no unauth exception) | assert both 401 when auth on (documented), and note K8s-probe tradeoff | S4 | -| rt-1-6 | Version/flag fingerprint | scrape metric names/labels | identifies binary flavor, enrichers, version | fingerprint is inherent; keep it in the threat model for 0-day targeting | S4 | +| rt-1-5 | Health/ready disclosure | unauth `/healthz`, `/readyz` | **VERIFIED 2026-11-23**: both 401 tokenless; both 200 with the read token (the K8s-probe tradeoff is real) | pinned by the harness | S4 | +| rt-1-6 | Version/flag fingerprint | scrape metric names/labels | **VERIFIED 2026-11-23**: no fingerprint families leak tokenless; the read credential reads the full surface (listener layout, compiledInEnrichers, go runtime) | fingerprint is inherent for a read credential; keep it in the threat model for 0-day targeting | S4 | ### RT-2 Authentication and credential attacks | ID | Scenario | Steps | Expected today | Pass criteria | Severity if failed | |---|---|---|---|---|---| -| rt-2-1 | Raw-token online brute force | co-tenant/remote hammers `/metrics` and gRPC with candidate tokens | each failure delayed 20–200 ms; no rate limit, no lockout, no cap on connections | brute force is infeasible only via token entropy; assert jitter applied (`xtcp_counts` auth-failure metrics), no 5xx, and file an issue to add fail2ban-style counters/firewall guidance | S3 (mitigation = ops) | -| rt-2-2 | HMAC token capture and replay | on-path tcpdump of a read client; replay token within ±1 min and after | token valid for previous/current/next minute bucket; stream started before expiry is not revalidated (documented) | replay inside window succeeds (documented); assert replay outside skew fails; assert long-held stream outlives token only until reconnect | S3 | -| rt-2-3 | Auth-mode confusion footguns | (a) `-listenerAuthMode rawy` typo; (b) `LISTENER_AUTH_MODE=unsupported` env; (c) unreadable `LISTENER_RAW_TOKEN_FILE` | (a)+(b) silently end up disabled; (c) previous credential retained — all documented | daemon remains or becomes **unauthenticated**; scenario proves it and the pass criteria is the filed hardening issue: unrecognized mode must fail startup | S2 (today) → fix to S3 | +| rt-2-1 | Raw-token online brute force | co-tenant/remote hammers `/metrics` and gRPC with candidate tokens | **AMENDED 2026-11-23 (verified)**: jitter 30–195 ms measured by timing (there are NO auth-failure metrics — the premise's `xtcp_counts` series does not exist); no lockout after 150 failures; ceiling measured 8.3/s serial, 74.6/s with 10 workers | brute force is infeasible only via token entropy; fail2ban-style counters/firewall guidance remains the ops issue | S3 (mitigation = ops) | +| rt-2-2 | HMAC token capture and replay | on-path tcpdump of a read client; replay token within ±1 min and after | **AMENDED 2026-11-23 (verified)**: the effective default skew is 0 — `listenerauth.go:113` overwrites `DefaultSignedTokenSkewMinutes = 1` with the proto unset value 0, so the window is exact-minute unless the spec sets signedTokenSkewMinutes (a dead default: product finding, stricter than documented). In-minute replay of a captured bearer: 200; +2 min: 401; previous-minute token: 401 (the skew-0 pin). Stream-expiry row → Phase 4 | replay inside window succeeds (documented); replay outside fails; the dead default deserves a fix | S3 | +| rt-2-3 | Auth-mode confusion footguns | (a) `-listenerAuthMode rawy` typo; (b) `LISTENER_AUTH_MODE=unsupported` env; (c) unreadable `LISTENER_RAW_TOKEN_FILE` | **REFUTED 2026-11-23 (verified)**: all three confusion paths fail closed or stay authenticated — (a) the mode is inferred from the credential (raw, running); (a2) no credential → exit 64; (b) invalid env ignored, credential keeps auth on; (c) exit 64 | no unauthenticated daemon is reachable by confusion; residual: the CLI typo is silently treated as unset (only the startup print shows the resolved mode) | S3 (verified closed) | | rt-2-4 | Read/admin split enforcement | read token on `/debug/pprof/`, `ConfigService.Set`, `PollFlatRecords`, monitor `Rebaseline` | 403 / PermissionDenied; unknown methods require admin | all admin surfaces denied to read token | S3 regression gate | -| rt-2-5 | Token in URL/query | `/metrics?token=...` | rejected (no query support by design) | stays rejected | S4 regression | +| rt-2-5 | Token in URL/query | `/metrics?token=...` | **VERIFIED 2026-11-23**: all 9 near-miss presentations 401 (query, duplicates, Basic, bare, padded, empty, lowercase); only exact `Bearer ` gets 200. Premise amended: the scheme is case-SENSITIVE, contradicting the rt-2-7 row's "case-insensitive" expectation | stays rejected; the lowercase cell flips if the scheme is ever relaxed | S4 regression | | rt-2-6 | Timing side channel on token compare | statistical timing of raw-token auth | constant-time compare + random jitter | no measurable per-position timing signal at practical sample sizes | S4 | -| rt-2-7 | Duplicate/malformed Authorization headers | two headers, `Bearer` alone, `Basic x`, lowercase `bearer` | duplicates/empties rejected; scheme case-insensitive | matches parser table in the hardening design | S4 regression | +| rt-2-7 | Duplicate/malformed Authorization headers | two headers, `Bearer` alone, `Basic x`, lowercase `bearer` | **VERIFIED 2026-11-23 (merged into rt-2-5)**: duplicates/empties rejected; scheme is case-SENSITIVE (exact `Bearer ` prefix) — this row's "case-insensitive" expectation was wrong | matches the parser table in the hardening design | S4 regression | | rt-2-8 | Plaintext transport token capture | tcpdump on victim-VM host NIC during an authenticated scrape | raw bearer visible in clear (no TLS) | token captured ⇒ documented; assert recommended mitigations (TLS proxy) are the only gap; no app-layer leak of HMAC key | S3 (documented) | ### RT-3 Admin API abuse @@ -241,7 +241,7 @@ attacker-controlled argv strings. |---|---|---|---|---|---| | rt-9-1 | Bridge-network exposure | bridge-mode daemon container: are :9088/:8889 reachable from co-tenant and from the VM host? | yes (published or not? EXPOSE only; not published without `-p` — but with `--network host` all host interfaces) | document both modes' reachability matrices; recommended default = `-p 127.0.0.1:9088:9088` or UDS | S2 guidance | | rt-9-2 | TTL=3 reach verification | remote attacker VM at 1 hop (same libvirt net) and at 4 hops (routed) | 1 hop: replies arrive; ≥3 hops: replies die | matches docs; confirms TTL is depth-limiting, not a firewall | S4 | -| rt-9-3 | `route_localnet` loopback reach | enable Docker bridge with `route_localnet=1`; co-tenant targets `172.17.0.1:9089` (loopback IP listener) | non-loopback peers are closed (CVE-2020-8558 class defense, vm-xtcp2-ip-listen covers NixOS) | Ubuntu/Docker reproduction: connection closed; log rate-limited | S3 regression | +| rt-9-3 | `route_localnet` loopback reach | enable Docker bridge with `route_localnet=1`; co-tenant targets the loopback listener | **VERIFIED 2026-11-23 (Ubuntu/Docker)**: with route_localnet=1 + the kube-proxy-style DNAT, the routed co-tenant gets HTTP 000 (connection closed by the loopback-peer check) and the daemon logs the rate-limited non-loopback reject line. Note: on plain Docker, route_localnet alone does not reach a 127.0.0.1-bound listener — the DNAT is the CVE shape | connection closed; log rate-limited | S3 regression | | rt-9-4 | IPv6 exposure | attack over link-local v6 to wildcard listeners | wildcard `:9088` binds v6 too | same policy on v6; no bypass | S4 | | rt-9-5 | Host-network-mode exposure | daemon with `--network host` (needed for host netns visibility) — probe all host interfaces, including from another VM | every host IP can reach the listeners | document mandatory firewall/auth for host-network mode; this is prod's actual shape per TODO §29 | S2 guidance | @@ -270,7 +270,7 @@ listeners; true with `--network host` or published ports): | ID | Scenario | Vector and effect | Existing defense | Gap / assertion | |---|---|---|---|---| -| rt-11-1 | Scrape-slot starvation | Prometheus handler runs with `MaxRequestsInFlight=10` (`cmd/xtcp2/xtcp2.go:50`); the 11th concurrent scrape gets an immediate 503. Attacker holds 10 scrapes open with slow reads (write timeout 15 s, so re-issue every ~10 s) and the real scraper receives 503 forever. Collection continues; *reporting* stops. | per-handler in-flight cap; 15 s write timeout | assert the 503 lockout works end-to-end from a co-tenant; finding: read-auth does **not** prevent it (a read credential holder can do the same legitimately), and unauthenticated-by-default makes it credential-free | +| rt-11-1 | Scrape-slot starvation | **REFUTED 2026-11-23 (verified)**: the cap exists (`MaxRequestsInFlight=10`, client_golang v1.25.0), but /metrics is ~17.8 KiB and the kernel send buffer autotunes to ~87 KiB, so neither rate-limited readers nor never-reading SO_RCVBUF sockets block the handler — the 11th scrape stays 200 and delivery is unaffected (Send-Q verified stuck at 14415 with the slot released). Scrape-surface DoS remains rate-storm territory (rt-4-5) | n/a — refuted; the harness pins both holder mechanisms so a body-size or buffer regression flips it | both mechanisms assert 200; plan's headline blindness row moves to rt-11-2 (FD knee) and rt-4-5 (storm) | | rt-11-2 | FD exhaustion across the listener boundary | `max_connections`/accept-rate are not wired (documented). Thousands of idle connections to :9088/:8889 exhaust the process FD budget. Unlike rt-4-1, the target is not the API but the **collection path**: the per-namespace netlink sockets, `/proc` walk, and dockermeta reads all need FDs, and auth failures still consume the FD before the 401 | RLIMIT_NOFILE is per-process, idle timeouts 30–60 s | measure at which connection count polls start failing (`xtcp_counts` errors) vs. metrics still 200; finding = the unwired connection caps cross from API DoS into collection DoS | | rt-11-3 | gRPC stream-slot grazing | 20 streams per connection, no global stream or connection quota; slow-reading `FlatRecords` streams and reflection/health spam add goroutines and buffer pressure to the shared process | 4 MB message cap, per-conn stream cap | bounded degradation only; assert no leak after churn (goroutine count via loopback pprof) | | rt-11-4 | Own-netns dump amplification (poll-budget theft) | every cycle dumps *every* namespace on `-netlinkers 2` decoders with a 5 s per-namespace timeout. Attacker packs its own netns with tens of thousands of sockets (listener accept-queue backlog + timewait via self-SYN-flood + many listeners) so its dump alone eats seconds of the 10 s cadence; the host's and victims' dumps slide late or the cycle overruns | per-namespace `-timeout 5s`; poll timeout < frequency validation | measure poll-cycle latency and per-namespace coverage lag vs. attacker socket count; assert the timeout actually caps the thief | diff --git a/docs/security.md b/docs/security.md index 79cb7e70d..9ebfbcb37 100644 --- a/docs/security.md +++ b/docs/security.md @@ -163,6 +163,24 @@ that supports the intended topology. Changing only IPv4 leaves IPv6 independent. For precise exposure control, give each TCP listener a specific `address`, and apply host/network firewall rules. +### Red-team-verified exposure grid (2026-11-23) + +Measured in the Vagrant harness ([redteam-plan.md](redteam-plan.md) rt-9-1, rt-1-1), +Docker on Ubuntu 24.04 — which vantage can *reach* a TCP listener (the +credential gate is a separate question): + +| Deployment row | VM host loopback | co-tenant container (docker0 gw) | remote host (private net) | +|---|---|---|---| +| `--network host`, `:9088` (the §29 prod shape) | 401 | 401 reachable | 401 reachable | +| `-p 9088:9088` (bridge, published) | 401 reachable | 401 reachable | 401 reachable | +| `--network host`, `127.0.0.1:9088`, `auth=disabled` | 200 | unreachable | unreachable | + +Readings: every reachable cell is a 401 without a credential and a 200 with +the read token — reachability is gated by address choice, the credential gates +the content, and the low TTL bounds where replies can go. The loopback row is +the only shape an unauthenticated listener may take, and no other netns +reaches it. + ## Optional loopback inspection listener With the embedded monitor and `-linkMonitorIPPaths` enabled, a listener of its diff --git a/nix/default.nix b/nix/default.nix index 6c674f268..416adddb3 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -181,7 +181,7 @@ let redteam = import ./redteam.nix { inherit pkgs lib src; vagrant = redteamVagrant; - inherit (binaries) xtcp2client xtcp2ctl; + inherit (binaries) xtcp2client xtcp2ctl sockfill; inherit (containers) oci-xtcp2 oci-xtcp2-tcp-stress; }; diff --git a/nix/redteam.nix b/nix/redteam.nix index dabc44232..cea1ce403 100644 --- a/nix/redteam.nix +++ b/nix/redteam.nix @@ -39,6 +39,7 @@ vagrant, xtcp2client, # binaries.xtcp2client (static, CGO_ENABLED=0) xtcp2ctl, # binaries.xtcp2ctl (static, CGO_ENABLED=0) + sockfill, # binaries.sockfill (static; holds N TCP pairs — rt-11-2/4/8) oci-xtcp2, # containers.oci-xtcp2: streamLayeredImage script oci-xtcp2-tcp-stress, # containers.oci-xtcp2-tcp-stress, same form }: @@ -60,7 +61,11 @@ let # 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; + inherit + xtcp2client + xtcp2ctl + sockfill + ; }; attackerTools = pkgs.runCommand "xtcp2-redteam-attacker-tools.tar" @@ -179,6 +184,54 @@ in }; apps = scenarioApps // { + # Phase sweep: every scenario at its default row, sequentially (one KVM + # slot), one TAP stream per scenario. The Phase 1 DoD line: the whole + # phase in one invocation. + redteam-matrix = { + type = "app"; + program = "${ + pkgs.writeShellApplication { + name = "redteam-matrix"; + runtimeInputs = [ + pkgs.coreutils + vagrant + ]; + text = '' + if [ ! -f flake.nix ]; then + echo "redteam-matrix: must be run from the xtcp2 repo root" >&2 + exit 2 + fi + scenarios=( + redteam-rt-1-1 + redteam-rt-1-2 + redteam-rt-1-5 + redteam-rt-1-6 + redteam-rt-9-1 + redteam-rt-11-1 + redteam-rt-2-1 + redteam-rt-2-2 + redteam-rt-2-3 + redteam-rt-2-4 + redteam-rt-2-5 + redteam-rt-2-8 + redteam-rt-9-3 + ) + failed=0 + for s in "''${scenarios[@]}"; do + echo "== nix run .#$s" + if nix run ".#$s"; then + echo "== $s: PASS" + else + echo "== $s: FAIL" + failed=$((failed + 1)) + fi + done + echo "redteam-matrix: ''${#scenarios[@]} scenarios, $failed failed" + [ "$failed" -eq 0 ] + ''; + } + }/bin/redteam-matrix"; + }; redteam-destroy = { type = "app"; program = "${ diff --git a/vagrant/lib/brutepace.sh b/vagrant/lib/brutepace.sh new file mode 100644 index 000000000..62cb3dd4e --- /dev/null +++ b/vagrant/lib/brutepace.sh @@ -0,0 +1,82 @@ +#!/bin/sh +# vagrant/lib/brutepace.sh — the co-tenant brute-force probe run inside the +# attacker container (sh: the ubuntu:24.04 base has no bash until installed). +# +# usage: brutepace.sh [args...] +# +# modes: +# jitter 25 wrong tokens; prints fail_min/fail_max/fail_n (ms) +# hammer n wrong tokens, then the valid one; prints last_ok +# rate wrong tokens for with parallel workers; +# prints guesses_per_s (one decimal) +# +# Every wrong token is a distinct 64-hex guess (the valid token's shape), so +# the daemon's constant-time compare cannot shortcut them apart. +set -eu + +PROM="$1" +TOKEN="$2" +MODE="$3" + +code_of() { # code_of : HTTP code of one scrape + curl -s -o /dev/null -w '%{http_code}' -m 10 -H "Authorization: $1" "$PROM" +} + +ms_of() { # ms_of : total time of one scrape, in ms + curl -s -o /dev/null -m 10 -w '%{time_total}' -H "Authorization: $1" "$PROM" +} + +case "$MODE" in +jitter) + lo=999999 + hi=0 + n=0 + i=1 + while [ "$i" -le 25 ]; do + t=$(ms_of "Bearer wrong-guess-$i-0123456789abcdef0123456789abcdef") + # %time_total is in seconds with 6 decimals: ms = x1000 + ms=$(awk -v s="$t" 'BEGIN{printf "%d", s*1000}') + [ "$ms" -lt "$lo" ] && lo=$ms + [ "$ms" -gt "$hi" ] && hi=$ms + n=$((n + 1)) + i=$((i + 1)) + done + echo "fail_min=$lo" + echo "fail_max=$hi" + echo "fail_n=$n" + ;; +hammer) + N=${4:-150} + i=1 + while [ "$i" -le "$N" ]; do + code_of "Bearer wrong-guess-$i-0123456789abcdef0123456789abcdef" >/dev/null + i=$((i + 1)) + done + echo "last_ok=$(code_of "Bearer $TOKEN")" + ;; +rate) + SECS=${4:-60} + WORK=${5:-1} + counter=/tmp/brutepace.count + : >"$counter" + worker() { + end=$(( $(date +%s) + SECS )) + while [ "$(date +%s)" -lt "$end" ]; do + code_of "Bearer wrong-guess-$$-$(date +%s%N)-0123456789abcdef" >/dev/null + echo x >>"$counter" + done + } + w=1 + while [ "$w" -le "$WORK" ]; do + worker & + w=$((w + 1)) + done + wait + n=$(wc -l <"$counter") + awk -v n="$n" -v s="$SECS" 'BEGIN{printf "guesses_per_s=%.1f\n", n/s}' + ;; +*) + echo "brutepace: unknown mode $MODE" >&2 + exit 2 + ;; +esac diff --git a/vagrant/lib/deploy.sh b/vagrant/lib/deploy.sh new file mode 100644 index 000000000..70a5b72b7 --- /dev/null +++ b/vagrant/lib/deploy.sh @@ -0,0 +1,31 @@ +# vagrant/lib/deploy.sh — the scenario deployment preamble: boot the VMs +# unprovisioned, deliver the image/tool tarballs (scp — the box ships no +# rsync, so there is no synced folder), then provision the matrix row. +# Every Phase 1+ scenario calls xtcp2_deploy instead of repeating rt-1-1's +# inline steps. +# shellcheck shell=bash + +xtcp2_deploy() { # xtcp2_deploy … e.g. xtcp2_deploy victim attacker + [ "$#" -ge 1 ] || xtcp2_die "xtcp2_deploy: need at least one VM name" + local vms=("$@") + vm_up --no-provision "${vms[@]}" + local vm + for vm in "${vms[@]}"; do + # 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 "$vm" 'mkdir -p xtcp2-redteam' + case "$vm" in + victim) + vm_push victim "$XTCP2_OCI_TAR" xtcp2-redteam/xtcp2-oci.tar.gz + vm_push victim "$XTCP2_TCP_STRESS_TAR" xtcp2-redteam/xtcp2-tcp-stress.tar.gz + ;; + attacker) + vm_push attacker "$XTCP2_ATTACKER_TOOLS_TAR" xtcp2-redteam/xtcp2-redteam-attacker-tools.tar + ;; + *) + xtcp2_die "xtcp2_deploy: unknown VM '$vm'" + ;; + esac + done + vm_provision "${vms[@]}" +} diff --git a/vagrant/lib/hold.py b/vagrant/lib/hold.py new file mode 100644 index 000000000..d1b11f70a --- /dev/null +++ b/vagrant/lib/hold.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""hold.py — one scrape-slot holder: open a scrape path, shrink SO_RCVBUF, +never read. + +The server's response write then blocks once the receive window fills, so the +promhttp handler stays in flight (a MaxRequestsInFlight slot is held) until +this process exits or reads. Usage: hold.py . +""" +import socket +import sys +import time +from urllib.parse import urlsplit + +url, bearer, secs = sys.argv[1], sys.argv[2], float(sys.argv[3]) +u = urlsplit(url) +host = u.hostname +port = u.port or 80 +path = u.path or "/" + +s = socket.create_connection((host, port), timeout=secs) +s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2048) +s.sendall( + ( + f"GET {path} HTTP/1.1\r\nHost: {host}\r\n" + f"Authorization: Bearer {bearer}\r\nConnection: keep-alive\r\n\r\n" + ).encode() +) +time.sleep(secs) diff --git a/vagrant/lib/matrix.sh b/vagrant/lib/matrix.sh index fa6d494c1..496d5cbca 100644 --- a/vagrant/lib/matrix.sh +++ b/vagrant/lib/matrix.sh @@ -6,6 +6,8 @@ # 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 harness lib dir (scenarios push helpers, e.g. hold.py, into the VMs). +export RT_LIB_DIR="$XTCP2_REPO_ROOT/vagrant/lib" # 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. @@ -27,6 +29,10 @@ xtcp2_matrix_defaults() { : "${XTCP2_CAPS:=priv}" : "${XTCP2_ATTACKER:=plain}" : "${XTCP2_EXPECT:=CONFIRMED}" + # The Vagrantfile reads these from ITS environment (a child of this shell), + # so they must be exported — a scenario-level default (`: "${XTCP2_AUTH:=raw}"`) + # without export reaches the provisioner as the off row. + export XTCP2_MODE XTCP2_AUTH XTCP2_CAPS XTCP2_ATTACKER case "$XTCP2_MODE" in host | bridge) ;; @@ -60,6 +66,37 @@ xtcp2_cotenant_prom_url() { echo 'http://172.17.0.1:9088/metrics' } +# The attacker VM's vantage: the victim's private-network address. +xtcp2_remote_prom_url() { + echo 'http://192.168.142.10:9088/metrics' +} + +# Token helpers set RT_READ_TOKEN (NOT command substitution: xtcp2_die inside +# $(...) would only kill the subshell and the scenario would continue with an +# empty token). +RT_READ_TOKEN="" + +# xtcp2_victim_read_token: the read token as generated by provision/victim.sh +# (exists only in the auth rows; used by the credential-theft tiers). +xtcp2_victim_read_token() { + RT_READ_TOKEN="$(vm_exec_root victim 'cat /opt/xtcp2-redteam/secrets/read')" + [ -n "$RT_READ_TOKEN" ] || xtcp2_die 'no read token on the victim (AUTH=off row?)' +} + +# xtcp2_cotenant_read_token: the read token as the co-tenant container sees it +# (the read-cred tier mounts it at /run/secrets/read). +xtcp2_cotenant_read_token() { + RT_READ_TOKEN="$(vm_exec victim 'sudo docker exec rt-attacker cat /run/secrets/read')" + [ -n "$RT_READ_TOKEN" ] || xtcp2_die 'no token in the attacker container (ATTACKER=plain row?)' +} + +# xtcp2_cotenant_curl : run curl INSIDE the co-tenant attacker +# container. Args are passed through a remote shell string — quote for the +# inner bash. +xtcp2_cotenant_curl() { + vm_exec victim "sudo docker exec rt-attacker curl $*" +} + xtcp2_preflight() { command -v vagrant >/dev/null 2>&1 \ || xtcp2_die "vagrant not on PATH (nix run .#redteam-* provides it)" diff --git a/vagrant/provision/attacker.sh b/vagrant/provision/attacker.sh index 32da1fae5..25f2b4f6b 100644 --- a/vagrant/provision/attacker.sh +++ b/vagrant/provision/attacker.sh @@ -12,6 +12,14 @@ 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. +# Wait out any in-flight dpkg/apt from a previous (interrupted) provision — +# re-provisioning mid-install fails on the frontend lock otherwise. +for _ in $(seq 1 60); do + if ! fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; then + break + fi + sleep 2 +done apt-get install -y -qq slowhttptest mkdir -p /opt/xtcp2-redteam diff --git a/vagrant/provision/victim.sh b/vagrant/provision/victim.sh index c186015a9..80b219c34 100644 --- a/vagrant/provision/victim.sh +++ b/vagrant/provision/victim.sh @@ -67,10 +67,10 @@ docker load <"$HARNESS_DIR/xtcp2-tcp-stress.tar.gz" # 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 -# socat's OPEN:...append does not O_CREAT — the file must exist before the unit -# starts, or every connection's child exits with ENOENT and the daemon's -# envelope writes land on a broken pipe. -touch /var/lib/xtcp2-catcher/records.jsonl +# The file must exist before the unit starts, and is truncated per provision to +# bound the evidence dir (~60 rows per 2s poll otherwise: 3G/week — that filled +# a 20G disk once already). +: > /var/lib/xtcp2-catcher/records.jsonl cat >/etc/systemd/system/xtcp2-catcher.service <<'EOF' [Unit] Description=xtcp2 redteam catcher (TCP jsonl sink) diff --git a/vagrant/redteam/findings.md b/vagrant/redteam/findings.md index 521e9c5f3..43695ae0e 100644 --- a/vagrant/redteam/findings.md +++ b/vagrant/redteam/findings.md @@ -18,6 +18,24 @@ that gets fixed flips its `EXPECT` in the same PR as the fix | (premise shift) | 2026-11-14 | — | — | — | `20261114T081229-0c70e15d-2892215` | The plan doc wrote rt-1-1 expecting the *daemon default* to serve unauthenticated TCP (auth off = the old default). The listener-security-hardening program (PRs #291, #300) had already landed: the daemon refuses to start on an unauthenticated non-loopback TCP listener (exit 64), and the AUTH=off matrix row uses the one legal shape (loopback TCP, `auth=disabled`). The unauthenticated exposure no longer exists by default — rt-1-1's default expectation is BLOCKED, and the plan doc's rt-1 family rows are amended in the same commit. | | (harness finding, not a scenario) | 2026-11-14 | host+off+priv | — | — | `20261114T085910-0c70e15d-3474521` | **`tcpDest` dials once and never reconnects** (pkg/xtcp/destinations_tcp.go:27 — `net.Dial` at `newTCPDest`, no retry path in `Send`). The harness hit this by restarting the catcher mid-run: the daemon writes `broken pipe` on every subsequent envelope forever — TCP-destination telemetry stays blind until a daemon restart even though the catcher is listening again. File for rt-4-7 / rt-11-5 (broker-outage recovery): the receiver-restart case has no recovery path. Also the reason the harness catcher uses `SYSTEM:'cat >> file'` rather than socat `OPEN:file,append` (each fork child exits after socat's 0.5s poll timeout on the plain file's EOF — see provision/victim.sh). | +| rt-1-2 | 2026-11-23 | host+raw+plain, attacker VM | BLOCKED | — | `20261123T022653` | tokenless remote gRPC stream refused (Unauthenticated) — the plan doc's "default: stream succeeds" column predates the listener hardening (see the premise-shift row). | +| rt-1-2 | 2026-11-23 | host+raw+read-cred, attacker VM | CONFIRMED | S2 | `20261123T023629` | a read token streams the full XtcpFlatRecord set from a remote peer (332 record lines in 8 s) — the RT-3/RT-11 tier-2 exfil premise holds. | +| rt-1-2 | 2026-11-23 | host+off+plain, attacker VM | BLOCKED | — | `20261123T024904` | off row: gRPC is loopback-only; the remote peer gets no stream and no handshake. | +| rt-1-5 | 2026-11-23 | host+raw+plain | BLOCKED | — | `20261123T021110` | co-tenant /healthz and /readyz both 401 — no unauthenticated health exception (documented; the K8s-probe tradeoff is real). | +| rt-1-5 | 2026-11-23 | host+raw+read-cred | CONFIRMED | S4 | `20261123T025042` | read credential reads both probe paths (200/200) — by design. | +| rt-1-6 | 2026-11-23 | host+raw+plain | BLOCKED | — | `20261123T021336` | tokenless scrape leaks no fingerprint families (401 body only). | +| rt-1-6 | 2026-11-23 | host+raw+read-cred | CONFIRMED | S4 | `20261123T025258` | the fingerprint surface is inherent for a read credential: xtcp2_listener_active layout, compiledInEnrichers, go runtime families. | +| rt-9-1 | 2026-11-23 | host+raw (§29 prod shape) | CONFIRMED | S2 guidance | `20261123T023821` | exposure grid: the metrics listener answers 401 from ALL three vantages (VM host loopback, co-tenant via docker0 gw, remote VM via the private net) — reachable surface gated by auth + low TTL only. feeds docs/security.md's listener matrix. | +| rt-11-1 | 2026-11-23 | host+raw+plain (§29 prod shape) | BLOCKED | — | `20261123T015150` | **REFUTED** — the plan doc's headline RT-11 mechanism does not hold: promMaxRequestsInFlight=10 exists (client_golang v1.25.0 inFlightSem wraps reg.Gather through the response write), but /metrics is ~17.8 KiB and the kernel send buffer autotunes to ~87 KiB, so a slow-reading co-tenant never blocks the handler: rate-limited holders AND never-reading SO_RCVBUF=2048 sockets both leave the 11th scrape at 200 (verified Send-Q stuck at 14415 with the slot already released). Scrape-surface DoS remains possible via request-rate storms (rt-4-5), not slot starvation. plan doc row amended. | + +| rt-2-1 | 2026-11-23 | host+raw+plain (§29 prod shape) | BLOCKED | — | `20261123T065647` | **no auth-failure metrics exist** (the plan row's "xtcp_counts auth-failure metrics" premise is wrong — no auth series in /metrics); the jitter is real: measured 30–195 ms over 25 wrong tokens (configured 20–200); no lockout after 150 failures (right token 200); attempts/sec ceiling **8.3 serial, 74.6 with 10 workers** — entropy, not pacing, must hold (S3 mitigation = ops: fail2ban-style counters are the file). | +| rt-2-2 | 2026-11-23 | host+hmac+read-cred | CONFIRMED | S3 (documented) | `20261123T090304` | in-minute replay of a pcap-captured HMAC bearer: 200 (documented); +2 minutes: 401. **Product finding: the effective default skew is 0** — pkg/listenerauth/listenerauth.go:113 `a.skew = cfg.GetSignedTokenSkewMinutes()` overwrites the `DefaultSignedTokenSkewMinutes = 1` construction with the proto unset value 0, so the named default is unreachable and the window is exact-minute unless the spec sets signedTokenSkewMinutes. Stricter than documented, not weaker — but the dead default deserves a fix (fail-loud: either honor the default or refuse skew=0 without an explicit setting). | +| rt-2-3 | 2026-11-23 | host+raw + 4 custom daemon runs | BLOCKED | — | `20261123T071048` | **REFUTED** — the plan's auth-mode confusion exposure no longer exists: (a) CLI typo `-listenerAuthMode rawy` + token: the mode is INFERRED from the credential (auth raw, running); (a2) same typo, no credential: exit 64 ("listener auth raw mode requires a token") — fails closed; (b) `LISTENER_AUTH_MODE=unsupported`: ignored, credential keeps auth on; (c) unreadable `LISTENER_RAW_TOKEN_FILE`: exit 64 — fails closed. Residual: the CLI typo is silently treated as unset (only the startup print shows the resolved mode). plan row amended. | +| rt-2-4 | 2026-11-23 | host+raw+read-cred (+admin token host-side) | CONFIRMED | S3 regression gate | `20261123T064029` | the full 401/403 grid holds over both surfaces and matches docs/security.md's verification table: HTTP metrics none/read/admin = 401/200/200; /debug/pprof/ on the metrics listener = 401/403/404 (the admin credential passes the gate; pprof is not served on this listener — class nuance, not a mismatch); gRPC get = fail/ok/ok, set-poll-frequency = PermissionDenied/ok. | +| rt-2-5 | 2026-11-23 | host+raw+read-cred | BLOCKED | — | `20261123T054809` | all 9 near-miss presentations 401 (query token, duplicates, Bearer alone, Basic, lowercase bearer, padded, bare, empty); only exact `Bearer ` gets 200. **Premise amended**: the scheme is case-SENSITIVE (exact `Bearer ` prefix, listenerauth.go:43) — the plan row's "scheme case-insensitive" is wrong; a future relaxation flips the lowercase cell. | +| rt-2-8 | 2026-11-23 | host+raw+read-cred | CONFIRMED | S3 (documented) | `20261123T083122` | on-path (docker0) capture of an authenticated scrape reads the raw bearer in cleartext (3 occurrences in a 12 s pcap) — no TLS by default; TLS proxy is the only mitigation. No HMAC key material on the wire (raw row: there is none). | +| rt-9-3 | 2026-11-23 | host+off (loopback listener) + route_localnet=1 + kube-proxy-style DNAT | BLOCKED | — | `20261123T072059` | the CVE-2020-8558-class defense holds on Ubuntu/Docker: a co-tenant routed through the misconfig (172.17.0.1:9088 --DNAT--> 127.0.0.1:9088) gets NO scrape (HTTP 000 — connection closed by the loopback-peer check, pkg/listeners listeners.go:422); the rate-limited reject line logs once per minute (cmd/xtcp2/reject_log.go). Note: on plain Docker (no kube-proxy NAT), route_localnet alone does not reach a 127.00.0.1-bound listener — the DNAT (installed host-side by the scenario) is the CVE shape. | + ## Notes - Severity scale: docs/redteam-plan.md §severity. diff --git a/vagrant/scenarios/rt-1-1-unauth-scrape.sh b/vagrant/scenarios/rt-1-1-unauth-scrape.sh index 200e97d04..eb88378da 100644 --- a/vagrant/scenarios/rt-1-1-unauth-scrape.sh +++ b/vagrant/scenarios/rt-1-1-unauth-scrape.sh @@ -35,6 +35,8 @@ 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/deploy.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" @@ -45,15 +47,9 @@ 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 xtcp2-redteam' -vm_push victim "$XTCP2_OCI_TAR" xtcp2-redteam/xtcp2-oci.tar.gz -vm_push victim "$XTCP2_TCP_STRESS_TAR" xtcp2-redteam/xtcp2-tcp-stress.tar.gz -vm_provision victim +# Boot the victim VM unprovisioned, deliver the image tarballs, provision the +# matrix row (lib/deploy.sh). +xtcp2_deploy victim # Baseline: the daemon answers locally and the catcher sees records before any # attack. AUTH=off binds 127.0.0.1 (200); auth rows bind :9088 and answer diff --git a/vagrant/scenarios/rt-1-2-grpc-unauth-stream.sh b/vagrant/scenarios/rt-1-2-grpc-unauth-stream.sh new file mode 100644 index 000000000..d1927edc7 --- /dev/null +++ b/vagrant/scenarios/rt-1-2-grpc-unauth-stream.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-1-2-grpc-unauth-stream.sh — RT-1, scenario 2: +# unauthenticated record streaming over gRPC (docs/redteam-plan.md RT-1). +# +# Question: can a remote peer (the attacker VM, one private-network hop away) +# stream the full XtcpFlatRecord stream — peer addresses, container ids, +# uplink NIC/LLDP — without credentials, via the repo's own client? +# +# EXPECT=BLOCKED (default row: §29 prod shape host+raw, plain attacker): the +# tokenless xtcp2client stream is refused (gRPC Unauthenticated). The plan +# doc's "default: stream succeeds" column predates the listener-security +# hardening (see findings.md, the premise-shift row). +# +# Flip (the credential-gated stream is the exfil premise of RT-3/RT-11 +# tier 2 — a read token streams everything): +# XTCP2_AUTH=raw XTCP2_ATTACKER=read-cred XTCP2_EXPECT=CONFIRMED \ +# nix run .#redteam-rt-1-2 +set -euo pipefail + +# This scenario's premise is the §29 prod shape (auth on); an env override +# still wins. +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-2: evidence in $RT_EVIDENCE" + +# Both VMs: the gRPC vantage is the attacker VM's xtcp2client. +xtcp2_deploy victim attacker + +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +# Attack: one FlatRecords stream from the attacker VM, 8s budget. +# -format json keeps the records in the evidence (the question is access; +# ~60 rec/s × 8 s ≈ 500 KiB, gitignored). The timeout bounds the remote +# client; `timeout` cannot wrap vm_exec (a shell function, not a binary). +CLIENT=/opt/xtcp2-redteam/bin/xtcp2client +GRPC_ARGS=(-network tcp -target 192.168.142.10 -port 8889 -format json -d 11) +if [ "$XTCP2_ATTACKER" = read-cred ] || [ "$XTCP2_ATTACKER" = admin ]; then + xtcp2_victim_read_token + GRPC_ARGS+=(-auth-token "$RT_READ_TOKEN") +fi +vm_exec attacker "timeout 8 $CLIENT ${GRPC_ARGS[*]} -workers 1" \ + >"$RT_EVIDENCE/xtcp2client.log" 2>&1 || true +cat "$RT_EVIDENCE/xtcp2client.log" | tail -5 +unauth="$(grep -ciE 'unauthenticated|permission denied|401|access' "$RT_EVIDENCE/xtcp2client.log" || true)" +records="$(grep -cE '^\{' "$RT_EVIDENCE/xtcp2client.log" || true)" + +if [ "$records" -gt 0 ]; then + ok "remote peer streamed XtcpFlatRecords ($records record lines)" +elif [ "$unauth" -gt 0 ]; then + ok "remote peer's tokenless stream refused (unauthenticated)" +elif [ -s "$RT_EVIDENCE/xtcp2client.log" ]; then + ok "remote peer got no stream and no auth handshake (unreachable: loopback-only gRPC)" +else + not_ok "no client output at all (harness failure — see evidence)" +fi +victim_still_reporting_tap + +if [ "$records" -gt 0 ]; then + actual=CONFIRMED +elif [ -s "$RT_EVIDENCE/xtcp2client.log" ]; then + actual=BLOCKED # refused, unauthenticated, or unreachable — no records leaked +else + actual=NA +fi +finish rt-1-2 "$actual" diff --git a/vagrant/scenarios/rt-1-5-health-disclosure.sh b/vagrant/scenarios/rt-1-5-health-disclosure.sh new file mode 100644 index 000000000..ccb459155 --- /dev/null +++ b/vagrant/scenarios/rt-1-5-health-disclosure.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-1-5-health-disclosure.sh — RT-1, scenario 5: +# health/ready endpoints without credentials (docs/redteam-plan.md RT-1). +# +# Question: can a co-tenant container learn daemon readiness (liveness) for +# free, without a credential? The documented design: health is read-classified +# and rides the same listener as metrics, with NO unauthenticated exception — +# so with auth on, /healthz and /readyz are 401. The K8s-probe tradeoff +# (probes need the token too) is the documented cost of that choice. +# +# EXPECT=BLOCKED (default row: §29 prod shape host+raw, plain attacker): +# both /healthz and /readyz answer 401 to a tokenless co-tenant. +# +# Flip (the tradeoff is real — read credential gets both): +# XTCP2_ATTACKER=read-cred XTCP2_EXPECT=CONFIRMED nix run .#redteam-rt-1-5 +set -euo pipefail + +# This scenario's premise is the §29 prod shape (auth on); an env override +# still wins. +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-5: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim + +# Baseline: the daemon answers locally (auth rows bind :9088 → 401 there). +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/healthz | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +# Attack: tokenless co-tenant reads both probe paths via the docker0 gateway. +GW=172.17.0.1 +HDR="" +HDR="" +if [ "$XTCP2_ATTACKER" = read-cred ] || [ "$XTCP2_ATTACKER" = admin ]; then + xtcp2_cotenant_read_token + HDR="-H \"Authorization: Bearer $RT_READ_TOKEN\"" +fi +leaked=0 +for path in healthz readyz; do + code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' $HDR http://$GW:9088/$path")" || code=000 + echo "rt-1-5: co-tenant /$path -> HTTP $code" + vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 $HDR http://$GW:9088/$path" \ + >"$RT_EVIDENCE/cotenant-$path.txt" || true + case "$code" in + 200) + ok "co-tenant read /$path without a credential barrier (HTTP 200)" + leaked=$((leaked + 1)) + ;; + 401 | 403) ok "co-tenant /$path rejected (HTTP $code — no unauth health exception)" ;; + 000) ok "co-tenant cannot reach /$path (loopback-only binding holds)" ;; + *) not_ok "co-tenant /$path returned HTTP $code" ;; + esac +done +victim_still_reporting_tap + +# Verdict: CONFIRMED only if BOTH probe paths leaked readiness without creds. +case "$leaked" in + 2) actual=CONFIRMED ;; + 0) actual=BLOCKED ;; + *) actual=NA ;; +esac +finish rt-1-5 "$actual" diff --git a/vagrant/scenarios/rt-1-6-fingerprint.sh b/vagrant/scenarios/rt-1-6-fingerprint.sh new file mode 100644 index 000000000..3c55a0110 --- /dev/null +++ b/vagrant/scenarios/rt-1-6-fingerprint.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-1-6-fingerprint.sh — RT-1, scenario 6: version/flag +# fingerprint (docs/redteam-plan.md RT-1). +# +# Question: what can a remote peer learn about the daemon binary (flavor, +# enrichers, listener layout, version) from a metrics scrape? The fingerprint +# is inherent to the metrics surface (xtcp2_listener_active{...}, +# compiledInEnrichers, go runtime families); the question is only whether it +# is reachable without a credential. +# +# EXPECT=BLOCKED (default row: §29 prod shape host+raw, plain attacker): the +# tokenless scrape body carries no xtcp_/xtcp2_/go_ families — nothing beyond +# the auth error. +# +# Flip (the fingerprint is inherent — a read credential reads it all): +# XTCP2_ATTACKER=read-cred XTCP2_EXPECT=CONFIRMED nix run .#redteam-rt-1-6 +set -euo pipefail + +# This scenario's premise is the §29 prod shape (auth on); an env override +# still wins. +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-6: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim + +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +# Attack: scrape from the co-tenant; inventory what the body discloses. +PROM="$(xtcp2_cotenant_prom_url)" +HDR="" +HDR="" +if [ "$XTCP2_ATTACKER" = read-cred ] || [ "$XTCP2_ATTACKER" = admin ]; then + xtcp2_cotenant_read_token + HDR="-H \"Authorization: Bearer $RT_READ_TOKEN\"" +fi +code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' $HDR $PROM")" || code=000 +vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 $HDR $PROM" \ + >"$RT_EVIDENCE/cotenant-scrape.txt" || true +echo "rt-1-6: co-tenant scrape HTTP $code" + +families=0 +if grep -qE '^(xtcp|go_|process_)' "$RT_EVIDENCE/cotenant-scrape.txt"; then + families=1 +fi + +case "$code" in + 200) + if [ "$families" = 1 ]; then + # The fingerprint surface, quoted into the findings row: listener + # layout + compiled-in enrichers + runtime families. + grep -E '^(xtcp2_listener_active|xtcp_gauges\{function="InitPromethus")' \ + "$RT_EVIDENCE/cotenant-scrape.txt" | head -8 \ + >"$RT_EVIDENCE/fingerprint.txt" || true + ok "co-tenant read the fingerprint surface (200, xtcp/go families present)" + else + not_ok "co-tenant got 200 but no fingerprint families in the body" + fi + ;; + 401 | 403) + if [ "$families" = 0 ]; then + ok "co-tenant scrape rejected (HTTP $code) with no fingerprint leakage" + else + not_ok "co-tenant got $code but the body leaked fingerprint families" + fi + ;; + 000) + ok "co-tenant cannot reach the metrics listener (loopback-only binding holds)" + ;; + *) + not_ok "co-tenant scrape returned HTTP $code" + ;; +esac +victim_still_reporting_tap + +case "$code" in + 200) [ "$families" = 1 ] && actual=CONFIRMED || actual=NA ;; + 401 | 403 | 000) [ "$families" = 0 ] && actual=BLOCKED || actual=CONFIRMED ;; + *) actual=NA ;; +esac +finish rt-1-6 "$actual" diff --git a/vagrant/scenarios/rt-11-1-scrape-starvation.sh b/vagrant/scenarios/rt-11-1-scrape-starvation.sh new file mode 100644 index 000000000..5bdfef8d0 --- /dev/null +++ b/vagrant/scenarios/rt-11-1-scrape-starvation.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-11-1-scrape-starvation.sh — RT-11, tier 1: +# scrape-slot starvation from a co-tenant container +# (docs/redteam-plan.md RT-11; the plan's headline monitoring-blindness row). +# +# The plan doc's mechanism: the Prometheus handler runs with +# promMaxRequestsInFlight = 10 (cmd/xtcp2/xtcp2.go:51), so an attacker +# holding 10 scrape slots with slow reads leaves the real scraper 503ing +# forever while collection and delivery carry on. +# +# EXPECT=BLOCKED — REFUTED AT HARNESS BUILD (2026-11-23, findings.md). The +# cap exists (client_golang v1.25.0 inFlightSem wraps reg.Gather through the +# response write), but a slow-reading co-tenant cannot hold it: /metrics is +# ~18 KiB, well under the kernel send buffer (autotunes to ~87 KiB), so the +# handler's write completes into the kernel even against a closed receive +# window (verified: Send-Q stuck at 14415 with the slot already released). +# The scenario pins the refutation with BOTH holder mechanisms so a future +# regression in either (bigger bodies, smaller buffers) flips it. +# +# attempt 1 — rate-limited curl readers (the plan doc's mechanism) +# attempt 2 — SO_RCVBUF=2048 sockets that never read (the obvious +# workaround; needs python3 in the attacker container) +set -euo pipefail + +# This scenario's premise needs authorized scrapes, so its default row is the +# §29 prod shape (an env override still wins). +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-11-1: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim + +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +PROM="$(xtcp2_cotenant_prom_url)" +# The attacker needs an authorized scrape to occupy slots: read-cred tier +# mounts the token; the plain tier reads the victim's token host-side (the +# plan's point is that a read credential holder — which the fleet scraper is — +# can attempt this legitimately). +if [ "$XTCP2_ATTACKER" = plain ]; then + xtcp2_victim_read_token +else + xtcp2_cotenant_read_token +fi +token="$RT_READ_TOKEN" +HDR="-H \"Authorization: Bearer $token\"" + +# Pre-attack: an authorized scrape works, and the body is small (the number +# that makes the whole attack moot — recorded for the findings row). +body_bytes="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 $HDR $PROM | wc -c")" || body_bytes=0 +echo "rt-11-1: authorized /metrics body is $body_bytes bytes" +if [ "$body_bytes" -gt 0 ]; then + ok "authorized scrape before the attack (${body_bytes}B body)" +else + not_ok "authorized scrape before the attack returned an empty body" +fi + +RT_PROBE_CODE="" +probe_11th() { # probe_11th : sets RT_PROBE_CODE to the 11th scrape's + # HTTP code (a global: the description echo must not ride the return path) + local desc="$1" code + code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' $HDR $PROM")" || code=000 + echo "rt-11-1: $desc -> 11th scrape HTTP $code" + RT_PROBE_CODE="$code" +} + +# --- attempt 1: 10 rate-limited readers (the plan doc's mechanism) ---------- +holders=() +kill_holders() { + local pid + for pid in "${holders[@]:-}"; do + kill "$pid" 2>/dev/null || true + done + holders=() +} +trap 'kill_holders || true' EXIT +for i in $(seq 1 10); do + vm_exec victim "sudo docker exec rt-attacker curl -s --limit-rate 500 -m 45 $HDR $PROM -o /dev/null" \ + >>"$RT_EVIDENCE/holder-rate-$i.log" 2>&1 & + holders+=("$!") +done +sleep 4 +probe_11th 'rate-limited holders' +code_rate="$RT_PROBE_CODE" +case "$code_rate" in + 503) ok "attempt 1: 11th scrape 503s — the documented starvation HOLDS" ;; + 200) ok "attempt 1: 11th scrape still 200 (rate-limited readers hold no slot)" ;; + *) not_ok "attempt 1: 11th scrape returned HTTP $code_rate" ;; +esac +kill_holders +wait 2>/dev/null || true + +# --- attempt 2: 10 SO_RCVBUF sockets that never read ------------------------- +vm_push victim "$RT_LIB_DIR/hold.py" /tmp/hold.py +vm_exec victim 'sudo docker cp /tmp/hold.py rt-attacker:/tmp/hold.py' +vm_exec victim 'sudo docker exec rt-attacker bash -c "command -v python3 >/dev/null || { apt-get update -qq >/dev/null && apt-get install -y -qq python3 >/dev/null; }"' +for i in $(seq 1 10); do + vm_exec victim "sudo docker exec -d rt-attacker python3 /tmp/hold.py $PROM $token 45" +done +sleep 4 +probe_11th 'SO_RCVBUF holders' +code_rcv="$RT_PROBE_CODE" +case "$code_rcv" in + 503) ok "attempt 2: 11th scrape 503s — never-reading sockets DO starve the slots" ;; + 200) ok "attempt 2: 11th scrape still 200 (response fits the send buffer; slot freed)" ;; + *) not_ok "attempt 2: 11th scrape returned HTTP $code_rcv" ;; +esac + +# The RT-11 invariant either way: collection and delivery carry on. +victim_still_reporting_tap + +# Recovery: after the holders are gone the scrape surface answers. +sleep 42 # let the 45s holders expire +codeafter="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' $HDR $PROM")" || codeafter=000 +if [ "$codeafter" = 200 ]; then + ok "scrape surface answers after the holders are gone (HTTP 200)" +else + not_ok "scrape surface did not recover (HTTP $codeafter)" +fi +victim_still_reporting_tap +trap - EXIT + +if [ "$code_rate" = 503 ] || [ "$code_rcv" = 503 ]; then + actual=CONFIRMED # either holder mechanism starves the slots +elif [ "$code_rate" = 200 ] && [ "$code_rcv" = 200 ]; then + actual=BLOCKED # refuted: neither mechanism holds a slot +else + actual=NA +fi +finish rt-11-1 "$actual" diff --git a/vagrant/scenarios/rt-2-1-brute-force-pacing.sh b/vagrant/scenarios/rt-2-1-brute-force-pacing.sh new file mode 100644 index 000000000..d7b91e72a --- /dev/null +++ b/vagrant/scenarios/rt-2-1-brute-force-pacing.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-1-brute-force-pacing.sh — RT-2, tier 1: raw-token +# online brute force (docs/redteam-plan.md RT-2). +# +# Premise checks (plan row rt-2-1), on the §29 prod shape (auth=raw): +# - wrong tokens are 401 with the context-aware failure jitter applied +# (20–200 ms, pkg/listenerauth/listenerauth.go:48) — no lockout, no +# rate limit, no cap on connections; +# - a valid token keeps working after sustained failures (no lockout); +# - the measured attempts/sec ceiling, serial and parallel — the number +# that bounds token-entropy decisions (findings.md). +# +# AMENDED 2026-11-23: the plan row's "assert jitter applied (xtcp_counts +# auth-failure metrics)" is wrong — the auth surface exports NO auth-failure +# counters (the /metrics families carry none). The jitter is verified +# directly: by timing. +# +# EXPECT=BLOCKED: brute force is infeasible only via token entropy (S3, +# mitigation = ops) — the BLOCKED outcome is "no credential cracked within +# the scenario's sample", with the pacing numbers recorded. +set -euo pipefail + +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-2-1: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +xtcp2_victim_read_token +token="$RT_READ_TOKEN" +PROM="http://172.17.0.1:9088/metrics" # the co-tenant vantage + +# All probes run inside the attacker container (the co-tenant vantage): +# brutepace.sh reports its numbers as sh-compatible key=value lines. +vm_push victim "$RT_LIB_DIR/brutepace.sh" /tmp/brutepace.sh >/dev/null +vm_exec victim 'sudo docker cp /tmp/brutepace.sh rt-attacker:/tmp/brutepace.sh' +scrape() { # scrape : run brutepace in the container + vm_exec victim "sudo docker exec rt-attacker sh /tmp/brutepace.sh $PROM $token $*" +} + +# --- 1. failure jitter: wrong tokens must land in [20,200]ms ---------------- +scrape jitter >"$RT_EVIDENCE/jitter.txt" 2>&1 +jitter_min="$(awk -F= '/^fail_min=/{print $2}' "$RT_EVIDENCE/jitter.txt")" +jitter_max="$(awk -F= '/^fail_max=/{print $2}' "$RT_EVIDENCE/jitter.txt")" +echo "rt-2-1: failure jitter ${jitter_min}..${jitter_max}ms over $(awk -F= '/^fail_n=/{print $2}' "$RT_EVIDENCE/jitter.txt") wrong tokens" +if awk -v lo="$jitter_min" -v hi="$jitter_max" 'BEGIN{exit !(lo>=20 && hi<=200)}'; then + ok "failure jitter ${jitter_min}..${jitter_max}ms within the configured 20-200ms" +else + not_ok "failure jitter ${jitter_min}..${jitter_max}ms outside the configured 20-200ms" +fi + +# --- 2. no lockout: the right token works after sustained failures ---------- +scrape hammer 150 >"$RT_EVIDENCE/hammer.txt" 2>&1 +locked="$(awk -F= '/^last_ok=/{print $2}' "$RT_EVIDENCE/hammer.txt")" +echo "rt-2-1: after 150 wrong tokens, the valid token got HTTP $locked" +if [ "$locked" = 200 ]; then + ok "no lockout: valid token still accepted after 150 failures" +else + not_ok "valid token rejected after 150 failures (HTTP $locked)" +fi +victim_still_reporting_tap + +# --- 3. guesses/sec ceiling: serial then parallel (10 workers) -------------- +scrape rate 60 1 >"$RT_EVIDENCE/rate-serial.txt" 2>&1 +serial=$(awk -F= '/^guesses_per_s=/{print $2}' "$RT_EVIDENCE/rate-serial.txt") +scrape rate 60 10 >"$RT_EVIDENCE/rate-parallel.txt" 2>&1 +parallel=$(awk -F= '/^guesses_per_s=/{print $2}' "$RT_EVIDENCE/rate-parallel.txt") +echo "rt-2-1: measured ceiling ${serial}/s serial, ${parallel}/s with 10 workers (findings.md)" +if awk -v s="$serial" 'BEGIN{exit !(s>0)}' && awk -v p="$parallel" -v s="$serial" 'BEGIN{exit !(p>=s)}'; then + ok "attempts/sec measured: ${serial} serial, ${parallel} parallel (entropy, not pacing, must hold)" +else + not_ok "attempts/sec measurement failed (serial=$serial parallel=$parallel — see evidence)" +fi +victim_still_reporting_tap + +# --- 4. daemon health: no 5xx, no crash, still collecting ------------------- +daemon="$(vm_exec victim "sudo docker inspect rt-xtcp2 --format '{{.State.Status}}'")" +if [ "$daemon" = running ]; then + ok "daemon still running after the hammer (no crash, no 5xx lockout)" +else + not_ok "daemon state after the hammer: $daemon" +fi +victim_still_reporting_tap + +# No credential cracked: the sampled guesses were wrong by construction, so +# BLOCKED = the pacing defense held and nothing leaked. +finish rt-2-1 BLOCKED diff --git a/vagrant/scenarios/rt-2-2-hmac-replay.sh b/vagrant/scenarios/rt-2-2-hmac-replay.sh new file mode 100644 index 000000000..6c1da2ff9 --- /dev/null +++ b/vagrant/scenarios/rt-2-2-hmac-replay.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-2-hmac-replay.sh — RT-2: HMAC token capture and +# replay (docs/redteam-plan.md RT-2, plan row rt-2-2). +# +# AMENDED 2026-11-23 (verified): the plan row's "token valid for +# previous/current/next minute bucket" does NOT hold for the provisioned +# shape — the effective skew is 0 (exact minute). pkg/listenerauth's +# newWithClock sets a.skew = DefaultSignedTokenSkewMinutes (1) and then +# immediately overwrites it with cfg.GetSignedTokenSkewMinutes(), which is +# 0 when the proto field is unset — so the named default is unreachable and +# the window is exact unless signedTokenSkewMinutes is in the spec. The +# mint-minute replay still works; the plan's replay analysis stands with +# the corrected window. +# +# Flow (minute-boundary deterministic — every step is guarded to land at a +# known offset within the UTC minute): +# 1. fresh-minute guard, mint (SignedToken: HMAC-SHA256(key, utc-minute)) +# 2. scrape with the minted token -> 200 (the fleet client's view) +# 3. on-path capture of the bearer from a docker0 pcap +# 4. replay immediately (same minute) -> 200 — CONFIRMED (documented) +# 5. wait to mint-minute+2, replay -> 401 (outside the window) +# 6. a previous-minute token -> 401 (the skew-0 pin: a future regression +# to the ±1-minute default flips this cell) +# 7. a fresh mint still works (the credential was not revoked by replays) +set -euo pipefail + +: "${XTCP2_AUTH:=hmac}" +: "${XTCP2_ATTACKER:=read-cred}" # the scrape must carry a real token +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/deploy.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-2-2: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap +PROM="http://172.17.0.1:9088/metrics" + +# mint : SignedToken(key, utc-minute + delta) — one line: the +# payload must survive vm_exec_root's %q quoting layer. +mint() { # mint + vm_exec_root victim "python3 -c \"import hmac,hashlib,base64,time,pathlib; key=pathlib.Path(\\\"/opt/xtcp2-redteam/secrets/read\\\").read_text().strip(); minute=int(time.time())//60+$1; mac=hmac.new(key.encode(),str(minute).encode(),hashlib.sha256).digest(); print(base64.urlsafe_b64encode(mac).rstrip(b\\\"=\\\").decode())\"" +} + +# fresh-minute guard: land the mint in seconds 05..45 of a UTC minute. +sec=$(( $(date -u +%s) % 60 )) +if [ "$sec" -lt 5 ] || [ "$sec" -gt 45 ]; then + wait=$(( 65 - sec )) + echo "rt-2-2: minute-boundary guard: sleeping ${wait}s (second :$sec)" + sleep "$wait" +fi + +# --- 1. the mint + the fleet client's scrape -------------------------------- +MINT_MINUTE=$(( $(date -u +%s) / 60 )) +HMAC_TOKEN="$(mint 0)" || xtcp2_die 'could not mint the HMAC token (python3 on the VM?)' +echo "rt-2-2: minted minute ${MINT_MINUTE}, token ${HMAC_TOKEN:0:8}…" +vm_exec_root victim 'apt-get install -y -qq tcpdump >/dev/null 2>&1 || true' +vm_exec_root victim 'rm -f /tmp/rt2-2.pcap' +vm_exec_root victim 'timeout 8 tcpdump -i docker0 -A -s 0 -w /tmp/rt2-2.pcap port 9088 >/dev/null 2>&1 &' +sleep 1 +code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $HMAC_TOKEN' $PROM")" +echo "rt-2-2: minted token scrape -> HTTP $code (second :$(( $(date -u +%s) % 60 )))" +if [ "$code" = 200 ]; then + ok "the minted HMAC token authenticates (the fleet client's view)" +else + not_ok "the minted token was rejected (HTTP $code — see evidence)" +fi + +# --- 2. the on-path capture ------------------------------------------------ +sleep 8 # the 8s tcpdump boundary +vm_exec_root victim 'chmod 0644 /tmp/rt2-2.pcap' +CAPTURED="$(vm_exec_root victim "grep -aoE 'Authorization: Bearer [A-Za-z0-9_-]+' /tmp/rt2-2.pcap | head -1")" +echo "rt-2-2: pcap header line: ${CAPTURED:0:24}…" +if [ -n "$CAPTURED" ]; then + ok "on-path capture reads the HMAC bearer off the wire" +else + not_ok "no Authorization header in the pcap (see evidence)" +fi + +# --- 3. replay 1: same minute (inside the window) -------------------------- +r1="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' -H '$CAPTURED' $PROM")" +echo "rt-2-2: replay in-minute -> HTTP $r1 (second :$(( $(date -u +%s) % 60 )))" +if [ "$r1" = 200 ]; then + ok "replay inside the token's minute succeeds (documented)" +else + not_ok "same-minute replay rejected (HTTP $r1)" +fi +victim_still_reporting_tap + +# --- 4. replay 2: mint-minute+2 (outside the window) ----------------------- +now=$(date -u +%s) +target=$(( (MINT_MINUTE + 2) * 60 + 5 )) +if [ "$target" -le "$now" ]; then + xtcp2_die 'minute guard failed: the run outlived the mint minute — rerun' +fi +sleep $(( target - now )) +r2="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' -H '$CAPTURED' $PROM")" +echo "rt-2-2: replay after the window -> HTTP $r2" +if [ "$r2" = 401 ]; then + ok "replay outside the window is rejected (HTTP 401) — the replay defense holds" +else + not_ok "replay outside the window got HTTP $r2 (want 401)" +fi + +# --- 5. the skew-0 pin: a previous-minute token is not accepted ------------- +PREV="$(mint -1)" || xtcp2_die 'could not mint the previous-minute token' +r3="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $PREV' $PROM")" +echo "rt-2-2: previous-minute token -> HTTP $r3" +if [ "$r3" = 401 ]; then + ok "previous-minute token rejected (effective skew is 0; the ±1-minute plan premise is amended)" +else + not_ok "previous-minute token accepted (HTTP $r3 — skew is NOT 0; amend this scenario)" +fi + +# --- 6. a fresh mint still works (no credential lockout from replays) ------- +NEXT="$(mint 0)" || xtcp2_die 'could not mint the current token' +r4="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $NEXT' $PROM")" +if [ "$r4" = 200 ]; then + ok "a fresh mint still authenticates (no lockout from replays)" +else + not_ok "fresh mint rejected (HTTP $r4)" +fi +victim_still_reporting_tap + +vm_exec_root victim 'base64 /tmp/rt2-2.pcap' 2>/dev/null | grep -v '^\[fog\]' >"$RT_EVIDENCE/rt2-2.pcap.b64" \ + && vm_exec_root victim 'rm -f /tmp/rt2-2.pcap' + +# CONFIRMED: the in-minute replay worked (documented); the out-of-window and +# previous-minute pins catch a skew regression. +finish rt-2-2 CONFIRMED diff --git a/vagrant/scenarios/rt-2-3-auth-mode-confusion.sh b/vagrant/scenarios/rt-2-3-auth-mode-confusion.sh new file mode 100644 index 000000000..fd2e4d1d1 --- /dev/null +++ b/vagrant/scenarios/rt-2-3-auth-mode-confusion.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-3-auth-mode-confusion.sh — RT-2: the auth-mode +# confusion footguns (docs/redteam-plan.md RT-2, plan row rt-2-3). +# +# The plan row's premise: a typo'd mode flag, an unsupported env mode, or an +# unreadable _FILE leaves the daemon unauthenticated (documented-broken, +# EXPECT=CONFIRMED with a hardening issue). +# +# REFUTED 2026-11-23 (verified on the VM): the listener-security-hardening +# made every confusion path fail closed — +# (a) -listenerAuthMode rawy (CLI typo) + a token: the typo equals unset, +# the mode is INFERRED from the credential (auth raw), the daemon +# serves authenticated; +# (a2) the same typo with no credential anywhere: exit 64 ("listener auth +# raw mode requires a token") — refuses to start; +# (b) LISTENER_AUTH_MODE=unsupported (invalid env) + a token: the invalid +# value is ignored, the credential infers raw — authenticated; +# (c) LISTENER_RAW_TOKEN_FILE=: exit 64 — refuses to start. +# +# So EXPECT=BLOCKED: no confusion path yields an unauthenticated daemon. +# The residual gap (worth the hardening issue): the CLI typo is silently +# treated as unset — the daemon tells the operator only in the startup +# print, not at the flag. +set -euo pipefail + +: "${XTCP2_AUTH:=raw}" +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-2-3: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +victim_still_reporting_tap +xtcp2_victim_read_token +token="$RT_READ_TOKEN" + +# The confusion probes run as EXTRA daemon containers next to the prod-shape +# one (the default-listener shape: UDS metrics, env/flag credentials) — the +# daemon image is scratch, so every assertion reads logs + docker inspect, +# never exec. +CAPS="--cap-add=NET_ADMIN --cap-add=SYS_ADMIN --cap-add=SYS_CHROOT" +cleanup() { + vm_exec victim 'sudo docker rm -f rt2a rt2b rt2c rt2d >/dev/null 2>&1 || true' +} +trap 'cleanup || true' EXIT +cleanup + +start() { # start : docker args AND the command (docker run + # takes its options before the image, the daemon's flags after it) + local name="$1" tail="$2" + vm_exec victim "sudo docker run -d --name $name $CAPS $tail" \ + >>"$RT_EVIDENCE/$name.run" 2>&1 + sleep 4 +} + +state() { # state : "running" or "exited:" + local st ec + st="$(vm_exec victim "sudo docker inspect $1 --format '{{.State.Status}}'")" + ec="$(vm_exec victim "sudo docker inspect $1 --format '{{.State.ExitCode}}'")" + if [ "$st" = running ]; then + echo "running" + else + echo "exited:$ec" + fi +} + +authed() { # authed : 1 when the log line says "(auth raw)" + vm_exec victim "sudo docker logs $1 2>&1 | grep -c '(auth raw)'" || echo 0 +} + +# --- (a) CLI typo + a token: the typo equals unset, the mode is inferred --- +start rt2a "-e LISTENER_RAW_TOKEN=$token xtcp2:latest -listenerAuthMode rawy" +vm_exec victim "sudo docker logs rt2a 2>&1" >"$RT_EVIDENCE/rt2a.log" 2>&1 +s="$(state rt2a)" +a="$(authed rt2a)" +echo "rt-2-3: (a) CLI typo + token -> $s, auth-raw lines: $a" +if [ "$s" = running ] && [ "$a" -ge 1 ]; then + ok "(a) CLI typo + token: daemon stays authenticated (mode inferred from the credential)" +else + not_ok "(a) CLI typo + token: daemon $s auth-raw:$a — see evidence" +fi + +# --- (a2) the same typo with NO credential: refuse to start (exit 64) ----- +start rt2b "xtcp2:latest -listenerAuthMode rawy" +vm_exec victim "sudo docker logs rt2b 2>&1" >"$RT_EVIDENCE/rt2b.log" 2>&1 +s="$(state rt2b)" +echo "rt-2-3: (a2) CLI typo, no credential -> $s" +if [ "$s" = "exited:64" ]; then + ok "(a2) CLI typo, no credential: daemon refuses to start (exit 64, fail closed)" +else + not_ok "(a2) CLI typo, no credential: daemon $s (want exited:64 — see evidence)" +fi + +# --- (b) invalid env mode + a token: the invalid value is ignored -------- +start rt2c "-e LISTENER_AUTH_MODE=unsupported -e LISTENER_RAW_TOKEN=$token xtcp2:latest" +vm_exec victim "sudo docker logs rt2c 2>&1" >"$RT_EVIDENCE/rt2c.log" 2>&1 +s="$(state rt2c)" +a="$(authed rt2c)" +echo "rt-2-3: (b) invalid env mode + token -> $s, auth-raw lines: $a" +if [ "$s" = running ] && [ "$a" -ge 1 ]; then + ok "(b) invalid env mode + token: ignored; the credential keeps auth on" +else + not_ok "(b) invalid env mode + token: daemon $s auth-raw:$a — see evidence" +fi + +# --- (c) unreadable _FILE: refuse to start (exit 64) ---------------------- +start rt2d "-e LISTENER_RAW_TOKEN_FILE=/run/secrets/nosuchfile xtcp2:latest" +vm_exec victim "sudo docker logs rt2d 2>&1" >"$RT_EVIDENCE/rt2d.log" 2>&1 +s="$(state rt2d)" +echo "rt-2-3: (c) unreadable token file -> $s" +if [ "$s" = "exited:64" ]; then + ok "(c) unreadable token file: daemon refuses to start (exit 64, fail closed)" +else + not_ok "(c) unreadable token file: daemon $s (want exited:64 — see evidence)" +fi + +# The one daemon that runs (a/b) must not be unauthenticated on the wire: +# with no token on the prod listener the scrape 401s (the default-listener +# shape (a) uses the SAME token). +victim_still_reporting_tap +cleanup +trap - EXIT + +# BLOCKED = no confusion path produced an unauthenticated daemon. +finish rt-2-3 BLOCKED diff --git a/vagrant/scenarios/rt-2-4-read-admin-split.sh b/vagrant/scenarios/rt-2-4-read-admin-split.sh new file mode 100644 index 000000000..285ef2f00 --- /dev/null +++ b/vagrant/scenarios/rt-2-4-read-admin-split.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-4-read-admin-split.sh — RT-2, tier 1: the read/admin +# split enforced over both surfaces (docs/redteam-plan.md RT-2). +# +# The 401/403 grid on the §29 prod shape (auth=raw, both listeners +# tokenFile+adminTokenFile): a read credential must reach read methods and +# 403/PermissionDenied on admin ones; no credential must be 401 everywhere. +# HTTP side: /metrics (read), /debug/pprof/ (admin — not served on this +# listener: read=403 at the gate, admin=404 past it). gRPC side: +# ConfigService.get (read) and set-poll-frequency (admin) via xtcp2ctl. +set -euo pipefail + +: "${XTCP2_AUTH:=raw}" +: "${XTCP2_ATTACKER:=read-cred}" # the grid presents the read credential +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/deploy.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-2-4: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim attacker +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +xtcp2_cotenant_read_token # read-cred tier: the read token as the co-tenant sees it +co_read="$RT_READ_TOKEN" +admin_token="$(vm_exec_root victim 'cat /opt/xtcp2-redteam/secrets/admin')" +[ -n "$admin_token" ] || xtcp2_die 'no admin token on the victim' +PROM="http://172.17.0.1:9088" + +# cotenant : HTTP code of one scrape from the attacker container +cotenant() { + vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $2' $PROM$1" +} +grid_line() { # grid_line + local name="$1" path="$2" wn="$3" wr="$4" wa="$5" cn cr ca + cn="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' $PROM$path")" + cr="$(cotenant "$path" "$co_read")" + ca="$(cotenant "$path" "$admin_token")" + echo "rt-2-4: $name — none:$cn read:$cr admin:$ca (want $wn/$wr/$wa)" \ + | tee -a "$RT_EVIDENCE/grid.txt" + if [ "$cn" = "$wn" ] && [ "$cr" = "$wr" ] && [ "$ca" = "$wa" ]; then + ok "$name grid $wn/$wr/$wa holds" + else + not_ok "$name grid $wn/$wr/$wa BROKEN (got $cn/$cr/$ca)" + fi +} + +# --- HTTP surface ------------------------------------------------------------ +grid_line "GET /metrics (read)" /metrics 401 200 200 +# pprof is the admin path on the metrics listener; it is not served there, so +# the admin credential passes the gate and 404s — the read one 403s at it. +grid_line "GET /debug/pprof/ (admin; unserved here)" /debug/pprof/ 401 403 404 +victim_still_reporting_tap + +# --- gRPC surface (xtcp2ctl drives ConfigService) ----------------------------- +CTL=/opt/xtcp2-redteam/bin/xtcp2ctl +# get is ACCESS_READ; set-poll-frequency is ACCESS_ADMIN (-frequency/-timeout +# are its required args, exactly as it would be invoked in the fleet). The +# tools image lives on the attacker VM (deploy.sh), so the gRPC grid runs +# from there — the split is a server-side behavior, not a vantage behavior. +ctl_run() { # ctl_run [args...]: "ok" or "fail" + local tok="$1" + shift + # xtcp2ctl takes the command first, then the shared flags + vm_exec attacker "$CTL $* -network tcp -target 192.168.142.10 -port 8889 -auth-token '$tok'" \ + >>"$RT_EVIDENCE/xtcp2ctl.log" 2>&1 && echo ok || echo fail +} + +g_none="$(ctl_run a-wrong-token-of-the-right-shape get)" +g_read="$(ctl_run "$co_read" get)" +g_admin="$(ctl_run "$admin_token" get)" +s_read="$(ctl_run "$co_read" set-poll-frequency -frequency 2s -timeout 1s)" +s_admin="$(ctl_run "$admin_token" set-poll-frequency -frequency 2s -timeout 1s)" +echo "rt-2-4: gRPC — get none:$g_none read:$g_read admin:$g_admin; set-poll-frequency read:$s_read admin:$s_admin" \ + | tee -a "$RT_EVIDENCE/grid.txt" + +if [ "$g_read" = ok ] && [ "$g_admin" = ok ] && [ "$s_admin" = ok ]; then + ok "gRPC read methods: read and admin tokens work (get)" +else + not_ok "gRPC read method failed (get none:$g_none read:$g_read admin:$g_admin — see evidence)" +fi +if [ "$s_read" = fail ] && grep -qiE "PermissionDenied" "$RT_EVIDENCE/xtcp2ctl.log"; then + ok "gRPC admin method denied to the read token (PermissionDenied)" +else + not_ok "gRPC admin method NOT denied to the read token (set-poll-frequency read:$s_read)" +fi +if [ "$s_admin" = ok ]; then + ok "gRPC admin method accepts the admin token" +else + not_ok "gRPC admin method rejected the admin token (set-poll-frequency admin:$s_admin)" +fi +victim_still_reporting_tap + +# The split is confirmed when every line held; a future regression to a +# shared credential flips the 403 to 200 and fails CI. +if grep -q "BROKEN" "$RT_EVIDENCE/grid.txt"; then + finish rt-2-4 NA +else + finish rt-2-4 CONFIRMED +fi diff --git a/vagrant/scenarios/rt-2-5-header-edge.sh b/vagrant/scenarios/rt-2-5-header-edge.sh new file mode 100644 index 000000000..61ac19f57 --- /dev/null +++ b/vagrant/scenarios/rt-2-5-header-edge.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-5-header-edge.sh — RT-2, tier 1: Authorization +# header parser edge cases (docs/redteam-plan.md RT-2, plan rows rt-2-5 and +# rt-2-7). +# +# Table-driven: each near-miss presentation of the read token must 401 — +# the token in a URL query, duplicate headers, `Bearer` alone, `Basic`, +# lowercase `bearer`, a padded token, a bare token without scheme. The +# one presentation that must 200 is the exact `Bearer `. +# +# AMENDED 2026-11-23: the plan row's "scheme case-insensitive" is wrong — +# the parser is exact-case (`Bearer ` prefix, pkg/listenerauth/listenerauth.go: +# 43/311), so a lowercase `bearer` is malformed and 401s. The grid pins the +# actual behavior; a future relaxation flips the lowercase cell. +set -euo pipefail + +: "${XTCP2_AUTH:=raw}" +: "${XTCP2_ATTACKER:=read-cred}" # the grid presents the read credential +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-2-5: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +xtcp2_cotenant_read_token +token="$RT_READ_TOKEN" +PROM="http://172.17.0.1:9088/metrics" + +# probe : one table row from the attacker container. +# is a single string of sh-escaped curl arguments (the quotes +# around header values must survive vm_exec's ssh flattening). +probe() { + local name="$1" want="$2" args="$3" code + code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' $args")" + echo "rt-2-5: $name -> $code (want $want)" | tee -a "$RT_EVIDENCE/grid.txt" + if [ "$code" = "$want" ]; then + ok "$name -> $want" + else + not_ok "$name -> $code (want $want)" + fi +} + +# presentation want curl args (quote-escaped) +probe "exact Bearer (the one valid shape)" 200 "-H 'Authorization: Bearer $token' $PROM" +probe "token in URL query" 401 "$PROM?token=$token" +probe "duplicate Authorization headers" 401 "-H 'Authorization: Bearer $token' -H 'Authorization: Bearer $token' $PROM" +probe "Bearer alone (no token)" 401 "-H 'Authorization: Bearer' $PROM" +probe "Basic scheme" 401 "-H 'Authorization: Basic $token' $PROM" +probe "lowercase bearer (scheme is case-sensitive)" 401 "-H 'Authorization: bearer $token' $PROM" +probe "padded token (trailing space)" 401 "-H 'Authorization: Bearer $token ' $PROM" +probe "bare token (no scheme)" 401 "-H 'Authorization: $token' $PROM" +probe "empty header value" 401 "-H 'Authorization;' $PROM" +victim_still_reporting_tap + +# BLOCKED = no presentation except the exact one yields the metrics body. +finish rt-2-5 BLOCKED diff --git a/vagrant/scenarios/rt-2-8-plaintext-capture.sh b/vagrant/scenarios/rt-2-8-plaintext-capture.sh new file mode 100644 index 000000000..3bf4de3d8 --- /dev/null +++ b/vagrant/scenarios/rt-2-8-plaintext-capture.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-2-8-plaintext-capture.sh — RT-2: plaintext transport +# token capture (docs/redteam-plan.md RT-2, plan row rt-2-8). +# +# An on-path attacker (here: the victim VM's host network, the position a +# privileged co-tenant or a compromised docker0 bridge peer holds) captures +# an authenticated scrape and reads the raw bearer token out of the pcap. +# +# EXPECT=CONFIRMED (documented S3): there is no TLS by default — the token +# is visible in cleartext. The mitigation is transport security (a TLS +# proxy), which the app cannot provide itself; the scenario pins that the +# ONLY gap is the transport (nothing app-layer about HMAC keys leaks on a +# raw row — there is no HMAC key to leak). +set -euo pipefail + +: "${XTCP2_AUTH:=raw}" +: "${XTCP2_ATTACKER:=read-cred}" # the scrape must carry a real token +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/deploy.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-2-8: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap +xtcp2_cotenant_read_token +token="$RT_READ_TOKEN" +PROM="http://172.17.0.1:9088/metrics" + +# --- on-path capture: tcpdump on docker0 while the co-tenant scrapes ------- +vm_exec_root victim 'apt-get install -y -qq tcpdump >/dev/null 2>&1 || true' +vm_exec_root victim 'rm -f /tmp/rt2-8.pcap' +vm_exec_root victim 'timeout 12 tcpdump -i docker0 -A -s 0 -w /tmp/rt2-8.pcap port 9088 >/dev/null 2>&1 &' +sleep 1 +vm_exec victim "for i in 1 2 3; do sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -H 'Authorization: Bearer $token' $PROM || true; done" +sleep 10 +vm_exec_root victim 'chmod 0644 /tmp/rt2-8.pcap' + +# --- the read: pull the bearer out of the pcap ------------------------------ +captured="$(vm_exec_root victim "grep -ac 'Authorization: Bearer $token' /tmp/rt2-8.pcap" || true)" +echo "rt-2-8: bearer-token occurrences in the docker0 pcap: $captured" +if [ "$captured" -ge 1 ]; then + ok "on-path capture reads the raw bearer token in cleartext ($captured occurrence(s) — documented; TLS is the only mitigation)" +else + not_ok "bearer token not found in the pcap (see evidence)" +fi + +# --- the app-layer non-leak: the HMAC key never appears (nothing to leak +# on a raw row — pinned so an hmac row regression flips it) ---------------- +key_lines="$(vm_exec_root victim "grep -ac 'HMAC' /tmp/rt2-8.pcap" || true)" +if [ "$key_lines" = 0 ]; then + ok "no HMAC key material on the wire (raw row: there is none)" +else + not_ok "HMAC-looking strings in the pcap — see evidence" +fi +victim_still_reporting_tap + +# Pull the pcap into the evidence dir before the VM's tmp gets recycled. +vm_exec_root victim 'base64 /tmp/rt2-8.pcap' 2>/dev/null | grep -v '^\[fog\]' >"$RT_EVIDENCE/rt2-8.pcap.b64" \ + && vm_exec_root victim 'rm -f /tmp/rt2-8.pcap' + +finish rt-2-8 CONFIRMED diff --git a/vagrant/scenarios/rt-9-1-exposure-grid.sh b/vagrant/scenarios/rt-9-1-exposure-grid.sh new file mode 100644 index 000000000..2401ba536 --- /dev/null +++ b/vagrant/scenarios/rt-9-1-exposure-grid.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-9-1-exposure-grid.sh — RT-9, scenario 1: the +# bridge-vs-host exposure grid (docs/redteam-plan.md RT-9). +# +# Question: from each vantage (co-tenant container on the same docker host; +# attacker VM one private-network hop away; the victim VM's own host), which +# listener addresses answer, per deployment mode (host vs bridge)? The grid +# feeds docs/security.md's listener matrix. +# +# EXPECT=CONFIRMED (default row: host+raw): the listeners are REACHABLE from +# every vantage (that is the documented §29 prod shape — an internet-exposed +# host is gated by auth + the low TTL, not by unreachability). CONFIRMED here +# means "reachable surface confirmed and recorded", not "breach": the auth +# gate itself is rt-1-1's 401 assertion. +# +# Off row (loopback-only listeners): every remote vantage is refused — +# XTCP2_AUTH=off XTCP2_EXPECT=BLOCKED nix run .#redteam-rt-9-1 +set -euo pipefail + +# This scenario's premise is the §29 prod shape (auth on); an env override +# still wins. +: "${XTCP2_AUTH:=raw}" +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/deploy.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-9-1: evidence in $RT_EVIDENCE (MODE=$XTCP2_MODE AUTH=$XTCP2_AUTH)" + +xtcp2_deploy victim attacker + +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +# The grid: three vantages × the metrics listener. Any HTTP answer (200/401/403) +# = reachable; 000 = unreachable. (The auth gate's outcome is rt-1-1's column.) +probe() { # probe + local desc="$1" + shift + local code + code="$("$@" 2>/dev/null)" || code=000 + case "$code" in + 200 | 401 | 403) + ok "$desc: reachable (HTTP $code)" + echo "$desc reachable $code" + ;; + 000) ok "$desc: unreachable (refused/timeout)" ;; + *) + not_ok "$desc: unexpected HTTP $code" + echo "$desc unexpected $code" + ;; + esac +} + +grid="$RT_EVIDENCE/grid.txt" +: >"$grid" + +# vantage 1: the victim VM's own host loopback. +probe "vm-host loopback" vm_exec victim \ + "curl -s -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics" \ + | tee -a "$grid" + +# vantage 2: the co-tenant container via the docker0 gateway. +probe "co-tenant (docker0 gw)" vm_exec victim \ + "sudo docker exec rt-attacker curl -s -m 5 -o /dev/null -w '%{http_code}' http://172.17.0.1:9088/metrics" \ + | tee -a "$grid" + +# vantage 3: the attacker VM across the private network. +probe "attacker VM (private net)" vm_exec attacker \ + "curl -s -m 5 -o /dev/null -w '%{http_code}' http://192.168.142.10:9088/metrics" \ + | tee -a "$grid" + +victim_still_reporting_tap + +# Verdict: CONFIRMED = at least the co-tenant and the remote VM both reached +# the listener (the exposed surface this scenario documents). BLOCKED = every +# remote vantage refused (the off row's loopback-only binding). +reach_cotenant=$(grep -c "co-tenant (docker0 gw) reachable" "$grid" || true) +reach_remote=$(grep -c "attacker VM (private net) reachable" "$grid" || true) +case $((reach_cotenant + reach_remote)) in + 2) actual=CONFIRMED ;; + 0) actual=BLOCKED ;; + *) actual=NA ;; +esac +echo "rt-9-1: grid recorded in $grid" +finish rt-9-1 "$actual" diff --git a/vagrant/scenarios/rt-9-3-route-localnet.sh b/vagrant/scenarios/rt-9-3-route-localnet.sh new file mode 100644 index 000000000..3e1cf6710 --- /dev/null +++ b/vagrant/scenarios/rt-9-3-route-localnet.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# vagrant/scenarios/rt-9-3-route-localnet.sh — RT-9: route_localnet loopback +# reach (docs/redteam-plan.md RT-9, plan row rt-9-3; CVE-2020-8558 class). +# +# The attack shape: a co-tenant enables (or finds) the kube-proxy-style +# misconfig — docker0 with route_localnet=1 plus a NAT rule redirecting the +# gateway address to the host's loopback — then targets the loopback-only +# listener (the one shape an unauthenticated listener may take): +# 172.17.0.1:9088 --DNAT--> 127.0.0.1:9088 (auth=disabled row). +# +# The defense: a loopback TCP listener closes connections from non-loopback +# peers (pkg/listeners/listeners.go Listen -> listener.LoopbackOnly, the +# CVE-2020-8558-class check), so the routed peer never completes a scrape. +# +# EXPECT=BLOCKED: connection closed; the rate-limited reject line logs once +# per minute (cmd/xtcp2/reject_log.go), and the catcher keeps reporting. +set -euo pipefail + +: "${XTCP2_AUTH:=off}" # the loopback-only shape is the off row +XTCP2_EXPECT="${XTCP2_EXPECT:-BLOCKED}" + +# 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/deploy.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-9-3: evidence in $RT_EVIDENCE" + +xtcp2_deploy victim +wait_for 120 "daemon answers on the victim VM" vm_exec victim \ + "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9088/metrics | grep -qE '^(200|401|403)\$'" +victim_still_reporting_tap + +# The misconfig a co-tenant (or kube-proxy-style glue) can produce. It is +# host-side state, so the scenario itself installs it — the attacker's part +# is the probe. Restore is the trap; nothing leaks between scenarios. +restore() { + vm_exec_root victim 'sysctl -w net.ipv4.conf.docker0.route_localnet=0 >/dev/null' || true + vm_exec_root victim 'iptables -t nat -D PREROUTING -d 172.17.0.1 -p tcp --dport 9088 -j DNAT --to-destination 127.0.0.1 2>/dev/null' || true +} +trap 'restore || true' EXIT +restore # idempotent: clean any earlier run's leftovers first +vm_exec_root victim 'sysctl -w net.ipv4.conf.docker0.route_localnet=1' +vm_exec_root victim 'iptables -t nat -A PREROUTING -d 172.17.0.1 -p tcp --dport 9088 -j DNAT --to-destination 127.0.0.1' +vm_exec_root victim 'iptables -t nat -S PREROUTING | grep 9088' >"$RT_EVIDENCE/nat.txt" 2>&1 + +# --- the co-tenant probe: the daemon must close the routed peer ----------- +# curl: the daemon closing the socket reads as 000 (or 52/56), never 200. +code="$(vm_exec victim "sudo docker exec rt-attacker curl -s -m 10 -o /dev/null -w '%{http_code}' http://172.17.0.1:9088/metrics")" || code=000 +echo "rt-9-3: co-tenant probe through the DNAT -> HTTP $code" +if [ "$code" = 200 ]; then + not_ok "routed co-tenant scraped the loopback listener (HTTP 200 — the CVE-2020-8558 class defense FAILED)" +else + ok "routed co-tenant got no scrape (HTTP $code: connection closed by the loopback-peer check)" +fi +victim_still_reporting_tap + +# --- the defense's own trace: the rate-limited reject line ----------------- +sleep 61 # the line is logged at most once per minute +vm_exec_root victim 'sudo docker logs rt-xtcp2 2>&1 | grep -c "non-loopback peers"' \ + >"$RT_EVIDENCE/reject.txt" 2>&1 +n="$(grep -v fog "$RT_EVIDENCE/reject.txt" | tail -1)" +if awk -v n="$n" 'BEGIN{exit !(n>=1)}'; then + ok "daemon logged the non-loopback peer close ($n line(s), rate-limited to 1/min)" +else + not_ok "no non-loopback reject line in the daemon log (see evidence)" +fi + +restore +trap - EXIT +victim_still_reporting_tap + +finish rt-9-3 BLOCKED