ByteGuideHub
Network Security • • 12 min read

Self-Hosted eBPF/XDP DDoS Mitigation: A Practical Guide to SYN Flood and Volumetric Attack Defense

Build a high-performance, kernel-level DDoS mitigation layer using eBPF/XDP to filter SYN floods and volumetric attacks before they reach userspace. Step-by-step guide with BPF map rate limiting, SYN cookie offload, and firewall integration.

Sponsored / Ad Space

Self-Hosted eBPF/XDP DDoS Mitigation: A Practical Guide

Quick Summary (TL;DR)

  • XDP runs your packet filter inside the NIC driver, before the kernel allocates an sk_buff, so it can drop millions of packets per second per core with a fraction of the CPU cost of iptables/nftables.
  • You’ll build a small eBPF program that parses Ethernet/IP/TCP, tracks per-source SYN rate in a BPF hash map, and XDP_DROPs offenders — plus a SYN-cookie offload path for when the flood is real.
  • Prerequisites: kernel ≥ 5.15 (5.10+ works), clang/llvm with BPF target, libbpf, bpftool, and an XDP-capable NIC (native mode preferred).
  • XDP complements — it does not replace — your stateful firewall and upstream DDoS scrubbing. It is the first line, not the only line.
  • Validate with hping3/tcpreplay and watch bpftool prog show + xdp_stat counters before you trust it in production.

Why eBPF/XDP for DDoS Mitigation?

A SYN flood is cheap to launch and expensive to absorb. Each spoofed SYN forces your kernel to allocate connection state (the SYN queue), and once that queue fills, legitimate clients time out. Traditional defenses — iptables hashlimit, nginx limit_req, or a userspace proxy — all react after the kernel has already done the expensive work: DMA, interrupt, sk_buff allocation, netfilter traversal.

XDP (eXpress Data Path) flips that. Your BPF program executes at the earliest possible hook — in the driver’s receive path, often before the packet is even copied into a socket buffer. That means an attacker’s 10 Mpps flood can be dropped for roughly the cost of a few memory reads and one hash lookup per packet.

The trade-offs are real: you write C, you deal with the BPF verifier, and a buggy program can (in theory) blackhole your own traffic. This guide walks the whole path — from kernel requirements to a working rate-limiter and SYN-cookie offload — so you can deploy it deliberately.

Prerequisites and Environment Setup

Hardware and Kernel Requirements

RequirementMinimumRecommended
Kernel5.10 LTS5.15+ or 6.x
NIC XDP modeGeneric (skb)Native driver mode
NIC examplesvirtio-netIntel ixgbe/i40e/ice, Mellanox mlx5
CPU2 cores, SSE24+ cores, NUMA-aware
Toolingclang 10, libbpfclang 14+, libbpf 1.x, bpftool

Check what your NIC supports:

ethtool -i eth0          # driver name
bpftool feature probe | grep -i xdp

If bpftool reports xdp support and your driver is in the recommended list, you get native mode. Otherwise you can still run in generic (skb) mode for testing — just expect a fraction of the throughput.

Installing Required Tools

On Debian/Ubuntu:

sudo apt update
sudo apt install -y clang llvm libelf-dev libbpf-dev \
  linux-headers-$(uname -r) bpftool iproute2 tcpdump hping3

Verify the BPF target is available:

clang -target bpf -O2 -c /dev/null -o /dev/null 2>&1 | head

No “unknown target” error means you’re good.

Understanding the XDP Hook and Packet Flow

The diagram below shows where XDP sits relative to the rest of the stack:

flowchart LR
    NIC[NIC RX Ring] --> XDP{XDP Program}
    XDP -->|XDP_DROP| Drop[Silent Drop]
    XDP -->|XDP_PASS| Stack[Kernel Network Stack]
    Stack --> NF[Netfilter / iptables]
    NF --> App[Userspace App]
    XDP -->|XDP_TX| TX[NIC TX Ring]
    XDP -->|XDP_REDIRECT| Other[Other CPU / iface]

XDP Action Codes

Your program returns exactly one of these per packet:

CodeMeaningUse case
XDP_PASSContinue to kernel stackLegitimate traffic
XDP_DROPSilently discardRate-limited attackers
XDP_TXBounce packet back out same NICSYN-ACK for cookie offload
XDP_REDIRECTSend to another CPU/ifaceLoad balancing
XDP_ABORTEDError pathShould never happen

The key insight: XDP_DROP is nearly free. XDP_PASS costs you the full stack. So the goal is to push as much bad traffic as possible into the DROP path before it reaches netfilter.

Building the XDP Program: SYN Flood Detection and Rate Limiting

BPF Map Design for Rate Limiting

We need two maps:

  1. syn_count — a per-source-IP counter (LRU_HASH), so eviction is automatic under memory pressure.
  2. config — a small array map holding tunables (threshold, window) so you can adjust without recompiling.
struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __type(key, __u32);        /* source IPv4 */
    __type(value, struct rate_state);
    __uint(max_entries, 65536);
} syn_count SEC(".maps");

struct rate_state {
    __u64 window_start_ns;
    __u32 count;
};

Writing the XDP C Code

Here’s a minimal, verifier-friendly program. Note the bounds checks — the verifier requires them.

#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define SYN_THRESHOLD 100
#define WINDOW_NS     1000000000ULL  /* 1 second */

struct rate_state { __u64 window_start_ns; __u32 count; };

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __type(key, __u32);
    __type(value, struct rate_state);
    __uint(max_entries, 65536);
} syn_count SEC(".maps");

SEC("xdp")
int xdp_syn_filter(struct xdp_md *ctx)
{
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end) return XDP_PASS;
    if (eth->h_proto != bpf_htons(ETH_P_IP)) return XDP_PASS;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end) return XDP_PASS;
    if (ip->protocol != IPPROTO_TCP) return XDP_PASS;

    struct tcphdr *tcp = (void *)ip + (ip->ihl * 4);
    if ((void *)(tcp + 1) > data_end) return XDP_PASS;

    /* Only SYN without ACK is a connection request */
    if (!tcp->syn || tcp->ack) return XDP_PASS;

    __u32 src = ip->saddr;
    __u64 now = bpf_ktime_get_ns();
    struct rate_state *st = bpf_map_lookup_elem(&syn_count, &src);

    if (!st) {
        struct rate_state init = { .window_start_ns = now, .count = 1 };
        bpf_map_update_elem(&syn_count, &src, &init, BPF_ANY);
        return XDP_PASS;
    }

    if (now - st->window_start_ns > WINDOW_NS) {
        st->window_start_ns = now;
        st->count = 1;
        return XDP_PASS;
    }

    if (++st->count > SYN_THRESHOLD) {
        return XDP_DROP;
    }
    return XDP_PASS;
}

char _license[] SEC("license") = "GPL";

This is deliberately simple. In production you’d also check tcp->doff for header length, handle IPv6, and probably hash on (src, dst_port) to avoid punishing a legitimate busy NAT gateway.

Compiling and Loading the XDP Program

clang -O2 -g -target bpf -c xdp_syn.c -o xdp_syn.o
sudo ip link set dev eth0 xdp obj xdp_syn.o sec xdp

To confirm it’s attached and see counters:

ip link show eth0 | grep xdp
sudo bpftool prog show | grep xdp_syn

Detach with ip link set dev eth0 xdp off.

How SYN Cookies Work

A SYN cookie is a stateless SYN-ACK: instead of remembering the half-open connection, the server encodes a cryptographic hash of (src, dst, ports, timestamp) into the sequence number. When the client ACKs, the server recomputes the hash and validates. No queue, no memory exhaustion.

Linux already does this in tcp_v4_syn_recv_sock — but only after the packet has traversed the stack and been queued. Under a flood, that queue is exactly what fills up.

Full SYN-cookie generation in XDP is advanced territory (you need to compute the hash, build a SYN-ACK, and XDP_TX it — and you must coordinate with the kernel’s own sequence-number expectations). For most self-hosted setups, the pragmatic pattern is:

sequenceDiagram
    participant C as Client
    participant X as XDP
    participant K as Kernel TCP
    C->>X: SYN (spoofed)
    X->>X: rate check
    alt under threshold
        X->>K: XDP_PASS
        K->>C: SYN-ACK (kernel cookie)
    else over threshold
        X->>C: XDP_DROP (silent)
    end

The XDP layer acts as a gate in front of the kernel’s cookie machinery, ensuring the kernel only ever sees a rate it can handle. For a full userspace-assisted cookie implementation, libraries like Cloudflare’s xdpcap/synproxy examples and the Linux SYNPROXY netfilter target are the right references — but note that SYNPROXY runs after XDP, so pairing them gives you defense in depth: XDP drops the worst of the flood, and SYNPROXY mops up what gets through.

A minimal kernel-side safety net:

sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_max_syn_backlog=8192
sysctl -w net.ipv4.tcp_synack_retries=2

Integrating with Existing Homelab Firewalls

XDP and iptables/nftables: Order of Operations

XDP runs before netfilter, so any packet dropped by XDP never reaches iptables. That’s the whole point — but it also means your iptables logs won’t show XDP-dropped packets. Use XDP-specific counters for visibility.

sudo bpftool map dump name syn_count | head -20

Using XDP with pfSense/OPNsense

pfSense and OPNsense are FreeBSD-based, so they don’t run Linux eBPF. Two practical options:

  1. Put a Linux XDP box in front of the FreeBSD firewall as a transparent bridge or router. The XDP box absorbs the flood; legit traffic passes to pfSense.
  2. Use the FreeBSD equivalent — pf’s max-src-conn-rate and synproxy — and accept the lower ceiling.

If you’re already on a Linux router (e.g., a Debian box running nftables), you’re in the sweet spot: attach XDP to the WAN interface and keep your nft rules for stateful inspection of what gets through.

