# Run untrusted code safely

Code from students, users, the internet or a language model can do anything: delete files, send your data somewhere, mine crypto or never stop. Run it in a sandbox – its own virtual machine with its own kernel, no access to your computer – and add three more fences: no network, short time limits, and an unprivileged user.

## What you'll build

A small “grader”: a function that takes a piece of Python, runs it with the input you give and returns its output, exit code and whether it was stopped. The script tries it with three submissions – a correct one, one that tries to reach the internet and one that never ends – so you can see each fence work.

## What you need

- A WBX Sandbox **API key** in `WBXSANDBOX_API_KEY`; `pip install wbxsandbox` or `npm install wbxsandbox`.
- About **10 minutes**.
- Not a programmer? Ask your assistant: *“Use WBX Sandbox without internet to run this script and tell me what it does.”* – it creates a sandbox with no network for you (see [Your first result](https://sandbox.wbx.cz/docs/guides/first-result.md)).

## The fences

| Fence | How | Protects against |
| --- | --- | --- |
| A fresh sandbox per submission | Create, run, delete. Nothing is shared between submissions. | One submission reading or changing another's files. |
| No network | `internet=False` / `network: { mode: "none" }`; or an *allowlist* of the few hosts it needs. | Sending data out, downloading more code, attacking other servers. |
| Short limits | A command timeout of seconds, a sandbox lifetime of minutes, a small template (`mini`: 1 vCPU, 256 MB). | Endless loops, running up your bill. |
| An unprivileged user | Commands run as root inside the sandbox; drop to the user `nobody` (uid 65534) – with `setpriv` in the command from the SDKs, or `"uid": 65534` over REST. | The submission changing the sandbox's own setup (your grading files, installed tools). |
| No secrets inside | Don't pass API keys in `env`, don't copy them to the disk. | The code printing or using your credentials. |

## Steps

1. ### The whole script

   **Python**

   ```
   # grader.py
   from wbxsandbox import Sandbox

   # run as the user nobody (uid/gid 65534) with an empty environment
   RUN = "setpriv --reuid=65534 --regid=65534 --clear-groups env -i PATH=/usr/local/bin:/usr/bin:/bin HOME=/tmp python3 main.py"

   def grade(code, stdin=""):
       # fresh sandbox, no network, 2 minutes of lifetime; deleted when the block ends
       with Sandbox.create(template="mini", timeout=120, internet=False) as sb:
           sb.files.write("/opt/task/main.py", code)
           sb.run("chmod -R a+rX /opt/task").check()
           r = sb.run(RUN, cwd="/opt/task", timeout=10, stdin=stdin)    # 10 seconds
           return {"exit_code": r.exit_code, "timed_out": r.timed_out,
                   "stdout": r.stdout[:2000], "stderr": r.stderr[-2000:], "truncated": r.truncated}

   SUBMISSIONS = {
       "correct": "n = int(input())\nprint(sum(range(n + 1)))",
       "network": "import urllib.request\nprint(urllib.request.urlopen('https://example.com', timeout=5).status)",
       "endless": "while True:\n    pass",
   }
   for name, code in SUBMISSIONS.items():
       print(name, grade(code, stdin="100\n"))
   ```

   **TypeScript**

   ```
   // grader.mts (an ES module – top-level await)
   import { WBX } from "wbxsandbox";

   // run as the user nobody (uid/gid 65534) with an empty environment
   const RUN = "setpriv --reuid=65534 --regid=65534 --clear-groups env -i PATH=/usr/local/bin:/usr/bin:/bin HOME=/tmp python3 main.py";
   const wbx = new WBX();

   async function grade(code: string, stdin = "") {
     // fresh sandbox, no network, 2 minutes of lifetime; deleted in finally
     const sb = await wbx.sandboxes.create({ template: "mini", timeoutSeconds: 120, network: { mode: "none" } });
     try {
       await sb.files.write("/opt/task/main.py", code);
       (await sb.commands.run("chmod -R a+rX /opt/task")).check();
       const r = await sb.commands.run(RUN, { cwd: "/opt/task", timeoutMs: 10_000, stdin, maxOutputBytes: 64_000 });
       return { exitCode: r.exitCode, timedOut: r.timedOut, stdout: r.stdout.slice(0, 2000),
                stderr: r.stderr.slice(-2000), truncated: r.truncated };
     } finally {
       await sb.kill();
     }
   }

   const SUBMISSIONS: Record<string, string> = {
     correct: "n = int(input())\nprint(sum(range(n + 1)))",
     network: "import urllib.request\nprint(urllib.request.urlopen('https://example.com', timeout=5).status)",
     endless: "while True:\n    pass",
   };
   for (const [name, code] of Object.entries(SUBMISSIONS)) console.log(name, await grade(code, "100\n"));
   ```

   **curl**

   ```
   H=(-H "Authorization: Bearer $WBXSANDBOX_API_KEY")
   API=https://sandbox.wbx.cz

   SB=$(curl -s -X POST $API/v1/sandboxes "${H[@]}" -H "Content-Type: application/json" \
     -d '{"template": "mini", "timeout_s": 120, "network": {"mode": "none"}}' | jq -r .id)

   # upload the submission (main.py on your disk) as raw bytes
   curl -s -X PUT "$API/v1/sandboxes/$SB/files?path=/opt/task/main.py" "${H[@]}" \
     -H "Content-Type: application/octet-stream" --data-binary @main.py

   # as root: make the submission readable for everyone
   curl -s -X POST $API/v1/sandboxes/$SB/exec "${H[@]}" -H "Content-Type: application/json" \
     -d '{"cmd": "chmod -R a+rX /opt/task"}' | jq -e '.exit_code == 0'

   # as the user nobody: "uid" starts the command as that user (gid defaults to the same)
   jq -n '{cmd: "env -i PATH=/usr/local/bin:/usr/bin:/bin HOME=/tmp python3 main.py", uid: 65534,
           cwd: "/opt/task", timeout_ms: 10000, stdin: "100\n"}' |
     curl -s -X POST $API/v1/sandboxes/$SB/exec "${H[@]}" -H "Content-Type: application/json" -d @- |
     jq '{exit_code, timed_out, stdout, stderr}'

   curl -s -X DELETE $API/v1/sandboxes/$SB "${H[@]}"
   ```

   Why two ways to drop root: the REST API can start a command as another user (`"uid": 65534`, see [Commands](https://sandbox.wbx.cz/docs/sandboxes/commands.md)), but the SDKs do not have that option – so the Python and TypeScript versions switch to `nobody` inside the command with `setpriv`. The result is the same.
2. ### Need a few websites? Use an allowlist

   If submissions must install packages, allow only the hosts they need instead of the whole internet. Everything else stays unreachable.

   **Python**

   ```
   Sandbox.create(template="mini", timeout=300, allow=["pypi.org", "files.pythonhosted.org"])
   ```

   **TypeScript**

   ```
   await wbx.sandboxes.create({ template: "mini", timeoutSeconds: 300,
     network: { mode: "allowlist", allow: ["pypi.org", "files.pythonhosted.org"] } });
   ```

   **curl**

   ```
   -d '{"template": "mini", "timeout_s": 300,
        "network": {"mode": "allowlist", "allow": ["pypi.org", "files.pythonhosted.org"]}}'
   ```

   Install packages as root *before* dropping privileges, then run the submission as `nobody`. Network settings can only make your team's network policy stricter, never looser.

## How to tell it works

- `correct` prints `exit_code 0` and `stdout` `5050`.
- `network` ends with a non-zero exit code and a Python network error in `stderr` – the sandbox has no route to the internet.
- `endless` comes back after about 10 seconds with `timed_out: True`; the process was killed.
- Add `import os; print(os.getuid())` to a submission: it prints `65534`.

## Common problems

| What you see | Meaning and fix |
| --- | --- |
| The submission cannot read its own file (`Permission denied`) | Files you upload belong to root. Keep the `chmod -R a+rX` step, and give the folder write access (`chmod a+w`) only if the code must write there – `/tmp` is writable for everyone. |
| `truncated: true` | The output was longer than the limit and was cut. Treat it as a failure or lower what you keep (TypeScript: `maxOutputBytes`). |
| `429 quota` when creating | Your plan's concurrent sandboxes are in use. Grade submissions with a small worker pool, or as a [batch of jobs](https://sandbox.wbx.cz/docs/guides/batch.md) – jobs wait for a free slot on their own. |
| `400` when creating | For example an allowlist entry that is not a host name or address range – the message says which. (A lifetime above your plan's maximum is not an error: it is capped to the maximum.) |
| The sandbox is gone before you read the result | Its lifetime ended. Keep `timeout` of the sandbox comfortably above the command timeout. |

How the isolation works underneath – Firecracker microVMs, the jailer, firewall rules – is described in [Security and isolation](https://sandbox.wbx.cz/docs/security.md); a one-page overview is [Run untrusted AI-generated code safely](https://sandbox.wbx.cz/untrusted-code).

## Next steps

- [Network options](https://sandbox.wbx.cz/docs/sandboxes/network.md): Full internet, allowlist, blocklist, no network, IPv6.
- [A batch of 100 tasks](https://sandbox.wbx.cz/docs/guides/batch.md): Grade a whole class at once with a price limit.
- [Security and isolation](https://sandbox.wbx.cz/docs/security.md): What separates your code from everyone else's.

Source: https://sandbox.wbx.cz/docs/guides/untrusted-code
