This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-xdp-lru-syn-flood-guardrail

eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail

Enforces early L4 packet filtering directly in the network driver layer via eBPF XDP before Linux kernel sk_buff allocation. Mandates bounded BPF_MAP_TYPE_LRU_HASH tables and verifier-compliant pointer bounds checks to drop volumetric spoofed SYN floods at line rate without exhausting host kernel memory.

Prohibited Anti-Pattern: Deferred Userspace Filtering and Unbounded BPF Hash Maps Under SYN Floods

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail - Enforces early L4 packet filtering directly in the network driver layer via eBPF XDP before Linux kernel sk_buff allocation. Mandates bounded BPF_MAP_TYPE_LRU_HASH tables and verifier-compliant pointer bounds checks to drop volumetric spoofed SYN floods at line rate without exhausting host kernel memory.
globs: **/*.bpf.c, **/*.bpf.h, **/*.c, **/*.h, src/ebpf/**/*.{c,h}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-lru-syn-flood-guardrail"
---

# eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Deferred Userspace Filtering and Unbounded BPF Hash Maps Under SYN Floods

## System Constraints
You are a Principal Systems & Network Security Architect enforcing eBPF/XDP kernel invariants. You must prevent memory exhaustion and CPU starvation from L4 volumetric attacks by enforcing deterministic in-kernel rate limiting using LRU maps and pre-allocation at the driver layer before sk_buff construction.

## Strict Guidelines
- Engineers MUST ALWAYS use `BPF_MAP_TYPE_LRU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` instead of standard `BPF_MAP_TYPE_HASH` for client IP tracking to prevent map exhaustion during randomized source IP spoofing attacks.
- Engineers MUST ALWAYS validate packet buffer bounds (`data + offset > data_end`) before dereferencing Ethernet, IPv4, IPv6, and TCP headers to satisfy the BPF kernel verifier.
- Engineers MUST NOT allow excessive or anomalous TCP SYN packets to reach `XDP_PASS`, ensuring malicious ingress traffic never triggers kernel `sk_buff` allocation or Netfilter connection tracking.
- Code SHOULD atomically update ingress rate metrics using atomic primitives or per-CPU LRU structures to prevent cross-core cache line contention at high packet-per-second (Mpps) rates.
- Services MUST return `XDP_DROP` immediately upon rate threshold violation directly in the NIC driver ring buffer.
- Components NEVER fall back to userspace daemons or IPTables/NFTables rulesets for line-rate volumetric DDoS protection when native XDP drivers are available.

## Bad vs Good Implementations
### XDP SYN-Flood Mitigation Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses BPF_MAP_TYPE_HASH which permanently allocates entries until saturated, failing under spoofed source-IP floods. Dereferences packet headers without bounds verification checks against data_end, causing BPF verifier rejections. Lacks atomic updates and deterministic eviction.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>

// ANTI-PATTERN: Standard dynamic HASH map exhausts kernel memory under spoofed IP attacks.
// Once full, bpf_map_update_elem fails, allowing malicious traffic to pass or dropping legitimate traffic.
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10000);
    __type(key, __u32);
    __type(value, __u64);
} syn_tracker 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;
    // Missing bounds check here causes kernel verifier rejection!
    struct iphdr *ip = (void *)(eth + 1);
    struct tcphdr *tcp = (void *)(ip + 1);
    
    // Incomplete parsing allows non-SYN packets or out-of-bounds reads
    if (tcp->syn && !tcp->ack) {
        __u32 src_ip = ip->saddr;
        __u64 *count = bpf_map_lookup_elem(&syn_tracker, &src_ip);
        if (count && *count > 1000) {
            // Too late: processing without atomic operations causes race conditions
            return XDP_DROP;
        }
    }
    return XDP_PASS; // Hands off to sk_buff allocation
}

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

#### Production Standard (Correct)
> **Standard**: Implements BPF_MAP_TYPE_LRU_HASH to cap kernel memory consumption and automatically cycle entries under attack. Enforces exhaustive boundary checks on Ethernet, IPv4, and TCP offsets to guarantee kernel verifier safety. Uses atomic increments and drops offending SYN packets before socket allocation.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>

#define SYN_THRESHOLD_PER_SEC 100

struct rate_limit_val {
    __u64 last_timestamp;
    __u32 packet_count;
};

