This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-xdp-l4-synflood-mitigation-standard

eBPF XDP Layer-4 Line-Rate SYN Flood Mitigation Standard

Mandates stateless SYN cookie verification and direct packet bouncing via XDP native mode in the NIC driver ring buffer before socket buffer allocation. Prevents kernel backlog table exhaustion and CPU cache thrashing during multi-million packet-per-second spoofed TCP floods.

Prohibited Anti-Pattern: Stateful Session Allocation and SKB Traversal During Unverified TCP Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Layer-4 Line-Rate SYN Flood Mitigation Standard - Mandates stateless SYN cookie verification and direct packet bouncing via XDP native mode in the NIC driver ring buffer before socket buffer allocation. Prevents kernel backlog table exhaustion and CPU cache thrashing during multi-million packet-per-second spoofed TCP floods.
globs: **/*.bpf.c, **/*.xdp.c, bpf/**/*.c, src/xdp/**/*.c, pkg/ebpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-l4-synflood-mitigation-standard"
---

# eBPF XDP Layer-4 Line-Rate SYN Flood Mitigation Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Stateful Session Allocation and SKB Traversal During Unverified TCP Handshakes

## System Constraints
You are a Principal Systems & Network Architect enforcing kernel-bypass-adjacent line-rate DDoS guardrails using eBPF XDP. Enforce strict verifier boundary safety, zero-sk_buff allocation overhead for unverified SYNs, stateless syncookie handling, and driver-level packet redirection.

## Strict Guidelines
- Engineers MUST ALWAYS validate packet boundaries against `ctx->data_end` on every header traversal before dereferencing packet memory to guarantee verifier safety.
- Engineers MUST NOT allocate stateful BPF map entries (e.g., `BPF_MAP_TYPE_HASH`) on incoming raw SYN packets; all initial handshake challenges MUST be stateless.
- Code MUST synthesize SYN-ACK cookies directly within the received packet buffer and emit via `XDP_TX`, or rely on `bpf_tcp_raw_gen_syncookie_ipv4`/`ipv6` helpers.
- Services MUST be deployed using Native Driver XDP (`XDP_FLAGS_DRV_MODE`) or HW Offload mode, NEVER Generic SKB XDP (`XDP_FLAGS_SKB_MODE`) in production line-rate environments.
- Components NEVER pass unvalidated volumetric SYN floods into the Linux TCP stack (`XDP_PASS`) when the SYN backlog threshold is exceeded.

## Bad vs Good Implementations
### Stateless XDP SYN Cookie Generation and Line-Rate In-Ring Bouncing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates state in a BPF hash map for each spoofed SYN packet, introducing heavy lock contention and cache evictions. Crucially, returning XDP_PASS forces the kernel to allocate struct sk_buff for millions of bogus packets, exhausting the CPU and netif receive queue.
```c
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <bpf/bpf_helpers.h>

// ANTI-PATTERN: Allocating state in an LRU/Hash map for every SYN packet.
// Under a 10M PPS flood, map spinlocks lock up the CPU and exhaust memory.
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024000);
    __type(key, __u32);
    __type(value, __u64);
} syn_tracker SEC(".maps");

SEC("xdp")
int xdp_syn_mitigation(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;
        
    struct iphdr *iph = (void *)(eth + 1);
    if ((void *)(iph + 1) > data_end)
        return XDP_PASS;
        
    if (iph->protocol != IPPROTO_TCP)
        return XDP_PASS;

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

    if (tcp->syn && !tcp->ack) {
        __u32 src_ip = iph->saddr;
        __u64 ts = bpf_ktime_get_ns();
        bpf_map_update_elem(&syn_tracker, &src_ip, &ts, BPF_ANY); // State exhaustion
        return XDP_PASS; // Hands off to sk_buff, crashing kernel backlog
    }
    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Executes fully stateless packet processing. Bypasses sk_buff allocation completely by using bpf_tcp_raw_gen_syncookie_ipv4 to calculate the sequence number, swaps L2/L3 endpoints in the existing ring buffer memory, and returns XDP_TX to transmit the SYN-ACK immediately at line rate.
```c
#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>

