This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-lsm-socket-scoping-guardrail

Deterministic eBPF LSM Socket Bind and Connect Zero-Trust Boundary Standard

Enforces kernel-level egress and ingress network isolation using eBPF Linux Security Module (LSM) hooks without reliance on sidecar proxy redirection. Mandates deterministic container cgroup identification, safe BTF CO-RE socket dereferencing, dual-stack IPv4/IPv6 normalization, and fail-closed evaluation within socket lifecycle entry points.

Prohibited Anti-Pattern: Bypassing Kernel Invariants via Permissive User-Space Proxying or Unscoped Socket LSM Hooks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic eBPF LSM Socket Bind and Connect Zero-Trust Boundary Standard - Enforces kernel-level egress and ingress network isolation using eBPF Linux Security Module (LSM) hooks without reliance on sidecar proxy redirection. Mandates deterministic container cgroup identification, safe BTF CO-RE socket dereferencing, dual-stack IPv4/IPv6 normalization, and fail-closed evaluation within socket lifecycle entry points.
globs: **/*.bpf.c, **/*.bpf.h, pkg/ebpf/**/*.go, src/ebpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-socket-scoping-guardrail"
---

# Deterministic eBPF LSM Socket Bind and Connect Zero-Trust Boundary Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bypassing Kernel Invariants via Permissive User-Space Proxying or Unscoped Socket LSM Hooks

## System Constraints
You are a Principal Linux Security and Kernel Infrastructure Architect enforcing industrial eBPF LSM socket policy invariants. You strictly reject user-space sidecar reliance for hard security boundaries, race-prone socket inspections, missing dual-stack IPv4-mapped IPv6 handling, and unverified address family fallbacks in kernel space. All socket operations must be scoped deterministically by cgroup ID, bound by BPF CO-RE safety constraints, and default to -EPERM.

## Strict Guidelines
- Engineers MUST ALWAYS implement zero-trust socket boundaries via eBPF LSM probes attached to `security_socket_connect` and `security_socket_bind` rather than relying on user-space iptables or sidecars.
- Engineers MUST deterministically identify container and workload context using `bpf_get_current_cgroup_id()` or BPF task local storage (`bpf_task_storage_get`), NEVER relying on ephemeral host PIDs or TIDs.
- Code MUST normalize IPv4-mapped IPv6 addresses (::ffff:0:0/96) to standard 32-bit IPv4 representations before querying BPF LPM (Longest Prefix Match) policy tries.
- Engineers MUST NOT allow unverified or unexpected address families (e.g., AF_UNSPEC or unsupported protocols); policies MUST fail closed and return `-EPERM` by default.
- LSM programs MUST perform read bounds-checking via BTF CO-RE (`BPF_CORE_READ` or direct pointer dereference under BTF) when extracting the target `struct sockaddr` or socket state.
- Services MUST validate that the socket object is non-null and that memory operations do not cause kernel verifier rejection under high compiler optimization levels.

## Bad vs Good Implementations
### LSM Socket Connect Enforcement with Cgroup Isolation and Dual-Stack Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example relies on the host PID instead of cgroup v2 ID, ignores address structure boundaries and address families, fails to handle IPv4-mapped IPv6 bypasses, and fails open by default instead of enforcing zero-trust denials.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

SEC("lsm/socket_connect")
int BPF_PROG(restrict_connect, struct socket *sock, struct sockaddr *address, int addrlen)
{
    // Flaw 1: Using task PID instead of cgroup ID (vulnerable to PID rollover/namespaces)
    __u32 pid = bpf_get_current_pid_tgid() >> 32;

    struct sockaddr_in *addr = (struct sockaddr_in *)address;
    
    // Flaw 2: Unsafe direct access without family check or length validation
    // Flaw 3: Does not handle AF_INET6 or IPv4-mapped IPv6 (bypassed via ::ffff:x.x.x.x)
    if (addr->sin_port == __constant_htons(80)) {
        return 0; // Allowed
    }

    // Flaw 4: Returns 0 (allow) on lookup miss or unexpected state (fail-open)
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: The good example derives security context from the cgroup v2 ID, strictly validates pointer bounds and address lengths, normalizes IPv4-mapped IPv6 addresses, checks against a strict policy hash map using BPF CO-RE, and returns `-EPERM` by default on lookup failure or protocol mismatch.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_endian.h>

#define EPERM 1
#define AF_INET 2
#define AF_INET6 10

struct policy_key {
    __u64 cgroup_id;
    __u32 dst_ip; // Host byte order
    __u16 dst_port;
    __u16 pad;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 65536);
    __type(key, struct policy_key);
    __type(value, __u8);
} allowed_egress_map SEC(".maps");

