Sub topic 11
Sandboxing code execution and limiting network egress
This chapter assumes you know how LLM tool calling works, can read short Python and JSON snippets, and understand tokens and basic access control. Earlier chapters covered tool allowlists, deterministic authorization, argument constraints, and scoped credentials. Those controls decide which calls are allowed. A sandbox limits what a call can do after it is allowed, which matters most when the tool runs code.
Why a sandbox is still needed
Tool scoping and argument checks work well when a tool does one narrow thing. A read_file tool has a small surface, so you can validate its path.
A code execution tool has no such surface. If the agent can run Python or shell commands, the code can read any file the process can read, open network connections, spawn processes, and use any credential in the environment. You cannot list every dangerous argument, because the argument is a whole program.
The model writes that program, and the model may be steered by untrusted text, as the threat model chapter described. So treat generated code as untrusted code. A sandbox is the boundary that keeps untrusted code from reaching the host, other users' data, and the internal network.
Sandboxing is least privilege applied to the execution environment. The code gets only the files, CPU, memory, time, and network destinations the task needs.
What a sandbox restricts
A sandbox limits several resources at once. Missing any one of them leaves a gap.
| Resource | What to restrict | Failure if left open |
|---|---|---|
| Filesystem | Read-only base image, one writable scratch directory, no host mounts | Code reads SSH keys or `.env` files, or changes the tool code itself |
| Processes | Non-root user, no extra capabilities, a process count cap | Privilege escalation, fork bombs |
| CPU, memory, time | Hard limits and a wall-clock timeout | One call exhausts the host |
| Credentials | None by default, or only the scoped token the task needs | Code reads cloud credentials from the environment |
| Network | Deny by default, allow named destinations | Data leaves, or the code reaches internal services |
Environment variables are easy to forget. If your agent process holds AWS_SECRET_ACCESS_KEY and starts the sandbox with an inherited environment, the generated code has that key. Start the sandbox with an empty environment and pass only what the task needs.
Isolation options and their trade-offs
Isolation strength and cost move together. Choose based on how much you trust the code and how bad a failure would be.
| Option | Isolation | Cost | Typical use |
|---|---|---|---|
| Restricted interpreter (blocked imports) | Weak. Easy to bypass | Very low | Not suitable as a security boundary |
| OS process with limits (`rlimit`, seccomp, namespaces) | Moderate. Shares the host kernel | Low | Trusted users, low-risk code |
| Container (Docker, OCI runtime) | Moderate. Shares the host kernel | Low to medium | Most internal agents |
| Hardened container (gVisor, user-space kernel) | Stronger. Fewer kernel calls reach the host | Medium | Multi-tenant code execution |
| MicroVM (Firecracker) or full VM | Strong. Separate kernel | Medium to high | Untrusted code from many users |
A plain container is a common starting point, but containers share the host kernel. A kernel bug can let code escape. If one agent runs code on behalf of many users, or the code's origin is untrusted web content, use a stronger option.
<br>
Avoid language-level sandboxes that try to block dangerous imports or builtins inside the same interpreter. Python's object model gives many routes back to blocked functionality. Isolate at the operating system or virtual machine level instead.
A locked-down container
The following Python function runs generated code in a throwaway container with no network, no environment inherited from the host, a read-only filesystem, limited resources, and a timeout. It needs Docker installed and an image named python:3.12-slim.
import subprocess
import tempfile
from pathlib import Path
def run_untrusted_python(code: str, timeout_s: int = 10) -> dict:
with tempfile.TemporaryDirectory() as scratch:
Path(scratch, "main.py").write_text(code)
cmd = [
"docker", "run", "--rm",
"--network", "none", # no network at all
"--read-only", # immutable root filesystem
"--cap-drop", "ALL", # no Linux capabilities
"--security-opt", "no-new-privileges",
"--user", "65534:65534", # unprivileged user
"--memory", "256m",
"--cpus", "0.5",
"--pids-limit", "64",
"--tmpfs", "/tmp:rw,size=16m",
"-v", f"{scratch}:/work:ro", # code mounted read-only
"python:3.12-slim",
"python", "/work/main.py",
]
try:
proc = subprocess.run(
cmd, capture_output=True, text=True, timeout=timeout_s
)
except subprocess.TimeoutExpired:
return {"status": "timeout"}
return {
"status": "ok" if proc.returncode == 0 else "error",
"stdout": proc.stdout[:10_000],
"stderr": proc.stderr[:10_000],
}
print(run_untrusted_python("print(sum(range(10)))"))Notes on the design:
--network noneremoves all network access. This is the safest default and fits tasks like data analysis or formatting.- No
-eflags and no--env-fileare passed, so the host's secrets stay out of the container. - Output is truncated. Untrusted code can print gigabytes, and that output goes back into the model's context.
- On timeout,
subprocess.runkills thedockerclient, but the container may keep running. For production, give the container a name with--nameand rundocker killon timeout. A runtime that enforces its own limit is better still.
Network egress control
Egress is traffic leaving your environment. For agents it has two risks:
- Exfiltration. Code or a tool sends private data to an attacker. This is the third leg of the data-flow problem from the previous chapter. If the agent has private data and sees untrusted input, closing egress breaks the attack.
- Reaching internal systems. Code makes requests to services that trust anything inside the network.
A common version of the second risk is the cloud metadata endpoint. On AWS, an instance can read temporary credentials from 169.254.169.254. If code in a sandbox can reach that address, it can obtain the host's role credentials. Block that address from sandboxes. On EC2, also require IMDSv2 and set the hop limit to 1 so containers cannot reach it through the host.
Egress policy should be deny by default, then allow specific destinations. There are three levels, from simplest to most precise:
- No network. Use when the task does not need it. This is the right default.
- Allowlisted hosts through a proxy. Sandboxes can reach only an egress proxy, and the proxy permits named domains such as a package index. Everything else fails.
- Per-tool network paths. Network calls happen in a separate, narrow tool (for example
fetch_urlwith domain checks), not inside the code sandbox.
The last option is often best. Let the sandbox compute, and let a reviewed tool with argument constraints do the network call.
Pitfalls with allowlists
- Allowlisting a broad domain. Permitting
*.amazonaws.comor a public paste site lets an attacker use your allowed destination as the drop point. They can write data to their own bucket under that domain. Allow specific hosts and, where possible, specific paths or buckets. - DNS as a channel. Even with blocked HTTP, code that can resolve names can encode data in lookups to a domain the attacker controls. Use
--network none, or send DNS only through a resolver that enforces the allowlist. - Redirects. An allowed URL can redirect to a disallowed one. Validate after redirects, or have the proxy enforce policy on the final connection.
- Resolving to private addresses. A name on the allowlist can point to
10.x,127.0.0.1, or169.254.x.x. Check the resolved IP address, not only the hostname. This is server-side request forgery, or SSRF. - Package installs. Letting code
pip installanything means running arbitrary code from the package. Pre-build the image with the libraries you need instead.
Network and data flow together
The diagram shows where the controls sit for a code execution call.
The runtime check from earlier chapters still applies. The sandbox does not replace it. The two layers cover different failures: the check stops unlisted tools, and the sandbox contains an allowed tool that behaves badly.
Handling files going in and out
The sandbox needs inputs and produces outputs. Treat both directions as boundaries.
- Inputs. Copy in only the files the task needs. Do not mount a user's home directory or the project root. Mount inputs read-only.
- Outputs. Collect results from one scratch directory, cap the size and file count, and check file names. Do not follow symlinks created by the sandboxed code. A symlink in the output pointing at
/etc/passwdcan trick a naive copy-out step into reading host files. - Persistence. Destroy the sandbox after the task. State that survives between runs lets one injection poison later runs or leak data across users.
When copying files out, apply the same path check as the read_file example from earlier chapters: resolve the path and confirm it stays inside the scratch root.
Common mistakes
- Treating a container as a full security boundary for multi-tenant, untrusted code.
- Running the sandbox as root, or with
--privileged. - Passing the agent's own environment variables into the sandbox.
- Setting a timeout in the model prompt ("do not run longer than 10 seconds") instead of in the runtime.
- Leaving the network open "just for now" and never revisiting it.
- Returning unbounded output to the model.
- Blocking egress from the sandbox but leaving it open from the agent runtime, which holds the credentials and the private data.
Checking that the sandbox works
Test the sandbox as an attacker would. Run a short script of probes and confirm each one fails.
probes = {
"network": "import urllib.request; urllib.request.urlopen('https://example.com', timeout=3)",
"write_root": "open('/etc/pwned', 'w').write('x')",
"env": "import os; assert not any('KEY' in k or 'TOKEN' in k for k in os.environ)",
"memory": "x = bytearray(2 * 1024**3)",
"loop": "while True: pass",
}
for name, code in probes.items():
result = run_untrusted_python(code, timeout_s=5)
print(name, "->", result["status"])Expected: network, write_root, memory, and loop report error or timeout. The env probe reports ok, because the assertion passes when no secrets are present. Keep these probes in your test suite so a changed flag or base image cannot silently weaken the sandbox.
Exercise
An agent summarizes private customer reports and also browses public web pages. A teammate proposes running the agent's generated Python in a Docker container with the default bridge network, so the code can download helper libraries. Name two risks of this design and the change you would make.
Show answer
First, the code can send the private report contents to any host, so a prompt injection in a web page can cause exfiltration. Second, from the default network the code may reach internal services or the cloud metadata endpoint (169.254.169.254) and obtain credentials. Change it to run the container with no network (--network none) and a pre-built image that already includes the helper libraries. If some network access is needed, route it through an egress proxy that allows only named hosts, or move it into a separate reviewed tool with argument constraints.
Exercise
A sandbox starts with the agent's inherited environment, which includes a cloud access key. The team says this is acceptable because egress is blocked. Why is it still a problem?
Show answer
Blocked egress is one layer and can fail through an allowlist mistake, a DNS channel, or a redirect. The generated code can also use the key without leaving the sandbox, for example through a mounted socket or an allowed internal endpoint. Least privilege says the sandbox should hold no credential it does not need. Start it with an empty environment and pass only a scoped, short-lived token if the task requires one.