This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-lsm-userns-credential-transition-guard

eBPF LSM Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds

Enforces kernel-level eBPF Linux Security Module (LSM) verification on credential preparation and namespace creation hooks to prevent unprivileged user namespace escalation. Prohibits ambient capability acquisition, unverified UID/GID namespace mappings, and unauthorized credential transformations in rootless execution contexts. Blocks privilege inheritance exploits across nested user namespace boundaries before execution context commits.

Prohibited Anti-Pattern: Permissive User Namespace Allocation Permitting Ambient Capability Inheritance and Host Credential Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF LSM Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds - Enforces kernel-level eBPF Linux Security Module (LSM) verification on credential preparation and namespace creation hooks to prevent unprivileged user namespace escalation. Prohibits ambient capability acquisition, unverified UID/GID namespace mappings, and unauthorized credential transformations in rootless execution contexts. Blocks privilege inheritance exploits across nested user namespace boundaries before execution context commits.
globs: bpf/**/*.bpf.c, bpf/**/*.bpf.h, src/security/ebpf/**/*.c, kernel/security/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-userns-credential-transition-guard"
---

# eBPF LSM Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive User Namespace Allocation Permitting Ambient Capability Inheritance and Host Credential Leaks

## System Constraints
You are a Principal Linux Systems and Security Engineer enforcing strict eBPF LSM invariants over kernel credential transitions. Mandate that every user namespace credential lifecycle hook verifies caller namespace invariants, blocks unprivileged ambient capability elevation, and enforces zero-trust kernel transitions using BPF CO-RE (Compile Once - Run Everywhere).

## Strict Guidelines
- Engineers MUST ALWAYS enforce LSM hooks on both `lsm/userns_create` and `lsm/cred_prepare` to detect and intercept unauthorized user namespace transitions.
- Engineers MUST NOT permit unprivileged tasks (`uid != 0` in `init_user_ns`) to acquire ambient capabilities (`cap_ambient`) across execution or credential transitions.
- BPF programs MUST ALWAYS employ `bpf_core_read` or CO-RE direct field access to extract `cred->user_ns`, `cred->cap_effective`, and `cred->cap_ambient` safely.
- Programs MUST return `-EPERM` immediately if a process running within a non-initial user namespace attempts to elevate capabilities beyond policy bounds defined in pinned BPF maps.
- Components NEVER rely on userspace runtime validation (such as seccomp or container runtime filters) to prevent kernel credential race conditions or unprivileged namespace transitions.

## Bad vs Good Implementations
### eBPF LSM Hook on cred_prepare to Block Ambient Capability Hijacking in User Namespaces

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to inspect whether the task is operating inside a non-initial user namespace (`init_user_ns`), trusts inner-namespace root identity (`uid == 0`), and fails to intercept ambient capability transformations. This allows unprivileged processes exploiting `CLONE_NEWUSER` to inherit ambient capabilities and execute setuid binaries inside the namespace to escape or manipulate host resources.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

SEC("lsm/cred_prepare")
int BPF_PROG(restrict_creds_bad, struct cred *new, const struct cred *old,
             gfp_t gfp_flags)
{
    // Anti-pattern: Missing CO-RE namespace isolation checks.
    // Blindly trusts UID check and ignores nested user_ns ambient capability hijacking.
    if (old->uid.val == 0) {
        return 0; // Allows any process mapped to UID 0 inside a nested userns to inherit privileges
    }
    return 0; // Default permit leaves ambient capabilities unbounded
}

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

