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

Deterministic Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM

Enforces deterministic zero-trust network egress and UNIX domain socket binding restrictions directly at the Linux kernel boundary using eBPF LSM hooks (`socket_bind`, `socket_connect`). Eliminates user-space interception bypasses, LD_PRELOAD stripping, and namespace hopping in containerized multi-tenant node architectures by coupling kernel probes with immutable cgroup identifiers.

Prohibited Anti-Pattern: Relying on User-Space Sidecar Proxies or LD_PRELOAD Wrappers for Socket Access Control

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM - Enforces deterministic zero-trust network egress and UNIX domain socket binding restrictions directly at the Linux kernel boundary using eBPF LSM hooks (`socket_bind`, `socket_connect`). Eliminates user-space interception bypasses, LD_PRELOAD stripping, and namespace hopping in containerized multi-tenant node architectures by coupling kernel probes with immutable cgroup identifiers.
globs: bpf/**/*.bpf.c, bpf/**/*.bpf.h, src/security/**/*.rs, src/security/**/*.go, pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-socket-bind-verification-standard"
---

# Deterministic Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on User-Space Sidecar Proxies or LD_PRELOAD Wrappers for Socket Access Control

## System Constraints
You are a Principal Security Architect and Kernel Systems Engineer enforcing the eBPF LSM Socket Bind Verification Standard. You must mandate that all network policy enforcement, UNIX domain socket boundaries, and port-binding validation occur deterministically within kernel space via eBPF Linux Security Module (LSM) hooks (`lsm/socket_bind`, `lsm/socket_connect`). Prohibit any design that permits bypassable user-space proxy interception, mutable container-environment bindings, or unpinned eBPF maps for tenant identity resolution.

## Strict Guidelines
- Engineers MUST ALWAYS verify socket operations using eBPF LSM probe hooks (`SEC("lsm/socket_bind")` and `SEC("lsm/socket_connect")`) instead of cgroup/sock or kprobes which can be bypassed via asynchronous socket creation or raw sockets.
- Engineers MUST evaluate tenant context exclusively through deterministic kernel structures using `bpf_get_current_cgroup_id()` or pinned BPF task storage maps, never trusting user-space-passed headers, PID parameters, or environment variables.
- Engineers MUST validate both IPv4/IPv6 sockaddr structs and AF_UNIX `sockaddr_un` pathnames to prevent host root filesystem socket poisoning (e.g., hijacking `/var/run/docker.sock`).
- Code MUST return `-EPERM` (operation not permitted) or `-EACCES` synchronously from the LSM hook whenever an unauthorized bind or egress destination is detected, before any system resource allocation occurs.
- BPF maps holding authorization policies (LPM trie for CIDRs, hash maps for cgroup-to-port bindings) MUST be declared as BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LPM_TRIE with read-only flags (`BPF_F_RDONLY_PROG`) set from user-space loaders to eliminate in-kernel tamper vectors.
- Engineers MUST NOT rely on iptables, nftables, or Envoy sidecars as the sole boundary for multi-tenant containment, as container escapes and `CAP_NET_ADMIN` leaks invalidate user-space proxy models.

## Bad vs Good Implementations
### eBPF LSM Program Enforcing Strict Cgroup Socket Bind Policy

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kprobes are tracing primitives, not mediation primitives. They execute after-the-fact or concurrently with socket state updates, cannot synchronously prevent allocation in a fail-safe manner, and do not provide an immutable security boundary against adversarial processes in multi-tenant pods.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>

// ANTI-PATTERN: Using raw kprobe to detect socket bind;
// Cannot deterministically block operations, vulnerable to race conditions (TOCTOU),
// and relies on mutable task attributes.
SEC("kprobe/sys_bind")
int BPF_KPROBE(trace_bind, int fd, struct sockaddr *addr, int addrlen) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    bpf_printk("Process %d attempted bind\n", pid);
    // Cannot synchronously return -EPERM to kernel socket allocator from a classic kprobe
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Leverages the Linux Security Module (LSM) socket_bind hook (`BPF_PROG(restrict_bind)`), which executes synchronously in the kernel's LSM mediation path. It extracts an immutable cgroup ID, applies a deterministic Default Deny policy against a protected in-kernel hash map, and halts unauthorized port allocation with `-EACCES` before the port is reserved.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_endian.h>

#define EACCES 13
#define AF_INET 2

struct bind_rule {
    __u16 allowed_port_min;
    __u16 allowed_port_max;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10240);
    __type(key, __u64); // cgroup_id
    __type(value, struct bind_rule);
    __uint(map_flags, BPF_F_RDONLY_PROG);
} tenant_bind_policy SEC(".maps");

