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

Linux BPF-LSM Container Namespace Mutation and Capability Hardening

Enforces synchronous, kernel-level rejection of unauthorized namespace transitions and process capability elevations inside containers using modern BPF-LSM probes. Prevents container breakout vectors (e.g., arbitrary user namespace creation and cap-set exploitation) by verifying cgroup context and denying operations directly at the LSM layer before syscall execution.

Prohibited Anti-Pattern: Relying on Asynchronous Tracepoints or User-Space Seccomp Filters for Critical Namespace Privilege Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Linux BPF-LSM Container Namespace Mutation and Capability Hardening - Enforces synchronous, kernel-level rejection of unauthorized namespace transitions and process capability elevations inside containers using modern BPF-LSM probes. Prevents container breakout vectors (e.g., arbitrary user namespace creation and cap-set exploitation) by verifying cgroup context and denying operations directly at the LSM layer before syscall execution.
globs: src/bpf/**/*.bpf.c, src/bpf/**/*.c, src/bpf/**/*.h, pkg/security/**/*.go, deploy/security/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bpf-lsm-runtime-container-namespace-guardrail"
---

# Linux BPF-LSM Container Namespace Mutation and Capability Hardening

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Relying on Asynchronous Tracepoints or User-Space Seccomp Filters for Critical Namespace Privilege Boundaries

## System Constraints
You are a Principal Software Architect and Linux Kernel Security Engineer. Enforce absolute architectural invariants around container namespace isolation using modern BPF-LSM (BPF Linux Security Modules). Never permit asynchronous audit hooks (tracepoints/kprobes) to perform access control, and mandate that all capability checks and namespace transitions within target container cgroups return -EPERM synchronously at the LSM boundary.

## Strict Guidelines
- Engineers MUST ALWAYS hook into BPF-LSM programs (e.g., `SEC("lsm/capable")`, `SEC("lsm/task_prctl")`, `SEC("lsm/userns_create")`) rather than asynchronous tracepoints or kprobes when enforcing security boundaries.
- Engineers MUST NOT allow unprivileged or container-scoped tasks to invoke `unshare(CLONE_NEWUSER)` or `setns()` unless explicitly allowlisted by an immutable BPF map keyed on container cgroup ID.
- Code SHOULD inspect the kernel task context directly using BPF CO-RE (Compile Once – Run Everywhere) helpers such as `bpf_get_current_task_btf()` and `bpf_current_task_under_cgroup()` to prevent Time-Of-Check to Time-Of-Use (TOCTOU) races.
- Services MUST return canonical negative errno values (specifically `-EPERM` or `-EACCES`) directly from BPF-LSM hooks to abort unpermitted syscalls prior to state mutation.
- Components NEVER fall back to user-space validation or audit-only logging for capability elevation attempts detected inside container cgroup hierarchies.

## Bad vs Good Implementations
### Blocking Unauthorized Namespace Mutation via BPF-LSM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Tracepoints are purely asynchronous observability hooks. Returning -1 from a tracepoint cannot block or prevent namespace creation. An attacker successfully unshares user namespaces to gain simulated CAP_SYS_ADMIN, enabling exploitation of downstream kernel vulnerabilities.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

// ANTI-PATTERN: Using a tracepoint for access control.
// Tracepoints are observation-only; the syscall has already passed security checks,
// and returning an error code from a tracepoint has zero effect on execution.
SEC("tracepoint/syscalls/sys_enter_unshare")
int tracepoint_unshare(struct trace_event_raw_sys_enter *ctx) {
    unsigned long flags = (unsigned long)ctx->args[0];
    if (flags & 0x10000000 /* CLONE_NEWUSER */) {
        bpf_printk("WARNING: Unshare CLONE_NEWUSER detected, cannot block!\n");
        return -1; // No-op: Kernel ignores return value on tracepoints
    }
    return 0;
}

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

