feat(xdp): IPv6 parity, monotonic ban expiry, per-protocol L4 minimum

IPv6 parity:
- blacklist6_map (LPM trie, 20-byte key) and is_blacklisted6(); the
  native_v6 path now passes the port gate and the L4 checks instead of
  returning XDP_PASS early.
- ban_cidr() covers V4 and V6; gateway bans by /32 or /128; subnet monitor
  bans v6 /64 prefixes; ban_ip() removed (dead code is a bug).
- v6 TCP feeds prefix stats through prefix_key_from_v6 (subnet detector
  now sees IPv6); UDP policy=drop and detect_tcp_bypass apply to v6.
- tests/xdp_ban_v6.rs and scripts/xdp_ipv6_smoke.sh (real netns/verifier).

Bug fixes (both families):
- Ban expiry compared SystemTime epoch-ns against bpf_ktime_get_ns(), so
  bans never expired. Userspace now writes CLOCK_MONOTONIC via
  xdp::monotonic_ns(); regression in tests/xdp_ban_clock.rs.
- The L4 gate required sizeof(struct tcphdr) for every protocol, so short
  UDP datagrams bypassed the port gate and the blacklist. The minimum is
  now per-protocol (UDP 8 bytes); smoke covers it.
This commit is contained in:
Loki 2026-11-15 23:08:05 +01:00
parent a90f0da226
commit b64c329125
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
12 changed files with 420 additions and 36 deletions

30
TODO.md
View file

