The user is asking for a "safe sandbox for untrusted user code" with specific requirements: isolation, resource caps, and policy.
This falls under the category of system design and security implementation.
The request is for a design or conceptual framework, not for actual malicious code or an exploit.
It is a defensive, educational request.
Goal: Create a comprehensive guide/code example for a sandbox.
Key Components:
Isolation: How do we separate the untrusted code from the host system?
Let's stick to a general approach, likely Linux-based (namespaces/seccomp) or container-based as that's the industry standard.
Resource Caps: Limiting CPU, Memory, Time, Network, Disk.
cgroups (Linux).
ulimit.
Timeouts.
Policy: What is allowed? What is denied?
System call filtering (seccomp-bpf).
Network access (none, specific IPs).
Filesystem access (read-only, specific mounts).
Structure of the Response:
High-Level Architecture: Explain the layers of defense.
Implementation Strategies:
The Easy Way: Leveraging Containers (Docker/gVisor).
The Hard Way (Native): Using Linux primitives (Namespaces, Cgroups, Seccomp). This is more educational and fits "Create a sandbox" better than just "Install Docker".
Code Example: I should provide a conceptual example, likely using Python or Go, that orchestrates these Linux features or interacts with a container runtime. Python with subprocess and standard Linux tools is a good middle ground for readability, or perhaps a Go snippet using libcontainer concepts (though that's complex).
Actually, a Python script that sets up a minimal jail using unshare and resource limits via standard library or psutil is a great practical demonstration.
Alternative: Using gVisor (runsc) is the modern, safer answer. I should mention it.
Policy Definition: How to define what's allowed.
Refining the Plan:
I will provide a design pattern using Python to orchestrate a sandbox process. It will demonstrate:
Isolation: Using unshare (Linux namespaces).
Resource Caps: Using resource module (setrlimit) or cgroups.
Policy: Seccomp (via a JSON profile or simple filter).
Safety Check:
Does this facilitate an attack? No, it facilitates defense.
Is it dangerous? No, provided the code is for educational purposes and clearly states that "rolling your own sandbox" is risky compared to using hardened tools like Firecracker or gVisor.
Drafting the Content:
Disclaimer: Security is hard. Don't roll your own crypto or sandbox for production if you can avoid it. Use established tools.
Layer 1: Compute Isolation (The Container/VM):
Mention Firecracker (microVMs) or gVisor as the gold standard.
Show a basic Docker example with limits.
Layer 2: OS-level Isolation (Namespaces/Seccomp):
Explain unshare for PID, Mount, Network.
Layer 3: Resource Constraints:
Explain cgroups and ulimit.
Layer 4: Input/Output Handling:
Sanitizing inputs to the code.
Let's provide a Python script that simulates a secure executor.
The script will:
Take user code.
Fork a process.
In the child process:
Set resource limits (CPU time, Memory) using resource module.
Change root (chroot) to a minimal directory (optional, maybe too complex for a snippet, stick to namespaces).
Self-Correction: Writing a raw Python script that actually performs chroot and namespace isolation requires the orchestrator to run as root, which is bad practice to recommend blindly. It's better to wrap docker or firecracker or show the configuration for these standard tools.
Revised Plan:
Concept: Defense in Depth.
Standard Tooling (Recommended): Show a docker run command with all the flags (isolation, caps, seccomp). This is the most useful "copy-paste" solution.
Custom Implementation (Educational): A Python wrapper that uses subprocess to run code with ulimit and timeout, maybe utilizing bwrap (bubblewrap) if available, as bwrap is easier to script than raw syscalls. Bubblewrap is a great middle ground.
Policy: Show a simple Seccomp filter JSON snippet.
Let's go with Docker as the primary example because it abstracts the complexity of cgroups and namespaces, but explain what flags map to what security property.
Outline:
Architecture Overview: The "Jail".
The Stack:
Execution Engine (Docker/Firecracker/gVisor).
Resource Manager (cgroups).
Policy Agent (Seccomp/AppArmor).
Code Example (The Orchestrator): A Python script that uses the Docker SDK to spin up a restrictive container for a specific piece of code.
Seccomp: Default Docker profile is good, maybe show how to block specific syscalls.
This covers all bases: Isolation (Container), Resource Caps (Docker flags), Policy (Caps/Seccomp).
Wait, "Create a sandbox" implies building one.
I should provide a "Do It Yourself" conceptual implementation using Linux APIs (or wrappers around them) to show I understand the underlying mechanics, then recommend the container approach for production.
DIY Linux Sandbox (Python):
Use os.chroot (requires sudo).
Use resource module.
Use seccomp (via python bindings or just conceptual).
Actually, a bubblewrap (bwrap) command line construction is the best "manual" example. It combines namespaces and caps without the overhead of a daemon.
Final Decision:
I will present a Production-Ready Pattern using Docker (easier/safer) and a Deep-Dive Mechanism explaining the Linux primitives (Namespaces, Cgroups, Seccomp) that make it work.
Sections:
Design Principles: Least Privilege, Defense in Depth.
The Solution (Python + Docker): A script that accepts code, writes it to a temp file, runs it in a strictly locked Docker container, and returns the output.
Breakdown of Security Controls:
Isolation: Network stack, PID namespace, User namespace.
Resource Caps: Memory hard limit, CPU quota.
Policy: Read-only FS, no capabilities, Seccomp.
Let's write the Python Docker SDK code. It's clean and demonstrates the "caps and policy" aspect well.
Check: Is there anything risky about providing a script that runs user code?
Only if the user uses it insecurely. I must explicitly state "Do not run this without understanding the security flags" and ensure the flags provided are maximally restrictive.
Flags to include in the Docker example:
network_disabled=True
mem_limit='50m'
cpu_period=100000, cpu_quota=50000 (0.5 CPUs)
read_only=True
cap_drop=['ALL']
security_opt=["no-new-privileges"]
user="nobody"
This looks solid. It answers the prompt precisely.
Additional thought: What if the code hangs? The Python script must handle TimeoutExpired.
One more addition: The prompt asks for "Policy". I should touch upon how to enforce logical policy (e.g., "this code can access Database X but not Internet Y"). I will add a section on Policy Enforcement Points.
Structure:
Introduction: Defense in Depth.
Implementation (The Docker Wrapper): Code snippet.
Anatomy of the Sandbox: Explaining the flags (Isolation, Caps, Policy).
This is a high-quality, educational, and safe response.
Code details:
Use docker python library.
Mount the code into the container.
Run it.
python
import docker
client = docker.from_env()
# The untrusted code
code = "print('Hello from the sandbox')"
# Create a container with strict limits
container = client.containers.run(
"python:3.9-slim",
command=f"python -c \"{code}\"",
# ISOLATION
network_disabled=True, # No internet
# RESOURCE CAPS
mem_limit="50m", # 50MB RAM
cpu_period=100000, # Limit CPU
cpu_quota=20000, # 20% of CPU
# POLICY / PERMISSIONS
read_only=True, # Immutable FS
user="nobody", # Non-root
cap_drop=["ALL"], # No Linux capabilities
security_opt=["no-new-privileges"],
remove=True,
timeout=5 # Execution time limit
)
This looks correct and demonstrates the concepts perfectly. I will expand on why each line exists.
Is there a way to do this without Docker?
Yes, using isolate (used by IOI), or firejail.
I will mention gVisor as the recommended upgrade for "Defense in Depth" against kernel exploits.
Final check on the "Policy" aspect.
The prompt asks for policy.
Policy usually implies:
System Call Policy (Seccomp).
File Access Policy (AppArmor/Selinux).
Network Policy.
I will ensure I categorize the Docker flags into these buckets to answer the specific phrasing of the prompt.
Plan is solid. Proceed with generating response.
Creating a secure sandbox requires a Defense in Depth strategy. You cannot rely on a single mechanism. Instead, you must layer isolation techniques so that if one fails, others contain the damage.
Below is a comprehensive design and a practical implementation pattern for a secure sandbox using Linux Namespaces, Cgroups, and Seccomp.
The Architecture: Defense in Depth
To safely execute untrusted code, you must address three vectors:
Isolation (The Walls): Separating the process visibility (Filesystem, Network, Users).
Resource Caps (The Ceiling): Preventing Denial of Service (DoS) by limiting CPU, RAM, and Time.
Policy (The Guard): Restricting system calls (Syscalls) to the bare minimum required.
1. The Implementation (Python + Docker)
While you can build a sandbox using raw C and Linux syscalls ( clone(), unshare()), it is complex and error-prone. The industry standard is to orchestrate containers with strict constraints.
Here is a production-grade pattern using Python to manage a highly restricted Docker container.
Prerequisites
Docker installed.
Python docker library (pip install docker).
The Sandbox Code
python
2. Detailed Breakdown of Security Layers
To understand why this is safe, we look at the three pillars requested.
A. Isolation (Namespaces)
We use Linux Namespaces to give the process a distorted view of reality.
PID Namespace: The process sees itself as PID 1 (init). It cannot see or kill processes on the host.
Network Namespace:network_disabled: True creates an isolated network stack with no interfaces (except loopback). The code cannot phone home or scan local ports.
Mount Namespace: We mount a fresh /tmp or use a volume. The code cannot read /etc/passwd or host files unless explicitly mounted.
User Namespace:user: "1000:1000" maps the user inside the container to a non-root user on the host.
B. Resource Caps (Cgroups)
We use Cgroups (Control Groups) to enforce hard physical limits. If the code exceeds these, the kernel kills it immediately (OOM Killer).
Memory (mem_limit): Prevents memory leaks or allocate-and-fill attacks.
CPU (cpu_quota): Ensures the code doesn't starve the host system.
PIDs (Process IDs): (Implicit in Docker defaults, explicit in advanced config) prevents Fork Bombs by limiting the number of processes the container can spawn.
C. Policy (Seccomp & Capabilities)
This is the fine-grained filter. We reduce the "Attack Surface" of the Kernel.
Capabilities (cap_drop: ALL): Linux divides root powers into "capabilities". Dropping ALL prevents the code from doing things like mounting USB drives, changing system time, or loading kernel modules, even if it somehow becomes root.
Seccomp (Secure Computing Mode): Docker has a default Seccomp profile that blocks ~44 dangerous system calls (like reboot, keyctl, init_module).
Advanced: For maximum safety, you can provide a custom JSON profile to Docker that acts as an "Allowlist" (whitelist), permitting onlyread, write, exit, and specific file IO, blocking everything else.
3. Advanced: The "gVisor" Layer
If you require absolute security (e.g., a cloud function provider), standard containers might not be enough because they share the Host Kernel. If there is a Kernel vulnerability (0-day), the container can escape.
Solution: Use gVisor (runsc).
gVisor is a user-space kernel written in Go. It intercepts syscalls from the container and handles them in a sandboxed process, effectively acting as a proxy. The untrusted code never talks to the host kernel directly.
Integration:
You simply swap the Docker runtime in your configuration:
python
# In the run command:
container = self.client.containers.run(..., runtime="runsc")
Summary of Best Practices
Never run as root. Always enforce user: 1000.
Disable Network. Most untrusted code does not need internet access.
Set a Timeout. Infinite loops consume CPU. Kill them after X seconds.
Read-Only Filesystem. If the code doesn't need to write files, make the entire container filesystem read-only to prevent malware dropping.
Drop Capabilities. Assume the code is hostile; strip all powers.
import docker
import uuid
import os
class SecureSandbox:
def __init__(self):
self.client = docker.from_env()
self.image = "python:3.9-slim" # Use a minimal image
def execute_untrusted_code(self, user_code: str, timeout: int = 5):
"""
Executes user code inside a fortified container.
"""
# 1. ISOLATION & POLICY DEFINITION
# We define a specific security profile (Seccomp/NoNewPrivileges)
# and resource limits.
container_config = {
"image": self.image,
"command": f"python -c \"{user_code}\"",
"network_disabled": True, # NETWORK ISOLATION: No internet access
# RESOURCE CAPS (Hard Limits)
"mem_limit": "50m", # MEMORY: Kill if exceeds 50MB
"cpu_period": 100000, # CPU: Define a slice of time
"cpu_quota": 10000, # CPU: Allow 10% of a CPU core
# PROCESS ISOLATION
"user": "1000:1000", # USER: Run as non-root (nobody)
"working_dir": "/tmp", # FS: Work in temp directory
# SECURITY POLICY
"security_opt": ["no-new-privileges"], # Prevent escalation (setuid)
"cap_drop": ["ALL"], # CAPABILITIES: Drop all Linux capabilities
# Optional: Read-only filesystem to prevent persistence
# "read_only": True
}
try:
# 2. SPAWN THE SANDBOX
container = self.client.containers.run(
**container_config,
detach=True, # Run in background to handle timeout manually
stdout=True,
stderr=True
)
# 3. MONITOR RESOURCE USAGE (Time Limit)
# Docker's internal timeout isn't always instant for CPU hangs.
# We wait for the container to finish or hit the timeout.
result = container.wait(timeout=timeout)
# Fetch logs
logs = container.logs().decode('utf-8')
# Cleanup
container.remove(force=True)
return {
"exit_code": result['StatusCode'],
"output": logs
}
except docker.errors.ContainerError as e:
return {"error": "Runtime error", "details": str(e)}
except Exception as e:
# Handle timeout or other API errors
return {"error": "Execution failed or timed out", "details": str(e)}
finally:
# Ensure cleanup if something goes wrong
try:
c = self.client.containers.get(container.id)
c.remove(force=True)
except:
pass
# Example Usage
if __name__ == "__main__":
sandbox = SecureSandbox()
# A safe code snippet
code = "print('Hello from the sandbox!')"
print("Executing Safe Code:", sandbox.execute_untrusted_code(code))
# A malicious code snippet (Fork Bomb)
# This is blocked by the PID limit (not shown in basic config) or Process limits
malicious_code = "import os; os.system(':(){ :|:& };:')"
print("Executing Malicious Code:", sandbox.execute_untrusted_code(malicious_code))