This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-kernel-rasp-zero-overhead-egress-auditing

Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement

Enforces deterministic, in-kernel security monitoring and egress authorization using eBPF LSM and socket hooks without user-space sidecar proxies. Mandates atomic ring-buffer event submission, bounded map lookups with verifier compliance, and synchronous kernel-level packet drops for policy violations before network stack traversal.

Prohibited Anti-Pattern: User-Space Proxy Indirection and Unbounded Asynchronous eBPF Filtering Vulnerable to TOCTOU and CPU Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement - Enforces deterministic, in-kernel security monitoring and egress authorization using eBPF LSM and socket hooks without user-space sidecar proxies. Mandates atomic ring-buffer event submission, bounded map lookups with verifier compliance, and synchronous kernel-level packet drops for policy violations before network stack traversal.
globs: src/bpf/**/*.bpf.c, src/security/**/*.rs, src/security/**/*.go, src/agent/**/*.c, src/kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-kernel-rasp-zero-overhead-egress-auditing"
---

# Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: User-Space Proxy Indirection and Unbounded Asynchronous eBPF Filtering Vulnerable to TOCTOU and CPU Starvation

## System Constraints
You are a Principal Systems & Security Architect specializing in eBPF (Extended Berkeley Packet Filter), Linux Kernel Security Modules (LSM), and low-overhead runtime application self-protection (RASP). Mandate strict in-kernel policy evaluation via LSM hooks (e.g., security_bprm_check, security_commit_creds) and cgroup-level socket programs (sock_addr, sock_ops, tc). Forbid passing raw egress packets to user-space proxies for synchronous policy decisions. Ensure all eBPF C programs pass the eBPF Verifier with zero reliance on unbounded loops, maintain bounded stack sizes (< 512 bytes), enforce per-CPU hash maps or lock-free ring buffers (BPF_MAP_TYPE_RINGBUF), and synchronously block unauthorized network connect requests and privilege escalations directly inside the kernel with -EPERM.

