fix: never ban a trusted proxy network from any ban source
The gateway already refused to ban addresses from proxy_protocol.trusted_cidrs, but the traffic-intelligence auto-ban and the subnet monitor still did, so a trusted load balancer living inside a banned /24 (or below the reputation threshold) could be knocked out together with its clients. - TrustedProxyCidr moved to src/config/trusted.rs (the edge section file hit the 250-line gate) and gained `overlaps_prefix`: a ban is suppressed when the banned prefix intersects a trusted network. - TrafficHook::with_trusted suppresses reputation and offender bans; its ban() now reports whether the ban was installed so `ban_offenders` counts real bans. - The subnet monitor takes a MonitorSetup bundle (spawn had 8 arguments) and suppresses both userspace CIDR bans and XDP prefix bans that overlap a trusted network, logging a warning instead. - IPv4-mapped addresses are normalised in `contains` too. - Tests: overlap maths (v4/v6, /0 rejected), tracker suppression vs unrelated networks, and auto-ban skipping a trusted range while still banning public offenders.
This commit is contained in:
parent
72c1f45d62
commit
bcae8901c6
11 changed files with 300 additions and 106 deletions
7
TODO.md
7
TODO.md
|
|
@ -287,9 +287,10 @@ module-size, secrets, `cargo deny`, rustdoc без warning'ов, clang+verifier,
|
||||||
|
|
||||||
### Осталось
|
### Осталось
|
||||||
|
|
||||||
- [ ] Monitor (`add_cidr`) и `traffic/hook` autoban не сверяются с `trusted_cidrs`: если
|
- [x] Monitor (`add_cidr`) и `traffic/hook` autoban сверяются с `trusted_cidrs`: бан
|
||||||
доверенный прокси физически живёт в банимой подсети, его адрес может попасть под
|
подавляется, если префикс пересекается с доверенной сетью (`TrustedProxyCidr::overlaps_prefix`),
|
||||||
префиксный бан. Нужна общая проверка перед любым баном.
|
о чём пишется warn. Тесты: `tests/subnet_detection.rs`, `tests/traffic_intel.rs`,
|
||||||
|
`tests/proxy_identity.rs`.
|
||||||
|
|
||||||
### Сделано в этом раунде
|
### Сделано в этом раунде
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -64,12 +64,15 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
||||||
let blacklist = Arc::new(Blacklist::new());
|
let blacklist = Arc::new(Blacklist::new());
|
||||||
let reputation = Arc::new(IpReputation::new());
|
let reputation = Arc::new(IpReputation::new());
|
||||||
let detector = Arc::new(Mutex::new(AttackDetector::new()));
|
let detector = Arc::new(Mutex::new(AttackDetector::new()));
|
||||||
let hook = Arc::new(TrafficHook::new(
|
let hook = Arc::new(
|
||||||
reputation.clone(),
|
TrafficHook::new(
|
||||||
blacklist.clone(),
|
reputation.clone(),
|
||||||
config.detect.autoban.clone(),
|
blacklist.clone(),
|
||||||
config.ban.ban_duration_secs,
|
config.detect.autoban.clone(),
|
||||||
));
|
config.ban.ban_duration_secs,
|
||||||
|
)
|
||||||
|
.with_trusted(config.proxy_protocol.trusted_cidrs.clone()),
|
||||||
|
);
|
||||||
let alert_dispatcher = AlertDispatcher::new();
|
let alert_dispatcher = AlertDispatcher::new();
|
||||||
let webhook_url = config.detect.alert.webhook_url.clone();
|
let webhook_url = config.detect.alert.webhook_url.clone();
|
||||||
let allowed_1s = Arc::new(AtomicU64::new(0));
|
let allowed_1s = Arc::new(AtomicU64::new(0));
|
||||||
|
|
@ -132,11 +135,14 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
||||||
let subnet_tracker = start_subnet_tracker(&config);
|
let subnet_tracker = start_subnet_tracker(&config);
|
||||||
monitor::spawn(
|
monitor::spawn(
|
||||||
&config.detect.prefix,
|
&config.detect.prefix,
|
||||||
Duration::from_secs(config.ban.ban_duration_secs),
|
monitor::MonitorSetup {
|
||||||
blacklist.clone(),
|
ban_ttl: Duration::from_secs(config.ban.ban_duration_secs),
|
||||||
!config.proxy_protocol.ingress_enabled,
|
blacklist: blacklist.clone(),
|
||||||
subnet_tracker.clone(),
|
trusted_peer: !config.proxy_protocol.ingress_enabled,
|
||||||
xdp_filter.clone(),
|
trusted_networks: config.proxy_protocol.trusted_cidrs.clone(),
|
||||||
|
tracker: subnet_tracker.clone(),
|
||||||
|
xdp: xdp_filter.clone(),
|
||||||
|
},
|
||||||
shutdown_rx.clone(),
|
shutdown_rx.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
//! Owns the [`Config`] root type, its serde defaults and the semantic validation
|
//! Owns the [`Config`] root type, its serde defaults and the semantic validation
|
||||||
//! that runs before the daemon binds a socket.
|
//! that runs before the daemon binds a socket.
|
||||||
mod sections;
|
mod sections;
|
||||||
|
mod trusted;
|
||||||
|
|
||||||
#[cfg(feature = "protocol-http")]
|
#[cfg(feature = "protocol-http")]
|
||||||
pub use sections::HttpProtocolConfig;
|
pub use sections::HttpProtocolConfig;
|
||||||
|
|
@ -12,9 +13,9 @@ pub use sections::MinecraftProtocolConfig;
|
||||||
pub use sections::ProtocolConfig;
|
pub use sections::ProtocolConfig;
|
||||||
pub use sections::{
|
pub use sections::{
|
||||||
BackendConfig, BanConfig, BindConfig, DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig,
|
BackendConfig, BanConfig, BindConfig, DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig,
|
||||||
LimitsConfig, LoggingConfig, MetricsConfig, PowConfig, ProxyProtocolConfig, StoreConfig, TrustedProxyCidr,
|
LimitsConfig, LoggingConfig, MetricsConfig, PowConfig, ProxyProtocolConfig, StoreConfig, WorkerConfig, XdpConfig,
|
||||||
WorkerConfig, XdpConfig,
|
|
||||||
};
|
};
|
||||||
|
pub use trusted::TrustedProxyCidr;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
|
//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
|
||||||
|
|
||||||
|
use crate::config::trusted::TrustedProxyCidr;
|
||||||
use serde::{Deserialize, Deserializer};
|
use serde::{Deserialize, Deserializer};
|
||||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
/// `[bind]` section: listen address and port of the edge node.
|
/// `[bind]` section: listen address and port of the edge node.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
|
@ -159,66 +158,6 @@ fn default_pow_difficulty() -> u8 {
|
||||||
4
|
4
|
||||||
}
|
}
|
||||||
|
|
||||||
/// CIDR network allowed to send inbound PROXY protocol headers.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct TrustedProxyCidr {
|
|
||||||
network: IpAddr,
|
|
||||||
prefix_len: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TrustedProxyCidr {
|
|
||||||
/// Returns whether `ip` belongs to this network.
|
|
||||||
#[must_use]
|
|
||||||
pub fn contains(&self, ip: IpAddr) -> bool {
|
|
||||||
// Masks are family-specific: a prefix above 32 would underflow the v4 shift.
|
|
||||||
let prefix = self.prefix_len;
|
|
||||||
match (self.network, ip) {
|
|
||||||
(IpAddr::V4(net), IpAddr::V4(ip)) => u32::from(net) & mask_v4(prefix) == u32::from(ip) & mask_v4(prefix),
|
|
||||||
(IpAddr::V6(net), IpAddr::V6(ip)) => u128::from(net) & mask_v6(prefix) == u128::from(ip) & mask_v6(prefix),
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromStr for TrustedProxyCidr {
|
|
||||||
type Err = String;
|
|
||||||
|
|
||||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
|
||||||
let (address, prefix) = value.split_once('/').map_or((value, None), |(a, p)| (a, Some(p)));
|
|
||||||
let network = IpAddr::from_str(address).map_err(|_| format!("invalid trusted proxy CIDR: {value}"))?;
|
|
||||||
let max_prefix = if network.is_ipv4() { 32 } else { 128 };
|
|
||||||
let prefix_len = prefix
|
|
||||||
.map_or(Ok(max_prefix), |prefix| prefix.parse::<u8>())
|
|
||||||
.map_err(|_| format!("invalid trusted proxy CIDR prefix: {value}"))?;
|
|
||||||
if prefix_len > max_prefix {
|
|
||||||
return Err(format!("trusted proxy CIDR prefix is too large: {value}"));
|
|
||||||
}
|
|
||||||
let network = match network {
|
|
||||||
IpAddr::V4(ip) => IpAddr::V4(Ipv4Addr::from(u32::from(ip) & mask_v4(prefix_len))),
|
|
||||||
IpAddr::V6(ip) => IpAddr::V6(Ipv6Addr::from(u128::from(ip) & mask_v6(prefix_len))),
|
|
||||||
};
|
|
||||||
Ok(Self { network, prefix_len })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for TrustedProxyCidr {
|
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
||||||
where
|
|
||||||
D: Deserializer<'de>,
|
|
||||||
{
|
|
||||||
let value = String::deserialize(deserializer)?;
|
|
||||||
value.parse().map_err(serde::de::Error::custom)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mask_v4(prefix: u8) -> u32 {
|
|
||||||
if prefix == 0 { 0 } else { u32::MAX << (32 - prefix) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mask_v6(prefix: u8) -> u128 {
|
|
||||||
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
|
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct ProxyProtocolConfig {
|
pub struct ProxyProtocolConfig {
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,5 @@ pub use detect::MinecraftProtocolConfig;
|
||||||
#[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))]
|
#[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))]
|
||||||
pub use detect::ProtocolConfig;
|
pub use detect::ProtocolConfig;
|
||||||
pub use detect::{DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig};
|
pub use detect::{DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig};
|
||||||
pub use edge::{
|
pub use edge::{BackendConfig, BanConfig, BindConfig, LimitsConfig, PowConfig, ProxyProtocolConfig, WorkerConfig};
|
||||||
BackendConfig, BanConfig, BindConfig, LimitsConfig, PowConfig, ProxyProtocolConfig, TrustedProxyCidr, WorkerConfig,
|
|
||||||
};
|
|
||||||
pub use platform::{LoggingConfig, MetricsConfig, StoreConfig, XdpConfig};
|
pub use platform::{LoggingConfig, MetricsConfig, StoreConfig, XdpConfig};
|
||||||
|
|
|
||||||
108
src/config/trusted.rs
Normal file
108
src/config/trusted.rs
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
//! Trusted PROXY-protocol networks and CIDR helpers shared by the edge paths.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Deserializer};
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// CIDR network allowed to send inbound PROXY protocol headers.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct TrustedProxyCidr {
|
||||||
|
network: IpAddr,
|
||||||
|
prefix_len: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrustedProxyCidr {
|
||||||
|
/// Returns whether `ip` belongs to this network.
|
||||||
|
#[must_use]
|
||||||
|
pub fn contains(&self, ip: IpAddr) -> bool {
|
||||||
|
// Masks are family-specific: a prefix above 32 would underflow the v4 shift.
|
||||||
|
let prefix = self.prefix_len;
|
||||||
|
match (self.network, normalize(ip)) {
|
||||||
|
(IpAddr::V4(net), IpAddr::V4(ip)) => u32::from(net) & mask_v4(prefix) == u32::from(ip) & mask_v4(prefix),
|
||||||
|
(IpAddr::V6(net), IpAddr::V6(ip)) => u128::from(net) & mask_v6(prefix) == u128::from(ip) & mask_v6(prefix),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns whether `ip/prefix_len` intersects this network.
|
||||||
|
///
|
||||||
|
/// Used before banning a prefix: a ban covering a trusted proxy address
|
||||||
|
/// would punish the proxy and every client behind it.
|
||||||
|
#[must_use]
|
||||||
|
pub fn overlaps_prefix(&self, ip: IpAddr, prefix_len: u8) -> bool {
|
||||||
|
match (self.network, normalize(ip)) {
|
||||||
|
(IpAddr::V4(net), IpAddr::V4(other)) => {
|
||||||
|
if prefix_len == 0 || prefix_len > 32 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let net_mask = mask_v4(self.prefix_len);
|
||||||
|
let other_mask = mask_v4(prefix_len);
|
||||||
|
let net_start = u32::from(net) & net_mask;
|
||||||
|
let net_end = net_start | !net_mask;
|
||||||
|
let other_start = u32::from(other) & other_mask;
|
||||||
|
let other_end = other_start | !other_mask;
|
||||||
|
net_start <= other_end && other_start <= net_end
|
||||||
|
},
|
||||||
|
(IpAddr::V6(net), IpAddr::V6(other)) => {
|
||||||
|
if prefix_len == 0 || prefix_len > 128 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let net_mask = mask_v6(self.prefix_len);
|
||||||
|
let other_mask = mask_v6(prefix_len);
|
||||||
|
let net_start = u128::from(net) & net_mask;
|
||||||
|
let net_end = net_start | !net_mask;
|
||||||
|
let other_start = u128::from(other) & other_mask;
|
||||||
|
let other_end = other_start | !other_mask;
|
||||||
|
net_start <= other_end && other_start <= net_end
|
||||||
|
},
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for TrustedProxyCidr {
|
||||||
|
type Err = String;
|
||||||
|
|
||||||
|
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||||
|
let (address, prefix) = value.split_once('/').map_or((value, None), |(a, p)| (a, Some(p)));
|
||||||
|
let network = IpAddr::from_str(address).map_err(|_| format!("invalid trusted proxy CIDR: {value}"))?;
|
||||||
|
let max_prefix = if network.is_ipv4() { 32 } else { 128 };
|
||||||
|
let prefix_len = prefix
|
||||||
|
.map_or(Ok(max_prefix), |prefix| prefix.parse::<u8>())
|
||||||
|
.map_err(|_| format!("invalid trusted proxy CIDR prefix: {value}"))?;
|
||||||
|
if prefix_len > max_prefix {
|
||||||
|
return Err(format!("trusted proxy CIDR prefix is too large: {value}"));
|
||||||
|
}
|
||||||
|
let network = match network {
|
||||||
|
IpAddr::V4(ip) => IpAddr::V4(Ipv4Addr::from(u32::from(ip) & mask_v4(prefix_len))),
|
||||||
|
IpAddr::V6(ip) => IpAddr::V6(Ipv6Addr::from(u128::from(ip) & mask_v6(prefix_len))),
|
||||||
|
};
|
||||||
|
Ok(Self { network, prefix_len })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for TrustedProxyCidr {
|
||||||
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let value = String::deserialize(deserializer)?;
|
||||||
|
value.parse().map_err(serde::de::Error::custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collapses IPv4-mapped IPv6 addresses to IPv4.
|
||||||
|
fn normalize(ip: IpAddr) -> IpAddr {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
|
||||||
|
IpAddr::V4(_) => ip,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mask_v4(prefix: u8) -> u32 {
|
||||||
|
if prefix == 0 { 0 } else { u32::MAX << (32 - prefix) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mask_v6(prefix: u8) -> u128 {
|
||||||
|
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
|
||||||
|
}
|
||||||
|
|
@ -38,6 +38,9 @@ struct BanPolicy {
|
||||||
blacklist: Arc<Blacklist>,
|
blacklist: Arc<Blacklist>,
|
||||||
ttl: Duration,
|
ttl: Duration,
|
||||||
trusted: bool,
|
trusted: bool,
|
||||||
|
/// Trusted PROXY-protocol networks; a prefix ban overlapping one of them is
|
||||||
|
/// suppressed, because it would punish the proxy and every client behind it.
|
||||||
|
trusted_networks: Vec<crate::config::TrustedProxyCidr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns the background subnet monitor when `[detect.prefix] enabled`.
|
/// Spawns the background subnet monitor when `[detect.prefix] enabled`.
|
||||||
|
|
@ -46,22 +49,37 @@ struct BanPolicy {
|
||||||
/// aggregator. Without either source the monitor stays disabled and logs a
|
/// aggregator. Without either source the monitor stays disabled and logs a
|
||||||
/// warning.
|
/// warning.
|
||||||
///
|
///
|
||||||
/// `ban_ttl` comes from `[ban].ban_duration_secs`. `trusted_peer` is false when
|
/// Everything the monitor task needs besides the detection config.
|
||||||
/// the observed address comes from an unverified ingress path (inbound PROXY
|
pub struct MonitorSetup {
|
||||||
/// protocol), where banning it could punish the transport proxy instead of the
|
/// Ban lifetime, from `[ban].ban_duration_secs`.
|
||||||
/// real client.
|
pub ban_ttl: Duration,
|
||||||
pub fn spawn(
|
/// Shared ban table.
|
||||||
detect: &DetectPrefixConfig,
|
pub blacklist: Arc<Blacklist>,
|
||||||
ban_ttl: Duration,
|
/// False when the observed address comes from an unverified ingress path
|
||||||
blacklist: Arc<Blacklist>,
|
/// (inbound PROXY protocol), where banning it could punish the transport
|
||||||
trusted_peer: bool,
|
/// proxy instead of the real client.
|
||||||
tracker: Option<Arc<SubnetTracker>>,
|
pub trusted_peer: bool,
|
||||||
xdp: Option<Arc<Mutex<XdpFilter>>>,
|
/// Trusted proxy networks; a prefix ban overlapping one is suppressed.
|
||||||
mut shutdown: watch::Receiver<bool>,
|
pub trusted_networks: Vec<crate::config::TrustedProxyCidr>,
|
||||||
) {
|
/// Userspace aggregator, used when XDP is not available.
|
||||||
|
pub tracker: Option<Arc<SubnetTracker>>,
|
||||||
|
/// Loaded XDP filter, preferred over the userspace tracker when present.
|
||||||
|
pub xdp: Option<Arc<Mutex<XdpFilter>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawns the background subnet monitor when `[detect.prefix] enabled`.
|
||||||
|
pub fn spawn(detect: &DetectPrefixConfig, setup: MonitorSetup, mut shutdown: watch::Receiver<bool>) {
|
||||||
if !detect.enabled {
|
if !detect.enabled {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
let MonitorSetup {
|
||||||
|
ban_ttl,
|
||||||
|
blacklist,
|
||||||
|
trusted_peer,
|
||||||
|
trusted_networks,
|
||||||
|
tracker,
|
||||||
|
xdp,
|
||||||
|
} = setup;
|
||||||
let Some(source) = build_source(tracker, xdp) else {
|
let Some(source) = build_source(tracker, xdp) else {
|
||||||
tracing::warn!("detect.prefix enabled but no stats source available; monitor disabled");
|
tracing::warn!("detect.prefix enabled but no stats source available; monitor disabled");
|
||||||
return;
|
return;
|
||||||
|
|
@ -72,6 +90,7 @@ pub fn spawn(
|
||||||
blacklist,
|
blacklist,
|
||||||
ttl: ban_ttl,
|
ttl: ban_ttl,
|
||||||
trusted: trusted_peer,
|
trusted: trusted_peer,
|
||||||
|
trusted_networks,
|
||||||
};
|
};
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
|
@ -124,7 +143,7 @@ fn apply_verdicts(verdicts: &[PrefixVerdict], source: &Source, policy: &BanPolic
|
||||||
}
|
}
|
||||||
match source {
|
match source {
|
||||||
#[cfg(feature = "xdp")]
|
#[cfg(feature = "xdp")]
|
||||||
Source::Xdp(xdp) if policy.trusted => ban_xdp_verdicts(xdp, verdicts, policy.ttl),
|
Source::Xdp(xdp) if policy.trusted => ban_xdp_verdicts(xdp, verdicts, policy.ttl, &policy.trusted_networks),
|
||||||
#[cfg(feature = "xdp")]
|
#[cfg(feature = "xdp")]
|
||||||
Source::Xdp(_) => {
|
Source::Xdp(_) => {
|
||||||
if verdicts.iter().any(|pv| pv.verdict == SubnetVerdict::Block) {
|
if verdicts.iter().any(|pv| pv.verdict == SubnetVerdict::Block) {
|
||||||
|
|
@ -132,7 +151,13 @@ fn apply_verdicts(verdicts: &[PrefixVerdict], source: &Source, policy: &BanPolic
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Source::Tracker(_) => {
|
Source::Tracker(_) => {
|
||||||
enforce_tracker_verdicts(verdicts, &policy.blacklist, policy.ttl, policy.trusted);
|
enforce_tracker_verdicts(
|
||||||
|
verdicts,
|
||||||
|
&policy.blacklist,
|
||||||
|
policy.ttl,
|
||||||
|
policy.trusted,
|
||||||
|
&policy.trusted_networks,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -150,6 +175,7 @@ pub fn enforce_tracker_verdicts(
|
||||||
blacklist: &Blacklist,
|
blacklist: &Blacklist,
|
||||||
ttl: Duration,
|
ttl: Duration,
|
||||||
trusted: bool,
|
trusted: bool,
|
||||||
|
trusted_networks: &[crate::config::TrustedProxyCidr],
|
||||||
) -> usize {
|
) -> usize {
|
||||||
let mut banned = 0;
|
let mut banned = 0;
|
||||||
for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) {
|
for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) {
|
||||||
|
|
@ -160,6 +186,16 @@ pub fn enforce_tracker_verdicts(
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if trusted_networks
|
||||||
|
.iter()
|
||||||
|
.any(|net| net.overlaps_prefix(pv.prefix, prefix_len(pv.prefix)))
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
prefix = %pv.prefix,
|
||||||
|
"subnet ban suppressed: the prefix contains a trusted proxy network"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
blacklist.add_cidr(pv.prefix, prefix_len(pv.prefix), ttl, "subnet_attack");
|
blacklist.add_cidr(pv.prefix, prefix_len(pv.prefix), ttl, "subnet_attack");
|
||||||
banned += 1;
|
banned += 1;
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
|
|
@ -172,8 +208,21 @@ pub fn enforce_tracker_verdicts(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "xdp")]
|
#[cfg(feature = "xdp")]
|
||||||
fn ban_xdp_verdicts(xdp: &XdpPrefixStats, verdicts: &[PrefixVerdict], ttl: Duration) {
|
fn ban_xdp_verdicts(
|
||||||
|
xdp: &XdpPrefixStats,
|
||||||
|
verdicts: &[PrefixVerdict],
|
||||||
|
ttl: Duration,
|
||||||
|
trusted_networks: &[crate::config::TrustedProxyCidr],
|
||||||
|
) {
|
||||||
for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) {
|
for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) {
|
||||||
|
let len = prefix_len(pv.prefix);
|
||||||
|
if trusted_networks.iter().any(|net| net.overlaps_prefix(pv.prefix, len)) {
|
||||||
|
tracing::warn!(
|
||||||
|
prefix = %pv.prefix,
|
||||||
|
"subnet kernel ban suppressed: the prefix contains a trusted proxy network"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let result = {
|
let result = {
|
||||||
let guard = xdp.filter_lock();
|
let guard = xdp.filter_lock();
|
||||||
guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), ttl.as_secs())
|
guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), ttl.as_secs())
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,8 @@ pub struct TrafficHook {
|
||||||
autoban: DetectAutobanConfig,
|
autoban: DetectAutobanConfig,
|
||||||
ban_ttl_secs: u64,
|
ban_ttl_secs: u64,
|
||||||
conn_window: AtomicU64,
|
conn_window: AtomicU64,
|
||||||
|
/// Trusted PROXY-protocol networks; addresses inside them are never banned.
|
||||||
|
trusted: Vec<crate::config::TrustedProxyCidr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TrafficHook {
|
impl TrafficHook {
|
||||||
|
|
@ -40,9 +42,17 @@ impl TrafficHook {
|
||||||
autoban,
|
autoban,
|
||||||
ban_ttl_secs,
|
ban_ttl_secs,
|
||||||
conn_window: AtomicU64::new(0),
|
conn_window: AtomicU64::new(0),
|
||||||
|
trusted: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Marks the networks whose addresses must never be banned (trusted proxies).
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_trusted(mut self, trusted: Vec<crate::config::TrustedProxyCidr>) -> Self {
|
||||||
|
self.trusted = trusted;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// A new connection was accepted by the accept loop.
|
/// A new connection was accepted by the accept loop.
|
||||||
///
|
///
|
||||||
/// Only bumps the cps window counter; the counter is drained by
|
/// Only bumps the cps window counter; the counter is drained by
|
||||||
|
|
@ -76,8 +86,9 @@ impl TrafficHook {
|
||||||
if self.blacklist.is_blocked(ip) {
|
if self.blacklist.is_blocked(ip) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
self.ban(ip, BAN_REASON_ATTACK);
|
if self.ban(ip, BAN_REASON_ATTACK) {
|
||||||
banned += 1;
|
banned += 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
banned
|
banned
|
||||||
}
|
}
|
||||||
|
|
@ -91,12 +102,21 @@ impl TrafficHook {
|
||||||
if self.reputation.score(ip) > self.autoban.reputation_threshold {
|
if self.reputation.score(ip) > self.autoban.reputation_threshold {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.ban(ip, reason);
|
let _ = self.ban(ip, reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ban(&self, ip: IpAddr, reason: &str) {
|
/// Bans `ip` unless it belongs to a trusted proxy network.
|
||||||
|
///
|
||||||
|
/// Returns whether the ban was actually installed.
|
||||||
|
fn ban(&self, ip: IpAddr, reason: &str) -> bool {
|
||||||
|
let host_prefix = if ip.is_ipv4() { 32 } else { 128 };
|
||||||
|
if self.trusted.iter().any(|net| net.overlaps_prefix(ip, host_prefix)) {
|
||||||
|
tracing::warn!(%ip, reason, "auto-ban suppressed: address belongs to a trusted proxy network");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
self.blacklist.add(ip, Duration::from_secs(self.ban_ttl_secs), reason);
|
self.blacklist.add(ip, Duration::from_secs(self.ban_ttl_secs), reason);
|
||||||
metrics::AUTO_BANS_TOTAL.with_label_values(&[reason]).inc();
|
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");
|
tracing::warn!(%ip, reason, ttl_secs = self.ban_ttl_secs, "auto-ban issued by traffic intelligence");
|
||||||
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -237,3 +237,25 @@ async fn plain_connection_uses_the_transport_peer() {
|
||||||
let outcome = handle_plain(&gateway, peer).await;
|
let outcome = handle_plain(&gateway, peer).await;
|
||||||
assert_eq!(outcome.client_ip, Some(peer.ip()));
|
assert_eq!(outcome.client_ip, Some(peer.ip()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trusted_network_overlap_checks_prefix_intersection() {
|
||||||
|
let net: TrustedProxyCidr = "10.0.0.0/8".parse().expect("cidr");
|
||||||
|
assert!(net.overlaps_prefix("10.1.2.0".parse().expect("ip"), 24), "same range");
|
||||||
|
assert!(
|
||||||
|
net.overlaps_prefix("10.0.0.0".parse().expect("ip"), 7),
|
||||||
|
"wider prefix overlaps"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!net.overlaps_prefix("11.0.0.0".parse().expect("ip"), 8),
|
||||||
|
"sibling range"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!net.overlaps_prefix("10.0.0.0".parse().expect("ip"), 0),
|
||||||
|
"/0 is rejected"
|
||||||
|
);
|
||||||
|
|
||||||
|
let v6: TrustedProxyCidr = "fd00::/8".parse().expect("cidr");
|
||||||
|
assert!(v6.overlaps_prefix("fd12::".parse().expect("ip"), 16));
|
||||||
|
assert!(!v6.overlaps_prefix("2001:db8::".parse().expect("ip"), 32));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
//! Integration tests for subnet-level detection: tracker, detector and verdicts.
|
//! Integration tests for subnet-level detection: tracker, detector and verdicts.
|
||||||
|
|
||||||
use rampart::config::Config;
|
use rampart::config::{Config, TrustedProxyCidr};
|
||||||
use rampart::engine::subnet::monitor::enforce_tracker_verdicts;
|
use rampart::engine::subnet::monitor::enforce_tracker_verdicts;
|
||||||
use rampart::engine::subnet_tracker::SubnetTracker;
|
use rampart::engine::subnet_tracker::SubnetTracker;
|
||||||
use rampart::filter::blacklist::Blacklist;
|
use rampart::filter::blacklist::Blacklist;
|
||||||
|
|
@ -299,7 +299,7 @@ fn block_verdict(prefix: IpAddr) -> PrefixVerdict {
|
||||||
fn trusted_tracker_block_reaches_the_blacklist_with_the_configured_ttl() {
|
fn trusted_tracker_block_reaches_the_blacklist_with_the_configured_ttl() {
|
||||||
let blacklist = Blacklist::new();
|
let blacklist = Blacklist::new();
|
||||||
let verdicts = [block_verdict(v4([203, 0, 113, 0]))];
|
let verdicts = [block_verdict(v4([203, 0, 113, 0]))];
|
||||||
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true);
|
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true, &[]);
|
||||||
assert_eq!(banned, 1);
|
assert_eq!(banned, 1);
|
||||||
assert!(blacklist.is_blocked(v4([203, 0, 113, 0])));
|
assert!(blacklist.is_blocked(v4([203, 0, 113, 0])));
|
||||||
}
|
}
|
||||||
|
|
@ -308,7 +308,7 @@ fn trusted_tracker_block_reaches_the_blacklist_with_the_configured_ttl() {
|
||||||
fn untrusted_tracker_block_only_warns() {
|
fn untrusted_tracker_block_only_warns() {
|
||||||
let blacklist = Blacklist::new();
|
let blacklist = Blacklist::new();
|
||||||
let verdicts = [block_verdict(v4([198, 51, 100, 0]))];
|
let verdicts = [block_verdict(v4([198, 51, 100, 0]))];
|
||||||
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), false);
|
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), false, &[]);
|
||||||
assert_eq!(banned, 0);
|
assert_eq!(banned, 0);
|
||||||
assert!(blacklist.is_empty());
|
assert!(blacklist.is_empty());
|
||||||
}
|
}
|
||||||
|
|
@ -317,7 +317,7 @@ fn untrusted_tracker_block_only_warns() {
|
||||||
fn tracker_ban_uses_the_given_duration() {
|
fn tracker_ban_uses_the_given_duration() {
|
||||||
let blacklist = Blacklist::new();
|
let blacklist = Blacklist::new();
|
||||||
let verdicts = [block_verdict(v4([192, 0, 2, 0]))];
|
let verdicts = [block_verdict(v4([192, 0, 2, 0]))];
|
||||||
enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_millis(1), true);
|
enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_millis(1), true, &[]);
|
||||||
std::thread::sleep(Duration::from_millis(2));
|
std::thread::sleep(Duration::from_millis(2));
|
||||||
assert!(
|
assert!(
|
||||||
!blacklist.is_blocked(v4([192, 0, 2, 0])),
|
!blacklist.is_blocked(v4([192, 0, 2, 0])),
|
||||||
|
|
@ -331,7 +331,7 @@ fn non_block_verdicts_do_not_ban() {
|
||||||
let mut verdict = block_verdict(v4([203, 0, 113, 0]));
|
let mut verdict = block_verdict(v4([203, 0, 113, 0]));
|
||||||
verdict.verdict = SubnetVerdict::Challenge;
|
verdict.verdict = SubnetVerdict::Challenge;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
enforce_tracker_verdicts(&[verdict], &blacklist, Duration::from_secs(60), true),
|
enforce_tracker_verdicts(&[verdict], &blacklist, Duration::from_secs(60), true, &[]),
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
assert!(blacklist.is_empty());
|
assert!(blacklist.is_empty());
|
||||||
|
|
@ -375,3 +375,23 @@ fn prefix_key_normalises_ipv4_mapped_addresses() {
|
||||||
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(prefix_of(mapped)));
|
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(prefix_of(mapped)));
|
||||||
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(v4([1, 2, 3, 0])));
|
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(v4([1, 2, 3, 0])));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tracker_block_is_suppressed_when_a_trusted_proxy_lives_in_the_prefix() {
|
||||||
|
let blacklist = Blacklist::new();
|
||||||
|
let verdicts = [block_verdict(v4([10, 9, 0, 0]))];
|
||||||
|
let trusted: Vec<TrustedProxyCidr> = vec!["10.9.0.5/32".parse().expect("trusted cidr")];
|
||||||
|
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true, &trusted);
|
||||||
|
assert_eq!(banned, 0, "a ban covering a trusted proxy must be suppressed");
|
||||||
|
assert!(blacklist.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tracker_block_still_applies_when_trusted_networks_do_not_overlap() {
|
||||||
|
let blacklist = Blacklist::new();
|
||||||
|
let verdicts = [block_verdict(v4([10, 9, 0, 0]))];
|
||||||
|
let trusted: Vec<TrustedProxyCidr> = vec!["192.0.2.0/24".parse().expect("trusted cidr")];
|
||||||
|
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true, &trusted);
|
||||||
|
assert_eq!(banned, 1);
|
||||||
|
assert!(blacklist.is_blocked(v4([10, 9, 0, 7])));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -446,3 +446,33 @@ fn alerts_fire_only_on_state_transitions() {
|
||||||
assert!(alerts[0].message.contains("attack started"));
|
assert!(alerts[0].message.contains("attack started"));
|
||||||
assert!(alerts[1].message.contains("attack ended"));
|
assert!(alerts[1].message.contains("attack ended"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_ban_never_targets_a_trusted_proxy_network() {
|
||||||
|
let reputation = Arc::new(IpReputation::new());
|
||||||
|
let blacklist = Arc::new(Blacklist::new());
|
||||||
|
let trusted: Vec<rampart::config::TrustedProxyCidr> = vec!["10.0.0.0/8".parse().expect("trusted cidr")];
|
||||||
|
let hook =
|
||||||
|
TrafficHook::new(Arc::clone(&reputation), Arc::clone(&blacklist), autoban_cfg(true), 60).with_trusted(trusted);
|
||||||
|
let inside = ip([10, 1, 2, 3]);
|
||||||
|
|
||||||
|
for _ in 0..6 {
|
||||||
|
reputation.record_bad(inside);
|
||||||
|
hook.on_connection_end(inside);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
reputation.score(inside) <= -50,
|
||||||
|
"reputation must fall below the threshold"
|
||||||
|
);
|
||||||
|
assert_eq!(hook.ban_offenders(), 0, "trusted addresses are never banned");
|
||||||
|
|
||||||
|
let public = ip([198, 51, 100, 9]);
|
||||||
|
for _ in 0..6 {
|
||||||
|
reputation.record_bad(public);
|
||||||
|
hook.on_connection_end(public);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
blacklist.is_blocked(public),
|
||||||
|
"non-trusted offenders are still banned by the reputation path"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue