Executive Overview
The evolution of artificial intelligence has transitioned from passive text generation to active, autonomous agency. Modern AI agents are no longer confined to answering prompts; they are equipped with execution tools that allow them to write, compile, and execute code in real time. While this capability dramatically expands an agent’s utility—turning it into a functional data analyst, software engineer, or systems administrator—it introduces a profound security paradox. An agent that can execute arbitrary code is only as secure as the infrastructure anchoring that execution.
When a large language model (LLM) hallucinates a malicious loop, falls victim to a prompt injection attack, or simply writes a resource-intensive script, the underlying system bears the consequences. Unchecked code can exhaust host memory, flood system processes, leak local environment variables, compromise API keys, or pivot to internal network services. Sandboxing—the practice of erecting strict operational boundaries around untrusted code—is no longer an optional optimization; it is the core defensive perimeter of modern agentic engineering.
This report examines the mechanics of securing AI agent code execution by implementing, testing, and benchmarking three distinct isolation tiers:
- Limited Subprocesses (leveraging Linux kernel features via system resource caps and network unsharing).
- Hardened Docker Containers (utilizing namespaces, cgroups, read-only root filesystems, and dropped capabilities).
- Firecracker MicroVMs (providing a full hardware-level boundary with a dedicated guest kernel per execution).
By subjecting each tier to a uniform suite of hostile payloads—ranging from CPU starvation loops and memory-grab exploits to fork floods and secret-reading scripts—we evaluate the direct trade-off between absolute isolation security and operational latency. Furthermore, we provide a unified architecture pattern where an LLM agent interacts with an abstract execution interface, enabling developers to swap underlying security boundaries without altering agent logic.
Detailed Chronology and Technical Implementation
To understand how these sandboxes operate under the hood, we must construct them from the ground up, moving from the lightest and most permissive tier to the most rigorous hardware-enforced isolation.
The implementation requires a modern Python environment (Python 3.10 or newer) running on Linux or Windows Subsystem for Linux (WSL) for subprocess controls, Docker for containerization, and an E2B account for microVM orchestration.
Step 1: Architecting the Agentic Execution Loop
An effective agent design decouples the LLM’s decision-making process from the execution environment. The agent receives a single tool definition, run_python, which accepts a string of code and returns standard output, standard error, and an exit code.
# agent.py
import json
from dataclasses import asdict
import anthropic
from sandbox import SubprocessSandbox
SYSTEM = "You are a data analyst. Solve tasks by writing Python and running it with the run_python tool."
TOOL =
"name": "run_python",
"description": "Run Python code in a sandbox. Returns stdout, stderr and the exit code. Files do not persist.",
"input_schema": "type": "object", "properties": "code": "type": "string", "required": ["code"],
def run_agent(task, sandbox, model="claude-sonnet-5-5", max_turns=6, client=None):
client = client or anthropic.Anthropic()
messages = ["role": "user", "content": task]
for _ in range(max_turns):
reply = client.messages.create(
model=model, max_tokens=4000, system=SYSTEM,
tools=[TOOL], messages=messages
)
messages.append("role": "assistant", "content": reply.content)
if reply.stop_reason != "tool_use":
return "".join(block.text for block in reply.content if block.type == "text")
results = []
for block in reply.content:
if block.type == "tool_use":
# The model's code executes strictly inside the sandboxed backend, never in the agent process
outcome = sandbox.run(block.input["code"])
results.append(
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(asdict(outcome)),
"is_error": outcome.exit_code != 0
)
messages.append("role": "user", "content": results)
return "Stopped: turn limit reached."
if __name__ == "__main__":
task = "Compute the mean and standard deviation of the first 1,000 square numbers."
print(run_agent(task, SubprocessSandbox()))
By abstracting execution behind a uniform .run(code) method, the agent remains completely agnostic to whether its code runs in a subprocess, a container, or a microVM.
Step 2: Tier One – The Limited Subprocess
The subprocess tier is the fastest option, relying on operating system primitives to restrict a child process. However, because it shares the host kernel and filesystem, it represents the weakest isolation level.
# sandbox.py (Part 1: Subprocess Backend)
import os
import resource
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass
MAX_OUTPUT = 10_000
SAFE_ENV = "PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"
@dataclass
class Result:
stdout: str
stderr: str
exit_code: int
timed_out: bool
seconds: float
def _trim(text):
return text if len(text) <= MAX_OUTPUT else text[:MAX_OUTPUT] + "n[output truncated]"
class SubprocessSandbox:
"""Fastest and weakest: a limited child process sharing host kernel and files."""
def __init__(self, timeout=5, memory_mb=256, processes=20, file_mb=1, network=False):
self.timeout, self.memory_mb, self.processes = timeout, memory_mb, processes
self.file_mb, self.network = file_mb, network
if not network:
# Fail closed: verify unshare network isolation availability
probe = subprocess.run(["unshare", "--net", "--map-root-user", "true"], capture_output=True)
if probe.returncode != 0:
raise RuntimeError("Network isolation unavailable. Use DockerSandbox or pass network=True.")
def _apply_limits(self):
drop = os.geteuid() == 0
if drop:
os.setgroups([])
os.setgid(65534) # Drop privileges to user 'nobody'
os.setuid(65534)
cpu = int(self.timeout) + 1
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
memory = self.memory_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
size = self.file_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_FSIZE, (size, size))
if drop:
resource.setrlimit(resource.RLIMIT_NPROC, (self.processes, self.processes))
def run(self, code):
workdir = tempfile.mkdtemp(prefix="sandbox-")
os.chmod(workdir, 0o777)
command = [sys.executable, "-I", "-c", code]
if not self.network:
command = ["unshare", "--net", "--map-root-user"] + command
started, timed_out = time.perf_counter(), False
try:
with open(f"workdir/.out", "w+b") as out, open(f"workdir/.err", "w+b") as err:
proc = subprocess.Popen(
command, cwd=workdir, env=SAFE_ENV, stdout=out, stderr=err,
start_new_session=True, preexec_fn=self._apply_limits
)
try:
proc.wait(timeout=self.timeout)
except subprocess.TimeoutExpired:
timed_out = True
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
out.seek(0)
err.seek(0)
return Result(
_trim(out.read().decode(errors="replace")),
_trim(err.read().decode(errors="replace")),
proc.returncode, timed_out, time.perf_counter() - started
)
finally:
try:
os.killpg(proc.pid, signal.SIGKILL)
except (ProcessLookupError, NameError):
pass
shutil.rmtree(workdir, ignore_errors=True)
Step 3: Tier Two – The Hardened Docker Container
Docker containers introduce namespaces and cgroups to isolate processes from one another, though they still rely on the host kernel. To make a container secure for untrusted AI agent execution, multiple defensive flags must be applied.

