How to sandbox AI agent code execution safely
Safely run AI-generated code in disposable, least-privilege sandboxes with file, network and resource limits plus approval for side effects.
In this guide
How do you safely run code generated by an AI agent?
Assume code, shell commands and scripts proposed by an AI agent are untrusted. The safest default is not to execute them. If a product genuinely needs code execution, run only an approved task inside a disposable sandbox separated from the application, customer data, host credentials and production network. OWASP classifies unexpected code execution as an agentic risk because an agent can turn a seemingly ordinary task into dangerous actions through generated code or tools.
Remove general-purpose command execution where possible
Offer narrow, purpose-built functions for common tasks instead of a shell. If users need computation, define the accepted language, packages, inputs, outputs and allowed operations. Do not expose a general command tool with the SaaS service account, production filesystem or unrestricted internet just because a model can generate commands; prompts and generated code are not reliable security boundaries.
Create a fresh, disposable sandbox for each job
Run work in an isolated environment with no host mounts, no Docker socket, no production secrets and no shared writable state between tenants. Use an unprivileged identity and a minimal, pinned runtime image. Standard containers can help isolate jobs, but many configurations still share the host kernel; drop unnecessary capabilities and select a stronger sandbox or virtual-machine boundary when the threat model requires it. Destroy the environment after completion, including temporary files and credentials. A language-level filter alone is not a sandbox.
Require a human gate for consequential side effects
Separate code evaluation from actions such as uploading, emailing, deleting, paying or modifying records. Show a person the exact proposed action and target, obtain appropriate confirmation, and then enforce authorization in the service that performs the action. A successful sandbox run or model explanation does not authorize a production change.
| Job type | Allowed inputs/files | Network policy | CPU/memory/time cap | Approval and cleanup |
|---|---|---|---|---|
What limits belong inside an agent code sandbox?
Make filesystem access explicit and temporary
Expose only the minimum input files and a designated output directory. Mount them read-only when possible, prevent path traversal and symlink escapes, and never mount host paths, credentials, source repositories or another tenant's workspace by default. Validate output size and type before it leaves the sandbox, and scan or encode it before another system consumes it.
Deny network access by default
Block outbound and inbound networking unless a narrowly defined task requires it. When network access is necessary, allowlist destinations through a controlled proxy, reject private and metadata address ranges, validate redirects and DNS resolution, and limit methods and response sizes. Do not let generated code fetch arbitrary URLs using the execution host's network privileges.
Set hard resource and concurrency budgets
Enforce wall-clock timeout, CPU, memory, process count, disk, file size, output bytes, system calls where available, and jobs per tenant. Kill the entire process tree at timeout and confirm cleanup; stopping only a parent process can leave child processes running. Use queue limits and cancellation so a loop or fork bomb cannot starve other customers or create unbounded provider and infrastructure costs.
How do you verify and operate code execution safely?
Separate sandbox control from sandbox workloads
Keep the orchestration service and credentials outside the untrusted execution environment. The sandbox should receive a short-lived job capability limited to that task, not reusable application secrets. Validate the job before launch and validate outputs after completion. Treat the sandbox's claim that a task succeeded as data that requires application-side checks.
Test escape and abuse cases before launch
Test attempts to read environment variables, traverse paths, access another tenant's files, spawn child processes, exhaust CPU or memory, open sockets, query cloud metadata, exploit package installation and return oversized or malicious outputs. Include image updates and runtime changes in regression testing. Use authorized security testing and keep production customer data out of test payloads.
Make cleanup and incident response observable
Record the job ID, tenant reference, approved runtime image, policy version, resource use, exit status and cleanup result. Avoid logging source code or sensitive inputs unless needed and protected. Alert on denied network attempts, repeated timeouts, unusual resource use and cleanup failures; provide an operator switch to stop new jobs and isolate the execution pool.
AI agent code sandbox FAQs
Is running generated Python with restricted built-ins a secure sandbox?
A language-level restriction alone is not a strong isolation boundary. If execution is necessary, use a disposable environment with operating-system or managed-platform isolation and explicit filesystem, network and resource limits.
Can the sandbox access production APIs with a service token?
Avoid reusable production credentials. If a specific API action is essential, issue a short-lived capability for that task and enforce tenant, object and operation authorization at the API boundary.
Should sandbox code have internet access to install packages?
Default to no network. If dependencies are needed, use reviewed, pinned artifacts from a controlled source rather than arbitrary package downloads during each customer job.
Does a container alone guarantee safe agent code execution?
No. Review the container runtime, kernel sharing, capabilities, mounts and network policy. Use an isolation boundary appropriate to the threat model, and test it on the actual execution platform.
Related practical guides
Related issue guides
Sources and publication record
Draft prepared 27 September 2026; engineering, security and editorial review pending · Sources checked .
- OWASP Top 10 for Agentic Applications 2026OWASP Gen AI Security Project
- Docker Engine securityDocker Documentation
- gVisor Security ModelgVisor Documentation
- LLM06:2025 Excessive AgencyOWASP Gen AI Security Project
- LLM05:2025 Improper Output HandlingOWASP Gen AI Security Project
- OWASP Server-Side Request Forgery Prevention Cheat SheetOWASP Foundation
- LLM10:2025 Unbounded ConsumptionOWASP Gen AI Security Project
- GenAI Red Teaming GuideOWASP Gen AI Security Project
- OWASP Cheat Sheet: LoggingOWASP Foundation
- Agent Control Standard (ACS)OWASP Gen AI Security Project
- OWASP Cheat Sheet: AuthorizationOWASP Foundation