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

eBPF LSM Kernel-Enforced Socket Egress Boundary Invariant

Mandates deterministic, zero-drift egress enforcement directly in the Linux Security Module (LSM) hookpoints via eBPF. Bypasses userspace proxy latency and race conditions by intercepting socket connection requests synchronously in kernel space before TCP SYN dispatch.

Prohibited Anti-Pattern: Relying on Userspace Sidecar Proxies or Asynchronous Packet Filters for Container Egress Control

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF LSM Kernel-Enforced Socket Egress Boundary Invariant - Mandates deterministic, zero-drift egress enforcement directly in the Linux Security Module (LSM) hookpoints via eBPF. Bypasses userspace proxy latency and race conditions by intercepting socket connection requests synchronously in kernel space before TCP SYN dispatch.
globs: bpf/**/*.bpf.c, bpf/**/*.h, src/bpf/**/*.c, src/**/*.rs, kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-kernel-socket-egress-invariant"
---

# eBPF LSM Kernel-Enforced Socket Egress Boundary Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Userspace Sidecar Proxies or Asynchronous Packet Filters for Container Egress Control

## System Constraints
You are a Principal Systems Architect and Linux Kernel Security Engineer. Mandate strict adherence to kernel-space security invariants using eBPF LSM (Linux Security Module) hooks for container socket egress control. You must reject any architectures relying solely on userspace network filtering, asynchronous iptables reconciliation, or ptrace-based interceptors. Enforce synchronous `-EPERM` rejections directly within `security_socket_connect` to guarantee zero-drift isolation, prevent TOCTOU connection bypasses, and eliminate sidecar proxy latency overhead.

## Strict Guidelines
- Engineers MUST ALWAYS attach egress boundary enforcement to the `lsm/socket_connect` hookpoint to intercept connection establishment synchronously before network packets hit the wire.
- Engineers MUST ALWAYS isolate network enforcement policies per container using `bpf_get_current_cgroup_id()` verified against kernel-managed cgroupv2 hierarchies.
- Engineers MUST ALWAYS enforce IP/CIDR egress rules using `BPF_MAP_TYPE_LPM_TRIE` maps with atomic lockless lookups to guarantee constant-time execution without page faults.
- Engineers MUST ALWAYS normalize IPv4-mapped IPv6 addresses (`::ffff:0:0/96`) into pure IPv4 representations prior to triage lookup to eliminate address-encoding bypass attacks.
- Engineers MUST NOT rely on userspace proxies (e.g., Envoy sidecars via DNAT/iptables redirect) as the sole security boundary for regulated or multi-tenant workloads.
- Code MUST return `-EPERM` (Operation not permitted) directly from the LSM hook whenever a destination address is missing from the cgroup-specific allowlist map.
- Programs NEVER mutate the `struct sockaddr` in `lsm/socket_connect` directly; modifications belong only in `cgroup/connect4` or `cgroup/connect6` programs.

## Bad vs Good Implementations
### eBPF LSM Socket Connect Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kprobes and tracepoints are observability constructs. They cannot abort connection setup synchronously or enforce network policy invariants, permitting exfiltration packets to reach the wire before userspace can terminate the task.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>

