This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-tc-ingress-packet-slicing-loop-invariant

eBPF TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants

Enforces verifier-bounded loops and strict linear packet bounds verification for Layer 7 protocol parsing within Traffic Control (TC) ingress eBPF programs. Guarantees that packet pointers are recalculated after calls to bpf_skb_pull_data and prevents BPF verifier path explosion and tail-call stack overflows during high-throughput packet routing. Ensures production safety by maintaining the 512-byte BPF stack limit and restricting tail calls within kernel recursion limits.

Prohibited Anti-Pattern: Unbounded L7 Header Parsing Loops with Stale SKB Data Pointers and Unchecked Tail Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants - Enforces verifier-bounded loops and strict linear packet bounds verification for Layer 7 protocol parsing within Traffic Control (TC) ingress eBPF programs. Guarantees that packet pointers are recalculated after calls to bpf_skb_pull_data and prevents BPF verifier path explosion and tail-call stack overflows during high-throughput packet routing. Ensures production safety by maintaining the 512-byte BPF stack limit and restricting tail calls within kernel recursion limits.
globs: bpf/**/*.c, bpf/**/*.h, src/ebpf/**/*.c, **/*.bpf.c, **/*.bpf.h
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-tc-ingress-packet-slicing-loop-invariant"
---

# eBPF TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded L7 Header Parsing Loops with Stale SKB Data Pointers and Unchecked Tail Calls

## System Constraints
You are a Principal Systems and Kernel Engineer enforcing eBPF TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants. Mandate strict linear bounds checks, loop bounds, and pointer refresh rules for all in-kernel parsing routines.