@ -165,7 +165,35 @@ guard/
`RunExit`, единственный `process::exit` теперь в `main` бина (clippy там не срабатывает).
- [x] Флакающий тест `pow_roundtrip::verifier_rejects_garbage_and_replay` (p≈1/16 из-за
случайного токена) — сидирован, 50 прогонов до (3 fail) / после (0 fail).
- [ ] IPv6-банов в XDP-putи нет (`ban_cidr` bail'ит на v6) — IPv6-паритет (вывод №8).
- [x] IPv6-паритет XDP (вывод №8) — сделано (2026-11-15):
- [x] **C**: `struct lpm_key6 { u32 prefixlen; u8 addr[16]; }` в `common.h`;
`blacklist6_map` (LPM_TRIE, 20-байтный ключ, value `u64` expiry, 100000, NO_PREALLOC) в `maps.h`;
в `universal_filter.c` non-mapped IPv6 больше не возвращает PASS раньше времени: общий L4-парсинг +
порт-гейт, затем блок `if (native_v6)`: `is_blacklisted6` (lookup `prefixlen=128`,
expiry-cleanup как у v4) → DROP; UDP при `G_UDP_POLICY==1` → DROP; `detect_tcp_bypass` → DROP;
TCP → `prefix_key_from_v6` + `update_prefix_stats` (оживило мёртвый код, замкнуло
детектор подсетей на v6); иначе PASS. Ringbuf-события для v6 не шлём (ABI `src_ip` u32).
- [x] **Rust**: `pub fn blacklist6_key(prefix_len: u8, &[u8;16]) -> [u8;20]` (prefixlen LE в 0..4,
addr network order в 4..20); `blacklist6_update`; `ban_cidr` матчит V4/V6;
`gateway.rs::xdp_ban` → `ban_cidr(ip, 32|128, dur)` для обоих семейств; `ban_ip` удалён
(после перевода gateway вызовов не осталось — «мёртвый код = баг»), `noop.rs` синхронизирован.
- [x] **Тесты**: `tests/xdp_ban_v6.rs` (layout ключа `/64` и `/128`, network order);
`scripts/xdp_ipv6_smoke.sh` — реальный netns+verifier smoke (без бана pass → с баном
blacklist+drop → после снятия снова pass), проверен на ядре 7.3.4.
- Non-goals (позже): conntrack/throttle/UDP rate-limit (`policy==2`)/RST-challenge для нативного v6
(нужны 128-битные flow/throttle-ключи); whitelist6 (у `whitelist_map` нет писателя даже для v4);
ringbuf-события для v6; unban v6.
- [x] **Expiry бана из userspace не работал в ядре** (найден и починен 2026-11-15, касался v4 и v6):
`blacklist_expiry_ns` писал `SystemTime` (epoch ns ≈ 1.7e18), а C сравнивает с
`bpf_ktime_get_ns()` (monotonic ≈ uptime) — бан жил до перезагрузки. Теперь userspace пишет
`CLOCK_MONOTONIC`-ns (`xdp::monotonic_ns`), регрессия — `tests/xdp_ban_clock.rs` и expiry-фаза
в `scripts/xdp_ipv6_smoke.sh`.
- [x] **Короткий L4-хвост обходил blacklist** (найден и починен 2026-11-15, v4 и v6):
`universal_filter.c` требовал `sizeof(struct tcphdr)` (20 байт) для всех протоколов, иначе
ранний `XDP_PASS` — UDP-датаграмма короче 20 байт не доходила до порт-гейта и blacklist.
Теперь минимум считается по протоколу (`sizeof(struct udphdr)` для UDP); регрессия —
«короткая датаграмма» в `scripts/xdp_ipv6_smoke.sh`. TCP-путь не изменился: там по-прежнему
требуется полный `struct tcphdr`.
## 3. Backlog

183
scripts/xdp_ipv6_smoke.sh Executable file
View file

@ -0,0 +1,183 @@
#!/usr/bin/env bash
# Функциональный smoke XDP-банов на РЕАЛЬНОМ ядре (netns + veth + verifier).
#
# Что проверяет:
# 1. verifier принимает universal_filter.o;
# 2. native-IPv6 без бана проходит, с записью /128 в blacklist6_map — дропается;
# 3. короткая UDP-датаграмма (<20 байт L4) тоже дропается — раньше она уходила
# в XDP_PASS мимо blacklist (проверка длины была рассчитана на TCP);
# 4. то же для IPv4 (общий L4-гейт);
# 5. expiry: бан с монотонным TTL реально истекает в ядре (раньше userspace
# писал epoch-ns, а C сравнивал с bpf_ktime_get_ns() — бан жил вечно).
#
# Требует root/CAP_BPF+CAP_NET_ADMIN, bpftool, clang, python3.
# Запуск: sudo bash scripts/xdp_ipv6_smoke.sh
set -u
NS=rampart_v6_smoke
DEV0=rth6
DEV1=rtap6
HOST6=fd00::1
NS6=fd00::2
HOST4=10.99.0.1
NS4=10.99.0.2
PORT=4444
OBJ=$(mktemp /tmp/rampart_v6_smoke.XXXXXX.o)
PIN=/sys/fs/bpf/rampart_v6_smoke
PASS=1
fail() { echo "FAIL: $1"; PASS=0; }
ok() { echo "ok: $1"; }
cleanup() {
bpftool net detach xdp dev "$DEV0" 2>/dev/null
rm -f "$PIN" "$OBJ"
ip link del "$DEV0" 2>/dev/null
ip netns del "$NS" 2>/dev/null
}
trap cleanup EXIT
[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; }
cd "$(dirname "$0")/.." || exit 2
clang -O2 -g -target bpf -mcpu=v3 -c xdp/core/universal_filter.c -o "$OBJ" \
-Ixdp -Ixdp/core -Ixdp/hooks -I/usr/include/x86_64-linux-gnu \
|| { echo "clang: не собралось"; exit 1; }
ok "clang: universal_filter.c собран"
ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; }
ip link add "$DEV0" type veth peer name "$DEV1" || exit 2
ip link set "$DEV1" netns "$NS"
ip -6 addr add "$HOST6/64" dev "$DEV0"
ip addr add "$HOST4/24" dev "$DEV0"
ip link set "$DEV0" up
ip -n "$NS" -6 addr add "$NS6/64" dev "$DEV1"
ip -n "$NS" addr add "$NS4/24" dev "$DEV1"
ip -n "$NS" link set "$DEV1" up
ip -n "$NS" link set lo up
ok "netns $NS + veth ($HOST6/$HOST4 <-> $NS6/$NS4)"
bpftool prog load "$OBJ" "$PIN" type xdp || { echo "verifier отверг программу"; exit 1; }
bpftool net attach xdp pinned "$PIN" dev "$DEV0" || exit 1
ok "verifier принял программу, attach на $DEV0"
IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ')
B4=""
B6=""
ST=""
for id in $IDS; do
desc=$(bpftool map show id "$id" 2>/dev/null)
case "$desc" in
*"name blacklist6_map"*) B6=$id ;;
*"name blacklist_map"*) B4=$id ;;
*"name stats_map"*) ST=$id ;;
esac
done
[ -n "$B4" ] && [ -n "$B6" ] && [ -n "$ST" ] || { echo "карты не найдены"; exit 1; }
ok "blacklist_map id=$B4, blacklist6_map id=$B6, stats_map id=$ST"
# Ключи LPM: prefixlen (u32 LE) + адрес в network order.
KEY6="80 00 00 00 fd 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02"
KEY4="20 00 00 00 0a 63 00 02"
send6() { # $1 = размер payload
ip netns exec "$NS" python3 -c "
import socket
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.sendto(b'x' * $1, ('$HOST6', $PORT))
"
}
send4() {
ip netns exec "$NS" python3 -c "
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b'x' * $1, ('$HOST4', $PORT))
"
}
# Суммы per-CPU счётчиков (только ненулевые).
stats() {
bpftool -j map dump id "$ST" | python3 -c "
import json, sys
names = {0: 'total', 1: 'tcp', 2: 'whitelist', 3: 'blacklist', 4: 'syn_thr',
5: 'pass', 6: 'drop', 7: 'udp', 8: 'rate', 9: 'chal_sent'}
out = {}
for e in json.load(sys.stdin):
k = names.get(e['formatted']['key'])
if k is not None:
out[k] = sum(v['value'] for v in e['formatted']['values'])
print(' '.join(f'{k}={v}' for k, v in out.items() if v) or 'все нули')
"
}
metric() { stats | tr ' ' '\n' | sed -n "s/^$1=//p" | head -1; }
mono_ns_hex() { # монотонные ns + $1 секунд, 8 байт little-endian
python3 -c "
import time
ns = time.clock_gettime_ns(time.CLOCK_MONOTONIC) + $1 * 1_000_000_000
print(' '.join(f'{b:02x}' for b in ns.to_bytes(8, 'little')))
"
}
# ── Фаза 1: IPv6 ──
pass0=$(metric pass)
for _ in 1 2 3; do send6 100; done
sleep 0.5
pass1=$(metric pass)
[ "${pass1:-0}" -gt "${pass0:-0}" ] \
&& ok "v6 без бана проходит (pass $pass0 -> $pass1)" \
|| fail "v6 без бана не проходит ($(stats))"
drop0=$(metric drop)
bpftool map update id "$B6" key hex $KEY6 value hex ff ff ff ff ff ff ff ff || fail "v6 map update"
for _ in 1 2 3; do send6 100; done
for _ in 1 2 3; do send6 1; done # короткая датаграмма
sleep 0.5
drop1=$(metric drop)
[ "${drop1:-0}" -ge $((${drop0:-0} + 6)) ] \
&& ok "v6 с баном дропает обычные и короткие (drop $drop0 -> $drop1)" \
|| fail "v6 бан не дропает всё ($(stats))"
bpftool map delete id "$B6" key hex $KEY6 || fail "v6 map delete"
pass2=$(metric pass)
for _ in 1 2 3; do send6 100; done
sleep 0.5
pass3=$(metric pass)
[ "${pass3:-0}" -gt "${pass2:-0}" ] \
&& ok "v6 после снятия бана проходит (pass $pass2 -> $pass3)" \
|| fail "v6 после снятия бана не проходит ($(stats))"
# ── Фаза 2: IPv4 (общий L4-гейт) ──
drop0=$(metric drop)
bpftool map update id "$B4" key hex $KEY4 value hex ff ff ff ff ff ff ff ff || fail "v4 map update"
for _ in 1 2 3; do send4 1; done # только короткие — регрессия на min_l4
sleep 0.5
drop1=$(metric drop)
[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \
&& ok "v4 короткие датаграммы дропаются баном (drop $drop0 -> $drop1)" \
|| fail "v4 короткая датаграмма прошла мимо бана ($(stats))"
bpftool map delete id "$B4" key hex $KEY4 || fail "v4 map delete"
# ── Фаза 3: expiry бана (монотонные часы) ──
TTL=2
bpftool map update id "$B6" key hex $KEY6 value hex $(mono_ns_hex $TTL) || fail "expiry update"
drop0=$(metric drop)
for _ in 1 2 3; do send6 100; done
sleep 0.5
drop1=$(metric drop)
[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \
&& ok "бан с TTL=${TTL}s дропает сразу (drop $drop0 -> $drop1)" \
|| fail "свежий бан не дропает ($(stats))"
sleep $((TTL + 2))
drop2=$(metric drop); pass2=$(metric pass)
for _ in 1 2 3; do send6 100; done
sleep 0.5
drop3=$(metric drop); pass3=$(metric pass)
[ "${drop3:-0}" -eq "${drop2:-0}" ] && [ "${pass3:-0}" -gt "${pass2:-0}" ] \
&& ok "бан истёк по монотонным часам (pass $pass2 -> $pass3, drop $drop2 -> $drop3)" \
|| fail "бан не истёк (pass $pass2 -> $pass3, drop $drop2 -> $drop3)"
[ "$PASS" = 1 ] && echo "PASS: XDP-баны (v4/v6, короткий L4, expiry) работают на живом ядре" || echo "FAIL"
[ "$PASS" = 1 ]

View file

@ -202,12 +202,14 @@ impl Gateway {
let Some(xdp) = &self.xdp else {
return;
};
let IpAddr::V4(ip_v4) = ip else {
return;
};
match xdp.lock().expect("xdp lock poisoned").ban_ip(ip_v4, duration_secs) {
Ok(()) => tracing::debug!("xdp ban {ip_v4} for {duration_secs}s"),
Err(e) => tracing::warn!("xdp ban failed for {ip_v4}: {e}"),
let prefix_len = if ip.is_ipv4() { 32 } else { 128 };
match xdp
.lock()
.expect("xdp lock poisoned")
.ban_cidr(ip, prefix_len, duration_secs)
{
Ok(()) => tracing::debug!("xdp ban {ip} for {duration_secs}s"),
Err(e) => tracing::warn!("xdp ban failed for {ip}: {e}"),
}
}

View file

@ -1,13 +1,23 @@
use super::XdpFilter;
use anyhow::{Result, bail};
use anyhow::Result;
use libbpf_rs::{MapCore, MapFlags};
use std::net::{IpAddr, Ipv4Addr};
pub(super) fn unix_ns() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64
/// Monotonic clock in ns since boot — the same clock as `bpf_ktime_get_ns()`,
/// which is what the XDP program compares ban expiry against. `SystemTime`
/// (epoch ns) is ~50 years larger, so bans written with it never expired.
///
/// # Panics
/// Never: `clock_gettime(CLOCK_MONOTONIC)` cannot fail on Linux.
#[must_use]
pub fn monotonic_ns() -> u64 {
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: `ts` is a valid, writable `timespec` and CLOCK_MONOTONIC is
// always available on Linux (the only target of the `xdp` feature).
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
let secs = u64::try_from(ts.tv_sec).unwrap_or(0);
secs.saturating_mul(1_000_000_000)
.saturating_add(u64::try_from(ts.tv_nsec).unwrap_or(0))
}
/// Encodes an LPM-trie key for `blacklist_map`: prefix length in byte 0 and the
@ -19,29 +29,47 @@ pub(super) fn blacklist_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] {
key
}
/// Absolute ban expiry in ns-since-epoch, saturating so an absurd duration
/// Encodes an LPM-trie key for `blacklist6_map`: prefix length as a
/// little-endian u32 in bytes 0..4 and the 16-byte IPv6 address in network
/// order in bytes 4..20 (20 bytes total, matching the C `struct lpm_key6`).
pub fn blacklist6_key(prefix_len: u8, v6: &[u8; 16]) -> [u8; 20] {
let mut key = [0u8; 20];
key[0] = prefix_len;
key[4..20].copy_from_slice(v6);
key
}
/// Absolute ban expiry on the monotonic clock, 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))
}
impl XdpFilter {
pub fn ban_ip(&self, ip: Ipv4Addr, duration_secs: u64) -> Result<()> {
self.blacklist_update(32, &ip.octets(), duration_secs)
}
/// Adds a CIDR ban to the LPM trie. IPv6 enforcement is not supported yet.
/// Adds a CIDR ban to the matching LPM trie: `blacklist_map` for IPv4,
/// `blacklist6_map` for IPv6.
///
/// # Errors
/// 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<()> {
let IpAddr::V4(net) = prefix else {
bail!("ipv6 cidr bans not supported yet");
};
self.blacklist_update(prefix_len, &net.octets(), duration_secs)
match prefix {
IpAddr::V4(net) => self.blacklist_update(prefix_len, &net.octets(), duration_secs),
IpAddr::V6(net) => self.blacklist6_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);
let expiry_ns = blacklist_expiry_ns(monotonic_ns(), duration_secs);
map.update(&key, &expiry_ns.to_le_bytes(), MapFlags::ANY)?;
Ok(())
}
fn blacklist6_update(&self, prefix_len: u8, v6: &[u8; 16], duration_secs: u64) -> Result<()> {
let map = self.find_map("blacklist6_map")?;
let key = blacklist6_key(prefix_len, v6);
let expiry_ns = blacklist_expiry_ns(monotonic_ns(), duration_secs);
map.update(&key, &expiry_ns.to_le_bytes(), MapFlags::ANY)?;
Ok(())
}

View file

@ -16,6 +16,8 @@ mod attach;
pub(crate) mod events;
mod maps;
pub use maps::{blacklist6_key, monotonic_ns};
pub struct XdpFilter {
obj: Option<Object>,
ringbuf: Option<RingBuffer<'static>>,

View file

@ -19,9 +19,13 @@ mod filter;
#[cfg(feature = "xdp")]
pub use filter::XdpFilter;
#[cfg(feature = "xdp")]
pub use filter::blacklist6_key;
#[cfg(feature = "xdp")]
pub use filter::events::{
AutoBanConfig, BanAction, XDP_EVENT_LEN, XdpEvent, XdpEventKind, auto_ban_decision, parse_xdp_event,
};
#[cfg(feature = "xdp")]
pub use filter::monotonic_ns;
#[cfg(feature = "xdp")]
pub use probe::XdpMetrics;

View file

@ -16,9 +16,6 @@ impl XdpFilter {
Ok(())
}
pub fn drain_events(&self) {}
pub fn ban_ip(&self, _ip: Ipv4Addr, _duration_secs: u64) -> Result<()> {
Ok(())
}
pub fn ban_cidr(&self, _prefix: IpAddr, _prefix_len: u8, _duration_secs: u64) -> Result<()> {
Ok(())
}

29
tests/xdp_ban_clock.rs Normal file
View file

@ -0,0 +1,29 @@
//! Часы бана: XDP сравнивает expiry с `bpf_ktime_get_ns()` (монотонные ns
//! с загрузки), поэтому userspace обязан писать то же самое. Регрессия:
//! раньше писался `SystemTime` (epoch ns ≈ 1.7e18), и бан не истекал никогда.
#![cfg(feature = "xdp")]
use rampart::xdp::monotonic_ns;
fn clock_monotonic_ns() -> u64 {
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: `ts` — валидный writable `timespec`; CLOCK_MONOTONIC на Linux
// поддерживается всегда (xdp-фича собирается только под Linux).
let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
assert_eq!(rc, 0, "clock_gettime(CLOCK_MONOTONIC) failed");
let secs = u64::try_from(ts.tv_sec).expect("tv_sec fits u64");
let nanos = u64::try_from(ts.tv_nsec).expect("tv_nsec fits u64");
secs * 1_000_000_000 + nanos
}
#[test]
fn ban_clock_is_monotonic_not_wall_clock() {
let expected = clock_monotonic_ns();
let got = monotonic_ns();
let diff = got.abs_diff(expected);
assert!(
diff < 5_000_000_000,
"monotonic_ns must read CLOCK_MONOTONIC: got {got}, expected ~{expected}"
);
}

38
tests/xdp_ban_v6.rs Normal file
View file

@ -0,0 +1,38 @@
//! Раскладка ключа `blacklist6_map` (LPM-trie): префикс-длина в байтах 0..4
//! little-endian + 16 байт адреса в network order (байты 4..20).
//! Ядро не нужно: проверяется чистая функция кодирования ключа.
#![cfg(feature = "xdp")]
use rampart::xdp::blacklist6_key;
const ADDR_2001_DB8_1: [u8; 16] = [0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
#[test]
fn key_layout_for_128_prefix() {
let key = blacklist6_key(128, &ADDR_2001_DB8_1);
assert_eq!(key.len(), 20);
assert_eq!(key[0], 128, "prefixlen goes first");
assert_eq!(key[1..4], [0, 0, 0], "u32 LE padding stays zero");
assert_eq!(key[4..20], ADDR_2001_DB8_1, "address kept in network order");
}
#[test]
fn key_layout_for_64_prefix() {
let key = blacklist6_key(64, &ADDR_2001_DB8_1);
assert_eq!(key[0], 64);
assert_eq!(key[1..4], [0, 0, 0]);
assert_eq!(key[4..20], ADDR_2001_DB8_1);
}
#[test]
fn leading_zero_address_is_not_confused_with_prefix_len() {
// ::1 — 15 нулевых байт перед единицей: ключ не должен «съесть» ни одного.
let key = blacklist6_key(128, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(key[0], 128, "prefixlen is not overwritten by the address");
assert_eq!(key[1..4], [0, 0, 0]);
assert_eq!(key[4..19], [0u8; 15]);
assert_eq!(key[19], 1);
}

View file

@ -50,6 +50,12 @@ struct lpm_key {
__u32 ip;
};
// ── LPM key for IPv6 blacklist (format of bpf_lpm_trie_key, 20 bytes) ──
struct lpm_key6 {
__u32 prefixlen;
__u8 addr[16];
};
// ── Ringbuf event (userspace receives these) ──
enum event_type {
EVENT_BAN = 0,

View file

@ -11,6 +11,16 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC);
} blacklist_map SEC(".maps");
// 🔗 IPv6 blacklist (LPM_TRIE, 128-bit prefix keys)
// Same value/expiry contract as blacklist_map
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 100000);
__type(key, struct lpm_key6);
__type(value, __u64); // ban expiry (ktime_ns)
__uint(map_flags, BPF_F_NO_PREALLOC);
} blacklist6_map SEC(".maps");
// 🔗 Whitelist (LPM_TRIE for CIDR) — checked before any filter
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);

