RFC: Per-sandbox introspection via control socket (sandlock ps / config)
Goal
Make long-running sandboxes inspectable from outside. Every sandbox (CLI, Python SDK, embedded) exposes a per-process Unix control socket; a new sandlock ps lists live sandboxes and sandlock config <name> returns the effective policy. The socket is the substrate; later verbs (stats, logs, port, diff, shutdown) plug in without further protocol work.
Motivation
Today sandlock list exists but only sees sandboxes that registered themselves in /dev/shm/sandlock-$UID/network.json, and registration only happens in the port_remap branch of run_command (crates/sandlock-cli/src/main.rs:504). Two consequences:
- Sandboxes launched without
--port-remap, and every sandbox created via the Python SDK (which never touchesnetwork_registry), are invisible tosandlock list/sandlock kill. - Even when a sandbox is listed, the registry only stores
pid,ports,allowed_hosts, and the virtual/etc/hosts(crates/sandlock-cli/src/network_registry.rs:13). None of the policy passed toSandbox()(Landlock rules, seccomp adjustments, http rules, limits, determinism flags) is recoverable. There is nosandlock inspectand no introspection API on a running sandbox.
On-disk persistence is not a complete answer on its own: the effective policy lives in supervisor memory, and a policy_fn calling ctx.deny_path() at runtime mutates it, so a snapshot file would be stale. The Docker precedent (/var/lib/docker/containers/<id>/config.v2.json) persists for daemon-restart recovery, which Sandlock's one-supervisor-per-sandbox model does not need. The only source of truth is the supervisor process itself, so the introspection path needs to talk to it.
Current state
Command::ListandCommand::Kill(crates/sandlock-cli/src/main.rs:141,:168): read fromnetwork.jsononly.network_registry::register(crates/sandlock-cli/src/network_registry.rs:68): single shared JSON file underflock, called from one CLI codepath.sandlock-coreandsandlock-ffihave no equivalent. Python SDK sandboxes do not register.- The TOML profile serializer in
crates/sandlock-core/src/profile.rsalready flattens theSandboxdataclass to a profile shape; reusable for the JSON response body.
Proposed design
Per-sandbox runtime dir
Layout under /dev/shm/sandlock-$UID/<name>/:
pid: single-line pid file; letspslist and prune dead sandboxes without opening the socket.control.sock: Unix stream socket, supervisor-owned, bound before the child is forked.
No other files. meta.json is redundant (start time, argv, exe are all in /proc/<pid>). policy.json is dropped in favor of the socket so that dynamic-policy mutations are reflected.
The supervisor unlinks its dir on normal exit and on signal-handled exit paths. Readers (ps, kill, config) prune dirs whose pid is no longer alive (same liveness check list uses today, crates/sandlock-cli/src/network_registry.rs:141).
The existing /dev/shm/sandlock-$UID/network.json is deleted; per the project's pre-1.0 no-backcompat stance, no shim.
Wire protocol
4-byte big-endian length prefix, then UTF-8 JSON. One client at a time per socket; no concurrency to manage.
Request:
{\"v\": 1, \"verb\": \"config\", \"args\": {}}
Response:
{\"v\": 1, \"ok\": true, \"data\": { ...effective Sandbox policy... }}
or
{\"v\": 1, \"ok\": false, \"err\": \"...\"}
The v field reserves room to rev the wire pre-1.0. config is the only verb defined in v1.
Core changes (sandlock-core, ~180 LOC)
- Supervisor setup:
mkdir <name>/, writepid, bindcontrol.sock. Hook into the existing supervisor lifecycle where seccomp/Landlock setup already runs. - Cleanup: unlink the dir on normal exit, on supervisor panic, and on the signal-handled paths.
- Control loop: serve
control.sockfrom the supervisor's event loop or a dedicated thread (decision deferred to implementation; depends on whether the seccomp-notify loop can absorb a periodic accept without notification latency cost). confighandler: reuse the profile serializer fromcrates/sandlock-core/src/profile.rsand emit JSON instead of TOML. Runtime kwargs (policy_fn,init_fn,work_fn) render as the literal string\"<callback>\".
CLI changes (sandlock-cli, ~80 LOC)
- Rename
sandlock listtosandlock ps. Columns: NAME, PID, UPTIME, CMD. UPTIME and CMD come from/proc/<pid>/statand/proc/<pid>/cmdline. - New
sandlock config <name>: opens<name>/control.sock, sends{\"v\":1,\"verb\":\"config\"}, prints thedatafield.--jsonis the default;--tomlround-trips into a profile via the existing TOML serializer. - Rewire
sandlock kill <name>to read pid from<name>/pid. - Delete
crates/sandlock-cli/src/network_registry.rsand the registration call atcrates/sandlock-cli/src/main.rs:522.
Deferred (each is now an independent verb addition)
stats: RSS / CPU% / threads / FDs from/proc/<pid>; branchfs delta and forks-used from supervisor counters. Backssandlock stats <name>, streaming by default per the Docker analogue.logs: ring buffer of recent seccomp denials (syscall name + count, no argv per TOCTOU) and MITM proxy decisions. Backssandlock logs <name>.port: current port-remap table. Backssandlock port <name>; replaces today'snetwork_registry::update_portscallback wiring.diff: branchfs A/M/D changes, reusing the existingChangetype thatdry_runreturns. Backssandlock diff <name>.shutdown: graceful stop request; optional fast path forsandlock kill.
Each is "register a verb handler"; the protocol, dir, and lifecycle are already in place.
Open questions
- Socket auth.
/dev/shm/sandlock-$UID/is mode-0700 per-user, so any same-user process can connect to any of that user's sandboxes. Same trust boundary asdocker.sockfor the docker group, but in a multi-sandbox-per-user setup it does let sandbox A's processes introspect sandbox B's policy if they can reach the host fs (Landlock normally prevents this, but worth naming the assumption). - Where the control loop runs. If the supervisor's main loop is busy with seccomp-notify, a dedicated thread may be needed to avoid notification latency. Defer to whoever knows that code best.
- Callback placeholder shape.
\"<callback>\"is a flat marker. Worth signaling more (function name, module) for debuggability?repr(fn)covers Python; less obvious for Rust closures. killvs graceful stop. Cleanest separation: leavekillas SIGKILL via pid (no socket round-trip needed when the supervisor is hung), add a futuresandlock stopfor graceful that goes through theshutdownverb.
Acceptance
sandlock pslists every live sandbox started by the same UID, regardless of whether it was launched viasandlock run, the Python SDK, or the FFI.- A Python
Sandbox(...)instance whose process is still running shows up insandlock psand answerssandlock config <name>with its effective policy. sandlock config <name> --tomlproduces a profile thatsandlock run -p <that profile>re-runs identically.- A sandbox using
policy_fnto callctx.deny_path(\"/etc\")at runtime reflects the addition insandlock config. - Supervisor crash (SIGKILL) leaves a stale dir that the next
sandlock psprunes. - The old
/dev/shm/sandlock-$UID/network.jsonis gone; no code references it.
@congwang-mk I will go ahead on this. My dev agent proposes
- Socket auth — accept same-UID trust, document it, add a peer-cred audit (not a gate) The trust boundary is "same UID," identical to docker.sock for the docker group. The RFC's concern about sandbox A introspecting sandbox B is already handled by the existing confinement model, not by the socket:
/dev/shm/sandlock-$UID/ is mode 0700, so only the owning UID can even see the directory. A sandboxed process that could reach host /dev/shm would already have escaped Landlock — Protection::AbstractUnixSocketScope (ABI v6) and the fs scoping rules prevent exactly this. If a sandbox can connect to another sandbox's control.sock, it has already broken out, and the socket is the least of the problems. The one real residual: a non-sandboxed same-UID process (a user shell, another tool) can introspect any of that user's sandboxes. That's the same-UID trust assumption and is acceptable for v1. Recommendation: accept same-UID trust. As a cheap defense-in-depth, call getsockopt(SO_PEERCRED) on accept() and log (not reject) any connection whose UID doesn't match the supervisor's UID — it should never happen given the 0700 dir, and a mismatch would signal tampering worth surfacing. Do not add a token/handshake for v1; it's complexity for a threat model Landlock already covers.
- Control loop — a dedicated tokio task, not an OS thread, and not in the notif loop The seccomp-notify loop (seccomp/notif.rs:2142) is the wrong place. It's a tight, sequential, latency-sensitive drain:
Copy 'outer: loop { readable().await; clear_ready(); loop { probe → recv → handle } } with an explicit comment: "Notifications are processed sequentially (not spawned) to avoid mutex contention between concurrent handlers." Injecting accept into that loop would add an extra epoll-wakeup branch on every notification burst and risk stretching syscall-notify latency — the exact thing the RFC's open question worries about.
A dedicated OS thread is also wrong: the supervisor's shared state is Arc
The OCI supervisor already proves the right pattern: supervisor_main / serve_running_init (sandlock-oci/src/supervisor.rs) runs its accept loop as a tokio::select! against its own UnixListener in the same multi-threaded runtime, completely independent of the seccomp-notify work.
Recommendation: spawn a dedicated tokio task right next to notif_handle at sandbox.rs:1927:
rust
Copy
self.rt_mut().control_handle = Some(tokio::spawn(
control::control_loop(listener, Arc::clone(&ctx), Arc::clone(&sandbox_snapshot))
));
tokio multiplexes this task against the notif task across the runtime's worker threads; neither blocks the other, and both share Arc
- Callback placeholder — ship "
" for v1, add an optional label hook The asymmetry is real and language-inherent:
Rust: policy_fn, init_fn, work_fn are stored as Box
keeps the wire simple and uniform,
gives debuggability where the language can provide it (Python sets the label from repr(fn) automatically; Rust callers opt in),
doesn't force Rust closures to lie or require struct-wrapping.
Ship v1 with just "
- kill vs graceful stop — adopt the RFC's split exactly The RFC's proposed separation is correct and matches what the code already does:
Today's kill uses killpg(entry.pid, SIGKILL) (main.rs), and the OCI supervisor uses killpg(init_pgid, signum) (supervisor.rs). The pid file gives the process-group leader, so kill stays a direct killpg(SIGKILL) via
please review https://github.com/multikernel/sandlock/pull/153
Implemented in #153.
Per-sandbox control socket under /dev/shm/sandlock-$UID/<name>/ with dual-pid file and Unix stream socket. sandlock ps lists running sandboxes with NAME/PID/UPTIME/CMD. sandlock config <name> fetches the effective policy (JSON or TOML). sandlock kill now reads both child and supervisor PIDs from the pid file and kills both. control_socket: bool opt-out knob (defaults to true). All 10 new integration tests pass alongside the existing suite.