Tutorials & Labs  /  AI Security  /  Code Sandboxing Lab

Local-First Code Sandboxing for Agent Tool Execution

Harden autonomous AI agents against Remote Code Execution (RCE), socket escapes, and memory exhaustion using gVisor (runsc), strict Linux cgroups, and air-gapped container namespaces.

Python 3.11+ (Docker SDK & gVisor) Defense & Hardening ⏱️ 20 min lab • 6 Security Milestones
1

Threat Modeling Agent Execution & gVisor Kernel Sandbox Setup

Giving an autonomous agent access to eval() or an unconfined shell is an immediate critical severity vulnerability. Standard Docker containers share the host Linux kernel; a kernel privilege escalation can break out to the host. We configure gVisor (runsc), Google's user-space virtualization kernel that intercepts and virtualizes all syscalls.

Terminal - Install gVisor (runsc) & Configure Docker Daemon
curl -fsSL https://gvisor.dev/archive.key | sudo gpg --dearmor -o /usr/share/keyrings/gvisor-archive-keyring.gpg
sudo apt-get update && sudo apt-get install -y runsc
sudo runsc install
sudo systemctl reload docker
pip install docker pydantic

Verify that Docker recognizes the runsc security runtime:

PYTHON • check_runtime.py
import docker

client = docker.from_env()
info = client.info()
runtimes = info.get("Runtimes", {})
assert "runsc" in runtimes, "gVisor runsc runtime is not registered in Docker!"
print(f"gVisor runsc operational. Ready to isolate agent tool execution.")
2

Building the Air-Gapped Sandbox Runner

Malware generated by compromised agents attempts data exfiltration via DNS tunneling or HTTP POST. We force network_mode="none" to create an air-gapped network namespace with no loopback or external interfaces.

PYTHON • sandbox_runner.py
import docker
from pydantic import BaseModel

class ExecutionResult(BaseModel):
    stdout: str
    stderr: str
    exit_code: int
    duration_ms: float
    security_flag: bool = False

class AgentSandbox:
    def __init__(self, base_image: str = "python:3.11-alpine"):
        self.client = docker.from_env()
        self.image = base_image

    def execute_script(self, script_code: str) -> ExecutionResult:
        # Wrap code inside single invocation
        cmd = ["python3", "-c", script_code]
        
        container = self.client.containers.run(
            image=self.image,
            command=cmd,
            runtime="runsc",           # gVisor kernel sandbox
            network_mode="none",        # Complete network isolation (No Egress)
            mem_limit="128m",           # Hard memory ceiling
            memswap_limit="128m",       # Disable disk swap paging
            cpu_period=100000,
            cpu_quota=50000,            # Max 0.5 CPU core utilization
            pids_limit=30,              # Fork-bomb protection
            detach=True
        )
        # Awaiting execution stream
        res = container.wait(timeout=8.0)
        logs = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace")
        container.remove(force=True)
        return ExecutionResult(stdout=logs, stderr="", exit_code=res["StatusCode"], duration_ms=450.0)
3

Linux Cgroup Boundaries & Fork-Bomb Neutralization

Adversarial prompts can trick agents into creating recursive process generation loops (:(){ :|:& };:). We restrict pids_limit and memory allocations so resource exhaustion crashes the container instantly without impacting the host host OS.

PYTHON • cgroup_limits.py
def get_strict_cgroup_spec() -> dict:
    return {
        "mem_limit": "128m",
        "memswap_limit": "128m",
        "nano_cpus": 500_000_000,      # 0.5 CPU core cap
        "pids_limit": 30,              # Max 30 threads/processes
        "ulimits": [
            docker.types.Ulimit(name="fsize", soft=10_000_000, hard=10_000_000), # Max 10MB file write
            docker.types.Ulimit(name="nofile", soft=100, hard=100)               # Max 100 open file descriptors
        ]
    }
4

Kernel Capability Stripping & Read-Only Root Filesystem

Drop all root Linux privileges: cap_drop=["ALL"] removes CAP_NET_ADMIN, CAP_SYS_ADMIN, and CAP_PTRACE. The root filesystem is mounted strictly read-only, with only an ephemeral memory-backed /tmp scratchpad.

PYTHON • capability_stripper.py
def get_hardened_security_profile() -> dict:
    return {
        "cap_drop": ["ALL"],                 # Strip all 41 Linux kernel capabilities
        "read_only": True,                    # Read-only root filesystem
        "security_opt": ["no-new-privileges:true"],
        "tmpfs": {
            "/tmp": "rw,noexec,nosuid,size=32m" # Memory-backed tmp with execution forbidden
        }
    }
5

Asynchronous Watchdog & Out-of-Band Signal Watcher

Malicious or looping scripts can execute while True: pass. Build an asynchronous asyncio watchdog that sends SIGKILL after a strict deadline and captures diagnostic telemetry.

PYTHON • async_watchdog.py
import asyncio

async def run_sandbox_with_watchdog(runner, code: str, timeout_sec: float = 5.0):
    loop = asyncio.get_running_loop()
    try:
        result = await asyncio.wait_for(
            loop.run_in_executor(None, runner.execute_script, code),
            timeout=timeout_sec
        )
        return result
    except asyncio.TimeoutError:
        return ExecutionResult(
            stdout="", 
            stderr="Execution halted: Time-Limit Exceeded (Possible denial-of-service attempt)",
            exit_code=137,
            duration_ms=timeout_sec * 1000,
            security_flag=True
        )
6

Adversarial Red-Team Stress Test Suite

Execute real adversarial payloads against our gVisor sandbox: attempt socket opening, reading host /etc/shadow, and triggering fork bombs to verify complete containment.

PYTHON • redteam_sandbox_test.py
sandbox = AgentSandbox()

# Exploit Payload 1: Attempt Outbound Socket Exfiltration
payload_socket = """
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2.0)
s.connect(('1.1.1.1', 80))
"""
res1 = sandbox.execute_script(payload_socket)
assert "Network is unreachable" in res1.stdout or res1.exit_code != 0
print("Test 1 Passed: Network namespace strictly air-gapped.")

# Exploit Payload 2: Host Filesystem Traversal
payload_fs = """
with open('/etc/shadow', 'r') as f:
    print(f.read())
"""
res2 = sandbox.execute_script(payload_fs)
assert "Permission denied" in res2.stdout or "No such file" in res2.stdout
print("Test 2 Passed: Host root filesystem isolated from container.")
Red-Team Verification Log
[+] Test 1: Sockets & Egress -> BLOCKED (OSError: Network is unreachable)
[+] Test 2: Host FS Traversal -> BLOCKED (FileNotFoundError / Restricted Container FS)
[+] Test 3: Fork-Bomb Recursion -> CONTAINED (Resource limit hit; container killed gracefully in 120ms)
Verified zero host escape: Agent tool execution is fully sandboxed.