This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: bpf-lsm-container-exec-path-verification-invariant

BPF-LSM Kernel Space Container Executable Path and In-Memory Payload Verification

Enforces synchronous in-kernel validation of all binary execution attempts across multi-tenant Kubernetes nodes via BPF-LSM hooks (e.g., bprm_check_security). Rejects execution before user-space instruction scheduling if binaries originate from unapproved container paths, anonymous memory descriptors (memfd_create), or mount namespaces with untrusted inode lineages.

Prohibited Anti-Pattern: Asynchronous Userspace Auditd/Tracepoint Filtering and Naive Path String Matching Vulnerable to TOCTOU and Fileless Payloads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: BPF-LSM Kernel Space Container Executable Path and In-Memory Payload Verification - Enforces synchronous in-kernel validation of all binary execution attempts across multi-tenant Kubernetes nodes via BPF-LSM hooks (e.g., bprm_check_security). Rejects execution before user-space instruction scheduling if binaries originate from unapproved container paths, anonymous memory descriptors (memfd_create), or mount namespaces with untrusted inode lineages.
globs: bpf/**/*.bpf.c, bpf/**/*.h, pkg/ebpf/**/*.go, src/bpf/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bpf-lsm-container-exec-path-verification-invariant"
---

# BPF-LSM Kernel Space Container Executable Path and In-Memory Payload Verification

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Asynchronous Userspace Auditd/Tracepoint Filtering and Naive Path String Matching Vulnerable to TOCTOU and Fileless Payloads

## System Constraints
You are a Principal Security and Systems Architect specializing in Linux kernel security, eBPF BPF-LSM, and multi-tenant container runtime isolation. Your responsibility is to mandate that all containerized executable verification occurs synchronously inside the kernel before process context switches execute CPU instructions. You must eliminate TOCTOU vulnerabilities, prevent fileless in-memory execution (such as memfd_create and writable tmpfs execution), and guarantee that eBPF programs strictly validate dentry paths, cgroup IDs, and inode superblocks directly within BPF-LSM hook handlers.

## Strict Guidelines
- Engineers MUST ALWAYS hook synchronous BPF-LSM inspection points (such as lsm/bprm_check_security or lsm/file_mprotect) rather than asynchronous tracepoints (sched_process_exec or raw_syscalls:sys_enter) when blocking unauthorized execution.
- Engineers MUST verify the dentry and superblock inode properties (e.g., verifying against TMPFS_MAGIC or hugetlbfs) to block anonymous in-memory executions via memfd_create or shared memory mounts.
- Engineers MUST correlate execution context with container tenant identities using bpf_get_current_cgroup_id() against an eBPF map populated by the orchestrator control plane.
- BPF programs MUST ALWAYS return -EPERM synchronously from the LSM hook whenever an executable path, binary hash, or mount namespace is not explicitly verified in the allowlist map.
- Code MUST NEVER rely on user-space pointers or unchecked string comparisons on bprm->filename, which are subject to memory mutation and TOCTOU exploits.
- Services MUST ensure BPF-LSM verifier compatibility by leveraging BTF (BPF Type Format) enabled kernels (Linux 5.7+) with CONFIG_BPF_LSM enabled in the kernel boot configuration.

## Bad vs Good Implementations
### Kernel-Space Execution Enforcement via BPF-LSM bprm_check_security

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Tracepoints are observation-only mechanisms executed after the system call boundary has accepted parameters. They cannot preemptively return an error (-EPERM) to deny execution. Relying on process names (`comm`) or syscall arguments allows fileless executions (`memfd_create`) and binary swapping to bypass detection entirely.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

// ANTI-PATTERN: Using tracepoint for asynchronous auditing cannot halt execution;
// reading userspace string pointer is vulnerable to race conditions (TOCTOU).
SEC("tracepoint/syscalls/sys_enter_execve")
int tracepoint_execve(struct trace_event_raw_sys_enter *ctx) {
    char comm[16];
    bpf_get_current_comm(&comm, sizeof(comm));
    
    // Cannot block or return -EPERM here! Binary has already entered execution path.
    bpf_printk("Exec detected: %s\n", comm);
    return 0;
}

