This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-lsm-microvm-privilege-fencing-standard

Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs

Enforces deterministic, kernel-space privilege confinement for ephemeral microVM workloads by anchoring Linux Security Module (LSM) BPF hooks to cgroup contexts. Eliminates Time-of-Check to Time-of-Use (TOCTOU) capability inheritance races by making security boundaries strictly synchronous and unbypassable.

Prohibited Anti-Pattern: Userspace Asynchronous Security Monitoring and Fail-Open LSM Hook Returns

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs - Enforces deterministic, kernel-space privilege confinement for ephemeral microVM workloads by anchoring Linux Security Module (LSM) BPF hooks to cgroup contexts. Eliminates Time-of-Check to Time-of-Use (TOCTOU) capability inheritance races by making security boundaries strictly synchronous and unbypassable.
globs: **/*.bpf.c, **/*.bpf.h, src/security/**/*.rs, pkg/ebpf/**/*.go, internal/lsm/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-microvm-privilege-fencing-standard"
---

# Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Userspace Asynchronous Security Monitoring and Fail-Open LSM Hook Returns

## System Constraints
You are a Principal Software Architect and Linux Kernel Security Engineer enforcing runtime-immutable eBPF LSM Privilege Fencing for ephemeral microVMs (e.g., Firecracker, Cloud Hypervisor). You must reject any code relying on asynchronous userspace telemetry for access control, insecure seccomp fail-open filters, or mutable privilege maps. Ensure synchronous, deterministic -EPERM enforcement at the LSM layer.

## Strict Guidelines
- Engineers MUST ALWAYS implement synchronous rejection (-EPERM) directly inside eBPF LSM hooks (`SEC("lsm/capable")`, `SEC("lsm/task_fix_setuid")`) rather than delegating decisions to userspace ring buffers.
- Engineers MUST NOT allow fallback-to-allow or fail-open execution paths when BPF policy map lookups miss or return null pointers.
- Code SHOULD seal BPF policy maps with `BPF_F_RDONLY_PROG` after hypervisor initialization to prevent guest workloads from tampering with allowed capability masks.
- Services MUST scope LSM execution contracts to specific microVM cgroups using `bpf_get_current_cgroup_id()` to avoid cross-tenant collateral enforcement.
- Components NEVER permit capability escalation (specifically `CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_BPF`, or `CAP_SYS_RAWIO`) unless verified against a signed, pre-boot VM deployment manifest.

## Bad vs Good Implementations
### Enforcing Immutable Kernel LSM Capability Boundaries

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing open when a policy entry is missing allows untracked microVM processes to inherit all host capabilities. Deferring block decisions to userspace or logging without returning `-EPERM` enables deterministic privilege escalation exploits.
```c
// Insecure: Fail-open lookup and asynchronous audit-only posture
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, __u64);
    __type(value, __u32);
} vm_allowed_caps SEC(".maps");

SEC("lsm/capable")
int BPF_PROG(restricted_capable, const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts, int ret) {
    __u64 cgroup_id = bpf_get_current_cgroup_id();
    __u32 *allowed_caps = bpf_map_lookup_elem(&vm_allowed_caps, &cgroup_id);

    // CRITICAL FLAW: Fails open if cgroup is not found or policy lookup fails
    if (!allowed_caps) {
        return 0; // Allowed by default
    }

    // CRITICAL FLAW: Only logs instead of blocking privilege escalation
    if (!(*allowed_caps & (1U << cap))) {
        bpf_printk("Warning: capability %d denied for cgroup %llu", cap, cgroup_id);
        return 0; // Does not block escalation
    }

    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Honors pre-existing hook denials, scopes enforcement strictly to monitored microVM cgroups, bounds check capability identifiers, and enforces synchronous `-EPERM` rejection from read-only pinned policy memory.
```c
// Secure: Synchronous, deterministic default-deny LSM capability fencing
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>
#include <errno.h>

