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

Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec

Enforces synchronous cryptographic integrity verification of executable binaries inside the kernel before container process execution. BPF-LSM hooks on bprm_creds_for_exec must query kernel IMA digests via bpf_ima_inode_hash or bpf_ima_file_hash and reject unmeasured or untrusted binaries with -EPERM to eliminate TOCTOU execution windows.

Prohibited Anti-Pattern: Permissive or Asynchronous Userspace Binary Verification Prone to Execution TOCTOU and Inode Spoofing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec - Enforces synchronous cryptographic integrity verification of executable binaries inside the kernel before container process execution. BPF-LSM hooks on bprm_creds_for_exec must query kernel IMA digests via bpf_ima_inode_hash or bpf_ima_file_hash and reject unmeasured or untrusted binaries with -EPERM to eliminate TOCTOU execution windows.
globs: **/*.bpf.c, **/*.bpf.h, pkg/security/**/*.go, src/security/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-lsm-binary-integrity-bprm-verification"
---

# Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive or Asynchronous Userspace Binary Verification Prone to Execution TOCTOU and Inode Spoofing

## System Constraints
You are a Principal Linux Security and Kernel Engineer enforcing eBPF BPF-LSM container binary integrity verification. Mandate deterministic, fail-closed kernel-level measurement via bprm_creds_for_exec, forbidding userspace-deferred exec checks, unvalidated IMA hashes, or permissive fallbacks on helper failures.

## Strict Guidelines
- Engineers MUST ALWAYS attach binary execution enforcement to the `bprm_creds_for_exec` LSM hook to ensure access control is evaluated at the exact point credential transitions occur.
- Engineers MUST ALWAYS verify cryptographic digests using `bpf_ima_file_hash()` or `bpf_ima_inode_hash()` against an immutable or authenticated kernel eBPF hash-map before granting execution clearance.
- Engineers MUST NOT allow execution if `bpf_ima_file_hash()` returns negative error codes, zero bytes, or an unmatched digest when the binary originates within a monitored container cgroup.
- Services MUST ensure that the BPF-LSM program returns `-EPERM` (operation not permitted) synchronously to terminate execution inside `do_execveat_common` prior to binary loading.
- Components NEVER execute userspace roundtrips via perf buffers or ring buffers to make binary execution authorization decisions, as this introduces exploitable TOCTOU race windows.

## Bad vs Good Implementations
### Kernel Binary Verification with BPF-LSM and IMA

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: bprm_check_security executes before finalized credentials and namespace resolution. Returning 0 while deferring hash evaluation to userspace introduces a critical Time-of-Check to Time-of-Use (TOCTOU) vulnerability where malicious payloads execute before userspace can intervene.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

SEC("lsm/bprm_check_security")
int BPF_PROG(restrict_exec, struct linux_binprm *bprm)
{
    // Flaw 1: bprm_check_security is evaluated before credential calculations are finalized.
    // Flaw 2: Emitting an event to userspace daemon for async verification allows
    // the binary to execute before the userspace verdict is returned (TOCTOU).
    struct task_struct *task = (struct task_struct *)bpf_get_current_task();
    __u32 pid = bpf_get_current_pid_tgid() >> 32;

    // Blindly allow execution while notifying userspace asynchronously
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Attaches to bprm_creds_for_exec, leverages the in-kernel bpf_ima_file_hash helper to retrieve the verified cryptographic measurement, and synchronously enforces map lookup with a strict fail-closed (-EPERM) policy.
```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 {
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, __u8[SHA256_DIGEST_LEN]);
    __type(value, __u32);
    __uint(max_entries, 65536);
} allowed_binaries SEC(".maps");

SEC("lsm/bprm_creds_for_exec")
int BPF_PROG(enforce_binary_integrity, struct linux_binprm *bprm)
{
    __u8 hash[SHA256_DIGEST_LEN];
    long ret;

    if (!bprm || !bprm->file)
        return -EPERM;

    // Extract IMA file digest directly from the kernel filesystem cache
    ret = bpf_ima_file_hash(bprm->file, hash, sizeof(hash));
    if (ret < 0) {
        // Fail closed: Reject binary if unmeasured, unhashed, or unsupported
        return -EPERM;
    }

    __u32 *policy = bpf_map_lookup_elem(&allowed_binaries, hash);
    if (!policy || *policy != 1) {
        // Binary digest not present in kernel whitelist
        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: Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec

Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec defines an industrial-grade behavioral standard for security engineering. Enforces synchronous cryptographic integrity verification of executable binaries inside the kernel before container process execution. BPF-LSM hooks on bprm_creds_for_exec must query kernel IMA digests via bpf_ima_inode_hash or bpf_ima_file_hash and reject unmeasured or untrusted binaries with -EPERM to eliminate TOCTOU execution windows. 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: Permissive or Asynchronous Userspace Binary Verification Prone to Execution TOCTOU and Inode Spoofing 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 DriftPermissive or Asynchronous Userspace Binary Verification Prone to Execution TOCTOU and Inode SpoofingCritical
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 execution enforcement to the `bprm_creds_for_exec` LSM hook to ensure access control is evaluated at the exact point credential transitions occur.

Engineers MUST ALWAYS attach binary execution enforcement to the `bprm_creds_for_exec` LSM hook to ensure access control is evaluated at the exact point credential transitions occur.

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 verify cryptographic digests using `bpf_ima_file_hash()` or `bpf_ima_inode_hash()` against an immutable or authenticated kernel eBPF hash-map before granting execution clearance.

Engineers MUST ALWAYS verify cryptographic digests using `bpf_ima_file_hash()` or `bpf_ima_inode_hash()` against an immutable or authenticated kernel eBPF hash-map before granting execution clearance.

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 execution if `bpf_ima_file_hash()` returns negative error codes, zero bytes, or an unmatched digest when the binary originates within a monitored container cgroup.

Engineers MUST NOT allow execution if `bpf_ima_file_hash()` returns negative error codes, zero bytes, or an unmatched digest when the binary originates within a monitored container cgroup.

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

Services MUST ensure that the BPF-LSM program returns `-EPERM` (operation not permitted) synchronously to terminate execution inside `do_execveat_common` prior to binary loading.

Services MUST ensure that the BPF-LSM program returns `-EPERM` (operation not permitted) synchronously to terminate execution inside `do_execveat_common` prior to binary loading.

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

Components NEVER execute userspace roundtrips via perf buffers or ring buffers to make binary execution authorization decisions, as this introduces exploitable TOCTOU race windows.

Components NEVER execute userspace roundtrips via perf buffers or ring buffers to make binary execution authorization decisions, as this introduces exploitable TOCTOU race windows.

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 Mandatory In-Kernel Binary Digest Verification via BPF-LSM bprm_creds_for_exec critical for AI coding assistants?

Enforces synchronous cryptographic integrity verification of executable binaries inside the kernel before container process execution. BPF-LSM hooks on bprm_creds_for_exec must query kernel IMA digests via bpf_ima_inode_hash or bpf_ima_file_hash and reject unmeasured or untrusted binaries with -EPERM to eliminate TOCTOU execution windows. 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 (Permissive or Asynchronous Userspace Binary Verification Prone to Execution TOCTOU and Inode Spoofing) 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

Mandatory