Cycle's hosted MCP is live. Your AI tooling just learned DevOps.Read the announcement

AI Sandboxes: Running AI Agents in Isolated Environments.

An AI sandbox is an isolated environment where an AI agent, or code an LLM generated, runs with only the access it needs. When the model makes a mistake, follows prompt-injected instructions or writes malicious code, the damage stays inside the sandbox, and the host, its credentials and the rest of the network stay a trusted environment.

Agents don't stop at text. They write code and run it, install packages, call tools and browse the web, often with nobody reading each step first. This page covers why that calls for an AI agent sandbox, what an AI sandbox has to control, the quarantined agent pattern, how the isolation options compare, and a hands-on example that runs untrusted Python in a locked-down Docker container on Ubuntu 24.04.

Why AI agents need a sandbox

Everything an agent produces is untrusted output. A model can write a cleanup command against the wrong directory, install a typosquatted package or loop forever, with no bad intent anywhere. The code runs because the agent decided to run it.

Prompt injection adds a second problem: someone else can steer the agent. OWASP's entry on prompt injection says "indirect prompt injections occur when an LLM accepts input from external sources, such as websites or files", and that "it is unclear if there are fool-proof methods of prevention." An agent that reads a poisoned issue or web page can be told to read ~/.ssh and post it somewhere. You can't filter every such instruction out, so you limit what the agent can reach when one gets through.

What an AI sandbox must control

Each row below is a separate way out of the sandbox, and each one needs its own control. Locking down the filesystem does nothing for network egress.

Control

Default for an agent sandbox

Filesystem

Read-only root, task inputs mounted read-only, one small scratch area and one output directory

Network egress

None. When a task needs a package index or an API, traffic goes through an allow list

Credentials and secrets

No host environment variables, SSH keys, cloud credentials or container runtime socket

CPU, memory and time

Caps on CPU, memory and process count, plus a wall-clock limit enforced from outside

Syscalls and privileges

Non-root user, no capabilities, no privilege escalation, a seccomp filter

Persistence between runs

Nothing carries over unless you copy it out on purpose

Containers build these from Linux namespaces, cgroups and seccomp, and VMs add a separate kernel. Container defaults are set for trusted apps, so an agent sandbox needs the stricter settings shown in the hands-on section.

The quarantined agent pattern

Treat the agent as a quarantined agent and its output as quarantined code. The agent runs in the sandbox with no standing privileges. A trusted component outside the sandbox holds the secrets, decides which tool calls to make on the agent's behalf and keeps the logs.

Anything the agent produces lands in quarantine first: files, patches, query results, generated scripts. OWASP's guidance on output handling is to "treat the model as any other user, adopting a zero-trust approach." In practice, that means:

  • Accept outputs only through one channel, such as a single output directory or structured stdout, with a size cap set by the host.
  • Accept regular files only. A symlink in the output that points at a host path can trick the host into reading or overwriting the wrong file.
  • Validate content before another system uses it, and require human review for anything with real impact, such as a merged patch or a production change.
  • Never execute output on the host. If it needs to run, it runs in another sandbox.

AI sandbox isolation options compared

The options differ mostly on one question: does the quarantined code share the host's kernel? A container does. gVisor's README spells out what that means: "container escape is possible with a single vulnerability." gVisor, microVMs and full VMs each put another boundary between the code and the host kernel.

Option

Isolation strength

Startup time

Overhead

Process limits (seccomp, cgroups, systemd sandboxing, nsjail)

Lowest: one process on the shared kernel, limited by filters

A process start

Negligible

Hardened container

Medium: namespaces, cgroups, seccomp and dropped capabilities on the shared kernel

No guest kernel to boot

Small

gVisor

High: a user-space application kernel handles the workload's system calls

No guest kernel to boot. gVisor's start-up benchmark attributes most of the time to Docker itself

Higher cost per system call, a small mostly fixed memory cost per sandbox, no added cost for plain CPU work (gVisor docs)

MicroVM (Firecracker, Cloud Hypervisor, Kata Containers)

High: a separate guest kernel behind KVM with a minimal device model

Firecracker's specification: 125 ms or less from the start call to the guest's init

Firecracker's specification: 5 MiB or less of VMM memory for a 1 vCPU, 128 MiB guest

Full VM

High: a separate guest kernel, with a larger emulated device model

Slowest: a full firmware and OS boot

Highest: a full guest OS per sandbox

Only the gVisor and Firecracker entries come from project docs, and the rest are relative. Firecracker measures its boot time on bare-metal hosts with a minimal guest kernel and root filesystem, so your own workload may not reach either figure.

Docker's default seccomp profile blocks around 44 of 300+ system calls, according to Docker's docs, and the flags in the hands-on section close the other easy paths. That's enough for your own agent's tool scripts and other code you mostly trust. See container hardening for the full list.

For code from a model that reads untrusted input, use gVisor or a microVM. gVisor's runsc runtime works with Docker and Kubernetes, and its docs list the cost as "reduced application compatibility and higher per-system call overhead." MicroVMs give each sandbox its own kernel behind a hypervisor. Kata Containers runs containers inside lightweight VMs that, in its README's words, "feel and perform like containers." An LLM sandbox that serves many users should never put two tenants on one shared kernel.

