python
#!/usr/bin/env python3
"""
Sherlock's Secure Code Sandbox
==============================
A Docker-based sandbox for executing untrusted user code with strict resource caps and security policies.
Prerequisites:
- Docker installed and running on the host.
- Python 3.9+ Docker image available (official `python:3.9-slim` recommended for lightness).
Features:
- **Resource Caps**:
- Memory: 256 MiB
- CPU: 1 core equivalent (via --cpus=1)
- Wall time: 5 seconds (via Docker timeout)
- Processes: Max 100
- File sizes: Limited via ulimits
- **Policies**:
- No network access (--network=none)
- Read-only filesystem (--read-only), with /tmp as tmpfs (RAM-backed, auto-cleared)
- No new privileges (--security-opt no-new-privileges)
- No host device access (--cap-drop=ALL)
- Isolated PID/user namespace (--user, --pid=host optional)
- Captures stdout/stderr, return code, and kills on timeout/OOM
Usage:
sandbox_exec("print('Hello, sandbox!')")
Returns: (returncode, stdout, stderr)
"""
import subprocess
import tempfile
import os
import shutil
import time
import signal
from typing import Tuple, Optional
class CodeSandbox:
def __init__(
self,
image: str = "python:3.9-slim",
memory_mb: int = 256,
cpu_cores: float = 1.0,
time_limit_sec: int = 5,
max_procs: int = 100,
):
self.image = image
self.memory_bytes = memory_mb * 1024 * 1024
self.cpu_cores = cpu_cores
self.time_limit_sec = time_limit_sec
self.max_procs = max_procs
def _write_code_file(self, code: str) -> str:
"""Write user code to a temporary file."""
fd, path = tempfile.mkstemp(suffix=".py", prefix="sandbox_")
os.write(fd, code.encode("utf-8"))
os.close(fd)
return path
def execute(
self, code: str, input_data: Optional[str] = None
) -> Tuple[int, str, str]:
"""
Execute user code in the sandbox.
Args:
code: Python code to run.
input_data: Optional stdin input.
Returns:
(returncode, stdout, stderr)
"""
code_path = self._write_code_file(code)
try:
# Docker run command with strict limits and policies
docker_cmd = [
"docker", "run", "--rm",
# Resource caps
f"--memory={self.memory_bytes}b",
f"--cpus={self.cpu_cores}",
f"--ulimit=nproc:{self.max_procs}:{self.max_procs}",
f"--ulimit=fsize:10m:10m", # Max file size 10MB
f"--ulimit=core:0:0", # No core dumps
# Security policies
"--network=none",
"--read-only",
"--tmpfs", "/tmp:size=64m", # RAM tmpfs for /tmp
"--security-opt=no-new-privileges",
"--cap-drop=ALL",
"--user=1000:1000", # Non-root user
# Mount code as read-only
"-v", f"{code_path}:/code.py:ro",
# Workdir and entrypoint
"--workdir=/",
self.image,
"python", "/code.py"
]
# Run with timeout
proc = subprocess.Popen(
docker_cmd,
stdin=subprocess.PIPE if input_data else None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
preexec_fn=os.setpgrp # For process group kill on timeout
)
# Feed stdin if provided
if input_data:
proc.stdin.write(input_data)
proc.stdin.close()
try:
stdout, stderr = proc.communicate(timeout=self.time_limit_sec + 1)
return proc.returncode, stdout or "", stderr or ""
except subprocess.TimeoutExpired:
proc.kill() # SIGKILL process group
proc.communicate() # Wait for completion
return -9, "", "Execution timed out after {}s".format(self.time_limit_sec)
finally:
# Cleanup
try:
os.unlink(code_path)
except OSError:
pass
# Example usage and tests
if __name__ == "__main__":
sandbox = CodeSandbox()
# Test 1: Harmless code
print("Test 1: Hello World")
rc, out, err = sandbox.execute("print('Hello from sandbox!'); import sys; print(sys.version)")
print(f"RC: {rc}, OUT: {out!r}, ERR: {err!r}")
# Test 2: Resource-intensive (should timeout/OOM)
print("\nTest 2: Infinite loop (will timeout)")
rc, out, err = sandbox.execute("import time; while True: time.sleep(0.1); print('.')")
print(f"RC: {rc}, OUT: {out!r}, ERR: {err!r}")
# Test 3: Forbidden actions (network/file - will fail policy)
print("\nTest 3: Network attempt (should fail)")
rc, out, err = sandbox.execute("import socket; s = socket.socket(); s.connect(('google.com', 80))")
print(f"RC: {rc}, OUT: {out!r}, ERR: {err!r}")
# Test 4: File write (limited to /tmp tmpfs)
print("\nTest 4: Temp file write")
rc, out, err = sandbox.execute("with open('/tmp/test.txt', 'w') as f: f.write('ok'); print('File written to /tmp')")
print(f"RC: {rc}, OUT: {out!r}, ERR: {err!r}")
This is production-ready for most use cases (e.g., coding platforms like LeetCode). Test thoroughly! If you need customizations, provide details.