Tool Sandboxing
Isolate code execution and network tools so agents cannot escape their boundaries.
In plain words
A sandbox is a sealed room where the AI's code can run and make a mess without being able to touch your real computers or secrets.
Think of it like…
A laboratory fume hood or a glovebox: dangerous experiments happen inside a sealed, ventilated enclosure with limited supplies and no connection to the rest of the building, and whatever goes in is thrown away after the experiment.
Where you’ve seen it
A data-analysis agent runs model-generated Python for each user request. The first version used the app server's Python process with its environment variables (including a database URL and an API key). A prompt-injected CSV caused the model to write code that printed os.environ. The redesign: each run starts a fresh microVM from a read-only image (about 125 ms to boot, versus 300 ms for a plain container) with 2 vCPUs, 512 MB of memory, a 64-process limit, a 10-second wall-clock timeout, a 10 MB output cap and a 100 MB tmpfs scratch directory; no environment secrets are injected; the filesystem outside scratch is read-only; DNS and network are off except an allowlisted internal package mirror; and the link-local cloud metadata address (169.254.169.254) is blocked. Uploaded files are copied in, results are copied out and the VM is destroyed. Red-team tests (environment dumps, fork bombs, metadata requests, port scans, a 5 GB memory allocation, writing outside scratch) all fail or are killed within limits, and the incident log shows 14 blocked egress attempts in the first month.
Words you’ll hear
- Sandbox
- An isolated environment that confines code and tools.
- MicroVM / gVisor
- Stronger isolation: a lightweight VM or a user-space kernel instead of a shared host kernel.
- Default-deny egress
- No network access except explicitly allowlisted destinations.
- Ephemeral execution
- A fresh environment per run that is destroyed afterwards.
Visual diagram
Theory & deep dive
Isolation options and threat model
Ask what you're defending against. Model-written code might: read secrets from environment variables or files; reach internal services (SSRF) and the cloud metadata endpoint (169.254.169.254) to steal instance credentials; exfiltrate data over HTTP or DNS; consume resources (fork bombs, memory and CPU exhaustion, mining); persist or escape to the host through kernel vulnerabilities; and attack other tenants sharing the machine. The isolation spectrum: process-level restrictions (seccomp, rlimits) are weak alone; containers (namespaces and cgroups) share the host kernel, so a kernel bug can lead to escape; gVisor intercepts syscalls in a user-space kernel, shrinking the attack surface at some performance cost; microVMs (Firecracker, Kata, Cloud Hypervisor) give each run its own kernel and a hardware-virtualisation boundary with fast boot (on the order of 100 to 300 ms); WebAssembly runtimes provide capability-based isolation for languages that compile to Wasm; managed services (cloud sandboxes, code-interpreter APIs) outsource the operations.
A practical rule: untrusted or LLM-generated code from the open internet needs a VM-grade or equivalent boundary; internal, reviewed scripts can run in hardened containers. Defence in depth still applies inside the boundary: run as a non-root user, drop Linux capabilities, apply a seccomp profile, mount the root filesystem read-only, provide a small tmpfs scratch space, disable host mounts and device access, and keep the sandbox in its own network namespace.
2 vCPUs, 512 MB memory, 64 processes, 10 s wall time, 10 MB stdout, 100 MB scratch. A fork bomb hits the process cap, a memory hog is OOM-killed at 512 MB and an infinite loop is terminated at 10 s, all without affecting the host.
Network, secrets, data flow and operations
Network: default-deny egress. If the code needs packages, allow only an internal mirror or pre-baked images; if it needs the web, route through a proxy with a domain allowlist, request size limits and logging. Block private IP ranges, link-local addresses and the metadata service, and restrict DNS to prevent tunnelling. Secrets: don't inject credentials into the sandbox. If an action needs authentication (read a file from storage), let the orchestrator perform it and pass in only the resulting data, or issue a very short-lived, narrowly scoped token. Data flow: copy input files in, copy outputs out through a validated channel with size and type checks and treat outputs as untrusted (they may contain injected instructions or malware); never mount host directories.
Operate it like production: ephemeral sandboxes (destroy after each run or session; if you reuse them for stateful notebooks, bound the lifetime and isolate per user), warm pools to hide boot latency, per-user quotas and concurrency limits, audit logs of code, resource usage and denied actions, alerts on repeated limit hits or blocked egress, and regular patching of the base image and hypervisor. Test with an adversarial suite (environment dumps, metadata requests, port scans, fork bombs, large allocations, writes outside scratch, symlink and path tricks, attempts to reach other sandboxes) and track that every case is contained. Accept the trade-offs: stronger isolation costs startup time and money, and some tasks (GPU access, large datasets) need careful design rather than weakening the boundary.
Allowed: pypi-mirror.internal:443. Everything else, including 169.254.169.254, 10.0.0.0/8, 192.168.0.0/16 and external DNS, is dropped. In month one the logs show 14 blocked attempts, each reviewed: 11 from a user's script that tried to download a dataset and 3 that probed the metadata address.
How it works, step by step
Step 1 of 41. Define the threat model
Decide who writes the code (model, user, third party) and what must be protected (secrets, network, other tenants).
- Match
- isolation to threat
When to use it & trade-offs
What it is
Tool sandboxing runs code and risky tools (a Python interpreter, shell, browser, file operations, network fetchers) inside an isolated, resource-limited environment so that even malicious or buggy model-generated code cannot reach your systems, secrets or other users' data. A sandbox combines isolation (containers with namespaces, cgroups and seccomp; user-space kernels such as gVisor; microVMs such as Firecracker; WebAssembly), no ambient credentials, a default-deny network policy with egress allowlists, a read-only filesystem with a scratch area, hard limits on CPU, memory, processes, time and output size, and ephemeral lifetimes (a fresh sandbox per run or session).
Why it matters: Code interpreters and browsing tools are among the most powerful and most dangerous agent capabilities. Model-written code can be wrong, and with prompt injection it can be hostile: it may try to read environment variables, scan the internal network, call the cloud metadata service, exfiltrate files or mine cryptocurrency. Shared-kernel containers are not a strong security boundary on their own, so the choice of isolation level should match the threat: executing untrusted code from the internet deserves a stronger boundary than running your own scripts.
When to reach for it
- Code interpreters and data-analysis agents
- Browser automation and file-processing tools
- Any tool executing model- or user-supplied code
When to avoid or be careful
- Running model code in the application process
- Injecting cloud or database credentials into the sandbox
- Allowing unrestricted outbound network access
Isolation options
Strengths: Fast, cheap, familiar.
Watch out: Shared host kernel; weaker against hostile code.
Strengths: Reduced kernel attack surface.
Watch out: Some syscall incompatibilities and overhead.
Strengths: Own kernel and hardware boundary; fast boot.
Watch out: More operational complexity; cost per VM.
Interview signals & numbers to know
When this topic comes up
- “The agent can run code”
- Container escape
- Cloud metadata SSRF
- Firecracker and gVisor
- Egress allowlist
Benchmarks & rules of thumb
- 125 ms vs 300 ms
- illustrative microVM versus container boot time
- 169.254.169.254
- cloud metadata address to block
- 2 vCPU · 512 MB · 64 pids · 10 s
- example hard limits per run
Common mistakes & follow-ups
Common interview mistakes
- Trusting a plain container to contain hostile code from the internet.
- Mounting host directories into the sandbox for convenience.
- Forgetting to cap output size and process count.
Likely interviewer follow-ups
- How would you safely run LLM-generated Python?
- Why is the cloud metadata endpoint dangerous?
- What's the difference between a container and a microVM for isolation?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Tool Sandboxing with generative AI interview Q&A and hands-on practice.