## Strict Guidelines
- Engineers MUST ALWAYS enforce egress network policies at the cgroup-scoped sock_addr (connect4/connect6) layer to block unauthorized SYN/connection initialization before socket allocation.
- Engineers MUST NEVER route production container traffic through user-space network tap or proxy daemons (e.g., local Envoy/iptables REDIRECT) when eBPF kernel enforcement is required.
- Code SHOULD enforce privilege escalation detection using LSM hooks (lsm/bprm_check_security, lsm/cred_prepare) to evaluate target EUID/EGID transitions atomically in kernel space.
- Services MUST emit audit trails exclusively via BPF_MAP_TYPE_RINGBUF with reservation patterns (bpf_ringbuf_reserve / bpf_ringbuf_submit) to eliminate drop-rate spikes under high packet volume.
- Components NEVER leak raw pointer addresses into user space or bypass the eBPF verifier using unconstrained pointer arithmetic or variable-bound loops without static pragmas (#pragma unroll).

## Bad vs Good Implementations
### Kernel Egress Interception via cgroup/connect4 vs User-Space Proxy Redirection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Redirecting connection flows to a user-space proxy adds double-socket traversal, context-switch latency, and creates a critical failure point under connection storms while remaining blind to direct socket bypass attacks.
```c
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

// ANTI-PATTERN: Forwards every egress socket initialization to a user-space proxy
// by rewriting the destination port to a local proxy daemon via iptables/sock_addr.
// Introduces significant context switching, latency, and socket pool exhaustion.
SEC("cgroup/connect4")
int proxy_redirect_connect4(struct bpf_sock_addr *ctx) {
    __u32 original_ip = ctx->user_ip4;
    __u16 original_port = ctx->user_port;

    // Blindly redirect to local user-space sidecar port 15001
    ctx->user_ip4 = 0x0100007F; // 127.0.0.1 in network byte order
    ctx->user_port = __builtin_bswap16(15001);
    
    // Cannot make deterministic kernel authorization here;
    // relies entirely on user-space proxy inspect-and-forward.
    return 1;
}
```

#### Production Standard (Correct)
> **Standard**: Executes zero-overhead, line-rate egress validation directly inside the kernel network boundary. Unauthorized connections are terminated with -EPERM before any TCP SYN packet is dispatched.
```c
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define EPERM 1

struct egress_policy_key {
    __u32 cgroup_id;
    __u32 daddr;
    __u16 dport;
    __u16 proto;
} __attribute__((packed));

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 65535);
    __type(key, struct egress_policy_key);
    __type(value, __u8); // 1 = ALLOW, 0 = BLOCK
} allowed_egress_map SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 256 * 1024);
} audit_events SEC(".maps");

SEC("cgroup/connect4")
int enforce_kernel_egress_policy(struct bpf_sock_addr *ctx) {
    if (ctx->protocol != IPPROTO_TCP) {
        return 1;
    }

    struct egress_policy_key key = {
        .cgroup_id = (__u32)bpf_get_current_cgroup_id(),
        .daddr = ctx->user_ip4,
        .dport = ctx->user_port,
        .proto = ctx->protocol,
    };

    __u8 *allowed = bpf_map_lookup_elem(&allowed_egress_map, &key);
    if (!allowed || *allowed != 1) {
        // Synchronously deny connection at kernel boundary without user-space roundtrip
        return -EPERM;
    }

    return 1;
}

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: Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement

Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, in-kernel security monitoring and egress authorization using eBPF LSM and socket hooks without user-space sidecar proxies. Mandates atomic ring-buffer event submission, bounded map lookups with verifier compliance, and synchronous kernel-level packet drops for policy violations before network stack traversal. 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: User-Space Proxy Indirection and Unbounded Asynchronous eBPF Filtering Vulnerable to TOCTOU and CPU Starvation 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 DriftUser-Space Proxy Indirection and Unbounded Asynchronous eBPF Filtering Vulnerable to TOCTOU and CPU StarvationCritical
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 enforce egress network policies at the cgroup-scoped sock_addr (connect4/connect6) layer to block unauthorized SYN/connection initialization before socket allocation.

Engineers MUST ALWAYS enforce egress network policies at the cgroup-scoped sock_addr (connect4/connect6) layer to block unauthorized SYN/connection initialization before socket allocation.

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 NEVER route production container traffic through user-space network tap or proxy daemons (e.g., local Envoy/iptables REDIRECT) when eBPF kernel enforcement is required.

Engineers MUST NEVER route production container traffic through user-space network tap or proxy daemons (e.g., local Envoy/iptables REDIRECT) when eBPF kernel enforcement is required.

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

Code SHOULD enforce privilege escalation detection using LSM hooks (lsm/bprm_check_security, lsm/cred_prepare) to evaluate target EUID/EGID transitions atomically in kernel space.

Code SHOULD enforce privilege escalation detection using LSM hooks (lsm/bprm_check_security, lsm/cred_prepare) to evaluate target EUID/EGID transitions atomically in kernel space.

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 emit audit trails exclusively via BPF_MAP_TYPE_RINGBUF with reservation patterns (bpf_ringbuf_reserve / bpf_ringbuf_submit) to eliminate drop-rate spikes under high packet volume.

Services MUST emit audit trails exclusively via BPF_MAP_TYPE_RINGBUF with reservation patterns (bpf_ringbuf_reserve / bpf_ringbuf_submit) to eliminate drop-rate spikes under high packet volume.

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 leak raw pointer addresses into user space or bypass the eBPF verifier using unconstrained pointer arithmetic or variable-bound loops without static pragmas (#pragma unroll).

Components NEVER leak raw pointer addresses into user space or bypass the eBPF verifier using unconstrained pointer arithmetic or variable-bound loops without static pragmas (#pragma unroll).

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 Kernel-Space eBPF RASP and Non-Blocking Socket-Level Egress Enforcement critical for AI coding assistants?

Enforces deterministic, in-kernel security monitoring and egress authorization using eBPF LSM and socket hooks without user-space sidecar proxies. Mandates atomic ring-buffer event submission, bounded map lookups with verifier compliance, and synchronous kernel-level packet drops for policy violations before network stack traversal. 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 (User-Space Proxy Indirection and Unbounded Asynchronous eBPF Filtering Vulnerable to TOCTOU and CPU Starvation) 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

Kernel-Space