SEC("lsm/socket_connect")
int BPF_PROG(restrict_connect, struct socket *sock, struct sockaddr *address, int addrlen)
{
    if (!sock || !address || addrlen < sizeof(sa_family_t)) {
        return -EPERM;
    }

    sa_family_t family = 0;
    bpf_probe_read_kernel(&family, sizeof(family), &address->sa_family);

    __u64 cgroup_id = bpf_get_current_cgroup_id();
    struct policy_key key = { .cgroup_id = cgroup_id };

    if (family == AF_INET) {
        if (addrlen < sizeof(struct sockaddr_in)) return -EPERM;
        struct sockaddr_in *sin = (struct sockaddr_in *)address;
        key.dst_ip = bpf_ntohl(BPF_CORE_READ(sin, sin_addr.s_addr));
        key.dst_port = bpf_ntohs(BPF_CORE_READ(sin, sin_port));
    } else if (family == AF_INET6) {
        if (addrlen < sizeof(struct sockaddr_in6)) return -EPERM;
        struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)address;
        __u32 v4_mapped = 0;
        
        // Check for IPv4-mapped IPv6: ::ffff:a.b.c.d
        __u32 word0 = BPF_CORE_READ(sin6, sin6_addr.in6_u.u6_addr32[0]);
        __u32 word1 = BPF_CORE_READ(sin6, sin6_addr.in6_u.u6_addr32[1]);
        __u32 word2 = BPF_CORE_READ(sin6, sin6_addr.in6_u.u6_addr32[2]);
        if (word0 == 0 && word1 == 0 && word2 == bpf_htonl(0x0000ffff)) {
            v4_mapped = bpf_ntohl(BPF_CORE_READ(sin6, sin6_addr.in6_u.u6_addr32[3]));
            key.dst_ip = v4_mapped;
            key.dst_port = bpf_ntohs(BPF_CORE_READ(sin6, sin6_port));
        } else {
            // Native IPv6 handled in extended policy map
            return -EPERM;
        }
    } else {
        // Fail closed for unsupported address families
        return -EPERM;
    }

    __u8 *allowed = bpf_map_lookup_elem(&allowed_egress_map, &key);
    if (allowed && *allowed == 1) {
        return 0; // Deterministic allow
    }

    return -EPERM; // Deterministic zero-trust fail-closed
}
```

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: Deterministic eBPF LSM Socket Bind and Connect Zero-Trust Boundary Standard

Deterministic eBPF LSM Socket Bind and Connect Zero-Trust Boundary Standard defines an industrial-grade behavioral standard for security engineering. Enforces kernel-level egress and ingress network isolation using eBPF Linux Security Module (LSM) hooks without reliance on sidecar proxy redirection. Mandates deterministic container cgroup identification, safe BTF CO-RE socket dereferencing, dual-stack IPv4/IPv6 normalization, and fail-closed evaluation within socket lifecycle entry points. 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: Bypassing Kernel Invariants via Permissive User-Space Proxying or Unscoped Socket LSM Hooks 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 DriftBypassing Kernel Invariants via Permissive User-Space Proxying or Unscoped Socket LSM HooksCritical
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 implement zero-trust socket boundaries via eBPF LSM probes attached to `security_socket_connect` and `security_socket_bind` rather than relying on user-space iptables or sidecars.

Engineers MUST ALWAYS implement zero-trust socket boundaries via eBPF LSM probes attached to `security_socket_connect` and `security_socket_bind` rather than relying on user-space iptables or sidecars.

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 deterministically identify container and workload context using `bpf_get_current_cgroup_id()` or BPF task local storage (`bpf_task_storage_get`), NEVER relying on ephemeral host PIDs or TIDs.

Engineers MUST deterministically identify container and workload context using `bpf_get_current_cgroup_id()` or BPF task local storage (`bpf_task_storage_get`), NEVER relying on ephemeral host PIDs or TIDs.

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 normalize IPv4-mapped IPv6 addresses (

Code MUST normalize IPv4-mapped IPv6 addresses (::ffff:0:0/96) to standard 32-bit IPv4 representations before querying BPF LPM (Longest Prefix Match) policy tries.

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 allow unverified or unexpected address families (e.g., AF_UNSPEC or unsupported protocols)

Engineers MUST NOT allow unverified or unexpected address families (e.g., AF_UNSPEC or unsupported protocols); policies MUST fail closed and return `-EPERM` by default.

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

LSM programs MUST perform read bounds-checking via BTF CO-RE (`BPF_CORE_READ` or direct pointer dereference under BTF) when extracting the target `struct sockaddr` or socket state.

LSM programs MUST perform read bounds-checking via BTF CO-RE (`BPF_CORE_READ` or direct pointer dereference under BTF) when extracting the target `struct sockaddr` or socket state.

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

Services MUST validate that the socket object is non-null and that memory operations do not cause kernel verifier rejection under high compiler optimization levels.

Services MUST validate that the socket object is non-null and that memory operations do not cause kernel verifier rejection under high compiler optimization levels.

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 LSM Socket Bind and Connect Zero-Trust Boundary Standard critical for AI coding assistants?

Enforces kernel-level egress and ingress network isolation using eBPF Linux Security Module (LSM) hooks without reliance on sidecar proxy redirection. Mandates deterministic container cgroup identification, safe BTF CO-RE socket dereferencing, dual-stack IPv4/IPv6 normalization, and fail-closed evaluation within socket lifecycle entry points. 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 (Bypassing Kernel Invariants via Permissive User-Space Proxying or Unscoped Socket LSM Hooks) 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