## Strict Guidelines
- Engineers MUST ALWAYS reload ctx->data and ctx->data_end pointers immediately following any invocation of bpf_skb_pull_data or helper functions that may linearize or reallocate socket buffer memory.
- Engineers MUST ALWAYS bound all parsing loops with a compile-time static constant (#pragma unroll or explicitly bounded loop counter <= MAX_PARSER_ITERATIONS) to satisfy verifier state complexity and path pruning constraints.
- Engineers MUST verify (void *)(cursor + struct_size) > data_end before every dereference, using unsigned comparison operators to prevent signed integer overflow vulnerabilities.
- Code SHOULD avoid storing large intermediate L7 state structures on the BPF stack; engineers MUST enforce the BPF stack budget limit (<= 512 bytes) by using per-CPU array scratch buffers for L7 parsing state.
- Services MUST bound tail-call depth explicitly to prevent hitting the kernel-enforced MAX_TAIL_CALL_CNT (33 in modern kernels) which results in silent, unrecoverable packet drops.
- Components NEVER assume contiguous SKB memory when parsing payload past the transport layer; non-linear packet slicing MUST use bpf_skb_pull_data or bpf_skb_load_bytes.

## Bad vs Good Implementations
### L7 Header Parsing in TC Ingress eBPF Program

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The program calls bpf_skb_pull_data but fails to refetch skb->data and skb->data_end, causing the BPF verifier to reject the program due to invalid or stale direct packet access pointers. Additionally, an unbounded while (*cursor != '\0') loop induces state explosion and verifier rejection.
```c
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <bpf/bpf_helpers.h>

SEC("tc")
int parse_l7_ingress(struct __sk_buff *skb) {
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;
    
    // Bug 1: bpf_skb_pull_data invalidates previous data/data_end pointers
    bpf_skb_pull_data(skb, 256);
    
    // Bug 2: Unbounded loop causes verifier rejection (path explosion)
    // Bug 3: Using stale 'data' pointer without refetching from skb
    char *cursor = (char *)data + 54; // Assume Eth + IP + TCP
    while (*cursor != '\0') { 
        if (cursor + 1 > (char *)data_end)
            return TC_ACT_SHOT;
        cursor++;
    }
    
    return TC_ACT_OK;
}
```

#### Production Standard (Correct)
> **Standard**: Refreshes skb->data and skb->data_end after bpf_skb_pull_data, strictly checks that (cursor + 1) does not exceed data_end on every step, and unrolls an explicitly bounded loop to prevent verifier rejection and path explosion.
```c
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <bpf/bpf_helpers.h>

#define MAX_L7_ITERATIONS 32
#define L7_DELIMITER '\n'

SEC("tc")
int parse_l7_ingress(struct __sk_buff *skb) {
    // Ensure linear memory access for headers
    if (bpf_skb_pull_data(skb, 128) < 0)
        return TC_ACT_SHOT;

    // Pointer refresh invariant: ALWAYS re-read pointers after pull
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;
    
    // Explicit boundary verification for network headers
    __u32 offset = 54; // ETH (14) + IPv4 (20) + TCP (20)
    if ((void *)((char *)data + offset) > data_end)
        return TC_ACT_OK;

    char *cursor = (char *)data + offset;

    // Verifier-bounded loop invariant: statically bounded counter
    #pragma unroll
    for (int i = 0; i < MAX_L7_ITERATIONS; i++) {
        if ((void *)(cursor + 1) > data_end)
            break;
            
        if (*cursor == L7_DELIMITER) {
            return TC_ACT_PIPE;
        }
        cursor++;
    }

    return TC_ACT_OK;
}
```

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 TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants

eBPF TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants defines an industrial-grade behavioral standard for devops engineering. Enforces verifier-bounded loops and strict linear packet bounds verification for Layer 7 protocol parsing within Traffic Control (TC) ingress eBPF programs. Guarantees that packet pointers are recalculated after calls to bpf_skb_pull_data and prevents BPF verifier path explosion and tail-call stack overflows during high-throughput packet routing. Ensures production safety by maintaining the 512-byte BPF stack limit and restricting tail calls within kernel recursion limits. 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: Unbounded L7 Header Parsing Loops with Stale SKB Data Pointers and Unchecked Tail Calls 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 DriftUnbounded L7 Header Parsing Loops with Stale SKB Data Pointers and Unchecked Tail CallsCritical
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 reload ctx->data and ctx->data_end pointers immediately following any invocation of bpf_skb_pull_data or helper functions that may linearize or reallocate socket buffer memory.

Engineers MUST ALWAYS reload ctx->data and ctx->data_end pointers immediately following any invocation of bpf_skb_pull_data or helper functions that may linearize or reallocate socket buffer memory.

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 bound all parsing loops with a compile-time static constant (#pragma unroll or explicitly bounded loop counter <= MAX_PARSER_ITERATIONS) to satisfy verifier state complexity and path pruning constraints.

Engineers MUST ALWAYS bound all parsing loops with a compile-time static constant (#pragma unroll or explicitly bounded loop counter <= MAX_PARSER_ITERATIONS) to satisfy verifier state complexity and path pruning constraints.

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 verify (void *)(cursor + struct_size) > data_end before every dereference, using unsigned comparison operators to prevent signed integer overflow vulnerabilities.

Engineers MUST verify (void *)(cursor + struct_size) > data_end before every dereference, using unsigned comparison operators to prevent signed integer overflow vulnerabilities.

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 SHOULD avoid storing large intermediate L7 state structures on the BPF stack

Code SHOULD avoid storing large intermediate L7 state structures on the BPF stack; engineers MUST enforce the BPF stack budget limit (<= 512 bytes) by using per-CPU array scratch buffers for L7 parsing state.

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 bound tail-call depth explicitly to prevent hitting the kernel-enforced MAX_TAIL_CALL_CNT (33 in modern kernels) which results in silent, unrecoverable packet drops.

Services MUST bound tail-call depth explicitly to prevent hitting the kernel-enforced MAX_TAIL_CALL_CNT (33 in modern kernels) which results in silent, unrecoverable packet drops.

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 assume contiguous SKB memory when parsing payload past the transport layer

Components NEVER assume contiguous SKB memory when parsing payload past the transport layer; non-linear packet slicing MUST use bpf_skb_pull_data or bpf_skb_load_bytes.

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 TC Ingress Packet Slicing and Verifier-Bounded Loop Invariants critical for AI coding assistants?

Enforces verifier-bounded loops and strict linear packet bounds verification for Layer 7 protocol parsing within Traffic Control (TC) ingress eBPF programs. Guarantees that packet pointers are recalculated after calls to bpf_skb_pull_data and prevents BPF verifier path explosion and tail-call stack overflows during high-throughput packet routing. Ensures production safety by maintaining the 512-byte BPF stack limit and restricting tail calls within kernel recursion limits. 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 (Unbounded L7 Header Parsing Loops with Stale SKB Data Pointers and Unchecked Tail Calls) 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