Code Execution and Sandboxing

Treat every line an agent writes as code from a stranger, and give it a room it cannot damage.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Code execution lets an agent calculate, transform data and test programs, and it is among the most powerful tools you can offer. Run generated code in an isolated, short-lived environment with no secrets, denied or tightly restricted network access, limited processor, memory, disk and time, and controlled file exchange. Language-level restrictions and timeouts alone are not a security boundary.

What you will learn: why generated code is untrusted, isolation options, resource, network and file controls, a sandbox lifecycle, output handling and how to test containment.
Prerequisites: Tool Permissions, Approvals and Abuse Risks and basic knowledge of processes and containers.

Beginner Why sandbox

What code execution is for

UseBenefit
Arithmetic and data analysisComputed answers instead of guessed numbers
File conversionHandle formats the model cannot read directly
Testing generated codeReal feedback for coding agents
Combining tool resultsFilter large data without loading it into context

The threat model

Generated code can be wrong by accident or hostile because the model was steered by injected text. Assume it will try anything the environment permits.

RiskExamplePrimary control
Read secretsEnvironment variables, key filesPut none inside
Send data outUpload to an outside serverNo network, or an allowlist proxy
Attack internal systemsScan the network, query metadata servicesNetwork isolation
Destroy dataDelete mounted foldersNo host mounts; copies only
Exhaust resourcesEndless loop, huge allocation, many processesHard limits
Escape isolationExploit a kernel or runtime flawStrong boundary, patching
PersistLeave something for the next userFresh environment per task

Unexpected code execution is one of the risks named in the OWASP Top 10 for Agentic Applications.

What is not enough

  • Asking the model to be careful. Instructions do not restrict a process.
  • Searching code for banned words. There are many ways to express the same action.
  • Removing a few functions from the language. Dynamic languages offer other routes.
  • A subprocess with a timeout. It still has your user's files and network.

Where the sandbox sits

Keep the agent's control loop, credentials and policy checks outside the environment that runs generated code. The loop sends code and approved input files in, and receives output, an exit status and selected files back. If the whole agent runs inside the sandbox with its model and tool keys, hostile code can read those keys, and the sandbox protects only the machine, not your accounts. Separating the two also lets you replace the isolation technology later without rewriting the agent.

Outside the sandboxInside the sandbox
Model calls and API keysInterpreter and approved libraries
Permission and approval checksCopies of the task's input files
Limit enforcement and shutdownA writable work folder
Audit recordsThe generated program
Intermediate Boundaries and limits

Choose limits from the workload

Limits that are too tight break honest work, and limits that are absent invite abuse. Run typical tasks and measure them, then set values with a margin and review them from real data.

LimitQuestion to answer
Wall-clock timeHow long will a user wait for this task?
Processor timeHow much computing does the largest normal input need?
MemoryHow much does loading that input take?
Disk and file countHow large are results and temporary files?
Process countDo libraries start helper processes?
Output sizeHow much text can the model use well?

Enforce them where the generated program cannot change them, and make sure that stopping a run also stops every process it started.

Resource limits, and their limits

This program starts code in a child process with a clean environment, a temporary folder and limits on processor time, memory and file size. It is a teaching example for Linux and deliberately shows what remains open.

"""Resource limits for a child process. NOT a security boundary. Linux."""
import resource
import subprocess
import sys
import tempfile

def limit():
    resource.setrlimit(resource.RLIMIT_CPU, (1, 1))            # seconds
    resource.setrlimit(resource.RLIMIT_AS, (256 * 2**20,) * 2)  # memory
    resource.setrlimit(resource.RLIMIT_FSIZE, (100_000,) * 2)  # file bytes

def run(code):
    with tempfile.TemporaryDirectory() as work:
        try:
            done = subprocess.run(
                [sys.executable, "-I", "-c", code],
                cwd=work, env={}, preexec_fn=limit,
                capture_output=True, text=True, timeout=3)
        except subprocess.TimeoutExpired:
            return "stopped: wall clock limit"
    if done.returncode == 0:
        return "ok: " + done.stdout.strip()[:60]
    if done.returncode < 0:
        return f"stopped: signal {-done.returncode}"
    return "error: " + done.stderr.strip().splitlines()[-1][:60]

samples = {
    "normal work":  "print(sum(range(1000)))",
    "busy loop":    "while True: pass",
    "sleeping":     "import time; time.sleep(30)",
    "huge memory":  "x = bytearray(10**9)",
    "huge file":    "open('f','wb').write(bytes(10**6))",
    "environment":  "import os; print(os.environ.get('HOME'))",
    "reads system": "print(open('/etc/passwd').read().split(':')[0])",
}
for name, code in samples.items():
    print(f"{name:<13} {run(code)}")

Output:

