feat(xdp): ABI layout tests, canonical CIDR (mapped v4 folding), per-CPU sum helper
- tests/xdp_abi_layout.rs: size/align/offset of every Rust mirror of a BPF struct - xdp::canonical_cidr folds ::ffff:a.b.c.d/(96+n) into the IPv4 trie as a.b.c.d/n for ban_cidr and whitelist_add_cidr; whitelist_remove folds mapped addresses - Blacklist prefix table folds mapped prefixes the same way; checked_shl masks - sum_percpu_u64 factored out of get_stats (no expect, wrapping sum) - tests for /0, >width, v6 key byte order, per-CPU sums, manager CIDR rejection
This commit is contained in:
parent
e2adf8601c
commit
8693551499
12 changed files with 410 additions and 79 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.
|
/// Converts `ip/prefix_len` into an inclusive address range.
|
||||||
///
|
///
|
||||||
/// IPv4-mapped IPv6 addresses are normalised to IPv4 first, matching the prefix
|
/// IPv4-mapped IPv6 addresses with a prefix of at least 96 bits are folded into
|
||||||
/// keys used by the subnet detector and the XDP prefix stats.
|
/// 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)> {
|
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 {
|
match ip {
|
||||||
IpAddr::V4(v4) => {
|
IpAddr::V4(v4) => {
|
||||||
if prefix_len == 0 || prefix_len > 32 {
|
if prefix_len == 0 || prefix_len > 32 {
|
||||||
return None;
|
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;
|
let base = u32::from(v4) & mask;
|
||||||
Some((
|
Some((
|
||||||
IpAddr::V4(Ipv4Addr::from(base)),
|
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 {
|
if prefix_len == 0 || prefix_len > 128 {
|
||||||
return None;
|
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;
|
let base = u128::from(v6) & mask;
|
||||||
Some((
|
Some((
|
||||||
IpAddr::V6(Ipv6Addr::from(base)),
|
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 libbpf_rs::{MapCore, MapFlags};
|
||||||
|
|
||||||
use super::XdpFilter;
|
use super::XdpFilter;
|
||||||
|
use super::cidr::canonical_cidr;
|
||||||
use crate::xdp::probe::{blacklist_expiry_ns, monotonic_ns};
|
use crate::xdp::probe::{blacklist_expiry_ns, monotonic_ns};
|
||||||
|
|
||||||
/// Encodes an LPM-trie key for `blacklist_map` and `whitelist_map`:
|
/// 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
|
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 {
|
impl XdpFilter {
|
||||||
/// Adds a CIDR ban to the matching LPM trie: `blacklist_map` for IPv4,
|
/// Adds a CIDR ban to the matching LPM trie: `blacklist_map` for IPv4,
|
||||||
/// `blacklist6_map` for IPv6.
|
/// `blacklist6_map` for IPv6.
|
||||||
|
|
@ -111,9 +62,9 @@ impl XdpFilter {
|
||||||
/// Invalid prefix length, XDP not loaded, map missing from the object, or
|
/// Invalid prefix length, XDP not loaded, map missing from the object, or
|
||||||
/// a BPF update failure.
|
/// a BPF update failure.
|
||||||
pub fn ban_cidr(&self, prefix: IpAddr, prefix_len: u8, duration_secs: u64) -> Result<()> {
|
pub fn ban_cidr(&self, prefix: IpAddr, prefix_len: u8, duration_secs: u64) -> Result<()> {
|
||||||
match normalize_cidr(prefix, prefix_len)? {
|
match canonical_cidr(prefix, prefix_len)? {
|
||||||
IpAddr::V4(net) => self.blacklist_update(prefix_len, &net.octets(), duration_secs),
|
(IpAddr::V4(net), len) => self.blacklist_update(len, &net.octets(), duration_secs),
|
||||||
IpAddr::V6(net) => self.blacklist6_update(prefix_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
|
/// Invalid prefix length, XDP not loaded, map missing from the object, or
|
||||||
/// a BPF update failure.
|
/// a BPF update failure.
|
||||||
pub fn whitelist_add_cidr(&self, prefix: IpAddr, prefix_len: u8) -> Result<()> {
|
pub fn whitelist_add_cidr(&self, prefix: IpAddr, prefix_len: u8) -> Result<()> {
|
||||||
match normalize_cidr(prefix, prefix_len)? {
|
match canonical_cidr(prefix, prefix_len)? {
|
||||||
IpAddr::V4(net) => {
|
(IpAddr::V4(net), len) => {
|
||||||
let map = self.find_map("whitelist_map")?;
|
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")?;
|
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(())
|
Ok(())
|
||||||
|
|
@ -175,6 +126,11 @@ impl XdpFilter {
|
||||||
/// XDP not loaded, the matching whitelist map is missing, or a BPF delete
|
/// XDP not loaded, the matching whitelist map is missing, or a BPF delete
|
||||||
/// failure.
|
/// failure.
|
||||||
pub fn whitelist_remove(&self, ip: IpAddr) -> Result<()> {
|
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 {
|
match ip {
|
||||||
IpAddr::V4(addr) => {
|
IpAddr::V4(addr) => {
|
||||||
let map = self.find_map("whitelist_map")?;
|
let map = self.find_map("whitelist_map")?;
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,13 @@ use attach::{attach_program, patch_rodata};
|
||||||
use events::{AutoBanConfig, build_ringbuf};
|
use events::{AutoBanConfig, build_ringbuf};
|
||||||
|
|
||||||
mod attach;
|
mod attach;
|
||||||
|
mod cidr;
|
||||||
pub(crate) mod events;
|
pub(crate) mod events;
|
||||||
mod maps;
|
mod maps;
|
||||||
|
|
||||||
pub use attach::{interface_cstr, is_rodata_map, xdp_attach_mode_name};
|
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 {
|
pub struct XdpFilter {
|
||||||
obj: Option<Object>,
|
obj: Option<Object>,
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ pub use probe::{
|
||||||
AttachMode, EnvironmentReport, FilesystemProbe, KernelVersion, MIN_KERNEL, STAT_BLACKLIST, STAT_CHALLENGE_FAILED,
|
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_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,
|
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")]
|
#[cfg(feature = "xdp")]
|
||||||
|
|
@ -28,8 +28,8 @@ pub use filter::events::{
|
||||||
};
|
};
|
||||||
#[cfg(feature = "xdp")]
|
#[cfg(feature = "xdp")]
|
||||||
pub use filter::{
|
pub use filter::{
|
||||||
XdpFilter, blacklist_key, blacklist6_key, interface_cstr, is_rodata_map, normalize_cidr, whitelist_key,
|
XdpFilter, blacklist_key, blacklist6_key, canonical_cidr, interface_cstr, is_rodata_map, normalize_cidr,
|
||||||
whitelist6_key, xdp_attach_mode_name,
|
whitelist_key, whitelist6_key, xdp_attach_mode_name,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(feature = "xdp")]
|
#[cfg(feature = "xdp")]
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ mod stats;
|
||||||
pub use stats::{
|
pub use stats::{
|
||||||
STAT_BLACKLIST, STAT_CHALLENGE_FAILED, STAT_CHALLENGE_SENT, STAT_CHALLENGE_VERIFIED, STAT_DROP,
|
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_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")]
|
#[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).
|
/// `STAT_FRAGMENT_BYPASS`: packets passed because their L4 header is unavailable (fragments).
|
||||||
pub const STAT_FRAGMENT_BYPASS: u32 = 12;
|
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`.
|
/// XDP program counters; the indices follow `STAT_*` from `xdp/core/maps.h`.
|
||||||
#[derive(Debug, Clone, Copy, Default)]
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
pub struct XdpStats {
|
pub struct XdpStats {
|
||||||
|
|
@ -74,11 +88,7 @@ impl XdpFilter {
|
||||||
// `stats_map` is a percpu_array: plain `lookup` does not support it and
|
// `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.
|
// the failure would silently read as zero, so sum the per-CPU slots.
|
||||||
match map.lookup_percpu(&key, MapFlags::ANY) {
|
match map.lookup_percpu(&key, MapFlags::ANY) {
|
||||||
Ok(Some(slots)) => slots
|
Ok(Some(slots)) => sum_percpu_u64(&slots),
|
||||||
.iter()
|
|
||||||
.flat_map(|slot| slot.chunks_exact(8))
|
|
||||||
.map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8")))
|
|
||||||
.sum(),
|
|
||||||
_ => 0,
|
_ => 0,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -102,7 +102,16 @@ async fn protected_routes_require_a_token() {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn blacklist_rejects_invalid_targets() {
|
async fn blacklist_rejects_invalid_targets() {
|
||||||
let router = app();
|
let router = app();
|
||||||
for target in ["not-an-ip", "10.0.0.0/8", "999.1.1.1", ""] {
|
for target in [
|
||||||
|
"not-an-ip",
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"0.0.0.0/0",
|
||||||
|
"::/0",
|
||||||
|
"1.2.3.4/32",
|
||||||
|
"1.2.3.4/33",
|
||||||
|
"999.1.1.1",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
let body = format!(r#"{{"target":"{target}","type":"ip","reason":"manual_ban"}}"#);
|
let body = format!(r#"{{"target":"{target}","type":"ip","reason":"manual_ban"}}"#);
|
||||||
let response = status(
|
let response = status(
|
||||||
&router,
|
&router,
|
||||||
|
|
|
||||||
115
tests/xdp_abi_layout.rs
Normal file
115
tests/xdp_abi_layout.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
||||||
|
//! ABI layout of every Rust type that mirrors a BPF map key/value, ringbuf record or
|
||||||
|
//! `.rodata` image.
|
||||||
|
//!
|
||||||
|
//! The expected numbers are parsed by hand from the C definitions in `xdp/core/`
|
||||||
|
//! (natural alignment rules of clang/BPF: every field aligned to its own size, struct
|
||||||
|
//! size rounded up to its largest member). A failure here means one side of the ABI
|
||||||
|
//! moved without the other. Value-level checks live in `xdp_globals.rs`,
|
||||||
|
//! `xdp_ban_keys.rs` and `xdp_whitelist_keys.rs`.
|
||||||
|
|
||||||
|
use std::mem::{align_of, offset_of, size_of};
|
||||||
|
|
||||||
|
use rampart::traffic::prefix::{PrefixKey, PrefixStatsVal};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefix_key_mirrors_struct_prefix_key() {
|
||||||
|
// prefix_stats.h: struct prefix_key { __u8 family; __u8 pad[7]; __u8 addr[16]; }
|
||||||
|
assert_eq!(size_of::<PrefixKey>(), 24);
|
||||||
|
assert_eq!(align_of::<PrefixKey>(), 1);
|
||||||
|
assert_eq!(offset_of!(PrefixKey, family), 0);
|
||||||
|
assert_eq!(offset_of!(PrefixKey, pad), 1);
|
||||||
|
assert_eq!(offset_of!(PrefixKey, addr), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefix_key_byte_codec_matches_the_c_offsets() {
|
||||||
|
let key = PrefixKey {
|
||||||
|
family: 6,
|
||||||
|
pad: [0; 7],
|
||||||
|
addr: [7; 16],
|
||||||
|
};
|
||||||
|
let bytes = key.to_bytes();
|
||||||
|
assert_eq!(bytes[0], 6, "family @0");
|
||||||
|
assert_eq!(bytes[8..24], [7; 16], "addr @8");
|
||||||
|
assert_eq!(PrefixKey::from_bytes(bytes), key);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefix_stats_val_mirrors_struct_prefix_stats_val() {
|
||||||
|
// prefix_stats.h: struct prefix_stats_val { __u64 syn_count, pkt_count, last_seen_ns, source_bits; }
|
||||||
|
assert_eq!(size_of::<PrefixStatsVal>(), 32);
|
||||||
|
assert_eq!(align_of::<PrefixStatsVal>(), 8);
|
||||||
|
assert_eq!(offset_of!(PrefixStatsVal, syn_count), 0);
|
||||||
|
assert_eq!(offset_of!(PrefixStatsVal, pkt_count), 8);
|
||||||
|
assert_eq!(offset_of!(PrefixStatsVal, last_seen_ns), 16);
|
||||||
|
assert_eq!(offset_of!(PrefixStatsVal, source_bits), 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefix_stats_val_byte_codec_matches_the_c_offsets() {
|
||||||
|
let val = PrefixStatsVal {
|
||||||
|
syn_count: 1,
|
||||||
|
pkt_count: 2,
|
||||||
|
last_seen_ns: 3,
|
||||||
|
source_bits: 4,
|
||||||
|
};
|
||||||
|
let bytes = val.to_bytes();
|
||||||
|
for (i, expected) in [1u64, 2, 3, 4].into_iter().enumerate() {
|
||||||
|
let at = i * 8;
|
||||||
|
assert_eq!(
|
||||||
|
u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "xdp")]
|
||||||
|
mod xdp {
|
||||||
|
use super::{align_of, offset_of, size_of};
|
||||||
|
use rampart::xdp::{RODATA_SIZE, XDP_EVENT_LEN, XdpGlobals, blacklist_key, blacklist6_key};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xdp_globals_mirrors_struct_rampart_config() {
|
||||||
|
// config.h: struct rampart_config, sizeof == 96 (its own _Static_assert).
|
||||||
|
assert_eq!(size_of::<XdpGlobals>(), 96);
|
||||||
|
assert_eq!(align_of::<XdpGlobals>(), 8);
|
||||||
|
assert_eq!(RODATA_SIZE, 96);
|
||||||
|
let expected = [
|
||||||
|
(offset_of!(XdpGlobals, start_port), 0),
|
||||||
|
(offset_of!(XdpGlobals, end_port), 2),
|
||||||
|
(offset_of!(XdpGlobals, syn_hit_count), 4),
|
||||||
|
(offset_of!(XdpGlobals, syn_window_ns), 8),
|
||||||
|
(offset_of!(XdpGlobals, syn_ban_duration_ns), 16),
|
||||||
|
(offset_of!(XdpGlobals, conntrack_idle_ns), 24),
|
||||||
|
(offset_of!(XdpGlobals, player_idle_ns), 32),
|
||||||
|
(offset_of!(XdpGlobals, ban_duration_ns), 40),
|
||||||
|
(offset_of!(XdpGlobals, max_out_of_order), 48),
|
||||||
|
(offset_of!(XdpGlobals, udp_policy), 49),
|
||||||
|
(offset_of!(XdpGlobals, udp_hit_count), 52),
|
||||||
|
(offset_of!(XdpGlobals, udp_window_ns), 56),
|
||||||
|
(offset_of!(XdpGlobals, feature_syn_throttle), 64),
|
||||||
|
(offset_of!(XdpGlobals, feature_events), 65),
|
||||||
|
(offset_of!(XdpGlobals, syn_challenge_enabled), 66),
|
||||||
|
(offset_of!(XdpGlobals, challenge_secret), 72),
|
||||||
|
(offset_of!(XdpGlobals, challenge_timeout_ms), 80),
|
||||||
|
(offset_of!(XdpGlobals, challenge_verified_ttl_ns), 88),
|
||||||
|
];
|
||||||
|
for (rust, c) in expected {
|
||||||
|
assert_eq!(rust, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lpm_keys_have_the_size_of_struct_lpm_key_and_key6() {
|
||||||
|
// common.h: struct lpm_key { __u32 prefixlen; __u32 ip; } -> 8
|
||||||
|
assert_eq!(size_of_val(&blacklist_key(24, &[0; 4])), 8);
|
||||||
|
// common.h: struct lpm_key6 { __u32 prefixlen; __u8 addr[16]; } -> 20, align 4
|
||||||
|
assert_eq!(size_of_val(&blacklist6_key(64, &[0; 16])), 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xdp_event_len_matches_struct_xdp_event() {
|
||||||
|
// common.h: struct xdp_event { __u32 type, src_ip, metadata; (4 pad) __u64 timestamp; } -> 24
|
||||||
|
assert_eq!(XDP_EVENT_LEN, 24);
|
||||||
|
}
|
||||||
|
}
|
||||||
95
tests/xdp_cidr_validation.rs
Normal file
95
tests/xdp_cidr_validation.rs
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
//! Prefix/CIDR validation for every ban and whitelist entry point.
|
||||||
|
//!
|
||||||
|
//! A `/0` would blackhole (or whitelist) a whole address family, anything above the
|
||||||
|
//! address width is nonsense, and the mask math must never shift by the full width.
|
||||||
|
#![cfg(feature = "xdp")]
|
||||||
|
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use rampart::filter::blacklist::Blacklist;
|
||||||
|
use rampart::xdp::{canonical_cidr, normalize_cidr};
|
||||||
|
|
||||||
|
fn ip(s: &str) -> IpAddr {
|
||||||
|
s.parse().expect("test address")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero_prefix_is_rejected_for_both_families() {
|
||||||
|
assert!(normalize_cidr(ip("10.0.0.1"), 0).is_err());
|
||||||
|
assert!(normalize_cidr(ip("2001:db8::1"), 0).is_err());
|
||||||
|
assert!(canonical_cidr(ip("::ffff:10.0.0.1"), 0).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefix_above_the_address_width_is_rejected() {
|
||||||
|
assert!(normalize_cidr(ip("10.0.0.1"), 33).is_err());
|
||||||
|
assert!(normalize_cidr(ip("10.0.0.1"), 255).is_err());
|
||||||
|
assert!(normalize_cidr(ip("2001:db8::1"), 129).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn full_width_prefixes_do_not_overflow_the_mask() {
|
||||||
|
assert_eq!(normalize_cidr(ip("10.1.2.3"), 32).expect("/32"), ip("10.1.2.3"));
|
||||||
|
assert_eq!(normalize_cidr(ip("2001:db8::1"), 128).expect("/128"), ip("2001:db8::1"));
|
||||||
|
assert_eq!(normalize_cidr(ip("10.1.2.3"), 1).expect("/1"), ip("0.0.0.0"));
|
||||||
|
assert_eq!(normalize_cidr(ip("ffff::1"), 1).expect("/1"), ip("8000::"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ipv6_masks_partial_bytes() {
|
||||||
|
assert_eq!(
|
||||||
|
normalize_cidr(ip("2001:db8:ffff::1"), 36).expect("/36"),
|
||||||
|
ip("2001:db8:f000::")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mapped_ipv6_folds_into_ipv4_with_the_length_shifted() {
|
||||||
|
let (net, len) = canonical_cidr(ip("::ffff:10.1.2.3"), 120).expect("mapped /120");
|
||||||
|
assert_eq!((net, len), (ip("10.1.2.0"), 24));
|
||||||
|
let (net, len) = canonical_cidr(ip("::ffff:10.1.2.3"), 128).expect("mapped /128");
|
||||||
|
assert_eq!((net, len), (ip("10.1.2.3"), 32));
|
||||||
|
// The empty IPv4 prefix is /0 in disguise.
|
||||||
|
assert!(canonical_cidr(ip("::ffff:10.1.2.3"), 96).is_err());
|
||||||
|
// Wider than IPv4 space: stays IPv6.
|
||||||
|
let (net, len) = canonical_cidr(ip("::ffff:10.1.2.3"), 64).expect("mapped /64");
|
||||||
|
assert_eq!((net, len), (ip("::"), 64));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn userspace_blacklist_rejects_zero_and_oversized_prefixes() {
|
||||||
|
let blacklist = Blacklist::new();
|
||||||
|
for (addr, len) in [
|
||||||
|
("10.0.0.1", 0),
|
||||||
|
("10.0.0.1", 33),
|
||||||
|
("2001:db8::1", 0),
|
||||||
|
("2001:db8::1", 129),
|
||||||
|
("::ffff:10.0.0.1", 0),
|
||||||
|
("::ffff:10.0.0.1", 96),
|
||||||
|
] {
|
||||||
|
blacklist.add_cidr(ip(addr), len, Duration::from_secs(60), "test");
|
||||||
|
}
|
||||||
|
assert!(blacklist.is_empty(), "no invalid CIDR may be installed");
|
||||||
|
assert!(!blacklist.is_blocked(ip("10.0.0.1")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn userspace_blacklist_accepts_full_width_prefixes() {
|
||||||
|
let blacklist = Blacklist::new();
|
||||||
|
blacklist.add_cidr(ip("10.0.0.7"), 32, Duration::from_secs(60), "test");
|
||||||
|
blacklist.add_cidr(ip("2001:db8::7"), 128, Duration::from_secs(60), "test");
|
||||||
|
assert!(blacklist.is_blocked(ip("10.0.0.7")));
|
||||||
|
assert!(!blacklist.is_blocked(ip("10.0.0.8")));
|
||||||
|
assert!(blacklist.is_blocked(ip("2001:db8::7")));
|
||||||
|
assert!(!blacklist.is_blocked(ip("2001:db8::8")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn userspace_blacklist_folds_mapped_prefixes_like_the_xdp_loader() {
|
||||||
|
let blacklist = Blacklist::new();
|
||||||
|
blacklist.add_cidr(ip("::ffff:10.9.8.7"), 120, Duration::from_secs(60), "test");
|
||||||
|
assert!(blacklist.is_blocked(ip("10.9.8.200")), "/120 mapped == v4 /24");
|
||||||
|
assert!(!blacklist.is_blocked(ip("10.9.9.1")));
|
||||||
|
assert!(blacklist.is_blocked(ip("::ffff:10.9.8.1")));
|
||||||
|
}
|
||||||
34
tests/xdp_key_byte_order.rs
Normal file
34
tests/xdp_key_byte_order.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
//! IPv6 LPM keys carry the address in network order right after the prefix length.
|
||||||
|
#![cfg(feature = "xdp")]
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv6Addr};
|
||||||
|
|
||||||
|
use rampart::xdp::{blacklist6_key, normalize_cidr, whitelist6_key};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ipv6_keys_hold_the_network_order_bytes_of_the_address() {
|
||||||
|
let addr: Ipv6Addr = "2001:db8:1234:5678:9abc:def0:1122:3344".parse().expect("ipv6");
|
||||||
|
let wire = addr.octets();
|
||||||
|
assert_eq!(
|
||||||
|
wire[0..4],
|
||||||
|
[0x20, 0x01, 0x0d, 0xb8],
|
||||||
|
"sanity: octets() is network order"
|
||||||
|
);
|
||||||
|
|
||||||
|
for key in [blacklist6_key(128, &wire), whitelist6_key(128, &wire)] {
|
||||||
|
assert_eq!(key[0..4], 128u32.to_le_bytes(), "prefixlen is a host-order (LE) u32");
|
||||||
|
assert_eq!(key[4..20], wire, "address bytes are not byte-swapped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn masked_cidr_bytes_feed_the_key_in_network_order() {
|
||||||
|
let addr: Ipv6Addr = "2001:db8:aaaa:bbbb:cccc:dddd:eeee:ffff".parse().expect("ipv6");
|
||||||
|
let net = normalize_cidr(IpAddr::V6(addr), 48).expect("/48");
|
||||||
|
let IpAddr::V6(net) = net else {
|
||||||
|
unreachable!("a v6 prefix stays v6");
|
||||||
|
};
|
||||||
|
let key = blacklist6_key(48, &net.octets());
|
||||||
|
assert_eq!(key[4..10], [0x20, 0x01, 0x0d, 0xb8, 0xaa, 0xaa]);
|
||||||
|
assert_eq!(key[10..20], [0u8; 10], "host bits cleared");
|
||||||
|
}
|
||||||
32
tests/xdp_percpu_sum.rs
Normal file
32
tests/xdp_percpu_sum.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
//! Per-CPU counter aggregation: libbpf returns one buffer per possible CPU.
|
||||||
|
|
||||||
|
use rampart::xdp::sum_percpu_u64;
|
||||||
|
|
||||||
|
fn slot(v: u64) -> Vec<u8> {
|
||||||
|
v.to_le_bytes().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sums_every_slot_regardless_of_cpu_count() {
|
||||||
|
for cpus in [1u64, 2, 7, 64, 512] {
|
||||||
|
let slots: Vec<Vec<u8>> = (1..=cpus).map(slot).collect();
|
||||||
|
assert_eq!(sum_percpu_u64(&slots), cpus * (cpus + 1) / 2, "{cpus} CPUs");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_but_possible_cpus_contribute_zero() {
|
||||||
|
let slots = vec![slot(5), slot(0), slot(0), slot(7)];
|
||||||
|
assert_eq!(sum_percpu_u64(&slots), 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_and_short_buffers_are_harmless() {
|
||||||
|
assert_eq!(sum_percpu_u64(&[]), 0);
|
||||||
|
assert_eq!(sum_percpu_u64(&[vec![1, 2, 3]]), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_counters_wrap_instead_of_panicking() {
|
||||||
|
assert_eq!(sum_percpu_u64(&[slot(u64::MAX), slot(2)]), 1);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue