This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-sockops-kernel-bypass-mtls-auth-guardrail

eBPF sockops Kernel-Bypass Authorization Verification Standard

Enforces that eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_MAP_TYPE_SOCKMAP implementations never unconditionally redirect socket buffers at the transport layer without explicit userspace attestation of Layer-7 authorization and mTLS identity. Prevents premature sk_msg/sockops kernel-bypass which evades iptables, netfilter, service mesh policy checks, and SPIFFE/SPIRE identity validation before handshake finalization.

Prohibited Anti-Pattern: Blind BPF_SOCK_OPS Socket Redirection Bypassing L7 Authorization and Mutual TLS Enforcement

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF sockops Kernel-Bypass Authorization Verification Standard - Enforces that eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_MAP_TYPE_SOCKMAP implementations never unconditionally redirect socket buffers at the transport layer without explicit userspace attestation of Layer-7 authorization and mTLS identity. Prevents premature sk_msg/sockops kernel-bypass which evades iptables, netfilter, service mesh policy checks, and SPIFFE/SPIRE identity validation before handshake finalization.
globs: **/*.c, **/*.bpf.c, **/*.go, src/**/*.{ts,tsx}, pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sockops-kernel-bypass-mtls-auth-guardrail"
---

# eBPF sockops Kernel-Bypass Authorization Verification Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Blind BPF_SOCK_OPS Socket Redirection Bypassing L7 Authorization and Mutual TLS Enforcement

## System Constraints
You are a Principal Security Architect enforcing the eBPF sockops Kernel-Bypass Authorization Verification Standard. Kernel-level socket redirection (sockmap / BPF_MAP_TYPE_SOCKHASH via bpf_msg_redirect_hash or bpf_sock_hash_update) achieves extreme acceleration by short-circuiting TCP/IP traversal, but completely evades host network firewalls, connection tracking (conntrack), and Layer-7 policy evaluation. You must mandate that no socket entry is added to an active redirection sockmap during BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB or PASSIVE_ESTABLISHED_CB callbacks without cryptographic identity verification. Redirection MUST be gated on explicit user-space verification of completed mTLS handshakes and validated SPIFFE IDs, managed via a synchronized security state BPF map.

## Strict Guidelines
- Engineers MUST NOT populate BPF_MAP_TYPE_SOCKMAP or BPF_MAP_TYPE_SOCKHASH directly inside raw BPF_SOCK_OPS_ESTABLISHED callbacks prior to userspace cryptographic handshake completion.
- Engineers MUST ALWAYS enforce a two-phase authorization model where initial TCP streams remain in standard network stack traversal until a userspace proxy/agent attests the mTLS session and populates an authorized connection map.
- eBPF sock_ops programs MUST check an explicit authorization map (e.g., auth_sessions) containing the peer identity and authorization epoch before calling bpf_sock_hash_update.
- Services MUST immediately purge sockets from the sockmap upon receiving TCP FIN/RST or TLS session termination events to prevent socket descriptor reuse attacks and cross-tenant traffic leakage.
- Components NEVER bypass L7 inspection when regulatory or organizational audit logging mandates full payload visibility, unless end-to-end payload cryptography is verified and session keys are non-repudiated.

## Bad vs Good Implementations
### Unauthenticated Socket Redirection vs. Policy-Gated Userspace Attestation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The BPF program immediately injects the connected socket into the redirection sockmap as soon as TCP completes the 3-way handshake. At this stage, no TLS handshake has occurred, no client certificate has been validated, and L7 policies (e.g., SPIFFE identity, RBAC) are bypassed entirely, enabling unauthorized lateral movement.
```c
// VULNERABLE: Direct kernel sockmap insertion on TCP establishment
// Completely bypasses host firewall and any pending mTLS/L7 authorization!
SEC("sockops")
int bpf_sockops_handler(struct bpf_sock_ops *skops) {
    if (skops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
        skops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB) {
        // Unconditionally redirecting traffic before identity verification
        struct sock_key key = {};
        extract_socket_key(skops, &key);
        bpf_sock_hash_update(skops, &sock_ops_map, &key, BPF_NOEXIST);
    }
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: The socket is only accelerated through sockmap redirection once userspace has validated the mTLS handshake and written an attested state record to `auth_sessions_map`. Unauthenticated handshakes traverse standard network pipelines for proxy inspection and policy enforcement.
```c
// SECURE: Kernel redirection is gated on verified L7 mTLS session state
SEC("sockops")
int bpf_sockops_handler(struct bpf_sock_ops *skops) {
    if (skops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
        skops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB) {
        struct sock_key key = {};
        extract_socket_key(skops, &key);

        // Query userspace-attested authorization map
        struct auth_policy *policy = bpf_map_lookup_elem(&auth_sessions_map, &key);
        if (!policy || policy->mtls_state != MTLS_ESTABLISHED_AND_VALIDATED) {
            // Pass through standard Linux TCP/IP stack to userspace mesh proxy for TLS negotiation
            return 0;
        }

        // Only bypass the network stack once userspace has verified identity and ACL
        bpf_sock_hash_update(skops, &sock_ops_map, &key, BPF_NOEXIST);
    }
    return 0;
}
```

### Userspace Agent Policy Attestation & Socket Registration Controller

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The controller executes eBPF bypass configuration on raw TCP connection initiation, completely prior to TLS negotiation or certificate exchange, breaking mutual TLS guarantees.
```typescript
// VULNERABLE: Enabling sockmap redirection indiscriminately on raw TCP connect
import { Socket } from 'net';

function onConnection(socket: Socket): void {
  // Anti-pattern: Marking socket as accelerated before mTLS handshake completes
  ebpfClient.enableSockmapBypass({
    srcIp: socket.remoteAddress!,
    srcPort: socket.remotePort!,
    dstIp: socket.localAddress!,
    dstPort: socket.localPort!
  });
}
```

#### Production Standard (Correct)
> **Standard**: Kernel bypass authorization is strictly tied to the `secureConnect` event, explicitly validating the client certificate SAN for a trusted SPIFFE identity before updating the eBPF authorization map.
```typescript
// SECURE: Enforcing mTLS handshake completion and SPIFFE ID validation prior to kernel bypass
import { TLSSocket } from 'tls';

interface EbpfBypassConfig {
  srcIp: string;
  srcPort: number;
  dstIp: string;
  dstPort: number;
  authorizedSpiffeId: string;
  mtlsState: number;
}

const MTLS_ESTABLISHED_AND_VALIDATED = 1;

async function handleMtlsConnection(tlsSocket: TLSSocket, expectedSpiffeId: string): Promise<void> {
  tlsSocket.on('secureConnect', async () => {
    const peerCert = tlsSocket.getPeerCertificate();
    const sanUri = peerCert.subjectaltname?.split(',').find(s => s.trim().startsWith('URI:spiffe://'));
    
    if (!sanUri || sanUri.replace('URI:', '').trim() !== expectedSpiffeId) {
      tlsSocket.destroy(new Error('Unauthorized SPIFFE Identity: mTLS verification failed'));
      return;
    }

    const bypassPayload: EbpfBypassConfig = {
      srcIp: tlsSocket.remoteAddress!,
      srcPort: tlsSocket.remotePort!,
      dstIp: tlsSocket.localAddress!,
      dstPort: tlsSocket.localPort!,
      authorizedSpiffeId: expectedSpiffeId,
      mtlsState: MTLS_ESTABLISHED_AND_VALIDATED
    };

    // Only notify eBPF auth map after identity is proven
    await ebpfClient.registerAuthorizedSession(bypassPayload);
  });
}
```

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 Kernel-Bypass Authorization Verification Standard

eBPF sockops Kernel-Bypass Authorization Verification Standard defines an industrial-grade behavioral standard for security engineering. Enforces that eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_MAP_TYPE_SOCKMAP implementations never unconditionally redirect socket buffers at the transport layer without explicit userspace attestation of Layer-7 authorization and mTLS identity. Prevents premature sk_msg/sockops kernel-bypass which evades iptables, netfilter, service mesh policy checks, and SPIFFE/SPIRE identity validation before handshake finalization. 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 BPF_SOCK_OPS Socket Redirection Bypassing L7 Authorization and Mutual TLS Enforcement 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 BPF_SOCK_OPS Socket Redirection Bypassing L7 Authorization and Mutual TLS EnforcementCritical
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 NOT populate BPF_MAP_TYPE_SOCKMAP or BPF_MAP_TYPE_SOCKHASH directly inside raw BPF_SOCK_OPS_ESTABLISHED callbacks prior to userspace cryptographic handshake completion.

Engineers MUST NOT populate BPF_MAP_TYPE_SOCKMAP or BPF_MAP_TYPE_SOCKHASH directly inside raw BPF_SOCK_OPS_ESTABLISHED callbacks prior to userspace cryptographic handshake completion.

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 enforce a two-phase authorization model where initial TCP streams remain in standard network stack traversal until a userspace proxy/agent attests the mTLS session and populates an authorized connection map.

Engineers MUST ALWAYS enforce a two-phase authorization model where initial TCP streams remain in standard network stack traversal until a userspace proxy/agent attests the mTLS session and populates an authorized connection map.

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

eBPF sock_ops programs MUST check an explicit authorization map (e.g., auth_sessions) containing the peer identity and authorization epoch before calling bpf_sock_hash_update.

eBPF sock_ops programs MUST check an explicit authorization map (e.g., auth_sessions) containing the peer identity and authorization epoch before calling bpf_sock_hash_update.

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

Services MUST immediately purge sockets from the sockmap upon receiving TCP FIN/RST or TLS session termination events to prevent socket descriptor reuse attacks and cross-tenant traffic leakage.

Services MUST immediately purge sockets from the sockmap upon receiving TCP FIN/RST or TLS session termination events to prevent socket descriptor reuse attacks and cross-tenant traffic leakage.

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

Components NEVER bypass L7 inspection when regulatory or organizational audit logging mandates full payload visibility, unless end-to-end payload cryptography is verified and session keys are non-repudiated.

Components NEVER bypass L7 inspection when regulatory or organizational audit logging mandates full payload visibility, unless end-to-end payload cryptography is verified and session keys are non-repudiated.

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 Kernel-Bypass Authorization Verification Standard critical for AI coding assistants?

Enforces that eBPF BPF_PROG_TYPE_SOCK_OPS and BPF_MAP_TYPE_SOCKMAP implementations never unconditionally redirect socket buffers at the transport layer without explicit userspace attestation of Layer-7 authorization and mTLS identity. Prevents premature sk_msg/sockops kernel-bypass which evades iptables, netfilter, service mesh policy checks, and SPIFFE/SPIRE identity validation before handshake finalization. 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 BPF_SOCK_OPS Socket Redirection Bypassing L7 Authorization and Mutual TLS Enforcement) 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