Ephemeral vs persistent sandboxes

An ephemeral sandbox exists for one task. It starts from a known image, runs, hands back its result and is destroyed, so nothing a compromised run plants survives.

A persistent sandbox keeps state between steps: installed packages, a cloned repo, a running dev server. Coding agents that work through a task over many turns often need one. The cost is drift, because every step can leave something behind, including whatever a prompt injection planted three steps ago.

The usual middle ground is one sandbox per session, not per command. Cap its lifetime, destroy it when the task ends and never reuse it across users or tenants. If the agent needs a warm start, bake the dependencies into a clean image instead of keeping an old sandbox alive.

Egress control and allow lists

Start every sandbox with no network. When a task needs one, allow destinations by name instead of blocking known-bad ones. A deny list misses every domain nobody thought to add.

The common pattern puts the sandbox on an internal-only network whose one way out is a forward proxy. The proxy checks each request's hostname against the allow list, such as your package mirror and one API, and logs every request. DNS can carry data out too, so resolve names at the proxy and don't give the sandbox an open resolver.

An allow list also caps the damage from prompt injection. A tricked agent can only send data to hosts you approved.

Keep secrets out of the sandbox

Assume anything inside the sandbox will be read by the code inside it. Don't put long-lived credentials there: no cloud keys, no SSH keys, no personal access tokens, no host environment passed through.

When a tool needs an API key, keep the key in the trusted environment. The agent asks the orchestrator to make the call, and the orchestrator checks the request, adds the credential and returns only the result. If code inside the sandbox must authenticate itself, issue a short-lived token scoped to that one task.

Two leaks are easy to miss. Cloud instances get their role or service account credentials from a metadata service at the link-local address 169.254.169.254, so block that address from every sandbox. And never mount the Docker socket into a sandbox. Docker's docs state that the docker group "grants root-level privileges", and a mounted socket gives the same access.

Observability and audit logs

Log enough to reconstruct what the agent did and why. That means the task or prompt, the model and version, every tool call with its arguments, the exact code that ran, its exit status, duration and resource peaks, every request through the egress proxy, and every file that left quarantine.

Keep the logs in the trusted environment. A quarantined agent that can write to its own audit trail can erase it. Alert on denied egress, OOM kills and timeouts, because a well-behaved task rarely produces any of them.

Exit status alone isn't enough. A task can catch its own failures and exit cleanly, so pull the runtime's events too. The hands-on example below shows an OOM kill that only the event log records.

Run untrusted Python in a locked-down container

This example runs model-generated Python in a hardened, throwaway Docker container, tested on Ubuntu 24.04 with the docker.io package from the Ubuntu archive. A container still shares the host kernel, so use this pattern for code you mostly trust, and move to gVisor or microVMs for code from untrusted input.

Install Docker and pull the image. The sandbox gets no network, so it can't fetch anything later:

sudo apt install docker.io
sudo docker pull python:3.12-slim

Create a task directory and save this as task/agent_code.py. It stands in for hostile model output and tries each thing the sandbox should stop:

import os
import socket
import subprocess
import time
import urllib.request
def attempt(label, action):
try:
action()
print(f"{label:<17} allowed")
except Exception as exc:
print(f"{label:<17} blocked: {exc}")
def reach_pypi():
urllib.request.urlopen("https://pypi.org/simple/", timeout=5)
def connect_by_ip():
socket.create_connection(("198.51.100.10", 443), timeout=5)
def write_usr_local():
with open("/usr/local/bin/helper", "w") as f:
f.write("#!/bin/sh\n")
def write_tmp():
with open("/tmp/scratch.txt", "w") as f:
f.write("scratch\n")
def exec_from_tmp():
with open("/tmp/payload.sh", "w") as f:
f.write("#!/bin/sh\necho ran\n")
os.chmod("/tmp/payload.sh", 0o755)
subprocess.run(["/tmp/payload.sh"], check=True)
def fork_500():
children = []
try:
for _ in range(500):
pid = os.fork()
if pid == 0:
time.sleep(1)
os._exit(0)
children.append(pid)
finally:
for pid in children:
os.waitpid(pid, 0)
def allocate_512mb():
child = subprocess.run(["python3", "-c", "b = b'x' * (512 * 1024 * 1024)"])
if child.returncode != 0:
raise RuntimeError(f"child exited with {child.returncode}")
def write_out():
with open("/out/result.json", "w") as f:
f.write('{"answer": 42}\n')
with open("/proc/self/status") as status:
for line in status:
if line.startswith(("Uid:", "CapEff:", "NoNewPrivs:", "Seccomp:")):
print(line.strip())
attempt("reach pypi.org", reach_pypi)
attempt("connect by IP", connect_by_ip)
attempt("write /usr/local", write_usr_local)
attempt("write /tmp", write_tmp)
attempt("exec from /tmp", exec_from_tmp)
attempt("fork 500", fork_500)
attempt("allocate 512 MB", allocate_512mb)
attempt("write /out", write_out)