// Anti-pattern: Relying on kprobe/tracepoint for egress security
// Tracepoints are passive, non-blocking, and vulnerable to TOCTOU races
SEC("tracepoint/syscalls/sys_enter_connect")
int trace_connect_enter(struct trace_event_raw_sys_enter *ctx) {
    // Cannot synchronously reject the connection inside the kernel
    // Cannot enforce hard isolation before the SYN packet is emitted
    long fd = ctx->args[0];
    bpf_printk("Egress connection attempt detected on fd %ld\n", fd);
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Hooks directly into the Linux Security Module layer using `lsm/socket_connect`. Connect requests to non-whitelisted destinations fail synchronously with `-EPERM`, aborting TCP socket initialization before any packet leaves the host.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define AF_INET 2

struct lpm_key {
    __u32 prefixlen;
    __u32 addr;
};

struct {
    __uint(type, BPF_MAP_TYPE_LPM_TRIE);
    __type(key, struct lpm_key);
    __type(value, __u8);
    __uint(map_flags, BPF_F_NO_PREALLOC);
    __uint(max_entries, 65536);
} egress_allowlist SEC(".maps");

SEC("lsm/socket_connect")
int BPF_PROG(restrict_socket_egress, struct socket *sock, struct sockaddr *address, int addrlen) {
    if (!address || addrlen < (int)sizeof(struct sockaddr_in)) {
        return 0;
    }

    if (address->sa_family != AF_INET) {
        // Non-IPv4 traffic restricted under strict default-deny boundary
        return -EPERM;
    }

    struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
    struct lpm_key key = {
        .prefixlen = 32,
        .addr = addr_in->sin_addr.s_addr
    };

    __u8 *allowed = bpf_map_lookup_elem(&egress_allowlist, &key);
    if (!allowed || *allowed != 1) {
        // Synchronously deny connection at the kernel boundary
        return -EPERM;
    }

    return 0;
}

char LICENSE[] SEC("license") = "Dual BSD/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: eBPF LSM Kernel-Enforced Socket Egress Boundary Invariant

eBPF LSM Kernel-Enforced Socket Egress Boundary Invariant defines an industrial-grade behavioral standard for security engineering. Mandates deterministic, zero-drift egress enforcement directly in the Linux Security Module (LSM) hookpoints via eBPF. Bypasses userspace proxy latency and race conditions by intercepting socket connection requests synchronously in kernel space before TCP SYN dispatch. 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 Userspace Sidecar Proxies or Asynchronous Packet Filters for Container Egress 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 Userspace Sidecar Proxies or Asynchronous Packet Filters for Container Egress 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 attach egress boundary enforcement to the `lsm/socket_connect` hookpoint to intercept connection establishment synchronously before network packets hit the wire.

Engineers MUST ALWAYS attach egress boundary enforcement to the `lsm/socket_connect` hookpoint to intercept connection establishment synchronously before network packets hit the wire.

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 isolate network enforcement policies per container using `bpf_get_current_cgroup_id()` verified against kernel-managed cgroupv2 hierarchies.

Engineers MUST ALWAYS isolate network enforcement policies per container using `bpf_get_current_cgroup_id()` verified against kernel-managed cgroupv2 hierarchies.

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 enforce IP/CIDR egress rules using `BPF_MAP_TYPE_LPM_TRIE` maps with atomic lockless lookups to guarantee constant-time execution without page faults.

Engineers MUST ALWAYS enforce IP/CIDR egress rules using `BPF_MAP_TYPE_LPM_TRIE` maps with atomic lockless lookups to guarantee constant-time execution without page faults.

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

Engineers MUST ALWAYS normalize IPv4-mapped IPv6 addresses (`::ffff:0:0/96`) into pure IPv4 representations prior to triage lookup to eliminate address-encoding bypass attacks.

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 NOT rely on userspace proxies (e.g., Envoy sidecars via DNAT/iptables redirect) as the sole security boundary for regulated or multi-tenant workloads.

Engineers MUST NOT rely on userspace proxies (e.g., Envoy sidecars via DNAT/iptables redirect) as the sole security boundary for regulated or multi-tenant workloads.

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

Code MUST return `-EPERM` (Operation not permitted) directly from the LSM hook whenever a destination address is missing from the cgroup-specific allowlist map.

Code MUST return `-EPERM` (Operation not permitted) directly from the LSM hook whenever a destination address is missing from the cgroup-specific allowlist 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.
7

Programs NEVER mutate the `struct sockaddr` in `lsm/socket_connect` directly

Programs NEVER mutate the `struct sockaddr` in `lsm/socket_connect` directly; modifications belong only in `cgroup/connect4` or `cgroup/connect6` programs.

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 LSM Kernel-Enforced Socket Egress Boundary Invariant critical for AI coding assistants?

Mandates deterministic, zero-drift egress enforcement directly in the Linux Security Module (LSM) hookpoints via eBPF. Bypasses userspace proxy latency and race conditions by intercepting socket connection requests synchronously in kernel space before TCP SYN dispatch. 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 Userspace Sidecar Proxies or Asynchronous Packet Filters for Container Egress 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

eBPF