A lightweight library to run untrusted Python code
Pybox is a lightweight Python library for running untrusted Python code. It tries to offer a reasonable tradeoff between security and user-friendliness.
The untrusted code is executed in a protected Docker sandbox with (most) side-effects disabled. All I/O is passed as JSON via the standard input, standard output and standard error.
Main features:
- ✅ Protected Docker sandbox, offering protection against:
- code escape attempts
- fork bombs (pids_limit)
- memory abuse
- file system writes
- network exfiltration (if disabled)
- ✅ Optional gVisor integration for enhanced security (highly recommended)
- ✅ Optional fast mode with container pool (faster but less secure)
- ✅ Provides both a Python and a FastAPI interface
Pybox is designed so you can switch between a safe and fast mode:
| Mode | Behavior | Security | Performance |
|---|---|---|---|
| safe (default) | destroy container after each run | ⭐⭐⭐⭐⭐ | slower |
| fast | reuse warm containers | ⭐⭐⭐ | much faster |
Install Pybox with
pip install -e .
docker build -t pybox:latest pybox/docker/Optionally, follow these instructions to install [gVisor] for enhanced security against kernel exploits.
from pybox import Executor, Config
cfg = Config(timeout=3.0)
executor = Executor(cfg)
code = "result = x + y"
input = {"x": 2, "y": 3}
result = executor.run(code, input)
print(result)
{'status': 'ok', 'result': 5, 'errmsg': '', 'returncode': 0}Pybox includes also a convenient run() function
from pybox import RunError, run
code = """
import math
result = math.hypot(x, y)
"""
input = {"x": 3, "y": 4}
result = run(code, input, config={"timeout": 3.0})
print(result)
5.0Start the service
uvicorn pybox.api:app --reloadSend a request
curl -X POST http://localhost:8000/run \
-H "Content-Type: application/json" \
-d '{"code": "result = x + y", "input": {"x": 2, "y": 3}}'