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

Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation

Enforces deterministic packet processing invariants for eBPF XDP programs configured for hardware-offload (`XDP_FLAGS_HW_MODE`) and native driver modes. Eliminates host CPU softIRQ starvation and memory bus saturation during multi-gigabit TCP SYN floods by strictly avoiding `sk_buff` allocation and ensuring verifier-compliant hardware-constrained execution.

Prohibited Anti-Pattern: Attaching XDP in generic SKB mode or utilizing host-bound BPF helpers that trigger softIRQ saturation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation - Enforces deterministic packet processing invariants for eBPF XDP programs configured for hardware-offload (`XDP_FLAGS_HW_MODE`) and native driver modes. Eliminates host CPU softIRQ starvation and memory bus saturation during multi-gigabit TCP SYN floods by strictly avoiding `sk_buff` allocation and ensuring verifier-compliant hardware-constrained execution.
globs: **/*.bpf.c, **/*.bpf.h, **/xdp_*.c, **/loader.go, **/xdp_loader.c, deploy/network/*.sh
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-hardware-offload-syn-flood-mitigation"
---

# Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Attaching XDP in generic SKB mode or utilizing host-bound BPF helpers that trigger softIRQ saturation

## System Constraints
You are a Principal Linux Kernel and Systems Reliability Engineer specializing in high-throughput network datapath architecture and eBPF/XDP. You enforce strict architectural standards for volumetric SYN flood mitigation at the NIC driver and SmartNIC boundary. Ensure all eBPF programs intended for hardware offload or driver execution avoid kernel socket buffer (`sk_buff`) allocations, implement defensive pointer arithmetic verified against `data_end`, utilize hardware-supported BPF map definitions, and gracefully handle offload fallback modes without degrading to generic XDP.

## Strict Guidelines
- Engineers MUST ALWAYS attach XDP programs using `XDP_FLAGS_HW_MODE` with a verified fallback to `XDP_FLAGS_DRV_MODE`, and MUST NEVER silently degrade to `XDP_FLAGS_SKB_MODE` in high-throughput production environments.
- Engineers MUST validate packet bounds against `ctx->data_end` prior to dereferencing any byte of `ethhdr`, `iphdr`, or `tcphdr` to satisfy both the host BPF verifier and SmartNIC firmware JIT compilers.
- Code MUST return `XDP_DROP` immediately upon detecting rate-limiting violations or anomalous TCP SYN flags, ensuring zero host memory or softIRQ cycles are spent on malicious frames.
- BPF programs intended for hardware offload MUST NOT invoke BPF helper functions that are unsupported by NIC NPU firmware (such as `bpf_trace_printk`, helper-based socket lookups, or non-offloadable map types like `BPF_MAP_TYPE_HASH` when only `BPF_MAP_TYPE_ARRAY` is offload-capable).
- Network loaders MUST verify that NIC hardware offload flags (`IFLA_XDP_FLAGS`) succeed via netlink/libbpf and export telemetry counters via offloaded array maps or hardware interface drop counters (`ethtool -S`).

## Bad vs Good Implementations
### eBPF XDP Offloaded Packet Filter for SYN Flood Mitigation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example omits critical pointer bounds checks before accessing the IP and TCP headers, which fails the kernel BPF verifier and breaks SmartNIC JIT offload. It also relies on `bpf_printk`, which is unsupported in hardware offload modes and forces CPU context switches, negating anti-DDoS mitigations.
```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 defensive bounds check on TCP header,
// using unoffloaded map operations and generic SKB mode assumptions
SEC("xdp")
int xdp_syn_filter_bad(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 *ip = data + sizeof(*eth);
    // Missing bounds check for iphdr! Verifier will reject or panic hardware JIT.
    if (ip->protocol != IPPROTO_TCP)
        return XDP_PASS;

    struct tcphdr *tcp = (void *)ip + (ip->ihl * 4);
    // Unchecked pointer dereference beyond data_end
    if (tcp->syn && !tcp->ack) {
        // Logging in fast-path drops throughput by orders of magnitude
        bpf_printk("SYN packet detected from %x\n", ip->saddr);
        return XDP_DROP;
    }

    return XDP_PASS;
}

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

#### Production Standard (Correct)
> **Standard**: The good example verifies every header pointer against `data_end` before memory access, avoids unsupported helper calls, uses a hardware-offload compatible array map for atomic drop metrics, and returns `XDP_DROP` before the Linux network stack can allocate `sk_buff` structs.
```c
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <bpf/bpf_helpers.h>

/* Hardware-offload compatible fixed array map for drop statistics */
struct {
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __type(key, __u32);
    __type(value, __u64);
    __uint(max_entries, 1);
} drop_stats SEC(".maps");

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

    /* 1. Validate Ethernet frame boundary */
    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_PASS;

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

    /* 2. Validate IPv4 header boundary and length */
    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_PASS;

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

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

    /* 3. Validate variable-length TCP header boundary */
    struct tcphdr *tcp = (void *)ip + ip_hdr_len;
    if ((void *)(tcp + 1) > data_end)
        return XDP_PASS;

    /* 4. Stateless drop of suspicious SYN packets without ACK under volumetric pressure */
    if (tcp->syn && !tcp->ack) {
        __u32 key = 0;
        __u64 *count = bpf_map_lookup_elem(&drop_stats, &key);
        if (count)
            __sync_fetch_and_add(count, 1);

        return XDP_DROP;
    }

    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.

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation

Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic packet processing invariants for eBPF XDP programs configured for hardware-offload (`XDP_FLAGS_HW_MODE`) and native driver modes. Eliminates host CPU softIRQ starvation and memory bus saturation during multi-gigabit TCP SYN floods by strictly avoiding `sk_buff` allocation and ensuring verifier-compliant hardware-constrained execution. 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: Attaching XDP in generic SKB mode or utilizing host-bound BPF helpers that trigger softIRQ saturation 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 DriftAttaching XDP in generic SKB mode or utilizing host-bound BPF helpers that trigger softIRQ saturationCritical
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 `XDP_FLAGS_HW_MODE` with a verified fallback to `XDP_FLAGS_DRV_MODE`, and MUST NEVER silently degrade to `XDP_FLAGS_SKB_MODE` in high-throughput production environments.

