Process Sandboxing & Subprocess Resource Limits
Executing untrusted code or background jobs risks resource exhaustion attacks. Python's `resource.setrlimit()` enforces OS-level quotas on CPU time, virtual memory (`RLIMIT_AS`), and file descriptors (`RLIMIT_NOFILE`), shutting down rogue processes before they compromise the host 🛡️📦.
import subprocess
import resource
def set_sandbox_limits():
# Cap child process to 2 seconds CPU and 128 open files:
resource.setrlimit(resource.RLIMIT_CPU, (2, 2))
resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128))
# Execute untrusted script inside constrained child process:
result = subprocess.run(
["python3", "-c", "import resource; print(resource.getrlimit(resource.RLIMIT_CPU))"],
preexec_fn=set_sandbox_limits,
capture_output=True,
text=True
)
print(f"Child CPU Limits: {result.stdout.strip()} 🚀")
# 73. Process Sandboxing & Subprocess Resource Limits If you build an online code execution engine, plugin runner, or async background job worker, a user could execute `while True: pass` (100% CPU lock) or a fork-bomb to crash the entire production server 🛑. ```python # The Malicious Script Problem: # - Infinite while loops monopolize CPU cores. # - Memory leaks trigger kernel Out-Of-Memory (OOM) killer on primary databases. # - Unbounded file descriptors exhaust Linux system table. ``` ### The POSIX Resource Limiting Architecture 1. **`RLIMIT_CPU`**: Maximum CPU time in seconds. When exceeded, the OS sends `SIGXCPU`, giving the process a chance to flush state, followed by immediate termination via `SIGKILL`. 2. **`RLIMIT_AS` (Address Space)**: Maximum bytes of virtual memory. Any `malloc` or memory page allocation beyond this quota raises `MemoryError`. 3. **`preexec_fn` Hook**: Runs inside the child process after `fork(2)` but before `execve(2)`. This sets hardware restrictions on the child without affecting the parent Python runtime 🛡️📦. --- ### Interactive Pop-Quiz 🧠 #### What operating system signal does the Linux kernel send to a sandboxed process that exceeds its RLIMIT_CPU quota? - [ ] `SIGXCPU` (followed by `SIGKILL` if execution continues) 🛑 - [ ] `SIGTERM` - [ ] `SIGINT` - [ ] `SIGHUP` --- ### Practical Challenge 🎯 Using `subprocess.run()`, spawn a child process running `python3 -c "import resource; print(resource.getrlimit(resource.RLIMIT_CPU)[0])"`. In `preexec_fn`, restrict CPU to `(3, 3)`. Capture the output, assert that `'3'` is printed, and print `'SANDBOX_VERIFIED'`. <details> <summary>Solution</summary> ```python import subprocess import resource def sandbox_hook(): resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) res = subprocess.run( ["python3", "-c", "import resource; print(resource.getrlimit(resource.RLIMIT_CPU)[0])"], preexec_fn=sandbox_hook, capture_output=True, text=True ) assert res.stdout.strip() == "3" print("SANDBOX_VERIFIED") ``` </details>