#### Production Standard (Correct)
> **Standard**: Implements an explicit invariant via CO-RE kernel memory reads comparing task user namespaces against `init_user_ns`. Strictly zero-tolerates non-zero `cap_ambient` values across nested user namespace boundaries, prevents unverified credential transitions via a pinned policy hashmap, and returns `-EPERM` at the kernel LSM boundary before credentials can be committed.
```c
#include "vmlinux.h"
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <errno.h>

#define CAP_SYS_ADMIN 21

extern const struct user_namespace init_user_ns __ksym;

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, u32);   // TGID
    __type(value, u8);  // Policy flags
} allowed_userns_procs SEC(".maps");

SEC("lsm/cred_prepare")
int BPF_PROG(restrict_creds_good, struct cred *new, const struct cred *old,
             gfp_t gfp_flags)
{
    struct user_namespace *old_ns = BPF_CORE_READ(old, user_ns);
    struct user_namespace *new_ns = BPF_CORE_READ(new, user_ns);
    kernel_cap_t new_ambient = BPF_CORE_READ(new, cap_ambient);
    u32 tgid = (u32)(bpf_get_current_pid_tgid() >> 32);

    // Block any non-init user_ns from introducing ambient capabilities
    if (old_ns != &init_user_ns || new_ns != &init_user_ns) {
        if (new_ambient.val != 0) {
            bpf_printk("LSM: Blocked ambient cap elevation in userns for tgid %u\n", tgid);
            return -EPERM;
        }
    }

    // Verify caller authorization if transitioning to a distinct user namespace
    if (old_ns != new_ns) {
        u8 *policy = bpf_map_lookup_elem(&allowed_userns_procs, &tgid);
        if (!policy) {
            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 LSM Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds

eBPF LSM Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds defines an industrial-grade behavioral standard for security engineering. Enforces kernel-level eBPF Linux Security Module (LSM) verification on credential preparation and namespace creation hooks to prevent unprivileged user namespace escalation. Prohibits ambient capability acquisition, unverified UID/GID namespace mappings, and unauthorized credential transformations in rootless execution contexts. Blocks privilege inheritance exploits across nested user namespace boundaries before execution context commits. 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: Permissive User Namespace Allocation Permitting Ambient Capability Inheritance and Host Credential Leaks 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 DriftPermissive User Namespace Allocation Permitting Ambient Capability Inheritance and Host Credential LeaksCritical
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 LSM hooks on both `lsm/userns_create` and `lsm/cred_prepare` to detect and intercept unauthorized user namespace transitions.

Engineers MUST ALWAYS enforce LSM hooks on both `lsm/userns_create` and `lsm/cred_prepare` to detect and intercept unauthorized user namespace transitions.

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 permit unprivileged tasks (`uid != 0` in `init_user_ns`) to acquire ambient capabilities (`cap_ambient`) across execution or credential transitions.

Engineers MUST NOT permit unprivileged tasks (`uid != 0` in `init_user_ns`) to acquire ambient capabilities (`cap_ambient`) across execution or credential transitions.

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

BPF programs MUST ALWAYS employ `bpf_core_read` or CO-RE direct field access to extract `cred->user_ns`, `cred->cap_effective`, and `cred->cap_ambient` safely.

BPF programs MUST ALWAYS employ `bpf_core_read` or CO-RE direct field access to extract `cred->user_ns`, `cred->cap_effective`, and `cred->cap_ambient` safely.

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

Programs MUST return `-EPERM` immediately if a process running within a non-initial user namespace attempts to elevate capabilities beyond policy bounds defined in pinned BPF maps.

Programs MUST return `-EPERM` immediately if a process running within a non-initial user namespace attempts to elevate capabilities beyond policy bounds defined in pinned BPF maps.

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 rely on userspace runtime validation (such as seccomp or container runtime filters) to prevent kernel credential race conditions or unprivileged namespace transitions.

Components NEVER rely on userspace runtime validation (such as seccomp or container runtime filters) to prevent kernel credential race conditions or unprivileged namespace transitions.

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 Invariant Enforcement for User Namespace Credential Transitions and Ambient Capability Bounds critical for AI coding assistants?

Enforces kernel-level eBPF Linux Security Module (LSM) verification on credential preparation and namespace creation hooks to prevent unprivileged user namespace escalation. Prohibits ambient capability acquisition, unverified UID/GID namespace mappings, and unauthorized credential transformations in rootless execution contexts. Blocks privilege inheritance exploits across nested user namespace boundaries before execution context commits. 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 (Permissive User Namespace Allocation Permitting Ambient Capability Inheritance and Host Credential Leaks) 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