feat(xdp): IPv6 UDP rate limit, working loader; English comments and docs

XDP behaviour:
- udp_rate_limit6 (LRU, full 128-bit source key) plus throttle_hit6, so
  udp_policy = "rate-limit" applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

Loader (XDP could never load before this):
- .rodata is one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Before, a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs checks map names and .rodata size without root.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, nav buttons,
  compact TOC and copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6
  coverage; testing.md covers the real-kernel smoke; stale links removed.
This commit is contained in:
Loki 2026-11-15 23:50:52 +01:00
parent b64c329125
commit a8a3057719
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
104 changed files with 2155 additions and 1030 deletions

View file

@ -12,13 +12,24 @@
#define IP_OFFSET 0x1FFF
#define IP_MF 0x2000
// ── Protocol-agnostic TCP state machine ──
/**
* Protocol-agnostic TCP connection states.
*
* A connection enters the map on the first bare SYN and advances only when
* the handshake completes; payload inspection is reachable from ESTABLISHED
* only, so no state can be skipped.
*/
enum connection_state {
STATE_SYN_RECEIVED = 0, // SYN seen, waiting for ACK (handshake completing)
STATE_ESTABLISHED = 1, // handshake done; payload handed to proto_hook()
};
// ── Flow key (4-tuple for connection tracking) ──
/**
* Flow key identifying one connection: the classic 4-tuple.
*
* Addresses and ports stay in network byte order; this key is only ever
* built and compared inside the BPF program.
*/
struct flow_key {
__u32 src_ip;
__u32 dst_ip;
@ -26,9 +37,14 @@ struct flow_key {
__u16 dst_port;
};
// ── Connection tracking entry ──
// LRU maps evict stale entries automatically when full; RST/FIN removes
// entries explicitly. last_seen supports future timer-based idle cleanup.
/**
* Connection tracking entry.
*
* LRU maps evict stale entries automatically when full; RST/FIN removes
* entries explicitly. last_seen supports future timer-based idle cleanup.
* expected_seq is the next in-order sequence number we accept on the
* server-to-client direction.
*/
struct conntrack_entry {
__u32 state;
__u32 expected_seq;
@ -38,25 +54,42 @@ struct conntrack_entry {
__u8 fails;
};
// ── SYN / UDP throttle entry ──
/**
* Fixed-window throttle state for one source address.
*
* window_start is a bpf_ktime_get_ns() timestamp, so windows survive
* wall-clock jumps; hits resets whenever the window rolls over.
*/
struct throttle_entry {
__u64 window_start;
__u32 hits;
};
// ── LPM key for blacklist/whitelist ──
/**
* LPM trie key for IPv4 blacklist and whitelist entries.
*
* prefixlen is in host byte order, the address in network byte order, which
* is the layout the kernel expects for BPF_MAP_TYPE_LPM_TRIE.
*/
struct lpm_key {
__u32 prefixlen;
__u32 ip;
};
// ── LPM key for IPv6 blacklist (format of bpf_lpm_trie_key, 20 bytes) ──
/**
* LPM trie key for IPv6 blacklist entries.
*
* Same layout as bpf_lpm_trie_key: host-order prefix length followed by 16
* address bytes, 20 bytes in total.
*/
struct lpm_key6 {
__u32 prefixlen;
__u8 addr[16];
};
// ── Ringbuf event (userspace receives these) ──
/**
* Event kinds that userspace can receive and react to.
*/
enum event_type {
EVENT_BAN = 0,
EVENT_RATE_LIMIT = 1,
@ -64,6 +97,13 @@ enum event_type {
EVENT_CONN_DROP = 3,
};
/**
* Ring buffer event record handed to userspace.
*
* src_ip is always IPv4 (or the low 32 bits of an IPv4-mapped address)
* because the record format is part of the userspace ABI; native IPv6
* drops are therefore not reported.
*/
struct xdp_event {
__u32 type;
__u32 src_ip;
@ -71,7 +111,14 @@ struct xdp_event {
__u64 timestamp;
};
// ── Bounds check macros (dual-bounds для verifier) ──
/**
* Dual bounds check for the verifier.
*
* A read of sz bytes at ptr is rejected unless it fits inside both the
* provisional end pointer (pend) and the packet tail (dend). barrier_var()
* keeps ptr in a register so the verifier does not lose the narrowed range
* on the second comparison. The caller must provide an error: label.
*/
#define CHECK_BOUNDS_OR_RETURN(ptr, sz, pend, dend) \
do { \
if ((void *)(ptr) + (sz) > (void *)(dend)) \
@ -81,15 +128,35 @@ struct xdp_event {
goto error; \
} while (0)
/**
* Pin a pointer in a register.
*
* The empty asm block gives the value a register home, which stops the
* verifier from widening a range it already proved.
*/
#define barrier_var(var) asm volatile("" : "+r"(var))
// ── Ringbuf for events → userspace (declared here for push_event) ──
/**
* Ring buffer carrying events to userspace.
*
* Declared next to push_event() rather than in maps.h so every program that
* includes this header gets the producer side without extra wiring.
*/
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24);
} events_ringbuf SEC(".maps");
// ── Event push to ringbuf ──
/**
* Publish one event to userspace.
*
* Fire-and-forget: a full or missing ring buffer silently drops the record
* because event reporting must never change the packet verdict.
*
* @param type event kind stored in the record
* @param src_ip source address, network byte order
* @param meta event-specific value, e.g. the threshold that fired
*/
static __always_inline void push_event(enum event_type type, __u32 src_ip, __u32 meta)
{
struct xdp_event *e = bpf_ringbuf_reserve(&events_ringbuf, sizeof(struct xdp_event), 0);

View file

@ -1,47 +1,138 @@
#ifndef RAMPART_CONFIG_H
#define RAMPART_CONFIG_H
// ⚙️ Runtime configurable globals (patched by Rust loader)
// These are volatile const — compiler replaces reads with immediate values
// after loader writes to .rodata section
/**
* Runtime-tunable filter configuration.
*
* The whole configuration lives in one aggregate in .rodata so that its
* layout is fixed by this C declaration and by the mirrored #[repr(C)]
* XdpGlobals in Rust, not by the linker's choice of symbol order. Separate
* globals used to be reordered by clang, which silently broke hardcoded
* offsets; a single aggregated object is emitted whole and stays stable.
*
* The object is volatile const: the loader patches the .rodata map before
* the program is loaded, so the compiler must not constant-fold reads.
*/
struct rampart_config {
// Protected port range: packets to ports outside it bypass the filter
// entirely (XDP_PASS before any counting). Default protects every
// TCP/UDP port; narrow it via loader patching for dedicated-edge setups.
__u16 start_port; // 1
__u16 end_port; // 65535
// ── Port range ──
// Protected port range: packets to ports OUTSIDE this range bypass the
// filter (XDP_PASS before any counting/filtering). Default protects all
// TCP/UDP ports; narrow it via loader patching for dedicated-edge setups.
static volatile const __u16 G_START_PORT = 1;
static volatile const __u16 G_END_PORT = 65535;
// SYN throttle window: hit count per source, window length, ban length.
__u32 syn_hit_count; // 10 max SYNs / window
__u64 syn_window_ns; // 3 sec
__u64 syn_ban_duration_ns; // 60 sec
// ── SYN throttle ──
static volatile const __u32 G_SYN_HIT_COUNT = 10; // max SYNs / window
static volatile const __u64 G_SYN_WINDOW_NS = 3000000000ULL; // 3 sec
static volatile const __u64 G_SYN_BAN_DURATION_NS = 60000000000ULL; // 60 sec
// Idle timeouts. The XDP path does not read them yet; they are part of
// the loader ABI so userspace can drive timer-based cleanup.
__u64 conntrack_idle_ns; // 30 sec
__u64 player_idle_ns; // 120 sec
// ── Idle timeouts ──
static volatile const __u64 G_CONNTRACK_IDLE_NS = 30000000000ULL; // 30 sec
static volatile const __u64 G_PLAYER_IDLE_NS = 120000000000ULL; // 120 sec
// Default ban duration userspace applies to new blacklist entries.
__u64 ban_duration_ns; // 5 min
// ── Blacklist default ban duration ──
static volatile const __u64 G_BAN_DURATION_NS = 300000000000ULL; // 5 min
// Out-of-order payload packets tolerated before the connection is cut.
__u8 max_out_of_order; // 4
// ── Max out-of-order packets before dropping connection ──
static volatile const __u8 G_MAX_OUT_OF_ORDER = 4;
// UDP policy and its rate-limit window.
__u8 udp_policy; // 0 = pass, 1 = drop, 2 = rate-limit
__u32 udp_hit_count; // 100 max packets / window
__u64 udp_window_ns; // 1 sec
// ── UDP policy ──
static volatile const __u8 G_UDP_POLICY = 0; // 0 = pass, 1 = drop, 2 = rate-limit
static volatile const __u32 G_UDP_HIT_COUNT = 100; // max packets / window
static volatile const __u64 G_UDP_WINDOW_NS = 1000000000ULL; // 1 sec
// Feature switches read on the hot path.
__u8 feature_syn_throttle; // 1
__u8 feature_events; // 1
// ── Feature flags ──
static volatile const __u8 G_FEATURE_SYN_THROTTLE = 1;
static volatile const __u8 G_FEATURE_EVENTS = 1;
// RST-challenge (Oubliette-style liveness proof). 0 disables it, leaving
// a single branch and zero cost for legitimate traffic. The secret is
// patched by the loader at attach time; the value below is a placeholder.
__u8 syn_challenge_enabled; // 0
__u64 challenge_secret; // 0xA5A55A5A5A5AA5A5
__u32 challenge_timeout_ms; // 3000 pending TTL
__u64 challenge_verified_ttl_ns; // 5 min
};
// ── RST-challenge (Oubliette liveness proof) ──
// 0 = disabled: single branch, zero cost for legitimate traffic.
// Secret is patched by the loader at attach time (default is a placeholder).
static volatile const __u8 G_SYN_CHALLENGE_ENABLED = 0;
static volatile const __u64 G_CHALLENGE_SECRET = 0xA5A55A5A5A5AA5A5ULL;
static volatile const __u32 G_CHALLENGE_TIMEOUT_MS = 3000; // pending TTL
static volatile const __u64 G_CHALLENGE_VERIFIED_TTL_NS = 300000000000ULL; // 5 min
/**
* Default configuration image shipped inside the object file.
*
* volatile const keeps every read tied to the patched .rodata map instead of
* being folded into a constant at compile time.
*/
static volatile const struct rampart_config G = {
.start_port = 1,
.end_port = 65535,
.syn_hit_count = 10,
.syn_window_ns = 3000000000ULL,
.syn_ban_duration_ns = 60000000000ULL,
.conntrack_idle_ns = 30000000000ULL,
.player_idle_ns = 120000000000ULL,
.ban_duration_ns = 300000000000ULL,
.max_out_of_order = 4,
.udp_policy = 0,
.udp_hit_count = 100,
.udp_window_ns = 1000000000ULL,
.feature_syn_throttle = 1,
.feature_events = 1,
.syn_challenge_enabled = 0,
.challenge_secret = 0xA5A55A5A5A5AA5A5ULL,
.challenge_timeout_ms = 3000,
.challenge_verified_ttl_ns = 300000000000ULL,
};
/**
* ABI guard for the configuration struct.
*
* The byte layout is part of the loader contract: src/xdp/globals.rs writes
* fields at offset_of!(XdpGlobals, ..), and the real-kernel smoke patches
* udp_policy and udp_hit_count by raw offset. Reordering or resizing a field
* must break the build instead of silently misconfiguring the filter.
*/
_Static_assert(sizeof(struct rampart_config) == 96,
"sizeof(struct rampart_config) must match XdpGlobals");
_Static_assert(__builtin_offsetof(struct rampart_config, start_port) == 0, "start_port");
_Static_assert(__builtin_offsetof(struct rampart_config, end_port) == 2, "end_port");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_hit_count) == 4, "syn_hit_count");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_window_ns) == 8, "syn_window_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_ban_duration_ns) == 16, "syn_ban_duration_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, conntrack_idle_ns) == 24, "conntrack_idle_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, player_idle_ns) == 32, "player_idle_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, ban_duration_ns) == 40, "ban_duration_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, max_out_of_order) == 48, "max_out_of_order");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_policy) == 49, "udp_policy");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_hit_count) == 52, "udp_hit_count");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_window_ns) == 56, "udp_window_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, feature_syn_throttle) == 64, "feature_syn_throttle");
_Static_assert(__builtin_offsetof(struct rampart_config, feature_events) == 65, "feature_events");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_challenge_enabled) == 66, "syn_challenge_enabled");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_secret) == 72, "challenge_secret");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_timeout_ms) == 80, "challenge_timeout_ms");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_verified_ttl_ns) == 88, "challenge_verified_ttl_ns");
/**
* Read-only aliases that keep the hot path short.
*
* They expand to field accesses on G, so they remain live reads of the
* patched .rodata and cost nothing at runtime.
*/
#define G_START_PORT G.start_port
#define G_END_PORT G.end_port
#define G_SYN_HIT_COUNT G.syn_hit_count
#define G_SYN_WINDOW_NS G.syn_window_ns
#define G_SYN_BAN_DURATION_NS G.syn_ban_duration_ns
#define G_CONNTRACK_IDLE_NS G.conntrack_idle_ns
#define G_PLAYER_IDLE_NS G.player_idle_ns
#define G_BAN_DURATION_NS G.ban_duration_ns
#define G_MAX_OUT_OF_ORDER G.max_out_of_order
#define G_UDP_POLICY G.udp_policy
#define G_UDP_HIT_COUNT G.udp_hit_count
#define G_UDP_WINDOW_NS G.udp_window_ns
#define G_FEATURE_SYN_THROTTLE G.feature_syn_throttle
#define G_FEATURE_EVENTS G.feature_events
#define G_SYN_CHALLENGE_ENABLED G.syn_challenge_enabled
#define G_CHALLENGE_SECRET G.challenge_secret
#define G_CHALLENGE_TIMEOUT_MS G.challenge_timeout_ms
#define G_CHALLENGE_VERIFIED_TTL_NS G.challenge_verified_ttl_ns
#endif /* RAMPART_CONFIG_H */

