This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-sockmap-l7-proxy-bypass-standard

eBPF SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants

Enforces strict kernel-level architectural controls for eBPF SOCKMAP/SOCKHASH socket redirection to bypass the host TCP/IP stack for local proxy and inter-pod communications. Requires explicit 4-tuple connection validation, bidirectional map insertion, TLS termination awareness, and resilient fallback mechanisms to standard veth stack processing upon socket state teardown.

Prohibited Anti-Pattern: Blind sock_hash redirection causing silent TCP state divergence, broken TLS handshakes, and hung connections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants - Enforces strict kernel-level architectural controls for eBPF SOCKMAP/SOCKHASH socket redirection to bypass the host TCP/IP stack for local proxy and inter-pod communications. Requires explicit 4-tuple connection validation, bidirectional map insertion, TLS termination awareness, and resilient fallback mechanisms to standard veth stack processing upon socket state teardown.
globs: **/*.bpf.c, **/*.bpf.h, **/ebpf/**/*.c, **/ebpf/**/*.go, **/pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sockmap-l7-proxy-bypass-standard"
---

# eBPF SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind sock_hash redirection causing silent TCP state divergence, broken TLS handshakes, and hung connections

## System Constraints
You are a Principal Systems & Kernel Engineer enforcing eBPF BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH socket-level L7 proxy bypass acceleration. Mandate strict 5-tuple lookup validation, bidirectional sockmap tracking, zero-copy verdict semantics, and proper handling of TCP lifecycle states (ESTABLISHED only) to prevent connection stalling, memory leaks, and protocol bypass vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS restrict BPF_PROG_TYPE_SOCK_OPS map updates exclusively to the BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB events to prevent half-open or unestablished sockets from entering the sockmap.
- Engineers MUST ALWAYS delete the corresponding socket keys from BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP upon BPF_SOCK_OPS_STATE_CB when the socket transitions out of BPF_TCP_ESTABLISHED (e.g., TCP_CLOSE, TCP_CLOSE_WAIT, TCP_LAST_ACK).
- Engineers MUST NOT redirect traffic via bpf_msg_redirect_hash or bpf_sk_redirect_hash if the connection encapsulates mTLS or TLS inside the payload unless the eBPF program integrates with kTLS (TCP_ULP_TLS) or explicitly evaluates after user-space termination.
- Engineers MUST verify the return value of bpf_msg_redirect_hash / bpf_msg_redirect_map and MUST return SK_PASS on any lookup miss, negative error code, or transient failure to allow standard TCP/IP fallback.
- Code MUST construct socket keys using explicit, deterministic network-byte-order 4-tuples (source IP, destination IP, source port, destination port) with bidirectional mirrored key lookups for ingress and egress paths.

## Bad vs Good Implementations
### eBPF Sockops and SK_MSG Socket-Map Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example inserts unestablished sockets into the map using only the remote port as a key, fails to handle connection termination events (causing stale pointer lookups and dropped connections), and blindly returns the result of bpf_msg_redirect_map without falling back to SK_PASS when redirection fails.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_SOCKMAP);
    __uint(max_entries, 65535);
    __type(key, __u32);
    __type(value, __u64);
} sock_map SEC(".maps");

// Flaw: Unconditionally pushes socket into map regardless of TCP state
// Flaw: Does not clean up map entry on TCP_CLOSE, leading to stale socket redirections
SEC("sockops")
int bpf_sockmap_ops(struct bpf_sock_ops *skops) {
    __u32 key = skops->remote_port;
    bpf_sock_map_update(skops, &sock_map, &key, BPF_NOEXIST);
    return 0;
}

SEC("sk_msg")
int bpf_sk_msg(struct sk_msg_md *msg) {
    __u32 key = msg->remote_port;
    // Flaw: Drops packets on redirection failure instead of passing to host stack
    return bpf_msg_redirect_map(msg, &sock_map, key, BPF_F_INGRESS);
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation uses a 4-tuple key, registers sockets only after the TCP handshake completes (ESTABLISHED callbacks), purges sockets on TCP close states, and safely falls back to standard kernel TCP/IP network traversal (SK_PASS) whenever hash lookup or redirection fails.
```c
#include <linux/bpf.h>
#include <bpf/bpf_endian.h>
#include <bpf/bpf_helpers.h>

struct sock_key {
    __u32 sip;
    __u32 dip;
    __u32 sport;
    __u32 dport;
};

struct {
    __uint(type, BPF_MAP_TYPE_SOCKHASH);
    __uint(max_entries, 65535);
    __type(key, struct sock_key);
    __type(value, __u64);
} sock_hash SEC(".maps");

static __always_inline void extract_key(struct bpf_sock_ops *skops, struct sock_key *key) {
    key->sip = skops->local_ip4;
    key->dip = skops->remote_ip4;
    key->sport = bpf_htonl(skops->local_port);
    key->dport = skops->remote_port;
}

SEC("sockops")
int bpf_sockmap_ops(struct bpf_sock_ops *skops) {
    struct sock_key key = {};
    __u32 op = skops->op;

    switch (op) {
    case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
    case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
        extract_key(skops, &key);
        bpf_sock_hash_update(skops, &sock_hash, &key, BPF_NOEXIST);
        break;
    case BPF_SOCK_OPS_STATE_CB:
        if (skops->args[1] == BPF_TCP_CLOSE || skops->args[1] == BPF_TCP_CLOSE_WAIT) {
            extract_key(skops, &key);
            bpf_map_delete_elem(&sock_hash, &key);
        }
        break;
    default:
        break;
    }
    return 0;
}

SEC("sk_msg")
int bpf_sk_msg(struct sk_msg_md *msg) {
    struct sock_key key = {
        .sip = msg->remote_ip4,
        .dip = msg->local_ip4,
        .sport = msg->remote_port,
        .dport = bpf_htonl(msg->local_port),
    };

    int ret = bpf_msg_redirect_hash(msg, &sock_hash, &key, BPF_F_INGRESS);
    if (ret != SK_PASS) {
        // Fallback to regular TCP/IP stack if redirect target is missing or fails
        return SK_PASS;
    }
    return SK_PASS;
}
```

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 SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants

eBPF SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants defines an industrial-grade behavioral standard for devops engineering. Enforces strict kernel-level architectural controls for eBPF SOCKMAP/SOCKHASH socket redirection to bypass the host TCP/IP stack for local proxy and inter-pod communications. Requires explicit 4-tuple connection validation, bidirectional map insertion, TLS termination awareness, and resilient fallback mechanisms to standard veth stack processing upon socket state teardown. 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 sock_hash redirection causing silent TCP state divergence, broken TLS handshakes, and hung connections 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 sock_hash redirection causing silent TCP state divergence, broken TLS handshakes, and hung connectionsCritical
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 restrict BPF_PROG_TYPE_SOCK_OPS map updates exclusively to the BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB events to prevent half-open or unestablished sockets from entering the sockmap.

Engineers MUST ALWAYS restrict BPF_PROG_TYPE_SOCK_OPS map updates exclusively to the BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB events to prevent half-open or unestablished sockets from entering the 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 ALWAYS delete the corresponding socket keys from BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP upon BPF_SOCK_OPS_STATE_CB when the socket transitions out of BPF_TCP_ESTABLISHED (e.g., TCP_CLOSE, TCP_CLOSE_WAIT, TCP_LAST_ACK).

Engineers MUST ALWAYS delete the corresponding socket keys from BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP upon BPF_SOCK_OPS_STATE_CB when the socket transitions out of BPF_TCP_ESTABLISHED (e.g., TCP_CLOSE, TCP_CLOSE_WAIT, TCP_LAST_ACK).

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 NOT redirect traffic via bpf_msg_redirect_hash or bpf_sk_redirect_hash if the connection encapsulates mTLS or TLS inside the payload unless the eBPF program integrates with kTLS (TCP_ULP_TLS) or explicitly evaluates after user-space termination.

Engineers MUST NOT redirect traffic via bpf_msg_redirect_hash or bpf_sk_redirect_hash if the connection encapsulates mTLS or TLS inside the payload unless the eBPF program integrates with kTLS (TCP_ULP_TLS) or explicitly evaluates after user-space termination.

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 verify the return value of bpf_msg_redirect_hash / bpf_msg_redirect_map and MUST return SK_PASS on any lookup miss, negative error code, or transient failure to allow standard TCP/IP fallback.

Engineers MUST verify the return value of bpf_msg_redirect_hash / bpf_msg_redirect_map and MUST return SK_PASS on any lookup miss, negative error code, or transient failure to allow standard TCP/IP fallback.

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 MUST construct socket keys using explicit, deterministic network-byte-order 4-tuples (source IP, destination IP, source port, destination port) with bidirectional mirrored key lookups for ingress and egress paths.

Code MUST construct socket keys using explicit, deterministic network-byte-order 4-tuples (source IP, destination IP, source port, destination port) with bidirectional mirrored key lookups for ingress and egress paths.

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 SOCKMAP Socket-Level L7 Proxy Bypass and Acceleration Invariants critical for AI coding assistants?

Enforces strict kernel-level architectural controls for eBPF SOCKMAP/SOCKHASH socket redirection to bypass the host TCP/IP stack for local proxy and inter-pod communications. Requires explicit 4-tuple connection validation, bidirectional map insertion, TLS termination awareness, and resilient fallback mechanisms to standard veth stack processing upon socket state teardown. 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 sock_hash redirection causing silent TCP state divergence, broken TLS handshakes, and hung connections) 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