From d68b45e2b8f26564e615eb62f8656597d17d5b5a Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 21 Nov 2026 15:10:37 +0100 Subject: [PATCH] fix(xdp): verifier padding, synchronous detach, percpu stats; add netns stress harness Found by running the netns smoke on a real 5.15 KVM node: - throttle_entry implicit padding rejected by the verifier (clang 14) - XDP program left attached after the edge exited - rampart_xdp_* gauges always zero (percpu_array read with lookup) - RUST_LOG could not raise rampart above info Smoke now keeps the origin inside the netns and polls for ban expiry. --- CHANGELOG.md | 10 ++ TODO.md | 4 +- docs/roadmap/README.md | 4 +- docs/roadmap/v0.4-anti-lockout.md | 2 +- docs/roadmap/v0.4-xdp-ci-harness.md | 2 +- docs/testing.md | 20 +++- scripts/xdp_netns_smoke.sh | 31 +++-- scripts/xdp_stress.sh | 177 ++++++++++++++++++++++++++++ src/app/runtime.rs | 32 ++++- src/xdp/probe/stats.rs | 9 +- xdp/core/common.h | 4 + 11 files changed, 268 insertions(+), 27 deletions(-) create mode 100644 scripts/xdp_stress.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index eee3ccd..0801865 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Added +- `scripts/xdp_stress.sh` — нагрузочный прогон SYN-флуда в netns (pps, дропы, CPU, живой клиент). - Anti-lockout: при старте edge предупреждает (`WARN`) о каждом активном SSH-клиенте, которого нет в `whitelist` (разбор `/proc/net/tcp{,6}`, без root). - Startup-диагностика XDP: детект контейнера (lxc/openvz/docker), единая строка окружения @@ -30,6 +31,15 @@ ### Fixed +- **XDP: verifier на ядре 5.15 отвергал программу** (`invalid indirect read from stack`): + неявный паддинг `struct throttle_entry` не обнулялся clang 14 — теперь явное поле `pad` + (размер 16 и ABI прежние). Найдено прогоном на реальной KVM-ноде. +- **XDP-программа оставалась на интерфейсе после остановки edge**: detach шёл в фоновом + потоке после 5-секундного sleep, процесс выходил раньше. Теперь detach синхронный в `run`. +- Метрики `rampart_xdp_*` всегда были нулевыми: `stats_map` — `percpu_array`, читалась + обычным `lookup`. Теперь `lookup_percpu` с суммой по CPU. +- `RUST_LOG` не мог поднять детализацию `rampart` выше `info` (принудительная директива + перебивала переменную окружения). - Docker edge image: в сборку добавлен `benches/`, без него Cargo не парсил манифест и образ не собирался (exit 101). - `rampart-cli status` подсказывал неверный бинарь (`rampart doctor` вместо diff --git a/TODO.md b/TODO.md index b0dbd9a..c531a5a 100644 --- a/TODO.md +++ b/TODO.md @@ -20,9 +20,9 @@ | Задача | Приоритет | Статус | План | |--------|-----------|--------|------| -| XDP netns+veth harness в CI | P0 | planned | [v0.4-xdp-ci-harness.md](docs/roadmap/v0.4-xdp-ci-harness.md) | +| XDP netns+veth harness в CI | P0 | in-progress | [v0.4-xdp-ci-harness.md](docs/roadmap/v0.4-xdp-ci-harness.md) | | Startup-диагностика окружения | P1 | in-progress | [v0.4-startup-diagnostics.md](docs/roadmap/v0.4-startup-diagnostics.md) | -| Anti-lockout и баны по порту | P1 | planned | [v0.4-anti-lockout.md](docs/roadmap/v0.4-anti-lockout.md) | +| Anti-lockout и баны по порту | P1 | in-progress | [v0.4-anti-lockout.md](docs/roadmap/v0.4-anti-lockout.md) | Статусы и правила ведутся в [docs/roadmap/README.md](docs/roadmap/README.md); при изменении статуса правятся оба места (файл задачи и эта таблица). diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index f008353..887f838 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -45,9 +45,9 @@ | Задача | Приоритет | Статус | План | |--------|-----------|--------|------| -| XDP netns+veth harness в CI | P0 | planned | [v0.4-xdp-ci-harness.md](v0.4-xdp-ci-harness.md) | +| XDP netns+veth harness в CI | P0 | in-progress | [v0.4-xdp-ci-harness.md](v0.4-xdp-ci-harness.md) | | Startup-диагностика окружения | P1 | in-progress | [v0.4-startup-diagnostics.md](v0.4-startup-diagnostics.md) | -| Anti-lockout и баны по порту | P1 | planned | [v0.4-anti-lockout.md](v0.4-anti-lockout.md) | +| Anti-lockout и баны по порту | P1 | in-progress | [v0.4-anti-lockout.md](v0.4-anti-lockout.md) | ## 5. v0.5 — продуктовые фичи diff --git a/docs/roadmap/v0.4-anti-lockout.md b/docs/roadmap/v0.4-anti-lockout.md index 19ffe24..c2b3568 100644 --- a/docs/roadmap/v0.4-anti-lockout.md +++ b/docs/roadmap/v0.4-anti-lockout.md @@ -3,7 +3,7 @@ | | | |---|---| | Milestone | v0.4 | -| Status | planned | +| Status | in-progress | | Priority | P1 | | Depends on | — | diff --git a/docs/roadmap/v0.4-xdp-ci-harness.md b/docs/roadmap/v0.4-xdp-ci-harness.md index 557ac78..8e5ea83 100644 --- a/docs/roadmap/v0.4-xdp-ci-harness.md +++ b/docs/roadmap/v0.4-xdp-ci-harness.md @@ -3,7 +3,7 @@ | | | |---|---| | Milestone | v0.4 | -| Status | planned | +| Status | in-progress | | Priority | P0 | | Depends on | — | diff --git a/docs/testing.md b/docs/testing.md index 26fed51..dcca308 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -74,7 +74,25 @@ TCP-payload по `ip->tot_len`), VLAN/QinQ-теги и фрагменты — з проходить ни тегированным, ни фрагментированным. `scripts/xdp_netns_smoke.sh` дополнительно гоняет реальный бинарь `rampart` end-to-end -(требует `hping3`). +(требует `hping3`): `BIN=./target/release/rampart sudo -E bash scripts/xdp_netns_smoke.sh`. +Origin поднимается внутри netns, поэтому хостовой файрвол (`ufw`, `INPUT DROP`) не мешает. +Проверяет verifier, attach, проксирование, события ringbuf, auto-ban, истечение SYN-бана +(60 с, поэтому прогон занимает ~1.5 минуты) и реальный detach после SIGTERM. + +Нагрузочный прогон в том же изолированном netns: + +```bash +BIN=./target/release/rampart DURATION=20 SOURCES=single INTERVAL_US=200 sudo -E bash scripts/xdp_stress.sh +SOURCES=random sudo -E ... # спуфленные источники: защищает RST-challenge, а не throttle +``` + +Печатает pps, дропы XDP, RST-challenge, загрузку CPU и долю успешных запросов +легитимного клиента во время флуда. + +Известные пробелы: `xdp_ipv6_smoke.sh` на ядре 5.15 не проходит (патч `.rodata` из +bpftool и NDP в стенде); в режиме `SOURCES=random` живой клиент пока не проходит +RST-challenge — это работа v0.5. Если `bpftool` на хосте — обёртка без пакета под +текущее ядро (Ubuntu), подставьте реальный бинарь из `/usr/lib/linux-tools-*/`. Единая точка входа для CI появится в v0.4 (`scripts/xdp_ci.sh`, см. [roadmap/v0.4-xdp-ci-harness.md](roadmap/v0.4-xdp-ci-harness.md)); до этого diff --git a/scripts/xdp_netns_smoke.sh b/scripts/xdp_netns_smoke.sh index 3c786a0..9a76c61 100755 --- a/scripts/xdp_netns_smoke.sh +++ b/scripts/xdp_netns_smoke.sh @@ -66,7 +66,7 @@ address = "$EDGE_IP" port = $EDGE_PORT [backend] -upstreams = ["$HOST_IP:$ORIGIN_PORT"] +upstreams = ["127.0.0.1:$ORIGIN_PORT"] [limits] handshake_timeout_secs = 5 @@ -92,16 +92,18 @@ enabled = true port = $METRICS_PORT [logging] -level = "info" +# debug: the script greps per-event "xdp event" lines +level = "debug" format = "text" [pow] enabled = false EOF -# Phase 3: origin server on the host half of the veth pair. +# Phase 3: origin server inside the namespace, on loopback: a host firewall with +# INPUT DROP (ufw) would otherwise cut the edge off from an origin on the host half. echo "rampart-smoke-origin" > "$WORK/index.html" -python3 -m http.server "$ORIGIN_PORT" --bind "$HOST_IP" -d "$WORK" >/dev/null 2>&1 & +ip netns exec "$NS" python3 -m http.server "$ORIGIN_PORT" --bind 127.0.0.1 -d "$WORK" >/dev/null 2>&1 & SRVPID=$! sleep 0.5 @@ -118,7 +120,7 @@ done if [ "$ATTACHED" = yes ]; then ok "XDP attached (verifier принят ядром $(uname -r))" else - fail "XDP не аттачнулся; лог:"; sed -n '1,30p' "$WORK/rampart.log"; exit 1 + fail "XDP не аттачнулся; лог (начало и конец):"; sed -n '1,6p' "$WORK/rampart.log"; echo '...'; tail -20 "$WORK/rampart.log"; exit 1 fi # Attach mode: native is expected on veth, but generic is a normal fallback in @@ -155,15 +157,22 @@ BANS=$(ip netns exec "$NS" curl -s --max-time 2 "http://127.0.0.1:$METRICS_PORT/ || fail "метрика autobans пуста" # A banned source is refused while the ban is active. -HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://$EDGE_IP:$EDGE_PORT/" || echo "err") -[ "$HTTP_CODE" = "err" ] || [ "$HTTP_CODE" = "000" ] \ +HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://$EDGE_IP:$EDGE_PORT/" || true) +# curl prints 000 when the connection is refused or dropped. +[ "${HTTP_CODE:-000}" = "000" ] \ && ok "забаненный клиент отклонён (http=$HTTP_CODE)" \ || fail "забаненный клиент получил ответ ($HTTP_CODE)" -# Phase 7: expiry. After 7s (ban is 5s) traffic must come back on its own. -sleep 7 -BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true) -echo "$BODY" | grep -q "rampart-smoke-origin" \ +# Phase 7: expiry. The in-kernel SYN ban lasts syn_ban_duration_ns (60 s, a +# constant in XdpGlobals, not the userspace auto_ban_duration_secs), so poll +# until traffic returns on its own instead of sleeping a fixed time. +RECOVERED=no +for _ in $(seq 16); do + sleep 5 + BODY=$(curl -s --max-time 3 "http://$EDGE_IP:$EDGE_PORT/" || true) + echo "$BODY" | grep -q "rampart-smoke-origin" && { RECOVERED=yes; break; } +done +[ "$RECOVERED" = yes ] \ && ok "бан истёк, легитимный трафик восстановлен" \ || fail "после expiry трафик не восстановился" diff --git a/scripts/xdp_stress.sh b/scripts/xdp_stress.sh new file mode 100644 index 0000000..a532da6 --- /dev/null +++ b/scripts/xdp_stress.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# SYN-flood stress test of the XDP path inside an isolated netns+veth pair. +# +# Measures, while a flood runs against the protected port: +# * how many packets XDP processed and dropped (rampart_xdp_* metrics); +# * whether a legitimate client from another address keeps getting answers; +# * CPU busy share of the host during the flood. +# +# Everything lives in a private namespace, so production interfaces and the +# host firewall are never touched. Keep RATE modest on a shared host. +# +# Run (root, kernel >= 5.15, iproute2, hping3, python3, curl): +# BIN=./target/release/rampart bash scripts/xdp_stress.sh +# Tunables (env): DURATION=20 (seconds), INTERVAL_US=100 (hping gap, lower = faster), +# SOURCES=single|random + +set -u + +NS=rampart_stress +HOST_IP=10.244.250.1 +LEGIT_IP=10.244.250.3 +EDGE_IP=10.244.250.2 +EDGE_PORT=9000 +ORIGIN_PORT=9100 +METRICS_PORT=9596 +BIN=${BIN:-./target/release/rampart} +DURATION=${DURATION:-20} +INTERVAL_US=${INTERVAL_US:-100} +SOURCES=${SOURCES:-single} +# Spoofed random sources defeat the per-source SYN throttle (each address sends one +# SYN), so that mode relies on the stateless RST challenge instead. +[ "$SOURCES" = random ] && CHALLENGE=true || CHALLENGE=false +WORK=$(mktemp -d) +PIDS=() +PASS=1 + +fail() { echo "FAIL: $1"; PASS=0; } +ok() { echo "ok: $1"; } + +cleanup() { + for pid in "${PIDS[@]}"; do kill -9 "$pid" 2>/dev/null; done + ip netns del "$NS" 2>/dev/null + ip link del rsh0 2>/dev/null + rm -rf "$WORK" +} +trap cleanup EXIT + +[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; } +[ -x "$BIN" ] || { echo "бинарь не найден: $BIN"; exit 2; } +command -v hping3 >/dev/null || { echo "нужен hping3"; exit 2; } + +ip netns del "$NS" 2>/dev/null +ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; } +ip link add rsh0 type veth peer name rstap +ip link set rstap netns "$NS" +ip addr add "$HOST_IP/24" dev rsh0 +ip addr add "$LEGIT_IP/24" dev rsh0 +ip link set rsh0 up +ip -n "$NS" addr add "$EDGE_IP/24" dev rstap +ip -n "$NS" link set rstap up +ip -n "$NS" link set lo up + +cat > "$WORK/edge.toml" <rampart-stress-origin" > "$WORK/index.html" +ip netns exec "$NS" python3 -m http.server "$ORIGIN_PORT" --bind 127.0.0.1 -d "$WORK" >/dev/null 2>&1 & +PIDS+=($!) +RAMPART_CONFIG="$WORK/edge.toml" ip netns exec "$NS" "$BIN" > "$WORK/rampart.log" 2>&1 & +PIDS+=($!) +for _ in $(seq 40); do + grep -q "XDP filter attached" "$WORK/rampart.log" && break + sleep 0.5 +done +if grep -q "XDP filter attached" "$WORK/rampart.log"; then + ok "XDP attached: $(grep -oE 'mode: [a-z ()]+' "$WORK/rampart.log" | tail -1)" +else + fail "XDP не аттачнулся"; tail -15 "$WORK/rampart.log"; exit 1 +fi + +legit() { + curl -s -o /dev/null -w "%{http_code} %{time_total}" --interface "$LEGIT_IP" --max-time 8 \ + --retry 5 --retry-connrefused --retry-all-errors --retry-delay 1 \ + "http://$EDGE_IP:$EDGE_PORT/" 2>/dev/null || echo "000 8.000" +} +metric() { + ip netns exec "$NS" curl -s --max-time 2 "http://127.0.0.1:$METRICS_PORT/metrics" \ + | awk -v m="$1" '$1==m{print int($2)}' +} +cpu_busy() { # prints "busy total" jiffies from /proc/stat + awk '/^cpu /{idle=$5+$6; t=0; for(i=2;i<=NF;i++)t+=$i; print t-idle, t}' /proc/stat +} + +echo "baseline legit: $(legit)" + +# Metrics are refreshed by the poller every 5 s; wait for a fresh sample. +sleep 6 +V0=$(metric rampart_xdp_challenge_verified); S0=$(metric rampart_xdp_challenge_sent); T0=$(metric rampart_xdp_total); D0=$(metric rampart_xdp_dropped); P0=$(metric rampart_xdp_passed) +read -r B0 C0 < <(cpu_busy) + +HPING_ARGS=(-S -p "$EDGE_PORT" -i "u$INTERVAL_US") +[ "$SOURCES" = random ] && HPING_ARGS+=(--rand-source) +ip netns exec "$NS" true # namespace sanity +timeout "$DURATION" hping3 "${HPING_ARGS[@]}" "$EDGE_IP" > "$WORK/hping.log" 2>&1 & +PIDS+=($!) + +# Probe the legitimate client during the flood. +OK_CNT=0; ALL_CNT=0; WORST=0 +END=$((SECONDS + DURATION - 2)) +while [ "$SECONDS" -lt "$END" ]; do + read -r CODE TIME < <(legit) + ALL_CNT=$((ALL_CNT + 1)) + [ "$CODE" = 200 ] && OK_CNT=$((OK_CNT + 1)) + WORST=$(awk -v a="$WORST" -v b="$TIME" 'BEGIN{print (b>a)?b:a}') + sleep 1 +done +wait "${PIDS[-1]}" 2>/dev/null +sleep 6 +read -r B1 C1 < <(cpu_busy) +V1=$(metric rampart_xdp_challenge_verified); S1=$(metric rampart_xdp_challenge_sent); T1=$(metric rampart_xdp_total); D1=$(metric rampart_xdp_dropped); P1=$(metric rampart_xdp_passed) + +VERIFIED=$((V1 - V0)); CHALLENGES=$((S1 - S0)); TOTAL=$((T1 - T0)); DROPPED=$((D1 - D0)); PASSED=$((P1 - P0)) +PPS=$((TOTAL / (DURATION > 0 ? DURATION : 1))) +CPU=$(awk -v b=$((B1 - B0)) -v t=$((C1 - C0)) 'BEGIN{printf "%.0f", t ? 100*b/t : 0}') +echo "---- результат (источники: $SOURCES, ${DURATION}s) ----" +echo "XDP обработал: $TOTAL пакетов (~$PPS pps), дропнул: $DROPPED, пропустил: $PASSED" +echo "RST-challenge отправлено: $CHALLENGES, подтверждено живых клиентов: $VERIFIED" +echo "CPU хоста занят: ${CPU}%" +echo "легитимный клиент: $OK_CNT/$ALL_CNT успешно, худшее время ${WORST}s" + +[ "$TOTAL" -gt 0 ] && ok "XDP видел флуд" || fail "XDP не обработал ни одного пакета" +if [ "$SOURCES" = random ]; then + [ "$CHALLENGES" -gt 0 ] && ok "флуд отвечается RST-challenge ($CHALLENGES)" || fail "challenge не сработал" +else + [ "$DROPPED" -gt 0 ] && ok "флуд дропается в XDP" || fail "XDP ничего не дропнул" +fi +if [ "$ALL_CNT" -gt 0 ] && [ $((OK_CNT * 10)) -ge $((ALL_CNT * 8)) ]; then + ok "легитимный клиент обслуживается под флудом (>=80%)" +elif [ "$SOURCES" = random ]; then + # Known gap, tracked in docs/roadmap/v0.5-rst-challenge-ga.md: with the RST + # challenge on, a real client is not yet verified even without a flood. + echo "WARN: легитимный клиент не прошёл RST-challenge ($OK_CNT/$ALL_CNT) — известный пробел v0.5" +else + fail "легитимный клиент деградировал ($OK_CNT/$ALL_CNT)" +fi + +kill -TERM "${PIDS[1]}" 2>/dev/null +wait "${PIDS[1]}" 2>/dev/null +sleep 1 +ip -n "$NS" link show rstap | grep -q xdp && fail "XDP остался после выхода" || ok "XDP отвязан после SIGTERM" + +[ "$PASS" = 1 ] && { echo "PASS — xdp stress ($(uname -r))"; exit 0; } +echo "FAIL — xdp stress"; tail -20 "$WORK/rampart.log"; exit 1 diff --git a/src/app/runtime.rs b/src/app/runtime.rs index 97cd7d0..ead334d 100644 --- a/src/app/runtime.rs +++ b/src/app/runtime.rs @@ -14,6 +14,7 @@ use crate::traffic::hook::TrafficHook; use crate::traffic::intel::detector::{AttackDetector, AttackStatus}; use crate::traffic::intel::reputation::IpReputation; use crate::traffic::profile::alert::{AlertDispatcher, send_webhook}; +use crate::xdp::XdpFilter; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; @@ -41,7 +42,8 @@ fn attack_status_value(status: AttackStatus) -> i64 { /// Startup failures: unreadable config, empty protocol registry, listener error. pub async fn run() -> anyhow::Result { tracing_subscriber::fmt() - .with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?)) + // RUST_LOG wins when set; a forced `rampart=info` directive would cap it. + .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("rampart=info"))) .init(); let config_path = std::env::var("RAMPART_CONFIG").unwrap_or_else(|_| "/etc/rampart/config.toml".to_string()); @@ -203,6 +205,9 @@ pub async fn run() -> anyhow::Result { // The configured difficulty is the floor and the starting point; the // adjuster only raises it under load. let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::with_floor(config.pow.difficulty))); + // Kept for the shutdown path: the polling thread detaches only after its sleep, + // which the process exit would cut short and leave the program on the NIC. + let xdp_for_shutdown = xdp_filter.clone(); let gateway = Arc::new(Gateway::new( config.clone(), rate_limiter, @@ -216,14 +221,29 @@ pub async fn run() -> anyhow::Result { registry, subnet_tracker, )); - tokio::select! { - result = listener::run(config, gateway, hook, shutdown_rx) => { - result?; - Ok(RunExit::Ok) - } + let exit = tokio::select! { + result = listener::run(config, gateway, hook, shutdown_rx) => result.map(|()| RunExit::Ok), // The drain timeout fired: hand the signal back so the binary can end the // process immediately, replacing the former `process::exit(0)`. _ = drain_rx => Ok(RunExit::DrainTimeout), + }; + detach_xdp(xdp_for_shutdown.as_ref()); + exit +} + +/// Detaches the XDP program before the process exits, so a stopped edge never +/// leaves a filter dropping traffic with nobody reading its events. +fn detach_xdp(xdp: Option<&Arc>>) { + let Some(xdp) = xdp else { + return; + }; + match xdp.lock() { + Ok(mut guard) => { + if let Err(e) = guard.unload() { + tracing::error!(error = %e, "XDP detach on shutdown failed; run `ip link set dev xdp off`"); + } + }, + Err(_) => tracing::error!("XDP lock poisoned on shutdown; run `ip link set dev xdp off`"), } } diff --git a/src/xdp/probe/stats.rs b/src/xdp/probe/stats.rs index bfa954b..75f578f 100644 --- a/src/xdp/probe/stats.rs +++ b/src/xdp/probe/stats.rs @@ -71,9 +71,12 @@ impl XdpFilter { let map = self.find_map("stats_map")?; let sum = |idx: u32| -> u64 { let key = idx.to_le_bytes(); - match map.lookup(&key, MapFlags::ANY) { - Ok(Some(v)) => v - .chunks_exact(8) + // `stats_map` is a percpu_array: plain `lookup` does not support it and + // the failure would silently read as zero, so sum the per-CPU slots. + match map.lookup_percpu(&key, MapFlags::ANY) { + Ok(Some(slots)) => slots + .iter() + .flat_map(|slot| slot.chunks_exact(8)) .map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8"))) .sum(), _ => 0, diff --git a/xdp/core/common.h b/xdp/core/common.h index e0ad622..0bec911 100644 --- a/xdp/core/common.h +++ b/xdp/core/common.h @@ -77,6 +77,10 @@ struct conntrack_entry { struct throttle_entry { __u64 window_start; __u32 hits; + /* Explicit padding: the verifier rejects helper reads of uninitialised + * stack bytes, and implicit padding is not zeroed by the compiler. The + * struct size (16) is unchanged. */ + __u32 pad; }; /**