#### Production Standard (Correct)
> **Standard**: By utilizing the `lsm/userns_create` hook with modern BPF CO-RE, the kernel consults the BPF program synchronously. Returning `-EPERM` ensures the kernel aborts the `unshare` or `clone` syscall before allocating a new user namespace, eliminating user-namespace-assisted breakouts.
```c
#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

struct {
    __uint(type, BPF_MAP_TYPE_CGROUP_ARRAY);
    __type(key, u32);
    __type(value, u32);
    __uint(max_entries, 1024);
} protected_cgroups SEC(".maps");

// PRODUCTION STANDARD: BPF-LSM synchronously blocks privilege/namespace mutation
SEC("lsm/userns_create")
int BPF_PROG(enforce_block_userns, const struct cred *cred, int ret)
{
    // If already blocked by previous security module, propagate error
    if (ret != 0)
        return ret;

    // Verify if current executing task belongs to a hardened container cgroup
    if (bpf_current_task_under_cgroup(&protected_cgroups, 0) == 1) {
        // Synchronously abort userns creation inside the container 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.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Linux BPF-LSM Container Namespace Mutation and Capability Hardening

Linux BPF-LSM Container Namespace Mutation and Capability Hardening defines an industrial-grade behavioral standard for devops engineering. Enforces synchronous, kernel-level rejection of unauthorized namespace transitions and process capability elevations inside containers using modern BPF-LSM probes. Prevents container breakout vectors (e.g., arbitrary user namespace creation and cap-set exploitation) by verifying cgroup context and denying operations directly at the LSM layer before syscall execution. 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 Asynchronous Tracepoints or User-Space Seccomp Filters for Critical Namespace Privilege Boundaries 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 Asynchronous Tracepoints or User-Space Seccomp Filters for Critical Namespace Privilege BoundariesCritical
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 hook into BPF-LSM programs (e.g., `SEC("lsm/capable")`, `SEC("lsm/task_prctl")`, `SEC("lsm/userns_create")`) rather than asynchronous tracepoints or kprobes when enforcing security boundaries.

Engineers MUST ALWAYS hook into BPF-LSM programs (e.g., `SEC("lsm/capable")`, `SEC("lsm/task_prctl")`, `SEC("lsm/userns_create")`) rather than asynchronous tracepoints or kprobes when enforcing security 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.
2

Engineers MUST NOT allow unprivileged or container-scoped tasks to invoke `unshare(CLONE_NEWUSER)` or `setns()` unless explicitly allowlisted by an immutable BPF map keyed on container cgroup ID.

Engineers MUST NOT allow unprivileged or container-scoped tasks to invoke `unshare(CLONE_NEWUSER)` or `setns()` unless explicitly allowlisted by an immutable BPF map keyed on container cgroup ID.

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 SHOULD inspect the kernel task context directly using BPF CO-RE (Compile Once – Run Everywhere) helpers such as `bpf_get_current_task_btf()` and `bpf_current_task_under_cgroup()` to prevent Time-Of-Check to Time-Of-Use (TOCTOU) races.

Code SHOULD inspect the kernel task context directly using BPF CO-RE (Compile Once – Run Everywhere) helpers such as `bpf_get_current_task_btf()` and `bpf_current_task_under_cgroup()` to prevent Time-Of-Check to Time-Of-Use (TOCTOU) races.

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

Services MUST return canonical negative errno values (specifically `-EPERM` or `-EACCES`) directly from BPF-LSM hooks to abort unpermitted syscalls prior to state mutation.

Services MUST return canonical negative errno values (specifically `-EPERM` or `-EACCES`) directly from BPF-LSM hooks to abort unpermitted syscalls prior to 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.
5

Components NEVER fall back to user-space validation or audit-only logging for capability elevation attempts detected inside container cgroup hierarchies.

Components NEVER fall back to user-space validation or audit-only logging for capability elevation attempts detected inside container cgroup 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Linux BPF-LSM Container Namespace Mutation and Capability Hardening critical for AI coding assistants?

Enforces synchronous, kernel-level rejection of unauthorized namespace transitions and process capability elevations inside containers using modern BPF-LSM probes. Prevents container breakout vectors (e.g., arbitrary user namespace creation and cap-set exploitation) by verifying cgroup context and denying operations directly at the LSM layer before syscall execution. 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 Asynchronous Tracepoints or User-Space Seccomp Filters for Critical Namespace Privilege Boundaries) 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

Linux