This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-cgroup-sock-create-egress-evasion-defense

eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense

Enforces deterministic socket interception at the BPF_CGROUP_INET_SOCK_CREATE attach point to prevent multi-tenant container workloads from allocating raw sockets or unauthorized protocols. Halts evasion techniques that bypass host-level CNI iptables/tc filtering and network namespace egress policies. Ensures strict fail-closed verification and security telemetry emission upon policy violation.

Prohibited Anti-Pattern: Permitting Unrestricted SOCK_RAW Allocation and Uninspected Socket Protocols in Cgroups

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense - Enforces deterministic socket interception at the BPF_CGROUP_INET_SOCK_CREATE attach point to prevent multi-tenant container workloads from allocating raw sockets or unauthorized protocols. Halts evasion techniques that bypass host-level CNI iptables/tc filtering and network namespace egress policies. Ensures strict fail-closed verification and security telemetry emission upon policy violation.
globs: bpf/**/*.bpf.c, src/bpf/**/*.c, pkg/ebpf/**/*.go, kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-cgroup-sock-create-egress-evasion-defense"
---

# eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permitting Unrestricted SOCK_RAW Allocation and Uninspected Socket Protocols in Cgroups

## System Constraints
You are a Principal Software Architect specializing in Linux kernel security and eBPF network isolation. Your mission is to enforce the eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense invariant. Multi-tenant containers must never be allowed to manufacture SOCK_RAW or arbitrary IP-protocol sockets to bypass host CNI policy enforcement and tenant segmentation. Reject fail-open constructs, enforce strict protocol allowlists, audit via BPF ring buffers, and ensure immediate socket rejection (EPERM) on unauthorized allocations.

## Strict Guidelines
- Engineers MUST ALWAYS attach to BPF_CGROUP_INET_SOCK_CREATE with fail-closed semantics, returning 0 (EPERM) whenever validation checks fail or security maps are unresolvable.
- Engineers MUST explicitly verify sk->type against an authorized socket allowlist (e.g., SOCK_STREAM, SOCK_DGRAM) and unconditionally block SOCK_RAW unless the target cgroup is explicitly present in an administrative exemption BPF hash map.
- Engineers MUST NOT evaluate socket parameters using unverified memory offsets; all reads from struct bpf_sock must use direct context access guarded by the BPF verifier or bpf_probe_read_kernel where required.
- Code MUST submit a structured security violation event via bpf_ringbuf_output containing cgroup_id, pid_tgid, uid_gid, socket type, and requested protocol prior to denying socket creation.
- Services MUST NEVER assume container seccomp profiles prevent SOCK_RAW creation if containers can retain or regain CAP_NET_RAW or run under misconfigured multi-tenant privileged boundaries.

## Bad vs Good Implementations
### eBPF CGroup Socket Create Interception

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This program fails open and fails to inspect sk->type. An unprivileged or compromised container with CAP_NET_RAW can create SOCK_RAW sockets and inject arbitrary egress packets directly into the virtual ethernet interface, bypassing higher-level CNI network policies and conntrack state tracking.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/in.h>

