Lightweight, non-root, filesystem-focused Linux sandboxing via bubblewrap.
simple-sandbox is a wrapper around bubblewrap (bwrap). It builds a minimal execution environment with a read-only host filesystem, fresh /proc and /dev, a private /tmp, and a per-workdir private writable $HOME, then runs commands inside it. The sandbox is a per-working-directory daemon: several processes may run in it at once, and it closes only when the last one finished.
Without any configuration, simple-sandbox provides:
- A read-only view of the host filesystem.
- A writable invocation working directory.
- A private writable
$HOME. - Fresh
/procand/dev. - A private
/tmp. - The host network unchanged.
Configuration is optional and exists only to extend this baseline with path-specific policies and environment filtering.
- Multi-process sandbox — the first invocation creates the sandbox and runs its command inside it; later invocations from the same working directory automatically attach to the running sandbox. Each invocation returns as soon as its own command finishes; the sandbox itself lives until the last user process — including orphaned descendants of finished commands — is gone (see Sandbox lifecycle).
- Namespace isolation — separate PID, mount, IPC, UTS, cgroup and user namespaces (
--unshare-all), with a supervisor as the sandbox's reaper and job parent. - Read-only host filesystem —
/is mounted read-only by default. Only the working directory and paths explicitly exposed by policy may modify the host filesystem. - Fresh
/procand minimal/dev— the sandbox gets its own procfs and a newly created minimal device tree instead of the host mounts. - Private
/tmp— a fresh tmpfs, plusTMPDIR=/tmpfor predictable temporary-file behavior. - Host runtime isolation —
/runand/var/runare replaced with empty tmpfs mounts, so host system D-Bus, journald and container-runtime sockets are not reachable. The target of/etc/resolv.confis re-exported read-only so name resolution keeps working; other runtime paths are opt-in via path policies. - Writable working directory — the invocation working directory is bind-mounted read-write from the real project path by design, even when that path lives inside
$HOME(its destination then resolves inside the private home). Exceptions: when the working directory is$HOMEitself, no extra bind is added (the private home already provides the writable cwd); a working directory equal to/is rejected because root cannot be made writable, and a$HOMEof/is rejected because the real home cannot be hidden. - Per-workdir private writable
$HOME— a private bind-mount directory under the sandbox state root hides the real home for the lifetime of the sandbox. Writes inside the sandbox home never reach the real home, sub-path policies under$HOMEstill work, and an explicit policy on$HOMEitself cannot re-expose the real home. - Interactive attaches — a client attached from a terminal gets a real pseudo-terminal inside the sandbox (line editing, Ctrl-C to the job, window-size updates). Non-terminal clients keep their pipes/socket fds:
simple-sandbox catreads your stdin, and exit codes (including the128+signalconvention) propagate to the caller. Terminal streams are never silently truncated: partial writes are completed on both sides, and the supervisor buffers each direction up to 1 MiB, pausing the producer instead of blocking its event loop, so a slow or stalled terminal throttles only its own job. - Configurable path policies — optional
hide,readonly,exposeandoverlayrules for individual paths. - Hierarchical path policies — parent paths are applied before child paths, allowing narrow exceptions inside broader rules without depending on configuration order.
- Environment allowlist — jobs start from an empty environment; only
PATH,TERM,LANG,LC_*locales and names listed inkeepare re-exported, so credentials such asGITHUB_TOKENorAWS_*never reach a job by default.HOME,TMPDIRandXDG_RUNTIME_DIRare always set to canonical sandbox values, and an optionalunsetlist subtracts names afterwards. The environment is a creation-time snapshot: jobs started by later attaches run with the environment of the invocation that created the sandbox, keeping behavior deterministic. - Crash-tolerant — if the supervisor dies, every sandboxed process dies with it (the PID namespace collapses); the next invocation detects the stale state and recreates the sandbox. A dead client never harms its job's sandbox:
SIGINT/SIGTERM/SIGHUPare forwarded to the job like a terminal would (the client keeps waiting and reports the job's real status), while a crashed orSIGKILLed pipe-mode client simply detaches the job. - Trusted launcher — the launcher is a single Python file with a pinned
#!/usr/bin/python3shebang, so the interpreter is never resolved throughPATH;bwrapis resolved to a canonical absolute path before use and rejected if it resides in the working directory or carries setuid. The in-sandbox supervisor and the attach client are ordinary functions in the same file, selected by a namespaced--simple-sandbox-*role marker; the file is bind-mounted read-only at its own path so the roles can execute it, withpython3 -I -S(isolated interpreter: no site-packages, no environment-driven import paths). The whole codebase is one plain-Python file — no embedded source strings. - Runtime validation — verifies bind-mount support and, only when the
overlaypath policy is used, overlay support; validatesXDG_RUNTIME_DIRownership and permissions; refuses symlinked state paths; creates private runtime state with0700permissions; checksSO_PEERCREDon every supervisor connection. - Strict policy validation — configuration is strictly validated; invalid paths, conflicting rules, attempts to apply policies to
/, and malformed environment variable names abort startup. - Zero privileges — everything runs as the invoking user. No root privileges and no setuid
bwrap. Nobody is root inside the sandbox either:bwrapidentity-maps the user's uid, which is exactly why attaching from outside the namespace requires the in-sandbox supervisor (plainnsenteris refused by the kernel for this mapping).
simple-sandbox resolves every external tool it invokes to a canonical absolute path during startup and aborts if a required dependency is missing or resides inside the working directory.
| Dependency | Purpose |
|---|---|
/usr/bin/python3 |
The interpreter for the launcher, the in-sandbox supervisor and the attach client (Python ≥ 3.8, standard library only). Pinned via the #!/usr/bin/python3 shebang, never resolved through PATH. |
bwrap |
Sandbox engine; must support --bind, plus --overlay-src for the optional overlay path policy, and must not be setuid. |
That is the whole trusted chain: JSON handling, hashing, canonicalization, locking and process supervision are Python standard library. For tests only: bats, bwrap, and script(1) (optional, for the pty checks).
Note:
bwraprequires Linux user namespaces (typically enabled by default viakernel.unprivileged_userns_clone).
git clone https://github.com/disafronov/simple-sandbox.git
cd simple-sandbox
chmod +x simple-sandboxInstall anywhere in your PATH, for example:
install -m 0755 simple-sandbox ~/.local/bin/simple-sandboxNo build step is required. If your distribution has no /usr/bin/python3, point the shebang at your interpreter or install the compatibility symlink.
simple-sandbox command [args...]
simple-sandbox accepts a command followed by its arguments.
The current working directory becomes the writable project directory inside the sandbox. If a sandbox for this working directory is already running, the command is executed inside the existing one instead of creating a new one.
The wrapper does not interpret the command's arguments as its own options. They are forwarded unchanged after the -- separator.
Examples:
# Interactive shell (starts the sandbox, or joins the running one)
simple-sandbox bash
# Build in the current directory
simple-sandbox make test
# From another terminal while the build is still running:
simple-sandbox less build.log # attaches to the same sandbox
# Pipe-friendly one-shots
make | simple-sandbox grep -c errorA sandbox is a per-working-directory daemon, deliberately detached from any single invocation:
- Creation. The first invocation validates the environment, mounts the sandbox via
bwrap(detached, new session) and starts the supervisor inside it. The supervisor is the parent of every job and the lifetime authority of the namespace. - Attachment. The creating invocation — and every later invocation from the same working directory — attaches to the supervisor over a unix socket and runs its command as a job. The command inherits its terminal (as a pty) or its pipes.
- Return. Each invocation returns as soon as its own command finishes, with that command's exit code. Other jobs keep running.
- Closing. The sandbox closes itself once the last user process inside it has exited and the idle grace (60 seconds) elapsed without a new connection. Accounting is per PID namespace, not per job: a command that daemonizes a child and exits immediately keeps the sandbox alive until that orphan (reparented to the in-sandbox reaper) finishes too. The window absorbs gaps between sequential commands (for example, an agent's tool-call latency) so back-to-back invocations reuse the same private
/tmpand home state.
Operational notes:
- The supervisor records its pid in the sandbox runtime directory; the documented emergency close is
kill "$(cat "$XDG_RUNTIME_DIR/sb/<id>/pid")"(no dedicated subcommand by design). - Killing a client never kills the sandbox. The client behaves like the
job's controlling terminal:
SIGINT/SIGTERM/SIGHUPreceived by the client are forwarded verbatim to the job's process group, the client keeps waiting, and it exits with the job's real status (130 only if the job actually died of SIGINT). Repeated Ctrl-C is repeated SIGINT — there is no auto-escalation to SIGKILL, exactly like a terminal; a signal-ignoring job survives it and must be killed by a signal it does not trap. The one mode difference is ontological and matchesdocker exec:SIGKILLof a pty-mode client is a lost terminal (the job gets HUP),SIGKILLor a crash of a pipe-mode client isdisown(the job runs on). - A crashed supervisor tears the whole sandbox down (PID-namespace collapse); the next invocation cleans up stale files and recreates it.
- Because the sandbox outlives the invocation that created it, sandboxed processes do not die when their launcher exits. This replaces the old
--die-with-parentcontract, which is incompatible with a shared long-lived sandbox.
Persistent sandbox state is keyed by the SHA-256 digest of the physical invocation working directory (pwd -P).
Each working directory receives its own instance:
$XDG_STATE_HOME/simple-sandbox/<sha256(workdir)>/ (persistent)
$XDG_RUNTIME_DIR/sb/<sha256(workdir)>/ (session runtime)
| Path | Purpose |
|---|---|
home/ |
Private writable $HOME (a bind-mounted directory hiding the real home). |
overlays/<id>/upper,work |
Runtime state for overlay path policies. |
lock |
Short flock guarding sandbox creation (not held for the sandbox's lifetime). |
sb/<id>/s |
Supervisor control socket (mode 0600; deliberately short to fit AF_UNIX path limits). |
sb/<id>/pid |
Supervisor pid as seen by the creator, for the documented emergency close. |
sb/<id>/log |
Supervisor stdout/stderr, shown on startup failure. |
State is reused by later invocations from the same physical working directory.
$XDG_STATE_HOME must be absolute and defaults to ~/.local/state. Only the sandbox's XDG_RUNTIME_DIR mount is backed by /run and disappears when that runtime directory is cleaned up at session end.
Policies may not overlap the sandbox state directory or its runtime directory; this prevents private-home and overlay data from being exposed back into the sandbox.
The optional configuration file is specified via:
SIMPLE_SANDBOX_CONFIG
When unset, the default path is:
${XDG_CONFIG_HOME:-~/.config}/simple-sandbox.json
The default configuration file is silently ignored when missing. A path set explicitly through SIMPLE_SANDBOX_CONFIG must exist.
Configuration is entirely optional.
If present, the JSON document may contain:
pathsunsetkeep
No other top-level keys are accepted.
Configuration is read at sandbox creation. While a sandbox is alive, editing or replacing the configuration file has no effect on its policies, its environment, or jobs attached later — stop the sandbox first to pick up changes.
Example:
{
"paths": {
"~/.ssh": "hide",
"~/.config/my-tool": "readonly",
"/var/tmp/project-cache": "expose",
"~/.cache/build": "overlay"
},
"unset": [
"AWS_SECRET_ACCESS_KEY",
"PRIVATE_TOKEN"
],
"keep": [
"DISPLAY",
"HTTPS_PROXY"
]
}Each key may be:
- absolute;
- relative to the working directory;
- contain
${VAR}; - use
~for the user's home directory.
The final path component is preserved while symlinked parent directories are canonicalized.
| Policy | Meaning |
|---|---|
hide |
Directory → tmpfs; file → read-only bind of /dev/null. |
readonly |
Rebind read-only while preserving the source mode bits, including execute permission. |
expose |
Read-write bind from the host. |
overlay |
Runtime overlay with a private upper layer. |
overlay applies only to directories.
Policies targeting / are rejected.
/run and /var/run are masked by default. A policy may re-expose a specific descendant (for example /run/current-system), but a policy on either tree root itself is rejected because it overlaps sandbox state.
Missing filesystem paths are skipped with a warning.
Policies cannot target $HOME itself: the real home is always hidden. Use a descendant path such as ~/.cache/my-tool to make that specific host path available.
If a ${VAR} reference expands an unset environment variable, the policy is skipped with a warning — except hide, which aborts startup. Silently dropping a hide rule could expose a secret, so an unset variable there is fatal. Use ${VAR?} or ${VAR:-} to opt an optional path into skipping instead. An unset or empty variable counts as missing. Skipped policies are reported once at sandbox creation as a single aggregated warning on standard error and copied into the creation log; later attaches do not repeat it.
Duplicate identical policies are merged.
Conflicting policies abort startup.
Parent paths are mounted before children so deeper paths can intentionally override broader ones. Configuration order is therefore irrelevant.
Example:
{
"paths": {
"~/.local/share": "hide",
"~/.local/share/uv": "expose"
}
}The broader directory remains hidden while the uv subdirectory is explicitly exposed.
Removes selected environment variables from the sandbox environment. Applied after keep, so a name listed in both is removed.
Each name must match:
^[A-Za-z_][A-Za-z0-9_]*$
Adds environment variable names to the sandbox allowlist. By default only PATH, TERM, LANG and LC_* locales are re-exported; HOME, TMPDIR and XDG_RUNTIME_DIR are always set to canonical sandbox values. keep opts specific extra names in (for example DISPLAY, VIRTUAL_ENV or HTTPS_PROXY).
Each name must match:
^[A-Za-z_][A-Za-z0-9_]*$
Names missing from the launcher environment are ignored.
Idle time, in whole seconds, that an empty sandbox waits before closing itself (default 60). Set it to 0 for CI-style "close immediately when idle" behavior.
- The host filesystem is readable by default. Read-only mounts restrict filesystem writes, not access to readable paths. Use explicit
hidepolicies for paths that must not be visible. Beware:hidepolicies covering the Python installation orbwrapcan make the supervisor unstartable. - Host UNIX sockets outside the runtime trees may remain accessible.
/runand/var/runare replaced with empty tmpfs mounts, so sockets there (system D-Bus, journald, container runtimes) are not reachable. Sockets elsewhere on the host filesystem remain visible through the read-only root bind, and a read-only mount does not prevent connecting to them; hide or mask such paths explicitly. - Runtime paths are opt-in. The
/runmask also hides paths some toolchains expect, such as NixOS/run/current-systemor/run/udev/data. Add areadonly(orexpose) path policy for the specific path you need. - Policies are explicit. Paths remain readable unless hidden by policy.
- The host network is shared. No network namespace isolation is performed.
- The environment is allowlisted. Variables outside the built-in allowlist that are not listed in
keepare absent from every job, includingSSH_AUTH_SOCK,DISPLAY,EDITOR,VIRTUAL_ENV,NIX_*andGIT_*. This is what keeps inherited credentials out; opt specific names back in withkeepwhen interactive tooling needs them. - No syscall filtering. No seccomp or similar syscall restrictions are applied.
bwrapis located throughPATH. The launcher resolvesbwrapviaPATH, then canonicalizes and checks it (workdir-residency, setuid). It cannot distinguish an intended systembwrapfrom any other PATH-resident build outside the working directory; the pinned interpreter is trusted,bwrapitself is part of the trust anchor. Do not treat launcher path checks as a complete defense against an untrustedPATH.- Pipe-mode attaches hand the job the client's terminal fds. The supervisor and the daemon itself run in their own session (
setsid), and pty-mode jobs get a fresh sandbox pty as controlling terminal; but a pipe-mode job inherits the client's stdin/stdout/stderr descriptors verbatim. Depending on kernel settings, terminal-related ioctls such asTIOCSTI(where permitted) may remain reachable through them. - Sandbox state is persistent per workdir. Private-home and overlay state live under
$XDG_STATE_HOME; only the sandboxXDG_RUNTIME_DIRis session-scoped. - A working directory under
/tmpis not supported. The sandbox mounts a fresh tmpfs over/tmp, which shadows such a workdir (pre-existing behavior, tested around). - Attached jobs run in the sandbox working directory with the creator's environment snapshot; the attaching client's cwd and environment intentionally do not leak into the job, and relative paths in the command resolve inside the sandbox, not in the client's host directory.
- A supervisor crash is a sandbox crash. All jobs in it die (this is the PID namespace behaving as designed, not a recovery hook).