This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-sock-ops-zero-copy-redirection-policy

eBPF SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail

Enforces zero-copy stream redirection via eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG between co-located network namespaces. Prevents userspace context switching through sidecar proxies by maintaining strict sockmap lifecycle hooks and 4-tuple connection symmetry in kernel space.

Prohibited Anti-Pattern: Traversing Complete TCP/IP Network Stack and Context Switching into Userspace Proxy for Co-located Pod Communication

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail - Enforces zero-copy stream redirection via eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG between co-located network namespaces. Prevents userspace context switching through sidecar proxies by maintaining strict sockmap lifecycle hooks and 4-tuple connection symmetry in kernel space.
globs: bpf/**/*.c, bpf/**/*.h, src/network/**/*.c, src/network/**/*.rs, deploy/daemonsets/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sock-ops-zero-copy-redirection-policy"
---

# eBPF SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Traversing Complete TCP/IP Network Stack and Context Switching into Userspace Proxy for Co-located Pod Communication

## System Constraints
You are a Principal Systems and Kernel Engineer enforcing eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG Zero-Copy Socket Redirection. You must prevent non-zero-copy traversal through host networking stacks for co-located pods. Ensure every socket-level eBPF program validates connection state, addresses endianness cleanly via BPF helpers, handles map eviction cleanup safely, and prevents orphaned map elements during TCP FIN/RST states.

## Strict Guidelines
- Engineers MUST ALWAYS pair BPF_PROG_TYPE_SOCK_OPS with BPF_PROG_TYPE_SK_MSG maps (BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP) to achieve actual zero-copy payload forwarding.
- Engineers MUST capture BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to register inbound and outbound sockets into the socket map precisely once.
- Engineers MUST ALWAYS handle TCP tear-down state transitions (BPF_SOCK_OPS_STATE_CB with TCP_CLOSE or TCP_CLOSE_WAIT) by deleting the corresponding 4-tuple key from the sockmap to prevent dangling socket references and kernel panics.
- Engineers MUST NOT redirect traffic across distinct host boundaries or across different overlay endpoints using SK_MSG without verifying co-location via netns cookie (bpf_get_netns_cookie) or matching node host IP.
- Engineers MUST explicitly verify socket families (AF_INET, AF_INET6) and ensure all IPv4 addresses and port conversions strictly preserve network byte order using bpf_ntohl and bpf_ntohs before map lookups or mutations.

## Bad vs Good Implementations
### Kernel Sockmap Registration via SOCK_OPS

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to filter the specific socket callback phase (allowing half-open or unestablished connections into the map), ignores socket family/protocol validation, uses an incomplete key prone to collisions, and fails to handle socket removal on TCP connection close.
```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");

SEC("sockops")
int bpf_sockmap_bad(struct bpf_sock_ops *skops) {
    // ANTI-PATTERN: Blindly updating map without filtering state callbacks
    // or checking IP protocol, leads to dangling references and crash on teardown
    __u32 key = skops->remote_port;
    bpf_sock_map_update(skops, &sock_map, &key, BPF_ANY);
    return 1;
}
```

#### Production Standard (Correct)
> **Standard**: Validates the address family, targets specific TCP established states to register the 4-tuple, normalizes port and IP endianness, and cleans up entries on TCP_CLOSE to eliminate orphaned socket state.
```c
#include <linux/bpf.h>
#include <linux/tcp.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

struct sock_key {
    __u32 sip4;
    __u32 dip4;
    __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_map SEC(".maps");

static __always_inline void extract_key(struct bpf_sock_ops *skops, struct sock_key *key) {
    key->sip4 = skops->local_ip4;
    key->dip4 = skops->remote_ip4;
    key->sport = bpf_htonl(skops->local_port);
    key->dport = skops->remote_port; // Already network-byte order
}

SEC("sockops")
int bpf_sockmap_guardrail(struct bpf_sock_ops *skops) {
    if (skops->family != 2 /* AF_INET */) {
        return 0;
    }

    struct sock_key key = {};
    extract_key(skops, &key);

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

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 SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail

eBPF SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces zero-copy stream redirection via eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG between co-located network namespaces. Prevents userspace context switching through sidecar proxies by maintaining strict sockmap lifecycle hooks and 4-tuple connection symmetry in kernel space. 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: Traversing Complete TCP/IP Network Stack and Context Switching into Userspace Proxy for Co-located Pod Communication 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 DriftTraversing Complete TCP/IP Network Stack and Context Switching into Userspace Proxy for Co-located Pod CommunicationCritical
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 pair BPF_PROG_TYPE_SOCK_OPS with BPF_PROG_TYPE_SK_MSG maps (BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP) to achieve actual zero-copy payload forwarding.

Engineers MUST ALWAYS pair BPF_PROG_TYPE_SOCK_OPS with BPF_PROG_TYPE_SK_MSG maps (BPF_MAP_TYPE_SOCKHASH or BPF_MAP_TYPE_SOCKMAP) to achieve actual zero-copy payload forwarding.

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 capture BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to register inbound and outbound sockets into the socket map precisely once.

Engineers MUST capture BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to register inbound and outbound sockets into the socket map precisely once.

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 ALWAYS handle TCP tear-down state transitions (BPF_SOCK_OPS_STATE_CB with TCP_CLOSE or TCP_CLOSE_WAIT) by deleting the corresponding 4-tuple key from the sockmap to prevent dangling socket references and kernel panics.

Engineers MUST ALWAYS handle TCP tear-down state transitions (BPF_SOCK_OPS_STATE_CB with TCP_CLOSE or TCP_CLOSE_WAIT) by deleting the corresponding 4-tuple key from the sockmap to prevent dangling socket references and kernel panics.

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 NOT redirect traffic across distinct host boundaries or across different overlay endpoints using SK_MSG without verifying co-location via netns cookie (bpf_get_netns_cookie) or matching node host IP.

Engineers MUST NOT redirect traffic across distinct host boundaries or across different overlay endpoints using SK_MSG without verifying co-location via netns cookie (bpf_get_netns_cookie) or matching node host IP.

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

Engineers MUST explicitly verify socket families (AF_INET, AF_INET6) and ensure all IPv4 addresses and port conversions strictly preserve network byte order using bpf_ntohl and bpf_ntohs before map lookups or mutations.

Engineers MUST explicitly verify socket families (AF_INET, AF_INET6) and ensure all IPv4 addresses and port conversions strictly preserve network byte order using bpf_ntohl and bpf_ntohs before map lookups or mutations.

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 SOCK_OPS and SK_MSG Zero-Copy Kernel Socket Redirection Guardrail critical for AI coding assistants?

Enforces zero-copy stream redirection via eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_PROG_TYPE_SK_MSG between co-located network namespaces. Prevents userspace context switching through sidecar proxies by maintaining strict sockmap lifecycle hooks and 4-tuple connection symmetry in kernel space. 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 (Traversing Complete TCP/IP Network Stack and Context Switching into Userspace Proxy for Co-located Pod Communication) 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