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

BPF-LSM Kernel-Level Cryptographic Binary Hash Enforcement Standard

Enforces immutable container security by intercepting binary execution at the kernel LSM layer (bprm_check_security). Guarantees synchronous integrity validation via cryptographic digests before process execution, strictly preventing TOCTOU races, unapproved binaries, and container drift.

Prohibited Anti-Pattern: Relying on Userland Path Checking or Asynchronous Syscall Tracing for Binary Authorization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: BPF-LSM Kernel-Level Cryptographic Binary Hash Enforcement Standard - Enforces immutable container security by intercepting binary execution at the kernel LSM layer (bprm_check_security). Guarantees synchronous integrity validation via cryptographic digests before process execution, strictly preventing TOCTOU races, unapproved binaries, and container drift.
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-lsm-binary-digest-enforcement"
---

# BPF-LSM Kernel-Level Cryptographic Binary Hash Enforcement Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Userland Path Checking or Asynchronous Syscall Tracing for Binary Authorization

## System Constraints
You are a Principal Linux Security and eBPF Systems Architect enforcing real-time binary digest verification through BPF-LSM. Mandate synchronous execution denial via bprm_check_security hooks, strict fail-closed behaviors, authenticated digest lookups via pinned kernel maps, and full mitigation of TOCTOU path-based vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS attach binary authorization hooks to the synchronous 'lsm/bprm_check_security' LSM hook point to ensure deterministic pre-execution denial.
- Engineers MUST NOT validate binaries by file path strings or mount namespaces alone; authorization MUST be bound to immutable kernel inode metadata, fs-verity digests, or cryptographic file hashes.
- Programs MUST ALWAYS default to a fail-closed model (-EPERM or -EACCES) when an unknown binary execution attempt occurs within monitored container cgroups.
- Engineers MUST NEVER use asynchronous tracepoints (e.g., 'sys_enter_execve') or seccomp alone for real-time binary payload authorization, as they suffer from Time-of-Check to Time-of-Use (TOCTOU) file substitution vulnerabilities.
- Kernel BPF maps storing authorized digests MUST be pinned in a secure bpffs directory with root-only capabilities (CAP_SYS_ADMIN/CAP_BPF) and marked with read-only access flags within BPF program contexts.
- All BPF-LSM programs MUST verify the container context via 'bpf_get_current_cgroup_id()' or task cgroup tracking before enforcing policy to prevent deadlocking system init or host critical daemons.

## Bad vs Good Implementations
### Insecure Path-Based Syscall Tracing vs. Synchronous BPF-LSM Hash Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a tracepoint on sys_enter_execve is asynchronous and non-blocking, meaning malicious code executes regardless. Additionally, validating file path strings introduces critical TOCTOU vulnerabilities because the file can be swapped or modified after the path check.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

// Anti-pattern: Tracepoint-based exec interception relies on mutable path strings
// and cannot block execution synchronously; subject to TOCTOU attacks.
SEC("tracepoint/syscalls/sys_enter_execve")
int trace_exec(struct trace_event_raw_sys_enter_execve *ctx) {
    char filename[256];
    bpf_probe_read_user_str(filename, sizeof(filename), (const char *)ctx->args[0]);

    // Insecure: Path check allows symlink substitution, mount spoofing, and file alteration
    if (filename[0] == '/' && filename[1] == 't' && filename[2] == 'm' && filename[3] == 'p') {
        bpf_printk("Execution attempted in /tmp: %s\n", filename);
        // Tracepoints cannot return -EPERM or abort the execve kernel execution pipeline
    }
    return 0;
}

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

#### Production Standard (Correct)
> **Standard**: Attaching directly to the LSM hook 'bprm_check_security' allows synchronous blocking by returning -EPERM. It identifies the target via immutable kernel struct data (inode and dev), scoping execution checks strictly to target cgroups and preventing TOCTOU races.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define SHA256_DIGEST_LEN 32

struct binary_id {
    __u64 inode;
    __u32 dev_major;
    __u32 dev_minor;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 10240);
    __type(key, struct binary_id);
    __type(value, __u8[SHA256_DIGEST_LEN]);
} allowed_binaries SEC(".maps");

