This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-bpflsm-container-exec-constraint-standard

eBPF BPF-LSM Container Binary Execution and Memory Protection Guardrail

Restricts executable memory mapping calls (`mprotect`, `mmap`) and process executions (`bprm_check_security`) at the kernel LSM layer to immutable, verified container rootfs mounts. Hardens runtime workloads against fileless ELF injection (memfd_create), arbitrary reverse shells, and untrusted shared-object loading by validating inode backing and namespace cgroup identifiers in kernel space.

Prohibited Anti-Pattern: Relying on Userspace Runtime Monitors or Post-Exec Syscall Filters Allowing Memory Injection and Ephemeral Binaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF BPF-LSM Container Binary Execution and Memory Protection Guardrail - Restricts executable memory mapping calls (`mprotect`, `mmap`) and process executions (`bprm_check_security`) at the kernel LSM layer to immutable, verified container rootfs mounts. Hardens runtime workloads against fileless ELF injection (memfd_create), arbitrary reverse shells, and untrusted shared-object loading by validating inode backing and namespace cgroup identifiers in kernel space.
globs: **/*.bpf.c, **/*.bpf.h, src/security/**/*.c, pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-bpflsm-container-exec-constraint-standard"
---

# eBPF BPF-LSM Container Binary Execution and Memory Protection Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Userspace Runtime Monitors or Post-Exec Syscall Filters Allowing Memory Injection and Ephemeral Binaries

## System Constraints
You are a Principal Systems and Security Engineer specializing in eBPF, BPF-LSM hooks, and container runtime isolation. Your mission is to enforce strict kernel-level execution control standards across all container workloads. You mandate invariant enforcement preventing W^X violations, anonymous executable memory allocations (such as via memfd_create), and unauthorized binary execution inside container namespaces.

## Strict Guidelines
- Engineers MUST hook `LSM_PROBE(bprm_check_security)` to enforce that all executed binaries resolve to read-only mounts belonging to approved container rootfs mount namespaces.
- Engineers MUST hook `LSM_PROBE(file_mprotect)` and `LSM_PROBE(mmap_file)` to strictly reject `PROT_EXEC` modifications on anonymous pages, writable files, or non-file-backed memory descriptors (e.g., `memfd`).
- BPF programs MUST track container cgroup identifiers via task struct introspection (`bpf_get_current_cgroup_id()`) and match against authenticated control-plane state maps before evaluating execution policy.
- Engineers MUST NOT permit fallback to permissive execution modes if BPF map lookup fails; unauthorized or untracked cgroup contexts attempting execution within monitored namespaces MUST default to returning `-EPERM`.
- BPF programs MUST employ CO-RE (`vmlinux.h`) and ensure read access through `bpf_core_read()` or direct access where verified, strictly guarding against TOCTOU race conditions when checking file path or superblock flags.

## Bad vs Good Implementations
### Enforcing Immutable Binary Execution and Blocking memfd Payloads in BPF-LSM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This implementation fails to validate executable file lineage, mount immutability, or anonymous file descriptors. It inspects process comm which is trivially spoofable, misses memfd-backed execution, and fails to check cgroup isolation context.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