normal work   ok: 499500
busy loop     stopped: signal 9
sleeping      stopped: wall clock limit
huge memory   error: MemoryError
huge file     error: OSError: [Errno 27] File too large
environment   ok: None
reads system  ok: root

The loop, the sleep, the large allocation and the large file were all stopped, and the environment variables were hidden. The last line is the point: the code still read a system file. Resource limits control how much a program consumes, not what it can reach. They are one layer inside a real sandbox, never a substitute. Do not run untrusted code with this alone.

Isolation options

OptionIdeaConsider
Hardened containerNamespaces, control groups and system-call filtersShares the host kernel
gVisorA user-space kernel handles the program's system callsCompatibility and overhead for some workloads
MicroVM, such as Firecracker or Kata ContainersA small virtual machine with its own kernelNeeds virtualization support; manage images
WebAssembly runtimeCode can use only capabilities the host grantsLimited language and library support
Managed sandbox serviceA provider runs the isolationCheck data location, limits, network and retention

For code that may be hostile, especially when different users share infrastructure, many teams choose gVisor or a virtual machine boundary over an ordinary container. No option is perfect. Match strength to risk, keep it patched and add layers around it. Kubernetes users can look at Agent Sandbox, a project under SIG Apps that defines a Sandbox resource for agent workloads and can run it with gVisor or Kata Containers; the isolation still comes from the chosen runtime.

Policywho may run what, and when approval is needed
Network boundarydeny by default, filtered proxy
Isolation boundarymicroVM or sandboxed runtime
Process limitsuser, processor, memory, disk, processes, time
Generated codesees only copied inputs
A failure of one layer should not expose everything.

Enforce settings before starting

Good defaults erode as people debug problems. Check the requested configuration in code.

"""Refuse to start a sandbox whose settings are too generous."""

RULES = [
    ("runtime",   lambda v: v in {"microvm", "gvisor"},
     "use a microVM or gVisor for untrusted code"),
    ("user",      lambda v: v not in (None, "root"), "run as non-root"),
    ("network",   lambda v: v in {"none", "allowlist"},
     "deny network or use an allowlist"),
    ("root_fs",   lambda v: v == "read-only", "make the system read-only"),
    ("secrets",   lambda v: v == [], "do not place secrets inside"),
    ("host_mounts", lambda v: v == [], "do not mount host folders"),
    ("memory_mb", lambda v: type(v) is int and 0 < v <= 2048,
     "set a memory limit"),
    ("timeout_s", lambda v: type(v) is int and 0 < v <= 300,
     "set a time limit"),
    ("reuse",     lambda v: v == "never", "start fresh for every task"),
]

def check(spec):
    return [advice for key, ok, advice in RULES if not ok(spec.get(key))]

quick = {"runtime": "container", "user": "root", "network": "open",
         "secrets": ["DB_PASSWORD"], "host_mounts": ["/home"],
         "root_fs": "read-write", "timeout_s": 0}
careful = {"runtime": "microvm", "user": "runner", "network": "none",
           "root_fs": "read-only", "secrets": [], "host_mounts": [],
           "memory_mb": 512, "timeout_s": 60, "reuse": "never"}

for name, spec in (("quick setup", quick), ("careful setup", careful)):
    problems = check(spec)
    print(f"{name}: {'start' if not problems else 'REFUSE'}")
    for problem in problems:
        print("  -", problem)

Output:

quick setup: REFUSE
  - use a microVM or gVisor for untrusted code
  - run as non-root
  - deny network or use an allowlist
  - make the system read-only
  - do not place secrets inside
  - do not mount host folders
  - set a memory limit
  - set a time limit
  - start fresh for every task
careful setup: start

The convenient setup fails nine rules. The checker treats a missing setting as unsafe, so a new field cannot slip through by omission. Its limits are example values. A checker of declarations also does not prove what is running; verify from inside a started sandbox that the network is closed and the paths are read only.

Expert Data, lifecycle and operations

Images and dependencies

The base image is part of the security boundary. Keep it small, build it from pinned versions, scan it and rebuild it when fixes appear. Remove tools that the task does not need. When an agent asks to install a package, it may choose a misspelled or invented name that an attacker has registered, and installation itself can run code. Offer an approved set, or resolve requests through a mirror that holds only reviewed packages. Record the image version with every execution so that you can reproduce a result and find which runs used an affected component.

State kept between steps deserves the same care as input files. Variables, installed packages and half-written outputs can change what later code does, so tell the agent when a session has been reset and keep important results as explicit files.

Network access

  • Start with none. Many analysis tasks need no connection.
  • If packages are needed, bake them into the image or use a controlled mirror.
  • Route other traffic through a proxy that allows named destinations and logs requests.
  • Block internal ranges and metadata addresses.
  • Remember indirect channels such as name lookups.

Secrets and privileged actions

