DEV Community

kosa8
kosa8

Posted on Originally published at kosa8.com

How to safely run untrusted code generated by LLMs

Treat code an LLM wrote as code from an unknown author. Run it in a fresh, disposable environment behind a kernel boundary it does not share with your host (a microVM, or at minimum a user-space kernel such as gVisor), with no credentials inside, a network closed except for hosts you list and enforced outside the sandbox, hard limits on CPU, memory, disk, processes and time, and a record of what it did. Reviewing or filtering the code helps, but only the runtime boundary limits what the code can reach once it runs.

Why LLM-generated code counts as untrusted

Three things make generated code untrusted even when the model is well behaved. It can be wrong: a cleanup script that deletes the wrong directory, a loop that never ends, a migration that drops a table. It can be steered: a prompt injection in a web page, an issue, a README, an email or a tool description can make the model write code that serves whoever planted it. And it pulls in code nobody chose: models suggest packages, and some of the names they suggest do not exist until an attacker registers them, a pattern researchers call package hallucination.

OWASP's Top 10 for LLM Applications 2025 names the two failures behind most of the damage. Improper Output Handling (LLM05) is passing model output to a shell or interpreter without controls. Excessive Agency (LLM06) is giving a model more tools and permissions than its task needs. The fix for both is the same: decide what the code can reach before it runs, and enforce that somewhere the code cannot change.

Untrusted code tends to try the same things:

  • read credentials from environment variables, dotfiles, SSH agents and cloud metadata endpoints;
  • send data to any host it can reach, including over DNS;
  • install packages and run their install scripts;
  • write outside its working folder, or change files you will run later;
  • use all the CPU, memory, disk or process slots on the machine;
  • leave something behind for the next run: a file, a cron entry, a background process.

The checklist

Each control covers a failure of the others.

  1. Use a boundary that does not share your host's kernel. For code nobody has reviewed, use a microVM (Firecracker, Cloud Hypervisor or Kata Containers on Linux with KVM, or Apple's Virtualization framework on a Mac) or, at minimum, a user-space kernel such as gVisor. A plain container is a floor for reviewed code, not a boundary for hostile code.

  2. Never run it in your application's process. No exec(), eval() or subprocess call on the server that holds your database credentials, even for a quick calculation.

  3. Put no secrets inside. No API keys in environment variables, no mounted home directory, no SSH agent, no cloud credentials, and never the container runtime's socket. If the code must call an API, add the credential outside the sandbox on the way out, or hand it a short-lived token scoped to that one task.

  4. Close the network, then open only what the task needs. Deny by default and allow named hosts, such as one package index or one API. Enforce the rule outside the sandbox, answer DNS only for allowed names, and block link-local and cloud metadata addresses such as 169.254.169.254.

  5. Cap resources and time. Set CPU, memory, disk and process-count limits and a wall-clock timeout for every run. Cap the size of stdout and stderr too, because that output flows back into the model's context.

  6. Start every run from a known state. Use a fresh sandbox per run, or restore a clean snapshot before each run. Never reuse one environment across users or tenants.

  7. Mount the minimum, read-only by default. Copy input files in, or mount one folder read-only, and collect results from one known output path.

  8. Record what happened. Keep commands, exit codes, network attempts (allowed and refused) and outputs, written by something outside the sandbox so the code cannot edit its own record.

Which isolation boundary to use

The boundary decides what a bug in the code, or in the layer under it, can reach. The table runs from weakest to strongest.

Technology What handles the code's system calls Shares the host kernel? Start-up Good fit
Language-level sandbox (restricted interpreter, AST filters) Your own process Yes, and your process memory Instant Not a security boundary on its own
OS process sandbox (seccomp, Landlock, macOS Seatbelt) The host kernel, behind a filter Yes Instant Narrowing a trusted tool's file and network access
Container (runc) The host kernel Yes Lowest Reviewed code on a patched host
Container under gVisor (runsc) gVisor's user-space kernel Only through a narrow set of calls Low; syscall-heavy work is slower A smaller host-kernel surface without VMs
WebAssembly runtime The runtime, through the interfaces you grant No direct system calls Very low Code you can compile to Wasm; few native packages
MicroVM (Firecracker, Cloud Hypervisor, Kata Containers) Its own guest kernel, behind hardware virtualization No Low; a small kernel boots in well under a second Unreviewed code that needs a full Linux
Full VM Its own guest kernel, full device model No Highest Occasional manual runs; long-lived environments

The trade-off is compatibility against attack surface. Generated code usually wants a full Linux userland: pip, npm, compilers and shell tools. That rules out language-level sandboxes and makes WebAssembly awkward for general use, which is why teams that run arbitrary generated code mostly choose between gVisor and a microVM. MicroVM vs container isolation for LLM code execution covers that choice in depth.

Network: deny by default, enforce outside

The most damaging thing hijacked code can do is send your data somewhere. An allow-list limits where data can go. Three details decide whether it holds:

  • Enforce it outside the sandbox. Put the rule on the host, in the virtual machine's network path or in a proxy the sandbox cannot reconfigure. Firewall rules inside the sandbox can be removed by root inside it.
  • Control DNS. Answer only allowed names, so blocked hosts do not resolve and DNS queries cannot carry data out.
  • Know what an allow-list does not cover. Traffic to an allowed host is still traffic. A host that accepts uploads, such as a code-hosting site, a paste service or a storage bucket, is a way out. Allow the narrowest hosts you can, and give pure computation no network at all.

