Agent Security

Sandboxing AI Code Execution: Isolation and Network Controls

Design AI code execution with explicit isolation, restricted networks, bounded resources, controlled outputs, and secrets kept outside generated programs.

· · 8 min read

Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.

An AI agent that executes generated code needs a boundary that assumes the program can be wrong, hostile, or influenced by untrusted inputs. Asking the model to avoid dangerous commands is useful guidance, but the executor must independently decide which files, networks, credentials, and resources the program can reach.

This guide develops a hypothetical CSV-analysis service. A customer uploads transaction data, the agent writes Python to calculate a report, and the service returns a result file. The proposed limits and lifecycle are illustrative design choices, not a tested deployment recipe or a claim of complete isolation.

Define the assets before choosing the runtime

Start with what must remain protected: other customers' data, the host, service credentials, internal networks, and the availability of the execution fleet. Then identify what the program legitimately needs. Our CSV job requires its uploaded input, a fixed scientific-computing environment, temporary working storage, and an output channel. It does not need the production database, a cloud API token, or unrestricted internet access.

Define the boundary around a job rather than around a conversation. Two messages in the same chat may involve different datasets and authority. A reused execution environment can accidentally preserve an earlier file or credential even when the model's visible context has changed.

The gVisor security model explicitly separates reducing host attack exposure from controlling what a sandbox is intentionally permitted to access. A sandboxed application can still use exposed files and network connections; isolation does not make an overly broad architecture safe. gVisor security model.

For this service, write a capability inventory before implementation: read one immutable input object, create files inside a bounded workspace, and submit one candidate report. Treat anything outside that inventory as a separate request that needs a different execution policy.

Choose an isolation layer with explicit assumptions

Ordinary containers, application-kernel sandboxes, and virtual machines expose different interfaces and impose different compatibility costs. Avoid describing them as interchangeable settings on one security dial. Evaluate the actual runtime, host configuration, workload, and maintenance process.

Docker's seccomp documentation describes syscall filtering through an allowlist and advises retaining its default profile rather than running unconfined. This reduces available operations; it does not establish that arbitrary native code cannot exploit a vulnerability in a shared host kernel. Docker seccomp profiles.

An application-kernel approach can mediate the interface between a process and the host. A virtual-machine approach introduces a guest operating system and virtualized devices. Both still depend on correctly configured host services, exposed resources, and patching. Benchmark compatibility with the exact libraries used by the analysis workload instead of assuming an isolation choice is transparent.

Firecracker's production guidance requires the jailer or equally restrictive process constraints, recommends its restrictive seccomp configuration, and describes host and guest patching obligations. Using a microVM therefore includes operational work beyond booting a guest image. Firecracker production host setup.

In this hypothetical service, the engineering team would compare candidate runtimes using the same hostile-input tests and representative analysis jobs. Its decision record should name the threat model, supported system features, patch owner, and conditions that trigger reevaluation.

Separate trusted preparation from untrusted execution

A useful proposed lifecycle has four stages: prepare, execute, collect, and destroy. The trusted controller owns transitions and records the job identifier, tenant, input digest, image digest, policy version, and deadline. Generated code cannot modify that record.

Preparation copies the authorized input into a fresh workspace and starts from a pinned runtime image. The image contains the approved dependencies. Installing arbitrary packages during execution would add network access and another supply-chain path; a dependency request should instead produce a new, reviewed environment version.

Execution receives a narrow input mount and a separate writable directory. Do not mount the host home directory, service configuration, container-engine socket, or a general credential directory for convenience. A read-only mount prevents changes to that mount; it does not prevent its contents being read or copied into the output.

Collection treats every produced file as untrusted. Verify that a candidate output is a regular file beneath the designated output root, enforce a size limit, and apply the expected format parser. Reject links or paths that resolve outside the allowed tree. Validation must be race resistant: inspect and read the same file object rather than checking a path and reopening an attacker-replaced path later.

Destruction removes the environment and temporary storage according to the service's retention policy. Returning the worker to a pool before cleanup is complete creates an opportunity for a later job to observe residual material. For tenant propagation beyond execution, see multi-tenant agent isolation.

Make network access a capability, not a default

