Skip to content
BotServBotServ
SandboxingDockerIsolationSecurityCode Execution

Sandboxing for AI Agents

Secure sandboxing for AI agents. Docker, Firejail, gVisor isolation, safe code execution and practical examples.

S

schutzgeist

7 min read
Sandboxing for AI Agents

Sandboxing for AI Agents

What this article covers

  • How to run AI agents in sandboxed environments.
  • Available sandbox technologies: Docker, Firejail, gVisor, nsjail.
  • How to isolate code execution, filesystem access, and networking.
  • Real-world examples for code agents, file agents, and web agents.
  • Best practices for security, performance, and maintenance.

Introduction: Sandboxing for AI agents explained

AI agents that execute code, modify files, or send network requests pose significant risks. A compromised agent (through prompt injection) can execute malicious code, delete files, or exfiltrate data. Sandboxing means isolating the agent in an environment that has no access to the host system. If the agent does something harmful, the damage stays within the sandbox, leaving your server untouched.

This article is for developers building AI agents with code execution or system access capabilities. You should understand what AI agents are and how Docker works. For Python fundamentals, see IRC-Coding.de.

Why do you need sandboxing?

Imagine building a code agent that writes and executes Python code. The agent receives a task, generates code, and runs it. What if the agent (via prompt injection) writes malicious code? os.system("rm -rf /") would wipe your entire system. In a sandbox, nothing happens: the code runs isolated, and your host system stays safe.

Sandboxing for AI agents in brief

Sandboxing is isolating the agent in an environment with restricted access. The agent can execute code, but only within the sandbox. The filesystem, network, and processes are all isolated. If the agent behaves maliciously, only the sandbox is affected.

The core principle: the agent can do anything inside the sandbox, but nothing outside.

Who this article is for

  • Developers building code agents.
  • Security professionals responsible for hardening agents.
  • System administrators running agents in production.
  • Teams deploying agents with system access.

Prior knowledge of Docker, AI agents, and security fundamentals is expected.

Key terms

  • Sandbox - Isolated execution environment. Use case: safe code execution.
  • Docker - Container platform. Use case: most popular sandbox choice.
  • Firejail - Linux sandbox tool. Use case: lightweight isolation.
  • gVisor - Google’s sandbox for containers. Use case: additional security layer.
  • nsjail - Google’s sandbox tool. Use case: process-based isolation.
  • Isolation - Separation of agent and host. Use case: the security principle.
  • AI agents - What gets isolated. Use case: the subject.
  • Prompt injection - Agent manipulation. Use case: why sandboxing is necessary.
  • Tool permissions - Rights management. Use case: complements sandboxing.

Sandbox technologies compared

TechnologyIsolationPerformanceComplexityUse case
DockerContainerGoodMediumStandard sandbox
FirejailProcessVery goodLowLightweight isolation
gVisorKernelFairHighHigh security
nsjailProcessVery goodMediumProcess-based
VMFullPoorHighMaximum isolation

Docker as a sandbox

Docker is the most popular sandbox for AI agents. You create an image with Python and dependencies, then run your agent code in a container.

Dockerfile for a code agent

FROM python:3.12-slim

# Python dependencies
RUN pip install --no-cache-dir ollama requests

# Working directory
WORKDIR /workspace

# Non-root user
RUN useradd -m agent
USER agent

# Copy code
COPY --chown=agent:agent agent.py .

# No network (optional)
# CMD ["python", "agent.py"]

Running an agent in Docker

# Build the image
docker build -t code-agent .

# Start container with restricted privileges
docker run --rm \
  --network none \                    # No network
  --memory 512m \                     # Memory limit
  --cpus 1 \                          # CPU limit
  --read-only \                       # Read-only filesystem
  --tmpfs /tmp:size=100m \            # Temp directory
  --cap-drop ALL \                    # Drop all capabilities
  --security-opt no-new-privileges \  # Prevent privilege escalation
  -v ./workspace:/workspace:ro \      # Mount workspace read-only
  code-agent

Executing Python code in Docker

import subprocess
import tempfile

def execute_in_docker(code, timeout=30):
    # Save code to a temporary file
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(code)
        code_file = f.name

    # Run in Docker
    result = subprocess.run([
        "docker", "run", "--rm",
        "--network", "none",
        "--memory", "512m",
        "--cpus", "1",
        "--read-only",
        "--tmpfs", "/tmp:size=100m",
        "--cap-drop", "ALL",
        "--security-opt", "no-new-privileges",
        "-v", f"{code_file}:/code.py:ro",
        "python:3.12-slim",
        "python", "/code.py"
    ], capture_output=True, text=True, timeout=timeout)

    return {
        "stdout": result.stdout,
        "stderr": result.stderr,
        "returncode": result.returncode
    }

Firejail as a sandbox

Firejail is a lightweight Linux sandbox that isolates processes.

Installation

sudo apt install firejail

Running an agent with Firejail

# Run agent in isolation
firejail --noprofile --private-tmp --nosound --no3d \
  --net=none \
  --private=/tmp/agent-workspace \
  --rlimit-fsize=10485760 \    # 10MB file size limit
  --rlimit-nproc=10 \          # Max 10 processes
  python agent.py

Executing Python code with Firejail

import subprocess
import tempfile

