diff --git a/src/filter/blacklist/prefix.rs b/src/filter/blacklist/prefix.rs index a465ac1..e9577e1 100644 --- a/src/filter/blacklist/prefix.rs +++ b/src/filter/blacklist/prefix.rs @@ -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)), diff --git a/src/xdp/filter/cidr/mod.rs b/src/xdp/filter/cidr/mod.rs new file mode 100644 index 0000000..b587196 --- /dev/null +++ b/src/xdp/filter/cidr/mod.rs @@ -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 { + 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() +} diff --git a/src/xdp/filter/maps.rs b/src/xdp/filter/maps.rs index af8cefa..e9be064 100644 --- a/src/xdp/filter/maps.rs +++ b/src/xdp/filter/maps.rs @@ -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 { - 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")?; diff --git a/src/xdp/filter/mod.rs b/src/xdp/filter/mod.rs index e0623b0..b8477ad 100644 --- a/src/xdp/filter/mod.rs +++ b/src/xdp/filter/mod.rs @@ -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, diff --git a/src/xdp/mod.rs b/src/xdp/mod.rs index 0909bf2..58fbac3 100644 --- a/src/xdp/mod.rs +++ b/src/xdp/mod.rs @@ -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")] diff --git a/src/xdp/probe/mod.rs b/src/xdp/probe/mod.rs index bd70e2b..32020d7 100644 --- a/src/xdp/probe/mod.rs +++ b/src/xdp/probe/mod.rs @@ -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")] diff --git a/src/xdp/probe/stats.rs b/src/xdp/probe/stats.rs index 75f578f..58b381d 100644 --- a/src/xdp/probe/stats.rs +++ b/src/xdp/probe/stats.rs @@ -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]) -> 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, } }; diff --git a/tests/manager_api.rs b/tests/manager_api.rs index 2dbd045..d24c20f 100644 --- a/tests/manager_api.rs +++ b/tests/manager_api.rs @@ -102,7 +102,16 @@ async fn protected_routes_require_a_token() { #[tokio::test] async fn blacklist_rejects_invalid_targets() { 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 response = status( &router, diff --git a/tests/xdp_abi_layout.rs b/tests/xdp_abi_layout.rs new file mode 100644 index 0000000..fea8cde --- /dev/null +++ b/tests/xdp_abi_layout.rs @@ -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::(), 24); + assert_eq!(align_of::(), 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::(), 32); + assert_eq!(align_of::(), 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::(), 96); + assert_eq!(align_of::(), 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); + } +} diff --git a/tests/xdp_cidr_validation.rs b/tests/xdp_cidr_validation.rs new file mode 100644 index 0000000..cba339e --- /dev/null +++ b/tests/xdp_cidr_validation.rs @@ -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"))); +} diff --git a/tests/xdp_key_byte_order.rs b/tests/xdp_key_byte_order.rs new file mode 100644 index 0000000..3611014 --- /dev/null +++ b/tests/xdp_key_byte_order.rs @@ -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"); +} diff --git a/tests/xdp_percpu_sum.rs b/tests/xdp_percpu_sum.rs new file mode 100644 index 0000000..0cf256c --- /dev/null +++ b/tests/xdp_percpu_sum.rs @@ -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 { + 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> = (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); +}