# sandbox.py (Part 2: Docker Backend)
class DockerSandbox:
"""A container utilizing namespaces and cgroups atop the host kernel."""
def __init__(self, image="python:3.12-slim", timeout=10, memory="256m", cpus="1", pids=64):
self.image, self.timeout, self.memory, self.cpus, self.pids = image, timeout, memory, cpus, pids
def _command(self, name):
return [
"docker", "run", "--rm", "-i", "--name", name,
"--network", "none", # Complete network isolation
"--read-only", "--tmpfs", "/tmp:rw,size=16m", # Immutable root filesystem with small scratch space
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--user", "65534:65534", # Run as unprivileged user inside container
"--memory", self.memory, "--memory-swap", self.memory, # Prevent swap exhaustion
"--cpus", self.cpus, "--pids-limit", str(self.pids),
"-w", "/tmp", self.image, "python", "-I", "-"
]
def run(self, code):
name = f"sandbox-uuid.uuid4().hex[:12]"
started = time.perf_counter()
try:
proc = subprocess.run(
self._command(name), input=code, capture_output=True,
text=True, timeout=self.timeout
)
return Result(
_trim(proc.stdout), _trim(proc.stderr), proc.returncode, False,
time.perf_counter() - started
)
except subprocess.TimeoutExpired:
subprocess.run(["docker", "kill", name], capture_output=True)
return Result("", "timed out", -9, True, time.perf_counter() - started)
Step 4: Tier Three – The MicroVM
MicroVMs provide a hardware-virtualized boundary. Each execution spins up a dedicated guest kernel via a hypervisor, ensuring complete state and kernel separation.
# sandbox.py (Part 3: E2B MicroVM Backend)
class E2BSandbox:
"""A Firecracker microVM with a dedicated kernel, provisioned per run."""
def __init__(self, timeout=10):
from e2b_code_interpreter import Sandbox
self._Sandbox, self.timeout = Sandbox, timeout
def run(self, code):
started, stdout, stderr, exit_code, timed_out = time.perf_counter(), "", "", 0, False
with self._Sandbox.create(timeout=60) as box:
try:
execution = box.run_code(code, timeout=self.timeout)
stdout, stderr = "".join(execution.logs.stdout), "".join(execution.logs.stderr)
if execution.error:
stderr += f"execution.error.name: execution.error.value"
exit_code = 1
except Exception as error:
stderr, exit_code, timed_out = str(error), 1, "timeout" in str(error).lower()
return Result(_trim(stdout), _trim(stderr), exit_code, timed_out, time.perf_counter() - started)
def get_backend(name):
return "subprocess": SubprocessSandbox, "docker": DockerSandbox, "e2b": E2BSandbox[name]()
Supporting Context & Metrics: Threat Modeling and Attack Suites
To evaluate the security postures of these three tiers, we deploy an adversarial test suite (attacks.py) containing six classic breakout and resource-exhaustion payloads.
# attacks.py
import argparse
import os
import socket
import tempfile
import threading
from sandbox import get_backend
parser = argparse.ArgumentParser()
parser.add_argument("--backend", default="subprocess", choices=["subprocess", "docker", "e2b"])
args = parser.parse_args()
# Plant a mock credentials file and open an internal loopback listener
folder = tempfile.mkdtemp()
os.chmod(folder, 0o755)
secret = os.path.join(folder, "credentials")
with open(secret, "w") as f:
f.write("aws_secret_access_key=NOT-A-REAL-KEY")
os.chmod(secret, 0o644)
server = socket.socket()
server.bind(("127.0.0.1", 0))
server.listen(5)
port = server.getsockname()[1]
threading.Thread(target=lambda: [server.accept() for _ in range(5)], daemon=True).start()
ATTACKS = [
("CPU loop", "while True: pass", None),
("Memory grab (512 MB)", 'x = b"x" * (512 * 1024 * 1024)nprint("ALLOCATED")', "ALLOCATED"),
("Fork flood (200 procs)", "import os, timenn = 0nfor _ in range(200):n try:n if os.fork() == 0:n time.sleep(3)n os._exit(0)n n += 1n except OSError:n breaknprint('ALL_FORKED' if n == 200 else 'LIMITED')", "ALL_FORKED"),
("Disk fill (50 MB)", 'open("big.bin", "wb").write(b"x" * (50 * 1024 * 1024))nprint("WROTE")', "WROTE"),
("Read host secret", f'print("LEAKED", open(secret!r).read())', "LEAKED"),
("Reach internal service", f'import socketns = socket.socket()ns.settimeout(2)ns.connect(("127.0.0.1", port))nprint("REACHED")', "REACHED"),
]
sandbox = get_backend(args.backend)
print(f"backend: args.backend")
for name, code, bad_word in ATTACKS:
result = sandbox.run(code)
blocked = result.timed_out if bad_word is None else bad_word not in result.stdout
print(f"name:<24'BLOCKED' if blocked else 'ALLOWED':<9result.seconds:5.1fs")
Comparative Attack Results Analysis
When executing python attacks.py --backend subprocess as an unprivileged user, the limitations of the subprocess tier become immediately evident:
backend: subprocess
CPU loop BLOCKED 5.0s
Memory grab (512 MB) BLOCKED 0.0s
Fork flood (200 procs) ALLOWED 0.1s
Disk fill (50 MB) BLOCKED 0.1s
Read host secret ALLOWED 0.0s
Reach internal service BLOCKED 0.0s
- CPU Loop & Memory Grab: Successfully intercepted by resource limits (
RLIMIT_CPUandRLIMIT_AS). - Fork Flood: Allowed because process limits (
RLIMIT_NPROC) require a dedicated user context to function reliably across all Linux distributions without impacting host stability. - Read Host Secret: Allowed because the subprocess executes directly within the user’s filesystem context, possessing read permissions over unprivileged files.
- Network & Disk Protection: Successfully blocked via network namespace unsharing and file size restrictions (
RLIMIT_FSIZE).
By contrast, shifting execution to Docker with the hardened flags (--network none, --read-only, --cap-drop ALL) blocks all six attacks. Shifting to E2B MicroVMs ensures complete hardware virtualization: even if memory or disk limits are reached, the blast radius is entirely contained within an ephemeral micro-instance that is instantly destroyed upon completion.
Latency Benchmarking
Security inherently incurs a performance cost. Using a benchmarking script (bench.py), we measure the median and peak latency of executing a trivial print(1) command across all three backends over 10 iterations (excluding warm-up initialization):
# bench.py
import argparse
import statistics
from sandbox import get_backend
parser = argparse.ArgumentParser()
parser.add_argument("--backend", default="subprocess", choices=["subprocess", "docker", "e2b"])
parser.add_argument("--runs", type=int, default=10)
args = parser.parse_args()
sandbox = get_backend(args.backend)
sandbox.run("print(1)") # Warm-up execution
times = [sandbox.run("print(1)").seconds * 1000 for _ in range(args.runs)]
print(f"args.backend: median statistics.median(times):.0f ms, slowest max(times):.0f ms over args.runs runs")
- Subprocess Tier: Median latency typically hovers between 15 ms to 30 ms, as it merely spawns an isolated Python interpreter process.
- Docker Container Tier: Median latency ranges between 200 ms to 450 ms, accounting for Docker daemon IPC overhead and container allocation.
- Firecracker MicroVM Tier (E2B): Median latency spans 150 ms to 300 ms for warm execution pools, though cold boots including kernel instantiation can stretch higher depending on network conditions to cloud orchestrators.
Official Statements and Industry Alignment
The industry consensus on AI agent sandboxing has shifted decisively toward hardware-level isolation. Major cloud and container infrastructure providers have formalized this architectural migration:
- Docker Inc. released architectural insights emphasizing that traditional containers share the host kernel, making them vulnerable to container breakouts—such as the November 2025
runcvulnerabilities that allowed attackers to escape container boundaries. Docker noted that modern AI workflows require hardware boundaries, leading to the deployment of dedicated microVM sandboxing architectures. - Amazon Web Services (AWS) highlighted that its Firecracker-based Lambda MicroVMs share no kernel state between execution sessions, offering multi-tenant security guarantees that software-level containment cannot match.
- Container Runtime Security: The Cloud Native Computing Foundation (CNCF) continues to issue advisories regarding container runtime vulnerabilities, reinforcing the principle that defense-in-depth must assume container escapes are possible if untrusted code is executed at scale.
Future Outlook
As autonomous AI agents evolve from isolated prompt-response models into persistent digital workers capable of managing complex enterprise workflows, the attack surface will expand exponentially.
The industry trajectory points toward microVMs becoming the default execution boundary for all production-grade agentic platforms. Innovations such as state-suspended microVMs (which maintain execution context for hours while remaining frozen when idle) will eliminate the latency penalty of cold boots. Furthermore, security policies will be strictly enforced by foundational infrastructure layers rather than managed or interpreted by the LLM itself.
For developers and systems architects, the mandate is clear: when building AI agents that write code, never rely on software goodwill or model instructions for safety. Implement a rigorous, multi-tiered defensive architecture—wrap execution tools in an abstracted interface, enforce strict resource quotas, eliminate network access by default, and isolate untrusted code behind hardware-enforced microVM boundaries.