def execute_in_firejail(code, timeout=30):
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(code)
        code_file = f.name

    result = subprocess.run([
        "firejail", "--noprofile",
        "--private-tmp",
        "--net=none",
        "--rlimit-fsize=10485760",
        "--rlimit-nproc=10",
        "python", code_file
    ], capture_output=True, text=True, timeout=timeout)

    return {
        "stdout": result.stdout,
        "stderr": result.stderr,
        "returncode": result.returncode
    }

gVisor for additional security

gVisor is Google’s sandbox that implements syscall filtering. It adds an extra security layer on top of Docker.

Installation

# Install gVisor
sudo apt install runsc

# Configure Docker for gVisor
sudo tee /etc/docker/daemon.json <<EOF
{
  "runtimes": {
    "runsc": {
      "path": "/usr/bin/runsc"
    }
  }
}
EOF
sudo systemctl restart docker

Running agents with gVisor

docker run --rm \
  --runtime=runsc \
  --network none \
  --memory 512m \
  code-agent

Practical example 1: Code agent with Docker

class DockerCodeAgent:
    def __init__(self, model="llama3.1"):
        self.model = model

    def execute_code(self, code, timeout=30):
        # Execute code in Docker
        result = execute_in_docker(code, timeout)
        return result

    def run(self, task):
        # Ask the model to write code
        code = call_ollama([
            {"role": "system", "content": "Schreibe Python-Code für die Aufgabe."},
            {"role": "user", "content": task}
        ])

        # Run code in sandbox
        result = self.execute_code(code)

        # Return result to the model
        if result["returncode"] == 0:
            return result["stdout"]
        else:
            return f"Fehler: {result['stderr']}"

Practical example 2: File agent with restricted filesystem

# Agent with read-only access to /data
docker run --rm \
  --network none \
  -v /data:/data:ro \           # Read-only
  --tmpfs /tmp:size=100m \       # Writable only in /tmp
  file-agent

Practical example 3: Web agent with restricted network

# Agent can only reach Ollama, not the internet
docker run --rm \
  --network agent-network \      # Custom network
  --network-alias agent \
  web-agent

# Configure network to only allow Ollama access
docker network create --internal agent-network
# Run Ollama on the same network
docker run --network agent-network -d ollama

Security guidelines

  • Never run as root: Always create a dedicated user for the agent.
  • Isolate the network: Grant network access only when necessary. Use --network none or internal networks.
  • Set resource limits: Configure memory and CPU limits to prevent resource exhaustion.
  • Use read-only filesystem: Add --read-only to prevent the agent from modifying files.
  • Drop capabilities: Use --cap-drop ALL to remove all Linux capabilities.
  • Prevent privilege escalation: Use --security-opt no-new-privileges.
  • Set timeouts: Implement timeouts to prevent infinite loops.
  • Enable audit logging: Log all sandbox calls. See Logging.
  • See also: Sandbox environments, Tool permissions.

Common pitfalls

  • No sandboxing used: Code runs directly on the host. High risk.
  • Running as root: Agent has unrestricted access. Can do anything.
  • No network isolation: Agent can exfiltrate data.
  • No resource limits: Agent can overload the host.
  • No timeouts: Infinite loops block the sandbox.
  • Sandbox not tested: Sandbox may have vulnerabilities. Test with malicious code.

Further reading

Key Takeaways:

  • Sandboxing isolates agents from the host system.
  • Docker is the standard sandbox, Firejail is lightweight, gVisor adds extra security.
  • Essential: never run as root, isolate the network, set resource limits, use read-only filesystems, set timeouts.
  • Code agents must always run in a sandbox.
  • Sandboxing alone is not enough: combine with tool permissions, prompt injection protection, and audit logging.

FAQ

What is sandboxing for AI agents?

Sandboxing isolates the agent in an environment with restricted access. The agent can execute code, but only within the sandbox. The filesystem, network, and processes are isolated.

Why do I need sandboxing?

AI agents that execute code are dangerous. A compromised agent (via prompt injection) can run malicious code. In a sandbox, the damage is contained because the agent has no access to the host system.

Which sandbox technology should I use?

Docker is the standard. Firejail is more lightweight. gVisor provides additional security. For maximum isolation, use VMs. The choice depends on your security requirements and performance constraints.

How do I use Docker as a sandbox?

Create a Docker image with Python and dependencies. Run the container with —network none, —memory, —cpus, —read-only, —cap-drop ALL, and —security-opt no-new-privileges.

What is Firejail?

Firejail is a lightweight Linux sandbox that isolates processes without Docker overhead. It works well for simple code execution scenarios.

What is gVisor?

gVisor is a sandbox from Google that runs as an additional security layer on top of Docker. It filters system calls and provides stronger isolation than raw containers.

How do I prevent network access?

With Docker, use —network none. If the agent needs to reach Ollama, create an internal Docker network containing only Ollama and the agent, but no internet connectivity.

How do I limit resources?

Use —memory for RAM, —cpus for CPU, and —rlimit-fsize for file sizes. Also set timeouts to prevent infinite loops from blocking the sandbox.

How do I build a code agent with sandboxing?

Have the model write code, execute it in Docker using all security flags, and return the output to the model. The agent can test code safely without putting the host at risk.

Is sandboxing enough by itself?

No. Combine sandboxing with tool permissions (control which tools the agent can access), prompt injection protection (prevent manipulation), and audit logging (maintain an audit trail).

References and Further Reading

Back to Blog
Share:

Related Posts