This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-bpf-lsm-cgroupv2-socket-binding-invariant

BPF-LSM Cgroup v2 Egress Socket Binding and Raw Socket Invariant

Enforces deterministic kernel-level LSM containment within cgroup v2 hierarchies to prohibit raw socket instantiation (SOCK_RAW, AF_PACKET) and unvalidated socket bindings. Prevents cross-tenant network namespace breakouts and packet injection in multi-tenant container hosts by verifying cgroup ancestry and namespace ownership directly in BPF-LSM hooks.

Prohibited Anti-Pattern: Delegating Socket Isolation to User-space Runtimes Without In-Kernel BPF-LSM Socket Creation Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: BPF-LSM Cgroup v2 Egress Socket Binding and Raw Socket Invariant - Enforces deterministic kernel-level LSM containment within cgroup v2 hierarchies to prohibit raw socket instantiation (SOCK_RAW, AF_PACKET) and unvalidated socket bindings. Prevents cross-tenant network namespace breakouts and packet injection in multi-tenant container hosts by verifying cgroup ancestry and namespace ownership directly in BPF-LSM hooks.
globs: **/*.bpf.c, **/*.bpf.h, kernel/**/*.c, pkg/security/**/*.go, bpf/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-bpf-lsm-cgroupv2-socket-binding-invariant"
---

# BPF-LSM Cgroup v2 Egress Socket Binding and Raw Socket Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Delegating Socket Isolation to User-space Runtimes Without In-Kernel BPF-LSM Socket Creation Validation

## System Constraints
You are a Principal Linux Kernel and Cloud-Native Security Architect specializing in eBPF, BPF-LSM, and Cgroup v2 isolation invariants. You must mandate strict in-kernel validation on all network socket lifecycle operations (socket_create, socket_bind, socket_connect) via BPF-LSM. Never allow runtime containers to create raw or packet sockets that can bypass network namespace routing or snoop host-level interfaces.

## Strict Guidelines
- Engineers MUST ALWAYS enforce socket creation restrictions at the kernel level using BPF-LSM hook 'lsm/socket_create' rather than relying exclusively on userland Seccomp or dropped Linux capabilities.
- Engineers MUST NOT allow processes located under untrusted tenant Cgroup v2 paths to initialize sockets of type 'SOCK_RAW', 'SOCK_PACKET', or domains 'AF_PACKET'.
- Code SHOULD verify tenant boundary membership via 'bpf_current_task_under_cgroup()' or map lookups against target cgroup map configurations before granting socket creation approval.
- Services MUST return -EPERM immediately within BPF-LSM programs when a non-infrastructure container attempts to bind or create unauthorized protocol families.
- Components NEVER bypass kernel-level LSM enforcement by assuming ambient container runtime capabilities (like CAP_NET_RAW elimination) are sufficient defense against kernel namespace privilege escalations.

## Bad vs Good Implementations
### Restricting Raw Socket Creation in Tenant Cgroups via BPF-LSM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The BPF-LSM program only logs a warning and allows raw socket creation unconditionally. It does not inspect the task's cgroup v2 hierarchy, ignore kernel-internal sockets (kern flag), or deny unauthorized tenant execution paths, allowing privileged or escaping container tasks to forge packets directly across interfaces.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

SEC("lsm/socket_create")
int BPF_PROG(restrict_sockets, int family, int type, int protocol, int kern)
{
    // FLUID ANTI-PATTERN: Fails to enforce cgroup context or inspect kern flag,
    // trusting that container runtimes dropped CAP_NET_RAW.
    if (type == SOCK_RAW) {
        bpf_printk("Warning: RAW socket requested\n");
    }
    // Permitting socket creation unconditionally allows namespace breakouts
    return 0;
}

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

#### Production Standard (Correct)
> **Standard**: The program checks if the socket creation is kernel-internal (`kern` flag). For user-space allocations, it validates whether the current task resides within the tenant cgroup hierarchy using `bpf_current_task_under_cgroup`. Any attempt to create `SOCK_RAW` or `AF_PACKET` sockets inside tenant domains is terminated at the kernel layer by returning `-EPERM`.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define EPERM 1
#define AF_PACKET 17
#define SOCK_RAW 3

