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

eBPF XDP Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants

Mandates kernel-space Layer 4 ingress filtering at the eBPF XDP driver hook before sk_buff allocation. Enforces strict linear packet boundary verification, lockless per-CPU tracking maps, and kernel helper SYN cookie validation to eliminate host socket table and netfilter connection-tracking exhaustion under volumetric attacks.

Prohibited Anti-Pattern: Delegating SYN flood defense to iptables/nftables or user-space proxies after kernel sk_buff allocation has already occurred.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants - Mandates kernel-space Layer 4 ingress filtering at the eBPF XDP driver hook before sk_buff allocation. Enforces strict linear packet boundary verification, lockless per-CPU tracking maps, and kernel helper SYN cookie validation to eliminate host socket table and netfilter connection-tracking exhaustion under volumetric attacks.
globs: bpf/**/*.c, bpf/**/*.h, src/xdp/**/*.c, src/xdp/**/*.go, pkg/network/ebpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-syn-flood-early-drop-invariants"
---

# eBPF XDP Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Delegating SYN flood defense to iptables/nftables or user-space proxies after kernel sk_buff allocation has already occurred.

## System Constraints
You are a Principal Systems Engineer and Kernel Network Architect specializing in eBPF, XDP, and high-throughput anti-DDoS architectures. You strictly enforce compile-time and runtime safety for XDP programs, requiring absolute pointer verification against data_end, zero sk_buff overhead prior to validation, zero spinlock contention under line-rate conditions via per-CPU maps, and correct offload of SYN cookie handshakes via raw BPF helpers.

## Strict Guidelines
- Engineers MUST ALWAYS verify packet bounds before dereferencing packet headers: assert `(void *)(header_ptr + 1) <= (void *)(long)ctx->data_end` before any protocol read.
- Engineers MUST NOT allow unverified TCP SYN packets to transition past the XDP hook into `XDP_PASS` without either rate-limiting or valid eBPF-driven TCP syncookie generation via `bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie`.
- Code SHOULD utilize `BPF_MAP_TYPE_PERCPU_ARRAY` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for rate metrics and client states to avoid inter-core cache-line bouncing and lock contention at 10M+ pps.
- Services MUST compile XDP programs targeting the native driver hook (`XDP_FLAGS_DRV_MODE`) rather than generic/SKB fallback mode (`XDP_FLAGS_SKB_MODE`) in production environments.
- Components NEVER execute unbounded loops or recursive logic inside the eBPF verifier path; bounded loops MUST have explicit unrolling pragmas (`#pragma unroll`) and verifier-visible termination limits.

## Bad vs Good Implementations
### eBPF XDP Ingress TCP SYN Inspection and Drop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails verifier bounds checking against ctx->data_end before accessing IP and TCP headers, leading to BPF load rejection. Passes all initial SYN packets to the host network stack, causing netfilter conntrack table blowout and TCP listen backlog exhaustion during volumetric SYN floods.
```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: Missing strict boundary checks and deferring drop to user space
SEC("xdp")
int xdp_syn_filter(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    struct ethhdr *eth = data;
    struct iphdr *ip = (struct iphdr *)(eth + 1);
    struct tcphdr *tcp = (struct tcphdr *)(ip + 1);

    // CRITICAL BUG: Verifier will reject this due to unverified memory access past data_end.
    // In addition, passing all SYNs unconditionally causes socket table exhaustion.
    if (ip->protocol == IPPROTO_TCP && tcp->syn && !tcp->ack) {
        return XDP_PASS; // Passes packet to kernel sk_buff allocation, exhausting conntrack
    }

    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Implements rigorous pointer verification against ctx->data_end on all header offsets, accounts for variable IPv4 IHL, leverages a per-CPU LRU hash map to mitigate lock contention, and drops malicious SYN floods via XDP_DROP at the NIC driver layer before sk_buff allocation.
```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>

struct {
    __uint(type, BPF_MAP_TYPE_LRU_PERCPU_HASH);
    __uint(max_entries, 1048576);
    __type(key, __u32);   // Client IPv4
    __type(value, __u64); // Rate counter / timestamp
} syn_rate_map 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;

    // Detect pure TCP SYN (handshake initiation)
    if (tcp->syn && !tcp->ack && !tcp->rst) {
        __u32 src_ip = ip->saddr;
        __u64 *syn_count = bpf_map_lookup_elem(&syn_rate_map, &src_ip);
        
        if (syn_count && *syn_count > 1000) {
            // Drop early in the NIC driver ring buffer before sk_buff allocation
            return XDP_DROP;
        }
    }

    return XDP_PASS;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF XDP Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants

eBPF XDP Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants defines an industrial-grade behavioral standard for devops engineering. Mandates kernel-space Layer 4 ingress filtering at the eBPF XDP driver hook before sk_buff allocation. Enforces strict linear packet boundary verification, lockless per-CPU tracking maps, and kernel helper SYN cookie validation to eliminate host socket table and netfilter connection-tracking exhaustion under volumetric attacks. 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: Delegating SYN flood defense to iptables/nftables or user-space proxies after kernel sk_buff allocation has already occurred. 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 DriftDelegating SYN flood defense to iptables/nftables or user-space proxies after kernel sk_buff allocation has already occurred.Critical
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 verify packet bounds before dereferencing packet headers

Engineers MUST ALWAYS verify packet bounds before dereferencing packet headers: assert `(void *)(header_ptr + 1) <= (void *)(long)ctx->data_end` before any protocol read.

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 allow unverified TCP SYN packets to transition past the XDP hook into `XDP_PASS` without either rate-limiting or valid eBPF-driven TCP syncookie generation via `bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie`.

Engineers MUST NOT allow unverified TCP SYN packets to transition past the XDP hook into `XDP_PASS` without either rate-limiting or valid eBPF-driven TCP syncookie generation via `bpf_tcp_raw_gen_syncookie_ipv4` / `bpf_tcp_check_syncookie`.

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 SHOULD utilize `BPF_MAP_TYPE_PERCPU_ARRAY` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for rate metrics and client states to avoid inter-core cache-line bouncing and lock contention at 10M+ pps.

Code SHOULD utilize `BPF_MAP_TYPE_PERCPU_ARRAY` or `BPF_MAP_TYPE_LRU_PERCPU_HASH` for rate metrics and client states to avoid inter-core cache-line bouncing and lock contention at 10M+ pps.

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 compile XDP programs targeting the native driver hook (`XDP_FLAGS_DRV_MODE`) rather than generic/SKB fallback mode (`XDP_FLAGS_SKB_MODE`) in production environments.

Services MUST compile XDP programs targeting the native driver hook (`XDP_FLAGS_DRV_MODE`) rather than generic/SKB fallback mode (`XDP_FLAGS_SKB_MODE`) in production 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 execute unbounded loops or recursive logic inside the eBPF verifier path

Components NEVER execute unbounded loops or recursive logic inside the eBPF verifier path; bounded loops MUST have explicit unrolling pragmas (`#pragma unroll`) and verifier-visible termination limits.

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 Dynamic Layer 4 SYN Flood Early-Drop Filter Invariants critical for AI coding assistants?

Mandates kernel-space Layer 4 ingress filtering at the eBPF XDP driver hook before sk_buff allocation. Enforces strict linear packet boundary verification, lockless per-CPU tracking maps, and kernel helper SYN cookie validation to eliminate host socket table and netfilter connection-tracking exhaustion under volumetric attacks. 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 (Delegating SYN flood defense to iptables/nftables or user-space proxies after kernel sk_buff allocation has already occurred.) 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