This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-sockops-fastpath-conntrack-fencing

eBPF Sockops TCP Fast-Path Stateful Firewall Bypass Fencing

Enforces strict conntrack state machine synchronization and network security policy fencing before short-circuiting TCP streams via eBPF sockops and sockmap redirection. Prevents silent bypass of stateful firewall inspection, asymmetric connection tracking timeouts, and unauthorized intra-node microsegmentation bypasses.

Prohibited Anti-Pattern: Blind socket hash insertion on TCP handshake completion without firewall policy lookup or conntrack synchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF Sockops TCP Fast-Path Stateful Firewall Bypass Fencing - Enforces strict conntrack state machine synchronization and network security policy fencing before short-circuiting TCP streams via eBPF sockops and sockmap redirection. Prevents silent bypass of stateful firewall inspection, asymmetric connection tracking timeouts, and unauthorized intra-node microsegmentation bypasses.
globs: bpf/**/*.c, bpf/**/*.h, pkg/ebpf/**/*.go, src/ebpf/**/*.rs, kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sockops-fastpath-conntrack-fencing"
---

# eBPF Sockops TCP Fast-Path Stateful Firewall Bypass Fencing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind socket hash insertion on TCP handshake completion without firewall policy lookup or conntrack synchronization

## System Constraints
You are a Principal Systems and Kernel Security Engineer enforcing eBPF Sockops TCP Fast-Path Stateful Firewall Bypass Fencing. Your mission is to guarantee that kernel-space socket acceleration programs (BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG using BPF_MAP_TYPE_SOCKHASH/SOCKMAP) strictly adhere to conntrack state machine invariants, synchronize state with host firewalls, and never bypass network security policies or microsegmentation boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS verify explicit firewall/policy allowance via a security map lookup BEFORE inserting sockets into BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP.
- Engineers MUST NEVER redirect socket streams across distinct network namespaces or security tiers without verifying egress and ingress policy match on both local and remote socket endpoints.
- Code MUST strictly evaluate connection state to ensure sockets are in BPF_TCP_ESTABLISHED before fast-path activation, refusing premature acceleration during SYN/SYN-ACK handshake phases.
- Code MUST evict socket references from sockmap/sockhash tables immediately upon detecting BPF_SOCK_OPS_STATE_CHANGED transitions to BPF_TCP_CLOSE, BPF_TCP_CLOSE_WAIT, or BPF_TCP_FIN_WAIT1 to prevent stale socket reuse or descriptor hijacking.
- Services MUST implement a fail-closed fallback: if policy lookup fails, or if conntrack synchronization cannot be confirmed, the eBPF program MUST return BPF_OK without updating the sockhash, forcing traffic through the standard kernel network stack and netfilter/conntrack hooks.
- Components NEVER short-circuit traffic when conntrack-dependent features (NAT, application-layer gateways, or L7 deep-packet inspection) are configured on the socket path.

## Bad vs Good Implementations
### Sockops TCP Established Event Fencing and Conntrack Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sockets are placed into the fast-path map immediately without checking firewall policy rules, verifying conntrack tracking status, or ensuring security policy acceptance. This bypasses netfilter tables (iptables/nftables) and Cilium/Calico microsegmentation policies, leaving intermediate firewall state machine tracking orphaned.
```c
// INSECURE: Blind sockmap registration bypassing firewall policy and conntrack
SEC("sockops")
int bpf_sockmap_bad(struct bpf_sock_ops *skops) {
    __u32 op = skops->op;

    // Blindly insert any established connection directly into the sockmap
    if (op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB || 
        op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB) {
        struct sock_key key = {
            .sip4 = skops->local_ip4,
            .dip4 = skops->remote_ip4,
            .sport = bpf_ntohl(skops->local_port),
            .dport = skops->remote_port >> 16,
        };
        // Direct socket bypass: Netfilter conntrack and security policies are bypassed
        bpf_sock_hash_update(skops, &sock_ops_map, &key, BPF_NOEXIST);
    }
    return BPF_OK;
}
```