Secrets: keep them out of the sandbox

Any secret the code can read, it can print, and anything it prints can end up in the model's context, a log or an outbound request. The reliable pattern is a broker. The sandbox holds a placeholder, and a proxy outside it swaps the placeholder for the real key only on requests to that key's own API host. A copied placeholder is worthless anywhere else.

One limit remains. While the sandbox runs, it can still use the key along its allowed route, because that is how it does its work. Scope every key at the provider (read-only where possible, one project where possible), give each agent its own key, and rotate a key when an agent misbehaves.

State, limits and clean-up

Run-to-run contamination is a quiet failure: a package installed by one run, a file left in /tmp, a background process still listening on a port. Either throw the environment away after each run or restore it from a clean snapshot. Snapshot restore is now cheap enough to do per run. In kosa8's own benchmark, restoring a small microVM from a memory snapshot took 74 ms at the median on one server; the benchmark study gives the hardware and method.

Make every limit fail closed. An out-of-memory kill or a timeout should end the run and return an error to the agent, not hang the worker that called it.

Common mistakes

  • Mounting the container runtime's socket so the code can build images. That hands the code control of the host.
  • Running containers with --privileged, extra capabilities or seccomp turned off.
  • Passing the parent process's environment into the sandbox, with every key in it.
  • Mounting the project or home directory read-write.
  • Reusing one long-lived sandbox for many users or tenants.
  • Trusting a regex, a linter or a second model to spot dangerous code before it runs. Filters are worth having as a first check, but obfuscated or harmless-looking code gets past them.

One way to do it: kosa8

kosa8 is Zero Trust cybersecurity infrastructure for AI agents, and it covers the checklist above as one tool. Each sandbox is its own microVM with its own kernel: Apple's Virtualization framework on a Mac, Cloud Hypervisor on KVM on x86-64 Linux. Network egress goes to an allow-list enforced on the host, outside the microVM. Secrets stay outside the sandbox: the host adds the real key on requests to that key's own host. Risky steps can wait for a person, and every action goes to a hash-chained, signed audit log. A checkpoint captures memory, processes and disk, and a rewind puts the sandbox back.

kosa8 sandbox create runner --cpus 2 --memory 2048 \
    --egress-allow pypi.org --egress-allow files.pythonhosted.org
kosa8 sandbox pull runner python:3.12-slim
kosa8 checkpoint runner --label clean
kosa8 sandbox run runner python:3.12-slim python -c "$(cat generated.py)"
kosa8 rewind runner --to clean --yes
Enter fullscreen mode Exit fullscreen mode

To try it without installing anything or making an account, kosa8.com/try runs code in a fresh sandbox with no outbound network: 15 minutes of run time free per 24 hours, each run up to 60 s. An AI agent can do the same with one HTTP call and no key:

curl -s https://api.kosa8.com/v1/try/agent -H 'content-type: application/json' -d '{"language":"python","code":"print(1)"}'
Enter fullscreen mode Exit fullscreen mode

The step-by-step version, with egress checks and the audit log, is the guide How do I run untrusted LLM-generated code safely?

What kosa8 does not do: it limits what generated code can reach, but it does not judge whether the code is correct, and it does not detect prompt injection. SOC 2 Type II is in progress; there is no SOC 2 report and no external penetration test yet.

Try free with no account. Starter is free with no card; plans from \$29 a month.

Questions

Is a Docker container enough to run LLM-generated code?

For code you have reviewed, on a patched host, a hardened container (non-root, all capabilities dropped, no new privileges, no network, read-only root filesystem) is a reasonable floor. For code nobody has reviewed it is not a strong boundary: the code's system calls go straight to the host kernel, so one kernel or container-runtime bug can become a host escape. Use gVisor or a microVM for that.

Can I scan generated code instead of sandboxing it?

Scanning and review catch obvious mistakes and are worth keeping, but they do not limit what the code can reach when it runs. Obfuscated or harmless-looking code gets past filters, so the runtime boundary, the network policy and the absence of secrets are what actually limit the damage.

Should LLM-generated code have internet access?

Only if the task needs it, and then only to named hosts. Pure computation needs no network; a package install needs a package index. Enforce the allow-list outside the sandbox, answer DNS only for allowed names, and remember that an allowed host that accepts uploads is still a way out.

How do I give generated code an API key safely?

Do not put the key inside. Use a broker outside the sandbox that adds the real key only to requests for that API's host, so the sandbox holds a placeholder that is useless anywhere else. Scope the key at the provider as well, because the sandbox can still use it along the allowed route while it runs.

Should every run get a fresh sandbox?

Yes, or a sandbox restored from a clean snapshot. Reusing one environment lets one run's packages, files or processes affect the next, and across users it leaks data. Restoring a small microVM from a snapshot takes tens of milliseconds on current hardware, so per-run isolation is affordable.

Sources and further reading

Related


This article was written with AI assistance and reviewed by the kosa8 team. It was first published at kosa8.com.

Top comments (0)