This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-xdp-stateful-ddos-quarantine-pipe

eBPF XDP Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding

Enforces pre-allocation packet filtering directly in the network driver RX ring buffer via eBPF XDP (eXpress Data Path). Eliminates Linux kernel socket buffer (sk_buff) allocation overhead and ksoftirqd CPU starvation under high-throughput Layer-4 amplification floods by tracking state inside LRU per-CPU maps and shedding malicious flows with XDP_DROP before kernel stack ingress.

Prohibited Anti-Pattern: Deferring Volumetric Mitigation to Netfilter or Using Unbounded BPF Maps In Ingress Pipeline

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding - Enforces pre-allocation packet filtering directly in the network driver RX ring buffer via eBPF XDP (eXpress Data Path). Eliminates Linux kernel socket buffer (sk_buff) allocation overhead and ksoftirqd CPU starvation under high-throughput Layer-4 amplification floods by tracking state inside LRU per-CPU maps and shedding malicious flows with XDP_DROP before kernel stack ingress.
globs: bpf/**/*.c, src/bpf/**/*.c, **/*.bpf.c, **/*.bpf.h
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-stateful-ddos-quarantine-pipe"
---

# eBPF XDP Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Deferring Volumetric Mitigation to Netfilter or Using Unbounded BPF Maps In Ingress Pipeline

## System Constraints
You are a Principal Systems & Kernel Security Engineer enforcing eBPF XDP Line-Rate Stateful DDoS Quarantine rules. Mandate early packet filtering before kernel sk_buff allocation, strict verifier-compliant pointer bounds checks, and lockless per-CPU memory structures.

## Strict Guidelines
- Engineers MUST ALWAYS execute volumetric packet dropping within native driver-mode XDP (XDP_DRV) before memory allocation for struct sk_buff occurs.
- Engineers MUST verify packet boundaries (data + offset > data_end) before dereferencing any byte in Ethernet, IPv4, IPv6, UDP, or TCP headers to satisfy the BPF verifier.
- Engineers MUST NOT use BPF_MAP_TYPE_HASH with standard spinlocks on line-rate hot paths; per-CPU hash maps (BPF_MAP_TYPE_PERCPU_HASH) or LRU maps (BPF_MAP_TYPE_LRU_HASH) MUST be utilized to prevent inter-core cache line bouncing.
- Code MUST strictly validate L4 header length fields against total IP payload sizes to prevent malformed fragmentation bypasses.
- Services MUST implement sliding-window rate limiters using hardware timestamping or bpf_ktime_get_ns() directly within the quarantine map entry.
- Components NEVER fall back to XDP_PASS when a flow exceeds stateful burst thresholds; packets meeting quarantine criteria MUST yield XDP_DROP.

## Bad vs Good Implementations
### eBPF XDP Stateful UDP Amplification Quarantine Filter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code fails to validate packet boundaries against data_end before dereferencing headers, which violates the BPF verifier guarantees. It uses a non-concurrency-safe global Hash map causing cacheline bouncing across cores, and passes unverified traffic to the OS network stack, exhausting kernel memory buffers under multi-gigabit reflection floods.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>

// ANTI-PATTERN: Generic global hash map creates lock contention;
// Incomplete bounds checks trigger verifier faults or kernel panic;
// Returns XDP_PASS on unhandled conditions, flooding kernel sk_buff allocations.
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 100000);
    __type(key, __u32);
    __type(value, __u64);
} tracking_map SEC(".maps");