View file

@ -1,8 +1,14 @@
#ifndef RAMPART_MAPS_H
#define RAMPART_MAPS_H
// 🔗 Blacklist (LPM_TRIE for CIDR support)
// Cleared by Rust userspace or per-entry expiry via ringbuf
/**
* IPv4 blacklist.
*
* An LPM trie so operators can ban a CIDR range rather than single hosts.
* The value is the ban expiry as a bpf_ktime_get_ns() timestamp; expired
* entries are removed lazily by the lookup helpers. BPF_F_NO_PREALLOC is
* required by the LPM trie type.
*/
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 100000);
@ -11,8 +17,12 @@ 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
/**
* IPv6 blacklist.
*
* LPM trie over 128-bit prefix keys, the exact analogue of blacklist_map:
* same expiry semantics, same required map flags.
*/
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 100000);
@ -21,7 +31,12 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC);
} blacklist6_map SEC(".maps");
// 🔗 Whitelist (LPM_TRIE for CIDR) — checked before any filter
/**
* Whitelist.
*
* LPM trie of trusted CIDRs; the filter consults it before any other check
* so allowlisted traffic can never be throttled or banned away.
*/
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 1000);
@ -30,8 +45,12 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC);
} whitelist_map SEC(".maps");
// 🔗 Connection tracking (SYN_RECEIVED → ESTABLISHED)
// LRU — автоматическое вытеснение старых записей
/**
* Connection tracking table (SYN_RECEIVED to ESTABLISHED).
*
* LRU so a flood of half-open flows evicts old entries instead of failing
* map updates; RST/FIN removes entries explicitly on the normal path.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 16384);
@ -39,7 +58,12 @@ struct {
__type(value, struct conntrack_entry);
} conntrack_map SEC(".maps");
// 🔗 SYN throttle per-source-IP (LRU)
/**
* Per-source SYN throttle state.
*
* LRU keeps memory bounded under spoofed-source floods, where the number of
* distinct keys is unbounded and an exact table would simply fill up.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535);
@ -47,7 +71,12 @@ struct {
__type(value, struct throttle_entry);
} connection_throttle SEC(".maps");
// 🔗 UDP rate limit per-source-IP (LRU) — policy from config.h
/**
* Per-source UDP rate-limit state.
*
* The window and threshold come from G_UDP_POLICY / G_UDP_HIT_COUNT, so the
* same map serves pass, drop and rate-limit modes without reloading.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535);
@ -55,15 +84,39 @@ struct {
__type(value, struct throttle_entry);
} udp_rate_limit SEC(".maps");
// ── RST-challenge pending state (challenge reflected, awaiting proof) ──
/**
* IPv6 twin of udp_rate_limit.
*
* Native IPv6 has no 32-bit source address to key on, so the key is the full
* 128-bit address; the value and window contract are identical.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535);
__type(key, struct in6_addr); // src6
__type(value, struct throttle_entry);
} udp_rate_limit6 SEC(".maps");
/**
* RST-challenge pending state, one record per challenged flow.
*
* marker is our chosen ISN and bad_ack is the deliberately unacceptable
* acknowledgement we sent; either one echoed back proves the source saw the
* challenge, so both are kept until the proof arrives or the TTL expires.
*/
struct challenge_pending {
__u64 sent_at; // ktime_ns of the reflected SYN-ACK
__u32 marker; // our ISN (client may echo it as ack)
__u32 bad_ack; // bogus ack sent (live client echoes it as RST seq)
};
// 🔗 RST-challenge: verified sources (liveness proven) — sliding TTL via
// last_seen, LRU eviction as the hard cap
/**
* Sources that already passed the RST challenge.
*
* The value is the last time the source proved liveness: the TTL is slid
* forward on each verified SYN, and LRU eviction is the hard cap when more
* sources are active than the table holds.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65536);
@ -71,7 +124,12 @@ struct {
__type(value, __u64); // last_seen (ktime_ns)
} challenge_verified SEC(".maps");
// 🔗 RST-challenge: outstanding challenges keyed by flow 4-tuple
/**
* Outstanding challenges, keyed by the flow 4-tuple.
*
* Keyed per flow rather than per source so two concurrent connections from
* the same host cannot overwrite each other's expected proof.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 16384);
@ -79,7 +137,12 @@ struct {
__type(value, struct challenge_pending);
} challenge_pending SEC(".maps");
// 🔗 Statistics (per-CPU, атомарные инкременты)
/**
* Statistics counters, indexed by the STAT_* constants below.
*
* Per-CPU array: increments need no atomics between CPUs, userspace sums the
* per-CPU values when it reads the map.
*/
#define STAT_TOTAL 0
#define STAT_TCP 1
#define STAT_WHITELIST 2
@ -93,6 +156,12 @@ struct {
#define STAT_CHALLENGE_VERIFIED 10
#define STAT_CHALLENGE_FAILED 11
/**
* Per-CPU counter storage.
*
* max_entries is rounded up past the highest STAT_* index so slots can be
* added without touching the map definition.
*/
struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 16);

