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

BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant

Enforces synchronous, in-kernel security mediation at Linux Security Module (LSM) hooks to block container privilege escalation and capability abuses before syscall completion. Eliminates Time-of-Check to Time-of-Use (TOCTOU) race conditions and user-space context-switching penalties by asserting immediate -EPERM enforcement in kernel space.

Prohibited Anti-Pattern: Deferred or Tracepoint-Based Capability Auditing Prone to TOCTOU and Unbounded Privilege Escalation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant - Enforces synchronous, in-kernel security mediation at Linux Security Module (LSM) hooks to block container privilege escalation and capability abuses before syscall completion. Eliminates Time-of-Check to Time-of-Use (TOCTOU) race conditions and user-space context-switching penalties by asserting immediate -EPERM enforcement in kernel space.
globs: **/*.bpf.c, **/*.bpf.h, pkg/ebpf/**/*.go, src/bpf/**/*.rs, kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bpf-lsm-runtime-container-capability-enforcement"
---

# BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Deferred or Tracepoint-Based Capability Auditing Prone to TOCTOU and Unbounded Privilege Escalation

## System Constraints
You are a Principal Security Architect specializing in Linux eBPF-LSM architecture and container kernel isolation. Mandate that all container capability restrictions and syscall mediation logic execute synchronously within BPF-LSM hook handlers, rejecting deferred userspace decisions and unblockable probe hooks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce security decisions synchronously within LSM hooks (e.g., 'SEC("lsm/capable")' or 'SEC("lsm/bprm_check_security")') returning '-EPERM' directly on policy violations.
- Engineers MUST NOT rely on asynchronous user-space rings ('BPF_MAP_TYPE_RINGBUF') or unprivileged tracepoints/kprobes for access control decisions, as they cannot abort kernel execution paths.
- Code MUST resolve container boundaries via kernel-verified cgroup identifiers ('bpf_current_task_under_cgroup') or task local storage ('bpf_task_storage_get') rather than relying on mutable PID namespaces.
- Services MUST compile against BTF-enabled 'vmlinux.h' with Core (Compile Once - Run Everywhere) relocations to prevent struct layout divergence across kernel versions.
- Components NEVER permit critical capabilities like 'CAP_SYS_ADMIN', 'CAP_BPF', or 'CAP_NET_ADMIN' to transition inside containerized tasks without an explicit, verifiable cgroup-scoped cryptographic policy map lookup.

## Bad vs Good Implementations
### Synchronous BPF-LSM Capability Mediation vs. Asynchronous Tracepoint Audit

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: kprobes and tracepoints observe kernel execution without the ability to block or return access control error codes (e.g., -EPERM) directly to the VFS or security framework, allowing exploit payloads to execute unimpeded before user-space can react.
```c
// VULNERABLE: Using kprobe/tracepoint to observe capability checks asynchronously.
// Tracepoints cannot return -EPERM or prevent the exploit from succeeding.
#include "vmlinux.h"
#include <bpf/bpf_tracing.h>

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 256 * 1024);
} events SEC(".maps");

SEC("kprobe/cap_capable")
int BPF_KPROBE(trace_cap_capable, const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts) {
    if (cap == 21 /* CAP_SYS_ADMIN */) {
        u32 pid = bpf_get_current_pid_tgid() >> 32;
        // Anti-pattern: Emitting event to user-space for enforcement after syscall initiated
        bpf_ringbuf_output(&events, &pid, sizeof(pid), 0);
    }
    return 0; // kprobes cannot block execution; privilege escalation succeeds!
}
```

#### Production Standard (Correct)
> **Standard**: By leveraging the synchronous 'lsm/capable' hook, the BPF program intercepts kernel capability checks in-line and returns -EPERM, completely aborting privilege escalation prior to system call execution without relying on user-space telemetry loops.
```c
// SECURE: Synchronous LSM mediation preventing capability escalation inline.
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define CAP_SYS_ADMIN 21

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

SEC("lsm/capable")
int BPF_PROG(enforce_container_cap, const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts, int ret) {
    // If capability check already failed, retain upstream failure
    if (ret != 0)
        return ret;

    // Verify whether calling task belongs to restricted container cgroup
    if (bpf_current_task_under_cgroup(&restricted_cgroups, 0) > 0) {
        if (cap == CAP_SYS_ADMIN) {
            // Immediately block privilege escalation within the kernel
            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: BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant

BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces synchronous, in-kernel security mediation at Linux Security Module (LSM) hooks to block container privilege escalation and capability abuses before syscall completion. Eliminates Time-of-Check to Time-of-Use (TOCTOU) race conditions and user-space context-switching penalties by asserting immediate -EPERM enforcement in kernel space. 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: Deferred or Tracepoint-Based Capability Auditing Prone to TOCTOU and Unbounded Privilege Escalation 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 DriftDeferred or Tracepoint-Based Capability Auditing Prone to TOCTOU and Unbounded Privilege EscalationCritical
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 security decisions synchronously within LSM hooks (e.g., 'SEC("lsm/capable")' or 'SEC("lsm/bprm_check_security")') returning '-EPERM' directly on policy violations.

Engineers MUST ALWAYS enforce security decisions synchronously within LSM hooks (e.g., 'SEC("lsm/capable")' or 'SEC("lsm/bprm_check_security")') returning '-EPERM' directly on policy violations.

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 user-space rings ('BPF_MAP_TYPE_RINGBUF') or unprivileged tracepoints/kprobes for access control decisions, as they cannot abort kernel execution paths.

Engineers MUST NOT rely on asynchronous user-space rings ('BPF_MAP_TYPE_RINGBUF') or unprivileged tracepoints/kprobes for access control decisions, as they cannot abort kernel execution paths.

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 resolve container boundaries via kernel-verified cgroup identifiers ('bpf_current_task_under_cgroup') or task local storage ('bpf_task_storage_get') rather than relying on mutable PID namespaces.

Code MUST resolve container boundaries via kernel-verified cgroup identifiers ('bpf_current_task_under_cgroup') or task local storage ('bpf_task_storage_get') rather than relying on mutable PID namespaces.

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 compile against BTF-enabled 'vmlinux.h' with Core (Compile Once - Run Everywhere) relocations to prevent struct layout divergence across kernel versions.

Services MUST compile against BTF-enabled 'vmlinux.h' with Core (Compile Once - Run Everywhere) relocations to prevent struct layout divergence across kernel versions.

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 permit critical capabilities like 'CAP_SYS_ADMIN', 'CAP_BPF', or 'CAP_NET_ADMIN' to transition inside containerized tasks without an explicit, verifiable cgroup-scoped cryptographic policy map lookup.

Components NEVER permit critical capabilities like 'CAP_SYS_ADMIN', 'CAP_BPF', or 'CAP_NET_ADMIN' to transition inside containerized tasks without an explicit, verifiable cgroup-scoped cryptographic policy map lookup.

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 BPF-LSM In-Kernel Capability Guardrails and Synchronous Mediation Invariant critical for AI coding assistants?

Enforces synchronous, in-kernel security mediation at Linux Security Module (LSM) hooks to block container privilege escalation and capability abuses before syscall completion. Eliminates Time-of-Check to Time-of-Use (TOCTOU) race conditions and user-space context-switching penalties by asserting immediate -EPERM enforcement in kernel space. 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 (Deferred or Tracepoint-Based Capability Auditing Prone to TOCTOU and Unbounded Privilege Escalation) 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

BPF-LSM