Sub topic 11
Sandboxing code execution and limiting network egress
This chapter assumes you know how tool calls reach your runtime. It also assumes you have read the earlier chapters on tool scoping and deterministic enforcement, and that you can read short Python snippets and basic container flags.
Why a sandbox is still needed
Tool allowlists and argument checks restrict which tools run and with what values. A code-execution tool is different, because the model writes the program. You cannot validate every possible program. Instead, you limit what the process can reach, whatever it contains.
A sandbox is an isolated environment with its own filesystem view, resource limits, and restricted network access. Assume the code is hostile, whether it came from a prompt-injected model or from a poisoned document the model summarized. The sandbox should make that code harmless.
Egress is outbound network traffic. Limiting it matters because exfiltration needs an outbound channel. If the sandbox cannot reach the internet, stolen data has nowhere to go.
Layers of isolation
| Layer | Control | What it limits |
|---|---|---|
| Process | Non-root user, dropped capabilities | Privilege escalation |
| Filesystem | Read-only root, small temporary directory | Persistence and reading host files |
| Resources | Memory, CPU, process count, timeout | Denial of service and runaway cost |
| Network | No network, or an allowlist | Exfiltration and calls to internal services |
| Credentials | None inside the sandbox | Abuse of your accounts |
Containers share the host kernel. For code from untrusted sources, a microVM or a user-space kernel such as gVisor gives a stronger boundary.
A locked-down runner
This function runs model-written Python in a throwaway container with no network.
import subprocess
def run_untrusted(code: str) -> str:
cmd = [
"docker", "run", "--rm", "-i",
"--network", "none",
"--read-only",
"--tmpfs", "/tmp:size=16m",
"--memory", "256m",
"--cpus", "0.5",
"--pids-limit", "64",
"--cap-drop", "ALL",
"--security-opt", "no-new-privileges",
"--user", "65534:65534",
"python:3.12-slim", "python", "-",
]
result = subprocess.run(
cmd, input=code, capture_output=True, text=True, timeout=10
)
return result.stdout if result.returncode == 0 else result.stderrThe timeout stops the Docker client. Give the container a --name and call docker kill on timeout, so it does not keep running.
Allowlisting network egress
Some tools need the network, such as a fetch tool or a package installer. Use a default-deny allowlist of hosts. Enforce it in code, and also at the network layer with a firewall or an egress proxy, so a bug in your code does not open everything.
import ipaddress
import socket
from urllib.parse import urlparse
ALLOWED_HOSTS = {"docs.example.com", "api.example.com"}
def check_egress(url: str) -> str:
parsed = urlparse(url)
if parsed.scheme != "https" or parsed.hostname not in ALLOWED_HOSTS:
raise PermissionError(f"egress to {url!r} is not allowed")
for info in socket.getaddrinfo(parsed.hostname, 443):
ip = ipaddress.ip_address(info[4][0])
if not ip.is_global:
raise PermissionError("host resolves to a non-public address")
return urlThe is_global check blocks private ranges and link-local addresses. One link-local address is the cloud metadata endpoint at 169.254.169.254, which can hand out instance credentials.
Common errors
- Allowing DNS while blocking everything else. DNS queries can carry data in hostnames.
- Following redirects. An allowed host can redirect to a disallowed one, so re-check every hop or disable redirects.
- Checking the name, then connecting later. DNS can change between the check and the connection. Pin the resolved IP or enforce at the proxy.
- Mounting the project directory or Docker socket into the sandbox. Either one gives the code your host.
- Putting secrets in environment variables inside the sandbox. Code can read and print them.
Exercise
A code-execution tool must call one internal reporting API at https://reports.internal.example. Name two controls you would use so the code cannot also reach the cloud metadata endpoint or send data to arbitrary hosts.
Show answer
Route all egress through a proxy or firewall rule that permits only reports.internal.example over HTTPS and denies everything else by default, which also blocks 169.254.169.254. Also keep credentials out of the sandbox, giving the API call a narrowly scoped, short-lived token supplied by the runtime rather than the code. Blocking non-global IPs and disabling redirects are good additions.