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,6 +1,8 @@
//! Detection sections (`[detect*]`) and the per-protocol handler policy.
use serde::Deserialize;
/// Секция `[detect]`: детекторы распределённых атак.
/// `[detect]` section: distributed attack detectors.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DetectConfig {
#[serde(default)]
@ -11,9 +13,10 @@ pub struct DetectConfig {
pub alert: DetectAlertConfig,
}
/// Секция `[detect.autoban]`: авто-бан источников по репутации и сигналам
/// детектора атак. Порог сравнивается со скором [`crate::traffic::reputation::IpReputation`],
/// TTL берётся из `ban.ban_duration_secs`.
/// `[detect.autoban]` section: auto-ban sources based on reputation and attack
/// detector signals. The threshold is compared against the
/// [`crate::traffic::reputation::IpReputation`] score, the TTL comes from
/// `ban.ban_duration_secs`.
#[derive(Debug, Clone, Deserialize)]
pub struct DetectAutobanConfig {
#[serde(default)]
@ -35,15 +38,15 @@ fn default_autoban_reputation_threshold() -> i32 {
-50
}
/// Секция `[detect.alert]`: webhook-алерты на переходах состояния атаки
/// («атака началась» / «атака закончилась»).
/// `[detect.alert]` section: webhook alerts on attack state transitions
/// (attack started, attack ended).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DetectAlertConfig {
#[serde(default)]
pub webhook_url: Option<String>,
}
/// Секция `[detect.prefix]`: subnet-level детектор распределённых атак.
/// `[detect.prefix]` section: subnet-level detector for distributed attacks.
#[derive(Debug, Clone, Deserialize)]
pub struct DetectPrefixConfig {
#[serde(default)]
@ -77,7 +80,7 @@ fn default_prefix_min_unique_sources() -> u64 {
16
}
/// Секция `[protocol]`: протокольные обработчики (plugin-by-feature).
/// `[protocol]` section: protocol handlers, enabled one plugin per feature.
#[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ProtocolConfig {
@ -89,6 +92,7 @@ pub struct ProtocolConfig {
pub minecraft: MinecraftProtocolConfig,
}
/// `[protocol.minecraft]` section: Minecraft handshake handler policy.
#[cfg(feature = "protocol-minecraft")]
#[derive(Debug, Clone, Deserialize)]
pub struct MinecraftProtocolConfig {
@ -129,7 +133,7 @@ fn default_minecraft_timeout_secs() -> u64 {
5
}
/// Секция `[protocol.http]`: политика HTTP/1.1-обработчика на edge-ноде.
/// `[protocol.http]` section: HTTP/1.1 handler policy on the edge node.
#[cfg(feature = "protocol-http")]
#[derive(Debug, Clone, Deserialize)]
pub struct HttpProtocolConfig {

View file

@ -1,7 +1,10 @@
//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
use serde::{Deserialize, Deserializer};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
/// `[bind]` section: listen address and port of the edge node.
#[derive(Debug, Clone, Deserialize)]
pub struct BindConfig {
#[serde(default = "default_bind_address")]
@ -26,7 +29,7 @@ fn default_bind_port() -> u16 {
25565
}
/// Generic upstream-бэкенды (список addr:port) за edge-нодой.
/// `[backend]` section: upstream backends (`addr:port`) behind the edge node.
#[derive(Debug, Clone, Deserialize)]
pub struct BackendConfig {
#[serde(default = "default_upstreams")]
@ -45,6 +48,7 @@ fn default_upstreams() -> Vec<String> {
vec!["127.0.0.1:25566".to_string()]
}
/// `[workers]` section: number of accept loops sharing the listen address.
#[derive(Debug, Clone, Deserialize)]
pub struct WorkerConfig {
#[serde(default = "default_worker_count")]
@ -61,6 +65,7 @@ fn default_worker_count() -> usize {
4
}
/// `[limits]` section: per-IP connection and rate limits.
#[derive(Debug, Clone, Deserialize)]
pub struct LimitsConfig {
#[serde(default = "default_handshake_timeout")]
@ -97,6 +102,7 @@ fn default_rate_limit_burst() -> f64 {
10.0
}
/// `[ban]` section: default ban duration.
#[derive(Debug, Clone, Deserialize)]
pub struct BanConfig {
#[serde(default = "default_ban_duration")]
@ -115,6 +121,7 @@ fn default_ban_duration() -> u64 {
3600
}
/// `[pow]` section: proof-of-work gate.
#[derive(Debug, Clone, Deserialize)]
pub struct PowConfig {
#[serde(default)]
@ -131,7 +138,6 @@ impl Default for PowConfig {
}
}
}
fn default_pow_difficulty() -> u8 {
4
}
@ -144,25 +150,14 @@ pub struct TrustedProxyCidr {
}
impl TrustedProxyCidr {
/// Returns whether `ip` belongs to this network.
#[must_use]
pub fn contains(&self, ip: IpAddr) -> bool {
let mask4 = mask_v4(self.prefix_len);
let mask6 = mask_v6(self.prefix_len);
match (self.network, ip) {
(IpAddr::V4(network), IpAddr::V4(ip)) => {
let mask = if self.prefix_len == 0 {
0
} else {
u32::MAX << (32 - self.prefix_len)
};
u32::from(network) & mask == u32::from(ip) & mask
},
(IpAddr::V6(network), IpAddr::V6(ip)) => {
let mask = if self.prefix_len == 0 {
0
} else {
u128::MAX << (128 - self.prefix_len)
};
u128::from(network) & mask == u128::from(ip) & mask
},
(IpAddr::V4(network), IpAddr::V4(ip)) => u32::from(network) & mask4 == u32::from(ip) & mask4,
(IpAddr::V6(network), IpAddr::V6(ip)) => u128::from(network) & mask6 == u128::from(ip) & mask6,
_ => false,
}
}
@ -213,6 +208,7 @@ fn mask_v6(prefix: u8) -> u128 {
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
}
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
#[derive(Debug, Clone, Deserialize)]
pub struct ProxyProtocolConfig {
#[serde(default)]

View file

@ -1,4 +1,4 @@
//! Секции единого конфига платформы.
//! Sections of the platform config.
mod detect;
mod edge;

View file

@ -1,5 +1,8 @@
//! Platform sections: store backends, XDP, logging and metrics.
use serde::Deserialize;
/// `[store]` section: redis and ClickHouse backends.
#[derive(Debug, Clone, Deserialize)]
pub struct StoreConfig {
pub redis_url: Option<String>,
@ -22,6 +25,7 @@ fn default_blacklist_cache_ttl() -> u64 {
300
}
/// `[xdp]` section: kernel-side filter configuration and auto-ban policy.
#[derive(Debug, Clone, Deserialize)]
pub struct XdpConfig {
#[serde(default)]
@ -32,7 +36,7 @@ pub struct XdpConfig {
pub protected_port_start: u16,
#[serde(default = "default_xdp_port_end")]
pub protected_port_end: u16,
/// "pass" | "drop" | "rate-limit" → G_UDP_POLICY.
/// UDP policy: "pass", "drop" or "rate-limit", mapped to `G_UDP_POLICY`.
#[serde(default = "default_xdp_udp_policy")]
pub udp_policy: String,
#[serde(default = "default_xdp_udp_hit_count")]
@ -41,7 +45,8 @@ pub struct XdpConfig {
pub udp_rate_window_ms: u64,
#[serde(default)]
pub syn_challenge_enabled: bool,
/// 128-битный hex (16 символов) для G_CHALLENGE_SECRET; None = плейсхолдер из config.h.
/// 128-bit hex (16 characters) for `G_CHALLENGE_SECRET`; `None` keeps the
/// placeholder from `config.h`.
#[serde(default)]
pub challenge_secret_hex: Option<String>,
#[serde(default = "default_xdp_challenge_timeout_ms")]
@ -50,14 +55,15 @@ pub struct XdpConfig {
pub throttle_enabled: bool,
#[serde(default = "default_xdp_events_enabled")]
pub events_enabled: bool,
/// OPT-IN: авто-бан по ringbuf-событиям XDP. По умолчанию выключен
/// («по умолчанию безопасно»): без него события только логируются.
/// Opt-in auto-ban driven by XDP ringbuf events. Disabled by default (secure
/// by default): without it events are only logged.
#[serde(default)]
pub auto_ban_enabled: bool,
/// Длительность авто-бана в секундах (для RATE_LIMIT/CONN_DROP).
/// Auto-ban duration in seconds (`RATE_LIMIT` / `CONN_DROP` events).
#[serde(default = "default_xdp_auto_ban_duration_secs")]
pub auto_ban_duration_secs: u64,
/// Порог `conn->fails` для авто-бана по EVENT_CONN_DROP (см. universal_filter.c:368).
/// `conn->fails` threshold for auto-ban on `EVENT_CONN_DROP`
/// (see `universal_filter.c:368`).
#[serde(default = "default_xdp_auto_ban_conn_drop_fails")]
pub auto_ban_conn_drop_fails: u8,
}
@ -118,6 +124,7 @@ fn default_xdp_auto_ban_conn_drop_fails() -> u8 {
3
}
/// `[logging]` section: log level and format.
#[derive(Debug, Clone, Deserialize)]
pub struct LoggingConfig {
#[serde(default = "default_log_level")]
@ -142,6 +149,7 @@ fn default_log_format() -> String {
"text".to_string()
}
/// `[metrics]` section: Prometheus scrape endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct MetricsConfig {
#[serde(default = "default_metrics_enabled")]