This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-sockops-ktls-l7-policy-guardrail

Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection

Enforces in-kernel L7 mutual TLS termination and zero-trust packet arbitration via Linux socket operations (BPF_PROG_TYPE_SOCK_OPS) and socket message programs (BPF_PROG_TYPE_SK_MSG). Bypasses userspace sidecar proxies by splicing peer sockets into BPF sockmaps and delegating cryptographic handoffs to Kernel TLS (kTLS) with atomic tail-call policy pipelines.

Prohibited Anti-Pattern: Punting Encrypted Wire Traffic to Userspace Sidecars or Operating on Pre-Decrypted L7 Buffers Without Kernel TLS Offload

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection - Enforces in-kernel L7 mutual TLS termination and zero-trust packet arbitration via Linux socket operations (BPF_PROG_TYPE_SOCK_OPS) and socket message programs (BPF_PROG_TYPE_SK_MSG). Bypasses userspace sidecar proxies by splicing peer sockets into BPF sockmaps and delegating cryptographic handoffs to Kernel TLS (kTLS) with atomic tail-call policy pipelines.
globs: src/ebpf/**/*.c, bpf/**/*.c, bpf/**/*.h, pkg/network/**/*.go, pkg/security/**/*.go, infra/ebpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sockops-ktls-l7-policy-guardrail"
---

# Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Punting Encrypted Wire Traffic to Userspace Sidecars or Operating on Pre-Decrypted L7 Buffers Without Kernel TLS Offload

## System Constraints
You are a Principal Systems Engineer and Kernel Security Architect enforcing strict eBPF socket-layer policy execution. You must ensure that L7 visibility, policy evaluation, and peer-to-peer traffic steering occur strictly within the Linux kernel socket layer via BPF sockmaps, sk_msg programs, and kTLS, eliminating userspace context switching, buffer re-allocations, and insecure plaintext leakage.

## Strict Guidelines
- Engineers MUST ALWAYS initialize and configure Kernel TLS (ULP tls / TCP_ULP) before attaching BPF sk_msg parsers to enforce policy on decrypted plaintext streams (sk_msg->data).
- Engineers MUST NEVER inspect or parse L7 protocol frames directly on raw sk_buff payloads in TC/XDP layers when the transport is TLS-encrypted.
- Engineers MUST ALWAYS verify verifier bounds on sk_msg data pointers (data + offset <= data_end) using 64-bit integer arithmetic prior to every dereference.
- Programs MUST ALWAYS return SK_PASS or SK_DROP deterministically, ensuring unhandled protocol frames are never implicitly forwarded without policy verification.
- Sockmap insertions MUST verify socket states via BPF_SOCK_OPS_STATE_CB or BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to guarantee only ESTABLISHED sockets enter the redirection map.
- Components NEVER fall back to unencrypted TCP socket redirection when kTLS socket option negotiation (setsockopt SOL_TCP, TCP_ULP, 'tls') fails.

## Bad vs Good Implementations
### BPF sk_msg L7 Header Inspection and Sockmap Redirection with kTLS Plaintext Bounds Checking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accesses sk_msg payload pointers without validating (data + len <= data_end), causing kernel verifier rejection. It fails to verify kTLS session flags and blindly passes non-matching or malformed frames instead of enforcing strict zero-trust drop semantics.
```c
// Flawed: Inspects sk_msg without bound checks and redirects encrypted/unvalidated streams
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

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

SEC("sk_msg")
int bpf_l7_filter_bad(struct sk_msg_md *msg)
{
    // Anti-pattern: No pointer bounds validation against msg->data_end
    // Blindly assumes payload is decrypted and reads out-of-bounds
    char *data = (char *)(long)msg->data;
    if (data[0] == 'G' && data[1] == 'E' && data[2] == 'T') {
        __u32 key = 0;
        bpf_msg_redirect_hash(msg, &sock_map, &key, BPF_F_INGRESS);
        return SK_PASS;
    }
    return SK_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict bounds verification against data_end before dereference, ensuring kernel verifier compliance. Evaluates decrypted L7 tokens exposed via kTLS socket buffers and applies zero-trust isolation by dropping unauthorized frames by default.
```c
// Production-grade: Bounds-safe L7 policy enforcement on kTLS socket stream with strict verdict drops
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

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

#define HTTP_GET_PREFIX 0x20544547 /* 'G' 'E' 'T' ' ' in little-endian */