View file

@ -3,23 +3,45 @@
#include "common.h"
// ── Per-prefix traffic statistics (shared ABI with Rust userspace) ──
// Layout is part of the userspace contract — do not reorder fields.
/**
* Per-prefix traffic statistics.
*
* The key layout is shared with the Rust userspace, which reads and resets
* these counters, so the fields must not be reordered. Coarse prefixes rather
* than single hosts keep the table small while still exposing a source
* subnet that floods.
*/
// family: 4 = IPv4 /24 префикс, 6 = IPv6 /64 префикс
/**
* Prefix key.
*
* family selects the prefix width (see PREFIX_FAMILY_V4 / PREFIX_FAMILY_V6);
* addr holds network-order prefix bytes, zero-padded to 16.
*/
struct prefix_key {
__u8 family;
__u8 pad[7];
__u8 addr[16]; // network-order байты префикса, zero-padded
__u8 addr[16]; // network-order prefix bytes, zero-padded
};
/**
* Counters accumulated for one prefix.
*
* last_seen_ns is a bpf_ktime_get_ns() timestamp, so userspace can ignore
* prefixes that went quiet without keeping its own clock.
*/
struct prefix_stats_val {
__u64 syn_count;
__u64 pkt_count;
__u64 last_seen_ns; // bpf_ktime_get_ns()
};
// 🔗 Prefix statistics (LRU) — читается и сбрасывается юзерспейсом
/**
* Prefix statistics table.
*
* LRU because the number of distinct sources is attacker-controlled; the
* userspace detector reads and resets the entries on its own schedule.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65536);
@ -30,17 +52,33 @@ struct {
#define PREFIX_FAMILY_V4 4
#define PREFIX_FAMILY_V6 6
// ── Build /24 IPv4 prefix key (network-order, low 8 bits masked out) ──
/**
* Build a /24 IPv4 prefix key.
*
* Copies the address in network order and clears the low octet, which is
* exactly a /24 mask without an arithmetic round trip.
*
* @param key key to initialise
* @param src_ip_net_order source address, network byte order
*/
static __always_inline void prefix_key_from_v4(struct prefix_key *key,
__u32 src_ip_net_order)
{
__builtin_memset(key, 0, sizeof(*key));
key->family = PREFIX_FAMILY_V4;
__builtin_memcpy(key->addr, &src_ip_net_order, 4);
key->addr[3] = 0; // обнулить младшие 8 бит адреса
key->addr[3] = 0; // mask the low octet to get a /24
}
// ── Build /64 IPv6 prefix key (network-order, low 64 bits masked out) ──
/**
* Build a /64 IPv6 prefix key.
*
* Only the high 64 bits are copied; the remainder stays zero from the
* memset, giving a /64 mask in network order.
*
* @param key key to initialise
* @param src_addr 16-byte source address, network byte order
*/
static __always_inline void prefix_key_from_v6(struct prefix_key *key,
const __u8 src_addr[16])
{
@ -49,8 +87,17 @@ static __always_inline void prefix_key_from_v6(struct prefix_key *key,
__builtin_memcpy(key->addr, src_addr, 8);
}
// ── Increment per-prefix counters (sliding window handled in userspace) ──
// is_syn: 1 → syn_count++, 0 → pkt_count++; last_seen_ns updated всегда.
/**
* Increment the counters for one prefix.
*
* Creates the entry on first sight. is_syn selects the counter to bump, so a
* SYN flood and a payload flood stay distinguishable downstream; last_seen_ns
* is refreshed on every call. The rate window itself lives in userspace.
*
* @param key prefix key, already built
* @param is_syn 1 counts a SYN, 0 counts any other packet
* @param now current bpf_ktime_get_ns() timestamp
*/
static __always_inline void update_prefix_stats(struct prefix_key *key,
__u8 is_syn, __u64 now)
{

View file

@ -4,7 +4,14 @@
#include "common.h"
#include "maps.h"
// ── Per-CPU stat increment ──
/**
* Increment one per-CPU counter.
*
* A missing slot (never updated, or an index past max_entries) is ignored so
* accounting can never change a packet verdict.
*
* @param idx STAT_* index into stats_map
*/
static __always_inline void inc_stat(__u32 idx)
{
__u64 *val = bpf_map_lookup_elem(&stats_map, &idx);
@ -12,7 +19,12 @@ static __always_inline void inc_stat(__u32 idx)
__sync_fetch_and_add(val, 1);
}
// ── Convenience wrappers ──
/**
* Named wrappers over inc_stat().
*
* They keep call sites readable and make the counter a decision of the call
* site rather than a magic index, so new counters need no edits here.
*/
static __always_inline void inc_total(void) { inc_stat(STAT_TOTAL); }
static __always_inline void inc_tcp(void) { inc_stat(STAT_TCP); }
static __always_inline void inc_udp(void) { inc_stat(STAT_UDP); }

View file

@ -1,19 +1,25 @@
#ifndef RAMPART_SYN_CHALLENGE_H
#define RAMPART_SYN_CHALLENGE_H
// ── Rampart RST-challenge (Oubliette-style liveness proof) ──
//
// Protocol-agnostic source verification, compatible with any TCP client:
// 1. SYN from a source that is neither whitelisted nor verified:
// kernel reflects a SYN-ACK with a DELIBERATELY WRONG ack number
// (deterministic from the 4-tuple + secret) and drops the original SYN.
// 2. Spoofed source never reacts — it does not own the address.
// 3. Live client's TCP stack rejects the unacceptable SYN-ACK
// (RFC 9293 SYN-SENT: SEG.ACK outside [ISS+1, SND.NXT] → RST)
// echoing secret-derived values. Seeing that RST marks the source
// verified; the app reconnects and its next SYN reaches the backend.
//
// Pending challenges expire after G_CHALLENGE_TIMEOUT_MS (spoof = silence).
/**
* Rampart RST challenge (Oubliette-style liveness proof).
*
* Protocol-agnostic source verification that any TCP client can pass:
*
* 1. A SYN from a source that is neither whitelisted nor verified makes
* the filter reflect a SYN-ACK with a deliberately wrong ack number
* (derived deterministically from the 4-tuple and the secret) and drop
* the original SYN.
* 2. A spoofed source never reacts, because it does not own the address.
* 3. A live client's TCP stack rejects the unacceptable SYN-ACK
* (RFC 9293 SYN-SENT: a SEG.ACK outside [ISS+1, SND.NXT] triggers a
* RST) and echoes secret-derived values in that RST. Seeing the RST
* marks the source verified; the application reconnects and its next
* SYN reaches the backend.
*
* Pending challenges expire after G_CHALLENGE_TIMEOUT_MS, so a silent
* spoofed source is forgotten instead of accumulating state.
*/
#include "common.h"
#include "config.h"
@ -22,7 +28,13 @@
#define CHAL_CONTINUE (-1) // fall through to the normal filter path
// ── Secret-dependent 64-bit mixing (splitmix-style finalizer) ──
/**
* Secret-dependent 64-bit mixing step (splitmix-style finalizer).
*
* @param h running hash
* @param v value to fold in
* @return mixed hash
*/
static __always_inline __u64 chal_mix64(__u64 h, __u64 v)
{
h ^= v;
@ -31,7 +43,16 @@ static __always_inline __u64 chal_mix64(__u64 h, __u64 v)
return h;
}
// Per-flow challenge values; infeasible to forge without G_CHALLENGE_SECRET
/**
* Derive the per-flow challenge values.
*
* Both the ISN and the bogus ack come from this hash, so forging a passing
* RST is infeasible without G_CHALLENGE_SECRET while the values stay stable
* for the same flow.
*
* @param k flow key of the connection being challenged
* @return 64-bit secret-derived value (high half ISN, low half bad ack)
*/
static __always_inline __u64 chal_derive(const struct flow_key *k)
{
__u64 h = (__u64)G_CHALLENGE_SECRET ^ 0x5253544348414C53ULL;
@ -42,7 +63,15 @@ static __always_inline __u64 chal_derive(const struct flow_key *k)
return h;
}
// ── Ones-complement helpers (both IPv4/TCP headers are 20 bytes = 10 words) ──
/**
* Sum the ten 16-bit words of a 20-byte header.
*
* Both the IPv4 and the TCP headers are exactly 20 bytes, so one helper
* serves each of them.
*
* @param w header viewed as ten 16-bit words
* @return unfolded ones-complement sum
*/
static __always_inline __u32 chal_sum10(const __u16 *w)
{
__u32 s = 0;
@ -51,6 +80,12 @@ static __always_inline __u32 chal_sum10(const __u16 *w)
return s;
}
/**
* Fold an accumulated sum into a ones-complement checksum.
*
* @param sum unfolded 32-bit sum of 16-bit words
* @return checksum, already complemented and ready for the header
*/
static __always_inline __u16 chal_csum_fold(__u32 sum)
{
sum = (sum >> 16) + (sum & 0xFFFF);
@ -58,17 +93,31 @@ static __always_inline __u16 chal_csum_fold(__u32 sum)
return (__u16)~sum;
}
// Rewrite the packet in place into a SYN-ACK: MAC/IP/ports swapped,
// seq = marker, ack = bad_ack (guaranteed unacceptable for the client),
// clean 20-byte TCP header, IP checksum recomputed, TCP checksum rebuilt.
// All reads happen BEFORE any packet write (writes invalidate verifier
// bounds), the tail is trimmed so the peer sees no leftover option bytes.
/**
* Rewrite the packet in place into a SYN-ACK carrying the challenge.
*
* MAC addresses and IP addresses are swapped, ports are swapped, seq is set
* to marker and ack to bad_ack; a guaranteed-unacceptable ack is what forces
* the live client into an RST. The TCP header is rebuilt clean (options
* gone), the IPv4 checksum recomputed and the TCP checksum rebuilt over the
* pseudo-header. The frame is trimmed so the peer sees no leftover option
* bytes from the original SYN.
*
* @param ctx XDP context, used to trim the tail
* @param eth Ethernet header of the packet
* @param l3 start of the IPv4 or IPv6 header
* @param is_ipv6 1 when l3 is an IPv6 header
* @param tcp TCP header of the packet
* @param marker ISN to advertise (our seq)
* @param bad_ack unacceptable ack number to advertise
*/
static __always_inline void chal_build_synack(struct xdp_md *ctx,
struct ethhdr *eth, void *l3,
__u8 is_ipv6, struct tcphdr *tcp,
__u32 marker, __u32 bad_ack)
{
// ── Snapshot phase (packet reads) ──
// Snapshot phase: every read happens before any write, because a write
// invalidates the verifier's bounds knowledge for later reads.
__u16 ipw[10];
__u16 tcpw[10];
__u8 ms[ETH_ALEN], md[ETH_ALEN];
@ -87,8 +136,8 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx,
daddr[0] = ((struct iphdr *)l3)->saddr;
}
// ── Compute images in registers ──
// IPv4 header: swap addresses, fresh TTL, recompute checksum
// Compute phase: build both header images in registers.
// IPv4: swap addresses, fresh TTL, recompute the checksum.
if (!is_ipv6) {
__u16 s0 = ipw[6], s1 = ipw[7];
ipw[6] = ipw[8];
@ -106,7 +155,7 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx,
bpf_htons(sizeof(struct tcphdr));
}
// TCP header: swap ports, inject secret-derived seq/ack, SYN|ACK
// TCP: swap ports, inject the secret-derived seq/ack and SYN|ACK.
__u16 nsport = tcpw[1]; // new source = old dest
__u16 ndport = tcpw[0]; // new dest = old source
tcpw[0] = nsport;
@ -122,7 +171,7 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx,
tcpw[8] = 0; // checksum placeholder
tcpw[9] = 0; // urg_ptr
// TCP checksum over pseudo-header + 20-byte header
// TCP checksum over pseudo-header plus the 20-byte header.
__u32 sum = 0;
if (is_ipv6) {
__u16 *w = (__u16 *)saddr;
@ -137,7 +186,7 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx,
sum += chal_sum10(tcpw);
tcpw[8] = chal_csum_fold(sum);
// ── Write phase ──
// Write phase: commit the images built above.
__builtin_memcpy(eth->h_dest, ms, ETH_ALEN);
__builtin_memcpy(eth->h_source, md, ETH_ALEN);
if (is_ipv6) {
@ -150,16 +199,29 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx,
}
__builtin_memcpy(tcp, tcpw, 20);
// Trim to the bare header (drop SYN options/payload remnants)
// Trim to the bare header so SYN options and payload remnants are gone.
long trim = (long)((void *)(long)ctx->data_end -
((void *)tcp + sizeof(struct tcphdr)));
if (trim > 0)
bpf_xdp_adjust_tail(ctx, -trim);
}
// ── Pure SYN from an unknown source: reflect the wrong SYN-ACK challenge ──
// Returns CHAL_CONTINUE (verified source — process normally), XDP_TX
// (challenge sent) or XDP_DROP.
/**
* Handle a bare SYN from a source that may not have proven liveness yet.
*
* A verified source refreshes its TTL and continues down the normal filter
* path. Anything else receives the reflected challenge.
*
* @param ctx XDP context
* @param eth Ethernet header
* @param l3 start of the IPv4 or IPv6 header
* @param is_ipv6 1 when l3 is an IPv6 header
* @param tcp TCP header
* @param flow flow key of this connection
* @param now current bpf_ktime_get_ns() timestamp
* @return CHAL_CONTINUE to process normally, XDP_TX when a challenge
* was sent, or XDP_DROP on failure
*/
static __always_inline int chal_on_syn(struct xdp_md *ctx, struct ethhdr *eth,
void *l3, __u8 is_ipv6,
struct tcphdr *tcp,
@ -197,9 +259,18 @@ static __always_inline int chal_on_syn(struct xdp_md *ctx, struct ethhdr *eth,
return XDP_TX;
}
// ── RST answering a pending challenge: proof of life ──
// Accept only if the RST echoes a secret-derived value (our bad ack as its
// seq, or our marker+1 as its ack). Anything else fails the challenge.
/**
* Handle a RST that may answer a pending challenge.
*
* Only a RST echoing a secret-derived value counts as proof of life: our bad
* ack as its seq, or our marker+1 as its ack. Everything else, including a
* reply that arrives after the timeout, fails the challenge and is dropped.
*
* @param tcp TCP header of the RST
* @param flow flow key of the connection
* @param now current bpf_ktime_get_ns() timestamp
* @return CHAL_CONTINUE when no challenge was pending, otherwise XDP_DROP
*/
static __always_inline int chal_on_rst(struct tcphdr *tcp,
const struct flow_key *flow, __u64 now)
{

View file

@ -1,17 +1,20 @@
// ── Rampart Universal XDP Filter ──
// Protocol-agnostic L3/L4 filter with an L7 extension point.
//
// Responsibilities (L3/L4):
// 1. No pure ACK drop (prevents TCP handshake deadlock)
// 2. LRU conntrack: SYN_RECEIVED → ESTABLISHED, seq tracking
// 3. RST/FIN removes conntrack entry (no stale state)
// 4. IPv6 support alongside IPv4
// 5. IP/CIDR blacklist + whitelist (LPM_TRIE)
// 6. SYN throttle per-IP, invalid TCP flag combos dropped
// 7. UDP policy from config.h: pass / drop / rate-limit
//
// Deep payload inspection is delegated to an optional protocol hook:
// see ../hooks/hook_api.h. Without a hook, established connections pass.
/**
* Rampart universal XDP filter.
*
* Protocol-agnostic L3/L4 filter with an optional L7 extension point. It
* owns, in this order:
*
* 1. No pure-ACK drop (prevents TCP handshake deadlock).
* 2. LRU conntrack: SYN_RECEIVED to ESTABLISHED, with sequence tracking.
* 3. RST/FIN removes the conntrack entry, so no stale state survives.
* 4. IPv6 support alongside IPv4.
* 5. IP/CIDR blacklist and whitelist (LPM trie).
* 6. Per-IP SYN throttle, with invalid TCP flag combinations dropped.
* 7. UDP policy from config.h: pass, drop or rate-limit.
*
* Deep payload inspection is delegated to an optional protocol hook (see
* ../hooks/hook_api.h). Without a hook, established connections pass.
*/
#include <linux/bpf.h>
#include <linux/if_ether.h>
@ -32,8 +35,15 @@
char __license[] SEC("license") = "GPL";
// ── TCP flag check (drop malicious combos) ──
// Returns 1 if packet should be dropped
/**
* Reject TCP flag combinations that no real stack emits.
*
* Every rule here is a signature of forged or scanner traffic, so a match
* means the packet can be dropped before it reaches any stateful logic.
*
* @param tcp TCP header of the packet
* @return 1 when the packet must be dropped, 0 when it looks legitimate
*/
static __always_inline __u8 detect_tcp_bypass(struct tcphdr *tcp)
{
__u8 flags = *((__u8 *)tcp + 13);
@ -59,7 +69,13 @@ static __always_inline __u8 detect_tcp_bypass(struct tcphdr *tcp)
return 0;
}
// ── Blacklist lookup with expiry; removes expired entries ──
/**
* Check the IPv4 blacklist and expire the entry on the way out.
*
* @param src_ip source address, network byte order
* @param now current bpf_ktime_get_ns() timestamp
* @return 1 when the source is currently banned, 0 otherwise
*/
static __always_inline __u8 is_blacklisted(__u32 src_ip, __u64 now)
{
struct lpm_key key = { .prefixlen = 32, .ip = src_ip };
@ -72,8 +88,16 @@ 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.
/**
* Check the IPv6 blacklist and expire the entry on the way out.
*
* Key layout mirrors bpf_lpm_trie_key: prefixlen in host order followed by
* 16 address bytes.
*
* @param addr 16-byte source address, network byte order
* @param now current bpf_ktime_get_ns() timestamp
* @return 1 when the source is currently banned, 0 otherwise
*/
static __always_inline __u8 is_blacklisted6(const __u8 addr[16], __u64 now)
{
struct lpm_key6 key = {};
@ -88,14 +112,32 @@ static __always_inline __u8 is_blacklisted6(const __u8 addr[16], __u64 now)
return 0;
}
/**
* Add a /32 ban for one source address.
*
* @param src_ip source address, network byte order
* @param until expiry as a bpf_ktime_get_ns() timestamp
*/
static __always_inline void ban_ip(__u32 src_ip, __u64 until)
{
struct lpm_key key = { .prefixlen = 32, .ip = src_ip };
bpf_map_update_elem(&blacklist_map, &key, &until, BPF_ANY);
}
// ── Generic per-IP window throttle (shared by SYN throttle and UDP RL) ──
// map: LRU_HASH keyed by src_ip; returns 1 if limit exceeded (caller bans/drops)
/**
* Fixed-window throttle for one IPv4 source address.
*
* Shared by the SYN throttle and the UDP rate limiter; only the map, the
* threshold and the window length differ. The caller decides the verdict,
* which is why an exceeded limit returns 1 instead of dropping.
*
* @param map LRU hash map keyed by src_ip
* @param src_ip source address, network byte order
* @param max_hits packets allowed per window
* @param window_ns window length in nanoseconds
* @param now current bpf_ktime_get_ns() timestamp
* @return 1 when the limit is exceeded, 0 when within it
*/
static __always_inline __u8 throttle_hit(void *map, __u32 src_ip,
__u32 max_hits, __u64 window_ns,
__u64 now)
@ -118,9 +160,51 @@ static __always_inline __u8 throttle_hit(void *map, __u32 src_ip,
return 0;
}
// ══════════════════════════════════════════
// Main XDP entry point
// ══════════════════════════════════════════
/**
* IPv6 twin of throttle_hit().
*
* Identical window logic; only the key width differs, so the caller passes a
* pointer to the 16-byte source address (the map key is struct in6_addr).
*
* @param map LRU hash map keyed by the source address
* @param key pointer to the 16-byte source address
* @param max_hits packets allowed per window
* @param window_ns window length in nanoseconds
* @param now current bpf_ktime_get_ns() timestamp
* @return 1 when the limit is exceeded, 0 when within it
*/
static __always_inline __u8 throttle_hit6(void *map, const void *key,
__u32 max_hits, __u64 window_ns,
__u64 now)
{
struct throttle_entry *th = bpf_map_lookup_elem(map, key);
if (th) {
if (now - th->window_start < window_ns) {
if (th->hits >= max_hits)
return 1;
__sync_fetch_and_add(&th->hits, 1);
} else {
th->window_start = now;
th->hits = 1;
}
} else {
struct throttle_entry new_th = { .window_start = now, .hits = 1 };
bpf_map_update_elem(map, key, &new_th, BPF_ANY);
}
return 0;
}
/**
* Main XDP entry point.
*
* Parses L2/L3/L4, applies whitelist and blacklist, then dispatches to the
* UDP policy or the TCP state machine. A return of XDP_PASS means the packet
* continues to the kernel stack; XDP_DROP means it is discarded here.
*
* @param ctx XDP context for the received frame
* @return the XDP verdict for this packet
*/
SEC("xdp")
int rampart_universal_filter(struct xdp_md *ctx)
{
@ -129,7 +213,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
inc_total();
// ── Parse Ethernet header ──
// Parse the Ethernet header.
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
return XDP_PASS;
@ -138,7 +222,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
if (eth->h_proto != bpf_htons(ETH_P_IP) && eth->h_proto != bpf_htons(ETH_P_IPV6))
return XDP_PASS;
// ── Parse IP header ──
// Parse the IP header.
__u32 src_ip = 0;
__u32 dst_ip = 0;
__u8 l4_proto = 0;
@ -182,14 +266,16 @@ 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)) {
// Native IPv6 — no 32-bit representable address, handled separately
// after the generic L4/port gates; must NOT touch v4 maps.
// Native IPv6: no 32-bit representable address, handled
// separately after the generic L4/port gates and must never
// touch the IPv4 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
// Source address must come from saddr, never daddr, or the
// filter would track the server instead of the client.
src_ip = ip6->saddr.in6_u.u6_addr32[3];
dst_ip = ip6->daddr.in6_u.u6_addr32[3];
l4_proto = ip6->nexthdr;
@ -197,7 +283,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
}
}
// ── Parse L4 header ──
// Parse the L4 header.
__u8 ip_hdr_len;
void *l4;
@ -220,7 +306,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
if ((void *)l4 + min_l4 > data_end)
return XDP_PASS;
// ── Port range check (protected services) ──
// Port range check: out-of-range destinations are not ours to defend.
__u16 dst_port;
if (l4_proto == IPPROTO_TCP)
dst_port = bpf_ntohs(((struct tcphdr *)l4)->dest);
@ -237,7 +323,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
__u64 now = bpf_ktime_get_ns();
// ── Native IPv6: blacklist + cheap L4 policy (no stateful v6 yet) ──
// Native IPv6: blacklist plus cheap L4 policy (no stateful v6 yet).
if (native_v6) {
if (is_blacklisted6(src6, now)) {
inc_blacklist();
@ -245,12 +331,23 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_DROP;
}
if (l4_proto == IPPROTO_UDP) {
if (G_UDP_POLICY == 1) { // drop
switch (G_UDP_POLICY) {
case 1: // drop
inc_drop();
return XDP_DROP;
case 2: // rate-limit (per-source, 128-bit key)
if (throttle_hit6(&udp_rate_limit6, src6,
G_UDP_HIT_COUNT, G_UDP_WINDOW_NS, now)) {
inc_rate_limit();
inc_drop();
// No ringbuf event: xdp_event.src_ip is u32 (ABI).
return XDP_DROP;
}
/* fallthrough: within limits — pass */
default: // pass
inc_pass();
return XDP_PASS;
}
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)) {
@ -266,14 +363,14 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_PASS;
}
// ── Whitelist check (CIDR) — before any filtering ──
// 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)) {
inc_whitelist();
return XDP_PASS;
}
// ── Blacklist check (CIDR with expiry) ──
// Blacklist check (CIDR with expiry).
if (is_blacklisted(src_ip, now)) {
inc_blacklist();
inc_drop();
@ -282,7 +379,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_DROP;
}
// ═══════════ UDP path ═══════════
// UDP path.
if (l4_proto == IPPROTO_UDP) {
switch (G_UDP_POLICY) {
case 1: // drop
@ -306,7 +403,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
}
}
// ═══════════ TCP path ═══════════
// TCP path.
struct tcphdr *tcp = l4;
// Malicious TCP flags
@ -324,7 +421,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
if ((void *)data + sizeof(struct ethhdr) + ip_hdr_len + tcp_hdr_len > data_end)
return XDP_DROP;
// ── Per-prefix stats key (/24; built once, after blacklist/bypass drops) ──
// Per-prefix stats key (/24), built once after blacklist and bypass drops.
struct prefix_key pkey;
prefix_key_from_v4(&pkey, src_ip);
@ -335,7 +432,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
if (tcp_payload_len < 0)
tcp_payload_len = 0;
// ── Build flow key ──
// Build the flow key.
struct flow_key flow = {
.src_ip = src_ip,
.dst_ip = dst_ip,
@ -343,7 +440,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
.dst_port = tcp->dest,
};
// ── SYN handling (new connection) ──
// SYN handling: a bare SYN opens a new connection.
if (tcp->syn && !tcp->ack) {
// SYN throttle per-IP
if (G_FEATURE_SYN_THROTTLE &&
@ -357,8 +454,9 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_DROP;
}
// ── RST-challenge: unverified source must prove liveness first ──
// (after throttle/blacklist, mirroring prefix_stats ordering)
// RST challenge: an unverified source must prove liveness first.
// Placed after throttle and blacklist so abusive sources never get a
// reply, mirroring the prefix_stats ordering.
if (G_SYN_CHALLENGE_ENABLED) {
int cv = chal_on_syn(ctx, eth, (void *)(eth + 1), is_ipv6,
tcp, &flow, now);
@ -387,11 +485,12 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_PASS; // Let SYN through
}
// ── Connection tracking lookup ──
// Connection tracking lookup.
// pkt_count: all non-SYN TCP that survived blacklist/bypass/throttle
update_prefix_stats(&pkey, 0, now);
// ── RST-challenge proof: match a pending challenge before conntrack ──
// RST challenge proof: match a pending challenge before conntrack,
// because the RST answers a flow that was never tracked.
if (G_SYN_CHALLENGE_ENABLED && tcp->rst) {
int cv = chal_on_rst(tcp, &flow, now);
if (cv != CHAL_CONTINUE)
@ -413,7 +512,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_PASS;
}
// ── Sequence number tracking (established connections only) ──
// Sequence number tracking, established connections only.
__u32 seq = bpf_ntohl(tcp->seq);
if (conn->state == STATE_ESTABLISHED && tcp_payload_len > 0 &&
seq != conn->expected_seq) {
@ -430,7 +529,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
return XDP_PASS;
}
// ── State machine ──
// State machine.
if (conn->state == STATE_SYN_RECEIVED) {
// Expecting the ACK that completes the 3-way handshake
if (!tcp->ack || seq != conn->expected_seq) {

View file

@ -1,61 +1,72 @@
#ifndef RAMPART_HOOK_API_H
#define RAMPART_HOOK_API_H
/*
* ── Rampart protocol-hook contract ──
/**
* Rampart protocol-hook contract.
*
* The universal XDP filter is protocol-agnostic: it validates L2/L3/L4,
* tracks the TCP handshake (SYN_RECEIVED → ESTABLISHED), applies
* blacklist/whitelist/throttle policy — and then delegates deep payload
* inspection to an optional protocol hook.
* tracks the TCP handshake (SYN_RECEIVED to ESTABLISHED) and applies the
* blacklist, whitelist and throttle policy. Only then does it delegate deep
* payload inspection to an optional protocol hook.
*
* ── WHAT THE HOOK SEES ──
* What the hook sees
* ------------------
*
* proto_hook() is called ONLY when:
* - packet is TCP, destination port is inside the protected range;
* - connection passed SYN throttle and completed the 3-way handshake
* (state == STATE_ESTABLISHED);
* - the segment carries a non-zero payload.
* proto_hook() is called only when all of the following hold:
*
* Pure SYN / SYN-ACK / ACK (handshake segments) NEVER reach the hook:
* the hook physically cannot block a clean TCP handshake.
* Empty ACKs also never reach the hook (keep-alives pass untouched).
* - the packet is TCP and its destination port is inside the protected
* range;
* - the connection passed the SYN throttle and completed the 3-way
* handshake (state == STATE_ESTABLISHED);
* - the segment carries a non-zero payload.
*
* struct cursor — bounds-checked window over the TCP payload:
* pos = first payload byte, end = one past the last
* byte of the packet (validated against data_end).
* struct pkt_meta — read-only metadata: 4-tuple (ports in HOST byte
* order), payload length, full TCP flags byte,
* L3 family.
* Pure SYN, SYN-ACK and ACK segments never reach the hook, so a hook
* physically cannot block a clean TCP handshake. Empty ACKs never reach it
* either: keep-alives pass untouched.
*
* ── VERDICTS ──
* Arguments:
*
* XDP_PASS — accept the segment; filter advances expected_seq by
* the consumed payload length and keeps conntrack entry.
* XDP_DROP — drop the segment AND tear down the conntrack entry.
* Anything else (XDP_ABORTED etc.) is treated as XDP_PASS; do not
* return it.
* struct cursor bounds-checked window over the TCP payload, where pos is
* the first payload byte and end is one past the last byte
* of the packet (validated against data_end).
* struct pkt_meta read-only metadata: the 4-tuple (ports in host byte
* order), payload length, the full TCP flags byte and the
* L3 family.
*
* ── RULES FOR HOOK IMPLEMENTATIONS ──
* Verdicts
* --------
*
* 1. Never block handshake traffic — guaranteed by design (see above),
* do not try to work around it either.
* 2. Bounded loops only: every loop must have a compile-time-constant
* trip count (or be provably bounded for the verifier), keep total
* complexity low — the program must still load with unrolled loops.
* 3. Every cursor advance MUST be bounds-checked against c->end
* (use cursor_take()); reading past c->end is forbidden even if it
* seems in-bounds in the packet.
* 4. Do not update conntrack/throttle/blacklist maps from the hook;
* emit events via push_event() if needed (ringbuf, may fail silently).
* 5. Keep the hook stateless per-call: all per-connection state lives
* in conntrack_map, which belongs to the core filter.
* XDP_PASS accept the segment; the filter advances expected_seq by the
* consumed payload length and keeps the conntrack entry.
* XDP_DROP drop the segment and tear down the conntrack entry.
*
* ── HOW TO ATTACH A HOOK ──
* Any other verdict (XDP_ABORTED and friends) is treated as XDP_PASS, so
* returning it is never useful.
*
* 1. Create hooks/<proto>_hook.h containing ONLY your own includes
* (common.h etc.) and a definition of proto_hook(). Do NOT include
* hook_api.h from the hook header — the core includes it for you:
* Rules for hook implementations
* ------------------------------
*
* 1. Never block handshake traffic. That is guaranteed by the design
* above; do not work around it either.
* 2. Bounded loops only. Every loop needs a compile-time-constant trip
* count, or must be provably bounded for the verifier, and total
* complexity must stay low so the program still loads when unrolled.
* 3. Every cursor advance must be bounds-checked against c->end via
* cursor_take(). Reading past c->end is forbidden even when it looks
* in-bounds in the packet.
* 4. Do not update the conntrack, throttle or blacklist maps from the
* hook. Emit events through push_event() instead (ring buffer, may
* fail silently).
* 5. Keep the hook stateless per call. All per-connection state lives in
* conntrack_map, which belongs to the core filter.
*
* How to attach a hook
* --------------------
*
* 1. Create hooks/<proto>_hook.h containing only your own includes
* (common.h etc.) and a definition of proto_hook(). Never include
* hook_api.h from the hook header, because the core includes it for
* you:
*
* // hooks/myproto_hook.h
* #include "../core/common.h"
@ -72,20 +83,32 @@
* -DRAMPART_PROTO_HOOK='"../hooks/myproto_hook.h"' \
* -c xdp/core/universal_filter.c -o universal_filter.o
*
* Without RAMPART_PROTO_HOOK the default no-op stub below is used
* Without RAMPART_PROTO_HOOK the default no-op stub defined below is used,
* and every established connection passes.
*/
#include <linux/bpf.h>
#include "../core/common.h"
// ── Bounds-checked cursor over the payload window ──
/**
* Bounds-checked cursor over the payload window.
*
* A plain pointer pair, so the hook can hand it to cursor_take() without
* extra state to keep in sync.
*/
struct cursor {
__u8 *pos; // next unparsed byte
__u8 *end; // one past last valid byte (== data_end)
};
// Take n bytes from the cursor; returns pointer or NULL on overrun.
/**
* Take n bytes from the cursor.
*
* @param c cursor to advance
* @param n number of bytes the caller intends to read
* @return pointer to the claimed bytes, or NULL when they would overrun
* c->end
*/
static __always_inline __u8 *cursor_take(struct cursor *c, __u32 n)
{
if (c->pos + n > c->end)
@ -96,7 +119,13 @@ static __always_inline __u8 *cursor_take(struct cursor *c, __u32 n)
return p;
}
// ── Read-only packet metadata handed to the hook ──
/**
* Read-only packet metadata handed to the hook.
*
* Addresses stay in network byte order and ports are converted to host order,
* so a hook can compare ports directly but must byte-swap addresses before
* printing them.
*/
struct pkt_meta {
__u32 src_ip; // IPv4 addr, or low 32 bits of IPv4-mapped IPv6
__u32 dst_ip; // same convention as src_ip
@ -110,7 +139,15 @@ struct pkt_meta {
#ifdef RAMPART_PROTO_HOOK
#include RAMPART_PROTO_HOOK
#else
/* Default stub: no deep inspection, everything established passes. */
/**
* Default hook stub.
*
* Performs no deep inspection, so every established connection passes.
*
* @param c payload cursor (unused)
* @param m packet metadata (unused)
* @return always XDP_PASS
*/
static __always_inline enum xdp_action
proto_hook(struct cursor *c, struct pkt_meta *m)
{