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:
parent
b64c329125
commit
a8a3057719
104 changed files with 2155 additions and 1030 deletions
|
|
@ -1,4 +1,4 @@
|
|||
//! Wiring-логика edge-демона: сборка сервисов и главный цикл запуска.
|
||||
//! Edge daemon wiring: service construction and the main run loop.
|
||||
|
||||
pub mod runtime;
|
||||
pub mod services;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
//! Runtime edge-демона: сборка компонентов, фоновые задачи и запуск listener.
|
||||
//! Edge daemon runtime: component assembly, background tasks and listener
|
||||
//! startup.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::engine::challenge::DifficultyAdjuster;
|
||||
|
|
@ -32,12 +33,12 @@ fn attack_status_value(status: AttackStatus) -> i64 {
|
|||
}
|
||||
}
|
||||
|
||||
/// Точка входа edge-демона (`rampart`): то, что делал `main` бинаря.
|
||||
/// Entry point of the edge daemon (`rampart`).
|
||||
///
|
||||
/// Возвращает [`RunExit`] — выбор кода и самого завершения делает бинарь.
|
||||
/// Returns [`RunExit`]; the binary decides whether and how the process ends.
|
||||
///
|
||||
/// # Errors
|
||||
/// Ошибки старта: нечитаемый конфиг, пустой реестр протоколов, сбой listener.
|
||||
/// Startup failures: unreadable config, empty protocol registry, listener error.
|
||||
pub async fn run() -> anyhow::Result<RunExit> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
|
|
@ -163,7 +164,7 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
|||
let status = det.lock().expect("detector lock poisoned").analyze(pps, cps);
|
||||
metrics::ATTACK_STATUS.set(attack_status_value(status));
|
||||
if let Some(alert) = alert_dispatcher.on_status(status) {
|
||||
// Дедупликация: алерт только на переходе состояния атаки.
|
||||
// Deduplication: an alert is emitted only on an attack state transition.
|
||||
metrics::INTEL_ALERTS_TOTAL.inc();
|
||||
tracing::warn!(pps, cps, "{alert}");
|
||||
push_attack_event(&ch, pps).await;
|
||||
|
|
@ -208,8 +209,8 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
|||
result?;
|
||||
Ok(RunExit::Ok)
|
||||
}
|
||||
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс
|
||||
// немедленно, как это делал прежний `process::exit(0)`.
|
||||
// The drain timeout fired: hand the signal back so the binary can end the
|
||||
// process immediately, replacing the former `process::exit(0)`.
|
||||
_ = drain_rx => Ok(RunExit::DrainTimeout),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
//! Сервисы edge-демона: реестр протоколов, whitelist, XDP и subnet-трекер.
|
||||
//! Edge daemon services: protocol registry, whitelist, XDP and the subnet
|
||||
//! tracker.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::engine::subnet::tracker::SubnetTracker;
|
||||
|
|
@ -13,11 +14,11 @@ use std::sync::Arc;
|
|||
use std::sync::Mutex;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Собирает реестр протоколов из скомпилированных реализаций.
|
||||
/// Builds the protocol registry from the compiled handlers.
|
||||
///
|
||||
/// Обработчики поставляются фичами: `protocol-http` регистрирует
|
||||
/// HTTP/1.1-обработчик с политикой из секции `[protocol.http]`.
|
||||
/// Внешние крейты регистрируют свои обработчики в этом же месте.
|
||||
/// Handlers are supplied by features: `protocol-http` registers the HTTP/1.1
|
||||
/// handler with the policy from `[protocol.http]`. External crates register
|
||||
/// their handlers at the same point.
|
||||
pub(crate) fn build_registry(config: &Config) -> ProtocolRegistry {
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
if config.protocol.minecraft.enabled {
|
||||
|
|
@ -115,8 +116,8 @@ pub(crate) fn start_xdp(
|
|||
Ok(None)
|
||||
}
|
||||
|
||||
/// Юзерспейс-агрегатор префиксов: активен, когда detect.prefix включён,
|
||||
/// а XDP-путь не работает (не собран или выключен в конфиге).
|
||||
/// Userspace prefix aggregator: active when `detect.prefix` is enabled and the
|
||||
/// XDP path does not run (not compiled in or disabled in the config).
|
||||
pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>> {
|
||||
let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled;
|
||||
if config.detect.prefix.enabled && !xdp_active {
|
||||
|
|
@ -131,11 +132,12 @@ pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>
|
|||
}
|
||||
}
|
||||
|
||||
/// Store-фичи проверяются на старте edge-демона: конфиг, запрашивающий redis,
|
||||
/// в бинаре без `store-redis` должен упасть сразу, а не молча потерять
|
||||
/// blacklist-sync (sync-задача в runtime.rs живёт под тем же cfg).
|
||||
/// Точка вызова — `build_whitelist`: ближайший `?`-хук, принимающий конфиг
|
||||
/// до бинда listener'а (сам runtime.rs вне правок этой задачи).
|
||||
/// Validates store features at edge startup: a config that asks for redis in a
|
||||
/// binary without `store-redis` must fail immediately instead of silently losing
|
||||
/// blacklist sync (the sync task in `runtime.rs` lives behind the same cfg).
|
||||
///
|
||||
/// Called from `build_whitelist`, the closest `?` hook that receives the config
|
||||
/// before the listener binds.
|
||||
fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) {
|
||||
|
|
@ -146,6 +148,11 @@ fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Parses `whitelist` entries into a shared address set.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails on an invalid entry or when the config requires store features that are
|
||||
/// not compiled in.
|
||||
pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>> {
|
||||
ensure_store_features(config)?;
|
||||
let mut set = HashSet::with_capacity(config.whitelist.len());
|
||||
|
|
@ -191,10 +198,10 @@ mod tests {
|
|||
assert!(ensure_store_features(&config_with_redis()).is_ok());
|
||||
}
|
||||
|
||||
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>`
|
||||
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]`
|
||||
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()`
|
||||
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова.
|
||||
/// XDP auto-ban wiring: `start_xdp` must accept the `Arc<Blacklist>` and, with
|
||||
/// `[xdp]` disabled, touch neither the kernel nor the blacklist. The
|
||||
/// `set_autoban` -> `load()` order inside the enabled branch cannot be checked
|
||||
/// without a kernel.
|
||||
#[test]
|
||||
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
|
||||
let (_tx, rx) = watch::channel(false);
|
||||
|
|
|
|||
|
|
@ -1,23 +1,23 @@
|
|||
//! Shutdown-drain машина edge-демона: сигнал, drain-таймер и код завершения.
|
||||
//! Edge daemon shutdown drain: signal handling, drain timer and exit code.
|
||||
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Результат завершения демона. Код выхода вычисляется здесь, но сам
|
||||
/// `process::exit` вызывается только в точке входа бинаря (`src/bin/rampart.rs`),
|
||||
/// поэтому библиотечный код остаётся свободным от lint `exit`.
|
||||
/// Daemon exit outcome. The exit code is computed here, but `process::exit` is
|
||||
/// only called from the binary entry point (`src/bin/rampart.rs`), which keeps
|
||||
/// the library free of the `exit` lint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunExit {
|
||||
/// Listener отработал штатно: drain уложился в таймаут.
|
||||
/// The listener finished cleanly: the drain fit into the timeout.
|
||||
Ok,
|
||||
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно
|
||||
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера).
|
||||
/// The drain timeout expired: the binary must terminate the process immediately
|
||||
/// (replaces the former `process::exit(0)` inside the shutdown timer).
|
||||
DrainTimeout,
|
||||
}
|
||||
|
||||
impl RunExit {
|
||||
/// Код завершения процесса для данного результата.
|
||||
/// Process exit code for this outcome.
|
||||
#[must_use]
|
||||
pub const fn code(self) -> i32 {
|
||||
match self {
|
||||
|
|
@ -27,11 +27,11 @@ impl RunExit {
|
|||
}
|
||||
}
|
||||
|
||||
/// Ставит фоновую shutdown-задачу.
|
||||
/// Spawns the background shutdown task.
|
||||
///
|
||||
/// shutdown-таймер обязан завершить процесс: сам `process::exit` вынесен в
|
||||
/// бинарь, а здесь мы лишь уведомляем `run` об истечении drain-таймаута через
|
||||
/// oneshot-канал. Логи и тайминг (5s после сигнала) сохранены без изменений.
|
||||
/// The timer must end the process, but `process::exit` now lives in the binary,
|
||||
/// so this only reports the drain timeout to `run` over a oneshot channel. The
|
||||
/// process is given five seconds to drain after the signal.
|
||||
pub(crate) fn spawn_shutdown_drain(shutdown_tx: watch::Sender<bool>, drain_tx: oneshot::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
|
|
@ -60,7 +60,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn run_exit_codes_match_previous_process_exit() {
|
||||
// Штатный путь и прежний drain-timeout (`process::exit(0)`) завершались с кодом 0.
|
||||
// Both the clean path and the former drain timeout (`process::exit(0)`) exited with code 0.
|
||||
assert_eq!(RunExit::Ok.code(), 0);
|
||||
assert_eq!(RunExit::DrainTimeout.code(), 0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Command-line client for the Rampart manager API.
|
||||
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Rampart manager daemon: HTTP API in front of the redis state store.
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
http::HeaderValue,
|
||||
|
|
@ -18,8 +20,8 @@ async fn main() -> anyhow::Result<()> {
|
|||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
.init();
|
||||
|
||||
// Manager живёт исключительно на redis-хранилище: без фичи стартовать
|
||||
// нечего — fail-fast вместо полумёртвого API (features additive, TODO SOLID D).
|
||||
// The manager lives exclusively on the redis store: without the feature there
|
||||
// is nothing to start, so fail fast instead of serving a half-dead API.
|
||||
if !cfg!(feature = "store-redis") {
|
||||
anyhow::bail!("rampart-manager requires a redis state store: built without store-redis feature");
|
||||
}
|
||||
|
|
@ -61,8 +63,8 @@ async fn main() -> anyhow::Result<()> {
|
|||
.route("/api/v1/health", get(api::inventory::health::health_check))
|
||||
.route("/api/v1/auth/login", post(api::auth::login));
|
||||
|
||||
// Redis-зависимые маршруты существуют только вместе с фичей; сам manager
|
||||
// без неё bail'ит выше, поэтому 501-заглушки были бы недостижимым кодом.
|
||||
// Redis-backed routes only exist together with the feature; the manager bails
|
||||
// out above without it, so 501 stubs here would be unreachable code.
|
||||
let protected = Router::new();
|
||||
#[cfg(feature = "store-redis")]
|
||||
let protected = protected
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! `rampart-tui` — интерактивный терминальный дашборд live-метрик Rampart.
|
||||
//! `rampart-tui` is an interactive terminal dashboard for live Rampart metrics.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
|
@ -21,7 +21,7 @@ struct Cli {
|
|||
/// URL Prometheus metrics endpoint
|
||||
#[arg(long, default_value = "http://127.0.0.1:9090/metrics")]
|
||||
url: String,
|
||||
/// Период опроса, секунды
|
||||
/// Scrape interval in seconds
|
||||
#[arg(long, default_value_t = 1)]
|
||||
refresh_secs: u64,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
//! Edge daemon entry point; all work is delegated to [`rampart::app::run`].
|
||||
|
||||
use rampart::app::{self, RunExit};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
match app::run().await? {
|
||||
// Штатное завершение listener: управление возвращается tokio-рантайму.
|
||||
// Clean listener shutdown: control returns to the tokio runtime.
|
||||
RunExit::Ok => Ok(()),
|
||||
// Drain-таймаут: бинарь — единственное место, где допустим process::exit.
|
||||
// Drain timeout: the binary is the only place where process::exit is allowed.
|
||||
exit => std::process::exit(exit.code()),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! `blacklist` subcommands: manage the manager blacklist over its HTTP API.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! `config` subcommand: prints configuration usage; lookups and updates are not
|
||||
//! implemented yet.
|
||||
|
||||
pub async fn run(key: Option<String>, value: Option<String>) -> anyhow::Result<()> {
|
||||
match (key, value) {
|
||||
(Some(_), Some(_)) => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
//! `doctor` subcommand: environment, manager API and XDP diagnostics.
|
||||
|
||||
use crate::xdp::{EnvironmentReport, FilesystemProbe, SystemProbe};
|
||||
|
||||
/// Ищет интерфейс с маршрутом по умолчанию в /proc/net/route
|
||||
/// (destination == 00000000). Работает без root.
|
||||
/// Finds the interface that owns the default route in `/proc/net/route`
|
||||
/// (destination `00000000`). Works without root.
|
||||
fn default_route_interface(probe: &impl SystemProbe) -> Option<String> {
|
||||
let routes = probe.read_file("/proc/net/route").ok()?;
|
||||
routes.lines().skip(1).find_map(|line| {
|
||||
|
|
@ -10,7 +12,7 @@ fn default_route_interface(probe: &impl SystemProbe) -> Option<String> {
|
|||
})
|
||||
}
|
||||
|
||||
/// Подсекция network/XDP: что видно окружению без root.
|
||||
/// Network/XDP section: what the environment exposes without root.
|
||||
fn print_network_section(all_ok: &mut bool) {
|
||||
println!("\nNetwork / XDP");
|
||||
println!("-------------");
|
||||
|
|
@ -57,6 +59,7 @@ fn print_network_section(all_ok: &mut bool) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Runs every diagnostic and prints the report.
|
||||
pub async fn run() -> anyhow::Result<()> {
|
||||
println!("Rampart Diagnostics");
|
||||
println!("=====================\n");
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Subcommand implementations for the Rampart CLI.
|
||||
|
||||
pub mod blacklist;
|
||||
pub mod config;
|
||||
pub mod doctor;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,9 @@
|
|||
//! `drain` subcommand: gracefully drain a node.
|
||||
|
||||
/// Drains `node` gracefully.
|
||||
///
|
||||
/// # Errors
|
||||
/// Always fails: draining is not implemented yet.
|
||||
pub async fn run(node: &str) -> anyhow::Result<()> {
|
||||
anyhow::bail!("graceful drain is not implemented for node {node}")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,17 @@
|
|||
//! `emergency` subcommand: switch the edge policy into or out of emergency mode.
|
||||
|
||||
/// Switches emergency mode on.
|
||||
///
|
||||
/// # Errors
|
||||
/// Always fails: emergency mode is not implemented yet.
|
||||
pub async fn enable() -> anyhow::Result<()> {
|
||||
anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart")
|
||||
}
|
||||
|
||||
/// Switches emergency mode off.
|
||||
///
|
||||
/// # Errors
|
||||
/// Always fails: emergency mode is not implemented yet.
|
||||
pub async fn disable() -> anyhow::Result<()> {
|
||||
anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! CLI-команды управления edge-узлами: статус, drain, аварийный режим.
|
||||
//! Edge node management commands: status, drain and emergency mode.
|
||||
pub mod drain;
|
||||
pub mod emergency;
|
||||
pub mod status;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! `status` subcommand: print the manager health summary.
|
||||
|
||||
pub async fn run() -> anyhow::Result<()> {
|
||||
println!("Rampart Status");
|
||||
println!("================\n");
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
//! CLI-команды для bin/rampart-cli.
|
||||
//! CLI commands used by `bin/rampart-cli`.
|
||||
#[allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
pub mod commands;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
//! Единый конфиг платформы Rampart.
|
||||
//! Single configuration of the Rampart platform.
|
||||
//!
|
||||
//! Owns the [`Config`] root type, its serde defaults and the semantic validation
|
||||
//! that runs before the daemon binds a socket.
|
||||
mod sections;
|
||||
|
||||
#[cfg(feature = "protocol-http")]
|
||||
|
|
@ -50,21 +53,21 @@ pub struct Config {
|
|||
}
|
||||
|
||||
impl Config {
|
||||
/// Парсит конфиг из TOML-строки и валидирует семантику.
|
||||
/// Parses the config from a TOML string and validates its semantics.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невалидном TOML или нарушении инвариантов
|
||||
/// (пустой список upstream-бэкендов, некорректные адреса).
|
||||
/// Fails on invalid TOML or on a violated invariant (empty upstream list,
|
||||
/// malformed addresses, unsafe PROXY protocol settings).
|
||||
pub fn parse_str(contents: &str) -> anyhow::Result<Self> {
|
||||
let config: Config = toml::from_str(contents)?;
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Читает и парсит конфиг из файла.
|
||||
/// Reads and parses the config from a file.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невозможности прочитать файл или невалидном содержимом.
|
||||
/// Fails when the file cannot be read or its contents are invalid.
|
||||
pub fn from_file(path: &str) -> anyhow::Result<Self> {
|
||||
let contents = fs::read_to_string(path)?;
|
||||
Self::parse_str(&contents)
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Секции единого конфига платформы.
|
||||
//! Sections of the platform config.
|
||||
|
||||
mod detect;
|
||||
mod edge;
|
||||
|
|
|
|||
|
|
@ -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")]
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
//! Adaptive proof-of-work difficulty driven by the observed connection rate.
|
||||
|
||||
use crate::metrics;
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Адаптирует сложность PoW к текущему темпу подключений.
|
||||
/// Adapts the PoW difficulty to the current connection rate.
|
||||
///
|
||||
/// The rate is counted over a sliding one-second window and the resulting
|
||||
/// difficulty is clamped to `[min, max]`.
|
||||
pub struct DifficultyAdjuster {
|
||||
window: VecDeque<Instant>,
|
||||
min: u8,
|
||||
|
|
@ -17,6 +22,7 @@ impl Default for DifficultyAdjuster {
|
|||
}
|
||||
|
||||
impl DifficultyAdjuster {
|
||||
/// Creates an adjuster clamped to `min.max(4)` and `max.min(10)`.
|
||||
#[must_use]
|
||||
pub fn new(min: u8, max: u8) -> Self {
|
||||
Self {
|
||||
|
|
@ -27,6 +33,7 @@ impl DifficultyAdjuster {
|
|||
}
|
||||
}
|
||||
|
||||
/// Records one connection and recomputes the difficulty for the window.
|
||||
pub fn record_connection(&mut self) {
|
||||
let now = Instant::now();
|
||||
self.window.push_back(now);
|
||||
|
|
@ -50,6 +57,7 @@ impl DifficultyAdjuster {
|
|||
}
|
||||
}
|
||||
|
||||
/// Returns the current difficulty and publishes it to the metrics gauge.
|
||||
#[must_use]
|
||||
pub fn current_difficulty(&self) -> u8 {
|
||||
metrics::POW_CURRENT_DIFFICULTY.set(self.current as i64);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Универсальный SHA-256 hashcash: генерация challenge, решатель,
|
||||
//! верификатор и адаптивная сложность.
|
||||
//! Universal SHA-256 hashcash: challenge generation, solver, verifier and
|
||||
//! adaptive difficulty.
|
||||
|
||||
mod difficulty;
|
||||
mod pow;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const CHALLENGE_TTL_SECS: u64 = 30;
|
|||
const MAX_NONCE_LEN: usize = 64;
|
||||
const ALLOWED_HEX_PREFIX: [u8; 4] = *b"0123";
|
||||
|
||||
/// Активная PoW-задача, выданная одному соединению.
|
||||
/// Active PoW challenge issued to one connection.
|
||||
pub struct Challenge {
|
||||
token: [u8; 32],
|
||||
created_at: Instant,
|
||||
|
|
@ -31,8 +31,8 @@ impl Challenge {
|
|||
}
|
||||
}
|
||||
|
||||
/// Challenge с явным токеном — для детерминированных тестов, где
|
||||
/// случайный дайджест даёт flaky-исход.
|
||||
/// Builds a challenge with an explicit token.
|
||||
/// Intended for deterministic tests, where a random token makes the outcome
|
||||
#[must_use]
|
||||
pub fn with_token(token: [u8; 32], difficulty: u8) -> Self {
|
||||
Self {
|
||||
|
|
@ -53,7 +53,9 @@ impl Challenge {
|
|||
hex::encode(self.token)
|
||||
}
|
||||
|
||||
/// Проверяет nonce и помечает challenge использованным при успехе.
|
||||
/// Verifies `nonce` and marks the challenge as used on success.
|
||||
///
|
||||
/// A challenge is single-use and expires after `CHALLENGE_TTL_SECS`.
|
||||
#[must_use]
|
||||
pub fn verify(&mut self, nonce: &str) -> bool {
|
||||
if self.used || self.is_expired() || nonce.len() > MAX_NONCE_LEN {
|
||||
|
|
@ -78,7 +80,7 @@ impl Challenge {
|
|||
}
|
||||
}
|
||||
|
||||
/// Переборный решатель hashcash (для клиентов и тестов).
|
||||
/// Brute-force hashcash solver used by clients and tests.
|
||||
#[must_use]
|
||||
pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
|
||||
let d = difficulty as usize;
|
||||
|
|
@ -99,10 +101,11 @@ pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
|
|||
None
|
||||
}
|
||||
|
||||
/// Проводит текстовый PoW-gate в потоке: выдаёт challenge и проверяет ответ.
|
||||
/// Runs the textual PoW gate on `stream`: issues a challenge and checks the
|
||||
/// answer.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку только при сбое ввода-вывода; неверное решение — `Ok(false)`.
|
||||
/// Only I/O failures are reported; a wrong solution is `Ok(false)`.
|
||||
pub async fn enforce(stream: &mut TcpStream, peer_ip: IpAddr, difficulty: u8) -> anyhow::Result<bool> {
|
||||
if difficulty == 0 {
|
||||
tracing::debug!("pow: difficulty 0, skipping for {peer_ip}");
|
||||
|
|
@ -150,8 +153,8 @@ mod tests {
|
|||
let mut challenge = Challenge::generate(4);
|
||||
let challenge_str = challenge.challenge_string();
|
||||
|
||||
// Подбираем nonce, который независимо рассчитанный SHA-256
|
||||
// заведомо отклоняет — тест детерминирован.
|
||||
// Search for a nonce that an independently computed SHA-256 provably rejects,
|
||||
// so the test stays deterministic.
|
||||
let mut wrong_nonce = None;
|
||||
for i in 0..10_000u32 {
|
||||
let candidate = format!("bad-{i}");
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Multi-worker TCP accept-loop с SO_REUSEPORT и graceful shutdown.
|
||||
//! Multi-worker TCP accept loop with `SO_REUSEPORT` and graceful shutdown.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::engine::tunnel::Gateway;
|
||||
|
|
@ -8,11 +8,14 @@ use std::sync::Arc;
|
|||
use tokio::net::TcpListener;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Запускает `workers.count` accept-loop'ов на одном адресе.
|
||||
/// Starts `workers.count` accept loops on a single address.
|
||||
///
|
||||
/// Each worker binds its own socket with `SO_REUSEPORT` and `SO_REUSEADDR`, so
|
||||
/// the kernel distributes incoming connections across them and a restart does
|
||||
/// not fail on `TIME_WAIT` sockets.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невозможности забиндить адрес или падении одного
|
||||
/// из accept-loop'ов.
|
||||
/// Fails when the address cannot be bound or when one of the accept loops dies.
|
||||
pub async fn run(
|
||||
config: Arc<Config>,
|
||||
gateway: Arc<Gateway>,
|
||||
|
|
@ -75,7 +78,7 @@ async fn accept_loop(
|
|||
let gateway = Arc::clone(&gateway);
|
||||
let hook = Arc::clone(&hook);
|
||||
tokio::spawn(async move {
|
||||
// Hot path Traffic Intelligence: только атомики и DashMap.
|
||||
// Traffic intelligence hot path: atomics and `DashMap` only.
|
||||
hook.on_accept();
|
||||
let outcome = gateway.handle(stream, peer_addr).await;
|
||||
if let Err(e) = outcome.result {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
//! Edge-движок: listener, generic TCP tunnel, PoW gate.
|
||||
//! Edge engine: multi-worker listener, generic TCP tunnel and the PoW gate.
|
||||
//!
|
||||
//! Owns the per-connection pipeline and the subnet-level detection wiring that
|
||||
//! sits between the kernel filter and the traffic intelligence layer.
|
||||
|
||||
pub mod challenge;
|
||||
pub mod listener;
|
||||
pub mod subnet;
|
||||
pub mod tunnel;
|
||||
|
||||
// Совместимость путей после переезда в subnet/: `engine::subnet_tracker` /
|
||||
// `engine::subnet_monitor` остаются валидными алиасами модулей.
|
||||
// Path compatibility after the move into `subnet/`: `engine::subnet_tracker` and
|
||||
// `engine::subnet_monitor` stay valid module paths.
|
||||
pub use subnet::{monitor as subnet_monitor, tracker as subnet_tracker};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
//! Subnet-level детектор: юзерспейс-агрегатор префиксов и монитор вердиктов.
|
||||
//! Subnet-level detector: userspace prefix aggregator and verdict monitor.
|
||||
pub mod monitor;
|
||||
pub mod tracker;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Периодический subnet-монитор: источник снапшотов → детектор → эскалация.
|
||||
//! Periodic subnet monitor: snapshot source, detector and verdict escalation.
|
||||
//!
|
||||
//! Источник выбирается по сборке и конфигу: XDP-карта `prefix_stats`
|
||||
//! (feature `xdp` + загруженный фильтр) либо юзерспейс-агрегатор
|
||||
//! The source is chosen by build features and config: the XDP `prefix_stats` map
|
||||
//! (feature `xdp` with a loaded filter) or the userspace aggregator
|
||||
//! [`SubnetTracker`].
|
||||
|
||||
use crate::config::DetectPrefixConfig;
|
||||
|
|
@ -32,10 +32,11 @@ impl Source {
|
|||
}
|
||||
}
|
||||
|
||||
/// Запускает фоновый subnet-монитор, если `[detect.prefix] enabled`.
|
||||
/// Spawns the background subnet monitor when `[detect.prefix] enabled`.
|
||||
///
|
||||
/// Приоритет источника: XDP-карта при загруженном фильтре, иначе
|
||||
/// юзерспейс-агрегатор. Без обоих источников монитор не запускается.
|
||||
/// Source priority: the XDP map when a filter is loaded, otherwise the userspace
|
||||
/// aggregator. Without either source the monitor stays disabled and logs a
|
||||
/// warning.
|
||||
pub fn spawn(
|
||||
detect: &DetectPrefixConfig,
|
||||
tracker: Option<Arc<SubnetTracker>>,
|
||||
|
|
@ -123,7 +124,7 @@ async fn enforce_block(source: &Source, pv: &PrefixVerdict) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Длина префикса, соответствующая гранулярности детекции (v4 /24, v6 /64).
|
||||
/// Prefix length matching the detection granularity (v4 /24, v6 /64).
|
||||
#[cfg(feature = "xdp")]
|
||||
fn prefix_len(prefix: IpAddr) -> u8 {
|
||||
match prefix {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
//! Юзерспейс-агрегатор новых соединений по префиксам (/24, /64).
|
||||
//! Userspace aggregator of new connections per prefix (/24 for IPv4, /64 for
|
||||
//! IPv6).
|
||||
//!
|
||||
//! Fallback-путь subnet-детектора, когда XDP выключен: питает
|
||||
//! [`crate::traffic::prefix::SubnetDetector`] теми же снапшотами.
|
||||
//! Fallback path of the subnet detector when XDP is disabled: it feeds
|
||||
//! [`crate::traffic::prefix::SubnetDetector`] with the same snapshot shape the
|
||||
//! kernel map produces.
|
||||
|
||||
use crate::traffic::prefix::{PrefixSnapshot, PrefixStatsSource, prefix_of};
|
||||
use dashmap::DashMap;
|
||||
|
|
@ -15,8 +17,10 @@ struct WindowState {
|
|||
started: Instant,
|
||||
}
|
||||
|
||||
/// Агрегатор новых соединений по префиксам. `take_snapshot` дренирует
|
||||
/// накопленное: каждый вызов закрывает одно окно детекции.
|
||||
/// Aggregates new connections per prefix.
|
||||
///
|
||||
/// `take_snapshot` drains the accumulated state, so every call closes exactly
|
||||
/// one detection window.
|
||||
pub struct SubnetTracker {
|
||||
windows: DashMap<IpAddr, WindowState>,
|
||||
}
|
||||
|
|
@ -35,7 +39,7 @@ impl SubnetTracker {
|
|||
}
|
||||
}
|
||||
|
||||
/// Регистрирует новое входящее соединение (юзерспейс-аналог SYN).
|
||||
/// Records a new inbound connection (userspace equivalent of a SYN).
|
||||
pub fn record_connection(&self, ip: IpAddr) {
|
||||
let prefix = prefix_of(ip);
|
||||
let mut state = self.windows.entry(prefix).or_insert_with(|| WindowState {
|
||||
|
|
@ -47,12 +51,12 @@ impl SubnetTracker {
|
|||
state.sources.insert(ip);
|
||||
}
|
||||
|
||||
/// Забирает и сбрасывает агрегаты текущего окна.
|
||||
/// Takes and resets the aggregates of the current window.
|
||||
#[must_use]
|
||||
pub fn take_snapshot(&self) -> Vec<(IpAddr, PrefixSnapshot)> {
|
||||
let mut out = Vec::new();
|
||||
// Дренируем все ключи: каждое окно начинается с чистой карты,
|
||||
// память не растёт при спуфинге множества префиксов.
|
||||
// Drain every key: the next window starts from an empty map, so memory does not
|
||||
// grow when an attacker spoofs many distinct prefixes.
|
||||
self.windows.retain(|prefix, state| {
|
||||
if state.syn_count == 0 {
|
||||
return false;
|
||||
|
|
@ -60,8 +64,8 @@ impl SubnetTracker {
|
|||
out.push((
|
||||
*prefix,
|
||||
PrefixSnapshot {
|
||||
// Юзерспейс видит только установленные соединения;
|
||||
// pkt_count отражает тот же поток.
|
||||
// Userspace only sees established connections, so `pkt_count` mirrors the same
|
||||
// flow as `syn_count`.
|
||||
pkt_count: state.syn_count,
|
||||
syn_count: state.syn_count,
|
||||
last_seen_ns: state.started.elapsed().as_nanos() as u64,
|
||||
|
|
@ -74,7 +78,7 @@ impl SubnetTracker {
|
|||
}
|
||||
}
|
||||
|
||||
/// Адаптер [`SubnetTracker`] под трейт [`PrefixStatsSource`].
|
||||
/// Adapts [`SubnetTracker`] to the [`PrefixStatsSource`] trait.
|
||||
pub struct TrackerSource {
|
||||
pub tracker: Arc<SubnetTracker>,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
//! Generic TCP proxy: фильтры входа → protocol handshake → upstream.
|
||||
//! Generic TCP proxy pipeline: ingress filters, protocol handshake, upstream
|
||||
//! relay.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::engine::challenge::DifficultyAdjuster;
|
||||
|
|
@ -20,7 +21,7 @@ mod gateway;
|
|||
#[cfg(feature = "protocol-minecraft")]
|
||||
mod proxy;
|
||||
|
||||
/// Общее состояние edge-движка, разделяемое между accept-loop'ами.
|
||||
/// Shared edge engine state handed to every accept loop by [`Arc`].
|
||||
pub struct Gateway {
|
||||
pub config: Arc<Config>,
|
||||
pub rate_limiter: Arc<RateLimiter>,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! Per-connection pipeline of the edge engine: filters, PoW gate, protocol
|
||||
//! handshake and upstream relay.
|
||||
|
||||
mod challenge;
|
||||
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
|
|
@ -56,11 +59,11 @@ impl Gateway {
|
|||
}
|
||||
}
|
||||
|
||||
/// Полный конвейер обработки входящего соединения.
|
||||
/// Runs the full pipeline for one inbound connection.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку только при сбое ввода-вывода апстрима; блокировки
|
||||
/// клиента ошибкой не считаются.
|
||||
/// Only upstream I/O failures are surfaced; a connection dropped by a filter or
|
||||
/// by the challenge gate is not an error.
|
||||
#[allow(unused_mut)]
|
||||
pub async fn handle(&self, mut client: TcpStream, peer_addr: std::net::SocketAddr) -> GatewayOutcome {
|
||||
let client_addr = if self.config.proxy_protocol.ingress_enabled {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Proof-of-work gate step of the connection pipeline.
|
||||
|
||||
use super::Gateway;
|
||||
use crate::engine::challenge::enforce as enforce_pow;
|
||||
use crate::metrics;
|
||||
|
|
@ -5,6 +7,14 @@ use std::net::IpAddr;
|
|||
use tokio::net::TcpStream;
|
||||
|
||||
impl Gateway {
|
||||
/// Runs the proof-of-work gate for `peer_ip` and reports whether the
|
||||
/// connection may continue.
|
||||
///
|
||||
/// Whitelisted peers skip the challenge but still publish the current
|
||||
/// difficulty to the metrics gauge.
|
||||
///
|
||||
/// # Errors
|
||||
/// Propagates I/O failures from the challenge exchange.
|
||||
pub(super) async fn pass_pow_gate(&self, client: &mut TcpStream, peer_ip: IpAddr) -> anyhow::Result<bool> {
|
||||
let pow_config = &self.config.pow;
|
||||
if !(pow_config.enabled && pow_config.difficulty > 0) {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,17 @@
|
|||
//! Encoding of upstream PROXY protocol v2 headers.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
mod inbound;
|
||||
pub(super) use inbound::read_v2_header;
|
||||
|
||||
/// Encodes a PROXY protocol v2 TCP header for the backend.
|
||||
/// The backend must accept connections only from trusted Rampart nodes.
|
||||
///
|
||||
/// The backend must accept connections only from trusted Rampart nodes, since
|
||||
/// anyone able to reach it could otherwise forge the source address.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when the source and destination address families differ.
|
||||
pub(super) fn protocol_v2(source: SocketAddr, destination: SocketAddr) -> anyhow::Result<Vec<u8>> {
|
||||
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
|
||||
if source.is_ipv4() != destination.is_ipv4() {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,13 @@ use tokio::net::TcpStream;
|
|||
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
|
||||
const FIXED_HEADER_BYTES: usize = 16;
|
||||
|
||||
/// Reads and validates an inbound PROXY protocol v2 header.
|
||||
///
|
||||
/// The whole header must arrive within `timeout`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails on timeout, on a bad signature or command, on an unsupported address
|
||||
/// family, on TLVs, and on a header larger than `max_header_bytes`.
|
||||
pub(crate) async fn read_v2_header(
|
||||
stream: &mut TcpStream,
|
||||
timeout: Duration,
|
||||
|
|
|
|||
|
|
@ -103,7 +103,10 @@ impl Blacklist {
|
|||
self.redis_entries.remove(&ip);
|
||||
}
|
||||
|
||||
/// Replace Redis-managed bans while preserving local detector bans.
|
||||
/// Replaces the Redis-managed ban set, preserving locally detected bans.
|
||||
///
|
||||
/// `redis_entries` is rebuilt from `entries` wholesale, so a ban that
|
||||
/// disappeared upstream stops applying after this call.
|
||||
pub fn replace_redis<I>(&self, entries: I)
|
||||
where
|
||||
I: IntoIterator<Item = (IpAddr, Duration, String)>,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
//! Фильтры входящего трафика.
|
||||
//! Inbound traffic filters.
|
||||
//!
|
||||
//! Owns the per-source guards applied on the accept path: blacklist,
|
||||
//! per-IP connection limit, geo policy and token-bucket rate limiting.
|
||||
|
||||
pub mod blacklist;
|
||||
pub mod connection_limit;
|
||||
|
|
|
|||
|
|
@ -71,8 +71,11 @@ impl RateLimiter {
|
|||
self.buckets.is_empty()
|
||||
}
|
||||
|
||||
/// Эвиктит простаивающие бакеты. Запускается, когда бакетов больше
|
||||
/// MAX_BUCKETS либо по расписанию (раз в SWEEP_INTERVAL).
|
||||
/// Evicts idle buckets.
|
||||
///
|
||||
/// Runs either when the table grows past `MAX_BUCKETS` (cap enforcement)
|
||||
/// or once per `SWEEP_INTERVAL`. Buckets touched within `eviction_idle`
|
||||
/// survive, so active sources keep their token state.
|
||||
pub fn sweep(&self) {
|
||||
let now = Instant::now();
|
||||
let elapsed_secs = now.duration_since(self.epoch).as_secs();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
//! Rampart — универсальная платформа сетевой защиты (L3/L4/L7).
|
||||
//! Rampart is a universal L3/L4/L7 network protection platform.
|
||||
//!
|
||||
//! The crate root owns the module tree; each module documents what it owns.
|
||||
pub mod app;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
//! Инвентарь manager-API: health, узлы и серверы.
|
||||
//! Manager API inventory: health, nodes and servers.
|
||||
//!
|
||||
//! Owns the read-side endpoints that describe the fleet as the manager sees it.
|
||||
pub mod health;
|
||||
pub mod nodes;
|
||||
pub mod servers;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
//! Management-плоскость Rampart: REST API, аутентификация, синхронизация узлов.
|
||||
//! Rampart management plane: REST API, authentication and node synchronisation.
|
||||
//!
|
||||
//! Owns [`AppState`], the handle shared by every handler through [`SharedState`].
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod sync;
|
||||
|
|
@ -8,10 +10,11 @@ use std::net::IpAddr;
|
|||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Общее состояние management-API.
|
||||
/// Shared state of the management API.
|
||||
pub struct AppState {
|
||||
/// Redis-клиент управления состоянием; присутствует только при собранной
|
||||
/// фиче `store-redis` (manager требует её на старте — см. bin/rampart-manager).
|
||||
/// Redis client for state management; present only when the `store-redis`
|
||||
/// feature is compiled in (the manager requires it at startup, see
|
||||
/// bin/rampart-manager).
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub redis_client: redis::Client,
|
||||
pub jwt_secret: String,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,9 @@
|
|||
//! Prometheus registry for the edge process: metric handles and the scrape
|
||||
//! endpoint.
|
||||
//!
|
||||
//! Metric names and help strings are part of the public monitoring contract and
|
||||
//! must stay stable across releases.
|
||||
|
||||
use prometheus::{
|
||||
Encoder, IntCounter, IntCounterVec, IntGauge, register_int_counter, register_int_counter_vec, register_int_gauge,
|
||||
};
|
||||
|
|
@ -65,7 +71,13 @@ pub static INTEL_ALERTS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| {
|
|||
.expect("INTEL_ALERTS_TOTAL")
|
||||
});
|
||||
|
||||
/// Отдаёт Prometheus-метрики по голому HTTP/0.9-совместимому ответу.
|
||||
/// Serves the Prometheus registry over a minimal HTTP endpoint.
|
||||
///
|
||||
/// Runs until the task is dropped; a failed connection is logged and never
|
||||
/// aborts the loop.
|
||||
///
|
||||
/// The request line is not parsed: every connection receives the current
|
||||
/// registry snapshot with `Content-Length` and is then closed.
|
||||
pub async fn run_metrics_server(addr: &str) {
|
||||
let listener = match TcpListener::bind(addr).await {
|
||||
Ok(l) => l,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
//! HTTP/1.1 protocol handler (feature `protocol-http`).
|
||||
//!
|
||||
//! Первый plugin-реализаций [`ProtocolHandler`]: читает request-head
|
||||
//! постепенно (TCP приходит фрагментами), проверяет его по политике из
|
||||
//! секции `[protocol.http]` и возвращает upstream для туннелирования.
|
||||
//! Прочитанная голова передаётся upstream как начальные байты туннеля.
|
||||
//! Owns the first plugin implementation of [`ProtocolHandler`]: it reads the
|
||||
//! request head incrementally (TCP arrives in fragments), evaluates it against
|
||||
//! the policy from the `[protocol.http]` section and returns the upstream to
|
||||
//! tunnel to.
|
||||
//!
|
||||
//! The bytes already consumed for the head are forwarded to the upstream as the
|
||||
//! initial tunnel payload, so the request is not lost.
|
||||
|
||||
mod parser;
|
||||
|
||||
|
|
@ -15,7 +18,7 @@ use std::time::Duration;
|
|||
use tokio::io::AsyncReadExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// Обработчик HTTP/1.1: verdict Allow → tunnel на upstream, Reject → drop.
|
||||
/// HTTP/1.1 handler: verdict `Allow` tunnels to the upstream, `Reject` drops.
|
||||
pub struct HttpProtocolHandler {
|
||||
policy: parser::Policy,
|
||||
timeout: Duration,
|
||||
|
|
@ -23,7 +26,10 @@ pub struct HttpProtocolHandler {
|
|||
}
|
||||
|
||||
impl HttpProtocolHandler {
|
||||
/// Собирает обработчик из конфига `[protocol.http]` и списка upstream'ов.
|
||||
/// Builds the handler from the `[protocol.http]` config and the upstream list.
|
||||
///
|
||||
/// The first upstream wins; falling back to `127.0.0.1:80` keeps the handler
|
||||
/// usable in tests where the list is empty.
|
||||
#[must_use]
|
||||
pub fn new(http: &HttpProtocolConfig, upstreams: &[String]) -> Self {
|
||||
Self {
|
||||
|
|
@ -37,10 +43,11 @@ impl HttpProtocolHandler {
|
|||
}
|
||||
}
|
||||
|
||||
/// Накапливает request-head без повторного чтения одного и того же префикса.
|
||||
/// Accumulates the request head without re-reading an already scanned prefix.
|
||||
///
|
||||
/// # Errors
|
||||
/// Таймаут, закрытие клиента, превышение `max_header_bytes` или ошибка I/O.
|
||||
/// Times out, the client closes, `max_header_bytes` is exceeded, or the
|
||||
/// socket reports an I/O error.
|
||||
async fn read_head(&self, stream: &mut TcpStream) -> anyhow::Result<Vec<u8>> {
|
||||
let limit = self.policy.max_header_bytes;
|
||||
if limit == 0 {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
//! Чистый парсер и валидатор HTTP/1.x request-head для edge-фильтра.
|
||||
//! Pure HTTP/1.x request-head parser and validator for the edge filter.
|
||||
//!
|
||||
//! Модуль не знает про I/O: на вход — накопленный заголовок, на выходе —
|
||||
//! [`Verdict`]. Это позволяет покрывать логику юнит-тестами без сокетов.
|
||||
//! Owns the parsing policy and verdicts only: the module knows nothing about
|
||||
//! I/O. Input is the accumulated head, output is a [`Verdict`], which keeps the
|
||||
//! logic unit-testable without sockets.
|
||||
|
||||
/// Политика проверки, снятая с секции `[protocol.http]`.
|
||||
/// Validation policy derived from the `[protocol.http]` section.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Policy {
|
||||
pub max_header_bytes: usize,
|
||||
|
|
@ -11,7 +12,7 @@ pub struct Policy {
|
|||
pub require_user_agent: bool,
|
||||
}
|
||||
|
||||
/// Результат проверки головы запроса.
|
||||
/// Outcome of validating a request head.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Allow { method: String, path: String, host: String },
|
||||
|
|
@ -21,7 +22,7 @@ pub enum Verdict {
|
|||
const ALLOWED_METHODS: [&str; 7] = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"];
|
||||
const HEADER_TERMINATOR: &[u8] = b"\r\n\r\n";
|
||||
|
||||
/// Ищет конец головы запроса (`\r\n\r\n`) и возвращает её полную длину.
|
||||
/// Looks for the end of the request head (`\r\n\r\n`) and returns its full length.
|
||||
#[must_use]
|
||||
pub fn scan_head(buf: &[u8]) -> Option<usize> {
|
||||
buf.windows(HEADER_TERMINATOR.len())
|
||||
|
|
@ -29,7 +30,7 @@ pub fn scan_head(buf: &[u8]) -> Option<usize> {
|
|||
.map(|pos| pos + HEADER_TERMINATOR.len())
|
||||
}
|
||||
|
||||
/// Разбирает и валидирует голову запроса согласно политике.
|
||||
/// Parses and validates a request head against the policy.
|
||||
#[must_use]
|
||||
pub fn evaluate(head: &[u8], policy: &Policy) -> Verdict {
|
||||
let Ok(text) = std::str::from_utf8(head) else {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,9 @@
|
|||
//! Protocol handler contracts.
|
||||
//!
|
||||
//! Owns the [`ProtocolHandler`] trait implemented by L7 plugins and the
|
||||
//! [`ProtocolRegistry`] that selects the active handler at startup. Concrete
|
||||
//! handlers live behind features (`protocol-http`, `protocol-minecraft`).
|
||||
|
||||
#[cfg(feature = "protocol-http")]
|
||||
pub mod http;
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
|
|
@ -7,8 +13,8 @@ use std::future::Future;
|
|||
use std::pin::Pin;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// Результат успешного protocol-handshake: адрес upstream-бэкенда,
|
||||
/// на который нужно проксировать соединение.
|
||||
/// Result of a successful protocol handshake: the upstream backend address the
|
||||
/// connection must be proxied to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Upstream {
|
||||
pub addr: String,
|
||||
|
|
@ -45,30 +51,31 @@ impl HandshakeResult {
|
|||
}
|
||||
}
|
||||
|
||||
/// Точка расширения платформы: реализация для конкретного L7-протокола.
|
||||
/// Platform extension point: one implementation per L7 protocol.
|
||||
///
|
||||
/// Контракт минимальный: обработчик проводит handshake с клиентом
|
||||
/// (чтение/запись в поток до момента, когда можно проксировать) и
|
||||
/// возвращает целевой [`Upstream`]. Реализации поставляются фичами
|
||||
/// (`--features protocol-http`, внешние plugin-крейты) — в ядре их нет.
|
||||
/// The contract is deliberately small. A handler drives the handshake with the
|
||||
/// client (reading and writing on the stream up to the point where proxying is
|
||||
/// possible) and returns the target [`Upstream`]. Implementations ship as
|
||||
/// features (`--features protocol-http`, external plugin crates); the core
|
||||
/// itself contains none.
|
||||
///
|
||||
/// Метод асинхронен через boxed future, чтобы трейт оставался
|
||||
/// dyn-совместимым (`ProtocolRegistry` хранит `Box<dyn ProtocolHandler>`).
|
||||
/// The method is async through a boxed future so the trait stays
|
||||
/// dyn-compatible (`ProtocolRegistry` stores `Box<dyn ProtocolHandler>`).
|
||||
pub trait ProtocolHandler: Send + Sync {
|
||||
/// Имя протокола (для метрик, логов и реестра).
|
||||
/// Protocol name, used in metrics, logs and the registry.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// Проводит handshake с клиентом и определяет upstream.
|
||||
/// Drives the client handshake and resolves the upstream.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невалидном клиентском потоке или отказе в доступе.
|
||||
/// Returns an error when the client stream is invalid or access is denied.
|
||||
fn handshake<'a>(
|
||||
&'a self,
|
||||
stream: &'a mut TcpStream,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
/// Реестр скомпилированных протокольных обработчиков.
|
||||
/// Registry of the protocol handlers compiled into this binary.
|
||||
#[derive(Default)]
|
||||
pub struct ProtocolRegistry {
|
||||
handlers: Vec<Box<dyn ProtocolHandler>>,
|
||||
|
|
@ -104,11 +111,11 @@ impl ProtocolRegistry {
|
|||
self.handlers.iter().find(|h| h.name() == name).map(|h| h.as_ref())
|
||||
}
|
||||
|
||||
/// Возвращает основной обработчик.
|
||||
/// Returns the primary handler, the first one registered.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку, если ни один протокол не скомпилирован —
|
||||
/// edge-нода обязана fail-fast на старте в этом случае.
|
||||
/// Returns an error when no protocol is compiled in; an edge node must
|
||||
/// fail fast at startup in that case.
|
||||
pub fn primary(&self) -> anyhow::Result<&dyn ProtocolHandler> {
|
||||
let Some(handler) = self.handlers.first() else {
|
||||
anyhow::bail!(
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
//! External state backends.
|
||||
//!
|
||||
//! Owns the [`StateStore`] contract plus the Redis implementation (blacklist
|
||||
//! sync between nodes) and the ClickHouse event sink.
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub mod redis;
|
||||
#[cfg(feature = "store-redis")]
|
||||
|
|
@ -5,22 +10,30 @@ pub use redis::{start_blacklist_sync, start_local_ban_publisher};
|
|||
|
||||
pub mod clickhouse;
|
||||
|
||||
/// Общий контракт внешнего хранилища состояния.
|
||||
/// Common contract for an external state store.
|
||||
#[allow(async_fn_in_trait)]
|
||||
pub trait StateStore: Send + Sync {
|
||||
/// Reads `key`, returning `None` when it is absent.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn get(&self, key: &str) -> anyhow::Result<Option<String>>;
|
||||
|
||||
/// Writes `value` under `key`, overwriting any previous value.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn set(&self, key: &str, value: &str) -> anyhow::Result<()>;
|
||||
|
||||
/// Deletes `key`; deleting a missing key is not an error.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn del(&self, key: &str) -> anyhow::Result<()>;
|
||||
|
||||
/// Publishes `message` to `channel` for subscribers to consume.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn publish(&self, channel: &str, message: &str) -> anyhow::Result<()>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Traffic Intelligence в hot path: репутация → авто-бан → метрики окна.
|
||||
//! Traffic Intelligence in the hot path: reputation, auto-ban and window metrics.
|
||||
//!
|
||||
//! Все вызовы из accept-пути дешёвые (DashMap/атомики), блокирующего
|
||||
//! ввода-вывода нет.
|
||||
//! Every call reachable from the accept path is cheap (DashMap/atomics) and
|
||||
//! performs no blocking I/O.
|
||||
|
||||
use crate::config::DetectAutobanConfig;
|
||||
use crate::filter::blacklist::Blacklist;
|
||||
|
|
@ -15,10 +15,10 @@ use std::time::Duration;
|
|||
const BAN_REASON_LOW_REPUTATION: &str = "low_reputation";
|
||||
const BAN_REASON_ATTACK: &str = "attack_detector";
|
||||
|
||||
/// Точка входа Traffic Intelligence для сетевого пути.
|
||||
/// Entry point of Traffic Intelligence on the network path.
|
||||
///
|
||||
/// События: новое соединение (`on_accept`), завершение обработки соединения
|
||||
/// (`on_connection_end`), эскалация детектора атак (`ban_offenders`).
|
||||
/// Events: a new connection (`on_accept`), a finished connection
|
||||
/// (`on_connection_end`) and attack-detector escalation (`ban_offenders`).
|
||||
pub struct TrafficHook {
|
||||
reputation: Arc<IpReputation>,
|
||||
blacklist: Arc<Blacklist>,
|
||||
|
|
@ -43,13 +43,18 @@ impl TrafficHook {
|
|||
}
|
||||
}
|
||||
|
||||
/// Новое соединение принято accept-loop'ом. Только счётчик окна cps.
|
||||
/// A new connection was accepted by the accept loop.
|
||||
///
|
||||
/// Only bumps the cps window counter; the counter is drained by
|
||||
/// [`Self::take_cps`] once per second.
|
||||
pub fn on_accept(&self) {
|
||||
self.conn_window.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Соединение обработано. Если источник попал под rate-limit (репутация
|
||||
/// упала до порога) — авто-бан с TTL из конфига.
|
||||
/// A connection finished processing.
|
||||
///
|
||||
/// If the source was pushed down to the reputation threshold, it is banned
|
||||
/// with the TTL taken from the config.
|
||||
pub fn on_connection_end(&self, ip: IpAddr) {
|
||||
if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
|
||||
return;
|
||||
|
|
@ -57,8 +62,10 @@ impl TrafficHook {
|
|||
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
|
||||
}
|
||||
|
||||
/// Эскалация детектора атак: бан всех источников ниже порога репутации.
|
||||
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик.
|
||||
/// Attack-detector escalation: bans every source below the reputation
|
||||
/// threshold and returns how many bans were issued.
|
||||
///
|
||||
/// Called once on the transition into `UnderAttack`, not on every tick.
|
||||
pub fn ban_offenders(&self) -> usize {
|
||||
if !self.autoban.enabled {
|
||||
return 0;
|
||||
|
|
@ -75,7 +82,7 @@ impl TrafficHook {
|
|||
banned
|
||||
}
|
||||
|
||||
/// Забирает накопленное окно новых соединений за секунду (cps).
|
||||
/// Takes the accumulated one-second window of new connections (cps).
|
||||
pub fn take_cps(&self) -> u64 {
|
||||
self.conn_window.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
|
|
@ -206,7 +213,7 @@ mod tests {
|
|||
enabled: true,
|
||||
reputation_threshold: -50,
|
||||
},
|
||||
// Короткий TTL как мок времени: бан жив, потом истекает.
|
||||
// Zero TTL as a time mock: the ban must be dead on arrival.
|
||||
0,
|
||||
);
|
||||
let target = ip([10, 3, 0, 1]);
|
||||
|
|
|
|||
|
|
@ -28,8 +28,12 @@ impl AttackDetector {
|
|||
}
|
||||
}
|
||||
|
||||
/// Анализирует окно метрик (пакеты/с и новые соединения/с) относительно
|
||||
/// накопленных профилей. Аномалией считается всплеск любой из метрик.
|
||||
/// Analyses one metrics window (packets/s and new connections/s) against
|
||||
/// the accumulated profiles.
|
||||
///
|
||||
/// A spike in either metric counts as an anomaly. Three consecutive
|
||||
/// anomalous windows escalate to [`AttackStatus::UnderAttack`]; a single
|
||||
/// one above the suspicious score yields [`AttackStatus::Suspicious`].
|
||||
pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus {
|
||||
self.pps_profiler.record(pps);
|
||||
self.cps_profiler.record(cps);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
//! Интеллект трафика: EWMA-сглаживание, детектор атак и репутация IP.
|
||||
//! Traffic intelligence: EWMA smoothing, attack detector and per-IP reputation.
|
||||
//!
|
||||
//! Owns the scoring primitives consumed by [`crate::traffic::hook`]; the
|
||||
//! modules are also re-exported at `traffic::{ewma, detector, reputation}`.
|
||||
pub mod detector;
|
||||
pub mod ewma;
|
||||
pub mod reputation;
|
||||
|
|
|
|||
|
|
@ -33,7 +33,10 @@ impl IpReputation {
|
|||
self.scores.get(&ip).map(|v| *v).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Возвращает источники со скором не выше `threshold` (нарушители).
|
||||
/// Returns the sources scored at or below `threshold` (the offenders).
|
||||
///
|
||||
/// The result is a snapshot copy, so it is safe to ban from it while other
|
||||
/// threads keep recording events.
|
||||
pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
|
||||
self.scores
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
//! Профилирование трафика, детектор атак и репутация IP.
|
||||
//! Traffic profiling, attack detection and per-IP reputation.
|
||||
//!
|
||||
//! Owns the state the edge node feeds from the accept path: [`hook::TrafficHook`]
|
||||
//! wires reputation, auto-ban and window metrics together, while the `intel`,
|
||||
//! `prefix` and `profile` submodules hold the detectors themselves.
|
||||
|
||||
pub mod hook;
|
||||
pub mod intel;
|
||||
pub mod prefix;
|
||||
pub mod profile;
|
||||
|
||||
// Совместимость путей после группировки: домены `intel/` и `profile/`
|
||||
// остаются доступны по прежним путям `traffic::{detector, ewma, ...}`.
|
||||
// Re-exported under the old paths (`traffic::{detector, ewma, ...}`) so the
|
||||
// grouping into `intel/` and `profile/` stays source-compatible.
|
||||
pub use intel::{detector, ewma, reputation};
|
||||
pub use profile::{alert, profiler};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
/// `family` для IPv4-префиксов (/24).
|
||||
/// `family` tag for IPv4 prefixes (/24).
|
||||
pub const PREFIX_FAMILY_V4: u8 = 4;
|
||||
/// `family` для IPv6-префиксов (/64).
|
||||
/// `family` tag for IPv6 prefixes (/64).
|
||||
pub const PREFIX_FAMILY_V6: u8 = 6;
|
||||
|
||||
/// Ключ карты `prefix_stats` (`BPF_MAP_TYPE_LRU_HASH`, max_entries 65536).
|
||||
/// Key of the `prefix_stats` map (`BPF_MAP_TYPE_LRU_HASH`, 65536 entries).
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixKey {
|
||||
|
|
@ -15,7 +15,8 @@ pub struct PrefixKey {
|
|||
}
|
||||
|
||||
impl PrefixKey {
|
||||
/// Строит ключ префикса для адреса (v4 → /24 в первых 4 байтах, v6 → /64).
|
||||
/// Builds the prefix key for an address (v4 maps to /24 in the first four
|
||||
/// bytes, v6 maps to /64).
|
||||
#[must_use]
|
||||
pub fn new(ip: IpAddr) -> Self {
|
||||
let mut key = Self::default();
|
||||
|
|
@ -32,7 +33,7 @@ impl PrefixKey {
|
|||
key
|
||||
}
|
||||
|
||||
/// Префикс как IP-адрес (маскированный).
|
||||
/// The prefix as a masked IP address; `None` for an unknown `family` tag.
|
||||
#[must_use]
|
||||
pub fn to_prefix(self) -> Option<IpAddr> {
|
||||
match self.family {
|
||||
|
|
@ -66,13 +67,14 @@ impl PrefixKey {
|
|||
}
|
||||
}
|
||||
|
||||
/// Возвращает префикс адреса: IPv4 и IPv4-mapped → /24, IPv6 → /64.
|
||||
/// Returns the prefix of an address: IPv4 and IPv4-mapped share /24, IPv6 uses /64.
|
||||
#[must_use]
|
||||
pub fn prefix_of(ip: IpAddr) -> IpAddr {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)),
|
||||
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||
// ::ffff:a.b.c.d живёт в том же /24-пространстве, что и a.b.c.d.
|
||||
// ::ffff:a.b.c.d must land in the same /24 bucket as a.b.c.d,
|
||||
// otherwise a dual-stack client could escape its own ban.
|
||||
Some(v4) => IpAddr::V4(masked_v4(v4)),
|
||||
None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
//! Subnet-level (prefix) детектор распределённых атак.
|
||||
//! Subnet-level (prefix) distributed attack detector.
|
||||
//!
|
||||
//! Источник данных — трейт [`PrefixStatsSource`]: карта XDP `prefix_stats`
|
||||
//! (feature `xdp`) либо юзерспейс-агрегатор [`crate::engine::subnet_tracker`].
|
||||
//! Контракт с XDP-агентом: [`PrefixKey`] / [`PrefixStatsVal`] должны совпадать
|
||||
//! побайтово со структурами ядра.
|
||||
//! Data arrives through the [`PrefixStatsSource`] trait: either the XDP
|
||||
//! `prefix_stats` map (feature `xdp`) or the user-space aggregator in
|
||||
//! [`crate::engine::subnet_tracker`]. [`PrefixKey`] and [`PrefixStatsVal`] must
|
||||
//! match the kernel structs byte for byte, hence the `repr(C)` layout.
|
||||
|
||||
mod key;
|
||||
mod stats;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use anyhow::Result;
|
|||
use std::future::Future;
|
||||
use std::net::IpAddr;
|
||||
|
||||
/// Значение карты `prefix_stats`.
|
||||
/// Value of the `prefix_stats` map.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixStatsVal {
|
||||
|
|
@ -12,7 +12,7 @@ pub struct PrefixStatsVal {
|
|||
}
|
||||
|
||||
impl PrefixStatsVal {
|
||||
/// Разбирает сырые 24 байта значения карты.
|
||||
/// Parses the raw 24-byte map value.
|
||||
#[must_use]
|
||||
pub fn from_bytes(bytes: [u8; 24]) -> Self {
|
||||
let read_u64 =
|
||||
|
|
@ -24,7 +24,7 @@ impl PrefixStatsVal {
|
|||
}
|
||||
}
|
||||
|
||||
/// Сериализует значение в сырые 24 байта карты.
|
||||
/// Serialises the value into the raw 24-byte map layout.
|
||||
#[must_use]
|
||||
pub fn to_bytes(self) -> [u8; 24] {
|
||||
let mut out = [0u8; 24];
|
||||
|
|
@ -35,10 +35,10 @@ impl PrefixStatsVal {
|
|||
}
|
||||
}
|
||||
|
||||
/// Агрегат по одному префиксу за окно детекции.
|
||||
/// Aggregated counters for one prefix over a detection window.
|
||||
///
|
||||
/// `unique_sources == 0` означает, что источник не считает уникальные адреса
|
||||
/// (XDP-путь); spoof-gate в этом случае Block не подтверждает.
|
||||
/// `unique_sources == 0` means the source does not count distinct addresses
|
||||
/// (the XDP path), and the spoof gate then never confirms `Block`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixSnapshot {
|
||||
pub syn_count: u64,
|
||||
|
|
@ -47,16 +47,17 @@ pub struct PrefixSnapshot {
|
|||
pub unique_sources: u64,
|
||||
}
|
||||
|
||||
/// Источник агрегатов по префиксам. Позволяет тестам работать без ядра.
|
||||
/// Source of per-prefix aggregates; keeps tests independent of the kernel.
|
||||
pub trait PrefixStatsSource {
|
||||
/// Снимок агрегатов за текущее окно.
|
||||
/// Snapshot of the aggregates for the current window.
|
||||
///
|
||||
/// # Errors
|
||||
/// Ошибка чтения источника (карта не загружена, BPF-сбой и т.п.).
|
||||
/// Returns an error when the source cannot be read (map not loaded, BPF
|
||||
/// failure and similar).
|
||||
fn snapshot(&self) -> impl Future<Output = Result<Vec<(IpAddr, PrefixSnapshot)>>> + Send;
|
||||
}
|
||||
|
||||
/// Эскалация вердиктов subnet-level детектора.
|
||||
/// Verdict escalation ladder of the subnet-level detector.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SubnetVerdict {
|
||||
Monitor,
|
||||
|
|
@ -65,7 +66,7 @@ pub enum SubnetVerdict {
|
|||
Block,
|
||||
}
|
||||
|
||||
/// Вердикт по одному префиксу.
|
||||
/// Verdict for a single prefix.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PrefixVerdict {
|
||||
pub prefix: IpAddr,
|
||||
|
|
@ -73,12 +74,13 @@ pub struct PrefixVerdict {
|
|||
pub snapshot: PrefixSnapshot,
|
||||
}
|
||||
|
||||
/// Детектор распределённых атак по префиксам.
|
||||
/// Detector for distributed attacks at prefix granularity.
|
||||
///
|
||||
/// Лестница эскалации по `syn_count` за окно: `< threshold` → Monitor,
|
||||
/// `< 2×threshold` → StrictLimit, иначе Challenge; Block только при
|
||||
/// `≥ 4×threshold` И прохождении spoof-gate (≥ `min_unique_sources`
|
||||
/// уникальных IP — защита от ложного бана CGNAT/спуфинга).
|
||||
/// Escalation ladder over the `syn_count` of one window: below `threshold` is
|
||||
/// `Monitor`, below `2 x threshold` is `StrictLimit`, anything higher is
|
||||
/// `Challenge`. `Block` requires at least `4 x threshold` *and* a passed spoof
|
||||
/// gate (at least `min_unique_sources` distinct IPs), which guards against
|
||||
/// false bans of CGNAT ranges and spoofed sources.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SubnetDetector {
|
||||
syn_threshold: u64,
|
||||
|
|
@ -99,7 +101,7 @@ impl SubnetDetector {
|
|||
Self::new(config.syn_threshold, config.min_unique_sources)
|
||||
}
|
||||
|
||||
/// Оценивает снимок и возвращает вердикты по активным префиксам.
|
||||
/// Evaluates a snapshot and returns verdicts for all active prefixes.
|
||||
#[must_use]
|
||||
pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> {
|
||||
snapshots
|
||||
|
|
@ -131,14 +133,15 @@ impl SubnetDetector {
|
|||
|
||||
#[must_use]
|
||||
fn spoof_gate_passed(&self, snap: &PrefixSnapshot) -> bool {
|
||||
// gate отключён (min_unique_sources == 0) либо подтверждено разнообразие.
|
||||
// The gate is disabled (min_unique_sources == 0) or diversity is confirmed.
|
||||
self.min_unique_sources == 0 || snap.unique_sources >= self.min_unique_sources
|
||||
}
|
||||
}
|
||||
|
||||
/// Реализация [`PrefixStatsSource`] поверх XDP-фильтра (feature `xdp`).
|
||||
/// Читает карту `prefix_stats`; уникальные источники ядро не считает,
|
||||
/// поэтому spoof-gate на этом пути Block не подтверждает.
|
||||
/// [`PrefixStatsSource`] backed by the XDP filter (feature `xdp`).
|
||||
///
|
||||
/// Reads the `prefix_stats` map. The kernel does not track distinct source
|
||||
/// addresses, so the spoof gate never confirms `Block` on this path.
|
||||
#[cfg(feature = "xdp")]
|
||||
pub struct XdpPrefixStats {
|
||||
filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>,
|
||||
|
|
@ -151,10 +154,11 @@ impl XdpPrefixStats {
|
|||
Self { filter }
|
||||
}
|
||||
|
||||
/// Блокирует мьютекс фильтра (для kernel-enforcement вердиктов).
|
||||
/// Locks the filter mutex (needed for kernel enforcement of verdicts).
|
||||
///
|
||||
/// # Panics
|
||||
/// Если мьютекс отравлен (паника в другом потоке во время удержания).
|
||||
/// Panics if the mutex is poisoned, that is, if another thread panicked
|
||||
/// while holding it.
|
||||
pub fn filter_lock(&self) -> std::sync::MutexGuard<'_, crate::xdp::XdpFilter> {
|
||||
self.filter.lock().expect("xdp lock poisoned")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,9 +56,11 @@ impl fmt::Display for Alert {
|
|||
}
|
||||
}
|
||||
|
||||
/// Дедуплицирующий диспетчер алертов: алерт выдаётся только на переходе
|
||||
/// состояния детектора (вход в `UnderAttack` и выход из него), не на каждом
|
||||
/// тике. Логика — poll-and-persist (LNVPS issue #331).
|
||||
/// Deduplicating alert dispatcher.
|
||||
///
|
||||
/// An alert is emitted only on a detector state transition (entering
|
||||
/// `UnderAttack` and leaving it), never on every tick. The behaviour is
|
||||
/// poll-and-persist: the previous status is kept as the baseline.
|
||||
#[derive(Default)]
|
||||
pub struct AlertDispatcher {
|
||||
previous: Mutex<Option<AttackStatus>>,
|
||||
|
|
@ -69,9 +71,11 @@ impl AlertDispatcher {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
/// Возвращает `Some(Alert)` только при переходе через границу атаки:
|
||||
/// вход в `UnderAttack` («attack started») или выход из него
|
||||
/// («attack ended»). Первое наблюдение алерта не порождает.
|
||||
/// Returns `Some(Alert)` only when the attack boundary is crossed: entering
|
||||
/// `UnderAttack` ("attack started") or leaving it ("attack ended").
|
||||
///
|
||||
/// The first observation never produces an alert, so a node that starts up
|
||||
/// during an attack does not report a transition it never saw.
|
||||
pub fn on_status(&self, status: AttackStatus) -> Option<Alert> {
|
||||
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
|
||||
if *previous == Some(status) {
|
||||
|
|
@ -89,9 +93,10 @@ impl AlertDispatcher {
|
|||
}
|
||||
}
|
||||
|
||||
/// Отправляет алерт на webhook (fire-and-forget, с таймаутом).
|
||||
/// Delivers an alert to a webhook (fire-and-forget, with a timeout).
|
||||
///
|
||||
/// Вызывать следует из фоновых задач: сетевой ввод-вывод недопустим в hot path.
|
||||
/// Call it from background tasks only: network I/O is not allowed on the hot
|
||||
/// path.
|
||||
pub async fn send_webhook(url: String, alert: Alert) {
|
||||
let payload = serde_json::json!({
|
||||
"level": alert.level.to_string(),
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! Профилирование трафика edge-ноды и алерты детектора атак.
|
||||
//! Edge-node traffic profiling and attack-detector alerts.
|
||||
//!
|
||||
//! Owns the sliding EWMA profiler and the deduplicating alert dispatcher;
|
||||
//! both are re-exported at `traffic::{profiler, alert}`.
|
||||
pub mod alert;
|
||||
pub mod profiler;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
//! Циклы приложения: fetch-таска (tokio) и UI-цикл (tick + события клавиатуры).
|
||||
//! Application loops: the fetch task (tokio) and the UI loop (tick plus
|
||||
//! keyboard events).
|
||||
//!
|
||||
//! Owns the wiring between a [`Fetcher`] and the terminal: the fetch task never
|
||||
//! draws and the UI loop never performs I/O beyond the terminal itself.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
|
@ -10,14 +14,14 @@ use crate::tui::prometheus::parse;
|
|||
use crate::tui::state::AppState;
|
||||
use crate::tui::ui;
|
||||
|
||||
/// Управляемые пользователем команды (клавиши).
|
||||
/// Commands the user can trigger from the keyboard.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Quit,
|
||||
Refresh,
|
||||
}
|
||||
|
||||
/// Маппинг клавиш: `q`/`Esc` — выход, `r` — обновить немедленно.
|
||||
/// Key mapping: `q`/`Esc` quit, `r` refreshes immediately.
|
||||
#[must_use]
|
||||
pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
|
||||
match code {
|
||||
|
|
@ -27,7 +31,7 @@ pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Приводит результат fetch к виду для [`AppState::apply_fetch`].
|
||||
/// Converts a fetch result into the shape expected by [`AppState::apply_fetch`].
|
||||
pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prometheus::MetricSet, String> {
|
||||
match result {
|
||||
Ok(body) => Ok(parse(&body)),
|
||||
|
|
@ -36,7 +40,10 @@ pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prome
|
|||
}
|
||||
}
|
||||
|
||||
/// Фоновая задача: fetch → [`AppState`]. Ошибки сети пишутся в снапшот баннером.
|
||||
/// Background task: fetch into [`AppState`].
|
||||
///
|
||||
/// Network failures are stored in the snapshot and rendered as an error banner,
|
||||
/// so a dead endpoint degrades the view instead of ending the session.
|
||||
pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, refresh: Duration, notify: Arc<Notify>) {
|
||||
loop {
|
||||
let started = std::time::Instant::now();
|
||||
|
|
@ -51,10 +58,11 @@ pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, r
|
|||
}
|
||||
}
|
||||
|
||||
/// UI-цикл: рисует кадр каждые ~100 мс, обрабатывает клавиши.
|
||||
/// UI loop: draws a frame roughly every 100 ms and handles key presses.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку терминала (draw/poll) — вызывающий восстанавливает TTY.
|
||||
/// Returns the terminal error from draw/poll; the caller is responsible for
|
||||
/// restoring the TTY.
|
||||
pub async fn run_ui(
|
||||
terminal: &mut ratatui::Terminal<impl ratatui::backend::Backend<Error = std::io::Error>>,
|
||||
state: Arc<AppState>,
|
||||
|
|
@ -71,13 +79,13 @@ pub async fn run_ui(
|
|||
}
|
||||
}
|
||||
|
||||
/// Неблокирующее ожидание клавиши в течение `timeout`.
|
||||
/// Non-blocking wait for a key press within `timeout`.
|
||||
fn poll_command(timeout: Duration) -> std::io::Result<Option<Command>> {
|
||||
if !crossterm::event::poll(timeout)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if let crossterm::event::Event::Key(key) = crossterm::event::read()? {
|
||||
// Реагируем только на нажатие (не автоповтор/отпускание).
|
||||
// React to presses only, ignoring auto-repeat and key releases.
|
||||
if key.kind == crossterm::event::KeyEventKind::Press {
|
||||
return Ok(handle_key(key.code));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,38 +1,44 @@
|
|||
//! Получение тела `/metrics`: трейт [`Fetcher`] для мока в тестах и HTTP-реализация.
|
||||
//! Fetching of the `/metrics` body: the [`Fetcher`] trait for test mocks plus
|
||||
//! the HTTP implementation.
|
||||
//!
|
||||
//! Owns the transport boundary of the TUI; parsing lives in
|
||||
//! [`crate::tui::prometheus`].
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::future::BoxFuture;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Ошибка загрузки метрик.
|
||||
/// Metrics fetch failure.
|
||||
#[derive(Debug, Error, Clone)]
|
||||
pub enum FetchError {
|
||||
/// Сетевая ошибка / DNS / таймаут.
|
||||
/// Network error, DNS failure or timeout.
|
||||
#[error("network error: {0}")]
|
||||
Network(String),
|
||||
/// Endpoint ответил не-200 статусом.
|
||||
/// The endpoint answered with a non-200 status.
|
||||
#[error("http status {0}")]
|
||||
Status(u16),
|
||||
}
|
||||
|
||||
/// Абстракция источника exposition-текста Prometheus.
|
||||
/// Abstraction over a source of Prometheus exposition text.
|
||||
pub trait Fetcher: Send + Sync {
|
||||
/// Загружает текущий срез метрик.
|
||||
/// Fetches the current metrics snapshot.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает [`FetchError`] при сетевом сбое или плохом HTTP-статусе.
|
||||
/// Returns [`FetchError`] on a network failure or a bad HTTP status.
|
||||
fn fetch(&self) -> BoxFuture<'_, Result<String, FetchError>>;
|
||||
}
|
||||
|
||||
/// Реализация [`Fetcher`] поверх reqwest GET.
|
||||
/// [`Fetcher`] implementation on top of a reqwest GET.
|
||||
pub struct HttpFetcher {
|
||||
url: String,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl HttpFetcher {
|
||||
/// Создаёт fetcher с таймаутом запроса 5 секунд.
|
||||
/// Creates a fetcher with a 5 second request timeout.
|
||||
///
|
||||
/// Returns `None` when the HTTP client cannot be built.
|
||||
pub fn new(url: impl Into<String>) -> Option<Self> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! Метрики TUI: парсер Prometheus-exposition и fetcher эндпоинтов.
|
||||
//! TUI metrics: the Prometheus exposition parser and the endpoint fetchers.
|
||||
//!
|
||||
//! Owns the read-only side of the TUI: turning `/metrics` text into a
|
||||
//! [`prometheus::MetricSet`] and pulling the body over HTTP (or a test mock).
|
||||
pub mod fetch;
|
||||
pub mod prometheus;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
//! Минималистичный парсер текстового формата Prometheus (version=0.0.4).
|
||||
//! Minimal parser for the Prometheus text exposition format (version 0.0.4).
|
||||
//!
|
||||
//! Поддерживает: комментарии (`# HELP`, `# TYPE`, `#`), строки вида
|
||||
//! `metric{label="value",...} value [timestamp]` и `metric value [timestamp]`.
|
||||
//! Значения `NaN`/`+Inf`/`-Inf` парсятся штатно через `f64::from_str`.
|
||||
//! Owns the parsing rules for `/metrics` bodies. Accepts comment lines
|
||||
//! (`# HELP`, `# TYPE`, `#`), `metric{label="value",...} value [timestamp]` and
|
||||
//! `metric value [timestamp]`. `NaN`/`+Inf`/`-Inf` are parsed through
|
||||
//! `f64::from_str`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Один сэмпл из exposition-формата Prometheus.
|
||||
/// One sample from the Prometheus exposition format.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MetricSample {
|
||||
pub name: String,
|
||||
|
|
@ -14,21 +15,23 @@ pub struct MetricSample {
|
|||
pub value: f64,
|
||||
}
|
||||
|
||||
/// Набор сэмплов одного ответа `/metrics`.
|
||||
/// All samples of a single `/metrics` response.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct MetricSet {
|
||||
samples: Vec<MetricSample>,
|
||||
}
|
||||
|
||||
impl MetricSet {
|
||||
/// Сумма значений всех серий с данным именем (для counter/gauge vec).
|
||||
/// Отсутствующая метрика даёт `0.0`.
|
||||
/// Sums the values of every series with this name (for counter/gauge vecs).
|
||||
///
|
||||
/// A missing metric yields `0.0`.
|
||||
#[must_use]
|
||||
pub fn sum(&self, name: &str) -> f64 {
|
||||
self.samples.iter().filter(|s| s.name == name).map(|s| s.value).sum()
|
||||
}
|
||||
|
||||
/// Значение серии с именем и одной меткой; `None`, если не найдено.
|
||||
/// Value of the series with this name carrying `label == value`, or `None`
|
||||
/// when no such series exists.
|
||||
#[must_use]
|
||||
pub fn labeled(&self, name: &str, label: &str, value: &str) -> Option<f64> {
|
||||
self.samples
|
||||
|
|
@ -37,17 +40,17 @@ impl MetricSet {
|
|||
.map(|s| s.value)
|
||||
}
|
||||
|
||||
/// Все сэмплы (для тестов и отладки).
|
||||
/// All samples (for tests and debugging).
|
||||
#[must_use]
|
||||
pub fn samples(&self) -> &[MetricSample] {
|
||||
&self.samples
|
||||
}
|
||||
}
|
||||
|
||||
/// Парсит тело ответа `/metrics`.
|
||||
/// Parses a `/metrics` response body.
|
||||
///
|
||||
/// Строки с ошибкой формата пропускаются (exposition-поток может быть частично
|
||||
/// повреждён — TUI не должен падать на этом).
|
||||
/// Lines with a malformed format are skipped: an exposition stream may be
|
||||
/// partially corrupted and the TUI must not die because of it.
|
||||
#[must_use]
|
||||
pub fn parse(input: &str) -> MetricSet {
|
||||
let mut samples = Vec::new();
|
||||
|
|
@ -64,18 +67,18 @@ fn parse_line(line: &str) -> Option<MetricSample> {
|
|||
if line.is_empty() || line.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
// Формат: metric[{labels}] value [timestamp]; значения меток могут
|
||||
// содержать пробелы, поэтому голову отрезаем с учётом кавычек.
|
||||
// Format: metric[{labels}] value [timestamp]. Label values may contain
|
||||
// spaces, so the head has to be cut with quote awareness.
|
||||
let (head, rest) = split_head_and_rest(line);
|
||||
let value_str = rest.split_whitespace().next()?;
|
||||
// Timestamp после value игнорируем.
|
||||
// A timestamp after the value is irrelevant for the TUI and dropped.
|
||||
|
||||
let (name, labels) = split_metric(head)?;
|
||||
let value = parse_value(value_str)?;
|
||||
Some(MetricSample { name, labels, value })
|
||||
}
|
||||
|
||||
/// Отделяет `metric{...}` от хвоста `value [timestamp]`.
|
||||
/// Splits `metric{...}` from the trailing `value [timestamp]`.
|
||||
fn split_head_and_rest(line: &str) -> (&str, &str) {
|
||||
let Some(open) = line.find('{') else {
|
||||
return match line.find(char::is_whitespace) {
|
||||
|
|
@ -92,7 +95,7 @@ fn split_head_and_rest(line: &str) -> (&str, &str) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Индекс `}` вне кавычек, начиная с позиции `from`.
|
||||
/// Index of the `}` outside quotes, starting at `from`.
|
||||
fn find_closing_brace(line: &str, from: usize) -> Option<usize> {
|
||||
let mut in_quotes = false;
|
||||
let mut escaped = false;
|
||||
|
|
@ -138,7 +141,7 @@ fn parse_labels(inner: &str) -> BTreeMap<String, String> {
|
|||
labels
|
||||
}
|
||||
|
||||
/// Разбивает `a="1", b="2"` по запятым вне кавычек.
|
||||
/// Splits `a="1", b="2"` on commas outside quotes.
|
||||
fn split_label_pairs(inner: &str) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let mut in_quotes = false;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
//! TUI-модуль Rampart: live-метрики edge-ноды/manager в терминале (ratatui).
|
||||
//! Rampart TUI: live edge-node and manager metrics in the terminal (ratatui).
|
||||
//!
|
||||
//! Используется бинарём `rampart-tui`; источник данных — Prometheus
|
||||
//! exposition endpoint (`/metrics`).
|
||||
//! Owns the terminal front end used by the `rampart-tui` binary; the data
|
||||
//! source is the Prometheus exposition endpoint (`/metrics`).
|
||||
//!
|
||||
//! The fetch task and the render loop communicate only through
|
||||
//! [`state::AppState`], so a slow or failing endpoint never blocks the UI.
|
||||
|
||||
pub mod app;
|
||||
pub mod metrics;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
//! Общее состояние TUI: последний срез метрик, история pps/drops, расчёт rate.
|
||||
//! Shared TUI state: the last metrics snapshot, the pps/drops history and the
|
||||
//! rate calculation.
|
||||
//!
|
||||
//! Owns the only hand-off point between the fetch task and the UI loop; every
|
||||
//! accessor is mutex-guarded and tolerates a poisoned lock.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Mutex;
|
||||
|
|
@ -6,17 +10,17 @@ use std::time::Instant;
|
|||
|
||||
use crate::tui::prometheus::MetricSet;
|
||||
|
||||
/// Максимальная длина скользящего окна графика.
|
||||
/// Maximum length of the chart's sliding window.
|
||||
pub const HISTORY_CAPACITY: usize = 120;
|
||||
|
||||
/// Один сэмпл истории (значения — rates, единиц/сек).
|
||||
/// A single history sample; the values are rates in units per second.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct HistoryPoint {
|
||||
pub packets_per_sec: f64,
|
||||
pub drops_per_sec: f64,
|
||||
}
|
||||
|
||||
/// Скользящее окно истории фиксированной ёмкости.
|
||||
/// Fixed-capacity sliding window of history samples.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct History {
|
||||
points: VecDeque<HistoryPoint>,
|
||||
|
|
@ -31,7 +35,7 @@ impl Default for History {
|
|||
}
|
||||
|
||||
impl History {
|
||||
/// Добавляет точку, вытесняя старейшую при переполнении окна.
|
||||
/// Appends a point, evicting the oldest one once the window is full.
|
||||
pub fn push(&mut self, point: HistoryPoint) {
|
||||
if self.points.len() == HISTORY_CAPACITY {
|
||||
self.points.pop_front();
|
||||
|
|
@ -39,14 +43,14 @@ impl History {
|
|||
self.points.push_back(point);
|
||||
}
|
||||
|
||||
/// Точки в хронологическом порядке.
|
||||
/// Points in chronological order.
|
||||
#[must_use]
|
||||
pub fn points(&self) -> &VecDeque<HistoryPoint> {
|
||||
&self.points
|
||||
}
|
||||
}
|
||||
|
||||
/// Состояние приложения, общее между fetch-потоком и UI-циклом.
|
||||
/// Application state shared between the fetch task and the UI loop.
|
||||
#[derive(Debug)]
|
||||
pub struct AppState {
|
||||
url: String,
|
||||
|
|
@ -56,7 +60,7 @@ pub struct AppState {
|
|||
}
|
||||
|
||||
impl AppState {
|
||||
/// Создаёт состояние с URL источника метрик (для статус-панели).
|
||||
/// Creates the state for a metrics source URL (shown in the status panel).
|
||||
#[must_use]
|
||||
pub fn new(url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
|
|
@ -67,14 +71,14 @@ impl AppState {
|
|||
}
|
||||
}
|
||||
|
||||
/// URL источника метрик.
|
||||
/// URL of the metrics source.
|
||||
#[must_use]
|
||||
pub fn url(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
}
|
||||
|
||||
/// Последний успешный/неуспешный результат fetch.
|
||||
/// Result of the latest successful or failed fetch.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Snapshot {
|
||||
pub metrics: Option<MetricSet>,
|
||||
|
|
@ -83,7 +87,7 @@ pub struct Snapshot {
|
|||
}
|
||||
|
||||
impl AppState {
|
||||
/// Записывает результат очередного fetch и обновляет историю rate.
|
||||
/// Records the result of the latest fetch and extends the rate history.
|
||||
pub fn apply_fetch(&self, result: Result<MetricSet, String>, elapsed_secs: f64) {
|
||||
let mut snapshot = match self.snapshot.lock() {
|
||||
Ok(guard) => guard,
|
||||
|
|
@ -119,9 +123,9 @@ impl AppState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Копия среза метрик + истории для отрисовки кадра.
|
||||
/// Copy of the metrics snapshot plus history for rendering one frame.
|
||||
///
|
||||
/// UI не держит лок — рисуем по снимку.
|
||||
/// The UI never holds a lock: it draws from the copy.
|
||||
#[must_use]
|
||||
pub fn frame_data(&self) -> FrameData {
|
||||
let snapshot = self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
|
@ -139,21 +143,21 @@ impl AppState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Снимок для одного кадра UI.
|
||||
/// Snapshot consumed by a single UI frame.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct FrameData {
|
||||
/// URL источника метрик.
|
||||
/// URL of the metrics source.
|
||||
pub url: String,
|
||||
pub snapshot: Snapshot,
|
||||
pub history: History,
|
||||
/// Время работы TUI (сек).
|
||||
/// TUI uptime in seconds.
|
||||
pub uptime_secs: u64,
|
||||
}
|
||||
|
||||
/// Rate счётчика из двух сэмплов: `(current - previous) / dt`.
|
||||
/// Counter rate from two samples: `(current - previous) / dt`.
|
||||
///
|
||||
/// `None` у предыдущего значения (первый сэмпл) даёт 0.0. Сброс счётчика
|
||||
/// (`current < previous`) трактуетcя как рестарт процесса → 0.0.
|
||||
/// A `None` previous value (first sample) yields 0.0. A counter reset
|
||||
/// (`current < previous`) is treated as a process restart and also yields 0.0.
|
||||
#[must_use]
|
||||
pub fn counter_rate(previous: Option<f64>, current: Option<f64>, elapsed_secs: f64) -> f64 {
|
||||
let (Some(previous), Some(current)) = (previous, current) else {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
//! Отрисовка кадра ratatui: статус-панель, таблица счётчиков, график pps/drops, помощь.
|
||||
//! ratatui frame rendering: status panel, counters table, pps/drops chart and
|
||||
//! the key help line.
|
||||
//!
|
||||
//! Owns the visual layout only; all values come from [`FrameData`].
|
||||
|
||||
use ratatui::Frame;
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
|
|
@ -9,7 +12,7 @@ use ratatui::widgets::{Axis, Block, Borders, Chart, Dataset, GraphType, Paragrap
|
|||
|
||||
use crate::tui::state::{FrameData, HistoryPoint};
|
||||
|
||||
/// Имена метрик edge/manager (см. src/metrics.rs и src/xdp/metrics.rs).
|
||||
/// Edge/manager metric names (see src/metrics.rs and src/xdp/metrics.rs).
|
||||
mod names {
|
||||
pub const XDP_TOTAL: &str = "rampart_xdp_total";
|
||||
pub const XDP_TCP: &str = "rampart_xdp_tcp";
|
||||
|
|
@ -27,7 +30,7 @@ mod names {
|
|||
pub const ATTACK_STATUS: &str = "rampart_attack_status";
|
||||
}
|
||||
|
||||
/// Рисует весь кадр.
|
||||
/// Draws the whole frame.
|
||||
pub fn render(frame: &mut Frame, data: &FrameData) {
|
||||
let [header, body, help] =
|
||||
Layout::vertical([Constraint::Length(3), Constraint::Min(3), Constraint::Length(1)]).areas(frame.area());
|
||||
|
|
@ -69,7 +72,7 @@ fn render_header(frame: &mut Frame, area: Rect, data: &FrameData) {
|
|||
frame.render_widget(Paragraph::new(line).block(Block::new().borders(Borders::ALL)), area);
|
||||
}
|
||||
|
||||
/// Пары «подпись → имя метрики» для таблицы.
|
||||
/// Counter label to metric name pairs for the table.
|
||||
const COUNTER_ROWS: &[(&str, &str)] = &[
|
||||
("XDP total", names::XDP_TOTAL),
|
||||
("XDP tcp", names::XDP_TCP),
|
||||
|
|
|
|||
|
|
@ -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"));
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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}'"))?;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Зондирование XDP-окружения: диагностика, статистика и метрики.
|
||||
//! XDP environment probing: diagnostics, statistics and metrics.
|
||||
|
||||
mod diagnostics;
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue