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

@ -1,3 +1,5 @@
//! Config parsing tests: defaults, section parsing and rejected invariants.
use rampart::config::Config;
#[test]

View file

@ -1,3 +1,6 @@
//! Integration tests for the accept-path filters: token-bucket rate limiting
//! and blacklist TTL handling.
use std::net::{IpAddr, Ipv4Addr};
use std::time::Duration;

View file

@ -1,3 +1,5 @@
//! Integration tests for the HTTP/1.1 protocol handler: request-head
//! accumulation across fragmented writes and policy rejection paths.
#![cfg(feature = "protocol-http")]
use rampart::config::HttpProtocolConfig;

View file

@ -1,3 +1,6 @@
//! PoW roundtrip tests: solver output must satisfy the verifier, replays and
//! garbage must not.
use rampart::engine::challenge::{Challenge, solve};
/// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1",

View file

@ -1,3 +1,6 @@
//! Protocol registry tests: empty registries fail fast, registered handlers
//! resolve by name.
use std::future::Future;
use std::pin::Pin;

View file

@ -1,4 +1,4 @@
//! Интеграционные тесты subnet-level детекции: трекер → детектор → вердикты.
//! Integration tests for subnet-level detection: tracker, detector and verdicts.
use rampart::config::Config;
use rampart::engine::subnet_tracker::SubnetTracker;
@ -12,7 +12,7 @@ fn v4(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
}
/// Фиксированный источник снапшотов — имитирует XDP-карту без ядра.
/// Fixed snapshot source that imitates the XDP map without a kernel.
struct FixedSource(Vec<(IpAddr, PrefixSnapshot)>);
impl PrefixStatsSource for FixedSource {
@ -24,8 +24,8 @@ impl PrefixStatsSource for FixedSource {
#[tokio::test]
async fn tracker_feeds_detector_and_blocks_distributed_attack() {
let tracker = SubnetTracker::new();
// 40 уникальных источников из одного /24 — распределённая атака
// (6 SYN от каждого: 240 >= 4 × threshold(50)).
// 40 unique sources from one /24 is a distributed attack: 6 SYNs each,
// i.e. 240 >= 4 x threshold(50).
for _ in 0..6 {
for last in 1..=40u8 {
tracker.record_connection(v4([203, 0, 113, last]));
@ -41,7 +41,7 @@ async fn tracker_feeds_detector_and_blocks_distributed_attack() {
assert_eq!(verdicts[0].snapshot.syn_count, 240);
assert_eq!(verdicts[0].snapshot.unique_sources, 40);
// Полный конвейер через трейт-источник (как в бинарнике).
// Full pipeline through the trait source, the way the binary drives it.
let source_snaps = FixedSource(snaps).snapshot().await.expect("source snapshot");
assert_eq!(detector.evaluate(&source_snaps)[0].verdict, SubnetVerdict::Block);
}
@ -49,7 +49,7 @@ async fn tracker_feeds_detector_and_blocks_distributed_attack() {
#[tokio::test]
async fn spoof_gate_many_syn_few_sources_no_block() {
let tracker = SubnetTracker::new();
// 500 SYN всего из 3 адресов — всплеск, но не распределённый.
// 500 SYNs from only 3 addresses: a burst, but not distributed.
for _ in 0..167 {
for ip in [v4([198, 51, 100, 1]), v4([198, 51, 100, 2]), v4([198, 51, 100, 3])] {
tracker.record_connection(ip);
@ -180,7 +180,7 @@ fn escalation_ladder_monitor_to_block() {
#[test]
fn spoof_gate_downgrades_block_to_challenge() {
let detector = SubnetDetector::new(100, 16);
// Много SYN из одного источника (или неизвестное разнообразие) → нет Block.
// Many SYNs from one source (or unknown diversity) must not yield Block.
let few = PrefixSnapshot {
syn_count: 1000,
unique_sources: 3,

View file

@ -1,5 +1,6 @@
//! Интеграционные тесты Traffic Intelligence в hot path: авто-бан по
//! репутации, детектор атак на синтетическом всплеске, алерты на переходах.
//! Integration tests for Traffic Intelligence on the hot path: auto-ban driven
//! by reputation, attack detection on a synthetic spike and alerts on state
//! transitions.
use rampart::config::DetectAutobanConfig;
use rampart::filter::blacklist::Blacklist;
@ -30,7 +31,7 @@ fn reputation_fall_after_drops_triggers_autoban() {
let attacker = ip([198, 51, 100, 7]);
for _ in 0..6 {
// Шесть дропов rate-limit'ом: -10 за каждый, порог auto-ban = -50.
// Six drops through the rate limiter: -10 each, auto-ban threshold is -50.
reputation.record_bad(attacker);
hook.on_connection_end(attacker);
}
@ -53,7 +54,7 @@ fn autoban_ttl_expires_ban() {
Arc::clone(&reputation),
Arc::clone(&blacklist),
autoban_cfg(true),
// Короткий TTL из «конфига» как мок времени.
// Zero TTL taken from the config as a time mock.
0,
);
let attacker = ip([198, 51, 100, 8]);
@ -72,12 +73,12 @@ fn autoban_ttl_expires_ban() {
fn detector_flags_synthetic_traffic_spike() {
let mut detector = AttackDetector::new();
// Базовая линия: тихий профиль.
// Baseline: a quiet profile.
for _ in 0..12 {
detector.analyze(500.0, 50.0);
}
// Синтетический всплеск: x200 pps и cps три окна подряд.
// Synthetic spike: 200x pps and cps for three consecutive windows.
assert_eq!(
detector.analyze(100_000.0, 10_000.0),
AttackStatus::Suspicious,

View file

@ -1,12 +1,11 @@
//! Тесты TUI-модуля: парсер Prometheus, расчёт rate, поведение при ошибках fetch.
//! Tests for the TUI module: Prometheus parser, rate calculation and fetch
//! error handling.
use futures::future::BoxFuture;
use rampart::tui::fetch::{FetchError, Fetcher, HttpFetcher};
use rampart::tui::prometheus::{MetricSample, parse};
use rampart::tui::state::{AppState, counter_rate};
// ---------- парсер ----------
#[test]
fn parses_metric_with_labels_value_and_timestamp() {
let set = parse("rampart_xdp_total{iface=\"eth0\",core=\"0\"} 123 1700000000000\n");
@ -53,11 +52,9 @@ fn parser_tolerates_malformed_lines() {
assert_eq!(set.samples().len(), 1);
}
// ---------- rate ----------
#[test]
fn rate_from_two_samples_divides_by_elapsed() {
// 1200 - 1100 = 100 пакетов за 2 сек
// 1200 - 1100 = 100 packets over 2 seconds.
assert_eq!(counter_rate(Some(1100.0), Some(1200.0), 2.0), 50.0);
}
@ -79,8 +76,6 @@ fn state_accumulates_history_rates() {
assert!(frame.snapshot.error.is_none());
}
// ---------- ошибки fetch (мок Fetcher + локальный HTTP-сервер) ----------
struct FailingFetcher {
error: FetchError,
}
@ -99,7 +94,7 @@ fn network_error_sets_error_banner_not_panic() {
error: FetchError::Network("connection refused".to_owned()),
};
// Тот же путь, что и в spawn_fetch_loop: normalize → apply_fetch.
// Same path as in spawn_fetch_loop: normalize, then apply_fetch.
let normalized = rampart::tui::app::normalize(Err(fetcher.error));
assert!(normalized.is_err());
let message = match normalized {

View file

@ -1,14 +1,14 @@
//! Часы бана: XDP сравнивает expiry с `bpf_ktime_get_ns()` (монотонные ns
//! с загрузки), поэтому userspace обязан писать то же самое. Регрессия:
//! раньше писался `SystemTime` (epoch ns ≈ 1.7e18), и бан не истекал никогда.
//! Ban clock: XDP compares expiry against `bpf_ktime_get_ns()` (monotonic nanoseconds
//! since boot), so userspace must write the same clock. Regression: `SystemTime` (epoch
//! nanoseconds, about 1.7e18) used to be written, and bans never expired.
#![cfg(feature = "xdp")]
use rampart::xdp::monotonic_ns;
fn clock_monotonic_ns() -> u64 {
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: `ts` — валидный writable `timespec`; CLOCK_MONOTONIC на Linux
// поддерживается всегда (xdp-фича собирается только под Linux).
// SAFETY: `ts` is a valid, writable `timespec`, and CLOCK_MONOTONIC is always
// supported on Linux (the xdp feature only builds on Linux).
let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
assert_eq!(rc, 0, "clock_gettime(CLOCK_MONOTONIC) failed");
let secs = u64::try_from(ts.tv_sec).expect("tv_sec fits u64");

View file

@ -1,6 +1,6 @@
//! Раскладка ключа `blacklist6_map` (LPM-trie): префикс-длина в байтах 0..4
//! little-endian + 16 байт адреса в network order (байты 4..20).
//! Ядро не нужно: проверяется чистая функция кодирования ключа.
//! Layout of the `blacklist6_map` key (LPM trie): the prefix length as a little-endian
//! u32 in bytes 0..4 plus the 16-byte address in network order (bytes 4..20).
//! No kernel needed: this exercises the pure key encoding function.
#![cfg(feature = "xdp")]
use rampart::xdp::blacklist6_key;
@ -28,7 +28,7 @@ fn key_layout_for_64_prefix() {
#[test]
fn leading_zero_address_is_not_confused_with_prefix_len() {
// ::1 — 15 нулевых байт перед единицей: ключ не должен «съесть» ни одного.
// ::1 has fifteen zero bytes before the final one: the key must not consume any of them.
let key = blacklist6_key(128, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(key[0], 128, "prefixlen is not overwritten by the address");

View file

@ -1,5 +1,5 @@
//! Интеграционные тесты wire-формата и политики авто-бана XDP-событий.
//! Ядро/Redis не нужны: проверяем чистые парсер и решение + дефолты конфига.
//! Integration tests for the wire format and the auto-ban policy of XDP events.
//! No kernel or Redis needed: the pure parser and decision are covered, plus config defaults.
#![cfg(feature = "xdp")]
use rampart::config::Config;
@ -8,21 +8,21 @@ use std::net::Ipv4Addr;
const IP: [u8; 4] = [203, 0, 113, 7];
/// Собирает кадр ровно как ядро (`push_event`, common.h:87-97): скаляры — native
/// (host) order, `src_ip` — сетевой порядок октетов (raw из заголовка пакета).
/// Builds a frame exactly as the kernel does (`push_event`, common.h:87-97): scalars in
/// native (host) order, `src_ip` in network octet order (raw from the packet header).
fn frame(kind: u32, octets: [u8; 4], metadata: u32, ts: u64) -> [u8; XDP_EVENT_LEN] {
let mut b = [0u8; XDP_EVENT_LEN];
b[0..4].copy_from_slice(&kind.to_ne_bytes());
b[4..8].copy_from_slice(&octets);
b[8..12].copy_from_slice(&metadata.to_ne_bytes());
// b[12..16] — выравнивающий padding под __u64: ядро его не инициализирует.
// b[12..16] is padding for `__u64`; the kernel does not initialise it.
b[16..24].copy_from_slice(&ts.to_ne_bytes());
b
}
#[test]
fn struct_size_is_24_bytes() {
// Раскладка common.h: __u32×3 + pad(4) + __u64 = 24, НЕ 16 как парсил код ранее.
// common.h layout: __u32 x3 + pad(4) + __u64 = 24, not 16 as the code parsed before.
assert_eq!(XDP_EVENT_LEN, 24);
}
@ -47,12 +47,12 @@ fn dirty_padding_does_not_corrupt_parse() {
#[test]
fn src_ip_is_network_order_octets_not_native_u32() {
// КЛЮЧЕВОЙ вывод по endianness: октеты лежат в точковом порядке напрямую.
// Key endianness insight: the octets sit in dotted order directly.
let f = frame(2, [198, 51, 100, 23], 0, 0);
let ev = parse_xdp_event(&f).expect("parses");
assert_eq!(ev.src_ip, Ipv4Addr::new(198, 51, 100, 23));
// Старый баг (`u32::from_ne_bytes` → Ipv4Addr::from(u32)) на little-endian
// давал бы переёрнутый адрес — фиксируем, что мы так НЕ делаем.
// The old bug (`u32::from_ne_bytes` -> `Ipv4Addr::from(u32)`) produced a reversed
// address on little-endian; this pins down that we do not do that.
if cfg!(target_endian = "little") {
let naive = u32::from_ne_bytes(<[u8; 4]>::try_from(&f[4..8]).expect("4 octets"));
assert_eq!(Ipv4Addr::from(naive), Ipv4Addr::new(23, 100, 51, 198));
@ -86,14 +86,14 @@ fn decision_matrix_by_type_and_enablement() {
enabled: false,
..AutoBanConfig::default()
};
// (kind, metadata=fails/хиты, банить ли при enabled)
// (kind, metadata=fails/hits, whether to ban when enabled)
let rows = [
(0u32, 255u32, false), // EVENT_BAN — ядро уже забанило: никогда
(1, 100, true), // EVENT_RATE_LIMIT — всегда баним
(2, 0, false), // EVENT_POLICY_DROP — политика по дефолту не банит
(3, 10, true), // EVENT_CONN_DROP fails=10 >= 3 — баним
(3, 0, false), // EVENT_CONN_DROP fails=0 (hook-drop) — не баним
(3, 2, false), // EVENT_CONN_DROP fails=2 < 3 — не баним
(0u32, 255u32, false), // EVENT_BAN: already banned by the kernel, never
(1, 100, true), // EVENT_RATE_LIMIT: always ban
(2, 0, false), // EVENT_POLICY_DROP: the policy does not ban by default
(3, 10, true), // EVENT_CONN_DROP fails=10 >= 3: ban
(3, 0, false), // EVENT_CONN_DROP fails=0 (hook drop): no ban
(3, 2, false), // EVENT_CONN_DROP fails=2 < 3: no ban
];
for (kind, meta, should_ban_when_on) in rows {
let ev = parse_xdp_event(&frame(kind, IP, meta, 0)).expect("known type");
@ -160,7 +160,7 @@ auto_ban_conn_drop_fails = 5
assert_eq!(policy.duration_secs, 45);
assert_eq!(policy.conn_drop_fails, 5);
// fails=4 ниже нового порога 5 — не бан; fails=5 — бан.
// fails=4 is below the new threshold of 5 (no ban); fails=5 reaches it (ban).
let below = parse_xdp_event(&frame(3, IP, 4, 0)).expect("frame parses");
assert!(auto_ban_decision(&below, &policy).is_none());
let at = parse_xdp_event(&frame(3, IP, 5, 0)).expect("frame parses");

58
tests/xdp_object_maps.rs Normal file
View file

@ -0,0 +1,58 @@
#![cfg(feature = "xdp")]
//! Contract between the loader (`src/xdp/filter/*`) and the C object: map names and the
//! `.rodata` size. Catches drift without root and without loading the program into the
//! kernel — exactly the class of bug that made XDP fail silently ("events_map not found",
//! "Invalid argument" on `.rodata`).
use libbpf_rs::ObjectBuilder;
use rampart::xdp::RODATA_SIZE;
fn open_object() -> libbpf_rs::OpenObject {
let bytes = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
ObjectBuilder::default()
.name("rampart")
.expect("object name")
.open_memory(bytes)
.expect("open XDP object (ELF/BTF parse must not need privileges)")
}
#[test]
fn every_map_the_loader_uses_exists_in_the_object() {
let obj = open_object();
let names: Vec<String> = obj.maps().map(|m| m.name().to_string_lossy().into_owned()).collect();
// Names come from `find_map`, `build_ringbuf` and `patch_rodata`.
for expected in [
"stats_map",
"prefix_stats",
"events_ringbuf",
"blacklist_map",
"blacklist6_map",
"whitelist_map",
"udp_rate_limit",
"udp_rate_limit6",
] {
assert!(
names.iter().any(|n| n == expected),
"loader expects map '{expected}', object has {names:?}"
);
}
assert!(
names.iter().any(|n| n.ends_with(".rodata")),
"loader expects a '.rodata' map, object has {names:?}"
);
}
#[test]
fn rodata_map_value_size_matches_loader_image() {
let obj = open_object();
let map = obj
.maps()
.find(|m| m.name().to_string_lossy().ends_with(".rodata"))
.expect("rodata map");
assert_eq!(
map.value_size() as usize,
RODATA_SIZE,
"sizeof(struct rampart_config) in config.h must equal sizeof(XdpGlobals)"
);
}