This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-tc-socket-microsegmentation-guardrail

eBPF TC Socket Microsegmentation and Kernel-Level Identity Injection

Enforces non-bypassable kernel-level microsegmentation by attaching eBPF Traffic Control (TC) classifiers to container veth interfaces for sidecarless identity tagging and mTLS validation. Eliminates user-space bypass vectors and iptables race conditions by performing tenant SPIFFE ID verification directly within skb execution paths.

Prohibited Anti-Pattern: Relying on user-space sidecar redirects or mutable iptables rules for microsegmentation and tenant identity attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF TC Socket Microsegmentation and Kernel-Level Identity Injection - Enforces non-bypassable kernel-level microsegmentation by attaching eBPF Traffic Control (TC) classifiers to container veth interfaces for sidecarless identity tagging and mTLS validation. Eliminates user-space bypass vectors and iptables race conditions by performing tenant SPIFFE ID verification directly within skb execution paths.
globs: src/**/*.{ts,tsx,go,c,h}, pkg/ebpf/**/*.{go,c,h}, daemon/network/**/*.{ts,go}, bpf/**/*.bpf.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-tc-socket-microsegmentation-guardrail"
---

# eBPF TC Socket Microsegmentation and Kernel-Level Identity Injection

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on user-space sidecar redirects or mutable iptables rules for microsegmentation and tenant identity attestation

## System Constraints
You are a Principal Software Architect enforcing zero-trust eBPF microsegmentation. Mandate direct-action Traffic Control (TC) filters attached to container veth pairs for cryptographic tenant identity injection and boundary validation. Forbid user-space redirect loopholes, ensure atomic BPF map identity synchronization, and mandate immediate packet drop on identity mismatch.

## Strict Guidelines
- Engineers MUST ALWAYS attach eBPF TC filters (BPF_PROG_TYPE_SCHED_CLS) in direct-action mode (da) to both ingress and egress qdiscs (clsact) of container virtual interfaces.
- Engineers MUST NOT rely on userspace proxies, loopback redirection, or iptables PREROUTING chains for tenant security boundaries, as raw sockets (AF_PACKET) and root host-net containers can bypass them.
- Control planes MUST populate tenant SPIFFE IDs and CIDR authorization rules into pinned BPF_MAP_TYPE_LPM_TRIE or BPF_MAP_TYPE_HASH maps using atomic batch operations.
- eBPF packet parsers MUST verify all pointer arithmetic against skb->data_end before header access to satisfy the kernel verifier and prevent out-of-bounds memory dereferencing.
- Services MUST drop packets immediately with TC_ACT_SHOT whenever tenant identity headers are absent, malformed, or unauthenticated, and emit audit telemetry via BPF_MAP_TYPE_RINGBUF.
- Components NEVER allow unencapsulated egress traffic to traverse outside the trusted node boundary without applying cryptographic SPIFFE identity injection into the packet options.

## Bad vs Good Implementations
### Enforcing Kernel-Level eBPF TC Filter Management and Boundary Invariants

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring network microsegmentation via iptables REDIRECT into a user-space proxy allows bypass via raw sockets (AF_PACKET), imposes significant context-switch overhead, and fails to guarantee atomic, non-bypassable identity injection at the Linux kernel boundary.
```typescript
import { execSync } from 'child_process';

interface VethAttachment {
  interfaceName: string;
  tenantId: string;
}

// ANTI-PATTERN: Relying on userspace iptables redirect and mutable sidecar proxies.
// Privileged containers with CAP_NET_RAW or host network access easily bypass iptables.
export class InsecureNetworkManager {
  public attachMicrosegmentation(config: VethAttachment): void {
    // Insecure: iptables PREROUTING can be bypassed by AF_PACKET raw sockets
    execSync(`iptables -t nat -A PREROUTING -i ${config.interfaceName} -p tcp -j REDIRECT --to-ports 15001`);
    
    // Insecure: Identity is managed in user-space proxy memory, susceptible to proxy crash/bypass
    console.log(`Routed interface ${config.interfaceName} to proxy for tenant ${config.tenantId}`);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Attaches direct-action eBPF classifiers to the clsact qdisc on both ingress and egress paths of the container interface. This ensures identity injection and validation occur deterministically in kernel space before any user-space processing, neutralizing raw socket bypass vectors.
```typescript
import { execSync } from 'child_process';
import { readFileSync, existsSync } from 'fs';

interface VethSecurityPolicy {
  interfaceName: string;
  tenantSpiffeIdHash: bigint;
  bpfObjPath: string;
  mapPinPath: string;
}