#### Production Standard (Correct)
> **Standard**: The program enforces state machine boundaries: it cleans up stale keys on TCP teardown states, validates that socket endpoints match security policy approval via an authoritative policy map, and safely falls back to standard kernel packet processing when authorization is absent.
```c
// SECURE: Conntrack-aware, policy-fenced sockops acceleration
SEC("sockops")
int bpf_sockmap_good(struct bpf_sock_ops *skops) {
    __u32 op = skops->op;

    switch (op) {
    case BPF_SOCK_OPS_STATE_CHANGED:
        // Evict sockets on teardown to prevent socket recycling race conditions
        if (skops->args[1] == BPF_TCP_CLOSE || skops->args[1] == BPF_TCP_CLOSE_WAIT) {
            struct sock_key key = {
                .sip4 = skops->local_ip4,
                .dip4 = skops->remote_ip4,
                .sport = bpf_ntohl(skops->local_port),
                .dport = skops->remote_port >> 16,
            };
            bpf_map_delete_elem(&sock_ops_map, &key);
        }
        break;

    case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
    case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
        // 1. Strict protocol verification: IPv4 TCP only
        if (skops->family != 2) {
            return BPF_OK;
        }

        struct sock_key key = {
            .sip4 = skops->local_ip4,
            .dip4 = skops->remote_ip4,
            .sport = bpf_ntohl(skops->local_port),
            .dport = skops->remote_port >> 16,
        };

        // 2. Fencing Guard: Query policy map to ensure stateful firewall permitted flow
        struct policy_verdict *verdict = bpf_map_lookup_elem(&policy_map, &key);
        if (!verdict || verdict->action != POLICY_ALLOW_ACCELERATION) {
            // Fallback to standard kernel stack to allow iptables/conntrack inspection
            return BPF_OK;
        }

        // 3. Insert into fast-path map only after verified conntrack & policy approval
        bpf_sock_hash_update(skops, &sock_ops_map, &key, BPF_NOEXIST);
        break;

    default:
        break;
    }

    return BPF_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 Sockops TCP Fast-Path Stateful Firewall Bypass Fencing

eBPF Sockops TCP Fast-Path Stateful Firewall Bypass Fencing defines an industrial-grade behavioral standard for devops engineering. Enforces strict conntrack state machine synchronization and network security policy fencing before short-circuiting TCP streams via eBPF sockops and sockmap redirection. Prevents silent bypass of stateful firewall inspection, asymmetric connection tracking timeouts, and unauthorized intra-node microsegmentation bypasses. 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: Blind socket hash insertion on TCP handshake completion without firewall policy lookup or conntrack synchronization 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 DriftBlind socket hash insertion on TCP handshake completion without firewall policy lookup or conntrack synchronizationCritical
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 explicit firewall/policy allowance via a security map lookup BEFORE inserting sockets into BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP.

Engineers MUST ALWAYS verify explicit firewall/policy allowance via a security map lookup BEFORE inserting sockets into BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP.

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 NEVER redirect socket streams across distinct network namespaces or security tiers without verifying egress and ingress policy match on both local and remote socket endpoints.

Engineers MUST NEVER redirect socket streams across distinct network namespaces or security tiers without verifying egress and ingress policy match on both local and remote socket endpoints.

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 strictly evaluate connection state to ensure sockets are in BPF_TCP_ESTABLISHED before fast-path activation, refusing premature acceleration during SYN/SYN-ACK handshake phases.

Code MUST strictly evaluate connection state to ensure sockets are in BPF_TCP_ESTABLISHED before fast-path activation, refusing premature acceleration during SYN/SYN-ACK handshake phases.

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 MUST evict socket references from sockmap/sockhash tables immediately upon detecting BPF_SOCK_OPS_STATE_CHANGED transitions to BPF_TCP_CLOSE, BPF_TCP_CLOSE_WAIT, or BPF_TCP_FIN_WAIT1 to prevent stale socket reuse or descriptor hijacking.

Code MUST evict socket references from sockmap/sockhash tables immediately upon detecting BPF_SOCK_OPS_STATE_CHANGED transitions to BPF_TCP_CLOSE, BPF_TCP_CLOSE_WAIT, or BPF_TCP_FIN_WAIT1 to prevent stale socket reuse or descriptor hijacking.

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 implement a fail-closed fallback

Services MUST implement a fail-closed fallback: if policy lookup fails, or if conntrack synchronization cannot be confirmed, the eBPF program MUST return BPF_OK without updating the sockhash, forcing traffic through the standard kernel network stack and netfilter/conntrack hooks.

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 short-circuit traffic when conntrack-dependent features (NAT, application-layer gateways, or L7 deep-packet inspection) are configured on the socket path.

Components NEVER short-circuit traffic when conntrack-dependent features (NAT, application-layer gateways, or L7 deep-packet inspection) are configured on the socket path.

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 Sockops TCP Fast-Path Stateful Firewall Bypass Fencing critical for AI coding assistants?

Enforces strict conntrack state machine synchronization and network security policy fencing before short-circuiting TCP streams via eBPF sockops and sockmap redirection. Prevents silent bypass of stateful firewall inspection, asymmetric connection tracking timeouts, and unauthorized intra-node microsegmentation bypasses. 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 (Blind socket hash insertion on TCP handshake completion without firewall policy lookup or conntrack synchronization) 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