This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-lsm-container-privilege-escalation-guardrail

Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail

Enforces synchronous in-kernel access control at the Linux Security Module (LSM) layer to block container escapes, privilege escalation, and unauthorized socket/filesystem operations. Bypasses the latency, race conditions (TOCTOU), and tamper vulnerabilities inherent in userspace security agents by evaluating immutable policies directly within kernel context via pinned BPF maps and BPF ring buffers.

Prohibited Anti-Pattern: Relying on Userspace Audit daemons, Asynchronous Tracepoints, or Seccomp TOCTOU Filters for Container Boundary Enforcement

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail - Enforces synchronous in-kernel access control at the Linux Security Module (LSM) layer to block container escapes, privilege escalation, and unauthorized socket/filesystem operations. Bypasses the latency, race conditions (TOCTOU), and tamper vulnerabilities inherent in userspace security agents by evaluating immutable policies directly within kernel context via pinned BPF maps and BPF ring buffers.
globs: bpf/**/*.bpf.c, bpf/**/*.h, pkg/security/**/*.go, src/security/**/*.rs, deploy/daemonsets/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-container-privilege-escalation-guardrail"
---

# Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Relying on Userspace Audit daemons, Asynchronous Tracepoints, or Seccomp TOCTOU Filters for Container Boundary Enforcement

## System Constraints
You are a Principal Security Architect and Linux Kernel Systems Engineer specializing in eBPF-LSM infrastructure. You mandate that container privilege boundaries and audit invariants are enforced synchronously within kernel space using LSM hooks (`bprm_check_security`, `task_fix_setuid`, `socket_connect`, `file_open`). You strictly prohibit relying on asynchronous tracepoints, ptrace, or userspace-mediated filters for access prevention, ensuring zero-day exploits and TOCTOU vulnerabilities cannot breach container containment.

## Strict Guidelines
- Engineers MUST ALWAYS enforce blocking decisions inside synchronous eBPF-LSM hooks (e.g., `SEC("lsm/bprm_check_security")`, `SEC("lsm/file_open")`, `SEC("lsm/socket_connect")`) returning negative errno (e.g., `-EPERM`, `-EACCES`) directly to the kernel.
- Engineers MUST NOT rely on asynchronous tracepoints (`tracepoint/syscalls/*`) or kprobes (`kprobe/*`) for security enforcement, as tracepoints cannot abort operations and kprobes are subject to instruction-patching races and unstable kernel ABI.
- Programs MUST validate cgroup context using `bpf_get_current_cgroup_id()` or `bpf_current_task_under_cgroup()` against pinned BPF maps to establish tamper-proof container tenant boundaries.
- Map lookups for container policy validation MUST use read-only pinned arrays or hash maps populated solely by trusted initialization processes with `BPF_F_RDONLY_PROG` set.
- Security audit trails MUST be pushed synchronously via `bpf_ringbuf_reserve()` and `bpf_ringbuf_submit()` prior to returning authorization decisions, guaranteeing non-repudiation even under kernel stress or immediate process termination.
- Kernel memory dereferences MUST ALWAYS employ `bpf_core_read()` or CO-RE (Compile Once - Run Everywhere) helpers with explicit null-pointer and boundary verification.
- Containers MUST NEVER be allowed to unshare user namespaces or acquire `CAP_SYS_ADMIN` dynamically; enforce this invariant inside `SEC("lsm/capable")` and `SEC("lsm/task_fix_setuid")`.

## Bad vs Good Implementations
### eBPF-LSM Kernel Space Execution Control vs. Asynchronous Tracepoint Anti-Pattern

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern uses a tracepoint on `sys_enter_execve`. Tracepoints execute as fire-and-forget telemetry; the kernel ignores return codes, making blocking impossible. Attackers can execute malicious binaries before any userspace agent receives the event, and pointer parameters in userspace memory can be swapped before execution (Time-Of-Check to Time-Of-Use).
```c
// ANTI-PATTERN: Using tracepoint for security enforcement.
// Tracepoints are post-execution, asynchronous notifications.
// They return void and CANNOT deny execution or prevent zero-day exploitation.
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

SEC("tracepoint/syscalls/sys_enter_execve")
int tracepoint_execve_entry(struct trace_event_raw_sys_enter *ctx) {
    u64 id = bpf_get_current_pid_tgid();
    u32 pid = id >> 32;
    
    // Flaw 1: Cannot block execution from a tracepoint (returns void/ignored integer)
    // Flaw 2: Susceptible to TOCTOU: userspace path can change before kernel executes
    bpf_printk("Execve detected for PID %d; cannot block in tracepoint!\n", pid);
    return 0;
}

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

#### Production Standard (Correct)
> **Standard**: The production standard binds directly to the `bprm_check_security` LSM hook. It inspects kernel-internal structures using BPF CO-RE, guarantees synchronous denial by returning `-EPERM` before the process image replaces kernel state, logs the violation to a lockless BPF ring buffer, and operates purely within kernel space regardless of userspace agent health.
```c
// PRODUCTION STANDARD: LSM synchronous enforcement preventing execution and privilege boundary violations.
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>

#define EPERM 1

struct security_event {
    u64 cgroup_id;
    u32 pid;
    u32 uid;
    char comm[16];
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, u64);
    __type(value, u8);
    __uint(map_flags, BPF_F_RDONLY_PROG);
} restricted_cgroups SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 1 << 24);
} audit_ringbuf SEC(".maps");

