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.
This commit is contained in:
Loki 2026-11-21 15:10:37 +01:00
parent 987ccec905
commit d68b45e2b8
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
11 changed files with 268 additions and 27 deletions

View file

@ -9,6 +9,7 @@
### Added ### Added
- `scripts/xdp_stress.sh` — нагрузочный прогон SYN-флуда в netns (pps, дропы, CPU, живой клиент).
- Anti-lockout: при старте edge предупреждает (`WARN`) о каждом активном SSH-клиенте, которого - Anti-lockout: при старте edge предупреждает (`WARN`) о каждом активном SSH-клиенте, которого
нет в `whitelist` (разбор `/proc/net/tcp{,6}`, без root). нет в `whitelist` (разбор `/proc/net/tcp{,6}`, без root).
- Startup-диагностика XDP: детект контейнера (lxc/openvz/docker), единая строка окружения - Startup-диагностика XDP: детект контейнера (lxc/openvz/docker), единая строка окружения
@ -30,6 +31,15 @@
### Fixed ### 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 не парсил - Docker edge image: в сборку добавлен `benches/`, без него Cargo не парсил
манифест и образ не собирался (exit 101). манифест и образ не собирался (exit 101).
- `rampart-cli status` подсказывал неверный бинарь (`rampart doctor` вместо - `rampart-cli status` подсказывал неверный бинарь (`rampart doctor` вместо

View file

@ -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) | | 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); Статусы и правила ведутся в [docs/roadmap/README.md](docs/roadmap/README.md);
при изменении статуса правятся оба места (файл задачи и эта таблица). при изменении статуса правятся оба места (файл задачи и эта таблица).

View file

@ -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) | | 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 — продуктовые фичи ## 5. v0.5 — продуктовые фичи

View file

@ -3,7 +3,7 @@
| | | | | |
|---|---| |---|---|
| Milestone | v0.4 | | Milestone | v0.4 |
| Status | planned | | Status | in-progress |
| Priority | P1 | | Priority | P1 |
| Depends on | — | | Depends on | — |

View file

@ -3,7 +3,7 @@
| | | | | |
|---|---| |---|---|
| Milestone | v0.4 | | Milestone | v0.4 |
| Status | planned | | Status | in-progress |
| Priority | P0 | | Priority | P0 |
| Depends on | — | | Depends on | — |

View file

@ -74,7 +74,25 @@ TCP-payload по `ip->tot_len`), VLAN/QinQ-теги и фрагменты — з
проходить ни тегированным, ни фрагментированным. проходить ни тегированным, ни фрагментированным.
`scripts/xdp_netns_smoke.sh` дополнительно гоняет реальный бинарь `rampart` end-to-end `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`, см. Единая точка входа для CI появится в v0.4 (`scripts/xdp_ci.sh`, см.
[roadmap/v0.4-xdp-ci-harness.md](roadmap/v0.4-xdp-ci-harness.md)); до этого [roadmap/v0.4-xdp-ci-harness.md](roadmap/v0.4-xdp-ci-harness.md)); до этого

View file

@ -66,7 +66,7 @@ address = "$EDGE_IP"
port = $EDGE_PORT port = $EDGE_PORT
[backend] [backend]
upstreams = ["$HOST_IP:$ORIGIN_PORT"] upstreams = ["127.0.0.1:$ORIGIN_PORT"]
[limits] [limits]
handshake_timeout_secs = 5 handshake_timeout_secs = 5
@ -92,16 +92,18 @@ enabled = true
port = $METRICS_PORT port = $METRICS_PORT
[logging] [logging]
level = "info" # debug: the script greps per-event "xdp event" lines
level = "debug"
format = "text" format = "text"
[pow] [pow]
enabled = false enabled = false
EOF 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 "<html><body>rampart-smoke-origin</body></html>" > "$WORK/index.html" echo "<html><body>rampart-smoke-origin</body></html>" > "$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=$! SRVPID=$!
sleep 0.5 sleep 0.5
@ -118,7 +120,7 @@ done
if [ "$ATTACHED" = yes ]; then if [ "$ATTACHED" = yes ]; then
ok "XDP attached (verifier принят ядром $(uname -r))" ok "XDP attached (verifier принят ядром $(uname -r))"
else 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 fi
# Attach mode: native is expected on veth, but generic is a normal fallback in # 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 пуста" || fail "метрика autobans пуста"
# A banned source is refused while the ban is active. # 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=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://$EDGE_IP:$EDGE_PORT/" || true)
[ "$HTTP_CODE" = "err" ] || [ "$HTTP_CODE" = "000" ] \ # curl prints 000 when the connection is refused or dropped.
[ "${HTTP_CODE:-000}" = "000" ] \
&& ok "забаненный клиент отклонён (http=$HTTP_CODE)" \ && ok "забаненный клиент отклонён (http=$HTTP_CODE)" \
|| fail "забаненный клиент получил ответ ($HTTP_CODE)" || fail "забаненный клиент получил ответ ($HTTP_CODE)"
# Phase 7: expiry. After 7s (ban is 5s) traffic must come back on its own. # Phase 7: expiry. The in-kernel SYN ban lasts syn_ban_duration_ns (60 s, a
sleep 7 # constant in XdpGlobals, not the userspace auto_ban_duration_secs), so poll
BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true) # until traffic returns on its own instead of sleeping a fixed time.
echo "$BODY" | grep -q "rampart-smoke-origin" \ 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 "бан истёк, легитимный трафик восстановлен" \ && ok "бан истёк, легитимный трафик восстановлен" \
|| fail "после expiry трафик не восстановился" || fail "после expiry трафик не восстановился"

177
scripts/xdp_stress.sh Normal file
View file

@ -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" <<TOML
[bind]
address = "$EDGE_IP"
port = $EDGE_PORT
[backend]
upstreams = ["127.0.0.1:$ORIGIN_PORT"]
[xdp]
enabled = true
interface = "rstap"
protected_port_start = $EDGE_PORT
protected_port_end = $EDGE_PORT
events_enabled = false
throttle_enabled = true
auto_ban_enabled = false
syn_challenge_enabled = $CHALLENGE
challenge_secret_hex = "$(head -c 8 /dev/urandom | od -An -tx1 | tr -d ' \n')"
[metrics]
enabled = true
port = $METRICS_PORT
[pow]
enabled = false
TOML
echo "<html>rampart-stress-origin</html>" > "$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

View file

@ -14,6 +14,7 @@ use crate::traffic::hook::TrafficHook;
use crate::traffic::intel::detector::{AttackDetector, AttackStatus}; use crate::traffic::intel::detector::{AttackDetector, AttackStatus};
use crate::traffic::intel::reputation::IpReputation; use crate::traffic::intel::reputation::IpReputation;
use crate::traffic::profile::alert::{AlertDispatcher, send_webhook}; use crate::traffic::profile::alert::{AlertDispatcher, send_webhook};
use crate::xdp::XdpFilter;
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering}; 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. /// Startup failures: unreadable config, empty protocol registry, listener error.
pub async fn run() -> anyhow::Result<RunExit> { pub async fn run() -> anyhow::Result<RunExit> {
tracing_subscriber::fmt() 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(); .init();
let config_path = std::env::var("RAMPART_CONFIG").unwrap_or_else(|_| "/etc/rampart/config.toml".to_string()); 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<RunExit> {
// The configured difficulty is the floor and the starting point; the // The configured difficulty is the floor and the starting point; the
// adjuster only raises it under load. // adjuster only raises it under load.
let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::with_floor(config.pow.difficulty))); 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( let gateway = Arc::new(Gateway::new(
config.clone(), config.clone(),
rate_limiter, rate_limiter,
@ -216,14 +221,29 @@ pub async fn run() -> anyhow::Result<RunExit> {
registry, registry,
subnet_tracker, subnet_tracker,
)); ));
tokio::select! { let exit = tokio::select! {
result = listener::run(config, gateway, hook, shutdown_rx) => { result = listener::run(config, gateway, hook, shutdown_rx) => result.map(|()| RunExit::Ok),
result?;
Ok(RunExit::Ok)
}
// The drain timeout fired: hand the signal back so the binary can end the // The drain timeout fired: hand the signal back so the binary can end the
// process immediately, replacing the former `process::exit(0)`. // process immediately, replacing the former `process::exit(0)`.
_ = drain_rx => Ok(RunExit::DrainTimeout), _ = 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<Mutex<XdpFilter>>>) {
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 <if> xdp off`");
}
},
Err(_) => tracing::error!("XDP lock poisoned on shutdown; run `ip link set dev <if> xdp off`"),
} }
} }

View file

@ -71,9 +71,12 @@ impl XdpFilter {
let map = self.find_map("stats_map")?; let map = self.find_map("stats_map")?;
let sum = |idx: u32| -> u64 { let sum = |idx: u32| -> u64 {
let key = idx.to_le_bytes(); let key = idx.to_le_bytes();
match map.lookup(&key, MapFlags::ANY) { // `stats_map` is a percpu_array: plain `lookup` does not support it and
Ok(Some(v)) => v // the failure would silently read as zero, so sum the per-CPU slots.
.chunks_exact(8) 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"))) .map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8")))
.sum(), .sum(),
_ => 0, _ => 0,

View file

@ -77,6 +77,10 @@ struct conntrack_entry {
struct throttle_entry { struct throttle_entry {
__u64 window_start; __u64 window_start;
__u32 hits; __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;
}; };
/** /**