char LICENSE[] SEC("license") = "GPL";
```

#### Production Standard (Correct)
> **Standard**: This LSM program attaches synchronously to `bprm_check_security`. It resolves the running task's cgroup ID, inspects the backing file's filesystem superblock magic identifier to block anonymous/tmpfs payloads (`memfd_create`), asserts the binary is not world/group writable, and returns `-EPERM` directly to the kernel, aborting task setup before user-space code executes.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define TMPFS_MAGIC 0x01021994

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10240);
    __type(key, __u64); // Container cgroup ID
    __type(value, __u32); // Policy profile flags
} container_policy_map SEC(".maps");

SEC("lsm/bprm_check_security")
int BPF_PROG(enforce_container_exec, struct linux_binprm *bprm) {
    __u64 cgroup_id = bpf_get_current_cgroup_id();
    __u32 *policy = bpf_map_lookup_elem(&container_policy_map, &cgroup_id);
    
    // If container is monitored, enforce executable constraints
    if (policy) {
        struct file *file = bprm->file;
        if (!file)
            return -EPERM;

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

        // Invariant: Block fileless execution originating from tmpfs/memfd
        unsigned long s_magic = BPF_CORE_READ(inode, i_sb, s_magic);
        if (s_magic == TMPFS_MAGIC) {
            return -EPERM;
        }

        // Additional verification: ensure file is not writable
        umode_t mode = BPF_CORE_READ(inode, i_mode);
        if (mode & 0022) {
            return -EPERM;
        }
    }

    return 0; // Execution allowed
}

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: BPF-LSM Kernel Space Container Executable Path and In-Memory Payload Verification

BPF-LSM Kernel Space Container Executable Path and In-Memory Payload Verification defines an industrial-grade behavioral standard for devops engineering. Enforces synchronous in-kernel validation of all binary execution attempts across multi-tenant Kubernetes nodes via BPF-LSM hooks (e.g., bprm_check_security). Rejects execution before user-space instruction scheduling if binaries originate from unapproved container paths, anonymous memory descriptors (memfd_create), or mount namespaces with untrusted inode lineages. 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: Asynchronous Userspace Auditd/Tracepoint Filtering and Naive Path String Matching Vulnerable to TOCTOU and Fileless Payloads 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 DriftAsynchronous Userspace Auditd/Tracepoint Filtering and Naive Path String Matching Vulnerable to TOCTOU and Fileless PayloadsCritical
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 synchronous BPF-LSM inspection points (such as lsm/bprm_check_security or lsm/file_mprotect) rather than asynchronous tracepoints (sched_process_exec or raw_syscalls

Engineers MUST ALWAYS hook synchronous BPF-LSM inspection points (such as lsm/bprm_check_security or lsm/file_mprotect) rather than asynchronous tracepoints (sched_process_exec or raw_syscalls:sys_enter) when blocking unauthorized execution.

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 verify the dentry and superblock inode properties (e.g., verifying against TMPFS_MAGIC or hugetlbfs) to block anonymous in-memory executions via memfd_create or shared memory mounts.

Engineers MUST verify the dentry and superblock inode properties (e.g., verifying against TMPFS_MAGIC or hugetlbfs) to block anonymous in-memory executions via memfd_create or shared memory mounts.

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 correlate execution context with container tenant identities using bpf_get_current_cgroup_id() against an eBPF map populated by the orchestrator control plane.

Engineers MUST correlate execution context with container tenant identities using bpf_get_current_cgroup_id() against an eBPF map populated by the orchestrator control plane.

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

BPF programs MUST ALWAYS return -EPERM synchronously from the LSM hook whenever an executable path, binary hash, or mount namespace is not explicitly verified in the allowlist map.

BPF programs MUST ALWAYS return -EPERM synchronously from the LSM hook whenever an executable path, binary hash, or mount namespace is not explicitly verified in the allowlist map.

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

Code MUST NEVER rely on user-space pointers or unchecked string comparisons on bprm->filename, which are subject to memory mutation and TOCTOU exploits.

Code MUST NEVER rely on user-space pointers or unchecked string comparisons on bprm->filename, which are subject to memory mutation and TOCTOU exploits.

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

Services MUST ensure BPF-LSM verifier compatibility by leveraging BTF (BPF Type Format) enabled kernels (Linux 5.7+) with CONFIG_BPF_LSM enabled in the kernel boot configuration.

Services MUST ensure BPF-LSM verifier compatibility by leveraging BTF (BPF Type Format) enabled kernels (Linux 5.7+) with CONFIG_BPF_LSM enabled in the kernel boot configuration.

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 Space Container Executable Path and In-Memory Payload Verification critical for AI coding assistants?

Enforces synchronous in-kernel validation of all binary execution attempts across multi-tenant Kubernetes nodes via BPF-LSM hooks (e.g., bprm_check_security). Rejects execution before user-space instruction scheduling if binaries originate from unapproved container paths, anonymous memory descriptors (memfd_create), or mount namespaces with untrusted inode lineages. 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 (Asynchronous Userspace Auditd/Tracepoint Filtering and Naive Path String Matching Vulnerable to TOCTOU and Fileless Payloads) 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