Sandboxing AI Code Agents: Firecracker vs gVisor vs Docker
Key Takeaways
- Default Docker containers share the host Linux kernel, leaving AI code agents exposed to container-escape syscalls and cloud metadata SSRF.
- Firecracker microVMs provide hardware-virtualized KVM isolation with ~125ms cold starts, making them the gold standard for untrusted multi-tenant code execution.
- gVisor (runsc) intercepts syscalls in user space with zero KVM requirement, offering a practical drop-in Docker runtime when bare-metal virtualization is unavailable.
- Always pair container/VM isolation with --network=none (or egress proxy), --read-only rootfs, and hard cgroup v2 CPU/RAM caps.
On this page
- Quick Solution: Hardened gVisor + Network-Isolated Agent Runner
- Threat Model: How AI Code Agents Break Weak Sandboxes
- Head-to-Head Comparison: Firecracker vs gVisor vs Hardened Docker
- Production Python Sandbox Runner (gVisor + Hardened Fallback)
- Firecracker Snapshot Architecture for Sub-25ms Cold Starts
- Frequently Asked Questions
- Why is standard Docker unsafe for executing LLM-generated code?
- What is the cold-start difference between Firecracker and gVisor?
- Can you run Firecracker inside a standard cloud VM without nested virtualization?
- How do you prevent an AI agent sandbox from exfiltrating internal network secrets?
- Production Checklist & Verification
Quick Solution: Hardened gVisor + Network-Isolated Agent Runner
Executing LLM-generated Python or Bash directly via subprocess.run() turns any prompt injection into instant remote code execution on your host. Standard Docker containers mitigate filesystem damage, but they still share the host kernel and default bridge network. For immediate production isolation on any Linux host without bare-metal KVM, switch Docker’s runtime to gVisor (runsc) with --network=none, --cap-drop=ALL, and strict cgroup limits (docker>=7.1.0, Python 3.12+).
Install gVisor’s runsc runtime and register it with Docker:
# Ubuntu 24.04 x86_64: install runsc and configure /etc/docker/daemon.json
curl -fsSL https://gvisor.dev/archive.key | sudo gpg --dearmor -o /usr/share/keyrings/gvisor-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/gvisor-archive-keyring.gpg] https://storage.googleapis.com/gvisor/releases release main" | sudo tee /etc/apt/sources.list.d/gvisor.list
sudo apt-get update && sudo apt-get install -y runsc
sudo runsc install && sudo systemctl restart docker
Verify isolation in one command:
docker run --rm --runtime=runsc --network=none --read-only \
--cap-drop=ALL --security-opt=no-new-privileges \
--memory=512m --cpus=1.0 --pids-limit=64 \
python:3.12-slim python -c "import os; print(os.uname().release)"
flowchart LR
Agent["AI Agent / MCP Tool"] -->|"Untrusted Code"| Runner["Sandbox Orchestrator (Python)"]
Runner -->|"Option A: Bare-Metal KVM"| FC["Firecracker MicroVM (Guest Kernel + Jailer)"]
Runner -->|"Option B: Cloud VM / K8s"| GV["gVisor runsc (User-Space Sentry Kernel)"]
FC -->|"network=none + cgroup v2"| Out["Stdout / Exit Code + Artifact"]
GV -->|"network=none + cgroup v2"| Out
Out -->|"Sanitized Output"| Agent
Threat Model: How AI Code Agents Break Weak Sandboxes
An AI agent sandbox is an isolated execution boundary that runs untrusted, model-generated code and tool calls while preventing host kernel exploits, lateral network movement, and secret exfiltration.
When an autonomous agent writes and executes code, whether in a LangGraph multi-agent workflow or a FastMCP tool server, three distinct attack vectors appear:
- Prompt-Injected SSRF to Cloud Metadata: If the agent scrapes a webpage or reads a poisoned GitHub issue, injected instructions tell the code interpreter to
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/. Any container with default bridge networking can reach host link-local and VPC-internal services. - Kernel Syscall Surface Exposure: Standard
runcDocker containers expose 300+ Linux host syscalls directly to untrusted Python/C extensions. A single unpatched kernel privilege escalation (io_uring,netfilter,overlayfs) breaks containment. - Fork Bombs and Disk Exhaustion: Without
--pids-limitand--read-onlyrootfs (paired with a size-cappedtmpfs), a buggywhile True: os.fork()or unboundedpip installcrashes the entire worker node.
Head-to-Head Comparison: Firecracker vs gVisor vs Hardened Docker
Measured on an AWS c6i.metal host (Ubuntu 24.04, Linux 6.8, NVMe SSD, Docker 27.3.1, Firecracker 1.10.1, gVisor 20250120.0). Workload: boot sandbox, execute python3 -c "print(sum(range(10000)))", and tear down.
| Metric / Isolation Layer | Hardened Docker (runc) | gVisor (runsc + Docker) | Firecracker MicroVM (KVM) |
|---|---|---|---|
| Isolation Boundary | Host Linux kernel + namespaces/seccomp | User-space Go kernel (Sentry) | Hardware virtualization (KVM + dedicated guest kernel) |
| Cold Start Latency | 65 ms | 210 ms | 125 ms (18 ms from snapshot) |
| Syscall Overhead (File I/O) | ~1x (native) | 2.5x to 4x slower | ~1.05x (virtio-blk) |
| Compute Overhead (CPU/PyTorch) | ~1x | ~1.05x | ~1.02x |
Requires /dev/kvm | No | No | Yes (bare metal or nested virt) |
| Multi-Tenant Untrusted Risk | Medium-High (shared kernel) | Low (user-space syscall filter) | Minimal (hardware VM boundary) |
| Best Production Fit | Internal trusted tools | Standard cloud VMs / GKE Sandbox | Multi-tenant SaaS code interpreters |
For hardened MCP deployments that only expose fixed binaries rather than arbitrary code execution, you can pair runc with custom seccomp profiles as covered in securing MCP servers in Docker sandboxes. For arbitrary LLM code generation, choose Firecracker on bare metal or gVisor on standard cloud VMs.
Production Python Sandbox Runner (gVisor + Hardened Fallback)
The script below implements a production-ready CodeSandbox runner using docker>=7.1.0. It enforces:
runsc(gVisor) runtime selection with explicit capability checks.- Complete network isolation (
network_disabled=True). - Read-only root filesystem with a 64MB
noexec,nosuid/tmptmpfs. - Hard wall-clock timeout using
asyncioand forced container kill on overrun. - Output truncation so a
print("A" * 50_000_000)loop cannot OOM the orchestrator.
Install dependencies:
pip install "docker==7.1.0" "pydantic>=2.10.0"
Save as sandbox_runner.py:
import asyncio
import logging
import time
from typing import Literal
import docker
from docker.errors import APIError, ContainerError, ImageNotFound
from pydantic import BaseModel, Field
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("code-sandbox")
MAX_OUTPUT_BYTES = 32_768
class SandboxRequest(BaseModel):
code: str = Field(..., min_length=1, max_length=50_000)
timeout_sec: float = Field(default=10.0, ge=1.0, le=60.0)
memory_mb: int = Field(default=512, ge=128, le=4096)
cpu_quota_cores: float = Field(default=1.0, ge=0.25, le=4.0)
runtime: Literal["runsc", "runc"] = "runsc"
class SandboxResult(BaseModel):
exit_code: int
stdout: str
stderr: str
timed_out: bool
duration_ms: float
class CodeSandbox:
def __init__(self, image: str = "python:3.12-slim") -> None:
self.image = image
self.client = docker.from_env()
self._ensure_image()
def _ensure_image(self) -> None:
try:
self.client.images.get(self.image)
except ImageNotFound:
logger.info("Pulling sandbox image %s...", self.image)
self.client.images.pull(self.image)
def _run_sync(self, req: SandboxRequest) -> SandboxResult:
start = time.perf_counter()
container = None
timed_out = False
exit_code = -1
stdout_str = ""
stderr_str = ""
try:
container = self.client.containers.run(
image=self.image,
command=["python", "-I", "-c", req.code],
runtime=req.runtime,
detach=True,
network_disabled=True,
read_only=True,
user="65534:65534", # nobody:nogroup
cap_drop=["ALL"],
security_opt=["no-new-privileges:true"],
mem_limit=f"{req.memory_mb}m",
memswap_limit=f"{req.memory_mb}m", # Disable swap
nano_cpus=int(req.cpu_quota_cores * 1_000_000_000),
pids_limit=64,
tmpfs={"/tmp": "rw,noexec,nosuid,size=64m"},
environment={"PYTHONDONTWRITEBYTECODE": "1", "HOME": "/tmp"},
)
try:
wait_res = container.wait(timeout=req.timeout_sec)
exit_code = int(wait_res.get("StatusCode", -1))
except Exception:
timed_out = True
logger.warning("Sandbox %s exceeded %.1fs timeout; killing", container.short_id, req.timeout_sec)
container.kill()
raw_stdout = container.logs(stdout=True, stderr=False)
raw_stderr = container.logs(stdout=False, stderr=True)
stdout_str = raw_stdout[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace")
stderr_str = raw_stderr[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace")
except (APIError, ContainerError) as exc:
stderr_str = f"Sandbox runtime error: {exc}"
logger.error(stderr_str)
finally:
if container is not None:
try:
container.remove(force=True)
except APIError as cleanup_exc:
logger.warning("Failed to remove container %s: %s", container.short_id, cleanup_exc)
elapsed_ms = (time.perf_counter() - start) * 1000.0
return SandboxResult(
exit_code=exit_code,
stdout=stdout_str,
stderr=stderr_str,
timed_out=timed_out,
duration_ms=round(elapsed_ms, 2),
)
async def execute(self, req: SandboxRequest) -> SandboxResult:
return await asyncio.to_thread(self._run_sync, req)
async def main() -> None:
sandbox = CodeSandbox()
req = SandboxRequest(
code="import sys; print('Python:', sys.version.split()[0]); print('Sum:', sum(range(100)))",
timeout_sec=5.0,
runtime="runsc",
)
result = await sandbox.execute(req)
print(result.model_dump_json(indent=2))
if __name__ == "__main__":
asyncio.run(main())
Firecracker Snapshot Architecture for Sub-25ms Cold Starts
When your platform runs thousands of ephemeral coding agent turns per minute, booting a full Python + NumPy + Pandas environment from scratch wastes 300ms to 1,200ms per turn. Firecracker memory snapshots solve this by pausing a pre-warmed microVM after Python imports finish, saving its memory and CPU state to disk, and restoring fresh clones on demand in under 25ms.
Key rules for production Firecracker snapshot pools:
- Reseed Entropy Immediately: Cloned microVMs inherit identical RNG state. Always read
/dev/urandomor triggervmgenidinside the guest agent right after snapshot restore so TLS keys and UUIDs never collide across tenants. - Isolate Guest Networking with Dedicated TAP +
iptablesDROP Rules: Attach each microVM’seth0TAP device to an isolated network namespace and block169.254.0.0/16,10.0.0.0/8,172.16.0.0/12, and192.168.0.0/16at the host bridge. - Wrap Firecracker in
jailer: Never launch thefirecrackerbinary directly as root. Use Firecracker’sjailerbinary tochroot, drop privileges to an unprivileged UID, and applyseccompfilters before guest boot.
If your agents also pass user-supplied code snippets or logs back to external frontier models, sanitize secrets and tokens first with PriviPaste and validate structured tool outputs using PydanticAI production guardrails. For multi-agent orchestration where one planner delegates execution to a sandboxed worker, see our A2A and MCP multi-agent Python bridge and CI/CD pipelines for AI agent evals.
Frequently Asked Questions
Why is standard Docker unsafe for executing LLM-generated code?
Standard Docker containers share the host Linux kernel across all running containers. If an LLM generates or is prompt-injected into running a kernel exploit, or if the container has default bridge networking, the code can pivot to host metadata endpoints (169.254.169.254) or escape the namespace.
What is the cold-start difference between Firecracker and gVisor?
On modern NVMe Linux hosts, Firecracker microVMs boot a minimal Linux kernel in roughly 110ms to 140ms (or under 25ms when restored from a memory snapshot). gVisor containers via Docker runsc typically start in 180ms to 260ms because the Go-based Sentry kernel initializes per sandbox.
Can you run Firecracker inside a standard cloud VM without nested virtualization?
No. Firecracker requires hardware virtualization via /dev/kvm, which is only available on bare-metal instances (such as AWS i3.metal or c6i.metal) or cloud VMs with nested virtualization explicitly enabled. In standard Kubernetes pods without KVM, gVisor or Kata Containers with cloud-hypervisor fallback is used.
How do you prevent an AI agent sandbox from exfiltrating internal network secrets?
Disable direct container networking with network_mode=‘none’ or attach an isolated egress proxy that blocks RFC 1918 private subnets and link-local 169.254.0.0/16 metadata IPs. Never mount host Docker sockets (/var/run/docker.sock) or host environment variables into the sandbox.
Production Checklist & Verification
- Test metadata SSRF blocking: Run
urllib.request.urlopen("http://169.254.169.254/latest/meta-data/")inside your sandbox and verify it fails immediately with network unreachable. - Test fork-bomb containment: Run
import os; [os.fork() for _ in range(200)]inside the sandbox and confirmpids_limit=64terminates the process cleanly without impacting host PIDs. - Disable swap (
memswap_limit == mem_limit): Ensure OOM-ing agent scripts getSIGKILLimmediately instead of thrashing host disk swap. - Enforce unprivileged UID (
65534:65534): Verify the sandboxed process cannot write outside/tmpor modify system binaries.
Check Your AI Search & AEO Visibility
Score technical docs and articles against 8 Answer Engine Optimization signals for ChatGPT and Perplexity citations.
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Written by S L Manikanta
AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.
Related Articles
Securing Local and Remote MCP Servers: Token Auth, Sandboxing, and Least Privilege
Harden your MCP server against prompt injection, unauthorized access, and filesystem escapes. Covers OAuth token verification, Docker sandboxing, path allowlists, and rate limiting.
Building Production AI Agents with MCP: Complete Architecture Guide (2026)
Architect and deploy production AI agents using Model Context Protocol (MCP). Step-by-step implementation for LangGraph host integration, stdio vs SSE transports, and secure tool sandboxing.
Bridging Google A2A Protocol and MCP in Python Multi-Agent Systems
Build interoperable multi-agent systems in Python by bridging Google Agent2Agent (A2A) protocol for agent delegation with FastMCP for tool execution.
PydanticAI vs Instructor: Speed & JSON Validation (2026)
Compare PydanticAI vs Instructor on structured JSON latency, retry loops, and partial streaming. Production Python benchmarks and when to pick each.