Engineers MUST ALWAYS attach XDP programs using `XDP_FLAGS_HW_MODE` with a verified fallback to `XDP_FLAGS_DRV_MODE`, and MUST NEVER silently degrade to `XDP_FLAGS_SKB_MODE` in high-throughput 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.
2

Engineers MUST validate packet bounds against `ctx->data_end` prior to dereferencing any byte of `ethhdr`, `iphdr`, or `tcphdr` to satisfy both the host BPF verifier and SmartNIC firmware JIT compilers.

Engineers MUST validate packet bounds against `ctx->data_end` prior to dereferencing any byte of `ethhdr`, `iphdr`, or `tcphdr` to satisfy both the host BPF verifier and SmartNIC firmware JIT compilers.

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 return `XDP_DROP` immediately upon detecting rate-limiting violations or anomalous TCP SYN flags, ensuring zero host memory or softIRQ cycles are spent on malicious frames.

Code MUST return `XDP_DROP` immediately upon detecting rate-limiting violations or anomalous TCP SYN flags, ensuring zero host memory or softIRQ cycles are spent on malicious frames.

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

BPF programs intended for hardware offload MUST NOT invoke BPF helper functions that are unsupported by NIC NPU firmware (such as `bpf_trace_printk`, helper-based socket lookups, or non-offloadable map types like `BPF_MAP_TYPE_HASH` when only `BPF_MAP_TYPE_ARRAY` is offload-capable).

BPF programs intended for hardware offload MUST NOT invoke BPF helper functions that are unsupported by NIC NPU firmware (such as `bpf_trace_printk`, helper-based socket lookups, or non-offloadable map types like `BPF_MAP_TYPE_HASH` when only `BPF_MAP_TYPE_ARRAY` is offload-capable).

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

Network loaders MUST verify that NIC hardware offload flags (`IFLA_XDP_FLAGS`) succeed via netlink/libbpf and export telemetry counters via offloaded array maps or hardware interface drop counters (`ethtool -S`).

Network loaders MUST verify that NIC hardware offload flags (`IFLA_XDP_FLAGS`) succeed via netlink/libbpf and export telemetry counters via offloaded array maps or hardware interface drop counters (`ethtool -S`).

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 Linux eBPF XDP Hardware-Offload Ingress SYN Flood Mitigation critical for AI coding assistants?

Enforces deterministic packet processing invariants for eBPF XDP programs configured for hardware-offload (`XDP_FLAGS_HW_MODE`) and native driver modes. Eliminates host CPU softIRQ starvation and memory bus saturation during multi-gigabit TCP SYN floods by strictly avoiding `sk_buff` allocation and ensuring verifier-compliant hardware-constrained execution. 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 (Attaching XDP in generic SKB mode or utilizing host-bound BPF helpers that trigger softIRQ saturation) 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

Linux