This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: bpf-lsm-kernel-mandatory-access-control

Kernel-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers

Enforce mandatory access control synchronously in kernel space using BPF-LSM hooks rather than asynchronous user-space security telemetry or seccomp-filter user notifications. Guarantees immutable, race-free boundary defense against privilege escalation, unauthorized binary execution, and capability manipulation within rootless container cgroups.

Prohibited Anti-Pattern: Relying on Asynchronous User-Space Daemons or Tracepoints for Container Execution Blocking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kernel-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers - Enforce mandatory access control synchronously in kernel space using BPF-LSM hooks rather than asynchronous user-space security telemetry or seccomp-filter user notifications. Guarantees immutable, race-free boundary defense against privilege escalation, unauthorized binary execution, and capability manipulation within rootless container cgroups.
globs: **/*.bpf.c, **/*.bpf.h, src/security/**/*.c, deploy/ebpf/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bpf-lsm-kernel-mandatory-access-control"
---

# Kernel-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Relying on Asynchronous User-Space Daemons or Tracepoints for Container Execution Blocking

## System Constraints
You are a Principal Systems & Security Architect specializing in Linux kernel security and eBPF. Enforce strict BPF-LSM-based Mandatory Access Control (MAC) patterns. Reject any architecture relying on asynchronous tracepoints, auditd logs, or user-space monitoring daemons for container process restriction, as they are inherently vulnerable to Time-of-Check to Time-of-Use (TOCTOU) exploits. Mandate synchronous in-kernel blocking via LSM hooks (such as bprm_check_security and task_prctl) backed by pinned BPF maps and BTF-validated structures.

## Strict Guidelines
- Engineers MUST ALWAYS implement blocking security policies inside synchronous LSM hooks (e.g., `SEC("lsm/bprm_check_security")` or `SEC("lsm/task_fix_setuid")`) rather than passive tracepoints (`sys_enter_execve`) or kprobes.
- Engineers MUST NOT rely on user-space agent responses or ptrace-based interventions to prevent unauthorized execution due to unavoidable TOCTOU race windows.
- Security policies MUST validate container identity via kernel cgroup IDs (`bpf_get_current_cgroup_id()`) matched against pinned, read-only kernel maps populated during container runtime initialization.
- Code MUST synchronously return `-EPERM` or `-EACCES` directly within the BPF-LSM program to abort unauthorized kernel operations before execution begins.
- BPF programs MUST use BPF Type Format (BTF) and Compile Once - Run Everywhere (CO-RE) `bpf_core_read()` helpers to access kernel structures reliably across kernel versions.

## Bad vs Good Implementations
### Synchronous Execution Blocking via BPF-LSM vs. Asynchronous Tracepoint Telemetry

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a tracepoint only generates passive telemetry. By the time a user-space daemon reads the ring buffer and attempts to kill the offending process via ptrace or SIGKILL, the malicious binary has already run, escalating privileges or corrupting container state.
```c
// VULNERABLE: Asynchronous tracepoint cannot block execution synchronously.
// Process execution proceeds in parallel while an event is pushed to user space,
// creating a severe TOCTOU window allowing exploits to complete before SIGKILL.

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

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

SEC("tracepoint/syscalls/sys_enter_execve")
int tracepoint_execve_entry(struct trace_event_raw_sys_enter *ctx) {
    u64 cgroup_id = bpf_get_current_cgroup_id();
    
    // Emitting telemetry to user-space agent to review and potentially 'kill' PID
    u32 *event = bpf_ringbuf_reserve(&audit_events, sizeof(u32), 0);
    if (!event) {
        return 0;
    }
    *event = (u32)cgroup_id;
    bpf_ringbuf_submit(event, 0);

    // Cannot block execution here! The binary starts executing immediately.
    return 0;
}

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

#### Production Standard (Correct)
> **Standard**: The BPF-LSM hook `bprm_check_security` executes within the kernel's LSM framework immediately prior to loading an executable binary. Returning `-EPERM` terminates the execve call synchronously with zero TOCTOU vulnerability.
```c
// SECURE: Synchronous kernel-space BPF-LSM hook.
// Blocks unauthorized execution atomically prior to binary loading.

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>

