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:
parent
5d7cdc24e3
commit
f53464a45e
25 changed files with 1825 additions and 28 deletions
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ pub enum AttackStatus {
|
|||
}
|
||||
|
||||
pub struct AttackDetector {
|
||||
profiler: TrafficProfiler,
|
||||
pps_profiler: TrafficProfiler,
|
||||
cps_profiler: TrafficProfiler,
|
||||
consecutive_anomalies: u32,
|
||||
}
|
||||
|
||||
|
|
@ -21,14 +22,21 @@ impl Default for AttackDetector {
|
|||
impl AttackDetector {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
profiler: TrafficProfiler::new(),
|
||||
pps_profiler: TrafficProfiler::new(),
|
||||
cps_profiler: TrafficProfiler::new(),
|
||||
consecutive_anomalies: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn analyze(&mut self, pps: f64) -> AttackStatus {
|
||||
self.profiler.record(pps);
|
||||
let score = self.profiler.anomaly_score(pps);
|
||||
/// Анализирует окно метрик (пакеты/с и новые соединения/с) относительно
|
||||
/// накопленных профилей. Аномалией считается всплеск любой из метрик.
|
||||
pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus {
|
||||
self.pps_profiler.record(pps);
|
||||
self.cps_profiler.record(cps);
|
||||
let score = self
|
||||
.pps_profiler
|
||||
.anomaly_score(pps)
|
||||
.max(self.cps_profiler.anomaly_score(cps));
|
||||
|
||||
if score > 3.0 {
|
||||
self.consecutive_anomalies += 1;
|
||||
|
|
@ -54,40 +62,49 @@ mod tests {
|
|||
fn test_attack_status_normal() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(100.0);
|
||||
d.analyze(100.0, 10.0);
|
||||
}
|
||||
assert_eq!(d.analyze(100.0), AttackStatus::Normal);
|
||||
assert_eq!(d.analyze(100.0, 10.0), AttackStatus::Normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_attack_status_suspicious() {
|
||||
fn test_attack_status_suspicious_pps_spike() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(1.0);
|
||||
d.analyze(1.0, 1.0);
|
||||
}
|
||||
assert_eq!(d.analyze(5.0), AttackStatus::Suspicious);
|
||||
assert_eq!(d.analyze(5.0, 1.0), AttackStatus::Suspicious);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_attack_status_suspicious_cps_spike() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(1.0, 1.0);
|
||||
}
|
||||
assert_eq!(d.analyze(1.0, 5.0), AttackStatus::Suspicious);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_attack_status_under_attack() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(1.0);
|
||||
d.analyze(1.0, 1.0);
|
||||
}
|
||||
d.analyze(10_000.0);
|
||||
d.analyze(10_000.0);
|
||||
assert_eq!(d.analyze(10_000.0), AttackStatus::UnderAttack);
|
||||
d.analyze(10_000.0, 100.0);
|
||||
d.analyze(10_000.0, 100.0);
|
||||
assert_eq!(d.analyze(10_000.0, 100.0), AttackStatus::UnderAttack);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consecutive_resets_on_normal() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(1.0);
|
||||
d.analyze(1.0, 1.0);
|
||||
}
|
||||
d.analyze(100.0);
|
||||
d.analyze(100.0);
|
||||
d.analyze(1.0);
|
||||
assert_eq!(d.analyze(1.0), AttackStatus::Normal);
|
||||
d.analyze(100.0, 10.0);
|
||||
d.analyze(100.0, 10.0);
|
||||
d.analyze(1.0, 1.0);
|
||||
assert_eq!(d.analyze(1.0, 1.0), AttackStatus::Normal);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
219
src/traffic/hook.rs
Normal file
219
src/traffic/hook.rs
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
//! Traffic Intelligence в hot path: репутация → авто-бан → метрики окна.
|
||||
//!
|
||||
//! Все вызовы из accept-пути дешёвые (DashMap/атомики), блокирующего
|
||||
//! ввода-вывода нет.
|
||||
|
||||
use crate::config::DetectAutobanConfig;
|
||||
use crate::filter::blacklist::Blacklist;
|
||||
use crate::metrics;
|
||||
use crate::traffic::reputation::IpReputation;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
const BAN_REASON_LOW_REPUTATION: &str = "low_reputation";
|
||||
const BAN_REASON_ATTACK: &str = "attack_detector";
|
||||
|
||||
/// Точка входа Traffic Intelligence для сетевого пути.
|
||||
///
|
||||
/// События: новое соединение (`on_accept`), завершение обработки соединения
|
||||
/// (`on_connection_end`), эскалация детектора атак (`ban_offenders`).
|
||||
pub struct TrafficHook {
|
||||
reputation: Arc<IpReputation>,
|
||||
blacklist: Arc<Blacklist>,
|
||||
autoban: DetectAutobanConfig,
|
||||
ban_ttl_secs: u64,
|
||||
conn_window: AtomicU64,
|
||||
}
|
||||
|
||||
impl TrafficHook {
|
||||
pub fn new(
|
||||
reputation: Arc<IpReputation>,
|
||||
blacklist: Arc<Blacklist>,
|
||||
autoban: DetectAutobanConfig,
|
||||
ban_ttl_secs: u64,
|
||||
) -> Self {
|
||||
Self {
|
||||
reputation,
|
||||
blacklist,
|
||||
autoban,
|
||||
ban_ttl_secs,
|
||||
conn_window: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Новое соединение принято accept-loop'ом. Только счётчик окна cps.
|
||||
pub fn on_accept(&self) {
|
||||
self.conn_window.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Соединение обработано. Если источник попал под rate-limit (репутация
|
||||
/// упала до порога) — авто-бан с TTL из конфига.
|
||||
pub fn on_connection_end(&self, ip: IpAddr) {
|
||||
if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
|
||||
return;
|
||||
}
|
||||
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
|
||||
}
|
||||
|
||||
/// Эскалация детектора атак: бан всех источников ниже порога репутации.
|
||||
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик.
|
||||
pub fn ban_offenders(&self) -> usize {
|
||||
if !self.autoban.enabled {
|
||||
return 0;
|
||||
}
|
||||
let offenders = self.reputation.offenders_below(self.autoban.reputation_threshold);
|
||||
let mut banned = 0;
|
||||
for ip in offenders {
|
||||
if self.blacklist.is_blocked(ip) {
|
||||
continue;
|
||||
}
|
||||
self.ban(ip, BAN_REASON_ATTACK);
|
||||
banned += 1;
|
||||
}
|
||||
banned
|
||||
}
|
||||
|
||||
/// Забирает накопленное окно новых соединений за секунду (cps).
|
||||
pub fn take_cps(&self) -> u64 {
|
||||
self.conn_window.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn autoban_if_toxic(&self, ip: IpAddr, reason: &str) {
|
||||
if self.reputation.score(ip) > self.autoban.reputation_threshold {
|
||||
return;
|
||||
}
|
||||
self.ban(ip, reason);
|
||||
}
|
||||
|
||||
fn ban(&self, ip: IpAddr, reason: &str) {
|
||||
self.blacklist.add(ip, Duration::from_secs(self.ban_ttl_secs), reason);
|
||||
metrics::AUTO_BANS_TOTAL.with_label_values(&[reason]).inc();
|
||||
tracing::warn!(%ip, reason, ttl_secs = self.ban_ttl_secs, "auto-ban issued by traffic intelligence");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
fn ip(octets: [u8; 4]) -> IpAddr {
|
||||
IpAddr::V4(Ipv4Addr::from(octets))
|
||||
}
|
||||
|
||||
fn hook(rep: &Arc<IpReputation>, bl: &Arc<Blacklist>) -> TrafficHook {
|
||||
TrafficHook::new(
|
||||
Arc::clone(rep),
|
||||
Arc::clone(bl),
|
||||
DetectAutobanConfig {
|
||||
enabled: true,
|
||||
reputation_threshold: -50,
|
||||
},
|
||||
60,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cps_window_counts_and_resets() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = hook(&rep, &bl);
|
||||
hook.on_accept();
|
||||
hook.on_accept();
|
||||
hook.on_accept();
|
||||
assert_eq!(hook.take_cps(), 3);
|
||||
assert_eq!(hook.take_cps(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_fall_triggers_autoban() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = hook(&rep, &bl);
|
||||
let target = ip([10, 1, 0, 1]);
|
||||
for _ in 0..6 {
|
||||
rep.record_bad(target);
|
||||
}
|
||||
assert_eq!(rep.score(target), -60);
|
||||
assert!(!bl.is_blocked(target));
|
||||
hook.on_connection_end(target);
|
||||
assert!(bl.is_blocked(target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_autoban_above_threshold() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = hook(&rep, &bl);
|
||||
let target = ip([10, 1, 0, 2]);
|
||||
for _ in 0..4 {
|
||||
rep.record_bad(target);
|
||||
}
|
||||
assert_eq!(rep.score(target), -40);
|
||||
hook.on_connection_end(target);
|
||||
assert!(!bl.is_blocked(target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disabled_autoban_never_bans() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = TrafficHook::new(
|
||||
Arc::clone(&rep),
|
||||
Arc::clone(&bl),
|
||||
DetectAutobanConfig {
|
||||
enabled: false,
|
||||
reputation_threshold: -50,
|
||||
},
|
||||
60,
|
||||
);
|
||||
let target = ip([10, 1, 0, 3]);
|
||||
for _ in 0..20 {
|
||||
rep.record_bad(target);
|
||||
}
|
||||
hook.on_connection_end(target);
|
||||
assert!(hook.ban_offenders() == 0);
|
||||
assert!(!bl.is_blocked(target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ban_offenders_bans_only_below_threshold() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = hook(&rep, &bl);
|
||||
let bad = ip([10, 2, 0, 1]);
|
||||
let ok = ip([10, 2, 0, 2]);
|
||||
for _ in 0..8 {
|
||||
rep.record_bad(bad);
|
||||
}
|
||||
rep.record_good(ok);
|
||||
assert_eq!(hook.ban_offenders(), 1);
|
||||
assert!(bl.is_blocked(bad));
|
||||
assert!(!bl.is_blocked(ok));
|
||||
assert_eq!(hook.ban_offenders(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_autoban_ttl_expires() {
|
||||
let rep = Arc::new(IpReputation::new());
|
||||
let bl = Arc::new(Blacklist::new());
|
||||
let hook = TrafficHook::new(
|
||||
Arc::clone(&rep),
|
||||
Arc::clone(&bl),
|
||||
DetectAutobanConfig {
|
||||
enabled: true,
|
||||
reputation_threshold: -50,
|
||||
},
|
||||
// Короткий TTL как мок времени: бан жив, потом истекает.
|
||||
0,
|
||||
);
|
||||
let target = ip([10, 3, 0, 1]);
|
||||
for _ in 0..20 {
|
||||
rep.record_bad(target);
|
||||
}
|
||||
hook.on_connection_end(target);
|
||||
assert!(!bl.is_blocked(target), "zero TTL must not produce an active ban");
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
pub mod alert;
|
||||
pub mod detector;
|
||||
pub mod ewma;
|
||||
pub mod hook;
|
||||
pub mod prefix;
|
||||
pub mod profiler;
|
||||
pub mod reputation;
|
||||
|
|
|
|||
|
|
@ -33,6 +33,15 @@ impl IpReputation {
|
|||
self.scores.get(&ip).map(|v| *v).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Возвращает источники со скором не выше `threshold` (нарушители).
|
||||
pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
|
||||
self.scores
|
||||
.iter()
|
||||
.filter(|entry| *entry.value() <= threshold)
|
||||
.map(|entry| *entry.key())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_trusted(&self, ip: IpAddr) -> bool {
|
||||
self.score(ip) > 50
|
||||
}
|
||||
|
|
@ -107,4 +116,23 @@ mod tests {
|
|||
rep.record_bad(ip);
|
||||
assert_eq!(rep.score(ip), -10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offenders_below_threshold() {
|
||||
let rep = IpReputation::new();
|
||||
let bad = v4([10, 0, 0, 1]);
|
||||
let good = v4([10, 0, 0, 2]);
|
||||
for _ in 0..6 {
|
||||
rep.record_bad(bad);
|
||||
}
|
||||
rep.record_good(good);
|
||||
let offenders = rep.offenders_below(-50);
|
||||
assert_eq!(offenders, vec![bad]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offenders_empty_when_none_below() {
|
||||
let rep = IpReputation::new();
|
||||
assert!(rep.offenders_below(-50).is_empty());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue