Area 06 · AI Security · Concept 10 of 20

Tool Sandboxing

Run code or commands written by the model in an isolated environment.

01–10 · The basePhase 7 · Weeks 24–26≈ 1 hour

The idea

Code interpreters and coding agents run code the model wrote. That code might be buggy, or written under an attacker’s influence. Never run it on your server or laptop directly. A sandbox is an isolated environment with no access to your secrets, network limited or blocked, resource limits, and a short lifetime.

Options range from Docker containers with strict settings, to gVisor or Firecracker microVMs, to hosted sandboxes (E2B, Modal, provider code execution tools). Mount only the files needed, and copy results out explicitly.

Also sandbox file-system tools: restrict paths to one working directory and reject path traversal like ../../etc/passwd.

Why it matters

Code execution turns injection into remote code execution. Sandboxing contains it.

Words to know

  • EgressOutbound network traffic; block it by default in sandboxes.

Try it without code

Break out on paper

  1. List what a malicious script could do on your laptop if an agent ran it.
  2. For each, write the sandbox setting that prevents it.

Use it in code

Run model-written code in a locked-down Docker container.

python
import subprocess, tempfile, pathlib

def run_sandboxed(code: str, timeout=10):
    with tempfile.TemporaryDirectory() as d:
        pathlib.Path(d, "main.py").write_text(code)
        cmd = ["docker", "run", "--rm", "--network=none", "--memory=256m", "--cpus=0.5",
               "--pids-limit=64", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges",
               "-v", f"{d}:/work:ro", "-w", "/work", "python:3.12-slim", "python", "main.py"]
        try:
            res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
            return res.stdout[-4000:], res.stderr[-2000:]
        except subprocess.TimeoutExpired:
            return "", "timeout"

print(run_sandboxed("import socket; socket.create_connection(('example.com', 80))"))
PRACTICE · TICK IT AFTER THIS

Give your agent a run_python tool backed by the sandbox and confirm network access and file writes fail.

Common mistakes

  • Mounting your home directory or Docker socket into the sandbox.
  • Passing environment variables with secrets.

Go deeper