SEC("lsm/bprm_check_security")
int BPF_PROG(restrict_exec, struct linux_binprm *bprm)
{
    // Flawed: Only checks process name or allows arbitrary execution if path is absent
    char comm[16];
    bpf_get_current_comm(&comm, sizeof(comm));

    // Blindly permits execution if not explicitly named 'malicious'
    if (comm[0] == 'm') {
        return -1;
    }
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Hooks `bprm_check_security` and `file_mprotect` using BPF-LSM. Checks container cgroup membership, verifies binary backing on a read-only superblock, and denies anonymous executable mapping conversions to eliminate memory injection attacks.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>

#define EPERM 1
#define SB_RDONLY 1

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

SEC("lsm/bprm_check_security")
int BPF_PROG(enforce_container_exec_immutability, struct linux_binprm *bprm)
{
    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *is_monitored = bpf_map_lookup_elem(&monitored_cgroups, &cgroup_id);
    if (!is_monitored)
        return 0; // Not a target container cgroup

    struct file *file = BPF_CORE_READ(bprm, file);
    if (!file)
        return -EPERM;

    // Block anonymous execution (e.g., memfd_create without backing mount)
    struct inode *inode = BPF_CORE_READ(file, f_inode);
    if (!inode)
        return -EPERM;

    // Enforce that container execution strictly occurs on a read-only mounted filesystem
    struct super_block *sb = BPF_CORE_READ(inode, i_sb);
    unsigned long s_flags = BPF_CORE_READ(sb, s_flags);
    if (!(s_flags & SB_RDONLY))
        return -EPERM; // Deny execution from writable container layers

    return 0;
}

SEC("lsm/file_mprotect")
int BPF_PROG(enforce_no_wx, struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot)
{
    u64 cgroup_id = bpf_get_current_cgroup_id();
    u8 *is_monitored = bpf_map_lookup_elem(&monitored_cgroups, &cgroup_id);
    if (!is_monitored)
        return 0;

    #define VM_EXEC 0x00000004
    #define VM_WRITE 0x00000002

    // Block transitioning pages into executable if not backed by read-only file
    if (prot & VM_EXEC) {
        struct file *vm_file = BPF_CORE_READ(vma, vm_file);
        if (!vm_file) {
            // Disallow PROT_EXEC on anonymous memory allocations (W^X / JIT evasion)
            return -EPERM;
        }
    }
    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: eBPF BPF-LSM Container Binary Execution and Memory Protection Guardrail

eBPF BPF-LSM Container Binary Execution and Memory Protection Guardrail defines an industrial-grade behavioral standard for security engineering. Restricts executable memory mapping calls (`mprotect`, `mmap`) and process executions (`bprm_check_security`) at the kernel LSM layer to immutable, verified container rootfs mounts. Hardens runtime workloads against fileless ELF injection (memfd_create), arbitrary reverse shells, and untrusted shared-object loading by validating inode backing and namespace cgroup identifiers in kernel space. 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 Runtime Monitors or Post-Exec Syscall Filters Allowing Memory Injection and Ephemeral Binaries 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 Runtime Monitors or Post-Exec Syscall Filters Allowing Memory Injection and Ephemeral BinariesCritical
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 hook `LSM_PROBE(bprm_check_security)` to enforce that all executed binaries resolve to read-only mounts belonging to approved container rootfs mount namespaces.

Engineers MUST hook `LSM_PROBE(bprm_check_security)` to enforce that all executed binaries resolve to read-only mounts belonging to approved container rootfs mount namespaces.

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 hook `LSM_PROBE(file_mprotect)` and `LSM_PROBE(mmap_file)` to strictly reject `PROT_EXEC` modifications on anonymous pages, writable files, or non-file-backed memory descriptors (e.g., `memfd`).

Engineers MUST hook `LSM_PROBE(file_mprotect)` and `LSM_PROBE(mmap_file)` to strictly reject `PROT_EXEC` modifications on anonymous pages, writable files, or non-file-backed memory descriptors (e.g., `memfd`).

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

BPF programs MUST track container cgroup identifiers via task struct introspection (`bpf_get_current_cgroup_id()`) and match against authenticated control-plane state maps before evaluating execution policy.

BPF programs MUST track container cgroup identifiers via task struct introspection (`bpf_get_current_cgroup_id()`) and match against authenticated control-plane state maps before evaluating execution policy.

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 NOT permit fallback to permissive execution modes if BPF map lookup fails

Engineers MUST NOT permit fallback to permissive execution modes if BPF map lookup fails; unauthorized or untracked cgroup contexts attempting execution within monitored namespaces MUST default to returning `-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.
5

BPF programs MUST employ CO-RE (`vmlinux.h`) and ensure read access through `bpf_core_read()` or direct access where verified, strictly guarding against TOCTOU race conditions when checking file path or superblock flags.

BPF programs MUST employ CO-RE (`vmlinux.h`) and ensure read access through `bpf_core_read()` or direct access where verified, strictly guarding against TOCTOU race conditions when checking file path or superblock flags.

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 BPF-LSM Container Binary Execution and Memory Protection Guardrail critical for AI coding assistants?

Restricts executable memory mapping calls (`mprotect`, `mmap`) and process executions (`bprm_check_security`) at the kernel LSM layer to immutable, verified container rootfs mounts. Hardens runtime workloads against fileless ELF injection (memfd_create), arbitrary reverse shells, and untrusted shared-object loading by validating inode backing and namespace cgroup identifiers in kernel space. 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 Runtime Monitors or Post-Exec Syscall Filters Allowing Memory Injection and Ephemeral Binaries) 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