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

eBPF BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail

Enforces synchronous, in-kernel blocking of unauthorized namespace transitions (`unshare`, `setns`) and privileged capability acquisition directly inside BPF Linux Security Module (LSM) hooks. Bypasses user-space round-trip latency and eliminates time-of-check-to-time-of-use (TOCTOU) races by evaluating caller task cgroup hierarchies, mount namespaces, and target security descriptors atomically within kernel context.

Prohibited Anti-Pattern: Delegating container containment enforcement to user-space tracepoint/kprobe monitors or asynchronous event loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail - Enforces synchronous, in-kernel blocking of unauthorized namespace transitions (`unshare`, `setns`) and privileged capability acquisition directly inside BPF Linux Security Module (LSM) hooks. Bypasses user-space round-trip latency and eliminates time-of-check-to-time-of-use (TOCTOU) races by evaluating caller task cgroup hierarchies, mount namespaces, and target security descriptors atomically within kernel context.
globs: **/*.bpf.c, **/*.bpf.h, src/security/**/*.c, src/security/**/*.rs, bpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-container-namespace-escape-guardrail"
---

# eBPF BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Delegating container containment enforcement to user-space tracepoint/kprobe monitors or asynchronous event loops

## System Constraints
You are a Principal Systems & Security Architect specializing in Linux kernel instrumentation, BPF_LSM, and runtime container security. Your mandate is to enforce zero-tolerance policies against asynchronous enforcement, TOCTOU-prone kprobe security checks, and unconstrained task namespace mutations (`CLONE_NEWUSER`, `CLONE_NEWNS`, `CLONE_NEWPID`). Ensure that all security controls execute directly within deterministic BPF_LSM hooks with appropriate return values (-EPERM), proper BPF CO-RE pointer dereferencing, and strict map synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS attach enforcement logic to authoritative BPF_LSM hooks (e.g., `SEC("lsm/task_prctl")`, `SEC("lsm/capable")`, `SEC("lsm/sb_mount")`) rather than observational kprobes or raw tracepoints.
- Engineers MUST ALWAYS return `-EPERM` directly from the LSM hook program to abort unauthorized system operations prior to kernel state mutation.
- Code MUST read task structures, cgroups, and namespace pointers safely using BPF CO-RE helpers (`BPF_CORE_READ` or direct field access with `vmlinux.h` preserved relocations).
- Engineers MUST NOT rely on userspace daemons (via perf/ring buffers) to decide whether to kill or permit a container breakout; the denial must be synchronous and in-kernel.
- Programs MUST verify whether the target process is operating within an unprivileged container namespace hierarchy before permitting calls to `unshare()` with `CLONE_NEWUSER` or `CLONE_NEWNS`.
- Maps tracking trusted container workloads MUST utilize atomic read/update mechanisms such as `bpf_map_lookup_elem` with read-mostly arrays or BPF concurrent hash tables.

## Bad vs Good Implementations
### In-Kernel Mitigation of Unauthorized Namespace Unsharing via BPF_LSM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using tracepoints or kprobes for security enforcement cannot deny the syscall; it only permits auditing or asynchronous userspace reactions. By the time userspace dispatches SIGKILL, malicious shellcode executed in the unshared namespace has already escalated privileges or mounted malicious overlays.
```c
// Anti-Pattern: Asynchronous tracepoint monitoring with userspace SIGKILL dispatch
// Leaves a window for race conditions (TOCTOU) allowing the payload to execute before kill.
SEC("tracepoint/syscalls/sys_enter_unshare")
int trace_sys_unshare(struct trace_event_raw_sys_enter *ctx) {
    u64 flags = (u64)ctx->args[0];
    u32 pid = bpf_get_current_pid_tgid() >> 32;

    if (flags & 0x10000000 /* CLONE_NEWUSER */) {
        // Sending alert to userspace daemon to issue kill(pid, SIGKILL)
        struct alert_event evt = { .pid = pid, .flags = flags };
        bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &evt, sizeof(evt));
    }
    return 0; // Operation is allowed to proceed unconditionally in-kernel!
}
```

