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

eBPF TC Egress Microsegmentation Fencing for Ephemeral Sandboxes

Autonomous code execution sandboxes must be strictly fenced at the kernel Traffic Control (TC) egress layer using eBPF programs attached to their virtual network interfaces prior to process initiation. Egress traffic must default to TC_ACT_SHOT with dynamic CIDR and L4 port allowlists enforced via atomic BPF LPM trie lookups to prevent network boundary escape and out-of-band lateral data exfiltration.

Prohibited Anti-Pattern: Asynchronous Userspace Filtering or Missing Kernel-Level TC Egress Barrier Before Process Launch

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF TC Egress Microsegmentation Fencing for Ephemeral Sandboxes - Autonomous code execution sandboxes must be strictly fenced at the kernel Traffic Control (TC) egress layer using eBPF programs attached to their virtual network interfaces prior to process initiation. Egress traffic must default to TC_ACT_SHOT with dynamic CIDR and L4 port allowlists enforced via atomic BPF LPM trie lookups to prevent network boundary escape and out-of-band lateral data exfiltration.
globs: src/sandbox/**/*.{ts,js,go,rs}, src/network/**/*.{ts,js,go,rs}, src/orchestration/**/*.{ts,js,go,rs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-tc-egress-microsegmentation-fencing"
---

# eBPF TC Egress Microsegmentation Fencing for Ephemeral Sandboxes

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Asynchronous Userspace Filtering or Missing Kernel-Level TC Egress Barrier Before Process Launch

## System Constraints
You are a Principal Security Architect enforcing kernel-level eBPF Traffic Control (TC) egress microsegmentation for sandboxed autonomous workloads. All ephemeral network namespaces must be constrained at the TC egress hook before any untrusted instructions execute. Refuse any implementation that relies exclusively on userspace forward proxies, asynchronous iptables/nftables provisioning, or post-exec firewall configuration that leaves a race-condition window open for lateral exfiltration.

## Strict Guidelines
- Engineers MUST ALWAYS attach the eBPF TC egress program directly to the host-side veth/netkit interface in direct-action mode before triggering untrusted code execution.
- Engineers MUST configure BPF maps with an explicit default-deny posture (TC_ACT_SHOT) returning dropped status for any non-allowlisted destination IP, port, or transport protocol.
- Engineers MUST NOT rely on userspace HTTP/SOCKS proxies or asynchronous firewalls (e.g., background iptables commands) to restrict network access for arbitrary code sandboxes.
- Services MUST synchronously populate LPM (Longest Prefix Match) trie maps with authorized destination CIDRs and L4 ports before unblocking the sandbox process runtime.
- Components NEVER start sandbox worker processes on a shared network namespace without dedicated, isolated TC egress qdiscs and pinned BPF maps.
- Code SHOULD include connection tracking state or TCP flag validation inside the eBPF program to prevent ACK/RST injection and out-of-order packet tunneling.

## Bad vs Good Implementations
### Synchronous eBPF TC Filter Attachment & Dynamic LPM Trie Initialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching the sandbox process prior to egress policy enforcement creates a critical race condition where untrusted code can perform immediate UDP/DNS or raw TCP exfiltration. Relying on deferred iptables or userspace string-matching fails to reliably isolate raw packet egress at the kernel boundary.
```typescript
import { spawn } from 'node:child_process';
import { execSync } from 'node:child_process';

export async function runUntrustedJob(jobId: string, script: string, allowedHost: string) {
  // Flaw 1: Container launched before network isolation is established (race window)
  const container = spawn('docker', ['run', '-d', '--name', jobId, 'node:20-slim', 'node', '-e', script]);

  // Flaw 2: Asynchronous userspace proxy / post-hoc iptables rule
  // Untrusted code can exfiltrate secrets during the 200-500ms setup window
  setTimeout(() => {
    execSync(`iptables -A OUTPUT -m string --string "${allowedHost}" --algo bm -j ACCEPT`);
    execSync('iptables -A OUTPUT -j DROP');
  }, 200);

  return container.pid;
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees zero-window execution safety by programmatically binding the eBPF TC filter in direct-action mode and populating the LPM allowlist map before the untrusted process binary is spawned into the network namespace.
```typescript
import { createNetworkNamespace, attachEbpfTcFilter, updateLpmTrieAllowlist, startSandboxedProcess } from './kernel-networking';

export interface EgressRule {
  destinationCidr: string;
  port: number;
  protocol: 'TCP' | 'UDP';
}

export async function runUntrustedJob(
  jobId: string,
  scriptPath: string,
  egressRules: EgressRule[]
): Promise<number> {
  // Step 1: Pre-create isolated netns and veth interface pair
  const netns = await createNetworkNamespace(`sandbox-${jobId}`);
  const hostVeth = `veth_${jobId.slice(0, 8)}`;

  try {
    // Step 2: Attach eBPF classifier at TC egress hook in direct-action mode
    // Invariant: Default action inside BPF bytecode is TC_ACT_SHOT (Drop)
    const tcHandle = await attachEbpfTcFilter({
      interfaceName: hostVeth,
      direction: 'egress',
      bpfProgramPath: '/opt/ebpf/tc_egress_fencing.o',
      section: 'classifier/egress'
    });

    // Step 3: Synchronously populate eBPF LPM trie allowlist map BEFORE execution
    for (const rule of egressRules) {
      await updateLpmTrieAllowlist(tcHandle.mapFd, rule);
    }

    // Step 4: Launch untrusted process inside the fully-fenced namespace
    const pid = await startSandboxedProcess({
      namespace: netns,
      binary: 'node',
      args: [scriptPath],
      enableNetworking: true
    });

    return pid;
  } catch (err) {
    await netns.destroy();
    throw new Error(`Failed to initialize secure sandbox fencing: ${(err as Error).message}`);
  }
}
```

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 TC Egress Microsegmentation Fencing for Ephemeral Sandboxes

eBPF TC Egress Microsegmentation Fencing for Ephemeral Sandboxes defines an industrial-grade behavioral standard for security engineering. Autonomous code execution sandboxes must be strictly fenced at the kernel Traffic Control (TC) egress layer using eBPF programs attached to their virtual network interfaces prior to process initiation. Egress traffic must default to TC_ACT_SHOT with dynamic CIDR and L4 port allowlists enforced via atomic BPF LPM trie lookups to prevent network boundary escape and out-of-band lateral data exfiltration. 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: Asynchronous Userspace Filtering or Missing Kernel-Level TC Egress Barrier Before Process Launch 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 DriftAsynchronous Userspace Filtering or Missing Kernel-Level TC Egress Barrier Before Process LaunchCritical
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 the eBPF TC egress program directly to the host-side veth/netkit interface in direct-action mode before triggering untrusted code execution.

Engineers MUST ALWAYS attach the eBPF TC egress program directly to the host-side veth/netkit interface in direct-action mode before triggering untrusted code execution.

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 configure BPF maps with an explicit default-deny posture (TC_ACT_SHOT) returning dropped status for any non-allowlisted destination IP, port, or transport protocol.

Engineers MUST configure BPF maps with an explicit default-deny posture (TC_ACT_SHOT) returning dropped status for any non-allowlisted destination IP, port, or transport protocol.

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 rely on userspace HTTP/SOCKS proxies or asynchronous firewalls (e.g., background iptables commands) to restrict network access for arbitrary code sandboxes.

Engineers MUST NOT rely on userspace HTTP/SOCKS proxies or asynchronous firewalls (e.g., background iptables commands) to restrict network access for arbitrary code sandboxes.

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 synchronously populate LPM (Longest Prefix Match) trie maps with authorized destination CIDRs and L4 ports before unblocking the sandbox process runtime.

Services MUST synchronously populate LPM (Longest Prefix Match) trie maps with authorized destination CIDRs and L4 ports before unblocking the sandbox process runtime.

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 start sandbox worker processes on a shared network namespace without dedicated, isolated TC egress qdiscs and pinned BPF maps.

Components NEVER start sandbox worker processes on a shared network namespace without dedicated, isolated TC egress qdiscs and pinned BPF maps.

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

Code SHOULD include connection tracking state or TCP flag validation inside the eBPF program to prevent ACK/RST injection and out-of-order packet tunneling.

Code SHOULD include connection tracking state or TCP flag validation inside the eBPF program to prevent ACK/RST injection and out-of-order packet tunneling.

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 Egress Microsegmentation Fencing for Ephemeral Sandboxes critical for AI coding assistants?

Autonomous code execution sandboxes must be strictly fenced at the kernel Traffic Control (TC) egress layer using eBPF programs attached to their virtual network interfaces prior to process initiation. Egress traffic must default to TC_ACT_SHOT with dynamic CIDR and L4 port allowlists enforced via atomic BPF LPM trie lookups to prevent network boundary escape and out-of-band lateral data exfiltration. 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 (Asynchronous Userspace Filtering or Missing Kernel-Level TC Egress Barrier Before Process Launch) 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