Do not place credentials in the sandbox. If code must use a service, give it a narrow tool outside the sandbox that checks each request, or a proxy that adds credentials and limits operations. Remember that anything the code can ask the proxy to do, hostile code can ask too, so the proxy's rules are the real boundary.

Moving files in and out

StageControl
InputCopy only files the user may access and the task needs
DuringQuota on disk and file count
OutputCollect from one folder; check names, types and sizes; reject links
DeliveryScan; never execute outputs automatically on trusted machines
AfterDelete the environment; keep only what policy requires

Output files and printed text are untrusted. A generated page may contain scripts, a spreadsheet may contain formulas and printed text may contain instructions aimed at the model.

Lifecycle

Createfrom a fixed image
Loadcopy inputs
Runlimits enforced outside
Collectvalidate outputs
Destroyconfirm removal
Never reuse one user's environment for another.

Within one task, keeping a session alive can be useful for iterative work. Set an idle timeout and a maximum lifetime, and restore from approved inputs, not from an unknown previous state. Warm pools can shorten start-up if each unit is used once.

Returning results to the agent

Send back the exit status, whether a limit was hit, a bounded amount of standard output and error text, and a list of produced files. Mark truncation clearly. Keep the beginning and end of long error output, where the useful lines usually are. Tell the agent which limit stopped the program so that it can change approach, for example by processing a file in parts, and cap the number of attempts. A program that exits successfully may still have computed the wrong thing, so ask for checks such as row counts and totals, and test results that matter independently.

What to record

  • Who asked, which task, image version and configuration.
  • The code, subject to privacy and retention rules.
  • Exit status, duration and resource use.
  • Network requests and denials.
  • Files produced, with sizes and hashes.

Alert on blocked connection attempts, repeated limit hits and unusual process activity.

Test containment

Keep a suite that, from inside the sandbox, tries to read environment secrets, reach the internet and internal addresses, write outside the work area, exceed each limit and find leftovers from earlier runs. Every attempt must fail. Run it when images, runtimes or settings change. For high-risk deployments, ask security specialists to review and test the design. Lab: Least Privilege, Authentication and RBAC offers practice.

Illustrative example: the analysis assistant

A team lets users upload spreadsheets for analysis. Version one runs code on the application server, and a test prompt prints database credentials. They move execution to a microVM per request with no network and no secrets, copy in only the uploaded file, return charts after validation and add the containment suite to their release checks.

Do you need code execution at all?

If the same calculations recur, write them as ordinary tools. A fixed tool is cheaper, faster and far easier to secure. Offer free execution when the variety of tasks justifies the operating burden, and consider who will maintain images, apply patches and respond to alerts.

Operating cost and capacity

Isolation has a price in start-up time, memory and engineering attention. Measure how long a sandbox takes to become ready, how many run at the busiest time and how much sits idle. Set a limit per user and per organization so that one workload cannot starve the rest. When capacity runs out, queue with a visible wait instead of silently falling back to a weaker environment. That fallback rule matters: an emergency shortcut that runs code on an application server "just for now" removes every protection described here.

When something goes wrong

Plan the response before you need it. You should be able to switch code execution off without taking the whole agent down, stop all running environments, revoke any proxy access and find which users and files were involved. Preserve logs and, where practical, a snapshot of a suspicious environment before destroying it. Decide who investigates and who informs affected people. Afterward, add the behavior to the containment suite. Subscribe to security notices for your runtime, kernel and base images, and set a deadline for applying serious fixes, because an isolation boundary with a known flaw offers much less than it appears to.

Questions for a managed sandbox provider

Ask what isolates one customer from another, what network access is allowed by default, where code and files are stored and for how long, which regions are used, how limits are enforced and billed, how quickly flaws are patched and how you are told about incidents. Run your own containment suite against the service instead of relying only on its description.

Common mistakes

  • Running generated code on the application server.
  • Passing environment variables through.
  • Leaving the network open for convenience.
  • Mounting host or shared folders.
  • Reusing environments across users.
  • Trusting output files.
  • Enforcing limits only from inside the code.

Checklist

  • A threat model names what must be protected.
  • Isolation strength matches the risk.
  • No secrets or host mounts are present.
  • Network is denied or filtered.
  • Processor, memory, disk, process and time limits are enforced outside.
  • Inputs and outputs are controlled.
  • Environments are destroyed after use.
  • Containment tests run on every change.

Frequently asked questions

Are containers a sandbox?

They isolate processes but share the host kernel. Hardened containers can suit lower-risk code; use stronger isolation for hostile or multi-user execution.

Is a language-level sandbox acceptable?

Rarely as the only boundary in a general-purpose language. Put operating-system or virtual-machine isolation around it.

Should a person approve code before it runs?

For code with real access, often yes. Inside a well-contained sandbox with no side effects, review may be unnecessary.

How long should a sandbox live?

No longer than one task needs, with both an idle limit and a maximum age.

References and further reading

Next steps