SEC("lsm/bprm_check_security")
int BPF_PROG(enforce_binary_digest, struct linux_binprm *bprm) {
    __u64 cgroup_id = bpf_get_current_cgroup_id();
    
    // Scope enforcement specifically to container workloads
    if (cgroup_id <= 1) {
        return 0; // Bypass host root init daemon
    }

    struct file *file = BPF_CORE_READ(bprm, file);
    if (!file) {
        return -EPERM; // Fail closed
    }

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

    struct binary_id key = {};
    key.inode = BPF_CORE_READ(inode, i_ino);
    key.dev_major = BPF_CORE_READ(inode, i_sb, s_dev) >> 20;
    key.dev_minor = BPF_CORE_READ(inode, i_sb, s_dev) & 0xFFFFF;

    __u8 *digest = bpf_map_lookup_elem(&allowed_binaries, &key);
    if (!digest) {
        // Deny execution: Unrecognized binary or digest missing from authorized map
        return -EPERM;
    }

    return 0; // Authorized
}

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: BPF-LSM Kernel-Level Cryptographic Binary Hash Enforcement Standard

BPF-LSM Kernel-Level Cryptographic Binary Hash Enforcement Standard defines an industrial-grade behavioral standard for security engineering. Enforces immutable container security by intercepting binary execution at the kernel LSM layer (bprm_check_security). Guarantees synchronous integrity validation via cryptographic digests before process execution, strictly preventing TOCTOU races, unapproved binaries, and container drift. 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 Userland Path Checking or Asynchronous Syscall Tracing for Binary Authorization 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 Userland Path Checking or Asynchronous Syscall Tracing for Binary AuthorizationCritical
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 binary authorization hooks to the synchronous 'lsm/bprm_check_security' LSM hook point to ensure deterministic pre-execution denial.

Engineers MUST ALWAYS attach binary authorization hooks to the synchronous 'lsm/bprm_check_security' LSM hook point to ensure deterministic pre-execution denial.

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 validate binaries by file path strings or mount namespaces alone

Engineers MUST NOT validate binaries by file path strings or mount namespaces alone; authorization MUST be bound to immutable kernel inode metadata, fs-verity digests, or cryptographic file hashes.

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

Programs MUST ALWAYS default to a fail-closed model (-EPERM or -EACCES) when an unknown binary execution attempt occurs within monitored container cgroups.

Programs MUST ALWAYS default to a fail-closed model (-EPERM or -EACCES) when an unknown binary execution attempt occurs 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.
4

Engineers MUST NEVER use asynchronous tracepoints (e.g., 'sys_enter_execve') or seccomp alone for real-time binary payload authorization, as they suffer from Time-of-Check to Time-of-Use (TOCTOU) file substitution vulnerabilities.

Engineers MUST NEVER use asynchronous tracepoints (e.g., 'sys_enter_execve') or seccomp alone for real-time binary payload authorization, as they suffer from Time-of-Check to Time-of-Use (TOCTOU) file substitution vulnerabilities.

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

Kernel BPF maps storing authorized digests MUST be pinned in a secure bpffs directory with root-only capabilities (CAP_SYS_ADMIN/CAP_BPF) and marked with read-only access flags within BPF program contexts.

Kernel BPF maps storing authorized digests MUST be pinned in a secure bpffs directory with root-only capabilities (CAP_SYS_ADMIN/CAP_BPF) and marked with read-only access flags within BPF program contexts.

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

All BPF-LSM programs MUST verify the container context via 'bpf_get_current_cgroup_id()' or task cgroup tracking before enforcing policy to prevent deadlocking system init or host critical daemons.

All BPF-LSM programs MUST verify the container context via 'bpf_get_current_cgroup_id()' or task cgroup tracking before enforcing policy to prevent deadlocking system init or host critical daemons.

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-Level Cryptographic Binary Hash Enforcement Standard critical for AI coding assistants?

Enforces immutable container security by intercepting binary execution at the kernel LSM layer (bprm_check_security). Guarantees synchronous integrity validation via cryptographic digests before process execution, strictly preventing TOCTOU races, unapproved binaries, and container drift. 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 Userland Path Checking or Asynchronous Syscall Tracing for Binary Authorization) 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