SEC("xdp")
int ddos_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 for ethhdr
    struct iphdr *ip = (void *)(eth + 1);
    // Missing bounds check for iphdr
    
    if (ip->protocol == IPPROTO_UDP) {
        struct udphdr *udp = (void *)(ip + 1);
        __u32 src_ip = ip->saddr;
        __u64 *hits = bpf_map_lookup_elem(&tracking_map, &src_ip);
        if (hits) {
            *hits += 1; // Thread safety hazard across CPUs
            if (*hits > 10000)
                return XDP_DROP;
        }
    }
    return XDP_PASS;
}
char _license[] SEC("license") = "GPL";
```

#### Production Standard (Correct)
> **Standard**: Adheres to all kernel verifier safety bounds, calculates IP header variable length dynamically, uses a lockless BPF_MAP_TYPE_LRU_PERCPU_HASH to eradicate core contention, and drops volumetric floods via XDP_DROP before packet allocation in the Linux socket buffer layer.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>

#define RATE_LIMIT_NS 1000000000ULL // 1 second window
#define MAX_PPS_THRESHOLD 50000

struct rate_state {
    __u64 last_seen;
    __u64 packet_count;
};

struct {
    __uint(type, BPF_MAP_TYPE_LRU_PERCPU_HASH);
    __uint(max_entries, 262144);
    __type(key, __u32);
    __type(value, struct rate_state);
} quarantine_map SEC(".maps");

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

    // Invariant 1: Rigorous Ethernet boundary check
    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_DROP;

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

    // Invariant 2: Rigorous IPv4 boundary check
    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_DROP;

    // Prevent variable IHL overflow bounds violation
    if (ip->ihl < 5)
        return XDP_DROP;
    if ((void *)ip + (ip->ihl * 4) > data_end)
        return XDP_DROP;

    // Focus on L4 Amplification vectors (e.g., DNS, NTP, CLDAP over UDP)
    if (ip->protocol == IPPROTO_UDP) {
        struct udphdr *udp = (void *)ip + (ip->ihl * 4);
        if ((void *)(udp + 1) > data_end)
            return XDP_DROP;

        __u32 src_ip = ip->saddr;
        __u64 now = bpf_ktime_get_ns();
        
        struct rate_state *state = bpf_map_lookup_elem(&quarantine_map, &src_ip);
        if (state) {
            if (now - state->last_seen < RATE_LIMIT_NS) {
                state->packet_count++;
                if (state->packet_count > MAX_PPS_THRESHOLD) {
                    return XDP_DROP; // Shed directly in NIC ring buffer
                }
            } else {
                state->last_seen = now;
                state->packet_count = 1;
            }
        } else {
            struct rate_state new_state = {
                .last_seen = now,
                .packet_count = 1
            };
            bpf_map_update_elem(&quarantine_map, &src_ip, &new_state, BPF_NOEXIST);
        }
    }

    return XDP_PASS;
}

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

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF XDP Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding

eBPF XDP Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding defines an industrial-grade behavioral standard for security engineering. Enforces pre-allocation packet filtering directly in the network driver RX ring buffer via eBPF XDP (eXpress Data Path). Eliminates Linux kernel socket buffer (sk_buff) allocation overhead and ksoftirqd CPU starvation under high-throughput Layer-4 amplification floods by tracking state inside LRU per-CPU maps and shedding malicious flows with XDP_DROP before kernel stack ingress. 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: Deferring Volumetric Mitigation to Netfilter or Using Unbounded BPF Maps In Ingress Pipeline 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 DriftDeferring Volumetric Mitigation to Netfilter or Using Unbounded BPF Maps In Ingress PipelineCritical
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 execute volumetric packet dropping within native driver-mode XDP (XDP_DRV) before memory allocation for struct sk_buff occurs.

Engineers MUST ALWAYS execute volumetric packet dropping within native driver-mode XDP (XDP_DRV) before memory allocation for struct sk_buff occurs.

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 verify packet boundaries (data + offset > data_end) before dereferencing any byte in Ethernet, IPv4, IPv6, UDP, or TCP headers to satisfy the BPF verifier.

Engineers MUST verify packet boundaries (data + offset > data_end) before dereferencing any byte in Ethernet, IPv4, IPv6, UDP, or TCP headers to satisfy the BPF 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 use BPF_MAP_TYPE_HASH with standard spinlocks on line-rate hot paths

Engineers MUST NOT use BPF_MAP_TYPE_HASH with standard spinlocks on line-rate hot paths; per-CPU hash maps (BPF_MAP_TYPE_PERCPU_HASH) or LRU maps (BPF_MAP_TYPE_LRU_HASH) MUST be utilized to prevent inter-core cache line bouncing.

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 MUST strictly validate L4 header length fields against total IP payload sizes to prevent malformed fragmentation bypasses.

Code MUST strictly validate L4 header length fields against total IP payload sizes to prevent malformed fragmentation bypasses.

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 implement sliding-window rate limiters using hardware timestamping or bpf_ktime_get_ns() directly within the quarantine map entry.

Services MUST implement sliding-window rate limiters using hardware timestamping or bpf_ktime_get_ns() directly within the quarantine map entry.

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 XDP_PASS when a flow exceeds stateful burst thresholds

Components NEVER fall back to XDP_PASS when a flow exceeds stateful burst thresholds; packets meeting quarantine criteria MUST yield XDP_DROP.

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 Line-Rate Stateful DDoS Quarantine and Pre-SKB Shedding critical for AI coding assistants?

Enforces pre-allocation packet filtering directly in the network driver RX ring buffer via eBPF XDP (eXpress Data Path). Eliminates Linux kernel socket buffer (sk_buff) allocation overhead and ksoftirqd CPU starvation under high-throughput Layer-4 amplification floods by tracking state inside LRU per-CPU maps and shedding malicious flows with XDP_DROP before kernel stack ingress. 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 (Deferring Volumetric Mitigation to Netfilter or Using Unbounded BPF Maps In Ingress Pipeline) 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