struct vm_cap_policy {
    __u64 allowed_mask;
    __u32 is_monitored;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 4096);
    __type(key, __u64); // cgroup_id
    __type(value, struct vm_cap_policy);
    __uint(map_flags, BPF_F_RDONLY_PROG);
} vm_policy_map SEC(".maps");

SEC("lsm/capable")
int BPF_PROG(fence_microvm_capabilities, const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts, int ret) {
    // If upstream hook already denied capability, honor previous decision
    if (ret != 0) {
        return ret;
    }

    __u64 cgroup_id = bpf_get_current_cgroup_id();
    struct vm_cap_policy *policy = bpf_map_lookup_elem(&vm_policy_map, &cgroup_id);

    // Workload is not an ephemeral microVM tracked by this security fence
    if (!policy || policy->is_monitored == 0) {
        return 0;
    }

    // Capability index boundary guard
    if (cap < 0 || cap >= 64) {
        return -EPERM;
    }

    // Synchronously deny any capability outside the immutable bitmask
    if (!(policy->allowed_mask & (1ULL << cap))) {
        return -EPERM;
    }

    return 0;
}

char _license[] SEC("license") = "Dual BSD/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: Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs

Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, kernel-space privilege confinement for ephemeral microVM workloads by anchoring Linux Security Module (LSM) BPF hooks to cgroup contexts. Eliminates Time-of-Check to Time-of-Use (TOCTOU) capability inheritance races by making security boundaries strictly synchronous and unbypassable. 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: Userspace Asynchronous Security Monitoring and Fail-Open LSM Hook Returns 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 DriftUserspace Asynchronous Security Monitoring and Fail-Open LSM Hook ReturnsCritical
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 synchronous rejection (-EPERM) directly inside eBPF LSM hooks (`SEC("lsm/capable")`, `SEC("lsm/task_fix_setuid")`) rather than delegating decisions to userspace ring buffers.

Engineers MUST ALWAYS implement synchronous rejection (-EPERM) directly inside eBPF LSM hooks (`SEC("lsm/capable")`, `SEC("lsm/task_fix_setuid")`) rather than delegating decisions to userspace ring buffers.

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 fallback-to-allow or fail-open execution paths when BPF policy map lookups miss or return null pointers.

Engineers MUST NOT allow fallback-to-allow or fail-open execution paths when BPF policy map lookups miss or return null pointers.

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 seal BPF policy maps with `BPF_F_RDONLY_PROG` after hypervisor initialization to prevent guest workloads from tampering with allowed capability masks.

Code SHOULD seal BPF policy maps with `BPF_F_RDONLY_PROG` after hypervisor initialization to prevent guest workloads from tampering with allowed capability masks.

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 scope LSM execution contracts to specific microVM cgroups using `bpf_get_current_cgroup_id()` to avoid cross-tenant collateral enforcement.

Services MUST scope LSM execution contracts to specific microVM cgroups using `bpf_get_current_cgroup_id()` to avoid cross-tenant collateral enforcement.

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 capability escalation (specifically `CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_BPF`, or `CAP_SYS_RAWIO`) unless verified against a signed, pre-boot VM deployment manifest.

Components NEVER permit capability escalation (specifically `CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_BPF`, or `CAP_SYS_RAWIO`) unless verified against a signed, pre-boot VM deployment manifest.

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 Runtime-Immutable eBPF LSM Privilege Fencing for MicroVMs critical for AI coding assistants?

Enforces deterministic, kernel-space privilege confinement for ephemeral microVM workloads by anchoring Linux Security Module (LSM) BPF hooks to cgroup contexts. Eliminates Time-of-Check to Time-of-Use (TOCTOU) capability inheritance races by making security boundaries strictly synchronous and unbypassable. 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 (Userspace Asynchronous Security Monitoring and Fail-Open LSM Hook Returns) 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

Runtime-Immutable