#### Production Standard (Correct)
> **Standard**: The BPF_LSM hook synchronously denies execution prior to kernel-state mutation by returning -EPERM. It evaluates process containment and credentials in kernel-space without race conditions or userspace context switches.
```c
// Production Standard: Authoritative, synchronous LSM hook denying unauthorized namespace unsharing
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>

#define EPERM 1
#define CLONE_NEWUSER 0x10000000
#define CLONE_NEWNS   0x00020000

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10240);
    __type(key, u64);   /* cgroup_id */
    __type(value, u8);  /* 1: protected container, 0: host */
} protected_cgroups SEC(".maps");

SEC("lsm/task_prctl")
int BPF_PROG(restrict_namespace_escalation, int option, unsigned long arg2,
             unsigned long arg3, unsigned long arg4, unsigned long arg5, int ret) {
    if (ret != 0)
        return ret;

    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *is_contained = bpf_map_lookup_elem(&protected_cgroups, &cgroup_id);
    if (!is_contained || *is_contained != 1)
        return 0; // Host process or non-restricted workload

    struct task_struct *task = (struct task_struct *)bpf_get_current_task_btf();
    u32 nsproxy_uid = BPF_CORE_READ(task, cred, uid.val);

    // In-kernel atomic blocking: Container processes cannot unshare user or mount namespaces
    if (option == PR_SET_SECUREBITS || (arg2 & (CLONE_NEWUSER | CLONE_NEWNS))) {
        if (nsproxy_uid != 0) {
            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: eBPF BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail

eBPF BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces synchronous, in-kernel blocking of unauthorized namespace transitions (`unshare`, `setns`) and privileged capability acquisition directly inside BPF Linux Security Module (LSM) hooks. Bypasses user-space round-trip latency and eliminates time-of-check-to-time-of-use (TOCTOU) races by evaluating caller task cgroup hierarchies, mount namespaces, and target security descriptors atomically within kernel context. 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: Delegating container containment enforcement to user-space tracepoint/kprobe monitors or asynchronous event loops 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 DriftDelegating container containment enforcement to user-space tracepoint/kprobe monitors or asynchronous event loopsCritical
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 enforcement logic to authoritative BPF_LSM hooks (e.g., `SEC("lsm/task_prctl")`, `SEC("lsm/capable")`, `SEC("lsm/sb_mount")`) rather than observational kprobes or raw tracepoints.

Engineers MUST ALWAYS attach enforcement logic to authoritative BPF_LSM hooks (e.g., `SEC("lsm/task_prctl")`, `SEC("lsm/capable")`, `SEC("lsm/sb_mount")`) rather than observational kprobes or raw tracepoints.

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 return `-EPERM` directly from the LSM hook program to abort unauthorized system operations prior to kernel state mutation.

Engineers MUST ALWAYS return `-EPERM` directly from the LSM hook program to abort unauthorized system operations prior to kernel state mutation.

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 read task structures, cgroups, and namespace pointers safely using BPF CO-RE helpers (`BPF_CORE_READ` or direct field access with `vmlinux.h` preserved relocations).

Code MUST read task structures, cgroups, and namespace pointers safely using BPF CO-RE helpers (`BPF_CORE_READ` or direct field access with `vmlinux.h` preserved relocations).

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 rely on userspace daemons (via perf/ring buffers) to decide whether to kill or permit a container breakout

Engineers MUST NOT rely on userspace daemons (via perf/ring buffers) to decide whether to kill or permit a container breakout; the denial must be synchronous and in-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.
5

Programs MUST verify whether the target process is operating within an unprivileged container namespace hierarchy before permitting calls to `unshare()` with `CLONE_NEWUSER` or `CLONE_NEWNS`.

Programs MUST verify whether the target process is operating within an unprivileged container namespace hierarchy before permitting calls to `unshare()` with `CLONE_NEWUSER` or `CLONE_NEWNS`.

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

Maps tracking trusted container workloads MUST utilize atomic read/update mechanisms such as `bpf_map_lookup_elem` with read-mostly arrays or BPF concurrent hash tables.

Maps tracking trusted container workloads MUST utilize atomic read/update mechanisms such as `bpf_map_lookup_elem` with read-mostly arrays or BPF concurrent hash tables.

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 BPF_LSM In-Kernel Container Namespace Escape and Credential Escalation Guardrail critical for AI coding assistants?

Enforces synchronous, in-kernel blocking of unauthorized namespace transitions (`unshare`, `setns`) and privileged capability acquisition directly inside BPF Linux Security Module (LSM) hooks. Bypasses user-space round-trip latency and eliminates time-of-check-to-time-of-use (TOCTOU) races by evaluating caller task cgroup hierarchies, mount namespaces, and target security descriptors atomically within kernel context. 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 (Delegating container containment enforcement to user-space tracepoint/kprobe monitors or asynchronous event loops) 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