Merge branch 'worktree-agent-ae36f7883b9775990'
# Conflicts: # tests/manager_api.rs
This commit is contained in:
commit
febc49f3eb
12 changed files with 403 additions and 78 deletions
|
|
@ -70,21 +70,22 @@ impl PrefixBans {
|
|||
}
|
||||
}
|
||||
|
||||
/// Bits an IPv4-mapped IPv6 address spends before its IPv4 part.
|
||||
const MAPPED_V4_BITS: u8 = 96;
|
||||
|
||||
/// Converts `ip/prefix_len` into an inclusive address range.
|
||||
///
|
||||
/// IPv4-mapped IPv6 addresses are normalised to IPv4 first, matching the prefix
|
||||
/// keys used by the subnet detector and the XDP prefix stats.
|
||||
/// IPv4-mapped IPv6 addresses with a prefix of at least 96 bits are folded into
|
||||
/// IPv4 (`::ffff:a.b.c.d/(96+n)` becomes `a.b.c.d/n`; `/96` is a rejected `/0`), matching the prefix keys of
|
||||
/// the subnet detector, the XDP prefix stats and the XDP ban tries. Shorter
|
||||
/// prefixes cover more than IPv4 space and stay IPv6 ranges.
|
||||
fn cidr_range(ip: IpAddr, prefix_len: u8) -> Option<(IpAddr, IpAddr)> {
|
||||
let ip = match ip {
|
||||
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
|
||||
IpAddr::V4(_) => ip,
|
||||
};
|
||||
match ip {
|
||||
IpAddr::V4(v4) => {
|
||||
if prefix_len == 0 || prefix_len > 32 {
|
||||
return None;
|
||||
}
|
||||
let mask = u32::MAX << (32 - prefix_len);
|
||||
let mask = u32::MAX.checked_shl(32 - u32::from(prefix_len)).unwrap_or(0);
|
||||
let base = u32::from(v4) & mask;
|
||||
Some((
|
||||
IpAddr::V4(Ipv4Addr::from(base)),
|
||||
|
|
@ -95,7 +96,12 @@ fn cidr_range(ip: IpAddr, prefix_len: u8) -> Option<(IpAddr, IpAddr)> {
|
|||
if prefix_len == 0 || prefix_len > 128 {
|
||||
return None;
|
||||
}
|
||||
let mask = u128::MAX << (128 - prefix_len);
|
||||
if let Some(v4) = v6.to_ipv4_mapped()
|
||||
&& prefix_len >= MAPPED_V4_BITS
|
||||
{
|
||||
return cidr_range(IpAddr::V4(v4), prefix_len - MAPPED_V4_BITS);
|
||||
}
|
||||
let mask = u128::MAX.checked_shl(128 - u32::from(prefix_len)).unwrap_or(0);
|
||||
let base = u128::from(v6) & mask;
|
||||
Some((
|
||||
IpAddr::V6(Ipv6Addr::from(base)),
|
||||
|
|
|
|||
72
src/xdp/filter/cidr/mod.rs
Normal file
72
src/xdp/filter/cidr/mod.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
//! CIDR validation and canonicalisation shared by the ban and whitelist paths.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
/// Prefix bits that an IPv4-mapped IPv6 address (`::ffff:a.b.c.d`) spends before its IPv4 part.
|
||||
const MAPPED_V4_BITS: u8 = 96;
|
||||
|
||||
/// Validates a CIDR prefix length and clears the host bits of `prefix`.
|
||||
///
|
||||
/// The kernel's LPM trie compares keys bit by bit, so `10.1.2.3/24` and
|
||||
/// `10.1.2.0/24` are different keys for the same range: without masking, two
|
||||
/// bans of the same subnet never share an entry and expiry bookkeeping falls
|
||||
/// apart. A zero-length prefix is rejected because "ban the entire address
|
||||
/// space" is never an intentional operator request.
|
||||
///
|
||||
/// IPv4-mapped IPv6 input is folded into IPv4 (see [`canonical_cidr`]); only the
|
||||
/// address is returned here, use [`canonical_cidr`] when the length is needed too.
|
||||
///
|
||||
/// # Errors
|
||||
/// `prefix_len` is 0 or exceeds 32 for IPv4 / 128 for IPv6, or a mapped address
|
||||
/// carries a prefix of exactly 96 bits (an empty IPv4 prefix).
|
||||
pub fn normalize_cidr(prefix: IpAddr, prefix_len: u8) -> Result<IpAddr> {
|
||||
canonical_cidr(prefix, prefix_len).map(|(net, _)| net)
|
||||
}
|
||||
|
||||
/// Like [`normalize_cidr`], but also returns the prefix length to use in the key.
|
||||
///
|
||||
/// XDP looks up a plain IPv4 packet in the IPv4 trie, so a ban of the mapped form
|
||||
/// `::ffff:a.b.c.d/(96+n)` must land there as `a.b.c.d/n`, exactly as the userspace
|
||||
/// blacklist treats it. A mapped address with a prefix shorter than 96 bits spans
|
||||
/// more than IPv4 space and stays an IPv6 prefix.
|
||||
///
|
||||
/// # Errors
|
||||
/// Same as [`normalize_cidr`].
|
||||
pub fn canonical_cidr(prefix: IpAddr, prefix_len: u8) -> Result<(IpAddr, u8)> {
|
||||
match prefix {
|
||||
IpAddr::V4(addr) => {
|
||||
ensure_prefix_len(prefix_len, 32, "IPv4")?;
|
||||
Ok((IpAddr::V4(Ipv4Addr::from(mask_v4(addr, prefix_len))), prefix_len))
|
||||
},
|
||||
IpAddr::V6(addr) => {
|
||||
ensure_prefix_len(prefix_len, 128, "IPv6")?;
|
||||
if let Some(v4) = addr.to_ipv4_mapped()
|
||||
&& prefix_len >= MAPPED_V4_BITS
|
||||
{
|
||||
return canonical_cidr(IpAddr::V4(v4), prefix_len - MAPPED_V4_BITS);
|
||||
}
|
||||
Ok((IpAddr::V6(Ipv6Addr::from(mask_v6(addr, prefix_len))), prefix_len))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_prefix_len(prefix_len: u8, max: u8, family: &str) -> Result<()> {
|
||||
if prefix_len == 0 || prefix_len > max {
|
||||
bail!("invalid {family} prefix length {prefix_len}: expected 1..={max}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mask_v4(addr: Ipv4Addr, prefix_len: u8) -> [u8; 4] {
|
||||
let shift = 32_u32.saturating_sub(u32::from(prefix_len));
|
||||
let mask = u32::MAX.checked_shl(shift).unwrap_or(0);
|
||||
(u32::from(addr) & mask).to_be_bytes()
|
||||
}
|
||||
|
||||
fn mask_v6(addr: Ipv6Addr, prefix_len: u8) -> [u8; 16] {
|
||||
let shift = 128_u32.saturating_sub(u32::from(prefix_len));
|
||||
let mask = u128::MAX.checked_shl(shift).unwrap_or(0);
|
||||
(u128::from(addr) & mask).to_be_bytes()
|
||||
}
|
||||
|
|
@ -1,9 +1,10 @@
|
|||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::Result;
|
||||
use libbpf_rs::{MapCore, MapFlags};
|
||||
|
||||
use super::XdpFilter;
|
||||
use super::cidr::canonical_cidr;
|
||||
use crate::xdp::probe::{blacklist_expiry_ns, monotonic_ns};
|
||||
|
||||
/// Encodes an LPM-trie key for `blacklist_map` and `whitelist_map`:
|
||||
|
|
@ -50,56 +51,6 @@ fn ipv6_lpm_key(prefix_len: u8, v6: &[u8; 16]) -> [u8; 20] {
|
|||
key
|
||||
}
|
||||
|
||||
/// Validates a CIDR prefix length and clears the host bits of `prefix`.
|
||||
///
|
||||
/// The kernel's LPM trie compares keys bit by bit, so `10.1.2.3/24` and
|
||||
/// `10.1.2.0/24` are different keys for the same range: without masking, two
|
||||
/// bans of the same subnet never share an entry and expiry bookkeeping falls
|
||||
/// apart. A zero-length prefix is rejected because "ban the entire address
|
||||
/// space" is never an intentional operator request.
|
||||
///
|
||||
/// # Errors
|
||||
/// `prefix_len` is 0 or exceeds 32 for IPv4 / 128 for IPv6.
|
||||
pub fn normalize_cidr(prefix: IpAddr, prefix_len: u8) -> Result<IpAddr> {
|
||||
match prefix {
|
||||
IpAddr::V4(addr) => {
|
||||
ensure_prefix_len(prefix_len, 32, "IPv4")?;
|
||||
Ok(IpAddr::V4(Ipv4Addr::from(mask_v4(addr, prefix_len))))
|
||||
},
|
||||
IpAddr::V6(addr) => {
|
||||
ensure_prefix_len(prefix_len, 128, "IPv6")?;
|
||||
Ok(IpAddr::V6(Ipv6Addr::from(mask_v6(addr, prefix_len))))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_prefix_len(prefix_len: u8, max: u8, family: &str) -> Result<()> {
|
||||
if prefix_len == 0 || prefix_len > max {
|
||||
bail!("invalid {family} prefix length {prefix_len}: expected 1..={max}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mask_v4(addr: Ipv4Addr, prefix_len: u8) -> [u8; 4] {
|
||||
let bits = u32::from(addr);
|
||||
let mask = u32::MAX << (32 - u32::from(prefix_len));
|
||||
(bits & mask).to_be_bytes()
|
||||
}
|
||||
|
||||
fn mask_v6(addr: Ipv6Addr, prefix_len: u8) -> [u8; 16] {
|
||||
let mut octets = addr.octets();
|
||||
let full_bytes = usize::from(prefix_len) / 8;
|
||||
let remainder = prefix_len % 8;
|
||||
for byte in octets.iter_mut().skip(full_bytes) {
|
||||
*byte = 0;
|
||||
}
|
||||
if remainder != 0 {
|
||||
// `full_bytes` is always < 16 here: a partial byte follows the full ones.
|
||||
octets[full_bytes] &= 0xffu8 << (8 - remainder);
|
||||
}
|
||||
octets
|
||||
}
|
||||
|
||||
impl XdpFilter {
|
||||
/// Adds a CIDR ban to the matching LPM trie: `blacklist_map` for IPv4,
|
||||
/// `blacklist6_map` for IPv6.
|
||||
|
|
@ -111,9 +62,9 @@ impl XdpFilter {
|
|||
/// Invalid prefix length, XDP not loaded, map missing from the object, or
|
||||
/// a BPF update failure.
|
||||
pub fn ban_cidr(&self, prefix: IpAddr, prefix_len: u8, duration_secs: u64) -> Result<()> {
|
||||
match normalize_cidr(prefix, prefix_len)? {
|
||||
IpAddr::V4(net) => self.blacklist_update(prefix_len, &net.octets(), duration_secs),
|
||||
IpAddr::V6(net) => self.blacklist6_update(prefix_len, &net.octets(), duration_secs),
|
||||
match canonical_cidr(prefix, prefix_len)? {
|
||||
(IpAddr::V4(net), len) => self.blacklist_update(len, &net.octets(), duration_secs),
|
||||
(IpAddr::V6(net), len) => self.blacklist6_update(len, &net.octets(), duration_secs),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -156,14 +107,14 @@ impl XdpFilter {
|
|||
/// Invalid prefix length, XDP not loaded, map missing from the object, or
|
||||
/// a BPF update failure.
|
||||
pub fn whitelist_add_cidr(&self, prefix: IpAddr, prefix_len: u8) -> Result<()> {
|
||||
match normalize_cidr(prefix, prefix_len)? {
|
||||
IpAddr::V4(net) => {
|
||||
match canonical_cidr(prefix, prefix_len)? {
|
||||
(IpAddr::V4(net), len) => {
|
||||
let map = self.find_map("whitelist_map")?;
|
||||
map.update(&whitelist_key(prefix_len, &net.octets()), &[1u8], MapFlags::ANY)?;
|
||||
map.update(&whitelist_key(len, &net.octets()), &[1u8], MapFlags::ANY)?;
|
||||
},
|
||||
IpAddr::V6(net) => {
|
||||
(IpAddr::V6(net), len) => {
|
||||
let map = self.find_map("whitelist6_map")?;
|
||||
map.update(&whitelist6_key(prefix_len, &net.octets()), &[1u8], MapFlags::ANY)?;
|
||||
map.update(&whitelist6_key(len, &net.octets()), &[1u8], MapFlags::ANY)?;
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -175,6 +126,11 @@ impl XdpFilter {
|
|||
/// XDP not loaded, the matching whitelist map is missing, or a BPF delete
|
||||
/// failure.
|
||||
pub fn whitelist_remove(&self, ip: IpAddr) -> Result<()> {
|
||||
// Fold mapped IPv6 into IPv4: that is the trie `whitelist_add` stored it in.
|
||||
let ip = match ip {
|
||||
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
|
||||
IpAddr::V4(_) => ip,
|
||||
};
|
||||
match ip {
|
||||
IpAddr::V4(addr) => {
|
||||
let map = self.find_map("whitelist_map")?;
|
||||
|
|
|
|||
|
|
@ -11,11 +11,13 @@ use attach::{attach_program, patch_rodata};
|
|||
use events::{AutoBanConfig, build_ringbuf};
|
||||
|
||||
mod attach;
|
||||
mod cidr;
|
||||
pub(crate) mod events;
|
||||
mod maps;
|
||||
|
||||
pub use attach::{interface_cstr, is_rodata_map, xdp_attach_mode_name};
|
||||
pub use maps::{blacklist_key, blacklist6_key, normalize_cidr, whitelist_key, whitelist6_key};
|
||||
pub use cidr::{canonical_cidr, normalize_cidr};
|
||||
pub use maps::{blacklist_key, blacklist6_key, whitelist_key, whitelist6_key};
|
||||
|
||||
pub struct XdpFilter {
|
||||
obj: Option<Object>,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ pub use probe::{
|
|||
AttachMode, EnvironmentReport, FilesystemProbe, KernelVersion, MIN_KERNEL, STAT_BLACKLIST, STAT_CHALLENGE_FAILED,
|
||||
STAT_CHALLENGE_SENT, STAT_CHALLENGE_VERIFIED, STAT_DROP, STAT_FRAGMENT_BYPASS, STAT_PASS, STAT_RATE_LIMIT,
|
||||
STAT_SYN_THROTTLE, STAT_TCP, STAT_TOTAL, STAT_UDP, STAT_WHITELIST, SystemProbe, XdpStats,
|
||||
driver_supports_native_xdp,
|
||||
driver_supports_native_xdp, sum_percpu_u64,
|
||||
};
|
||||
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
@ -28,8 +28,8 @@ pub use filter::events::{
|
|||
};
|
||||
#[cfg(feature = "xdp")]
|
||||
pub use filter::{
|
||||
XdpFilter, blacklist_key, blacklist6_key, interface_cstr, is_rodata_map, normalize_cidr, whitelist_key,
|
||||
whitelist6_key, xdp_attach_mode_name,
|
||||
XdpFilter, blacklist_key, blacklist6_key, canonical_cidr, interface_cstr, is_rodata_map, normalize_cidr,
|
||||
whitelist_key, whitelist6_key, xdp_attach_mode_name,
|
||||
};
|
||||
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ mod stats;
|
|||
pub use stats::{
|
||||
STAT_BLACKLIST, STAT_CHALLENGE_FAILED, STAT_CHALLENGE_SENT, STAT_CHALLENGE_VERIFIED, STAT_DROP,
|
||||
STAT_FRAGMENT_BYPASS, STAT_PASS, STAT_RATE_LIMIT, STAT_SYN_THROTTLE, STAT_TCP, STAT_TOTAL, STAT_UDP,
|
||||
STAT_WHITELIST, XdpStats,
|
||||
STAT_WHITELIST, XdpStats, sum_percpu_u64,
|
||||
};
|
||||
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
|
|||
|
|
@ -42,6 +42,20 @@ pub const STAT_CHALLENGE_FAILED: u32 = 11;
|
|||
/// `STAT_FRAGMENT_BYPASS`: packets passed because their L4 header is unavailable (fragments).
|
||||
pub const STAT_FRAGMENT_BYPASS: u32 = 12;
|
||||
|
||||
/// Sums a per-CPU `__u64` counter over every slot libbpf returned.
|
||||
///
|
||||
/// `lookup_percpu` yields one buffer per *possible* CPU (not per online CPU), so the
|
||||
/// CPU count is never assumed here. Counters wrap like the kernel's and a short
|
||||
/// trailing chunk (never produced for a `__u64` value) is ignored.
|
||||
#[must_use]
|
||||
pub fn sum_percpu_u64(slots: &[Vec<u8>]) -> u64 {
|
||||
slots
|
||||
.iter()
|
||||
.flat_map(|slot| slot.chunks_exact(8))
|
||||
.filter_map(|chunk| <[u8; 8]>::try_from(chunk).ok())
|
||||
.fold(0u64, |acc, raw| acc.wrapping_add(u64::from_le_bytes(raw)))
|
||||
}
|
||||
|
||||
/// XDP program counters; the indices follow `STAT_*` from `xdp/core/maps.h`.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct XdpStats {
|
||||
|
|
@ -74,11 +88,7 @@ impl XdpFilter {
|
|||
// `stats_map` is a percpu_array: plain `lookup` does not support it and
|
||||
// the failure would silently read as zero, so sum the per-CPU slots.
|
||||
match map.lookup_percpu(&key, MapFlags::ANY) {
|
||||
Ok(Some(slots)) => slots
|
||||
.iter()
|
||||
.flat_map(|slot| slot.chunks_exact(8))
|
||||
.map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8")))
|
||||
.sum(),
|
||||
Ok(Some(slots)) => sum_percpu_u64(&slots),
|
||||
_ => 0,
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue