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

Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate

Enforces deterministic, in-kernel verification of binary integrity and memory-mapping invariants using eBPF Linux Security Modules (LSM) hooks (`bprm_check_security`, `file_mprotect`, `mmap_file`). Halts execution of tampered binaries, unverified shared libraries, and mutable executable memory segments (W^X violations) directly within the kernel before payload execution can occur in containerized workloads.

Prohibited Anti-Pattern: Relying on Userspace Audit Daemons or Permitting W^X (Write XOR Execute) Memory State Transitions Inside Container Namespaces

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate - Enforces deterministic, in-kernel verification of binary integrity and memory-mapping invariants using eBPF Linux Security Modules (LSM) hooks (`bprm_check_security`, `file_mprotect`, `mmap_file`). Halts execution of tampered binaries, unverified shared libraries, and mutable executable memory segments (W^X violations) directly within the kernel before payload execution can occur in containerized workloads.
globs: **/*.bpf.c, **/*.bpf.h, kernel/**/*.c, pkg/security/**/*.go, src/security/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/lsm-bpf-runtime-binary-integrity-gate"
---

# Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Userspace Audit Daemons or Permitting W^X (Write XOR Execute) Memory State Transitions Inside Container Namespaces

## System Constraints
You are a Principal Linux Kernel and Security Engineer enforcing strict dynamic binary integrity and W^X invariants via BPF LSM. You reject architectural patterns that delegate memory-mapping access control to asynchronous user-space scanners. You mandate that all executable pages, dynamic loader operations, and memory protection modifications be verified synchronously at the kernel layer using LSM hooks before page tables are updated or binaries enter user-space execution.

## Strict Guidelines
- Engineers MUST ALWAYS attach LSM hooks to `bprm_check_security` to validate binary file integrity signatures or cryptographic hashes against an in-kernel pinned BPF hash map before execution dispatch.
- Engineers MUST ALWAYS intercept `security_file_mprotect` and `security_mmap_file` to reject any operations requesting simultaneous write and execute permissions (`PROT_WRITE | PROT_EXEC`) or modifying code pages after initial mapping.
- Engineers MUST NOT allow unverified dynamic shared objects (`.so`) to map into running container namespaces without passing deterministic integrity policy checks in `security_mmap_file`.
- Code SHOULD verify container namespace identification via `bpf_get_current_pid_tgid()` and kernel task struct cgroup identifiers (`task->cgroups`) before applying namespace-specific immutability enforcement.
- Security policies MUST return `-EPERM` synchronously from the LSM hook rather than relying on delayed user-space signal dispatch (`SIGKILL`) or post-exec audit logs.
- Components NEVER execute unsigned anonymous memory allocations as executable pages (`memfd_create` execution evasion vectors MUST be blocked in `bprm_check_security`).

## Bad vs Good Implementations
### LSM BPF Program Blocking W^X Violations and Untrusted Dynamic Code Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The BPF LSM hook passively logs the creation of writable and executable (W+X) memory pages instead of blocking them. This gives memory-only payloads and supply-chain tampering mechanisms an uninterrupted execution window to rewrite `.text` segments or stage dynamic shellcode.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>

// ANTI-PATTERN: Merely logging W^X violations or deferring policy checks to userspace
SEC("lsm/file_mprotect")
int BPF_PROG(enforce_memory_protection, struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot)
{
    // Insecure: Permitting writable and executable mappings to proceed
    if ((prot & 0x01) && (prot & 0x02)) { // PROT_READ/WRITE/EXEC unconstrained
        bpf_printk("Warning: W+X memory mapping detected in PID %d\n", bpf_get_current_pid_tgid() >> 32);
        // Fails to abort: Returning 0 permits zero-day shellcode staging
        return 0;
    }
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: This LSM BPF program intercepts kernel memory-mapping transitions synchronously. It verifies whether the task belongs to an enforced container cgroup, strictly disallows both `PROT_WRITE | PROT_EXEC` combinations and write adjustments to active executable segments, and returns `-EPERM` prior to VMA modification.
```c
#include <vmlinux.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_helpers.h>

#define PROT_READ  0x1
#define PROT_WRITE 0x2
#define PROT_EXEC  0x4
#define EPERM      1

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

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, u64);
    __type(value, u8);
} monitored_cgroups SEC(".maps");

SEC("lsm/file_mprotect")
int BPF_PROG(enforce_memory_protection, struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot)
{
    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *monitored = bpf_map_lookup_elem(&monitored_cgroups, &cgroup_id);

    if (!monitored)
        return 0;

    // Mandatory W^X enforcement: Deny simultaneous PROT_WRITE and PROT_EXEC
    if ((reqprot & (PROT_WRITE | PROT_EXEC)) == (PROT_WRITE | PROT_EXEC)) {
        bpf_printk("LSM Gate: Blocked W^X transition for cgroup %llu\n", cgroup_id);
        return -EPERM;
    }

    // Prevent making existing executable segments writable
    unsigned long vm_flags = BPF_CORE_READ(vma, vm_flags);
    if ((vm_flags & 0x00000004) && (reqprot & PROT_WRITE)) { // VM_EXEC
        bpf_printk("LSM Gate: Blocked write modification to executable segment\n");
        return -EPERM;
    }

    return 0;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate

Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, in-kernel verification of binary integrity and memory-mapping invariants using eBPF Linux Security Modules (LSM) hooks (`bprm_check_security`, `file_mprotect`, `mmap_file`). Halts execution of tampered binaries, unverified shared libraries, and mutable executable memory segments (W^X violations) directly within the kernel before payload execution can occur in containerized workloads. 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 Userspace Audit Daemons or Permitting W^X (Write XOR Execute) Memory State Transitions Inside Container Namespaces 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 Userspace Audit Daemons or Permitting W^X (Write XOR Execute) Memory State Transitions Inside Container NamespacesCritical
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 LSM hooks to `bprm_check_security` to validate binary file integrity signatures or cryptographic hashes against an in-kernel pinned BPF hash map before execution dispatch.

Engineers MUST ALWAYS attach LSM hooks to `bprm_check_security` to validate binary file integrity signatures or cryptographic hashes against an in-kernel pinned BPF hash map before execution dispatch.

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 intercept `security_file_mprotect` and `security_mmap_file` to reject any operations requesting simultaneous write and execute permissions (`PROT_WRITE | PROT_EXEC`) or modifying code pages after initial mapping.

Engineers MUST ALWAYS intercept `security_file_mprotect` and `security_mmap_file` to reject any operations requesting simultaneous write and execute permissions (`PROT_WRITE | PROT_EXEC`) or modifying code pages after initial mapping.

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 allow unverified dynamic shared objects (`.so`) to map into running container namespaces without passing deterministic integrity policy checks in `security_mmap_file`.

Engineers MUST NOT allow unverified dynamic shared objects (`.so`) to map into running container namespaces without passing deterministic integrity policy checks in `security_mmap_file`.

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 SHOULD verify container namespace identification via `bpf_get_current_pid_tgid()` and kernel task struct cgroup identifiers (`task->cgroups`) before applying namespace-specific immutability enforcement.

Code SHOULD verify container namespace identification via `bpf_get_current_pid_tgid()` and kernel task struct cgroup identifiers (`task->cgroups`) before applying namespace-specific immutability 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

Security policies MUST return `-EPERM` synchronously from the LSM hook rather than relying on delayed user-space signal dispatch (`SIGKILL`) or post-exec audit logs.

Security policies MUST return `-EPERM` synchronously from the LSM hook rather than relying on delayed user-space signal dispatch (`SIGKILL`) or post-exec audit logs.

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.
6

Components NEVER execute unsigned anonymous memory allocations as executable pages (`memfd_create` execution evasion vectors MUST be blocked in `bprm_check_security`).

Components NEVER execute unsigned anonymous memory allocations as executable pages (`memfd_create` execution evasion vectors MUST be blocked in `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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Linux Kernel LSM BPF Dynamic Binary and Memory Immutability Gate critical for AI coding assistants?

Enforces deterministic, in-kernel verification of binary integrity and memory-mapping invariants using eBPF Linux Security Modules (LSM) hooks (`bprm_check_security`, `file_mprotect`, `mmap_file`). Halts execution of tampered binaries, unverified shared libraries, and mutable executable memory segments (W^X violations) directly within the kernel before payload execution can occur in containerized workloads. 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 Userspace Audit Daemons or Permitting W^X (Write XOR Execute) Memory State Transitions Inside Container Namespaces) 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

Linux