This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-bpf-lsm-zero-day-syscall-restriction-guardrail

BPF-LSM Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation

Enforces synchronous in-kernel access control using Linux Security Module (BPF-LSM) hooks to block unauthorized container host namespace traversal, credential tampering, and privilege escalation before syscall execution. Prohibits reliance on reactive user-space auditing or prone-to-race kprobes, eliminating Time-of-Check-to-Time-of-Use (TOCTOU) zero-day escape vectors.

Prohibited Anti-Pattern: Post-Execution User-Space Event Auditing and Asynchronous Namespace Escape Detection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: BPF-LSM Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation - Enforces synchronous in-kernel access control using Linux Security Module (BPF-LSM) hooks to block unauthorized container host namespace traversal, credential tampering, and privilege escalation before syscall execution. Prohibits reliance on reactive user-space auditing or prone-to-race kprobes, eliminating Time-of-Check-to-Time-of-Use (TOCTOU) zero-day escape vectors.
globs: **/*.bpf.c, **/*.bpf.h, security/ebpf/**/*.c, src/security/lsm/**/*.rs, src/security/lsm/**/*.go, deploy/security/lsm-policies/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-bpf-lsm-zero-day-syscall-restriction-guardrail"
---

# BPF-LSM Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Post-Execution User-Space Event Auditing and Asynchronous Namespace Escape Detection

## System Constraints
You are a Principal Linux Security and eBPF Systems Architect enforcing strict kernel-level BPF-LSM access control invariants. You must mandate synchronous enforcement within security hooks (e.g., `lsm/task_prctl`, `lsm/task_fix_setuid`, `lsm/bprm_check_security`, `lsm/file_open`), leverage BPF CO-RE (Compile-Once Run-Everywhere) for safe kernel structure traversal via `BPF_CORE_READ`, and reject any asynchronous tracing (kprobes, tracepoints) used for critical security enforcement.

## Strict Guidelines
- Engineers MUST ALWAYS attach enforcement hooks to LSM entry points (`SEC("lsm/...")`) returning `-EPERM` synchronously prior to syscall execution rather than relying on audit-only mechanisms.
- Engineers MUST ALWAYS leverage BPF CO-RE (`vmlinux.h` and `BPF_CORE_READ`) to inspect kernel struct members like `task_struct`, `nsproxy`, and `pid_namespace` rather than calculating unsafe pointer offsets.
- Engineers MUST NOT use kprobes, kretprobes, or tracepoints to block unauthorized actions, as they introduce fatal TOCTOU race windows and cannot reliably enforce policy denials.
- Code MUST verify whether the target task belongs to an isolated container namespace before permitting operations that modify namespace configurations (`setns`, `unshare`) or sensitive capabilities.
- Services MUST route runtime security alerts through non-blocking `bpf_ringbuf_output` to prevent memory exhaustion and lock contention during container denial-of-service attempts.

## Bad vs Good Implementations
### Synchronous BPF-LSM Container Namespace Escape Mediation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kprobes fire asynchronously or without LSM veto capability; they cannot return security denial codes (-EPERM) to preempt kernel state modification, leaving the host fully exposed to zero-day escapes.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>

// ANTI-PATTERN: Using asynchronous kprobe tracing to detect namespace tampering.
// Kprobes execute without the ability to block the operation (-EPERM is ignored),
// creating a fatal TOCTOU race window where the container escape succeeds before userspace reacts.
SEC("kprobe/sys_setns")
int BPF_KPROBE(trace_setns, int fd, int nstype) {
    struct task_struct *task = (struct task_struct *)bpf_get_current_task();
    pid_t pid = bpf_get_current_pid_tgid() >> 32;
    
    // Asynchronously log to a trace pipe; cannot stop host namespace takeover
    bpf_printk("WARNING: PID %d invoked setns, potential escape!\n", pid);
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Attaching to an LSM hook provides direct veto power via `-EPERM` within kernel space, preempting execution before host namespaces or task security contexts can be altered.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>

#define EPERM 1

char LICENSE[] SEC("license") = "Dual BSD/GPL";

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

// LSM hook intercepting setns before target namespace changes occur
SEC("lsm/task_prctl")
int BPF_PROG(restrict_namespace_traversal, int option, unsigned long arg2,
             unsigned long arg3, unsigned long arg4, unsigned long arg5)
{
    struct task_struct *task = bpf_get_current_task_btf();
    struct pid_namespace *task_pid_ns;
    struct pid_namespace *init_pid_ns;

    // Safely resolve namespaces using BPF CO-RE
    task_pid_ns = BPF_CORE_READ(task, nsproxy, pid_ns_for_children);
    init_pid_ns = BPF_CORE_READ(task_pid_ns, parent);

    // Detect if container process attempts to acquire root privileges
    if (task_pid_ns != NULL && init_pid_ns != NULL) {
        // Blocking containerized task from unauthorized privilege mutation
        if (option == PR_SET_SECUREBITS || option == PR_SET_MM) {
            u64 pid_tgid = bpf_get_current_pid_tgid();
            bpf_ringbuf_output(&security_events, &pid_tgid, sizeof(pid_tgid), 0);
            return -EPERM;
        }
    }
    return 0;
}
```

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 Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation

BPF-LSM Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation defines an industrial-grade behavioral standard for devops engineering. Enforces synchronous in-kernel access control using Linux Security Module (BPF-LSM) hooks to block unauthorized container host namespace traversal, credential tampering, and privilege escalation before syscall execution. Prohibits reliance on reactive user-space auditing or prone-to-race kprobes, eliminating Time-of-Check-to-Time-of-Use (TOCTOU) zero-day escape vectors. 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: Post-Execution User-Space Event Auditing and Asynchronous Namespace Escape Detection 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 DriftPost-Execution User-Space Event Auditing and Asynchronous Namespace Escape DetectionCritical
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 hooks to LSM entry points (`SEC("lsm/...")`) returning `-EPERM` synchronously prior to syscall execution rather than relying on audit-only mechanisms.

Engineers MUST ALWAYS attach enforcement hooks to LSM entry points (`SEC("lsm/...")`) returning `-EPERM` synchronously prior to syscall execution rather than relying on audit-only mechanisms.

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 leverage BPF CO-RE (`vmlinux.h` and `BPF_CORE_READ`) to inspect kernel struct members like `task_struct`, `nsproxy`, and `pid_namespace` rather than calculating unsafe pointer offsets.

Engineers MUST ALWAYS leverage BPF CO-RE (`vmlinux.h` and `BPF_CORE_READ`) to inspect kernel struct members like `task_struct`, `nsproxy`, and `pid_namespace` rather than calculating unsafe pointer offsets.

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

Engineers MUST NOT use kprobes, kretprobes, or tracepoints to block unauthorized actions, as they introduce fatal TOCTOU race windows and cannot reliably enforce policy denials.

Engineers MUST NOT use kprobes, kretprobes, or tracepoints to block unauthorized actions, as they introduce fatal TOCTOU race windows and cannot reliably enforce policy denials.

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 verify whether the target task belongs to an isolated container namespace before permitting operations that modify namespace configurations (`setns`, `unshare`) or sensitive capabilities.

Code MUST verify whether the target task belongs to an isolated container namespace before permitting operations that modify namespace configurations (`setns`, `unshare`) or sensitive capabilities.

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

Services MUST route runtime security alerts through non-blocking `bpf_ringbuf_output` to prevent memory exhaustion and lock contention during container denial-of-service attempts.

Services MUST route runtime security alerts through non-blocking `bpf_ringbuf_output` to prevent memory exhaustion and lock contention during container denial-of-service attempts.

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 Kernel Invariant: Enforcing Zero-Trust Container Isolation and Syscall Mediation critical for AI coding assistants?

Enforces synchronous in-kernel access control using Linux Security Module (BPF-LSM) hooks to block unauthorized container host namespace traversal, credential tampering, and privilege escalation before syscall execution. Prohibits reliance on reactive user-space auditing or prone-to-race kprobes, eliminating Time-of-Check-to-Time-of-Use (TOCTOU) zero-day escape vectors. 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 (Post-Execution User-Space Event Auditing and Asynchronous Namespace Escape Detection) 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