fix: XDP unsafe loader + Redis sync; enforce 250-line/4-file layout limits
- xdp: CString for if_nametoindex (was UB), real detach via prog fd (fabricated borrow_raw(-1) silently never detached), SAFETY comments, saturating expiry math; +5 unit tests - redis: real pubsub reconnect with exponential backoff (was sleep+return); KEYS -> SCAN in heartbeat sweep - ci: cargo test --all-features, repo-gates job — module size gate (scripts/check_module_size.sh, ratchet baseline) + default-secrets grep - refactor src/ to <=250 LOC/file, <=4 .rs/dir without behavior change; thin bins (rampart.rs 330 -> 6 LOC), new app/, subnet/, intel/, profile/, prefix/, challenge/, filter/, probe/, inventory/, metrics/, node/ - docs: TODO v5.0 (status refresh, new rules, findings backlog), README quickstart now matches real binaries - verify: fmt/clippy -D warnings/test --all-features (164 tests)/clang XDP green
This commit is contained in:
parent
7545b3d3ad
commit
bf6d34c882
64 changed files with 2052 additions and 1408 deletions
58
src/xdp/filter/attach.rs
Normal file
58
src/xdp/filter/attach.rs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
use anyhow::{Context, Result};
|
||||
use libbpf_rs::{MapCore, Object, OpenObject, RingBuffer, RingBufferBuilder};
|
||||
use std::ffi::CString;
|
||||
|
||||
use crate::xdp::globals::{RODATA_MAP_NAME, XdpGlobals};
|
||||
|
||||
/// Builds the NUL-terminated C string libc's `if_nametoindex` requires.
|
||||
/// Rejects interface names containing an interior NUL byte instead of
|
||||
/// silently truncating at it (the `&str`-as-`*const c_char` UB we removed).
|
||||
pub(super) fn interface_cstr(name: &str) -> Result<CString> {
|
||||
CString::new(name).with_context(|| format!("interface name {name:?} contains an interior NUL byte"))
|
||||
}
|
||||
|
||||
/// Патчит карту `rampart_.rodata` (volatile const глобалы) ДО загрузки объекта.
|
||||
pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> Result<()> {
|
||||
let image = globals.build_rodata_image();
|
||||
let mut map = open_obj
|
||||
.maps_mut()
|
||||
.find(|m| m.name() == RODATA_MAP_NAME)
|
||||
.with_context(|| format!("map '{RODATA_MAP_NAME}' not found in XDP object"))?;
|
||||
map.set_initial_value(&image)
|
||||
.with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'"))
|
||||
}
|
||||
|
||||
pub(super) fn build_ringbuf(obj: &Object) -> Result<RingBuffer<'static>> {
|
||||
let map = obj
|
||||
.maps()
|
||||
.find(|m| m.name() == "events_map")
|
||||
.context("events_map not found")?;
|
||||
let mut builder = RingBufferBuilder::new();
|
||||
builder.add(&map, |data: &[u8]| {
|
||||
if data.len() >= 16 {
|
||||
let ty = u32::from_ne_bytes(data[0..4].try_into().expect("4 bytes for type"));
|
||||
let ip4 = u32::from_ne_bytes(data[4..8].try_into().expect("4 bytes for ip"));
|
||||
let val = u64::from_ne_bytes(data[8..16].try_into().expect("8 bytes for val"));
|
||||
tracing::debug!(event = ty, src_ip = ip4, data = val, "xdp event");
|
||||
}
|
||||
0
|
||||
})?;
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interface_cstr_accepts_plain_names() {
|
||||
let c = interface_cstr("eth0").expect("valid interface name");
|
||||
assert_eq!(c.as_bytes(), b"eth0");
|
||||
assert_eq!(c.as_bytes_with_nul(), b"eth0\0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_cstr_rejects_interior_nul() {
|
||||
assert!(interface_cstr("et\0h0").is_err());
|
||||
}
|
||||
}
|
||||
43
src/xdp/filter/maps.rs
Normal file
43
src/xdp/filter/maps.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
pub(super) fn unix_ns() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos() as u64
|
||||
}
|
||||
|
||||
/// Encodes an LPM-trie key for `blacklist_map`: prefix length in byte 0 and the
|
||||
/// four IPv4 octets in bytes 4..8 (bytes 1..3 are padding the kernel ignores).
|
||||
pub(super) fn blacklist_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] {
|
||||
let mut key = [0u8; 8];
|
||||
key[0] = prefix_len;
|
||||
key[4..8].copy_from_slice(v4);
|
||||
key
|
||||
}
|
||||
|
||||
/// Absolute ban expiry in ns-since-epoch, saturating so an absurd duration
|
||||
/// clamps to `u64::MAX` rather than wrapping into the past.
|
||||
pub(super) fn blacklist_expiry_ns(now_ns: u64, duration_secs: u64) -> u64 {
|
||||
now_ns.saturating_add(duration_secs.saturating_mul(1_000_000_000))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blacklist_key_puts_prefix_len_first_and_octets_last() {
|
||||
assert_eq!(blacklist_key(24, &[10, 0, 1, 200]), [24, 0, 0, 0, 10, 0, 1, 200]);
|
||||
assert_eq!(blacklist_key(32, &[127, 0, 0, 1]), [32, 0, 0, 0, 127, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blacklist_expiry_converts_secs_to_ns() {
|
||||
assert_eq!(blacklist_expiry_ns(1_000, 2), 1_000 + 2_000_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blacklist_expiry_saturates_instead_of_wrapping() {
|
||||
assert_eq!(blacklist_expiry_ns(u64::MAX, 1), u64::MAX);
|
||||
assert_eq!(blacklist_expiry_ns(0, u64::MAX), u64::MAX);
|
||||
}
|
||||
}
|
||||
215
src/xdp/filter/mod.rs
Normal file
215
src/xdp/filter/mod.rs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
use anyhow::{Context, Result, bail};
|
||||
use libbpf_rs::{MapCore, MapFlags, Object, ObjectBuilder, RingBuffer, Xdp, XdpFlags};
|
||||
use std::net::IpAddr;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::os::unix::io::AsFd;
|
||||
|
||||
use super::XdpStats;
|
||||
use super::globals::XdpGlobals;
|
||||
use crate::traffic::prefix::{PrefixKey, PrefixStatsVal};
|
||||
|
||||
use attach::{build_ringbuf, interface_cstr, patch_rodata};
|
||||
use maps::{blacklist_expiry_ns, blacklist_key, unix_ns};
|
||||
|
||||
mod attach;
|
||||
mod maps;
|
||||
|
||||
pub struct XdpFilter {
|
||||
obj: Option<Object>,
|
||||
ringbuf: Option<RingBuffer<'static>>,
|
||||
ifindex: i32,
|
||||
interface: String,
|
||||
globals: XdpGlobals,
|
||||
}
|
||||
|
||||
impl XdpFilter {
|
||||
pub fn new(interface: &str) -> Self {
|
||||
Self {
|
||||
obj: None,
|
||||
ringbuf: None,
|
||||
ifindex: 0,
|
||||
interface: interface.to_string(),
|
||||
globals: XdpGlobals::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Задаёт глобалы для патчинга `.rodata` при следующем `load()`.
|
||||
pub fn set_globals(&mut self, globals: XdpGlobals) {
|
||||
self.globals = globals;
|
||||
}
|
||||
|
||||
pub fn load(&mut self) -> Result<()> {
|
||||
// Диагностика ДО загрузки: fail-fast на неподдерживаемом ядре/драйвере.
|
||||
super::probe::preflight(&self.interface)?;
|
||||
|
||||
let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
|
||||
let mut open_obj = ObjectBuilder::default()
|
||||
.open_memory(bpf_obj)
|
||||
.context("Failed to open XDP object")?;
|
||||
patch_rodata(&mut open_obj, &self.globals)?;
|
||||
let obj = open_obj.load().context("Failed to load XDP object (verifier error?)")?;
|
||||
|
||||
let c_interface = interface_cstr(&self.interface)?;
|
||||
// SAFETY: `c_interface` is a valid, NUL-terminated C string and is kept
|
||||
// alive until the end of this scope (past the `if_nametoindex` call), so
|
||||
// the raw pointer satisfies the `const char *` contract of the libc FFI.
|
||||
// Rust `&str` is NOT NUL-terminated, hence the `CString` conversion above.
|
||||
let ifindex = unsafe { libc::if_nametoindex(c_interface.as_ptr()) };
|
||||
if ifindex == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
bail!("interface '{}' not found: {err}", self.interface);
|
||||
}
|
||||
|
||||
let prog = obj
|
||||
.progs()
|
||||
.find(|p| p.name() == "rampart_universal_filter")
|
||||
.context("XDP program 'rampart_universal_filter' not found")?;
|
||||
Xdp::new(prog.as_fd()).attach(ifindex as i32, XdpFlags::NONE)?;
|
||||
|
||||
let rbuf = build_ringbuf(&obj)?;
|
||||
|
||||
self.obj = Some(obj);
|
||||
self.ringbuf = Some(rbuf);
|
||||
self.ifindex = ifindex as i32;
|
||||
tracing::info!("XDP filter attached to {}", self.interface);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unload(&mut self) -> Result<()> {
|
||||
if let Some(obj) = self.obj.as_ref() {
|
||||
self.detach_program(obj)?;
|
||||
}
|
||||
self.ringbuf = None;
|
||||
self.obj = None;
|
||||
self.ifindex = 0;
|
||||
tracing::info!("XDP filter detached from {}", self.interface);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Detaches the XDP program using the real program fd owned by the loaded
|
||||
/// `Object` (mirroring `load`'s `Xdp::new(prog.as_fd()).attach(..)`). A
|
||||
/// detach failure while a filter is active is surfaced loudly and returned,
|
||||
/// never swallowed — otherwise the kernel keeps dropping packets we no
|
||||
/// longer intend to filter.
|
||||
fn detach_program(&self, obj: &Object) -> Result<()> {
|
||||
let prog = obj
|
||||
.progs()
|
||||
.find(|p| p.name() == "rampart_universal_filter")
|
||||
.context("XDP program 'rampart_universal_filter' not found while detaching")?;
|
||||
if let Err(e) = Xdp::new(prog.as_fd()).detach(self.ifindex, XdpFlags::NONE) {
|
||||
tracing::error!(
|
||||
interface = %self.interface,
|
||||
ifindex = self.ifindex,
|
||||
error = %e,
|
||||
"XDP detach failed while filter was active"
|
||||
);
|
||||
return Err(e).with_context(|| format!("failed to detach XDP from '{}'", self.interface));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn drain_events(&self) {
|
||||
if let Some(rb) = &self.ringbuf {
|
||||
let _ = rb.consume();
|
||||
}
|
||||
}
|
||||
|
||||
fn find_map<'a>(&'a self, name: &str) -> Result<impl MapCore + 'a> {
|
||||
self.obj
|
||||
.as_ref()
|
||||
.context("XDP not loaded")?
|
||||
.maps()
|
||||
.find(|m| m.name() == name)
|
||||
.with_context(|| format!("map '{}' not found", name))
|
||||
}
|
||||
|
||||
pub fn ban_ip(&self, ip: Ipv4Addr, duration_secs: u64) -> Result<()> {
|
||||
self.blacklist_update(32, &ip.octets(), duration_secs)
|
||||
}
|
||||
|
||||
/// Бан CIDR через `blacklist_map` (LPM trie): длина префикса в key[0].
|
||||
///
|
||||
/// # Errors
|
||||
/// XDP не загружен, IPv6-префиксы (ядро их пока не банит) или ошибка карты.
|
||||
pub fn ban_cidr(&self, prefix: IpAddr, prefix_len: u8, duration_secs: u64) -> Result<()> {
|
||||
let IpAddr::V4(net) = prefix else {
|
||||
bail!("ipv6 cidr bans not supported yet");
|
||||
};
|
||||
self.blacklist_update(prefix_len, &net.octets(), duration_secs)
|
||||
}
|
||||
|
||||
fn blacklist_update(&self, prefix_len: u8, v4: &[u8; 4], duration_secs: u64) -> Result<()> {
|
||||
let map = self.find_map("blacklist_map")?;
|
||||
let key = blacklist_key(prefix_len, v4);
|
||||
let expiry_ns = blacklist_expiry_ns(unix_ns(), duration_secs);
|
||||
map.update(&key, &expiry_ns.to_le_bytes(), MapFlags::ANY)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unban_ip(&self, ip: Ipv4Addr) -> Result<()> {
|
||||
let map = self.find_map("blacklist_map")?;
|
||||
let key = blacklist_key(32, &ip.octets());
|
||||
map.delete(&key)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Читает карту `prefix_stats` (агрегаты по префиксам /24 и /64).
|
||||
///
|
||||
/// # Errors
|
||||
/// XDP не загружен, карта отсутствует в объекте или ошибка BPF-чтения.
|
||||
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
|
||||
let map = self.find_map("prefix_stats")?;
|
||||
let mut out = Vec::new();
|
||||
for key in map.keys() {
|
||||
let Ok(kb) = <[u8; 24]>::try_from(key.as_slice()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(val) = map.lookup(&kb, MapFlags::ANY).context("prefix_stats lookup failed")? else {
|
||||
continue;
|
||||
};
|
||||
let Ok(vb) = <[u8; 24]>::try_from(val.as_slice()) else {
|
||||
continue;
|
||||
};
|
||||
out.push((PrefixKey::from_bytes(kb), PrefixStatsVal::from_bytes(vb)));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn get_stats(&self) -> Result<XdpStats> {
|
||||
let map = self.find_map("stats_map")?;
|
||||
let sum = |idx: u32| -> u64 {
|
||||
let key = idx.to_le_bytes();
|
||||
match map.lookup(&key, MapFlags::ANY) {
|
||||
Ok(Some(v)) => v
|
||||
.chunks_exact(8)
|
||||
.map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8")))
|
||||
.sum(),
|
||||
_ => 0,
|
||||
}
|
||||
};
|
||||
Ok(XdpStats {
|
||||
total: sum(0),
|
||||
tcp: sum(1),
|
||||
whitelist: sum(2),
|
||||
blacklist: sum(3),
|
||||
syn_throttle: sum(4),
|
||||
passed: sum(5),
|
||||
dropped: sum(6),
|
||||
udp: sum(7),
|
||||
rate_limit: sum(8),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `XdpFilter` is only ever accessed from the single thread that owns it,
|
||||
// held behind `Arc<Mutex<XdpFilter>>`; that Mutex serialization is the invariant
|
||||
// that makes moving it across threads sound. Auto-`Send` is not derived because
|
||||
// `libbpf_rs::Object` and the `RingBuffer<'static>` wrap non-`Send` libbpf
|
||||
// handles, so the marker is asserted manually under the ownership discipline above.
|
||||
unsafe impl Send for XdpFilter {}
|
||||
|
||||
impl Drop for XdpFilter {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.unload();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue