fix(core): close auth bypass, hangs and memory leaks found by review
Security:
- An empty API_PASSWORD passed validation (only the literal "changeme" was
rejected) and verify_password("", "") returned true, so a login with an
empty password minted an admin token. Require >= 16 characters and >= 32
non-whitespace bytes for JWT_SECRET; verify rejects an empty stored secret.
- syn_challenge_enabled required a real challenge_secret_hex: the public
placeholder from config.h is now rejected in every spelling.
- docker-compose: Redis/ClickHouse/Grafana are loopback-only and every
password uses ${VAR:?} instead of a default. An exposed Redis was a way to
lift bans and publish unbans to the whole fleet with one redis-cli.
- Empty CORS_ORIGIN no longer means "allow any origin".
- ban_cidr / userspace blacklist validate and mask prefixes; CIDR bans are
stored as ranges, so a /24 or /64 ban actually covers the subnet (before,
only the network address was blocked).
Availability:
- ClickHouse client has connect/request timeouts and no mutex held across
await: a hung analytics backend can no longer freeze the ban path. Events
go through a bounded buffer with a drop counter.
- Redis uses a ConnectionManager with per-command timeouts; pubsub and
reconcile reset the backoff after success; publish cannot block shutdown.
- Ban durations from pubsub are clamped and use checked_add; the sync task
survives panics instead of silently dying.
- Blacklist TOCTOU (remove_if) and replace_redis no longer empties the table
during a Redis reconnect.
- RateLimiter and reputation have hard caps with incremental eviction instead
of an unbounded DashMap and a stop-the-world retain.
- The attack detector scores before updating its baseline and needs several
quiet windows to leave UnderAttack, so a sustained flood keeps banning new
offenders instead of ending after one tick.
- accept() backs off on EMFILE/ENFILE, shutdown Err is treated as shutdown,
a global semaphore bounds in-flight connections, rate limiting runs before
PoW, whitelisted IPs are never banned, and connect/handshake/relay have
timeouts with an idle budget.
- PoW uses the configured difficulty as a floor, the clamp is enforced, and
nonce framing survives split segments and coalesced handshake bytes.
- Subnet tracker memory is capped (prefixes and per-prefix sources) and the
monitor bans with the configured TTL.
CI and docs:
- CI runs the test suite with --no-default-features --features protocol-http;
make ebpf fails on errors; the secrets gate catches weak compose defaults.
- doctor skips protected endpoints without a token and exits non-zero on
failure; a drain timeout returns exit code 1.
- TODO §2b records the review findings, what is fixed and what is deferred;
configuration/testing docs describe the new XDP and secret semantics.
This commit is contained in:
parent
14dcaccdbf
commit
c1a076a4a3
57 changed files with 4193 additions and 1171 deletions
|
|
@ -1,16 +1,93 @@
|
|||
//! Attack state machine over the hour-of-week traffic profile.
|
||||
//!
|
||||
//! [`AttackDetector`] scores every one-second window against the baselines
|
||||
//! *before* the window is folded into them. Scoring first is what keeps a
|
||||
//! sustained flood visible: a detector that learns the attack as normal stops
|
||||
//! escalating after a few ticks, and anything that depends on
|
||||
//! [`AttackStatus::UnderAttack`] (for example offender bans) stops working for
|
||||
//! the rest of the attack.
|
||||
//!
|
||||
//! Two baselines are combined:
|
||||
//!
|
||||
//! - [`TrafficProfiler`]: the hour-of-week shape, updated from clean windows.
|
||||
//! - A slow seeded EWMA (1% per window): the global traffic level. It covers
|
||||
//! the cold start and the first tick of every hour slot, where the
|
||||
//! hour-of-week baseline is still zero or close to it.
|
||||
//!
|
||||
//! A window is scored against the higher of the two, and attack-level windows
|
||||
//! are not recorded at all. A flood therefore never becomes the baseline it is
|
||||
//! compared to, while ordinary drift (below [`DetectorThresholds::attack_score`])
|
||||
//! keeps both baselines current.
|
||||
//!
|
||||
//! Leaving [`AttackStatus::UnderAttack`] requires
|
||||
//! [`DetectorThresholds::recover_after`] consecutive windows below
|
||||
//! [`DetectorThresholds::attack_score`]. The exit hysteresis keeps a single
|
||||
//! calm window in the middle of an attack from restarting the escalation
|
||||
//! count.
|
||||
|
||||
use crate::traffic::ewma::Ewma;
|
||||
use crate::traffic::profiler::TrafficProfiler;
|
||||
|
||||
/// Smoothing factor of the slow global baseline: one percent per window, so a
|
||||
/// legitimate traffic shift is learned in about a hundred seconds.
|
||||
const SLOW_ALPHA: f64 = 0.01;
|
||||
/// Upper bound of a reported score; `10` means "at least ten times the
|
||||
/// baseline" and keeps the attack state machine from chasing huge ratios.
|
||||
const MAX_ANOMALY_RATIO: f64 = 10.0;
|
||||
|
||||
/// Classification of the current traffic window.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AttackStatus {
|
||||
/// Traffic is within the learned baseline.
|
||||
Normal,
|
||||
/// A ratio above [`DetectorThresholds::suspicious_score`] was observed,
|
||||
/// but the escalation count is not reached yet.
|
||||
Suspicious,
|
||||
/// Consecutive anomalous windows were observed; the edge escalates.
|
||||
UnderAttack,
|
||||
}
|
||||
|
||||
/// Tunables of the attack state machine.
|
||||
///
|
||||
/// The scores are ratios to the baseline (a value of `3.0` means "three times
|
||||
/// the usual rate"). The defaults match the v0.3 policy; a caller that needs a
|
||||
/// different sensitivity passes its own values to
|
||||
/// [`AttackDetector::with_thresholds`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct DetectorThresholds {
|
||||
/// Ratio that marks a window as suspicious.
|
||||
pub suspicious_score: f64,
|
||||
/// Ratio that counts a window as anomalous for escalation.
|
||||
pub attack_score: f64,
|
||||
/// Consecutive anomalous windows required to enter `UnderAttack`.
|
||||
pub escalate_after: u32,
|
||||
/// Consecutive sub-attack windows required to leave `UnderAttack`.
|
||||
pub recover_after: u32,
|
||||
}
|
||||
|
||||
impl Default for DetectorThresholds {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
suspicious_score: 2.0,
|
||||
attack_score: 3.0,
|
||||
escalate_after: 3,
|
||||
recover_after: 5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detects floods from the packets-per-second and connections-per-second
|
||||
/// profiles.
|
||||
pub struct AttackDetector {
|
||||
pps_profiler: TrafficProfiler,
|
||||
cps_profiler: TrafficProfiler,
|
||||
pps_slow: Ewma,
|
||||
cps_slow: Ewma,
|
||||
primed: bool,
|
||||
thresholds: DetectorThresholds,
|
||||
consecutive_anomalies: u32,
|
||||
recovery_windows: u32,
|
||||
under_attack: bool,
|
||||
}
|
||||
|
||||
impl Default for AttackDetector {
|
||||
|
|
@ -20,95 +97,99 @@ impl Default for AttackDetector {
|
|||
}
|
||||
|
||||
impl AttackDetector {
|
||||
/// Builds a detector with the default [`DetectorThresholds`].
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::with_thresholds(DetectorThresholds::default())
|
||||
}
|
||||
|
||||
/// Builds a detector with explicit thresholds.
|
||||
#[must_use]
|
||||
pub fn with_thresholds(thresholds: DetectorThresholds) -> Self {
|
||||
Self {
|
||||
pps_profiler: TrafficProfiler::new(),
|
||||
cps_profiler: TrafficProfiler::new(),
|
||||
pps_slow: Ewma::new(SLOW_ALPHA),
|
||||
cps_slow: Ewma::new(SLOW_ALPHA),
|
||||
primed: false,
|
||||
thresholds,
|
||||
consecutive_anomalies: 0,
|
||||
recovery_windows: 0,
|
||||
under_attack: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyses one metrics window (packets/s and new connections/s) against
|
||||
/// the accumulated profiles.
|
||||
/// Analyses one metrics window (packets/s and new connections/s) and
|
||||
/// returns the attack classification.
|
||||
///
|
||||
/// 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`].
|
||||
/// A window is anomalous when its ratio to the baseline reaches
|
||||
/// [`DetectorThresholds::attack_score`].
|
||||
/// [`DetectorThresholds::escalate_after`] consecutive anomalous windows
|
||||
/// enter `UnderAttack`; the status is left only after
|
||||
/// [`DetectorThresholds::recover_after`] consecutive windows below the
|
||||
/// attack score. The first window only primes the baselines.
|
||||
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;
|
||||
} else {
|
||||
self.consecutive_anomalies = 0;
|
||||
if !self.primed {
|
||||
self.primed = true;
|
||||
self.pps_slow.seed(pps);
|
||||
self.cps_slow.seed(cps);
|
||||
self.pps_profiler.record(pps);
|
||||
self.cps_profiler.record(cps);
|
||||
return AttackStatus::Normal;
|
||||
}
|
||||
|
||||
if self.consecutive_anomalies >= 3 {
|
||||
// Score against the baselines first: recording first would fold the
|
||||
// spike into the baseline it is scored against.
|
||||
let pps_baseline = self.pps_profiler.baseline().max(self.pps_slow.value());
|
||||
let cps_baseline = self.cps_profiler.baseline().max(self.cps_slow.value());
|
||||
let score = anomaly_ratio(pps, pps_baseline).max(anomaly_ratio(cps, cps_baseline));
|
||||
|
||||
self.update_state(score);
|
||||
|
||||
// Attack-level windows never enter the baselines (see the module
|
||||
// documentation); everything else keeps both of them current.
|
||||
if score < self.thresholds.attack_score {
|
||||
self.pps_profiler.record(pps);
|
||||
self.cps_profiler.record(cps);
|
||||
self.pps_slow.update(pps);
|
||||
self.cps_slow.update(cps);
|
||||
}
|
||||
|
||||
if self.under_attack {
|
||||
AttackStatus::UnderAttack
|
||||
} else if score > 2.0 {
|
||||
} else if score >= self.thresholds.suspicious_score {
|
||||
AttackStatus::Suspicious
|
||||
} else {
|
||||
AttackStatus::Normal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_attack_status_normal() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(100.0, 10.0);
|
||||
fn update_state(&mut self, score: f64) {
|
||||
if score >= self.thresholds.attack_score {
|
||||
self.consecutive_anomalies = self.consecutive_anomalies.saturating_add(1);
|
||||
self.recovery_windows = 0;
|
||||
} else {
|
||||
self.consecutive_anomalies = 0;
|
||||
self.recovery_windows = self.recovery_windows.saturating_add(1);
|
||||
}
|
||||
assert_eq!(d.analyze(100.0, 10.0), AttackStatus::Normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_attack_status_suspicious_pps_spike() {
|
||||
let mut d = AttackDetector::new();
|
||||
for _ in 0..10 {
|
||||
d.analyze(1.0, 1.0);
|
||||
if self.under_attack {
|
||||
if self.recovery_windows >= self.thresholds.recover_after {
|
||||
self.under_attack = false;
|
||||
}
|
||||
} else if self.consecutive_anomalies >= self.thresholds.escalate_after {
|
||||
self.under_attack = true;
|
||||
}
|
||||
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, 1.0);
|
||||
}
|
||||
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, 1.0);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ratio of a window to its baseline, capped at [`MAX_ANOMALY_RATIO`].
|
||||
///
|
||||
/// Returns zero for an unset baseline and for non-finite windows, so a broken
|
||||
/// counter cannot pin the detector in the attack state.
|
||||
fn anomaly_ratio(sample: f64, baseline: f64) -> f64 {
|
||||
if !sample.is_finite() || baseline <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
(sample.max(0.0) / baseline).min(MAX_ANOMALY_RATIO)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,29 @@
|
|||
//! Time-aware exponential moving average used by the traffic profilers.
|
||||
//!
|
||||
//! The average is expressed in samples per unit time and is fed once per
|
||||
//! metrics window by [`crate::traffic::profiler::TrafficProfiler`].
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
/// Smoothing factor used for `alpha` values outside the valid `(0, 1]` range
|
||||
/// and for `NaN`, so a malformed configuration cannot freeze the baseline.
|
||||
const DEFAULT_ALPHA: f64 = 0.125;
|
||||
|
||||
/// Exponential moving average with a wall-clock aware step count.
|
||||
///
|
||||
/// # Formula
|
||||
///
|
||||
/// For a sample `x` that arrives `dt` seconds after the previous update,
|
||||
/// `steps = max(dt, 1)` and `weight = (1 - alpha)^steps`. The average is then
|
||||
///
|
||||
/// ```text
|
||||
/// value = value * weight + x * (1 - weight)
|
||||
/// ```
|
||||
///
|
||||
/// A larger `alpha` gives more weight to the newest sample; `alpha = 1` makes
|
||||
/// the average equal to the last finite sample. The step count keeps the
|
||||
/// smoothing independent of the tick rate: one update after a two-second gap
|
||||
/// is worth two one-second updates.
|
||||
pub struct Ewma {
|
||||
value: f64,
|
||||
last: Instant,
|
||||
|
|
@ -7,51 +31,59 @@ pub struct Ewma {
|
|||
}
|
||||
|
||||
impl Ewma {
|
||||
/// Builds a smoothed average that starts at zero.
|
||||
///
|
||||
/// `alpha` is clamped to `(0, 1]`; `NaN`, infinity and non-positive values
|
||||
/// fall back to the default 0.125 instead of silently disabling the
|
||||
/// smoothing or producing a non-finite baseline.
|
||||
#[must_use]
|
||||
pub fn new(alpha: f64) -> Self {
|
||||
Self {
|
||||
value: 0.0,
|
||||
last: Instant::now(),
|
||||
alpha,
|
||||
alpha: sanitize_alpha(alpha),
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds `sample` into the average, following the formula in the type
|
||||
/// documentation.
|
||||
///
|
||||
/// Non-finite samples are ignored (the update timestamp is not advanced
|
||||
/// either), so one broken counter reading cannot poison the baseline.
|
||||
pub fn update(&mut self, sample: f64) {
|
||||
if !sample.is_finite() {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let elapsed = now.duration_since(self.last).as_secs_f64();
|
||||
let steps = elapsed.max(1.0);
|
||||
let steps = now.duration_since(self.last).as_secs_f64().max(1.0);
|
||||
let weight = (1.0 - self.alpha).powf(steps);
|
||||
self.value = self.value * weight + sample * (1.0 - weight);
|
||||
self.last = now;
|
||||
}
|
||||
|
||||
/// Replaces the average with `value` and restarts the step timer.
|
||||
///
|
||||
/// Used to prime a baseline from the first observed window instead of
|
||||
/// climbing from zero, which would otherwise read as an anomaly.
|
||||
pub fn seed(&mut self, value: f64) {
|
||||
if !value.is_finite() {
|
||||
return;
|
||||
}
|
||||
self.value = value;
|
||||
self.last = Instant::now();
|
||||
}
|
||||
|
||||
/// Current smoothed value.
|
||||
#[must_use]
|
||||
pub fn value(&self) -> f64 {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ewma_initial() {
|
||||
let ewma = Ewma::new(0.125);
|
||||
assert_eq!(ewma.value(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ewma_update() {
|
||||
let mut ewma = Ewma::new(1.0);
|
||||
ewma.update(100.0);
|
||||
assert!((ewma.value() - 100.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ewma_convergence() {
|
||||
let mut ewma = Ewma::new(0.5);
|
||||
for _ in 0..10 {
|
||||
ewma.update(50.0);
|
||||
}
|
||||
assert!((ewma.value() - 50.0).abs() < 1.0);
|
||||
fn sanitize_alpha(alpha: f64) -> f64 {
|
||||
if alpha.is_finite() && alpha > 0.0 {
|
||||
alpha.min(1.0)
|
||||
} else {
|
||||
DEFAULT_ALPHA
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,79 @@
|
|||
use dashmap::DashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
//! Per-source reputation with time decay and idle-TTL eviction.
|
||||
//!
|
||||
//! A source starts neutral (`0`); [`IpReputation::record_bad`] subtracts ten
|
||||
//! points and [`IpReputation::record_good`] adds one, clamped to `[-100, 100]`.
|
||||
//! Scores decay toward neutral on read (half of the magnitude per thirty
|
||||
//! minutes of inactivity), so one old success cannot keep a source trusted
|
||||
//! forever and one old failure cannot keep it toxic.
|
||||
//!
|
||||
//! State lives in sixty-four locked shards. [`IpReputation::sweep`] visits
|
||||
//! eight of them per call and drops entries idle for longer than ten minutes;
|
||||
//! recording advances one step per minute, so the table is reclaimed without
|
||||
//! an external scheduler and no full-map `retain`.
|
||||
//!
|
||||
//! [`IpReputation::offenders_below`] returns at most 64 of the worst sources,
|
||||
//! so one escalation cannot flood the ban list or the log.
|
||||
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{BinaryHeap, HashMap};
|
||||
use std::hash::BuildHasher;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Idle age after which a source is forgotten.
|
||||
const IDLE_TTL: Duration = Duration::from_secs(600);
|
||||
/// Time after which a dead source's score is halved.
|
||||
const DECAY_HALF_LIFE: Duration = Duration::from_secs(1800);
|
||||
/// Minimum interval between two automatic sweep steps.
|
||||
const SWEEP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
/// Number of independently locked score shards.
|
||||
const SHARDS: usize = 64;
|
||||
/// Shards examined by one [`IpReputation::sweep`] call.
|
||||
const SWEEP_SHARDS_PER_TICK: usize = 8;
|
||||
/// Upper bound of a single offender batch.
|
||||
const MAX_OFFENDERS_PER_CYCLE: usize = 64;
|
||||
const GOOD_STEP: i32 = 1;
|
||||
const BAD_STEP: i32 = -10;
|
||||
const MAX_SCORE: i32 = 100;
|
||||
const MIN_SCORE: i32 = -100;
|
||||
|
||||
/// Tunables of [`IpReputation`].
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ReputationPolicy {
|
||||
/// Idle age after which a source is forgotten.
|
||||
pub idle_ttl: Duration,
|
||||
/// Time after which a dead source's score is halved.
|
||||
pub decay_half_life: Duration,
|
||||
/// Upper bound of a single [`IpReputation::offenders_below`] batch.
|
||||
pub max_offenders: usize,
|
||||
}
|
||||
|
||||
impl Default for ReputationPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
idle_ttl: IDLE_TTL,
|
||||
decay_half_life: DECAY_HALF_LIFE,
|
||||
max_offenders: MAX_OFFENDERS_PER_CYCLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reputation entry: the raw score and when it was last touched.
|
||||
struct Entry {
|
||||
score: i32,
|
||||
last_update: Instant,
|
||||
}
|
||||
|
||||
/// Reputation scores of the sources seen by the edge node.
|
||||
pub struct IpReputation {
|
||||
scores: Arc<DashMap<IpAddr, i32>>,
|
||||
shards: Box<[Mutex<HashMap<IpAddr, Entry>>]>,
|
||||
hasher: RandomState,
|
||||
policy: ReputationPolicy,
|
||||
epoch: Instant,
|
||||
last_sweep: AtomicU64,
|
||||
sweep_cursor: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Default for IpReputation {
|
||||
|
|
@ -13,129 +83,166 @@ impl Default for IpReputation {
|
|||
}
|
||||
|
||||
impl IpReputation {
|
||||
/// Builds a reputation table with the production policy.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::with_policy(ReputationPolicy::default())
|
||||
}
|
||||
|
||||
/// Builds a reputation table with an explicit policy.
|
||||
pub fn with_policy(policy: ReputationPolicy) -> Self {
|
||||
Self {
|
||||
scores: Arc::new(DashMap::new()),
|
||||
shards: (0..SHARDS).map(|_| Mutex::new(HashMap::new())).collect(),
|
||||
hasher: RandomState::new(),
|
||||
policy,
|
||||
epoch: Instant::now(),
|
||||
last_sweep: AtomicU64::new(0),
|
||||
sweep_cursor: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a successful connection.
|
||||
pub fn record_good(&self, ip: IpAddr) {
|
||||
let mut entry = self.scores.entry(ip).or_insert(0);
|
||||
*entry = (*entry + 1).min(100);
|
||||
self.sweep_if_due();
|
||||
self.adjust(ip, GOOD_STEP);
|
||||
}
|
||||
|
||||
/// Records a failed or abusive connection.
|
||||
pub fn record_bad(&self, ip: IpAddr) {
|
||||
let mut entry = self.scores.entry(ip).or_insert(0);
|
||||
*entry = (*entry - 10).max(-100);
|
||||
self.sweep_if_due();
|
||||
self.adjust(ip, BAD_STEP);
|
||||
}
|
||||
|
||||
/// Current decayed score of `ip`; `0` for unknown or idle sources.
|
||||
pub fn score(&self, ip: IpAddr) -> i32 {
|
||||
self.scores.get(&ip).map(|v| *v).unwrap_or(0)
|
||||
let now = Instant::now();
|
||||
let index = self.shard_index(ip);
|
||||
let shard = self.lock(index);
|
||||
let Some(entry) = shard.get(&ip) else { return 0 };
|
||||
let idle = now.duration_since(entry.last_update);
|
||||
if idle > self.policy.idle_ttl {
|
||||
return 0;
|
||||
}
|
||||
decayed_score(entry.score, idle, self.policy.decay_half_life)
|
||||
}
|
||||
|
||||
/// Returns the sources scored at or below `threshold` (the offenders).
|
||||
/// Returns up to [`ReputationPolicy::max_offenders`] of the worst sources
|
||||
/// scored at or below `threshold`.
|
||||
///
|
||||
/// The result is a snapshot copy, so it is safe to ban from it while other
|
||||
/// threads keep recording events.
|
||||
/// The snapshot is safe to ban from while other threads keep recording
|
||||
/// events. When more offenders exist than the batch cap, exactly one
|
||||
/// aggregated warning carries the total count.
|
||||
pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
|
||||
self.scores
|
||||
.iter()
|
||||
.filter(|entry| *entry.value() <= threshold)
|
||||
.map(|entry| *entry.key())
|
||||
.collect()
|
||||
let now = Instant::now();
|
||||
let limit = self.policy.max_offenders;
|
||||
let mut worst: BinaryHeap<(i32, IpAddr)> = BinaryHeap::new();
|
||||
let mut found = 0usize;
|
||||
for index in 0..self.shards.len() {
|
||||
let shard = self.lock(index);
|
||||
for (ip, entry) in shard.iter() {
|
||||
let idle = now.duration_since(entry.last_update);
|
||||
if idle > self.policy.idle_ttl {
|
||||
continue;
|
||||
}
|
||||
let score = decayed_score(entry.score, idle, self.policy.decay_half_life);
|
||||
if score > threshold {
|
||||
continue;
|
||||
}
|
||||
found += 1;
|
||||
worst.push((score, *ip));
|
||||
if worst.len() > limit {
|
||||
worst.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
let offenders: Vec<IpAddr> = worst.into_iter().map(|(_, ip)| ip).collect();
|
||||
if found > offenders.len() {
|
||||
tracing::warn!(
|
||||
found,
|
||||
returned = offenders.len(),
|
||||
"reputation offender batch truncated for this cycle"
|
||||
);
|
||||
}
|
||||
offenders
|
||||
}
|
||||
|
||||
/// Whether the source is above the trusted score.
|
||||
pub fn is_trusted(&self, ip: IpAddr) -> bool {
|
||||
self.score(ip) > 50
|
||||
}
|
||||
|
||||
/// Number of live entries.
|
||||
pub fn len(&self) -> usize {
|
||||
(0..self.shards.len()).map(|index| self.lock(index).len()).sum()
|
||||
}
|
||||
|
||||
/// Whether the table is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// Evicts idle entries from the next shard slice; returns the count.
|
||||
pub fn sweep(&self) -> usize {
|
||||
let now = Instant::now();
|
||||
let shard_count = self.shards.len();
|
||||
let start = self.sweep_cursor.fetch_add(SWEEP_SHARDS_PER_TICK, Ordering::Relaxed);
|
||||
let mut removed = 0;
|
||||
for offset in 0..SWEEP_SHARDS_PER_TICK.min(shard_count) {
|
||||
let index = (start + offset) % shard_count;
|
||||
let mut shard = self.lock(index);
|
||||
let before = shard.len();
|
||||
shard.retain(|_, entry| now.duration_since(entry.last_update) <= self.policy.idle_ttl);
|
||||
removed += before - shard.len();
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
fn adjust(&self, ip: IpAddr, delta: i32) {
|
||||
let now = Instant::now();
|
||||
let index = self.shard_index(ip);
|
||||
let mut shard = self.lock(index);
|
||||
let entry = shard.entry(ip).or_insert(Entry {
|
||||
score: 0,
|
||||
last_update: now,
|
||||
});
|
||||
let idle = now.duration_since(entry.last_update);
|
||||
let decayed = decayed_score(entry.score, idle, self.policy.decay_half_life);
|
||||
entry.score = (decayed + delta).clamp(MIN_SCORE, MAX_SCORE);
|
||||
entry.last_update = now;
|
||||
}
|
||||
|
||||
/// Advances one sweep step when [`SWEEP_INTERVAL`] has elapsed, so eviction
|
||||
/// does not depend on an external timer.
|
||||
fn sweep_if_due(&self) {
|
||||
let elapsed = self.epoch.elapsed().as_secs();
|
||||
let last = self.last_sweep.load(Ordering::Relaxed);
|
||||
if elapsed.saturating_sub(last) < SWEEP_INTERVAL.as_secs() {
|
||||
return;
|
||||
}
|
||||
let advanced = self
|
||||
.last_sweep
|
||||
.compare_exchange(last, elapsed, Ordering::AcqRel, Ordering::Relaxed);
|
||||
if advanced.is_ok() {
|
||||
self.sweep();
|
||||
}
|
||||
}
|
||||
|
||||
fn shard_index(&self, ip: IpAddr) -> usize {
|
||||
(self.hasher.hash_one(ip) as usize) % self.shards.len()
|
||||
}
|
||||
|
||||
fn lock(&self, index: usize) -> MutexGuard<'_, HashMap<IpAddr, Entry>> {
|
||||
// A poisoned shard still holds consistent scores; keep serving.
|
||||
self.shards[index].lock().unwrap_or_else(|poison| poison.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
fn v4(octets: [u8; 4]) -> IpAddr {
|
||||
IpAddr::V4(Ipv4Addr::from(octets))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_initial_score() {
|
||||
let rep = IpReputation::new();
|
||||
assert_eq!(rep.score(v4([192, 168, 1, 1])), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_good() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = v4([10, 0, 0, 1]);
|
||||
rep.record_good(ip);
|
||||
assert_eq!(rep.score(ip), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_bad() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = v4([10, 0, 0, 2]);
|
||||
rep.record_bad(ip);
|
||||
assert_eq!(rep.score(ip), -10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_cap_positive() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = v4([10, 0, 0, 3]);
|
||||
for _ in 0..200 {
|
||||
rep.record_good(ip);
|
||||
}
|
||||
assert_eq!(rep.score(ip), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_cap_negative() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = v4([10, 0, 0, 4]);
|
||||
for _ in 0..20 {
|
||||
rep.record_bad(ip);
|
||||
}
|
||||
assert_eq!(rep.score(ip), -100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_trusted() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = v4([10, 0, 0, 5]);
|
||||
assert!(!rep.is_trusted(ip));
|
||||
for _ in 0..51 {
|
||||
rep.record_good(ip);
|
||||
}
|
||||
assert!(rep.is_trusted(ip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reputation_v6() {
|
||||
let rep = IpReputation::new();
|
||||
let ip = IpAddr::V6(Ipv6Addr::LOCALHOST);
|
||||
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());
|
||||
fn decayed_score(score: i32, idle: Duration, half_life: Duration) -> i32 {
|
||||
if score == 0 || half_life.is_zero() {
|
||||
return 0;
|
||||
}
|
||||
let factor = 0.5f64.powf(idle.as_secs_f64() / half_life.as_secs_f64());
|
||||
// Rounding (instead of truncation) keeps an immediate second update from
|
||||
// decaying a score of `1` back to zero on the microsecond scale.
|
||||
(f64::from(score) * factor).round() as i32
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,17 +17,22 @@ pub struct PrefixKey {
|
|||
impl PrefixKey {
|
||||
/// Builds the prefix key for an address (v4 maps to /24 in the first four
|
||||
/// bytes, v6 maps to /64).
|
||||
///
|
||||
/// The address is normalised through [`prefix_of`] first, so an
|
||||
/// IPv4-mapped IPv6 source (`::ffff:a.b.c.d`) produces exactly the same key
|
||||
/// as the plain IPv4 address. XDP `prefix_stats` entries and the user-space
|
||||
/// tracker therefore agree on the bucket of a dual-stack client.
|
||||
#[must_use]
|
||||
pub fn new(ip: IpAddr) -> Self {
|
||||
let mut key = Self::default();
|
||||
match ip {
|
||||
match prefix_of(ip) {
|
||||
IpAddr::V4(v4) => {
|
||||
key.family = PREFIX_FAMILY_V4;
|
||||
key.addr[..4].copy_from_slice(&masked_v4(v4).octets());
|
||||
key.addr[..4].copy_from_slice(&v4.octets());
|
||||
},
|
||||
IpAddr::V6(v6) => {
|
||||
key.family = PREFIX_FAMILY_V6;
|
||||
key.addr.copy_from_slice(&masked_v6_segments(v6));
|
||||
key.addr.copy_from_slice(&v6.octets());
|
||||
},
|
||||
}
|
||||
key
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue