# How Do I Run Untrusted or LLM-Generated Python Safely?

> Don't run it in your own process: exec with restricted builtins and RestrictedPython are not security boundaries. Run it in a fresh --no-env microVM, as a user with no sudo and no network, inside a systemd scope with memory, process and time caps, and cap its output. On prod, every hostile snippet hit its limit.

Source: https://sandboxer.com/guides/run-untrusted-python-safely. Updated 2026-11-22.

**Short answer:** Don't run it in your own process: exec with restricted builtins and RestrictedPython are not security boundaries. Run it in a fresh --no-env microVM, as a user with no sudo and no network, inside a systemd scope with memory, process and time caps, and cap its output. On prod, every hostile snippet hit its limit.

Part of [Best ways to run untrusted or LLM-generated code safely](/guides/best-ways-to-run-untrusted-code-safely).

Python that a model wrote, or a user pasted, can loop forever, eat all memory, fork until the machine stalls, read your keys, call out to the internet, overwrite files and print gigabytes. This page runs each of those, on purpose, against one wrapper and shows the limit that stopped it. The deeper tuning lives in sibling pages: [CPU, memory and process caps](/guides/limit-cpu-and-memory-for-untrusted-code-inside-a-sandbox), [an outbound allowlist](/guides/allowlist-an-agents-outbound-network-in-a-sandbox) and [a fresh sandbox per tool call](/guides/a-fresh-sandbox-per-tool-call).

## What stops what

| Hostile snippet | Limit that stops it | What we saw on prod |
| - | - | - |
| `while True: pass` | `sbx exec --timeout` from outside; `timeout` inside | `sbx exec` exit 124 after 5.1 s; wrapper exit 124 after 10.0 s |
| Memory bomb | Scope `MemoryMax=512M` | Killed at 448 MB, exit 137 |
| Memory bomb, no cap | The VM's own RAM | Killed at 3712 MB on a 4 GB `small`, exit 137; the sandbox stayed up |
| Fork bomb | Scope `TasksMax=64` (the cgroup's `pids.max`) | `fork refused after 62 children: [Errno 11]`; 0 processes left |
| Read env and secrets | `--no-env` sandbox, then `env -i` | Only `PATH`, `HOME`, `LANG` |
| Network call out | nftables rule on the run's user | DNS fails; `1.1.1.1` gets `No route to host` |
| Write outside the work dir | A separate `runner` user, a fresh temp dir | `Permission denied` on `~/.bashrc`, `/etc/passwd` and the wrapper |
| Output flood | The wrapper reads at most 64 KB, then kills the run | `output_truncated: true`, exit 137 after 0.06 s |
| `exec(code, {"__builtins__": {}})` | Nothing: it is not a boundary | Escaped and ran `id -un` |

Last checked: 2026-11-22, on prod

Every row ran on one `small` sandbox (2 vCPU, 4 GB) created with `--no-env`, with Python 3.12.3, the default `user` with `sudo`, and the snippets in `~/s/`.

## Why exec and RestrictedPython are not enough

The tempting fix is to run the code in your own process with fewer builtins. Python's docs for [`exec`](https://docs.python.org/3/library/functions.html#exec) say it plainly: "This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities." They add that overriding `__builtins__` "is not a security mechanism: the executed code can still access all builtins."

Here is the escape, with every builtin removed:

```python
# s/escape.py
code = """
for c in ().__class__.__base__.__subclasses__():
    if c.__name__ == "_wrap_close":
        g = c.__init__.__globals__
        g["__builtins__"]["print"]("escaped as:", g["popen"]("id -un").read().strip())
"""
exec(code, {"__builtins__": {}})
```

```text
escaped as: user
```

`print` alone fails in that namespace (`NameError: name 'print' is not defined`), yet the code walked from an empty tuple to `object`'s subclasses, found one defined in the `os` module, and took `popen` from its globals. There are many such paths.

[RestrictedPython](https://restrictedpython.readthedocs.io/en/latest/) rewrites code at compile time to block some of them, and its own docs say: "RestrictedPython is not a sandbox system or a secured environment." It is useful for small, trusted-author expressions. Neither tool limits memory, CPU, processes, network or output, and a crash takes your process with it. Put the code in a separate VM instead, and treat in-process checks as convenience.

## The boundary: a no-env microVM

Each sandbox is a microVM with its own kernel ([machines docs](/docs/machines)), so code inside it can't see your laptop, your server or other sandboxes. Create it with `--no-env` and it receives none of your account's variables, files or credentials ([environments docs](/docs/environments)). Run as the default `user`, the environment holds only Sandboxer's own variables:

```bash
sbx new --name aeo-pyun-1 --type small --no-env
sbx exec sb_jk91jfzqcq 'env | cut -d= -f1 | sort | tr "\n" " "'
```

```text
_ HOME LANG LC_ALL LOGNAME PATH PWD SANDBOXER_API_URL SANDBOXER_ID SANDBOXER_SUBDOMAIN SANDBOXER_TOKEN SHELL SHLVL USER XDG_RUNTIME_DIR
```

In a `--no-env` sandbox, `SANDBOXER_TOKEN` is limited to that sandbox (reading it and hosting its ports). The wrapper below starts the code with `env -i`, so even that token isn't passed. To give the code one key it needs, see [Pass secrets to a sandbox safely](/guides/pass-secrets-to-a-sandbox-safely).

From outside, `sbx exec --timeout` is the first wall-clock cap. Flags go before the command:

```bash
time sbx exec sb_jk91jfzqcq --timeout 5 'python3 s/loop.py'; echo exit=$?
```

```text
real	0m5.106s
exit=124
```

The [CLI reference](/docs/cli) documents this: a timed-out run is killed, `sbx exec` exits 124, and the API's `exitCode` is the killed process's 137.

With no cap, the memory bomb can fill the whole VM. On a 4 GB `small`, the kernel's out-of-memory killer ended the Python process (exit 137) and the sandbox kept running:

```bash
sbx exec sb_jk91jfzqcq --timeout 60 'python3 s/membomb.py' | tail -2; echo exit=${PIPESTATUS[0]}
sbx exec sb_jk91jfzqcq 'sudo dmesg | grep -i "out of memory" | tail -1'
```

```text
3648 MB
3712 MB
exit=137
[119902.599088] Out of memory: Killed process 725 (python3) total-vm:3884712kB, anon-rss:3826944kB, … UID:1000 …
```

That is fine for a sandbox that holds only the untrusted run. If your agent runs in the same sandbox, cap the run so the agent keeps its memory, as the wrapper does.

## The wrapper: every limit, JSON out

`setup-runner.sh` runs once inside the sandbox as `user`. It creates a `runner` user with no sudo, blocks all of `runner`'s traffic except loopback with one nftables rule (the owner-match approach from [the allowlist guide](/guides/allowlist-an-agents-outbound-network-in-a-sandbox), without the proxy), and installs `run-untrusted`:

```bash
#!/usr/bin/env bash
# Run once inside the sandbox as `user` (it has sudo).
set -euo pipefail

# 1. A user for untrusted code: no sudo, no docker group, no password.
id runner &>/dev/null || sudo useradd --create-home --shell /usr/sbin/nologin runner

# 2. No network for `runner`, except loopback (IPv4 and IPv6).
sudo nft delete table inet runner_egress 2>/dev/null || true
sudo nft -f - <<'NFT'
table inet runner_egress {
  chain output {
    type filter hook output priority filter; policy accept;
    meta skuid "runner" oif != "lo" counter reject with icmpx admin-prohibited
  }
}
NFT

# 3. The wrapper: one run, every limit on, JSON out.
sudo tee /usr/local/bin/run-untrusted >/dev/null <<'PY'
#!/usr/bin/env python3
"""usage: run-untrusted [--timeout S] [--mem 512M] [--tasks 64] [--max-output BYTES] code.py"""
import argparse, json, os, shutil, subprocess, tempfile, time, uuid

ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--timeout", type=int, default=10)
ap.add_argument("--mem", default="512M")
ap.add_argument("--tasks", type=int, default=64)
ap.add_argument("--max-output", type=int, default=65536)
a = ap.parse_args()

work = tempfile.mkdtemp(prefix="run-")            # fresh work dir per run
shutil.copy(a.file, os.path.join(work, "main.py"))
subprocess.run(["sudo", "chown", "-R", "runner:runner", work], check=True)
unit = "untrusted-" + uuid.uuid4().hex[:8]
cmd = ["sudo", "systemd-run", "--scope", "--quiet", f"--unit={unit}",
       "--uid=runner", "--gid=runner",
       "-p", f"MemoryMax={a.mem}", "-p", "MemorySwapMax=0",
       "-p", f"TasksMax={a.tasks}", "-p", f"RuntimeMaxSec={a.timeout + 5}",
       "env", "-i", "-C", work, "PATH=/usr/bin:/bin", f"HOME={work}", "LANG=C.UTF-8",
       "timeout", "-k", "2", str(a.timeout), "python3", "-I", "main.py"]

t0 = time.monotonic()
p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, total, flooded = b"", 0, False
while chunk := p.stdout.read1(65536):
    total += len(chunk)
    out += chunk[: max(0, a.max_output - len(out))]
    if total > a.max_output:                       # output flood: kill the whole run
        flooded = True
        subprocess.run(["sudo", "systemctl", "kill", "--signal=KILL", f"{unit}.scope"],
                       stderr=subprocess.DEVNULL)
        break
code = p.wait()
if code < 0:
    code = 128 - code                              # killed by a signal: 137 = SIGKILL
secs = round(time.monotonic() - t0, 2)
subprocess.run(["sudo", "systemctl", "kill", "--signal=KILL", f"{unit}.scope"],
               stderr=subprocess.DEVNULL)              # leftovers, e.g. forked children
subprocess.run(["sudo", "rm", "-rf", work])
print(json.dumps({
    "exit_code": code,
    "timed_out": code == 124,
    "output": out.decode("utf-8", "replace"),
    "output_truncated": flooded,
    "seconds": secs,
}))
PY
sudo chmod 755 /usr/local/bin/run-untrusted
echo ready
```

What each piece does:

- **A fresh work dir per run**, owned by `runner`, deleted afterwards. `runner` can write there and in world-writable `/tmp`, nowhere else that matters.
- **A systemd scope** holds the run and all its children, with `MemoryMax`, `TasksMax` and `RuntimeMaxSec`. The scope options are explained in [the CPU and memory guide](/guides/limit-cpu-and-memory-for-untrusted-code-inside-a-sandbox).
- **`env -i`** starts Python with three variables and nothing inherited. `python3 -I` ignores `PYTHON*` variables and the user site directory.
- **`timeout -k 2`** gives exit 124 on a wall-clock overrun. `RuntimeMaxSec` 5 seconds later catches anything that outlived it.
- **The output cap** reads stdout and stderr together and kills the scope once it passes `--max-output` bytes, so a flood costs milliseconds, not memory.
- **The final `systemctl kill`** clears leftover children, so the next run starts clean.

The nftables rule is loaded at setup and isn't saved, so it is gone after a boot from disk. To make it permanent, or to allow a few domains through a proxy, use the systemd unit and snapshot from [the allowlist guide](/guides/allowlist-an-agents-outbound-network-in-a-sandbox).

## Each hostile snippet, on prod

Each result below is `sbx exec <id> "run-untrusted s/<name>.py"`, with long output trimmed.

**Infinite loop** (`while True: pass`):

```json
{"exit_code": 124, "timed_out": true, "output": "", "output_truncated": false, "seconds": 10.02}
```

**Memory bomb**, 64 MB at a time:

```python
chunks = []
while True:
    chunks.append(bytearray(64 * 1024 * 1024))
    print(f"{len(chunks) * 64} MB", flush=True)
```

```json
{"exit_code": 137, "timed_out": false, "output": "64 MB\n128 MB\n…\n448 MB\n", "output_truncated": false, "seconds": 0.26}
```

**Fork bomb**, children that sleep so they pile up:

```python
import os, time
n = 0
try:
    while True:
        if os.fork() == 0:
            time.sleep(60)
            os._exit(0)
        n += 1
except OSError as e:
    print(f"fork refused after {n} children: {e}")
```

```json
{"exit_code": 0, "timed_out": false, "output": "fork refused after 62 children: [Errno 11] Resource temporarily unavailable\n", "output_truncated": false, "seconds": 15.09}
```

62 children, the parent and `timeout` make the 64 tasks. The parent exited at once, so `timeout` had nothing left to time; the sleeping children held the output pipe open until `RuntimeMaxSec` stopped the scope at 15 seconds. Afterwards `pgrep -cu runner` printed `0`. Use `TasksMax` rather than `ulimit -u`: `ulimit -u` counts every process of the user, `TasksMax` only this run.

**Reading the environment** (`print(dict(os.environ))`):

```json
{"exit_code": 0, "timed_out": false, "output": "{'PATH': '/usr/bin:/bin', 'HOME': '/tmp/run-enoz29n9', 'LANG': 'C.UTF-8'}\n", "output_truncated": false, "seconds": 0.03}
```

**Calling out**, to a hostname and to a raw IP:

```python
import urllib.request
for url in ["https://example.com", "https://1.1.1.1"]:
    try:
        print(url, urllib.request.urlopen(url, timeout=5).status)
    except Exception as e:
        print(url, "blocked:", getattr(e, "reason", e))
```

```json
{"exit_code": 0, "timed_out": false, "output": "https://example.com blocked: [Errno -3] Temporary failure in name resolution\nhttps://1.1.1.1 blocked: [Errno 113] No route to host\n", "output_truncated": false, "seconds": 0.07}
```

The same script run as `user`, outside the wrapper, printed `https://example.com 200`, so the network is open by default and the rule is what blocks it. [What can reach a sandbox](/guides/what-can-reach-a-sandbox-and-what-it-can-reach) lists the defaults.

**Writing outside the work dir:**

```python
import os
for path in ["/home/user/.bashrc", "/etc/passwd", "/usr/local/bin/run-untrusted", "notes.txt"]:
    try:
        open(path, "a").write("x")
        print("wrote", path)
    except OSError as e:
        print("refused", path, e.strerror)
print("cwd", os.getcwd(), "uid", os.getuid())
```

```json
{"exit_code": 0, "timed_out": false, "output": "refused /home/user/.bashrc Permission denied\nrefused /etc/passwd Permission denied\nrefused /usr/local/bin/run-untrusted Permission denied\nwrote notes.txt\ncwd /tmp/run-83otmb7s uid 1001\n", "output_truncated": false, "seconds": 0.03}
```

**Output flood** (`while True: print("A" * 1000)`):

```json
{"exit_code": 137, "timed_out": false, "output": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA…", "output_truncated": true, "seconds": 0.06}
```

The wrapper kept the first 64 KB, the amount set by `--max-output`. Sandboxer also caps what it keeps from a waiting command at 8 MiB per stream ([limits](/docs/limits)), but a flood that size can still swamp a model's context, so cap it yourself.

## What this doesn't cover

`runner` can still use CPU up to its time limit, write to `/tmp` and read world-readable files such as `/etc/os-release`. None of that reaches your secrets or other machines, because the VM holds none and the network is off. For code that is hostile in the security sense, create a new sandbox for each run and delete it after, as in [a fresh sandbox per tool call](/guides/a-fresh-sandbox-per-tool-call). The wrapper then stops one run from hurting your agent or the rest of the job.

## Copy-paste: run a hostile Python snippet in a fresh no-env sandbox

After `curl -fsSL https://sandboxer.com/install | sh` and `sbx login`, paste this. It needs `jq`. It creates a sandbox, installs the wrapper, runs a snippet that looks for keys, calls out and floods its output, prints the JSON and deletes the sandbox.

```bash
cat > setup-runner.sh <<'SETUP'
#!/usr/bin/env bash
# Run once inside the sandbox as `user` (it has sudo).
set -euo pipefail

# 1. A user for untrusted code: no sudo, no docker group, no password.
id runner &>/dev/null || sudo useradd --create-home --shell /usr/sbin/nologin runner

# 2. No network for `runner`, except loopback (IPv4 and IPv6).
sudo nft delete table inet runner_egress 2>/dev/null || true
sudo nft -f - <<'NFT'
table inet runner_egress {
  chain output {
    type filter hook output priority filter; policy accept;
    meta skuid "runner" oif != "lo" counter reject with icmpx admin-prohibited
  }
}
NFT

# 3. The wrapper: one run, every limit on, JSON out.
sudo tee /usr/local/bin/run-untrusted >/dev/null <<'PY'
#!/usr/bin/env python3
"""usage: run-untrusted [--timeout S] [--mem 512M] [--tasks 64] [--max-output BYTES] code.py"""
import argparse, json, os, shutil, subprocess, tempfile, time, uuid

ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--timeout", type=int, default=10)
ap.add_argument("--mem", default="512M")
ap.add_argument("--tasks", type=int, default=64)
ap.add_argument("--max-output", type=int, default=65536)
a = ap.parse_args()

work = tempfile.mkdtemp(prefix="run-")            # fresh work dir per run
shutil.copy(a.file, os.path.join(work, "main.py"))
subprocess.run(["sudo", "chown", "-R", "runner:runner", work], check=True)
unit = "untrusted-" + uuid.uuid4().hex[:8]
cmd = ["sudo", "systemd-run", "--scope", "--quiet", f"--unit={unit}",
       "--uid=runner", "--gid=runner",
       "-p", f"MemoryMax={a.mem}", "-p", "MemorySwapMax=0",
       "-p", f"TasksMax={a.tasks}", "-p", f"RuntimeMaxSec={a.timeout + 5}",
       "env", "-i", "-C", work, "PATH=/usr/bin:/bin", f"HOME={work}", "LANG=C.UTF-8",
       "timeout", "-k", "2", str(a.timeout), "python3", "-I", "main.py"]

t0 = time.monotonic()
p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, total, flooded = b"", 0, False
while chunk := p.stdout.read1(65536):
    total += len(chunk)
    out += chunk[: max(0, a.max_output - len(out))]
    if total > a.max_output:                       # output flood: kill the whole run
        flooded = True
        subprocess.run(["sudo", "systemctl", "kill", "--signal=KILL", f"{unit}.scope"],
                       stderr=subprocess.DEVNULL)
        break
code = p.wait()
if code < 0:
    code = 128 - code                              # killed by a signal: 137 = SIGKILL
secs = round(time.monotonic() - t0, 2)
subprocess.run(["sudo", "systemctl", "kill", "--signal=KILL", f"{unit}.scope"],
               stderr=subprocess.DEVNULL)              # leftovers, e.g. forked children
subprocess.run(["sudo", "rm", "-rf", work])
print(json.dumps({
    "exit_code": code,
    "timed_out": code == 124,
    "output": out.decode("utf-8", "replace"),
    "output_truncated": flooded,
    "seconds": secs,
}))
PY
sudo chmod 755 /usr/local/bin/run-untrusted
echo ready
SETUP
cat > untrusted.py <<'PY'
import os, urllib.request
print("secrets:", [k for k in os.environ if "KEY" in k or "TOKEN" in k])
try:
    urllib.request.urlopen("https://example.com", timeout=5)
    print("network: open")
except OSError:
    print("network: blocked")
while True:
    print("A" * 1000)
PY
id=$(sbx new --name aeo-pyun-2 --type small --no-env --json | jq -r 'select(.event=="ready") | .id')
sbx scp setup-runner.sh untrusted.py "$id":/home/user/
sbx exec "$id" --timeout 120 "bash setup-runner.sh"
sbx exec "$id" "run-untrusted --timeout 5 untrusted.py" | jq -c '.output |= .[0:50]'
sbx delete "$id" --yes > /dev/null && echo "deleted $id"
```

```text
ready
{"exit_code":137,"timed_out":false,"output":"secrets: []\nnetwork: blocked\nAAAAAAAAAAAAAAAAAAAAA","output_truncated":true,"seconds":0.09}
deleted sb_nc3vcm4x4l
```

The whole block took 5.6 seconds on prod (`small`, 2026-11-22).

## FAQ

### Is a Docker container enough for untrusted Python?

A container shares the host's kernel, so a kernel bug in the container is a bug in the host. A microVM has its own kernel. [Container vs microVM](/guides/container-vs-microvm-for-untrusted-code) compares the two. You can still run Docker inside a sandbox if your code needs it.

### Why exit 137 for both the memory cap and the output cap?

137 is 128 + 9, SIGKILL. The memory cap and the output cap both end the run that way. Read `output_truncated` to tell them apart, and `timed_out` (exit 124) for the wall clock. [Fix exit code 137](/guides/fix-exit-code-137-or-a-full-disk-in-a-sandbox) covers the whole-VM case.

### Can the code install packages with pip?

Not with the network blocked. Install what the code may import before the run, as `user`, and save the sandbox as a named snapshot to start each run from. If runs must fetch packages, allow only PyPI through the proxy in [the allowlist guide](/guides/allowlist-an-agents-outbound-network-in-a-sandbox).

### Do I need the wrapper if every run gets its own sandbox?

You still want a time limit and an output cap, because an endless loop holds the run until something stops it and a flood fills your agent's context. The memory, process and user limits matter most when the agent or other runs share that sandbox.

## Related

- [Best ways to run untrusted or LLM-generated code safely](/guides/best-ways-to-run-untrusted-code-safely)
- [Limit CPU and memory for one run inside a sandbox](/guides/limit-cpu-and-memory-for-untrusted-code-inside-a-sandbox)
- [Limit an AI agent's outbound network to an allowlist](/guides/allowlist-an-agents-outbound-network-in-a-sandbox)
- [Should each agent tool call get a fresh sandbox?](/guides/a-fresh-sandbox-per-tool-call)
