This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-lsm-runtime-immutability-drift-enforcement-production-standard

eBPF LSM Container Runtime Immutability and Executable Drift Enforcement

Enforces strict runtime immutability and blocks container binary drift directly in the Linux kernel using Linux Security Module (LSM) eBPF probes. Intercepts file execution, memory mappings, and namespace-scoped process transitions to guarantee W^X violations (PROT_WRITE | PROT_EXEC) and untrusted fileless executions (e.g., memfd_create) are dropped before reaching userspace.

Prohibited Anti-Pattern: Post-Execution Userspace Auditing and Tolerating In-Memory W^X Code Modification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF LSM Container Runtime Immutability and Executable Drift Enforcement - Enforces strict runtime immutability and blocks container binary drift directly in the Linux kernel using Linux Security Module (LSM) eBPF probes. Intercepts file execution, memory mappings, and namespace-scoped process transitions to guarantee W^X violations (PROT_WRITE | PROT_EXEC) and untrusted fileless executions (e.g., memfd_create) are dropped before reaching userspace.
globs: bpf/**/*.bpf.c, src/security/ebpf/**/*.c, pkg/ebpf/**/*.go, kernel/security/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-runtime-immutability-drift-enforcement-production-standard"
---

# eBPF LSM Container Runtime Immutability and Executable Drift Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Post-Execution Userspace Auditing and Tolerating In-Memory W^X Code Modification

## System Constraints
You are a Principal Linux Security and Kernel Engineer enforcing kernel-level workload immutability. You mandate that all executable drift, dynamic in-memory code generation (W^X violations), fileless execution, and unauthorized modifications to mounted container image layers are unconditionally blocked using eBPF LSM (Linux Security Module) hooks at kernel runtime with zero userspace interception latency.

## Strict Guidelines
- Engineers MUST ALWAYS hook eBPF programs to LSM probes `lsm/file_mprotect` and `lsm/bprm_check_security` rather than userspace ptrace or non-blocking tracepoints (e.g., kprobes, tracepoint/syscalls).
- Engineers MUST ALWAYS deny `mprotect` calls requesting simultaneous or sequential writable and executable permissions (`PROT_WRITE | PROT_EXEC` or transitioning from writable to executable) within monitored container cgroups.
- Engineers MUST ALWAYS block execution of anonymous files created via `memfd_create` or temporary non-root storage (`/tmp`, `/dev/shm`) by verifying `vma->vm_file` backings in `lsm/bprm_check_security`.
- Engineers MUST validate target namespace IDs and cgroup v2 paths against a BPF pinned map (`BPF_MAP_TYPE_HASH`) populated by the container runtime during pod initialization.
- Services MUST NOT execute binaries modified after container initialization; LSM probes must compare the in-memory or on-disk inode/device metadata against the immutable manifest BPF map and reject mismatches with `-EPERM`.

## Bad vs Good Implementations
### Blocking In-Memory W^X Drift and Fileless Code Execution via eBPF LSM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Tracepoints cannot return enforcement errors to the kernel. Attackers can execute shellcode via in-memory allocation before any userspace agent processes the alert.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>

// ANTI-PATTERN: Using tracepoints to asynchronously log memory protections.
// Execution is already permitted by the kernel; malicious payloads execute before
// userspace can evaluate or terminate the process.
SEC("tracepoint/syscalls/sys_enter_mprotect")
int trace_mprotect_entry(struct trace_event_raw_sys_enter *ctx) {
    unsigned long prot = ctx->args[2];
    // PROT_WRITE (0x2) and PROT_EXEC (0x4)
    if ((prot & 0x2) && (prot & 0x4)) {
        // Logging after the kernel has already allowed dispatch (TOCTOU)
        bpf_printk("ALERT: W^X violation attempted in PID %d\n", bpf_get_current_pid_tgid() >> 32);
    }
    return 0; // Tracepoints cannot block kernel operations
}
```

#### Production Standard (Correct)
> **Standard**: Attaches directly to the `lsm/file_mprotect` kernel hook, verifies cgroup membership, and rejects requests combining VM_WRITE and VM_EXEC or upgrading writable memory to executable by returning `-EPERM` directly at the kernel boundary.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define VM_WRITE 0x00000002
#define VM_EXEC  0x00000004

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

SEC("lsm/file_mprotect")
int BPF_PROG(enforce_runtime_immutability, struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot, int ret) {
    // If a lower-level LSM already denied the operation, preserve the error code
    if (ret != 0)
        return ret;

    // Confine enforcement strictly to target production container cgroups
    if (!bpf_current_task_under_cgroup(&monitored_cgroups, 0))
        return 0;

    // Enforce strict W^X: Block mappings that request both Write and Execute flags
    if ((prot & (VM_WRITE | VM_EXEC)) == (VM_WRITE | VM_EXEC)) {
        return -EPERM;
    }

    // Prevent transitioning existing writable allocations into executable code
    unsigned long prev_flags = BPF_CORE_READ(vma, vm_flags);
    if ((prev_flags & VM_WRITE) && (prot & VM_EXEC)) {
        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: eBPF LSM Container Runtime Immutability and Executable Drift Enforcement

eBPF LSM Container Runtime Immutability and Executable Drift Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces strict runtime immutability and blocks container binary drift directly in the Linux kernel using Linux Security Module (LSM) eBPF probes. Intercepts file execution, memory mappings, and namespace-scoped process transitions to guarantee W^X violations (PROT_WRITE | PROT_EXEC) and untrusted fileless executions (e.g., memfd_create) are dropped before reaching userspace. 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 Userspace Auditing and Tolerating In-Memory W^X Code Modification 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 Userspace Auditing and Tolerating In-Memory W^X Code ModificationCritical
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 hook eBPF programs to LSM probes `lsm/file_mprotect` and `lsm/bprm_check_security` rather than userspace ptrace or non-blocking tracepoints (e.g., kprobes, tracepoint/syscalls).

Engineers MUST ALWAYS hook eBPF programs to LSM probes `lsm/file_mprotect` and `lsm/bprm_check_security` rather than userspace ptrace or non-blocking tracepoints (e.g., kprobes, tracepoint/syscalls).

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 deny `mprotect` calls requesting simultaneous or sequential writable and executable permissions (`PROT_WRITE | PROT_EXEC` or transitioning from writable to executable) within monitored container cgroups.

Engineers MUST ALWAYS deny `mprotect` calls requesting simultaneous or sequential writable and executable permissions (`PROT_WRITE | PROT_EXEC` or transitioning from writable to executable) within monitored container cgroups.

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 ALWAYS block execution of anonymous files created via `memfd_create` or temporary non-root storage (`/tmp`, `/dev/shm`) by verifying `vma->vm_file` backings in `lsm/bprm_check_security`.

Engineers MUST ALWAYS block execution of anonymous files created via `memfd_create` or temporary non-root storage (`/tmp`, `/dev/shm`) by verifying `vma->vm_file` backings in `lsm/bprm_check_security`.

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

Engineers MUST validate target namespace IDs and cgroup v2 paths against a BPF pinned map (`BPF_MAP_TYPE_HASH`) populated by the container runtime during pod initialization.

Engineers MUST validate target namespace IDs and cgroup v2 paths against a BPF pinned map (`BPF_MAP_TYPE_HASH`) populated by the container runtime during pod 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.
5

Services MUST NOT execute binaries modified after container initialization

Services MUST NOT execute binaries modified after container initialization; LSM probes must compare the in-memory or on-disk inode/device metadata against the immutable manifest BPF map and reject mismatches with `-EPERM`.

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 Container Runtime Immutability and Executable Drift Enforcement critical for AI coding assistants?

Enforces strict runtime immutability and blocks container binary drift directly in the Linux kernel using Linux Security Module (LSM) eBPF probes. Intercepts file execution, memory mappings, and namespace-scoped process transitions to guarantee W^X violations (PROT_WRITE | PROT_EXEC) and untrusted fileless executions (e.g., memfd_create) are dropped before reaching userspace. 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 Userspace Auditing and Tolerating In-Memory W^X Code Modification) 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