#define EPERM 1

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10240);
    __type(key, u64);   /* cgroup_id */
    __type(value, u8);  /* policy flags */
} restricted_containers SEC(".maps");

SEC("lsm/bprm_check_security")
int BPF_PROG(enforce_container_exec, struct linux_binprm *bprm, int ret)
{
    // Respect existing LSM decisions
    if (ret != 0)
        return ret;

    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *policy = bpf_map_lookup_elem(&restricted_containers, &cgroup_id);
    
    if (policy) {
        // Inspect executable inode or credentials synchronously
        struct file *file = BPF_CORE_READ(bprm, file);
        struct inode *inode = BPF_CORE_READ(file, f_inode);
        umode_t mode = BPF_CORE_READ(inode, i_mode);

        // Deny execution of SUID/SGID binaries in restricted container contexts
        if (mode & (04000 | 02000)) {
            return -EPERM; // Atomic in-kernel block: process never executes
        }
    }

    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-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers

Kernel-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers defines an industrial-grade behavioral standard for devops engineering. Enforce mandatory access control synchronously in kernel space using BPF-LSM hooks rather than asynchronous user-space security telemetry or seccomp-filter user notifications. Guarantees immutable, race-free boundary defense against privilege escalation, unauthorized binary execution, and capability manipulation within rootless container cgroups. 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 User-Space Daemons or Tracepoints for Container Execution Blocking 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 User-Space Daemons or Tracepoints for Container Execution BlockingCritical
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 implement blocking security policies inside synchronous LSM hooks (e.g., `SEC("lsm/bprm_check_security")` or `SEC("lsm/task_fix_setuid")`) rather than passive tracepoints (`sys_enter_execve`) or kprobes.

Engineers MUST ALWAYS implement blocking security policies inside synchronous LSM hooks (e.g., `SEC("lsm/bprm_check_security")` or `SEC("lsm/task_fix_setuid")`) rather than passive tracepoints (`sys_enter_execve`) or kprobes.

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 user-space agent responses or ptrace-based interventions to prevent unauthorized execution due to unavoidable TOCTOU race windows.

Engineers MUST NOT rely on user-space agent responses or ptrace-based interventions to prevent unauthorized execution due to unavoidable TOCTOU race windows.

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

Security policies MUST validate container identity via kernel cgroup IDs (`bpf_get_current_cgroup_id()`) matched against pinned, read-only kernel maps populated during container runtime initialization.

Security policies MUST validate container identity via kernel cgroup IDs (`bpf_get_current_cgroup_id()`) matched against pinned, read-only kernel maps populated during container runtime initialization.

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

Code MUST synchronously return `-EPERM` or `-EACCES` directly within the BPF-LSM program to abort unauthorized kernel operations before execution begins.

Code MUST synchronously return `-EPERM` or `-EACCES` directly within the BPF-LSM program to abort unauthorized kernel operations before execution begins.

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

BPF programs MUST use BPF Type Format (BTF) and Compile Once - Run Everywhere (CO-RE) `bpf_core_read()` helpers to access kernel structures reliably across kernel versions.

BPF programs MUST use BPF Type Format (BTF) and Compile Once - Run Everywhere (CO-RE) `bpf_core_read()` helpers to access kernel structures reliably 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Kernel-Space Mandatory Access Control via BPF-LSM Hooks for Rootless Containers critical for AI coding assistants?

Enforce mandatory access control synchronously in kernel space using BPF-LSM hooks rather than asynchronous user-space security telemetry or seccomp-filter user notifications. Guarantees immutable, race-free boundary defense against privilege escalation, unauthorized binary execution, and capability manipulation within rootless container cgroups. 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 User-Space Daemons or Tracepoints for Container Execution Blocking) 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-Space