// INVARIANT: LRU Map automatically evicts least recently used keys during high-cardinality IP floods
struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __uint(max_entries, 65536);
    __type(key, __u32); // IPv4 Source Address
    __type(value, struct rate_limit_val);
} syn_tracker SEC(".maps");

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

    // Strict verifier bounds checking
    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_DROP;

    if (eth->h_proto != __builtin_bswap16(ETH_P_IP))
        return XDP_PASS;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_DROP;

    if (ip->protocol != IPPROTO_TCP)
        return XDP_PASS;

    // Verify IHL to safely handle IP options before TCP header
    __u32 ip_hdr_len = ip->ihl * 4;
    if (ip_hdr_len < sizeof(struct iphdr))
        return XDP_DROP;

    struct tcphdr *tcp = (void *)((__u8 *)ip + ip_hdr_len);
    if ((void *)(tcp + 1) > data_end)
        return XDP_DROP;

    // Target isolated SYN packets (SYN flag set, ACK flag clear)
    if (tcp->syn && !tcp->ack) {
        __u32 src_ip = ip->saddr;
        __u64 now = bpf_ktime_get_ns();
        struct rate_limit_val *val = bpf_map_lookup_elem(&syn_tracker, &src_ip);

        if (val) {
            // Within 1-second rolling interval window (1e9 ns)
            if (now - val->last_timestamp < 1000000000ULL) {
                __u32 count = __sync_fetch_and_add(&val->packet_count, 1);
                if (count > SYN_THRESHOLD_PER_SEC) {
                    // Drop directly in NIC driver ring buffer; bypass sk_buff allocation
                    return XDP_DROP;
                }
            } else {
                val->last_timestamp = now;
                val->packet_count = 1;
            }
        } else {
            struct rate_limit_val initial = {
                .last_timestamp = now,
                .packet_count = 1,
            };
            bpf_map_update_elem(&syn_tracker, &src_ip, &initial, BPF_ANY);
        }
    }

    return XDP_PASS;
}

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

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail

eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces early L4 packet filtering directly in the network driver layer via eBPF XDP before Linux kernel sk_buff allocation. Mandates bounded BPF_MAP_TYPE_LRU_HASH tables and verifier-compliant pointer bounds checks to drop volumetric spoofed SYN floods at line rate without exhausting host kernel memory. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Deferred Userspace Filtering and Unbounded BPF Hash Maps Under SYN Floods Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDeferred Userspace Filtering and Unbounded BPF Hash Maps Under SYN FloodsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use `BPF_MAP_TYPE_LRU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` instead of standard `BPF_MAP_TYPE_HASH` for client IP tracking to prevent map exhaustion during randomized source IP spoofing attacks.

Engineers MUST ALWAYS use `BPF_MAP_TYPE_LRU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` instead of standard `BPF_MAP_TYPE_HASH` for client IP tracking to prevent map exhaustion during randomized source IP spoofing attacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS validate packet buffer bounds (`data + offset > data_end`) before dereferencing Ethernet, IPv4, IPv6, and TCP headers to satisfy the BPF kernel verifier.

Engineers MUST ALWAYS validate packet buffer bounds (`data + offset > data_end`) before dereferencing Ethernet, IPv4, IPv6, and TCP headers to satisfy the BPF kernel verifier.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT allow excessive or anomalous TCP SYN packets to reach `XDP_PASS`, ensuring malicious ingress traffic never triggers kernel `sk_buff` allocation or Netfilter connection tracking.

Engineers MUST NOT allow excessive or anomalous TCP SYN packets to reach `XDP_PASS`, ensuring malicious ingress traffic never triggers kernel `sk_buff` allocation or Netfilter connection tracking.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD atomically update ingress rate metrics using atomic primitives or per-CPU LRU structures to prevent cross-core cache line contention at high packet-per-second (Mpps) rates.

Code SHOULD atomically update ingress rate metrics using atomic primitives or per-CPU LRU structures to prevent cross-core cache line contention at high packet-per-second (Mpps) rates.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST return `XDP_DROP` immediately upon rate threshold violation directly in the NIC driver ring buffer.

Services MUST return `XDP_DROP` immediately upon rate threshold violation directly in the NIC driver ring buffer.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER fall back to userspace daemons or IPTables/NFTables rulesets for line-rate volumetric DDoS protection when native XDP drivers are available.

Components NEVER fall back to userspace daemons or IPTables/NFTables rulesets for line-rate volumetric DDoS protection when native XDP drivers are available.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is eBPF XDP In-Kernel LRU Map SYN-Flood Mitigation Guardrail critical for AI coding assistants?

Enforces early L4 packet filtering directly in the network driver layer via eBPF XDP before Linux kernel sk_buff allocation. Mandates bounded BPF_MAP_TYPE_LRU_HASH tables and verifier-compliant pointer bounds checks to drop volumetric spoofed SYN floods at line rate without exhausting host kernel memory. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Deferred Userspace Filtering and Unbounded BPF Hash Maps Under SYN Floods) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

eBPF