SEC("sk_msg")
int bpf_l7_filter_good(struct sk_msg_md *msg)
{
    void *data = (void *)(long)msg->data;
    void *data_end = (void *)(long)msg->data_end;

    /* Strict verifier invariant: verify minimum 4 bytes exist for method check */
    if ((char *)data + sizeof(__u32) > (char *)data_end)
        return SK_DROP;

    /* Inspect plaintext HTTP token offloaded via in-kernel kTLS */
    __u32 method = *(__u32 *)data;
    if (method == HTTP_GET_PREFIX) {
        __u32 target_peer = 1;
        long err = bpf_msg_redirect_hash(msg, &sock_map, &target_peer, BPF_F_INGRESS);
        if (err == 0)
            return SK_PASS;
    }

    /* Zero-trust invariant: explicitly drop unauthorized or non-matching frames */
    return SK_DROP;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection

Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection defines an industrial-grade behavioral standard for devops engineering. Enforces in-kernel L7 mutual TLS termination and zero-trust packet arbitration via Linux socket operations (BPF_PROG_TYPE_SOCK_OPS) and socket message programs (BPF_PROG_TYPE_SK_MSG). Bypasses userspace sidecar proxies by splicing peer sockets into BPF sockmaps and delegating cryptographic handoffs to Kernel TLS (kTLS) with atomic tail-call policy pipelines. 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: Punting Encrypted Wire Traffic to Userspace Sidecars or Operating on Pre-Decrypted L7 Buffers Without Kernel TLS Offload 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 DriftPunting Encrypted Wire Traffic to Userspace Sidecars or Operating on Pre-Decrypted L7 Buffers Without Kernel TLS OffloadCritical
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 initialize and configure Kernel TLS (ULP tls / TCP_ULP) before attaching BPF sk_msg parsers to enforce policy on decrypted plaintext streams (sk_msg->data).

Engineers MUST ALWAYS initialize and configure Kernel TLS (ULP tls / TCP_ULP) before attaching BPF sk_msg parsers to enforce policy on decrypted plaintext streams (sk_msg->data).

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 inspect or parse L7 protocol frames directly on raw sk_buff payloads in TC/XDP layers when the transport is TLS-encrypted.

Engineers MUST NEVER inspect or parse L7 protocol frames directly on raw sk_buff payloads in TC/XDP layers when the transport is TLS-encrypted.

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 verify verifier bounds on sk_msg data pointers (data + offset <= data_end) using 64-bit integer arithmetic prior to every dereference.

Engineers MUST ALWAYS verify verifier bounds on sk_msg data pointers (data + offset <= data_end) using 64-bit integer arithmetic prior to every dereference.

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

Programs MUST ALWAYS return SK_PASS or SK_DROP deterministically, ensuring unhandled protocol frames are never implicitly forwarded without policy verification.

Programs MUST ALWAYS return SK_PASS or SK_DROP deterministically, ensuring unhandled protocol frames are never implicitly forwarded without policy verification.

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

Sockmap insertions MUST verify socket states via BPF_SOCK_OPS_STATE_CB or BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to guarantee only ESTABLISHED sockets enter the redirection map.

Sockmap insertions MUST verify socket states via BPF_SOCK_OPS_STATE_CB or BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB to guarantee only ESTABLISHED sockets enter the redirection 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.
6

Components NEVER fall back to unencrypted TCP socket redirection when kTLS socket option negotiation (setsockopt SOL_TCP, TCP_ULP, 'tls') fails.

Components NEVER fall back to unencrypted TCP socket redirection when kTLS socket option negotiation (setsockopt SOL_TCP, TCP_ULP, 'tls') fails.

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 Deterministic eBPF Socket-Level kTLS Policy Enforcement and Sockmap Redirection critical for AI coding assistants?

Enforces in-kernel L7 mutual TLS termination and zero-trust packet arbitration via Linux socket operations (BPF_PROG_TYPE_SOCK_OPS) and socket message programs (BPF_PROG_TYPE_SK_MSG). Bypasses userspace sidecar proxies by splicing peer sockets into BPF sockmaps and delegating cryptographic handoffs to Kernel TLS (kTLS) with atomic tail-call policy pipelines. 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 (Punting Encrypted Wire Traffic to Userspace Sidecars or Operating on Pre-Decrypted L7 Buffers Without Kernel TLS Offload) 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

Deterministic