// PRODUCTION STANDARD: Kernel-enforced eBPF TC filters attached to clsact qdisc.
// Guarantees non-bypassable, sidecarless identity tagging and packet drops before user-space boundary.
export class EbpfTcMicrosegmentationController {
  public attachKernelGuardrail(policy: VethSecurityPolicy): void {
    if (!existsSync(policy.bpfObjPath)) {
      throw new Error(`eBPF object bytecode missing at path: ${policy.bpfObjPath}`);
    }

    // 1. Ensure clsact qdisc is attached to the target veth interface
    try {
      execSync(`tc qdisc add dev ${policy.interfaceName} clsact`, { stdio: 'pipe' });
    } catch (error: unknown) {
      // clsact may already exist; continue if existing, fail on other errors
      const msg = error instanceof Error ? error.message : String(error);
      if (!msg.includes('File exists')) {
        throw new Error(`Failed to initialize clsact qdisc on ${policy.interfaceName}: ${msg}`);
      }
    }

    // 2. Attach TC classifier to egress for identity tagging (direct action mode)
    execSync(
      `tc filter replace dev ${policy.interfaceName} egress bpf da obj ${policy.bpfObjPath} sec tc_egress_identity`,
      { stdio: 'inherit' }
    );

    // 3. Attach TC classifier to ingress for boundary verification and drop (TC_ACT_SHOT)
    execSync(
      `tc filter replace dev ${policy.interfaceName} ingress bpf da obj ${policy.bpfObjPath} sec tc_ingress_verify`,
      { stdio: 'inherit' }
    );
  }
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF TC Socket Microsegmentation and Kernel-Level Identity Injection

eBPF TC Socket Microsegmentation and Kernel-Level Identity Injection defines an industrial-grade behavioral standard for security engineering. Enforces non-bypassable kernel-level microsegmentation by attaching eBPF Traffic Control (TC) classifiers to container veth interfaces for sidecarless identity tagging and mTLS validation. Eliminates user-space bypass vectors and iptables race conditions by performing tenant SPIFFE ID verification directly within skb execution paths. 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 user-space sidecar redirects or mutable iptables rules for microsegmentation and tenant identity attestation 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 user-space sidecar redirects or mutable iptables rules for microsegmentation and tenant identity attestationCritical
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 eBPF TC filters (BPF_PROG_TYPE_SCHED_CLS) in direct-action mode (da) to both ingress and egress qdiscs (clsact) of container virtual interfaces.

Engineers MUST ALWAYS attach eBPF TC filters (BPF_PROG_TYPE_SCHED_CLS) in direct-action mode (da) to both ingress and egress qdiscs (clsact) of container virtual interfaces.

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 rely on userspace proxies, loopback redirection, or iptables PREROUTING chains for tenant security boundaries, as raw sockets (AF_PACKET) and root host-net containers can bypass them.

Engineers MUST NOT rely on userspace proxies, loopback redirection, or iptables PREROUTING chains for tenant security boundaries, as raw sockets (AF_PACKET) and root host-net containers can bypass them.

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

Control planes MUST populate tenant SPIFFE IDs and CIDR authorization rules into pinned BPF_MAP_TYPE_LPM_TRIE or BPF_MAP_TYPE_HASH maps using atomic batch operations.

Control planes MUST populate tenant SPIFFE IDs and CIDR authorization rules into pinned BPF_MAP_TYPE_LPM_TRIE or BPF_MAP_TYPE_HASH maps using atomic batch operations.

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

eBPF packet parsers MUST verify all pointer arithmetic against skb->data_end before header access to satisfy the kernel verifier and prevent out-of-bounds memory dereferencing.

eBPF packet parsers MUST verify all pointer arithmetic against skb->data_end before header access to satisfy the kernel verifier and prevent out-of-bounds memory dereferencing.

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 drop packets immediately with TC_ACT_SHOT whenever tenant identity headers are absent, malformed, or unauthenticated, and emit audit telemetry via BPF_MAP_TYPE_RINGBUF.

Services MUST drop packets immediately with TC_ACT_SHOT whenever tenant identity headers are absent, malformed, or unauthenticated, and emit audit telemetry via BPF_MAP_TYPE_RINGBUF.

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

Components NEVER allow unencapsulated egress traffic to traverse outside the trusted node boundary without applying cryptographic SPIFFE identity injection into the packet options.

Components NEVER allow unencapsulated egress traffic to traverse outside the trusted node boundary without applying cryptographic SPIFFE identity injection into the packet options.

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 TC Socket Microsegmentation and Kernel-Level Identity Injection critical for AI coding assistants?

Enforces non-bypassable kernel-level microsegmentation by attaching eBPF Traffic Control (TC) classifiers to container veth interfaces for sidecarless identity tagging and mTLS validation. Eliminates user-space bypass vectors and iptables race conditions by performing tenant SPIFFE ID verification directly within skb execution paths. 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 user-space sidecar redirects or mutable iptables rules for microsegmentation and tenant identity attestation) 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