The user wants a design for a sandbox to run untrusted user code.
The key requirements are:
- Isolation: Keeping the host system and other users safe.
- Quotas: Limiting resource usage (CPU, memory, time, I/O).
- Policy: Defining what the code is allowed to do (filesystem access, networking, syscalls).
High-Level Strategy:
A sandbox design isn't a single technology; it's a layered architecture. I should structure the answer by moving from the "hardest" security (virtualization) to "softest" (language-level), and then cover the cross-cutting concerns of quotas and policy.
Layer 1: The Execution Environment (Isolation)
- Option A: Virtual Machines (VMs). Strongest isolation. Firecracker, gVisor (conceptually similar).
- Option B: Containers (Namespaces/Cgroups). Standard industry approach. Docker, runC. Weaker than VMs but faster.
- Option C: System Call Filtering/Seccomp. A mechanism inside containers/processes.
- Option D: Language Runtimes (Sandboxing within the process). V8 (Node.js/Chrome), Luau, JVM SecurityManager (deprecated, maybe mention it's not enough alone).
Decision: I will propose a "Defense in Depth" approach.
- Outer Layer: Lightweight VM (Firecracker) or Container (gVisor).
- Middle Layer: OS-level user namespace + Seccomp.
- Inner Layer: Language-level restrictions.
Layer 2: Resource Management (Quotas)
How do we stop infinite loops or memory leaks?
- CPU/RAM: Cgroups (Linux) or VM configuration.
- Time: Timeout alarms (SIGALRM) or watchdog processes.
- Disk/Network I/O: Cgroups or Traffic Control (tc).
Layer 3: Access Control (Policy)
What can the code actually touch?
- Filesystem: OverlayFS (read-only base + writable temp layer), Chroot, or explicit allow-lists.
- Networking: Network Namespaces (no network vs. restricted network vs. full internet). IPTables/Proxies.
- Syscalls: Seccomp-bpf filters (allow read/write, forbid
reboot or module_load).
Structure of the Response:
- Executive Summary: Defense in depth is key.
- Architectural Layers (The "Onion" Model):
- Layer 1: Boundary Enforcement (Isolation) -> VMs vs. Containers.
- Layer 2: Resource Constraints (Quotas) -> Cgroups, throttling.
- Layer 3: Capability Control (Policy) -> Seccomp, Filesystem, Network.
- Detailed Design Choices (Trade-offs):
- Scenario A: High Performance (Containers + gVisor/Kata).
- Scenario B: Maximum Security (MicroVMs like Firecracker).
- Implementation Components (Linux Specifics):
- Namespaces (PID, NET, MNT, UTS).
- Cgroups (v2 preferred).
- Seccomp.
- User namespaces (root inside, non-root outside).
- The Control Loop (The "Warden"):
- How to start/stop/monitor the sandbox.
- Handling timeouts (the "kill -9" problem).
- Language-Specific Considerations: (V8 isolates, etc.)
Refining the Content:
- Isolation: I need to mention gVisor (runsc) because it provides a userspace kernel, effectively isolating the host kernel from the untrusted code. This is often better than standard Docker for untrusted code.
- Quotas: Need to distinguish between "Wall Clock Time" (timeout) and "CPU Time" (cycles).
- Policy: I should introduce a JSON/YAML policy definition concept. e.g.,
allow_net: false, fs_ro: ["/app"].
Drafting the Design - Step-by-Step:
- Intro: Acknowledge the risk. Assume Linux host (standard for this).
- The "Hardware/Virtualization" Layer: Use Firecracker microVMs or Kata Containers. Why? Kernel isolation is the hardest barrier. If the host kernel has a 0-day, the container escapes. A VM stops that.
- The "OS/Process" Layer: If VMs are too slow, use
gVisor. It intercepts syscalls.
- The "Resource" Layer: Cgroups. Limit memory to OOM kill if exceeded. Limit CPU to throttle.
- The "Input/Output" Layer:
- Network: Use a virtual ethernet pair (veth). Route through a proxy or just drop packets.
- Disk: Empty directory mounted as
/tmp. Root FS mounted Read-Only.
- The "Communicator": How does user code talk to the host? gRPC/Stdin-Stdout over a socket.
Self-Correction/Review:
- Is this too abstract? I should provide concrete Linux examples (e.g.,
clone(), unshare, seccomp).
- Did I cover "Policy"? I need to explicitly define what a "Policy Engine" looks like.
- What about Fork bombs? Restrict PIDs in cgroups.
Final Polish:
Organize into:
- Architecture Overview (The Diagram description).
- Isolation Strategy (The container/VM debate).
- Resource Quotas (The Limits).
- Security Policy (The Rules).
- The Execution Lifecycle (How to run it).
Let's write it out.
Designing a sandbox for untrusted code requires a "Defense in Depth" approach. You cannot rely on a single mechanism. Instead, you must layer isolation strategies so that if one layer fails, the next contains the breach.
Below is a comprehensive design for a secure sandbox architecture, focusing on Isolation (where it runs), Quotas (how much it uses), and Policy (what it is allowed to do).
1. High-Level Architecture
We will design a Micro-VM / Container Hybrid Architecture.
- Why? Containers (Docker) are fast but share the host kernel (riskier). Virtual Machines (VMs) are secure but heavy.
- The Solution: Use lightweight micro-VMs (like Firecracker or gVisor) to provide hardware-level isolation with near-container speed.
The Components:
- The Controller: The API that receives user code and configuration.
- The Scheduler: Decides which physical host receives the job.
- The Worker Node: A physical server running a Linux OS, stripped of all non-essential packages.
- The Sandbox Instance: A transient micro-VM executing the user code.
2. Isolation Strategy
Goal: Ensure that even if the user code is malicious (e.g., an exploit or a worm), it cannot access the host system, other users' data, or the network.
Layer A: Compute Isolation (The Boundary)
Do not run code directly on the host kernel.
- Technology: Firecracker (used by AWS Lambda) or gVisor.
- Mechanism: These tools create a lightweight VM with a reduced Linux kernel. The user code runs inside this VM.
- Benefit: The untrusted code has its own kernel. If it exploits a kernel bug, it is trapped inside the micro-VM and cannot access the underlying host hardware or kernel.
Layer B: User Isolation (The Identity)
Inside the micro-VM, strict namespace isolation is applied:
- PID Namespace: The code cannot see processes outside its sandbox.
- Mount Namespace: The code gets its own filesystem root. It cannot see the host's files.
- User Namespace: The code runs as
root inside the sandbox, but maps to an unprivileged user (UID 65534) on the host.
C: Filesystem Isolation
The sandbox should not have a persistent disk.
- Root Filesystem: A read-only SquashFS image containing only the necessary runtime (e.g., Python stdlib, Node binaries).
- Writable Layer: A temporary
tmpfs (RAM disk) mounted at /tmp. When the execution finishes, the RAM is wiped. No data leaks to disk.
3. Resource Quotas (DoS Prevention)
Goal: Prevent a single user from monopolizing resources (Fork bombs, Crypto miners, Memory leaks).
We enforce quotas at two levels: The Hypervisor (Hard Limits) and the OS (Throttling).
CPU
- vCPU Limit: Assign strictly 1 or 2 virtual CPUs to the micro-VM.
- CFS Quota (Inside VM): Use Linux Cgroups v2. Set
cpu.max to limit the CPU time slice.
- Example: 100ms of CPU time every 1000ms (effectively 10% of a core).
Memory
- Virtual Memory Limit: Set the VM memory to a hard cap (e.g., 256MB).
- OOM Killer: Enable the kernel's Out-Ofemory killer. If the process exceeds the limit, the kernel immediately kills it.
Time (Execution Duration)
This is the most critical quota for serverless code.
- Mechanism: The Controller sets a "Time-to-Live" (TTL) for the sandbox.
- Enforcement: A watchdog process runs outside the sandbox. If the code runs longer than
X seconds (e.g., 5 seconds), the watchdog sends a SIGKILL to the VM process and terminates it immediately.
I/O & Disk
- IOPS Throttling: Use Linux
blkio cgroups to limit read/write operations per second to prevent disk saturation.
- Disk Size: The
tmpfs writable layer is mounted with a size limit (e.g., size=64M).
4. Security Policy
Goal: Define what the code is allowed to communicate with.
We define this using an Allow-List Deny-All model. Anything not explicitly permitted is blocked.
A. Seccomp (System Calls)
We use seccomp-bpf filters to forbid dangerous system calls.
- Forbidden:
reboot, mount, umount, kexec_load, init_module, ptrace.
- Allowed: Standard IO, network socket calls, memory management.
- Result: Even if the user has "root" in the container, they cannot crash the kernel or load malicious drivers.
B. Networking Policy
The default state should be No Network.
- Scenario 1 (Pure Compute): The VM has no virtual network interface card (NIC). It is physically impossible for the code to access the internet.
- Scenario 2 (API Access): If the code needs to fetch data:
- Assign a private IP only.
- Egress Filtering: Use IPTables to block all traffic except destination port 443 (HTTPS) and only to specific IP ranges (e.g., your database or public APIs).
- Ingress Filtering: Block all incoming connections.
5. Implementation Example (Workflow)
Here is the lifecycle of an execution request:
- Request: User sends
print("Hello") (Python).
- Validation: Controller validates JSON input and checks user permissions.
- Scheduling:
- A free Firecracker micro-VM is assigned.
- The Python code is injected via a generic input file (mounted as read-only).
- Enforcement:
- Policy: Seccomp profile is loaded into the VM kernel.
- Quotas: Cgroups applied (CPU: 0.5 cores, Mem: 128MB).
- Network: NIC is detached.
- Execution:
- The Python interpreter starts.
- It reads the input file.
- It executes the code.
- Monitoring:
- The Watchdog monitors the PID. If execution time > 3000ms, force kill.
- Cleanup:
- The process exits.
- The Firecracker VM is destroyed immediately.
- The
tmpfs is discarded.
- Logs (stdout/stderr) are captured and sent back to the user via a secure channel.
Summary of Defense Layers
| Layer | Mechanism | Purpose |
|---|
| Hardware | Micro-VM (Firecracker) | Prevents kernel exploits from touching the host. |
| OS | Namespaces & Chroot | Prevents process visibility and file access. |
| Kernel | Seccomp | Prevents dangerous syscalls (e.g., mount). |
| Resource | Cgroups & Limits | Prevents Fork Bombs and Memory Exhaustion. |
| Network | IPTables / No NIC | Prevents C2 communication (botnets) or data exfiltration. |
| Lifecycle | Watchdog Process | Prevents zombie processes and infinite loops. |