feat: traffic intel hot path, SYN RST-challenge, XDP environment diagnostics

Traffic Intel (was dead code, now wired):
- TrafficHook in listener accept path: cps/pps windows -> AttackDetector
- auto-ban IPs below reputation threshold under attack ([detect.autoban])
- AlertDispatcher: webhook on attack state transition only (dedup), metrics
  AUTO_BANS_TOTAL / INTEL_* ; [detect.alert].webhook_url

XDP SYN RST-challenge (Oubliette pattern, off by default):
- G_SYN_CHALLENGE_ENABLED=0: kernel replies bad-ACK SYN-ACK via XDP_TX,
  spoofed sources stay silent, live clients answer RST with secret echo ->
  challenge_verified (LRU, sliding TTL); brute-force of marker impossible
- maps challenge_verified/challenge_pending, STAT_CHALLENGE_*, all logic
  in xdp/core/syn_challenge.h (221 lines)

XDP diagnostics (src/xdp/diagnostics.rs):
- EnvironmentReport: kernel version/BTF/driver->AttachMode verdict,
  fail-fast before load on unsupported kernels; wired into  CLI
- SystemProbe trait for kernel-less testing

fix: .gitignore 'bin/' matched src/bin/ — rampart.rs was never committed

cargo build/clippy(-D warnings, --features xdp)/test green: 107 tests
This commit is contained in:
Loki 2026-08-24 10:11:10 +02:00
parent 5d7cdc24e3
commit f53464a45e
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
25 changed files with 1825 additions and 28 deletions

View file

@ -1,6 +1,9 @@
use std::fmt;
use std::net::Ipv4Addr;
use std::time::Instant;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::traffic::detector::AttackStatus;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertLevel {
@ -19,7 +22,7 @@ impl fmt::Display for AlertLevel {
}
}
#[derive(Clone)]
#[derive(Debug, Clone, PartialEq)]
pub struct Alert {
pub level: AlertLevel,
pub message: String,
@ -53,6 +56,61 @@ impl fmt::Display for Alert {
}
}
/// Дедуплицирующий диспетчер алертов: алерт выдаётся только на переходе
/// состояния детектора (вход в `UnderAttack` и выход из него), не на каждом
/// тике. Логика — poll-and-persist (LNVPS issue #331).
#[derive(Default)]
pub struct AlertDispatcher {
previous: Mutex<Option<AttackStatus>>,
}
impl AlertDispatcher {
pub fn new() -> Self {
Self::default()
}
/// Возвращает `Some(Alert)` только при переходе через границу атаки:
/// вход в `UnderAttack` («attack started») или выход из него
/// («attack ended»). Первое наблюдение алерта не порождает.
pub fn on_status(&self, status: AttackStatus) -> Option<Alert> {
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
if *previous == Some(status) {
return None;
}
let was_under_attack = *previous == Some(AttackStatus::UnderAttack);
*previous = Some(status);
match (was_under_attack, status) {
(false, AttackStatus::UnderAttack) => {
Some(Alert::new(AlertLevel::Critical, "attack started".into(), None, 0.0))
},
(true, _) => Some(Alert::new(AlertLevel::Info, "attack ended".into(), None, 0.0)),
_ => None,
}
}
}
/// Отправляет алерт на webhook (fire-and-forget, с таймаутом).
///
/// Вызывать следует из фоновых задач: сетевой ввод-вывод недопустим в hot path.
pub async fn send_webhook(url: String, alert: Alert) {
let payload = serde_json::json!({
"level": alert.level.to_string(),
"message": alert.message,
"pps": alert.pps,
});
let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build();
let client = match client {
Ok(c) => c,
Err(e) => {
tracing::warn!("webhook client build failed: {e}");
return;
},
};
if let Err(e) = client.post(url).json(&payload).send().await {
tracing::warn!("webhook delivery failed: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -77,4 +135,35 @@ mod tests {
assert!(s.contains("INFO"));
assert!(s.contains("traffic spike"));
}
#[test]
fn test_dispatcher_two_transitions_two_alerts() {
let dispatcher = AlertDispatcher::new();
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert_eq!(dispatcher.on_status(AttackStatus::Suspicious), None);
let started = dispatcher.on_status(AttackStatus::UnderAttack);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
let ended = dispatcher.on_status(AttackStatus::Normal);
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert!(started.is_some());
assert!(ended.is_some());
assert!(
started.expect("started alert").message.contains("attack started")
&& ended.expect("ended alert").message.contains("attack ended")
);
}
#[test]
fn test_dispatcher_suspicious_does_not_flap_alerts() {
let dispatcher = AlertDispatcher::new();
for status in [
AttackStatus::Normal,
AttackStatus::Suspicious,
AttackStatus::Normal,
AttackStatus::Suspicious,
] {
assert_eq!(dispatcher.on_status(status), None);
}
}
}