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

eBPF XDP Native Line-Rate SYN Flood Filter & Early-Drop Standard

Enforces deterministic early packet inspection and mitigation at the network driver ring level via eBPF XDP native mode prior to socket buffer allocation. Prevents host memory exhaustion caused by high-volume TCP SYN floods by validating packet bounds at compile time, tracking connection velocity with lockless per-CPU maps, and dropping malicious traffic using XDP_DROP before kernel sk_buff structures are materialized.

Prohibited Anti-Pattern: Falling back to sk_buff-dependent layers or unverified XDP generic mode during volumetric L4 SYN floods

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: "eBPF XDP Native Line-Rate SYN Flood Filter & Early-Drop Standard - Enforces deterministic early packet inspection and mitigation at the network driver ring level via eBPF XDP native mode prior to socket buffer allocation. Prevents host memory exhaustion caused by high-volume TCP SYN floods by validating packet bounds at compile time, tracking connection velocity with lockless per-CPU maps, and dropping malicious traffic using XDP_DROP before kernel sk_buff structures are materialized."
globs: "**/*.bpf.c, **/*.bpf.h, **/*.c, **/*.h, src/ebpf/**/*.c"
alwaysApply: true
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-syn-flood-mitigation-standard"
---

# eBPF XDP Native Line-Rate SYN Flood Filter & Early-Drop Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Falling back to sk_buff-dependent layers or unverified XDP generic mode during volumetric L4 SYN floods

## System Constraints
You are a Principal Systems and Network Infrastructure Engineer enforcing strict eBPF XDP line-rate filtering invariants. Mandate native driver ring execution, strict verifier-compatible packet bounds checks, lockless per-CPU map access, and immediate drop primitives to neutralize L4 volumetric floods before kernel socket buffer allocation.

## Strict Guidelines
- Engineers MUST ALWAYS attach XDP programs using native driver mode (XDP_FLAGS_DRV_MODE) or offload mode (XDP_FLAGS_HW_MODE); generic skb mode (XDP_FLAGS_SKB_MODE) MUST NOT be used in production DDoS mitigation pipelines.
- Engineers MUST ALWAYS perform explicit boundary checks (`(void *)(header + 1) > data_end`) before dereferencing Ethernet, IPv4, IPv6, or TCP header structures to satisfy the eBPF verifier.
- Engineers MUST use `BPF_MAP_TYPE_PERCPU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for packet rate telemetry and flood state tracking to eliminate cross-CPU spinlock contention and cacheline bouncing.
- Engineers MUST NOT invoke socket layer allocations, conntrack evaluations, or standard iptables/nftables hooks for unverified initial SYN packets exceeding velocity thresholds.
- Code SHOULD leverage kernel SYN cookie helpers (`bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie_ipv4`) or early algorithmic bloom filters to validate handshakes before emitting `XDP_PASS`.

## Bad vs Good Implementations
### XDP Ingress Packet Inspection and Rate Drop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The program omits verifier-mandated bounds checks before dereferencing packet headers, risking kernel rejection or faults. It uses a non-per-CPU hash map, creating atomic cacheline contention at line rate, and passes flood traffic to the host stack via XDP_PASS where sk_buff allocation exhausts host RAM.
```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: Global shared map causes cross-core lock contention;
// missing packet boundary validation causes verifier rejection;
// returning XDP_PASS routes packets into sk_buff allocation path.
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __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;
    // BUG: Missing check: (void *)(eth + 1) > data_end
    struct iphdr *ip = (void *)(eth + 1);
    // BUG: Missing check: (void *)(ip + 1) > data_end
    struct tcphdr *tcp = (void *)((void *)ip + (ip->ihl * 4));
    
    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, passing packet to stack exhausts memory pools
            return XDP_PASS;
        }
    }
    return XDP_PASS;
}
char _license[] SEC("license") = "GPL";
```

#### Production Standard (Correct)
> **Standard**: Implements strict bounds checks verified against data_end for each layer (Ethernet, IPv4, TCP), tracks rates using an LRU per-CPU map to eliminate cross-core lock contention, and returns XDP_DROP immediately at the NIC driver ring before sk_buff memory structures are allocated by the kernel.
```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>