View file

@ -72,6 +72,22 @@ static __always_inline __u8 is_blacklisted(__u32 src_ip, __u64 now)
return 0;
}
// ── IPv6 blacklist lookup with expiry; removes expired entries ──
// Key layout mirrors bpf_lpm_trie_key: prefixlen (host order) + 16 addr bytes.
static __always_inline __u8 is_blacklisted6(const __u8 addr[16], __u64 now)
{
struct lpm_key6 key = {};
key.prefixlen = 128;
__builtin_memcpy(key.addr, addr, 16);
__u64 *ban_until = bpf_map_lookup_elem(&blacklist6_map, &key);
if (!ban_until)
return 0;
if (*ban_until > now)
return 1;
bpf_map_delete_elem(&blacklist6_map, &key); // expired — clean up
return 0;
}
static __always_inline void ban_ip(__u32 src_ip, __u64 until)
{
struct lpm_key key = { .prefixlen = 32, .ip = src_ip };
@ -127,6 +143,8 @@ int rampart_universal_filter(struct xdp_md *ctx)
__u32 dst_ip = 0;
__u8 l4_proto = 0;
__u8 is_ipv6 = 0;
__u8 native_v6 = 0;
__u8 src6[16];
if (eth->h_proto == bpf_htons(ETH_P_IP)) {
struct iphdr *ip = (void *)(eth + 1);
@ -164,16 +182,20 @@ int rampart_universal_filter(struct xdp_md *ctx)
ip6->daddr.in6_u.u6_addr32[0] != 0 ||
ip6->daddr.in6_u.u6_addr32[1] != 0 ||
ip6->daddr.in6_u.u6_addr32[2] != bpf_htonl(0xFFFF)) {
// Non-mapped IPv6 — pass for now (not supported)
return XDP_PASS;
}
// Native IPv6 — no 32-bit representable address, handled separately
// after the generic L4/port gates; must NOT touch v4 maps.
native_v6 = 1;
is_ipv6 = 1;
l4_proto = ip6->nexthdr;
__builtin_memcpy(src6, &ip6->saddr, 16);
} else {
// FIX: source address must come from saddr, never daddr
src_ip = ip6->saddr.in6_u.u6_addr32[3];
dst_ip = ip6->daddr.in6_u.u6_addr32[3];
l4_proto = ip6->nexthdr;
is_ipv6 = 1;
}
}
// ── Parse L4 header ──
__u8 ip_hdr_len;
@ -189,7 +211,13 @@ int rampart_universal_filter(struct xdp_md *ctx)
ip_hdr_len = ip->ihl * 4;
}
if ((void *)l4 + sizeof(struct tcphdr) > data_end)
// Minimum L4 header per protocol: a short UDP datagram used to fall through
// to XDP_PASS because the check was sized for TCP, letting it bypass the
// blacklist entirely. IPv6 native fragmentation is already filtered above
// (nexthdr must be TCP/UDP), so a short UDP header here is a real datagram.
__u32 min_l4 = (l4_proto == IPPROTO_TCP) ? sizeof(struct tcphdr)
: sizeof(struct udphdr);
if ((void *)l4 + min_l4 > data_end)
return XDP_PASS;
// ── Port range check (protected services) ──
@ -209,6 +237,35 @@ int rampart_universal_filter(struct xdp_md *ctx)
__u64 now = bpf_ktime_get_ns();
// ── Native IPv6: blacklist + cheap L4 policy (no stateful v6 yet) ──
if (native_v6) {
if (is_blacklisted6(src6, now)) {
inc_blacklist();
inc_drop();
return XDP_DROP;
}
if (l4_proto == IPPROTO_UDP) {
if (G_UDP_POLICY == 1) { // drop
inc_drop();
return XDP_DROP;
}
inc_pass();
return XDP_PASS; // policy 2 (rate-limit) needs a 128-bit key — not supported for v6
}
// TCP: forged-flag combos are L4-generic, no state needed
if (detect_tcp_bypass((struct tcphdr *)l4)) {
inc_drop();
return XDP_DROP;
}
// Per-prefix stats (/64) — feeds the subnet detector for IPv6
struct prefix_key pkey6;
prefix_key_from_v6(&pkey6, src6);
struct tcphdr *tcp6 = (struct tcphdr *)l4;
update_prefix_stats(&pkey6, (tcp6->syn && !tcp6->ack) ? 1 : 0, now);
inc_pass();
return XDP_PASS;
}
// ── Whitelist check (CIDR) — before any filtering ──
struct lpm_key wl_key = { .prefixlen = 32, .ip = src_ip };
if (bpf_map_lookup_elem(&whitelist_map, &wl_key)) {