Save the runner as run-sandboxed.sh. It starts one container per task, kills it after 30 seconds, prints its output, removes it and accepts only regular files in the quarantine directory:

#!/bin/bash
# Usage: sudo ./run-sandboxed.sh <task-dir> <script.py>
set -u
task_dir=$(realpath "$1")
script=$2
name="sandbox-$$"
work=$(mktemp -d)
mkdir -m 0777 "$work/out"
docker run --detach --name "$name" \
--network none \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
--cap-drop ALL \
--security-opt no-new-privileges \
--pids-limit 64 \
--memory 256m --memory-swap 256m \
--cpus 1 \
--user 65534:65534 \
-v "$task_dir:/task:ro" \
-v "$work/out:/out" \
python:3.12-slim python3 "/task/$script" > /dev/null
status=$(timeout 30s docker wait "$name")
if [ -z "$status" ]; then
echo "time limit reached, killing $name" >&2
docker kill "$name" > /dev/null
status=$(docker wait "$name")
fi
docker logs "$name"
docker rm "$name" > /dev/null
unexpected=$(find "$work/out" -mindepth 1 ! -type f)
if [ -n "$unexpected" ]; then
echo "rejected, not a regular file: $unexpected" >&2
exit 1
fi
echo "exit status $status, quarantined output in $work/out" >&2

Run it:

chmod +x run-sandboxed.sh
sudo ./run-sandboxed.sh task agent_code.py
Uid: 65534 65534 65534 65534
CapEff: 0000000000000000
NoNewPrivs: 1
Seccomp: 2
reach pypi.org blocked: <urlopen error [Errno -3] Temporary failure in name resolution>
connect by IP blocked: [Errno 101] Network is unreachable
write /usr/local blocked: [Errno 30] Read-only file system: '/usr/local/bin/helper'
write /tmp allowed
exec from /tmp blocked: [Errno 13] Permission denied: '/tmp/payload.sh'
fork 500 blocked: [Errno 11] Resource temporarily unavailable
allocate 512 MB blocked: child exited with -9
write /out allowed
exit status 0, quarantined output in /tmp/tmp.IZpdEOVvez/out

The code runs as nobody with no capabilities, no_new_privs set and a seccomp filter active. It can't resolve or reach anything on the network. It can't write outside /tmp and /out, it can't run what it drops in /tmp, and the kernel stops it at 64 processes and 256 MiB of memory. Its one result sits in the quarantine directory, waiting for review.

Flag

What it does

--network none

Gives the container a loopback interface and nothing else

--read-only

Mounts the root filesystem read-only, so nothing can replace a library or persist

--tmpfs /tmp:rw,noexec,nosuid,size=64m

Adds 64 MiB of in-memory scratch space where files can't be executed directly

--cap-drop ALL

Drops every Linux capability

--security-opt no-new-privileges

Stops setuid binaries and file capabilities from raising privileges

--pids-limit 64

Caps the process count, which stops fork bombs

--memory 256m --memory-swap 256m

Caps memory with no swap, and the kernel kills the process that crosses it

--cpus 1

Limits the container to one CPU's worth of time

--user 65534:65534

Runs the code as nobody instead of root

-v "$task_dir:/task:ro"

Shares the task files read-only

timeout 30s docker wait

Kills the container from outside when the wall-clock limit runs out

noexec stops a dropped file from being executed directly, but an interpreter can still read it. python3 /tmp/x.py works, which is why the other limits matter.

Test the time limit with code that never ends:

printf 'while True:\n pass\n' > task/spin.py
sudo ./run-sandboxed.sh task spin.py
time limit reached, killing sandbox-739
exit status 137, quarantined output in /tmp/tmp.nG2CNs0Phm/out

Exit status 137 means the process was killed with SIGKILL. The runner removed the container, so nothing is left running.

Docker's event log keeps a record of both runs:

sudo docker events --since 1h --until 0s --filter event=oom --filter event=die \
--format '{{.Action}} {{.Actor.Attributes.name}}{{with .Actor.Attributes.exitCode}} exit={{.}}{{end}}'
oom sandbox-558
die sandbox-558 exit=0
die sandbox-739 exit=137

The first run exited 0, because the probe caught its own failures, but the event log shows the OOM kill inside it. Ship these events to the audit log next to the task ID.

Podman accepts the same flags. To use it, replace docker with podman in the runner.

Running AI sandboxes in production

One Docker host and a runner script cover a team's internal agent. Past that, the work moves to the fleet. Images get pinned by digest and pre-pulled so sandboxes start without waiting, hosts need capacity for the sum of the limits you hand out, and a reconciler removes sandboxes a crashed runner left behind.

Agents that run code for different customers need more. Code from different customers belongs in separate gVisor sandboxes or microVMs, never in neighboring containers on one kernel, and the egress proxy, secret broker and audit logs live outside every sandbox.

Expect the model to run something it shouldn't at some point. With these controls in place, that run fails inside the sandbox and shows up in your logs.

Cookies

Cookies Preferences

We run basic, anonymous analytics by default to measure site traffic. By clicking "Accept," you allow additional cookies for advanced app improvements and tailored advertising. Choose what you share by clicking "Customize."