#define SYN_RATE_THRESHOLD 5000

struct {
    __uint(type, BPF_MAP_TYPE_LRU_PERCPU_HASH);
    __uint(max_entries, 65536);
    __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;
    if ((void *)(eth + 1) > data_end)
        return XDP_DROP;

    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_DROP;

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

    int ip_hdr_len = ip->ihl * 4;
    if (ip_hdr_len < sizeof(struct iphdr))
        return XDP_DROP;

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

    // Detect pure SYN packet
    if (tcp->syn && !tcp->ack) {
        __u32 src_ip = ip->saddr;
        __u64 init_val = 1;
        __u64 *count = bpf_map_lookup_elem(&syn_tracker, &src_ip);
        
        if (count) {
            __sync_fetch_and_add(count, 1);
            if (*count > SYN_RATE_THRESHOLD) {
                // Drop directly at driver layer; avoids sk_buff allocation
                return XDP_DROP;
            }
        } else {
            bpf_map_update_elem(&syn_tracker, &src_ip, &init_val, 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 Native Line-Rate SYN Flood Filter & Early-Drop Standard

eBPF XDP Native Line-Rate SYN Flood Filter & Early-Drop Standard defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic early packet inspection and mitigation at the network driver ring level via eBPF XDP native mode prior to socket buffer allocation. Prevents host memory exhaustion caused by high-volume TCP SYN floods by validating packet bounds at compile time, tracking connection velocity with lockless per-CPU maps, and dropping malicious traffic using XDP_DROP before kernel sk_buff structures are materialized. 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: Falling back to sk_buff-dependent layers or unverified XDP generic mode during volumetric L4 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 DriftFalling back to sk_buff-dependent layers or unverified XDP generic mode during volumetric L4 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 attach XDP programs using native driver mode (XDP_FLAGS_DRV_MODE) or offload mode (XDP_FLAGS_HW_MODE)

Engineers MUST ALWAYS attach XDP programs using native driver mode (XDP_FLAGS_DRV_MODE) or offload mode (XDP_FLAGS_HW_MODE); generic skb mode (XDP_FLAGS_SKB_MODE) MUST NOT be used in production DDoS mitigation pipelines.

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 perform explicit boundary checks (`(void *)(header + 1) > data_end`) before dereferencing Ethernet, IPv4, IPv6, or TCP header structures to satisfy the eBPF verifier.

Engineers MUST ALWAYS perform explicit boundary checks (`(void *)(header + 1) > data_end`) before dereferencing Ethernet, IPv4, IPv6, or TCP header structures to satisfy the eBPF 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 use `BPF_MAP_TYPE_PERCPU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for packet rate telemetry and flood state tracking to eliminate cross-CPU spinlock contention and cacheline bouncing.

Engineers MUST use `BPF_MAP_TYPE_PERCPU_HASH` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for packet rate telemetry and flood state tracking to eliminate cross-CPU spinlock contention and cacheline 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

Engineers MUST NOT invoke socket layer allocations, conntrack evaluations, or standard iptables/nftables hooks for unverified initial SYN packets exceeding velocity thresholds.

Engineers MUST NOT invoke socket layer allocations, conntrack evaluations, or standard iptables/nftables hooks for unverified initial SYN packets exceeding velocity thresholds.

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

Code SHOULD leverage kernel SYN cookie helpers (`bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie_ipv4`) or early algorithmic bloom filters to validate handshakes before emitting `XDP_PASS`.

Code SHOULD leverage kernel SYN cookie helpers (`bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie_ipv4`) or early algorithmic bloom filters to validate handshakes before emitting `XDP_PASS`.

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 Native Line-Rate SYN Flood Filter & Early-Drop Standard critical for AI coding assistants?

Enforces deterministic early packet inspection and mitigation at the network driver ring level via eBPF XDP native mode prior to socket buffer allocation. Prevents host memory exhaustion caused by high-volume TCP SYN floods by validating packet bounds at compile time, tracking connection velocity with lockless per-CPU maps, and dropping malicious traffic using XDP_DROP before kernel sk_buff structures are materialized. 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 (Falling back to sk_buff-dependent layers or unverified XDP generic mode during volumetric L4 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