The CSV computation should begin without external network access. Docker documents that its none network driver creates only a loopback interface inside the container. That is a specific networking configuration, not proof that mounted sockets, inherited descriptors, or an allowed helper cannot communicate on the program's behalf. Docker none network driver.

If a job needs an external lookup, prefer a separate broker with a narrow operation, bounded response, and explicit destination policy. A request such as fetch_exchange_rate(date, currency_pair) is easier to constrain than a general-purpose URL fetcher carrying service credentials.

Enforce restrictions where traffic actually exits. A domain allowlist needs a policy for redirects, destination changes, private address ranges, and cloud metadata endpoints. Cover IPv4 and IPv6, direct-IP requests, alternate protocols, and DNS behavior. A sandbox with unrestricted DNS may still disclose information through queries even if other outbound connections are denied.

Firecracker's production document states that it does not filter guest network traffic itself and places filtering responsibility on the host. Runtime isolation and egress authorization therefore require separate evidence. Test the configured enforcement path, not merely the presence of a network-policy file.

Bound the job and its surrounding infrastructure

A timeout inside the generated program is insufficient because the program can ignore it. The external controller should enforce a wall-clock deadline and terminate the complete execution environment. Track cancellation through collection so a late report cannot be accepted after the job has been revoked.

Docker documents that containers have no resource constraints by default and explains the distinction between hard and soft memory limits. Selecting a container runtime does not automatically establish a CPU or memory budget. Docker resource constraints.

For the example service, consider these illustrative policy dimensions:

Resource Proposed control Failure outcome
Compute CPU allocation and an external deadline Stop and report a bounded execution failure
Memory Enforced hard limit, with defined swap policy Record memory exhaustion without claiming a valid result
Processes Process-count ceiling Reject additional process creation
Storage Workspace quota and output-size ceiling Stop writes before exhausting shared capacity
Output Bounded stdout, stderr, and artifact collection Truncate diagnostics with an explicit marker

Limit aggregate concurrency as well. A thousand individually bounded jobs can still exhaust a host, queue, or logging service. Admission control should reserve capacity before launching work and release it only after cleanup. Resource-limit failures should remain visible outcomes rather than being silently retried into a larger bill.

Keep secrets outside generated code

The simplest useful secret policy for the CSV job is to provide none. A model-generated script does not need the application's storage credentials merely to read an already staged input file.

Where an external action is necessary, keep credentials inside a trusted broker and authorize a particular operation. Scope grants to the job and expiry, limit the returned data, and revoke access when the job is canceled. Do not mistake a short-lived credential for a narrow credential: during its lifetime, its permissions still matter.

Also inspect indirect exposure. A copied configuration file, inherited environment variable, authenticated proxy, crash dump, or diagnostic response can reveal authority the intended interface never advertised. Build the job environment from an explicit allowlist rather than inheriting the controller's full process environment. The broader capability design belongs in least privilege for agent tools.

Walk through an attempted boundary violation

Suppose the hypothetical agent writes a CSV script that unexpectedly tries to access a host configuration path, connect to an internal service, and generate an oversized report. The desired outcome is three independent denials: the file is not exposed, the network path is unavailable, and the output quota prevents unbounded growth.

The controller records the execution outcome and bounded diagnostics. It does not grant broader permissions simply because the agent explains that the script needs them. If the task actually requires new data, the workflow returns to preparation with an explicit new capability decision.

Before deployment, run safe probes for absent files, denied destinations, excessive output, process limits, and deadline handling. Test cross-job cleanup using harmless tenant-specific markers. Verify host observations as well as process messages: a script printing “access denied” proves nothing about whether a request reached its destination.

Frequently asked questions

Is a container enough for arbitrary agent code?

That depends on the threat model and configuration. Evaluate the host boundary, privileges, mounts, network paths, resource controls, and patching. A container label alone is not an acceptance criterion.

Should code receive production credentials for convenience?

Prefer a trusted broker that exposes only the required operation. Direct credentials expand what compromised or mistaken code can do and complicate revocation, audit, and output handling.

Can a successful exit code prove the report is safe?

No. It shows how the process terminated. Validate output format, size, provenance, and task correctness separately, and keep artifact collection inside the same untrusted-output boundary.

Source reference list

AI Agent Security
Code Execution
Sandboxing
Network Security