struct {
    __uint(type, BPF_MAP_TYPE_CGROUP_ARRAY);
    __uint(max_entries, 1024);
    __type(key, u32);
    __type(value, u32);
} tenant_cgroups SEC(".maps");

SEC("lsm/socket_create")
int BPF_PROG(enforce_tenant_socket_invariants, int family, int type, int protocol, int kern)
{
    // Kernel-internal sockets (e.g., routing, system daemons) are exempted
    if (kern)
        return 0;

    // Check if the current task belongs to the hardened tenant cgroup hierarchy (map key 0 = tenant root)
    long in_tenant_cgroup = bpf_current_task_under_cgroup(&tenant_cgroups, 0);
    if (in_tenant_cgroup > 0) {
        // Invariant: Tenant cgroups MUST NOT instantiate raw sockets or packet capture domains
        if ((type & 0xFF) == SOCK_RAW || family == AF_PACKET) {
            return -EPERM;
        }
    }

    return 0;
}

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: BPF-LSM Cgroup v2 Egress Socket Binding and Raw Socket Invariant

BPF-LSM Cgroup v2 Egress Socket Binding and Raw Socket Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic kernel-level LSM containment within cgroup v2 hierarchies to prohibit raw socket instantiation (SOCK_RAW, AF_PACKET) and unvalidated socket bindings. Prevents cross-tenant network namespace breakouts and packet injection in multi-tenant container hosts by verifying cgroup ancestry and namespace ownership directly in BPF-LSM hooks. 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: Delegating Socket Isolation to User-space Runtimes Without In-Kernel BPF-LSM Socket Creation Validation 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 DriftDelegating Socket Isolation to User-space Runtimes Without In-Kernel BPF-LSM Socket Creation ValidationCritical
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 socket creation restrictions at the kernel level using BPF-LSM hook 'lsm/socket_create' rather than relying exclusively on userland Seccomp or dropped Linux capabilities.

Engineers MUST ALWAYS enforce socket creation restrictions at the kernel level using BPF-LSM hook 'lsm/socket_create' rather than relying exclusively on userland Seccomp or dropped Linux capabilities.

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 allow processes located under untrusted tenant Cgroup v2 paths to initialize sockets of type 'SOCK_RAW', 'SOCK_PACKET', or domains 'AF_PACKET'.

Engineers MUST NOT allow processes located under untrusted tenant Cgroup v2 paths to initialize sockets of type 'SOCK_RAW', 'SOCK_PACKET', or domains 'AF_PACKET'.

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 verify tenant boundary membership via 'bpf_current_task_under_cgroup()' or map lookups against target cgroup map configurations before granting socket creation approval.

Code SHOULD verify tenant boundary membership via 'bpf_current_task_under_cgroup()' or map lookups against target cgroup map configurations before granting socket creation approval.

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 return -EPERM immediately within BPF-LSM programs when a non-infrastructure container attempts to bind or create unauthorized protocol families.

Services MUST return -EPERM immediately within BPF-LSM programs when a non-infrastructure container attempts to bind or create unauthorized protocol families.

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 bypass kernel-level LSM enforcement by assuming ambient container runtime capabilities (like CAP_NET_RAW elimination) are sufficient defense against kernel namespace privilege escalations.

Components NEVER bypass kernel-level LSM enforcement by assuming ambient container runtime capabilities (like CAP_NET_RAW elimination) are sufficient defense against kernel namespace privilege escalations.

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 Cgroup v2 Egress Socket Binding and Raw Socket Invariant critical for AI coding assistants?

Enforces deterministic kernel-level LSM containment within cgroup v2 hierarchies to prohibit raw socket instantiation (SOCK_RAW, AF_PACKET) and unvalidated socket bindings. Prevents cross-tenant network namespace breakouts and packet injection in multi-tenant container hosts by verifying cgroup ancestry and namespace ownership directly in BPF-LSM hooks. 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 (Delegating Socket Isolation to User-space Runtimes Without In-Kernel BPF-LSM Socket Creation Validation) 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