"""01 DOCKER SANDBOX. Run an untrusted code string inside a throwaway Docker container. No network, capped memory, container gone the moment it's done. This is the box. Run: python 01_docker_sandbox.py Needs: Docker installed and running. If Docker is missing, this prints what it WOULD do and exits 0. It never fakes output. """ import shutil import subprocess import sys IMAGE = "python:3.11-slim" UNTRUSTED_CODE = "print('hello from inside the box'); print(2 + 2)" def have_docker() -> bool: return shutil.which("docker") is not None def run_in_sandbox(code: str) -> str: """Run `code` inside a fresh, network-less, memory-capped container. Container is removed automatically (`--rm`) the instant the process exits.""" cmd = [ "docker", "run", "--rm", "--network", "none", # no internet from inside the box "--memory", "256m", # cap how much RAM the box can grab "--cpus", "0.5", IMAGE, "python3", "-c", code, ] result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) return result.stdout.strip() or result.stderr.strip() def main(): if not have_docker(): print("Docker not found on this machine.") print("What this script WOULD do:") print(f" docker run --rm --network none --memory 256m {IMAGE} python3 -c \"{UNTRUSTED_CODE}\"") print("Install Docker Desktop (or the docker CLI) and re-run to see it live.") sys.exit(0) print("== UNTRUSTED CODE ==") print(UNTRUSTED_CODE) print("\n== RUNNING INSIDE A THROWAWAY CONTAINER ==") try: output = run_in_sandbox(UNTRUSTED_CODE) print(output) except subprocess.TimeoutExpired: print("Sandbox timed out after 60s (that's the timeout working as intended).") sys.exit(1) print("\nContainer is already gone. Nothing from that run touched your host.") if __name__ == "__main__": main()