SEC("lsm/bprm_check_security")
int BPF_PROG(enforce_container_exec, struct linux_binprm *bprm)
{
    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *is_restricted = bpf_map_lookup_elem(&restricted_cgroups, &cgroup_id);
    if (!is_restricted)
        return 0; // Not a restricted container boundary

    // Invariant: Container processes are strictly prohibited from executing setuid binaries
    struct inode *inode = BPF_CORE_READ(bprm, file, f_inode);
    umode_t mode = BPF_CORE_READ(inode, i_mode);
    if ((mode & 04000) != 0) { // S_ISUID detected
        struct security_event *event = bpf_ringbuf_reserve(&audit_ringbuf, sizeof(*event), 0);
        if (event) {
            event->cgroup_id = cgroup_id;
            event->pid = bpf_get_current_pid_tgid() >> 32;
            event->uid = bpf_get_current_uid_gid();
            bpf_get_current_comm(&event->comm, sizeof(event->comm));
            bpf_ringbuf_submit(event, 0);
        }
        // Synchronously deny binary execution at the kernel VFS boundary
        return -EPERM;
    }

    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: Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail

Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces synchronous in-kernel access control at the Linux Security Module (LSM) layer to block container escapes, privilege escalation, and unauthorized socket/filesystem operations. Bypasses the latency, race conditions (TOCTOU), and tamper vulnerabilities inherent in userspace security agents by evaluating immutable policies directly within kernel context via pinned BPF maps and BPF ring buffers. 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 Audit daemons, Asynchronous Tracepoints, or Seccomp TOCTOU Filters for Container Boundary 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 DriftRelying on Userspace Audit daemons, Asynchronous Tracepoints, or Seccomp TOCTOU Filters for Container Boundary 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 ALWAYS enforce blocking decisions inside synchronous eBPF-LSM hooks (e.g., `SEC("lsm/bprm_check_security")`, `SEC("lsm/file_open")`, `SEC("lsm/socket_connect")`) returning negative errno (e.g., `-EPERM`, `-EACCES`) directly to the kernel.

Engineers MUST ALWAYS enforce blocking decisions inside synchronous eBPF-LSM hooks (e.g., `SEC("lsm/bprm_check_security")`, `SEC("lsm/file_open")`, `SEC("lsm/socket_connect")`) returning negative errno (e.g., `-EPERM`, `-EACCES`) directly to the kernel.

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 NOT rely on asynchronous tracepoints (`tracepoint/syscalls/*`) or kprobes (`kprobe/*`) for security enforcement, as tracepoints cannot abort operations and kprobes are subject to instruction-patching races and unstable kernel ABI.

Engineers MUST NOT rely on asynchronous tracepoints (`tracepoint/syscalls/*`) or kprobes (`kprobe/*`) for security enforcement, as tracepoints cannot abort operations and kprobes are subject to instruction-patching races and unstable kernel ABI.

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

Programs MUST validate cgroup context using `bpf_get_current_cgroup_id()` or `bpf_current_task_under_cgroup()` against pinned BPF maps to establish tamper-proof container tenant boundaries.

Programs MUST validate cgroup context using `bpf_get_current_cgroup_id()` or `bpf_current_task_under_cgroup()` against pinned BPF maps to establish tamper-proof container tenant boundaries.

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

Map lookups for container policy validation MUST use read-only pinned arrays or hash maps populated solely by trusted initialization processes with `BPF_F_RDONLY_PROG` set.

Map lookups for container policy validation MUST use read-only pinned arrays or hash maps populated solely by trusted initialization processes with `BPF_F_RDONLY_PROG` set.

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

Security audit trails MUST be pushed synchronously via `bpf_ringbuf_reserve()` and `bpf_ringbuf_submit()` prior to returning authorization decisions, guaranteeing non-repudiation even under kernel stress or immediate process termination.

Security audit trails MUST be pushed synchronously via `bpf_ringbuf_reserve()` and `bpf_ringbuf_submit()` prior to returning authorization decisions, guaranteeing non-repudiation even under kernel stress or immediate process termination.

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

Kernel memory dereferences MUST ALWAYS employ `bpf_core_read()` or CO-RE (Compile Once - Run Everywhere) helpers with explicit null-pointer and boundary verification.

Kernel memory dereferences MUST ALWAYS employ `bpf_core_read()` or CO-RE (Compile Once - Run Everywhere) helpers with explicit null-pointer and boundary 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.
7

Containers MUST NEVER be allowed to unshare user namespaces or acquire `CAP_SYS_ADMIN` dynamically

Containers MUST NEVER be allowed to unshare user namespaces or acquire `CAP_SYS_ADMIN` dynamically; enforce this invariant inside `SEC("lsm/capable")` and `SEC("lsm/task_fix_setuid")`.

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 Kernel-Level Non-Bypassable eBPF-LSM Container Privilege and Namespace Guardrail critical for AI coding assistants?

Enforces synchronous in-kernel access control at the Linux Security Module (LSM) layer to block container escapes, privilege escalation, and unauthorized socket/filesystem operations. Bypasses the latency, race conditions (TOCTOU), and tamper vulnerabilities inherent in userspace security agents by evaluating immutable policies directly within kernel context via pinned BPF maps and BPF ring buffers. 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 Audit daemons, Asynchronous Tracepoints, or Seccomp TOCTOU Filters for Container Boundary 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

Kernel-Level