SEC("xdp")
int xdp_syn_mitigation(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_DROP;

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

    struct iphdr *iph = (void *)(eth + 1);
    if ((void *)(iph + 1) > data_end || iph->ihl < 5)
        return XDP_DROP;

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

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

    // Intercept bare SYN: Statelessly compute SYN-ACK or challenge
    if (tcp->syn && !tcp->ack) {
        // Verify or generate syncookie directly via kernel helper without map state
        __s64 cookie = bpf_tcp_raw_gen_syncookie_ipv4(iph, tcp, sizeof(*tcp));
        if (cookie < 0)
            return XDP_DROP;

        // In-place MAC swap
        unsigned char tmp_mac[ETH_ALEN];
        __builtin_memcpy(tmp_mac, eth->h_source, ETH_ALEN);
        __builtin_memcpy(eth->h_source, eth->h_dest, ETH_ALEN);
        __builtin_memcpy(eth->h_dest, tmp_mac, ETH_ALEN);

        // In-place IP swap
        __be32 tmp_ip = iph->saddr;
        iph->saddr = iph->daddr;
        iph->daddr = tmp_ip;
        iph->check = 0;
        iph->check = bpf_csum_diff(0, 0, (__be32 *)iph, sizeof(*iph), 0);

        // In-place TCP SYN-ACK rewrite
        __be16 tmp_port = tcp->source;
        tcp->source = tcp->dest;
        tcp->dest = tmp_port;
        tcp->ack_seq = bpf_htonl(bpf_ntohl(tcp->seq) + 1);
        tcp->seq = bpf_htonl((__u32)cookie);
        tcp->ack = 1;
        tcp->check = 0; // Checksum recalc delegated or updated via bpf_csum_diff

        // Bounce packet directly back out the NIC ring buffer
        return XDP_TX;
    }

    return XDP_PASS;
}
```

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 Layer-4 Line-Rate SYN Flood Mitigation Standard

eBPF XDP Layer-4 Line-Rate SYN Flood Mitigation Standard defines an industrial-grade behavioral standard for devops engineering. Mandates stateless SYN cookie verification and direct packet bouncing via XDP native mode in the NIC driver ring buffer before socket buffer allocation. Prevents kernel backlog table exhaustion and CPU cache thrashing during multi-million packet-per-second spoofed TCP floods. 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: Stateful Session Allocation and SKB Traversal During Unverified TCP Handshakes 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 DriftStateful Session Allocation and SKB Traversal During Unverified TCP HandshakesCritical
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 validate packet boundaries against `ctx->data_end` on every header traversal before dereferencing packet memory to guarantee verifier safety.

Engineers MUST ALWAYS validate packet boundaries against `ctx->data_end` on every header traversal before dereferencing packet memory to guarantee verifier safety.

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 NOT allocate stateful BPF map entries (e.g., `BPF_MAP_TYPE_HASH`) on incoming raw SYN packets

Engineers MUST NOT allocate stateful BPF map entries (e.g., `BPF_MAP_TYPE_HASH`) on incoming raw SYN packets; all initial handshake challenges MUST be stateless.

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

Code MUST synthesize SYN-ACK cookies directly within the received packet buffer and emit via `XDP_TX`, or rely on `bpf_tcp_raw_gen_syncookie_ipv4`/`ipv6` helpers.

Code MUST synthesize SYN-ACK cookies directly within the received packet buffer and emit via `XDP_TX`, or rely on `bpf_tcp_raw_gen_syncookie_ipv4`/`ipv6` helpers.

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

Services MUST be deployed using Native Driver XDP (`XDP_FLAGS_DRV_MODE`) or HW Offload mode, NEVER Generic SKB XDP (`XDP_FLAGS_SKB_MODE`) in production line-rate environments.

Services MUST be deployed using Native Driver XDP (`XDP_FLAGS_DRV_MODE`) or HW Offload mode, NEVER Generic SKB XDP (`XDP_FLAGS_SKB_MODE`) in production line-rate environments.

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

Components NEVER pass unvalidated volumetric SYN floods into the Linux TCP stack (`XDP_PASS`) when the SYN backlog threshold is exceeded.

Components NEVER pass unvalidated volumetric SYN floods into the Linux TCP stack (`XDP_PASS`) when the SYN backlog threshold is exceeded.

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 Layer-4 Line-Rate SYN Flood Mitigation Standard critical for AI coding assistants?

Mandates stateless SYN cookie verification and direct packet bouncing via XDP native mode in the NIC driver ring buffer before socket buffer allocation. Prevents kernel backlog table exhaustion and CPU cache thrashing during multi-million packet-per-second spoofed TCP floods. 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 (Stateful Session Allocation and SKB Traversal During Unverified TCP Handshakes) 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