feat(xdp): IPv6 UDP rate limit, working loader; English comments and docs

XDP behaviour:
- udp_rate_limit6 (LRU, full 128-bit source key) plus throttle_hit6, so
  udp_policy = "rate-limit" applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

Loader (XDP could never load before this):
- .rodata is one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Before, a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs checks map names and .rodata size without root.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, nav buttons,
  compact TOC and copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6
  coverage; testing.md covers the real-kernel smoke; stale links removed.
This commit is contained in:
Loki 2026-11-15 23:50:52 +01:00
parent b64c329125
commit a8a3057719
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
104 changed files with 2155 additions and 1030 deletions

View file

@ -18,14 +18,14 @@ pub(super) fn interface_cstr(name: &str) -> Result<CString> {
CString::new(name).with_context(|| format!("interface name {name:?} contains an interior NUL byte"))
}
/// Внутренний data-map `.rodata` ищется по суффиксу: libbpf именует его
/// `<obj_name>.rodata`, а имя объекта при `open_memory` без явного `.name()`
/// вообще `memory` — точное сравнение ломалось на живом ядре (smoke-тест).
/// The internal `.rodata` data map is matched by suffix: libbpf names it
/// `<obj_name>.rodata`, and with `open_memory` and no explicit `.name()` the object is
/// called `memory` — an exact comparison broke on a live kernel (smoke test).
pub(super) fn is_rodata_map(name: &str) -> bool {
name.ends_with(".rodata")
}
/// Патчит карту `*.rodata` (volatile const глобалы) ДО загрузки объекта.
/// Patches the `*.rodata` map (volatile-const globals) before the object is loaded.
pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> Result<()> {
let image = globals.build_rodata_image();
if !open_obj
@ -42,12 +42,23 @@ pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> R
.maps_mut()
.find(|m| m.name().to_str().is_some_and(is_rodata_map))
.context("rodata map vanished between passes")?;
// libbpf rejects a value whose size differs from the map's (EINVAL, and the
// error message says nothing useful). Fail loudly here instead: a mismatch
// means `struct rampart_config` in config.h and `XdpGlobals` drifted apart.
let expected = map.value_size() as usize;
if image.len() != expected {
bail!(
"XDP .rodata map expects {expected} bytes, loader image has {} — \
struct rampart_config (xdp/core/config.h) and XdpGlobals (src/xdp/globals.rs) diverged",
image.len()
);
}
map.set_initial_value(&image)
.with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'"))
}
/// Честное имя режима attach по `attach_mode` из `bpf_xdp_query_opts`
/// (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3).
/// Honest name of the attach mode, derived from the `attach_mode` field of
/// `bpf_xdp_query_opts` (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3).
pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str {
match mode {
1 => "native (drv)",
@ -57,13 +68,13 @@ pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str {
}
}
/// Собирает ringbuf-колбэк для `events_map`.
/// Builds the ringbuf callback for `events_ringbuf`.
///
/// Колбэк обязан быть `'static`, поэтому всё разделяемое состояние (`Arc<Blacklist>`,
/// копия `AutoBanConfig`) захватывается `move`-клонами. Когда `blacklist` — `None`
/// (фича не подключена) или политика выключена, события только парсятся и
/// логируются структурированно; баны не пишутся. В горячем пути нет `format!` —
/// `tracing`-поля и `&'static str` причины.
/// The callback must be `'static`, so all shared state (`Arc<Blacklist>`, a copy of
/// `AutoBanConfig`) is captured by `move` clones. When `blacklist` is `None` (feature not
/// wired) or the policy is disabled, events are only parsed and logged in a structured
/// way; no bans are written. The hot path does no `format!` — only `tracing` fields and
/// `&'static str` reasons.
pub(super) fn build_ringbuf(
obj: &Object,
blacklist: Option<Arc<Blacklist>>,
@ -71,8 +82,8 @@ pub(super) fn build_ringbuf(
) -> Result<RingBuffer<'static>> {
let map = obj
.maps()
.find(|m| m.name() == "events_map")
.context("events_map not found")?;
.find(|m| m.name() == "events_ringbuf")
.context("events_ringbuf not found")?;
let mut builder = RingBufferBuilder::new();
builder.add(&map, move |data: &[u8]| {
let Some(event) = parse_xdp_event(data) else {
@ -93,10 +104,10 @@ pub(super) fn build_ringbuf(
};
if let Some(ban) = auto_ban_decision(&event, &cfg) {
let addr = IpAddr::V4(ban.ip);
// `Blacklist::add` возвращает `()` (DashMap::insert игнорируется), а
// править blacklist.rs вне нашей зоны нельзя — поэтому «новый ли бан»
// определяем через публичный `is_blocked` ДО перезаписи. Это дедуп
// лога/метрики по активному бану, а не по факту вставки.
// `Blacklist::add` returns `()` (it ignores `DashMap::insert`) and blacklist.rs is
// out of our edit scope, so "is this a new ban" is decided through the public
// `is_blocked` before the overwrite. This dedups the log line and the metric by
// active ban, not by the fact of insertion.
let already_banned = blacklist.is_blocked(addr);
blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason);
if already_banned {
@ -134,8 +145,8 @@ mod tests {
#[test]
fn rodata_map_matches_libbpf_naming() {
// libbpf строит имя `<obj><section>` без замены точки (libbpf.c ~1911),
// при open_memory без name объект называется "memory":
// libbpf builds the name as `<obj><section>` without rewriting the dot
// (libbpf.c ~1911); with open_memory and no name the object is called "memory":
assert!(is_rodata_map("rampart.rodata"));
assert!(is_rodata_map("memory.rodata"));
assert!(is_rodata_map(".rodata"));

View file

@ -1,32 +1,32 @@
//! Разбор и политика для событий XDP-ringbuf (`struct xdp_event`).
//! Parsing and policy for XDP ringbuf events (`struct xdp_event`).
//!
//! Чистые (без I/O, без libbpf) функции, чтобы их можно было покрыть
//! юнит-тестами без ядра/Redis. Wiring колбэка — в [`super::attach`].
//! Pure functions (no I/O, no libbpf) so that they can be covered by unit tests without
//! a kernel or Redis. The callback wiring lives in [`super::attach`].
use std::net::Ipv4Addr;
use crate::config::XdpConfig;
/// Точный размер `struct xdp_event` (см. `xdp/core/common.h:61-66`):
/// Exact size of `struct xdp_event` (see `xdp/core/common.h:61-66`):
/// `__u32 type` @0, `__u32 src_ip` @4, `__u32 metadata` @8,
/// 4 байта padding @12 (выравнивание `__u64`), `__u64 timestamp` @16 → 24.
/// 4 bytes of padding @12 (to align `__u64`), `__u64 timestamp` @16 -> 24.
pub const XDP_EVENT_LEN: usize = 24;
/// Тип события из `enum event_type` (`common.h:54-59`).
/// Event type from `enum event_type` (`common.h:54-59`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XdpEventKind {
/// `EVENT_BAN` — пакет уже был в blacklist_map и сброшен ядром.
/// `EVENT_BAN` — the packet was already in `blacklist_map` and was dropped by the kernel.
Ban,
/// `EVENT_RATE_LIMIT` — превышен порог троттлинга (SYN/UDP).
/// `EVENT_RATE_LIMIT` — the throttling threshold was exceeded (SYN/UDP).
RateLimit,
/// `EVENT_POLICY_DROP` — статичная политика (UDP drop / вредоносные TCP-флаги).
/// `EVENT_POLICY_DROP` — a static policy match (UDP drop / malicious TCP flags).
PolicyDrop,
/// `EVENT_CONN_DROP` — flow сброшен (несоответствие seq или verdict хука).
/// `EVENT_CONN_DROP` — the flow was dropped (sequence mismatch or a hook verdict).
ConnDrop,
}
impl XdpEventKind {
/// Декодирует числовое значение из C-enum. Неизвестный тип → `None` + debug.
/// Decodes the numeric value of the C enum. An unknown type yields `None` plus a debug log.
fn from_u32(raw: u32) -> Option<Self> {
match raw {
0 => Some(Self::Ban),
@ -41,41 +41,43 @@ impl XdpEventKind {
}
}
/// Разобранное событие ringbuf.
/// A parsed ringbuf event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XdpEvent {
pub kind: XdpEventKind,
/// IPv4 источника (для IPv4-mapped IPv6 ядро кладёт в `src_ip` младший u32).
/// Source IPv4 address (for IPv4-mapped IPv6 the kernel stores the low u32 in `src_ip`).
pub src_ip: Ipv4Addr,
/// Поле `__u32 metadata`: для `RateLimit` — порог срабатывания троттлинга,
/// для `ConnDrop` — счётчик `conn->fails`, иначе `0`.
/// The `__u32 metadata` field: for `RateLimit` the throttling threshold that fired, for
/// `ConnDrop` the `conn->fails` counter, `0` otherwise.
pub metadata: u32,
/// `bpf_ktime_get_ns()` на момент генерации (monotonic, не wall-clock).
/// `bpf_ktime_get_ns()` at generation time (monotonic, not wall clock).
pub timestamp_ns: u64,
}
/// Разбирает 24-байтовый кадр `struct xdp_event`.
/// Parses a 24-byte `struct xdp_event` frame.
///
/// # Byte order (проверено по C-источнику)
/// Скалярные поля (`type`, `metadata`, `timestamp`) пишутся ядром в ПОРЯДКЕ ХОСТА
/// без конверсии: `push_event` присваивает их как есть — `e->type = type`,
/// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()`
/// (`common.h:92-95`, `bpf_htonl`/`bpf_ntohl` к ним НЕ применяется). Userspace
/// читает те же байты на той же машине → `from_ne_bytes` корректно.
/// # Byte order (verified against the C source)
/// The scalar fields (`type`, `metadata`, `timestamp`) are written by the kernel in host
/// order without conversion: `push_event` assigns them as they are — `e->type = type`,
/// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()` (`common.h:92-95`; no
/// `bpf_htonl`/`bpf_ntohl` is applied). Userspace reads the same bytes on the same
/// machine, so `from_ne_bytes` is correct.
///
/// А вот `src_ip` — сетевой порядок (big-endian octets): он приходит прямо из
/// заголовка пакета `src_ip = ip->saddr` (`universal_filter.c:149`) и пишется в
/// событие без `bpf_htonl` (`common.h:93`). Значит байты `data[4..8]` — это октеты
/// адреса в точковом порядке, и читать их надо как `Ipv4Addr::new(octets...)`, а НЕ
/// как `from_ne_bytes(u32)` (прежний баг: на LE-хосте давал перевернутый IP).
/// `src_ip` is different: it is in network order (big-endian octets) because it comes
/// straight from the packet header as `src_ip = ip->saddr` (`universal_filter.c:149`)
/// and is copied into the event without `bpf_htonl` (`common.h:93`). Bytes `data[4..8]`
/// are therefore the address octets in dotted order and must be read as
/// `Ipv4Addr::new(octets...)`, not as `from_ne_bytes(u32)` (the old bug produced a
/// reversed IP on little-endian hosts).
///
/// Возвращает `None`, если кадр короче `XDP_EVENT_LEN` или тип неизвестен.
/// Returns `None` if the frame is shorter than `XDP_EVENT_LEN` or the type is unknown.
pub fn parse_xdp_event(bytes: &[u8]) -> Option<XdpEvent> {
let raw: &[u8; XDP_EVENT_LEN] = bytes.get(..XDP_EVENT_LEN)?.try_into().ok()?;
let kind = XdpEventKind::from_u32(u32::from_ne_bytes(raw[0..4].try_into().ok()?))?;
let src_ip = Ipv4Addr::new(raw[4], raw[5], raw[6], raw[7]);
let metadata = u32::from_ne_bytes(raw[8..12].try_into().ok()?);
// raw[12..16] — выравнивающий padding под __u64, не читаем (он не инициализирован).
// `raw[12..16]` is alignment padding for `__u64`; it is not read because the kernel
// never initialises it.
let timestamp_ns = u64::from_ne_bytes(raw[16..24].try_into().ok()?);
Some(XdpEvent {
kind,
@ -85,7 +87,7 @@ pub fn parse_xdp_event(bytes: &[u8]) -> Option<XdpEvent> {
})
}
/// Параметры авто-бана, резолвинг из секции `[xdp]`.
/// Auto-ban parameters, resolved from the `[xdp]` section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoBanConfig {
pub enabled: bool,
@ -104,7 +106,7 @@ impl Default for AutoBanConfig {
}
impl AutoBanConfig {
/// Берёт значения из `[xdp]`-секции конфига (единственный источник истины).
/// Takes the values from the `[xdp]` config section (the single source of truth).
pub fn from_xdp(cfg: &XdpConfig) -> Self {
Self {
enabled: cfg.auto_ban_enabled,
@ -114,33 +116,35 @@ impl AutoBanConfig {
}
}
/// Готовый бан для применения к userspace-`Blacklist`.
/// A ready-to-apply ban for the userspace `Blacklist`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BanAction {
pub ip: Ipv4Addr,
pub duration_secs: u64,
/// Статичная причина (без аллокаций в горячем пути).
/// Static reason (no allocation on the hot path).
pub reason: &'static str,
}
/// Чистое решение: банить ли источник события и на сколько.
/// Pure decision: whether the event source should be banned and for how long.
///
/// Возвращает `None`, если фича выключена или тип события не банится.
/// Разбор по типам обоснован C-кодом:
/// Returns `None` when the feature is disabled or the event type is not bannable. The
/// per-type split follows the C code:
///
/// * [`XdpEventKind::Ban`] — НЕ баним. Событие эмитится уже ПОСЛЕ того, как
/// ядро нашло IP в `blacklist_map` и дропнуло пакет (`universal_filter.c:220-225`);
/// повторный userspace-бан бессмысленен и мог бы скрыть штатный expiry.
/// * [`XdpEventKind::PolicyDrop`] — НЕ баним по умолчанию. Это статичная
/// политика на каждый пакет: UDP-drop-политика (`:234`) и вредоносные TCP-флаги
/// (`:259`). Бан по одному malformed-пакету перебанит легитимных, но глючных
/// клиентов — порог аккумулирования здесь отсутствует по смыслу.
/// * [`XdpEventKind::RateLimit`] — банیم. Порог троттлинга уже фактически превышен;
/// при этом UDP-путь (`:237-243`) только дропает и НЕ заносит в blacklist (в
/// отличие от SYN-пути `:295`) — userspace-бан добавляет реальную защиту.
/// * [`XdpEventKind::ConnDrop`] — баним, только если `metadata` (=`conn->fails`)
/// достиг порога (`:364-368`). Дроп по протокольному хуку приходит с `fails = 0`
/// (`:418`) и ниже порога, т.е. не банится.
/// * [`XdpEventKind::Ban`] — not banned. The event is emitted only after the kernel has
/// already found the IP in `blacklist_map` and dropped the packet
/// (`universal_filter.c:220-225`), so a second userspace ban is pointless and could
/// mask the regular expiry.
/// * [`XdpEventKind::PolicyDrop`] — not banned by default. This is a static per-packet
/// policy: the UDP drop policy (`:234`) and malicious TCP flags (`:259`). Banning on a
/// single malformed packet would re-ban legitimate but buggy clients, and there is no
/// accumulation threshold here by design.
/// * [`XdpEventKind::RateLimit`] — banned. The throttling threshold has already been
/// exceeded; the UDP path (`:237-243`) only drops and does not insert into the
/// blacklist (unlike the SYN path at `:295`), so the userspace ban adds real
/// protection.
/// * [`XdpEventKind::ConnDrop`] — banned only when `metadata` (= `conn->fails`) reached
/// the threshold (`:364-368`). A protocol-hook drop arrives with `fails = 0` (`:418`),
/// below the threshold, so it is not banned.
#[must_use]
pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<BanAction> {
if !config.enabled {
@ -162,5 +166,5 @@ pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<Ban
}
}
// Покрытие парсера и политики — в `tests/xdp_events.rs` (держим модуль под
// лимитом 250 строк; `src/xdp/filter/` уже на пределе в 4 файла на каталог).
// Parser and policy coverage lives in `tests/xdp_events.rs` (this module is kept under
// the 250-line limit; `src/xdp/filter/` already has the maximum of 4 files per directory).

View file

@ -41,28 +41,29 @@ impl XdpFilter {
}
}
/// Задаёт глобалы для патчинга `.rodata` при следующем `load()`.
/// Sets the globals used to patch `.rodata` on the next `load()`.
pub fn set_globals(&mut self, globals: XdpGlobals) {
self.globals = globals;
}
/// Подключает OPT-IN авто-бан по ringbuf-событиям к userspace-`Blacklist`.
/// Wires the opt-in auto-ban from ringbuf events into the userspace `Blacklist`.
///
/// До вызова `load()`. Политика читается из `[xdp]`-секции; если
/// `auto_ban_enabled = false` (по умолчанию), колбэк лишь логирует события и
/// не трогает blacklist.
/// Must be called before `load()`. The policy is read from the `[xdp]` section; when
/// `auto_ban_enabled = false` (the default) the callback only logs events and never
/// touches the blacklist.
pub fn set_autoban(&mut self, blacklist: Arc<Blacklist>, config: &XdpConfig) {
self.blacklist = Some(blacklist);
self.autoban = AutoBanConfig::from_xdp(config);
}
pub fn load(&mut self) -> Result<()> {
// Диагностика ДО загрузки: fail-fast на неподдерживаемом ядре/драйвере.
// Diagnostics before loading: fail fast on an unsupported kernel or driver.
super::probe::preflight(&self.interface)?;
let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
// Имя объекта задаётся ЯВНО: при open_memory libbpf не знает имени файла,
// а по нему именуются внутренние maps ("rampart_.rodata" в patch_rodata).
// The object name is set explicitly: with `open_memory` libbpf does not know the
// file name, yet the internal maps are named after it (`rampart_.rodata`, see
// `patch_rodata`).
let mut open_obj = ObjectBuilder::default()
.name("rampart")
.context("failed to set BPF object name")?
@ -87,9 +88,9 @@ impl XdpFilter {
.find(|p| p.name() == "rampart_universal_filter")
.context("XDP program 'rampart_universal_filter' not found")?;
let xdp = Xdp::new(prog.as_fd());
// Лестница режимов: пробуем native (drv); если драйвер не тянет —
// честный fallback в generic (skb) с предупреждением (вывод №1 из
// конкурентного анализа: печатать режим как есть, без вранья).
// Mode ladder: try native (drv) first; if the driver cannot handle it, fall back to
// generic (skb) with a warning (finding #1 of the competitive analysis: report the
// mode as it is, no window dressing).
let ifindex = ifindex as i32;
if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) {
tracing::warn!(
@ -167,10 +168,10 @@ impl XdpFilter {
.with_context(|| format!("map '{}' not found", name))
}
/// Читает карту `prefix_stats` (агрегаты по префиксам /24 и /64).
/// Reads the `prefix_stats` map (aggregates per /24 and /64 prefix).
///
/// # Errors
/// XDP не загружен, карта отсутствует в объекте или ошибка BPF-чтения.
/// XDP is not loaded, the map is missing from the object, or a BPF read fails.
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
let map = self.find_map("prefix_stats")?;
let mut out = Vec::new();

View file

@ -1,53 +1,58 @@
//! Патчинг volatile const глобалов XDP-программы (`xdp/core/config.h`) из TOML-конфига.
//! Patches the XDP program's volatile-const globals (`xdp/core/config.h`) from the TOML config.
//!
//! Глобалы живут в секции `.rodata`, которая при загрузке превращается в карту
//! с именем `rampart_.rodata`. Образ патчится до `load()` через
//! `OpenMapMut::set_initial_value()` (см. [`crate::xdp::filter`]).
//! The globals live in the `.rodata` section, which libbpf turns into a map named
//! `rampart_.rodata` on load. The image is patched before `load()` via
//! `OpenMapMut::set_initial_value()` (see [`crate::xdp::filter`]).
//!
//! # Схема маппинга `[xdp]` → G_* (единственный источник истины)
//! # `[xdp]` -> `G_*` mapping (single source of truth)
//!
//! | Конфиг | Глобал | Тип |
//! | Config key | Global | Type |
//! |-------------------------|------------------------------|-----|
//! | `protected_port_start` | `G_START_PORT` | u16 |
//! | `protected_port_end` | `G_END_PORT` | u16 |
//! | `udp_policy` | `G_UDP_POLICY` | u8 ("pass"=0, "drop"=1, "rate-limit"=2) |
//! | `udp_rate_hit_count` | `G_UDP_HIT_COUNT` | u32 |
//! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (мс → нс) |
//! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool → 0/1) |
//! | `events_enabled` | `G_FEATURE_EVENTS` | u8 (bool → 0/1) |
//! | `syn_challenge_enabled` | `G_SYN_CHALLENGE_ENABLED` | u8 (bool → 0/1) |
//! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (ms -> ns) |
//! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool -> 0/1) |
//! | `events_enabled` | `G_FEATURE_EVENTS` | u8 (bool -> 0/1) |
//! | `syn_challenge_enabled` | `G_SYN_CHALLENGE_ENABLED` | u8 (bool -> 0/1) |
//! | `challenge_secret_hex` | `G_CHALLENGE_SECRET` | u64 (hex, big-endian) |
//! | `challenge_timeout_ms` | `G_CHALLENGE_TIMEOUT_MS` | u32 |
//!
//! Остальные глобалы (`G_SYN_*`, `G_CONNTRACK_IDLE_NS`, `G_PLAYER_IDLE_NS`,
//! `G_BAN_DURATION_NS`, `G_MAX_OUT_OF_ORDER`, `G_CHALLENGE_VERIFIED_TTL_NS`)
//! конфигом пока не управляются и патчатся значениями по умолчанию из config.h.
//! The remaining globals (`G_SYN_*`, `G_CONNTRACK_IDLE_NS`, `G_PLAYER_IDLE_NS`,
//! `G_BAN_DURATION_NS`, `G_MAX_OUT_OF_ORDER`, `G_CHALLENGE_VERIFIED_TTL_NS`) are not
//! configurable yet; they are patched with the defaults from config.h.
use anyhow::{Context, Result, bail};
use std::mem::offset_of;
use crate::config::XdpConfig;
/// Имя карты с образом `.rodata` загруженного BPF-объекта.
/// Имя внутренней `.rodata`-карты при `ObjectBuilder::name("rampart")`:
/// libbpf конструирует `<obj_name><section>` без замены точки (sanitizer
/// пропускаёт `.`; libbpf.c, map name logic) → `rampart.rodata`.
/// Поиск в `patch_rodata` всё равно по суффиксу — имя здесь для диагностики.
/// Name of the map holding the loaded BPF object's `.rodata` image.
///
/// This is the name of libbpf's internal `.rodata` map when the object is built with
/// `ObjectBuilder::name("rampart")`: libbpf concatenates `<obj_name><section>` without
/// rewriting the dot (the sanitizer passes `.` through; see libbpf.c map naming), so the
/// result is `rampart.rodata`. `patch_rodata` matches by suffix anyway, so the name is
/// only used for diagnostics.
pub(crate) const RODATA_MAP_NAME: &str = "rampart.rodata";
/// Размер образа `.rodata` в байтах (см. `build_rodata_image`).
pub const RODATA_SIZE: usize = 96;
/// Size of the `.rodata` image in bytes: exactly `sizeof(struct rampart_config)` from
/// `xdp/core/config.h`, which `XdpGlobals` (`#[repr(C)]`) mirrors field for field.
pub const RODATA_SIZE: usize = std::mem::size_of::<XdpGlobals>();
/// Значение `G_UDP_POLICY`: пропускать UDP.
/// `G_UDP_POLICY` value: pass UDP through.
pub const UDP_POLICY_PASS: u8 = 0;
/// Значение `G_UDP_POLICY`: дропать весь UDP.
/// `G_UDP_POLICY` value: drop all UDP.
pub const UDP_POLICY_DROP: u8 = 1;
/// Значение `G_UDP_POLICY`: rate-limit по окну/порогу.
/// `G_UDP_POLICY` value: rate-limit per window/threshold.
pub const UDP_POLICY_RATE_LIMIT: u8 = 2;
/// Дефолт-плейсхолдер `G_CHALLENGE_SECRET` из config.h.
/// Default placeholder for `G_CHALLENGE_SECRET` from config.h.
const DEFAULT_CHALLENGE_SECRET: u64 = 0xA5A5_A5A5_A5A5_A5A5;
/// Runtime-значения глобалов XDP-программы; `Default` совпадает с config.h.
/// Runtime values of the XDP program globals; `Default` matches config.h.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XdpGlobals {
pub start_port: u16,
@ -96,53 +101,55 @@ impl Default for XdpGlobals {
}
impl XdpGlobals {
/// Собирает байтовый образ `.rodata` в порядке объявления глобалов
/// в `xdp/core/config.h` с естественным выравниванием каждого поля.
/// Builds the byte image of `.rodata`: a mirror of `struct rampart_config` from
/// `xdp/core/config.h`.
///
/// RISK: раскладка предполагает, что линкер кладёт статические переменные
/// в секцию `.rodata` в порядке объявления с natural alignment — на
/// практике это так (каждая `static volatile const` получает своё
/// выравнивание, padding виден в смещениях ниже), но стандарт C этого не
/// гарантирует. TODO: верифицировать смещения на сервере через BTF-dump
/// карты `rampart_.rodata` (`bpftool btf dump`) и зафиксировать их здесь.
/// Offsets come from the `#[repr(C)]` type itself (`offset_of!`) instead of being
/// hardcoded, because the layout is defined by the C struct — not by the symbol order
/// the linker happens to pick.
pub fn build_rodata_image(&self) -> Vec<u8> {
let mut img = vec![0u8; RODATA_SIZE];
// u16 ×2 без padding: смещения 0..4.
img[0..2].copy_from_slice(&self.start_port.to_le_bytes());
img[2..4].copy_from_slice(&self.end_port.to_le_bytes());
// u32, align 4: 4..8.
img[4..8].copy_from_slice(&self.syn_hit_count.to_le_bytes());
// u64, align 8: 8..48 (SYN throttle + idle timeouts + ban duration).
img[8..16].copy_from_slice(&self.syn_window_ns.to_le_bytes());
img[16..24].copy_from_slice(&self.syn_ban_duration_ns.to_le_bytes());
img[24..32].copy_from_slice(&self.conntrack_idle_ns.to_le_bytes());
img[32..40].copy_from_slice(&self.player_idle_ns.to_le_bytes());
img[40..48].copy_from_slice(&self.ban_duration_ns.to_le_bytes());
// u8 ×3 подряд: 48, 49, 50 (max_out_of_order, udp_policy, —).
img[48] = self.max_out_of_order;
img[49] = self.udp_policy;
// u32 после u8: padding 50..52, значение 52..56.
img[52..56].copy_from_slice(&self.udp_hit_count.to_le_bytes());
// u64, align 8: 56..64.
img[56..64].copy_from_slice(&self.udp_window_ns.to_le_bytes());
// u8 ×3 (feature flags + challenge flag): 64, 65, 66.
img[64] = u8::from(self.feature_syn_throttle);
img[65] = u8::from(self.feature_events);
img[66] = u8::from(self.syn_challenge_enabled);
// u64 после u8: padding 67..72, значение 72..80.
img[72..80].copy_from_slice(&self.challenge_secret.to_le_bytes());
// u32: 80..84.
img[80..84].copy_from_slice(&self.challenge_timeout_ms.to_le_bytes());
// u64 после u32: padding 84..88, значение 88..96.
img[88..96].copy_from_slice(&self.challenge_verified_ttl_ns.to_le_bytes());
let put16 = |img: &mut [u8], off: usize, v: u16| img[off..off + 2].copy_from_slice(&v.to_le_bytes());
let put32 = |img: &mut [u8], off: usize, v: u32| img[off..off + 4].copy_from_slice(&v.to_le_bytes());
let put64 = |img: &mut [u8], off: usize, v: u64| img[off..off + 8].copy_from_slice(&v.to_le_bytes());
put16(&mut img, offset_of!(Self, start_port), self.start_port);
put16(&mut img, offset_of!(Self, end_port), self.end_port);
put32(&mut img, offset_of!(Self, syn_hit_count), self.syn_hit_count);
put64(&mut img, offset_of!(Self, syn_window_ns), self.syn_window_ns);
put64(
&mut img,
offset_of!(Self, syn_ban_duration_ns),
self.syn_ban_duration_ns,
);
put64(&mut img, offset_of!(Self, conntrack_idle_ns), self.conntrack_idle_ns);
put64(&mut img, offset_of!(Self, player_idle_ns), self.player_idle_ns);
put64(&mut img, offset_of!(Self, ban_duration_ns), self.ban_duration_ns);
img[offset_of!(Self, max_out_of_order)] = self.max_out_of_order;
img[offset_of!(Self, udp_policy)] = self.udp_policy;
put32(&mut img, offset_of!(Self, udp_hit_count), self.udp_hit_count);
put64(&mut img, offset_of!(Self, udp_window_ns), self.udp_window_ns);
img[offset_of!(Self, feature_syn_throttle)] = u8::from(self.feature_syn_throttle);
img[offset_of!(Self, feature_events)] = u8::from(self.feature_events);
img[offset_of!(Self, syn_challenge_enabled)] = u8::from(self.syn_challenge_enabled);
put64(&mut img, offset_of!(Self, challenge_secret), self.challenge_secret);
put32(
&mut img,
offset_of!(Self, challenge_timeout_ms),
self.challenge_timeout_ms,
);
put64(
&mut img,
offset_of!(Self, challenge_verified_ttl_ns),
self.challenge_verified_ttl_ns,
);
img
}
/// Строит глобалы из секции `[xdp]` конфига.
/// Builds the globals from the `[xdp]` section of the config.
///
/// # Errors
/// Неизвестное значение `udp_policy`; некорректный `challenge_secret_hex`
/// (не hex или не 8 байт); `protected_port_end < protected_port_start`.
/// Unknown `udp_policy` value; malformed `challenge_secret_hex` (not hex, or not
/// 8 bytes); `protected_port_end < protected_port_start`.
pub fn from_config(cfg: &XdpConfig) -> Result<Self> {
let mut g = Self {
start_port: cfg.protected_port_start,
@ -175,7 +182,8 @@ impl XdpGlobals {
}
}
/// Парсит 128-битный hex (16 символов, опциональный префикс `0x`) в u64 (big-endian).
/// Parses a 16-hex-digit secret (8 bytes, optional `0x` prefix) into a big-endian u64.
/// `_`, `:` and `-` separators are ignored.
fn parse_secret_hex(s: &str) -> Result<u64> {
let cleaned = s.trim().trim_start_matches("0x").replace(['_', ':', '-'], "");
let bytes = hex::decode(&cleaned).with_context(|| format!("invalid xdp.challenge_secret_hex '{s}'"))?;

View file

@ -1,20 +1,21 @@
//! Prometheus-метрики загрузчика XDP.
//! Prometheus metrics of the XDP loader.
//!
//! Регистрируются в глобальный реестр `prometheus` (тот же, что собирает
//! `prometheus::gather()` в `crate::metrics::run_metrics_server`), поэтому
//! endpoint `/metrics` подхватывает их без правок вне `src/xdp/`.
//! They register into the global `prometheus` registry — the same one that
//! `prometheus::gather()` in `crate::metrics::run_metrics_server` scrapes — so the
//! `/metrics` endpoint picks them up without changes outside `src/xdp/`.
use prometheus::{IntCounter, register_int_counter};
use std::sync::LazyLock;
/// Сколько раз событие XDP-ringbuf привело к userspace-авто-бану
/// (счётчик инкрементится только на НОВЫЙ бан, не на продление).
/// How many times an XDP ringbuf event resulted in a userspace auto-ban.
///
/// The counter is incremented only for a new ban, never for a refresh of an active one.
pub static XDP_AUTOBANS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!("rampart_xdp_autobans_total", "Auto-bans issued from XDP ringbuf events")
.expect("XDP_AUTOBANS_TOTAL")
});
/// Форсирует регистрацию счётчика (для вызова на старте загрузки XDP).
/// Forces registration of the counter (called at the start of the XDP load).
pub fn init() {
LazyLock::force(&XDP_AUTOBANS_TOTAL);
}

View file

@ -1,4 +1,8 @@
//! Загрузчик XDP-программы (L3/L4-уровень защиты).
//! Loader for the XDP program (L3/L4 protection layer).
//!
//! Owns the filter lifecycle (`XdpFilter`), the `.rodata` globals image (`XdpGlobals`),
//! ringbuf event parsing, XDP metrics and the pre-attach environment probe. Without the
//! `xdp` feature a no-op filter is exported instead.
mod probe;
pub use probe::{
@ -9,7 +13,7 @@ pub use probe::{
#[cfg(feature = "xdp")]
mod globals;
#[cfg(feature = "xdp")]
pub use globals::XdpGlobals;
pub use globals::{RODATA_SIZE, XdpGlobals};
#[cfg(feature = "xdp")]
mod metrics;

View file

@ -23,10 +23,10 @@ impl XdpFilter {
Ok(())
}
/// Честная ошибка: чтение `prefix_stats` не подключено без feature `xdp`.
/// Honest failure: reading `prefix_stats` is not wired up without the `xdp` feature.
///
/// # Errors
/// Всегда — сборка без XDP не имеет доступа к картам ядра.
/// Always: a build without XDP has no access to the kernel maps.
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
anyhow::bail!("prefix_stats reading not wired yet: built without xdp feature")
}

View file

@ -1,8 +1,8 @@
//! Диагностика окружения перед XDP-attach: ядро, BTF, драйвер NIC, привилегии.
//! Environment diagnostics before XDP attach: kernel, BTF, NIC driver, privileges.
//!
//! Основной источник боли при XDP — непонятные ошибки attach на неподдерживаемых
//! ядрах и драйверах. Модуль собирает [`EnvironmentReport`] ДО загрузки BPF-программы
//! и даёт человекочитаемый вердикт с предупреждениями.
//! The main source of pain with XDP is opaque attach failures on unsupported kernels and
//! drivers. This module collects an [`EnvironmentReport`] before the BPF program is
//! loaded and produces a human-readable verdict with warnings.
mod report;
mod types;

View file

@ -5,7 +5,7 @@ use super::types::{
driver_supports_native_xdp,
};
/// Структурированный отчёт о пригодности окружения для XDP.
/// Structured report on how suitable the environment is for XDP.
pub struct EnvironmentReport {
pub kernel_version: Option<KernelVersion>,
pub btf_available: bool,
@ -15,7 +15,7 @@ pub struct EnvironmentReport {
}
impl EnvironmentReport {
/// Собирает отчёт через произвольную реализацию [`SystemProbe`].
/// Collects the report through any [`SystemProbe`] implementation.
#[must_use]
pub fn collect(probe: &dyn SystemProbe, interface: &str) -> Self {
let kernel_version = probe
@ -61,7 +61,7 @@ impl EnvironmentReport {
}
}
/// Ожидаемый режим attach по таблице драйверов.
/// Expected attach mode according to the driver table.
#[must_use]
pub fn attach_mode(&self) -> AttachMode {
match self.driver_name.as_deref() {
@ -70,7 +70,7 @@ impl EnvironmentReport {
}
}
/// Человекочитаемое объяснение вердикта.
/// Human-readable explanation of the verdict.
#[must_use]
pub fn verdict(&self) -> String {
let kernel = self
@ -87,10 +87,10 @@ impl EnvironmentReport {
}
}
/// Fail-fast проверка минимальной версии ядра.
/// Fail-fast check of the minimum kernel version.
///
/// # Errors
/// Версия ядра не определена или ниже [`MIN_KERNEL`].
/// The kernel version is unknown or below [`MIN_KERNEL`].
pub fn validate(&self) -> Result<()> {
let Some(version) = self.kernel_version else {
bail!("не удалось определить версию ядра ({OSRELEASE_PATH}) — XDP attach отклонён");
@ -102,11 +102,11 @@ impl EnvironmentReport {
}
}
/// Предстартовая диагностика перед загрузкой XDP-программы:
/// структурный отчёт в лог, предупреждения, fail-fast на старом ядре.
/// Pre-attach diagnostics before the XDP program is loaded: a structured report in the
/// log, warnings, and a fail-fast check for an old kernel.
///
/// # Errors
/// См. [`EnvironmentReport::validate`].
/// See [`EnvironmentReport::validate`].
#[cfg(feature = "xdp")]
pub(crate) fn preflight(interface: &str) -> Result<()> {
use super::types::FilesystemProbe;

View file

@ -1,15 +1,15 @@
use std::fmt;
/// Минимально поддерживаемая версия ядра: 5.15 LTS.
/// Minimum supported kernel version: 5.15 LTS.
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";
/// Драйверы с известной поддержкой native XDP (по данным xdpgeneric/native
/// матриц upstream-ядра). Отсутствие в списке не означает отсутствие поддержки,
/// но для таких драйверов предсказываем generic mode.
/// Drivers with known native XDP support (from the upstream kernel's native/generic
/// matrices). Absence from this list does not mean support is missing, but for such
/// drivers generic mode is predicted.
const NATIVE_XDP_DRIVERS: &[&str] = &[
"virtio_net",
"ixgbe",
@ -31,7 +31,7 @@ const NATIVE_XDP_DRIVERS: &[&str] = &[
"macvlan",
];
/// Версия ядра Linux, пригодная для сравнения (`major.minor.patch`).
/// Linux kernel version, suitable for comparison (`major.minor.patch`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct KernelVersion {
pub major: u16,
@ -45,9 +45,9 @@ impl KernelVersion {
Self { major, minor, patch }
}
/// Парсит строку формата `uname -r`. Берёт первые три числовых компонента,
/// дистрибутивные суффиксы (`6.8.0-45-generic`, `5.15.0-rc2`) отбрасываются.
/// Строка без цифр не парсится.
/// Parses a `uname -r` style string. Takes the first three numeric components and
/// discards distribution suffixes (`6.8.0-45-generic`, `5.15.0-rc2`). A string without
/// digits does not parse.
#[must_use]
pub fn parse(release: &str) -> Option<Self> {
let mut nums = release
@ -66,15 +66,16 @@ impl fmt::Display for KernelVersion {
}
}
/// Режим присоединения XDP-программы к интерфейсу.
/// Mode in which the XDP program is attached to the interface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachMode {
/// Программа исполняется в контексте драйвера NIC — минимальные накладные расходы.
/// The program runs in the NIC driver context: lowest overhead.
Native,
/// Программа вызывается из сетевого стека после ingress — работает везде, дороже по CPU.
/// The program is invoked from the network stack after ingress: works everywhere, but
/// costs more CPU.
Generic,
/// Аппаратная разгрузка в NIC — требует явного включения и поддержки железа,
/// автоматически не выбирается.
/// Hardware offload into the NIC: requires explicit enablement and hardware support,
/// never selected automatically.
Offload,
}
@ -88,13 +89,13 @@ impl fmt::Display for AttachMode {
}
}
/// Абстракция над procfs/sysfs: реальная реализация — [`FilesystemProbe`],
/// в тестах — мок. Изолирует диагностику от реального ядра.
/// Abstraction over procfs/sysfs: the real implementation is [`FilesystemProbe`], tests
/// supply a mock. Keeps the diagnostics independent of the real kernel.
pub trait SystemProbe {
/// Читает файл целиком.
/// Reads a file in full.
///
/// # Errors
/// Проксирует ошибку чтения файла.
/// Proxies the file read error.
fn read_file(&self, path: &str) -> std::io::Result<String>;
#[must_use]
@ -107,7 +108,7 @@ pub trait SystemProbe {
fn effective_uid(&self) -> u32;
}
/// Реальная реализация [`SystemProbe`] поверх `std::fs`.
/// Real [`SystemProbe`] implementation on top of `std::fs`.
pub struct FilesystemProbe;
impl SystemProbe for FilesystemProbe {
@ -123,10 +124,10 @@ impl SystemProbe for FilesystemProbe {
Some(std::fs::read_link(path).ok()?.to_string_lossy().into_owned())
}
/// Эвристика: эффективный uid берётся из `/proc/self/status`.
/// root почти всегда имеет CAP_BPF/CAP_NET_ADMIN (если явно не урезаны);
/// для не-root подтверждение возможно только попыткой attach.
/// Нечитаемый статус трактуем как непривилегированный процесс.
/// Heuristic: the effective uid is taken from `/proc/self/status`. root almost always
/// holds CAP_BPF/CAP_NET_ADMIN (unless explicitly dropped); for non-root the only
/// confirmation is an actual attach attempt. An unreadable status is treated as an
/// unprivileged process.
fn effective_uid(&self) -> u32 {
std::fs::read_to_string(STATUS_PATH)
.ok()
@ -147,7 +148,7 @@ pub(super) fn driver_from_link(target: &str) -> Option<String> {
(!name.is_empty()).then(|| name.to_owned())
}
/// Поддерживает ли драйвер native XDP (по таблице известных драйверов).
/// Whether the driver supports native XDP (per the table of known drivers).
#[must_use]
pub fn driver_supports_native_xdp(driver: &str) -> bool {
NATIVE_XDP_DRIVERS.contains(&driver)

View file

@ -1,4 +1,4 @@
//! Зондирование XDP-окружения: диагностика, статистика и метрики.
//! XDP environment probing: diagnostics, statistics and metrics.
mod diagnostics;
#[cfg(feature = "xdp")]

View file

@ -1,4 +1,4 @@
/// Счётчики XDP-программы; индексы соответствуют STAT_* из xdp/core/maps.h.
/// XDP program counters; the indices follow `STAT_*` from `xdp/core/maps.h`.
#[derive(Debug, Clone, Copy, Default)]
pub struct XdpStats {
pub total: u64,