commit b0cf56336ae5200801cf3a25c0c41cbf29439601 Author: sandbox Date: Thu Oct 15 12:56:24 2026 +0300 sandboxd render edition diff --git a/README.md b/README.md new file mode 100644 index 0000000..1899064 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Public exec-sandbox daemon for Render. diff --git a/__pycache__/sandboxd.cpython-314.pyc b/__pycache__/sandboxd.cpython-314.pyc new file mode 100644 index 0000000..ac25f6a Binary files /dev/null and b/__pycache__/sandboxd.cpython-314.pyc differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e503c35 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +stdlib only diff --git a/sandboxd.py b/sandboxd.py new file mode 100644 index 0000000..7c699dc --- /dev/null +++ b/sandboxd.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""sandboxd — exec sandbox daemon (Render edition). stdlib-only. +Env: PORT (injected), SANDBOX_KEY (secret). Per-uid workdirs under ./users/.""" +import json, os, subprocess, threading, time, secrets, shutil +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +PORT = int(os.environ.get("PORT", "10000")) +KEY = os.environ.get("SANDBOX_KEY", "") +BASE = os.path.dirname(os.path.abspath(__file__)) +USERS = os.path.join(BASE, "users") +os.makedirs(USERS, exist_ok=True) +BLOCK = ("rm -rf /", "rm -rf /*", "mkfs", "dd of=/dev", ":(){", "fork()", "shutdown", + "reboot", "halt -f", "kill -9 1", "chmod -R 777 /", "> /dev/sd", + "iptables -F", "useradd", "userdel", "passwd root", "/etc/shadow") +SEM = threading.Semaphore(3) +LOG = lambda *a: print(time.strftime("%H:%M:%S"), *a, flush=True) + + +def user_dir(uid): + d = os.path.join(USERS, str(int(uid))) + os.makedirs(d, exist_ok=True) + return d + + +def run_cmd(uid, cmd, timeout): + cmd = cmd or "" + cl = cmd.lower() + for b in BLOCK: + if b in cl: + return {"stdout": "", "stderr": "blocked: dangerous command", "exit": -1, "time_s": 0} + timeout = max(3, min(int(timeout or 60), 75)) + d = user_dir(uid) + script = os.path.join("/tmp", "sbx_%d_%s.sh" % (int(uid), secrets.token_hex(4))) + with open(script, "w", encoding="utf-8") as f: + f.write("#!/bin/bash\ncd %s || exit 9\nulimit -v 1500000 -u 96 -f 100000 2>/dev/null\n" % d) + f.write(cmd) + os.chmod(script, 0o700) + t0 = time.time() + try: + with SEM: + p = subprocess.run(["bash", script], capture_output=True, text=True, + timeout=timeout, cwd=d) + out, err, code = p.stdout, p.stderr, p.returncode + except subprocess.TimeoutExpired: + out, err, code = "", "timeout after %ss" % timeout, -2 + finally: + try: + os.remove(script) + except OSError: + pass + dt = round(time.time() - t0, 2) + # cleanup runaway user dirs >200MB + try: + sz = sum(os.path.getsize(os.path.join(r, x)) for r, _, fs in os.walk(d) for x in fs) + if sz > 200 * 1024 * 1024: + shutil.rmtree(d, ignore_errors=True) + err += "\n[user dir reset: quota 200MB]" + except OSError: + pass + return {"stdout": (out or "")[-6000:], "stderr": (err or "")[-2000:], "exit": code, "time_s": dt} + + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _json(self, code, obj): + b = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + if self.path == "/health": + self._json(200, {"ok": True, "ts": int(time.time()), "node": "render"}) + else: + self._json(404, {"error": "not found"}) + + def do_POST(self): + if self.path != "/exec": + return self._json(404, {"error": "not found"}) + if self.headers.get("X-Sandbox-Key", "") != KEY: + return self._json(403, {"error": "bad key"}) + try: + n = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(n) or b"{}") + except Exception: + return self._json(400, {"error": "bad json"}) + uid = body.get("uid") + try: + uid = int(uid) + except (TypeError, ValueError): + return self._json(400, {"error": "bad uid"}) + try: + self._json(200, run_cmd(uid, body.get("cmd", ""), body.get("timeout", 60))) + except Exception as e: + LOG("exec error:", repr(e)) + self._json(500, {"error": str(e)[:200]}) + + +if __name__ == "__main__": + LOG("sandboxd render starting on port", PORT, "keyset:", bool(KEY)) + ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever()