feat(v0.4): xdp_ci entry point, per-port bans, capability-based diagnostics, recovery check

- scripts/xdp_ci.sh with honest SKIP and RESULT lines, CI job xdp-kernel
- Blacklist::add_port/is_blocked_on, enforced by the gateway (userspace only)
- diagnostics read CapEff: root without CAP_BPF is not privileged
- smoke phase 9 verifies 'ip link set dev <if> xdp off' recovery
- module-size gate: lockout moved into a directory, detach_xdp into services
This commit is contained in:
Loki 2026-11-21 15:34:21 +01:00
parent d68b45e2b8
commit a4cf78e475
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
21 changed files with 431 additions and 54 deletions

View file

@ -14,7 +14,6 @@ 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};
@ -23,7 +22,7 @@ use tokio::sync::oneshot;
use tokio::sync::watch;
use tracing_subscriber::EnvFilter;
use super::services::{build_registry, build_whitelist, start_subnet_tracker, start_xdp};
use super::services::{build_registry, build_whitelist, detach_xdp, start_subnet_tracker, start_xdp};
use super::shutdown::{RunExit, spawn_shutdown_drain};
fn attack_status_value(status: AttackStatus) -> i64 {
@ -231,22 +230,6 @@ pub async fn run() -> anyhow::Result<RunExit> {
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`"),
}
}
async fn push_attack_event(writer: &Option<Arc<tokio::sync::Mutex<ClickHouseWriter>>>, pps: f64) {
let Some(writer) = writer else {
return;

View file

@ -192,3 +192,19 @@ pub fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>>
}
Ok(Arc::new(set))
}
/// Detaches the XDP program before the process exits, so a stopped edge never
/// leaves a filter dropping traffic with nobody reading its events.
pub(crate) 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

@ -28,7 +28,8 @@ impl Gateway {
// blacklist entries and XDP/Redis bans propagate across all nodes, so a
// whitelisted address must never enter that path.
if !trusted {
if self.blacklist.is_blocked(peer_ip) {
let local_port = client.local_addr().map_or(0, |addr| addr.port());
if self.blacklist.is_blocked_on(peer_ip, local_port) {
metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc();
return Ok(());
}

View file

@ -5,8 +5,10 @@
//! [`Blacklist::clear_expired`]. Deadlines are monotonic and clamped, so a
//! hostile expiry can never overflow or panic.
mod port;
mod prefix;
use self::port::PortBans;
use self::prefix::PrefixBans;
use dashmap::DashMap;
use std::collections::HashSet;
@ -39,6 +41,7 @@ pub struct Blacklist {
entries: Arc<DashMap<IpAddr, BanEntry>>,
redis_entries: Arc<DashMap<IpAddr, BanEntry>>,
prefixes: PrefixBans,
ports: PortBans,
local_ban_events: broadcast::Sender<LocalBanEvent>,
}
@ -56,6 +59,7 @@ impl Blacklist {
entries: Arc::new(DashMap::new()),
redis_entries: Arc::new(DashMap::new()),
prefixes: PrefixBans::new(),
ports: PortBans::new(),
local_ban_events,
}
}
@ -170,7 +174,7 @@ impl Blacklist {
/// Total number of tracked bans.
pub fn len(&self) -> usize {
self.entries.len() + self.redis_entries.len() + self.prefixes.len()
self.entries.len() + self.redis_entries.len() + self.prefixes.len() + self.ports.len()
}
/// Returns whether all ban tables are empty.
@ -184,6 +188,7 @@ impl Blacklist {
self.entries.retain(|_, entry| entry.expires > now);
self.redis_entries.retain(|_, entry| entry.expires > now);
self.prefixes.clear_expired(now);
self.ports.clear_expired(now);
}
/// Checks `entries`, lazily removing `ip` only if it is still expired.

View file

@ -0,0 +1,79 @@
//! Per-port ban table.
//!
//! A ban keyed by `(address, local port)` cuts an attacker off from one protected
//! service while leaving its other ports (SSH, monitoring) reachable. These bans are
//! local to the node: the Redis mirror and the XDP maps are keyed by address only, so
//! a port ban is deliberately never published or pushed into the kernel.
use super::{Blacklist, clamp_duration, deadline, normalize};
use dashmap::DashMap;
use std::net::IpAddr;
use std::time::{Duration, Instant};
/// Upper bound on distinct port bans kept in memory.
const MAX_PORT_BANS: usize = 4096;
/// Thread-safe set of active `(address, port)` bans.
pub(super) struct PortBans {
entries: DashMap<(IpAddr, u16), Instant>,
}
impl PortBans {
pub(super) fn new() -> Self {
Self {
entries: DashMap::new(),
}
}
/// Bans `ip` on `port` until `expires`. Port `0` is rejected (it would mean
/// "any port"); a full table refuses new keys but still extends existing ones.
pub(super) fn add(&self, ip: IpAddr, port: u16, expires: Instant) -> bool {
if port == 0 || (self.entries.len() >= MAX_PORT_BANS && !self.entries.contains_key(&(ip, port))) {
return false;
}
self.entries.insert((ip, port), expires);
true
}
pub(super) fn remove(&self, ip: IpAddr, port: u16) {
self.entries.remove(&(ip, port));
}
/// Whether `ip` is banned on exactly `port`; an expired entry is dropped only
/// if it is still expired (no TOCTOU against a concurrent re-ban).
pub(super) fn is_blocked(&self, ip: IpAddr, port: u16, now: Instant) -> bool {
if let Some(expires) = self.entries.get(&(ip, port))
&& *expires > now
{
return true;
}
self.entries.remove_if(&(ip, port), |_, expires| *expires <= now);
false
}
pub(super) fn len(&self) -> usize {
self.entries.len()
}
pub(super) fn clear_expired(&self, now: Instant) {
self.entries.retain(|_, expires| *expires > now);
}
}
impl Blacklist {
/// Whether `ip` is banned for local `port`: address-wide bans, or this exact port.
pub fn is_blocked_on(&self, ip: IpAddr, port: u16) -> bool {
self.is_blocked(ip) || self.ports.is_blocked(normalize(ip), port, Instant::now())
}
/// Bans `ip` on `port` only; local to this node (Redis and XDP are keyed by address).
/// Returns `false` for port `0` or when the table is full.
pub fn add_port(&self, ip: IpAddr, port: u16, duration: Duration) -> bool {
self.ports.add(normalize(ip), port, deadline(clamp_duration(duration)))
}
/// Removes a per-port ban.
pub fn remove_port(&self, ip: IpAddr, port: u16) {
self.ports.remove(normalize(ip), port);
}
}

View file

@ -1,8 +1,8 @@
use anyhow::{Result, bail};
use super::types::{
AttachMode, BTF_PATH, KernelVersion, MIN_KERNEL, OSRELEASE_PATH, SystemProbe, container_blocks_xdp,
detect_container, driver_from_link, driver_supports_native_xdp,
AttachMode, BTF_PATH, KernelVersion, MIN_KERNEL, OSRELEASE_PATH, STATUS_PATH, SystemProbe, caps_allow_xdp,
container_blocks_xdp, detect_container, driver_from_link, driver_supports_native_xdp, parse_cap_eff,
};
/// Structured report on how suitable the environment is for XDP.
@ -25,7 +25,10 @@ impl EnvironmentReport {
.ok()
.and_then(|r| KernelVersion::parse(r.trim()));
let btf_available = probe.path_exists(BTF_PATH);
let privileged = probe.effective_uid() == 0;
// Capabilities decide, not the uid: root in a container without CAP_BPF still
// cannot attach. Without a readable CapEff the uid heuristic remains.
let cap_eff = probe.read_file(STATUS_PATH).ok().and_then(|s| parse_cap_eff(&s));
let privileged = cap_eff.map_or_else(|| probe.effective_uid() == 0, caps_allow_xdp);
let driver_link = probe.symlink_target(&format!("/sys/class/net/{interface}/device/driver"));
let driver_name = driver_link.as_deref().and_then(driver_from_link);
@ -40,8 +43,8 @@ impl EnvironmentReport {
}
if !privileged {
warnings.push(
"процесс не от root: CAP_BPF/CAP_NET_ADMIN не подтверждены, \
attach скорее всего завершится EPERM"
"нет прав на XDP (нужны CAP_NET_ADMIN + CAP_BPF + CAP_PERFMON или root без урезанных \
capabilities): attach скорее всего завершится EPERM"
.to_owned(),
);
}
@ -90,7 +93,12 @@ impl EnvironmentReport {
),
(
"privileges",
if self.privileged { "root" } else { "non-root" }.to_owned(),
if self.privileged {
"xdp-capable"
} else {
"missing-xdp-caps"
}
.to_owned(),
),
(
"driver",
@ -118,7 +126,7 @@ impl EnvironmentReport {
return format!("контейнер '{kind}' не поддерживает XDP: нужна KVM-VDS или bare metal");
}
if !self.privileged {
return "запустите от root или выдайте CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON".to_owned();
return "выдайте процессу CAP_NET_ADMIN, CAP_BPF и CAP_PERFMON (docker: --cap-add) или запустите от root без урезанных capabilities".to_owned();
}
if !self.btf_available {
return "ядро без BTF (/sys/kernel/btf/vmlinux): используйте ядро с CONFIG_DEBUG_INFO_BTF=y".to_owned();

View file

@ -5,7 +5,12 @@ pub const MIN_KERNEL: KernelVersion = KernelVersion::new(5, 15, 0);
pub(super) const OSRELEASE_PATH: &str = "/proc/sys/kernel/osrelease";
pub(super) const BTF_PATH: &str = "/sys/kernel/btf/vmlinux";
const STATUS_PATH: &str = "/proc/self/status";
pub(super) const STATUS_PATH: &str = "/proc/self/status";
const CAP_NET_ADMIN: u32 = 12;
const CAP_SYS_ADMIN: u32 = 21;
const CAP_PERFMON: u32 = 38;
const CAP_BPF: u32 = 39;
pub(super) const SYSTEMD_CONTAINER_PATH: &str = "/run/systemd/container";
const OPENVZ_PATH: &str = "/proc/vz";
@ -183,3 +188,17 @@ pub(super) fn driver_from_link(target: &str) -> Option<String> {
pub fn driver_supports_native_xdp(driver: &str) -> bool {
NATIVE_XDP_DRIVERS.contains(&driver)
}
/// Effective capability mask (`CapEff`) from `/proc/self/status`.
pub(super) fn parse_cap_eff(status: &str) -> Option<u64> {
status
.lines()
.find_map(|line| u64::from_str_radix(line.strip_prefix("CapEff:")?.trim(), 16).ok())
}
/// Whether the mask allows loading and attaching XDP: `CAP_NET_ADMIN` plus
/// `CAP_BPF`+`CAP_PERFMON` (kernel 5.8+) or the legacy `CAP_SYS_ADMIN`.
pub(super) fn caps_allow_xdp(mask: u64) -> bool {
let has = |bit: u32| mask & (1 << bit) != 0;
has(CAP_NET_ADMIN) && ((has(CAP_BPF) && has(CAP_PERFMON)) || has(CAP_SYS_ADMIN))
}