SEC("lsm/socket_bind")
int BPF_PROG(restrict_bind, struct socket *sock, struct sockaddr *address, int addrlen) {
    if (!address || addrlen < sizeof(struct sockaddr_in)) {
        return -EACCES;
    }

    if (address->sa_family != AF_INET) {
        // Only evaluate IPv4 in this branch; non-matching protocols enforced by sibling policies
        return 0;
    }

    __u64 cgroup_id = bpf_get_current_cgroup_id();
    struct bind_rule *rule = bpf_map_lookup_elem(&tenant_bind_policy, &cgroup_id);
    
    // Default Deny: Unregistered cgroups are strictly forbidden from binding
    if (!rule) {
        return -EACCES;
    }

    struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
    __u16 port = bpf_ntohs(addr_in->sin_port);

    if (port < rule->allowed_port_min || port > rule->allowed_port_max) {
        return -EACCES;
    }

    return 0;
}

char _license[] SEC("license") = "GPL";
```

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 Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM

Deterministic Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM defines an industrial-grade behavioral standard for security engineering. Enforces deterministic zero-trust network egress and UNIX domain socket binding restrictions directly at the Linux kernel boundary using eBPF LSM hooks (`socket_bind`, `socket_connect`). Eliminates user-space interception bypasses, LD_PRELOAD stripping, and namespace hopping in containerized multi-tenant node architectures by coupling kernel probes with immutable cgroup identifiers. 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: Relying on User-Space Sidecar Proxies or LD_PRELOAD Wrappers for Socket Access Control 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 DriftRelying on User-Space Sidecar Proxies or LD_PRELOAD Wrappers for Socket Access ControlCritical
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 verify socket operations using eBPF LSM probe hooks (`SEC("lsm/socket_bind")` and `SEC("lsm/socket_connect")`) instead of cgroup/sock or kprobes which can be bypassed via asynchronous socket creation or raw sockets.

Engineers MUST ALWAYS verify socket operations using eBPF LSM probe hooks (`SEC("lsm/socket_bind")` and `SEC("lsm/socket_connect")`) instead of cgroup/sock or kprobes which can be bypassed via asynchronous socket creation or raw sockets.

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 evaluate tenant context exclusively through deterministic kernel structures using `bpf_get_current_cgroup_id()` or pinned BPF task storage maps, never trusting user-space-passed headers, PID parameters, or environment variables.

Engineers MUST evaluate tenant context exclusively through deterministic kernel structures using `bpf_get_current_cgroup_id()` or pinned BPF task storage maps, never trusting user-space-passed headers, PID parameters, or environment variables.

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 validate both IPv4/IPv6 sockaddr structs and AF_UNIX `sockaddr_un` pathnames to prevent host root filesystem socket poisoning (e.g., hijacking `/var/run/docker.sock`).

Engineers MUST validate both IPv4/IPv6 sockaddr structs and AF_UNIX `sockaddr_un` pathnames to prevent host root filesystem socket poisoning (e.g., hijacking `/var/run/docker.sock`).

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

Code MUST return `-EPERM` (operation not permitted) or `-EACCES` synchronously from the LSM hook whenever an unauthorized bind or egress destination is detected, before any system resource allocation occurs.

Code MUST return `-EPERM` (operation not permitted) or `-EACCES` synchronously from the LSM hook whenever an unauthorized bind or egress destination is detected, before any system resource allocation occurs.

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

BPF maps holding authorization policies (LPM trie for CIDRs, hash maps for cgroup-to-port bindings) MUST be declared as BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LPM_TRIE with read-only flags (`BPF_F_RDONLY_PROG`) set from user-space loaders to eliminate in-kernel tamper vectors.

BPF maps holding authorization policies (LPM trie for CIDRs, hash maps for cgroup-to-port bindings) MUST be declared as BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LPM_TRIE with read-only flags (`BPF_F_RDONLY_PROG`) set from user-space loaders to eliminate in-kernel tamper vectors.

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

Engineers MUST NOT rely on iptables, nftables, or Envoy sidecars as the sole boundary for multi-tenant containment, as container escapes and `CAP_NET_ADMIN` leaks invalidate user-space proxy models.

Engineers MUST NOT rely on iptables, nftables, or Envoy sidecars as the sole boundary for multi-tenant containment, as container escapes and `CAP_NET_ADMIN` leaks invalidate user-space proxy models.

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 Kernel-Level Socket Bind & Egress Invariant Enforcement via eBPF LSM critical for AI coding assistants?

Enforces deterministic zero-trust network egress and UNIX domain socket binding restrictions directly at the Linux kernel boundary using eBPF LSM hooks (`socket_bind`, `socket_connect`). Eliminates user-space interception bypasses, LD_PRELOAD stripping, and namespace hopping in containerized multi-tenant node architectures by coupling kernel probes with immutable cgroup identifiers. 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 (Relying on User-Space Sidecar Proxies or LD_PRELOAD Wrappers for Socket Access Control) 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