SEC("cgroup/sock_create")
int sock_create_permissive(struct bpf_sock *sk) {
    // ANTI-PATTERN: Blindly trusting socket creation or failing open
    // Allowing SOCK_RAW lets compromised pods craft raw IP headers,
    // spoof source IPs, or circumvent tc-based CNI egress firewalls.
    if (sk->family != AF_INET && sk->family != AF_INET6) {
        return 1; // Allows non-IP or raw packet sockets without auditing
    }

    // Omits socket type check: SOCK_RAW, SOCK_PACKET pass directly through
    return 1;
}
```

#### Production Standard (Correct)
> **Standard**: The hardened eBPF program inspects sk->type at socket allocation. Only standard STREAM/DGRAM sockets are allowed by default. Any attempt to create a SOCK_RAW socket by an unauthorized cgroup triggers a ring buffer audit event and immediately fails closed with return 0 (EPERM), thwarting network policy bypass attempts.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/in.h>

#define SOCK_STREAM 1
#define SOCK_DGRAM  2
#define SOCK_RAW    3

struct audit_event {
    __u64 cgroup_id;
    __u32 pid;
    __u32 uid;
    __u32 socket_type;
    __u32 protocol;
};

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 1 << 24);
} audit_events SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, __u64);
    __type(value, __u8);
} raw_sock_allowed_cgroups SEC(".maps");

SEC("cgroup/sock_create")
int sock_create_defense(struct bpf_sock *sk) {
    if (!sk)
        return 0; // Fail-closed on null context

    // Enforce protocol validation for IPv4 and IPv6
    if (sk->family == AF_INET || sk->family == AF_INET6) {
        // Permit standard TCP and UDP allocations unconditionally
        if (sk->type == SOCK_STREAM || sk->type == SOCK_DGRAM) {
            return 1;
        }

        // Intercept SOCK_RAW attempts
        if (sk->type == SOCK_RAW) {
            __u64 cgroup_id = bpf_get_current_cgroup_id();
            __u8 *allowed = bpf_map_lookup_elem(&raw_sock_allowed_cgroups, &cgroup_id);
            if (allowed && *allowed == 1) {
                return 1; // Explicitly authorized privileged cgroup
            }

            // Reserve ring buffer slot for security audit
            struct audit_event *event = bpf_ringbuf_reserve(&audit_events, sizeof(*event), 0);
            if (event) {
                event->cgroup_id = cgroup_id;
                event->pid = bpf_get_current_pid_tgid() >> 32;
                event->uid = bpf_get_current_uid_gid();
                event->socket_type = sk->type;
                event->protocol = sk->protocol;
                bpf_ringbuf_submit(event, 0);
            }

            // 0 equates to -EPERM returned to user space sys_socket
            return 0;
        }
    }

    // Block unrecognized socket types by default
    return 0;
}

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: eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense

eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense defines an industrial-grade behavioral standard for security engineering. Enforces deterministic socket interception at the BPF_CGROUP_INET_SOCK_CREATE attach point to prevent multi-tenant container workloads from allocating raw sockets or unauthorized protocols. Halts evasion techniques that bypass host-level CNI iptables/tc filtering and network namespace egress policies. Ensures strict fail-closed verification and security telemetry emission upon policy violation. 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: Permitting Unrestricted SOCK_RAW Allocation and Uninspected Socket Protocols in Cgroups 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 DriftPermitting Unrestricted SOCK_RAW Allocation and Uninspected Socket Protocols in CgroupsCritical
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 to BPF_CGROUP_INET_SOCK_CREATE with fail-closed semantics, returning 0 (EPERM) whenever validation checks fail or security maps are unresolvable.

Engineers MUST ALWAYS attach to BPF_CGROUP_INET_SOCK_CREATE with fail-closed semantics, returning 0 (EPERM) whenever validation checks fail or security maps are unresolvable.

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 explicitly verify sk->type against an authorized socket allowlist (e.g., SOCK_STREAM, SOCK_DGRAM) and unconditionally block SOCK_RAW unless the target cgroup is explicitly present in an administrative exemption BPF hash map.

Engineers MUST explicitly verify sk->type against an authorized socket allowlist (e.g., SOCK_STREAM, SOCK_DGRAM) and unconditionally block SOCK_RAW unless the target cgroup is explicitly present in an administrative exemption BPF hash 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.
3

Engineers MUST NOT evaluate socket parameters using unverified memory offsets

Engineers MUST NOT evaluate socket parameters using unverified memory offsets; all reads from struct bpf_sock must use direct context access guarded by the BPF verifier or bpf_probe_read_kernel where 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.
4

Code MUST submit a structured security violation event via bpf_ringbuf_output containing cgroup_id, pid_tgid, uid_gid, socket type, and requested protocol prior to denying socket creation.

Code MUST submit a structured security violation event via bpf_ringbuf_output containing cgroup_id, pid_tgid, uid_gid, socket type, and requested protocol prior to denying socket creation.

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

Services MUST NEVER assume container seccomp profiles prevent SOCK_RAW creation if containers can retain or regain CAP_NET_RAW or run under misconfigured multi-tenant privileged boundaries.

Services MUST NEVER assume container seccomp profiles prevent SOCK_RAW creation if containers can retain or regain CAP_NET_RAW or run under misconfigured multi-tenant privileged boundaries.

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 eBPF BPF_CGROUP_INET_SOCK_CREATE Egress Pod Evasion Defense critical for AI coding assistants?

Enforces deterministic socket interception at the BPF_CGROUP_INET_SOCK_CREATE attach point to prevent multi-tenant container workloads from allocating raw sockets or unauthorized protocols. Halts evasion techniques that bypass host-level CNI iptables/tc filtering and network namespace egress policies. Ensures strict fail-closed verification and security telemetry emission upon policy violation. 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 (Permitting Unrestricted SOCK_RAW Allocation and Uninspected Socket Protocols in Cgroups) 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

eBPF