Testing and Validation

Generating SYN Flood Traffic

Only test against systems you own. Use hping3 from a lab VM:

sudo hping3 -S --flood -V -p 80 192.0.2.10

Or use tcpreplay with a captured pcap for reproducible tests:

sudo tcpreplay -i eth1 --mbps=500 syn_flood.pcap

You should see your XDP program’s drop count rise while top shows minimal CPU increase on the target.

Monitoring and Metrics

MetricSourceWhat it tells you
XDP dropsbpftool prog show / xdp_statPackets filtered
SYN queue overflownetstat -s | grep -i listenWhether kernel still struggles
CPU per Mppsperf topEfficiency of your program
Map evictionsbpftool map showWhether max_entries is too small

Performance Tuning and Best Practices

  • Pin maps with bpftool map pin so they survive program reloads.
  • Use XDP_FLAGS_UPDATE_IF_NOEXIST for atomic replacement — no dropped packets during updates.
  • Spread across CPUs with XDP_REDIRECT + cpumap if a single core saturates.
  • Run a watchdog that detaches the program if bpftool prog show reports errors, so a bad build can’t blackhole you.
  • Log to a ring buffer, not bpf_printk, in production — bpf_printk is slow.
  • Benchmark before/after with pktgen or iperf3; don’t assume XDP is faster for your specific traffic mix.

Comparison: XDP vs. Traditional Firewall Approaches

ApproachHook pointThroughputStateful?ComplexityBest for
XDP (native)NIC driver10–100+ Mpps/coreLimited (maps)HighVolumetric drops, SYN floods
XDP (generic)After sk_buff1–5 Mpps/coreLimitedHighTesting, unsupported NICs
nftables / iptablesNetfilter0.5–2 MppsYesLowStateful policy, NAT
SYNPROXY (nft)Netfilter~1 MppsYes (stateless cookies)MediumSYN flood after XDP
Userspace proxyApplication10–100 KppsYesMediumL7 inspection

The realistic architecture is layered: XDP drops the obvious flood, SYNPROXY handles the residual, and your stateful firewall does the fine-grained policy.

Conclusion

XDP gives you a genuinely different capability: the ability to say “no” to a packet before your kernel has spent a single cycle on it. For a homelab or small production deployment facing SYN floods and volumetric noise, a ~100-line BPF program plus a handful of sysctls is often the difference between a service that stays up and one that doesn’t.

Start in generic mode, validate with realistic traffic, then move to native mode on your production NIC. Keep your existing firewall — XDP is the first line, not the only one.


FAQ

What is the difference between XDP and traditional iptables for DDoS mitigation? XDP processes packets at the driver level before the kernel network stack, offering orders of magnitude higher throughput and lower latency. iptables operates later in the stack, after sk_buff allocation, making it less efficient for high-volume attacks. XDP can drop millions of packets per second per core, while iptables may struggle under volumetric floods.

Can I use XDP with a virtualized homelab environment? Yes, but support depends on the hypervisor and NIC. For VMs you need SR-IOV or virtio-net with XDP support (available in recent kernels). Alternatively, use XDP in generic (skb) mode, which works with any NIC but offers lower performance. For best results, use physical NICs with native XDP support.

How does SYN cookie offload in XDP work? When the SYN rate exceeds a threshold, the XDP program can either drop the excess or generate SYN-ACK cookies itself without involving the kernel TCP stack — computing a cryptographic hash of the connection tuple and sending a SYN-ACK with that cookie. When the client returns the ACK, the cookie is validated and only then does the connection proceed to the kernel. In practice, most self-hosted setups use XDP as a rate gate in front of the kernel’s own cookie machinery.

Is eBPF/XDP safe to use in production? Yes — the kernel’s BPF verifier ensures programs cannot crash the system or access invalid memory. Still, test thoroughly in staging, keep a watchdog that detaches the program if it misbehaves, and monitor performance impact before rolling out broadly.

What are the hardware requirements for XDP? You need a NIC that supports XDP native mode (most modern 10G+ NICs from Intel, Mellanox, Broadcom; many Intel 1G NICs like i40e/ixgbe work well). The CPU should support at least SSE2 and have enough cores to handle the packet rate. Memory is less critical, but ensure enough for BPF maps.

How do I update the XDP program without dropping packets? Use XDP_FLAGS_UPDATE_IF_NOEXIST with atomic replacement, or libbpf’s xdp_program__attach which supports live update. Alternatively, load the new program with bpftool and atomically swap it using XDP_FLAGS_REPLACE. This ensures no downtime during updates.

Can XDP mitigate volumetric attacks that saturate the uplink? XDP can drop attack traffic at the NIC level, preventing it from consuming CPU and memory. However, if the uplink bandwidth itself is saturated, XDP cannot help because packets never reach your server. For attacks exceeding your bandwidth you need upstream protection — scrubbing centers or BGP flowspec.

Sponsored / Ad Space