Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: connect allowlisted sockets through a per-command supervisor
Replacing the sandbox's socket at connect() time (NOTIF_ADDFD SETFD) broke
epoll registrations, duplicated descriptors and EISCONN, and every pending
connect held a privileged server thread past the command's timeout.

With an allowlist, the server now runs the command through a supervisor
(sbx-server --net-supervise) that runs inside the sandbox as its parent.
The supervisor creates the sandbox's IP sockets itself (ADDFD_FLAG_SEND on
socket()) and keeps a handle until they connect, listen or are closed, so
connect() acts on the sandbox's own socket. It shares the command's process
group and limits, bounds pending connects at 64, and stops waiting on a
blocking connect as soon as the caller is gone. pidfd_getfd was not an
option: the Jobs seccomp profile refuses it without CAP_SYS_PTRACE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
Wauplin and claude committed Nov 4, 2026
commit b8e77c0626b7fc64d4ed31d24ebac85c63187751
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,14 @@ How it works (`src/network.rs`). Both layers are inherited by every descendant a

- A **seccomp filter** allows `AF_UNIX` and `AF_NETLINK` sockets, and TCP over IPv4/IPv6. It refuses UDP (so DNS too), ICMP, raw and packet sockets, any other family, TCP Fast Open, io_uring, `ptrace`, `process_vm_writev` and `pidfd_getfd`.
- A **Landlock** ruleset (ABI 4) refuses every TCP `connect()`, loopback included. Binding and listening still work, so the port proxy keeps working.
- With an allowlist, the filter also sends each `connect()` to the server. The server reads the destination, checks it, and if it is allowed, it connects a socket of its own to that address and installs it in place of the sandbox's socket. It connects the copy it checked, so changing the address in memory after the check has no effect.
- With an allowlist, the server runs the command through a **connect supervisor**: the same binary (`sbx-server --net-supervise`), started as the command's parent with the sandbox's uid, limits and Landlock domain. The filter sends the sandbox's IP `socket()`, `connect()` and `listen()` calls to it. The supervisor creates each IP socket and installs it as the result of `socket()`, keeping a handle on it. On `connect()`, it checks the destination and connects that handle, which is the sandbox's own socket, to the address it checked. epoll registrations, duplicated descriptors and socket options keep working, and changing the address in memory after the check has no effect.
- The supervisor is in the command's process group, so a timeout or a kill ends it with the command. Its threads count against the sandbox's limits, not the server's, and it handles at most 64 pending connects at a time. A blocking `connect()` stops waiting as soon as the caller is gone.
- Allowlisted hostnames are resolved once by the server and pinned in `/etc/hosts`. The sandbox resolves them without DNS, to exactly the addresses that were allowed.

Limits:

- Socket options set before `connect()` (for example `TCP_NODELAY`) are not carried over to the server's socket. A blocking `connect()` ignores `SO_SNDTIMEO`.
- With an allowlist, background processes that outlive the command that started them lose their network access when it exits. Start long-running services as background processes of their own (`/v1/processes`).
- With an allowlist, the supervisor holds a handle on a socket until it connects, listens or is closed. A socket the sandbox closes before connecting stays open for up to a second.
- Tools that talk to themselves over local TCP (Ray, NCCL, Jupyter kernels) need `127.0.0.1` in the allowlist. In dedicated mode that also lets the sandbox reach the server's port, which still requires its token.
- Debuggers (`gdb`, `strace`) do not work in a restricted sandbox: `ptrace` is refused.
- A writable volume is still a way to move data out. Mount volumes read-only for strict isolation.
Expand Down
38 changes: 37 additions & 1 deletion scripts/network-regression.sh
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ try:
w.write(b"GET / HTTP/1.0\r\n\r\n")
assert (await r.read(12)).startswith(b"HTTP/1.0 200")
asyncio.run(main())
elif kind == "epoll": # registered with epoll before connect()
import select
s = socket.socket(); s.setblocking(False)
ep = select.epoll(); ep.register(s, select.EPOLLOUT | select.EPOLLET); ep.poll(0)
assert s.connect_ex((sys.argv[2], int(sys.argv[3]))) == errno.EINPROGRESS
assert ep.poll(2), "epoll missed the connection"
elif kind == "dup": # a duplicate descriptor sees the connection, a second connect() is EISCONN
import os
s = socket.socket(); other = socket.socket(fileno=os.dup(s.fileno()))
s.connect((sys.argv[2], int(sys.argv[3])))
other.getpeername()
assert s.connect_ex((sys.argv[2], int(sys.argv[3]))) == errno.EISCONN
elif kind == "hang": # blocking connects that never complete
import threading
for _ in range(8):
threading.Thread(target=lambda: socket.create_connection((sys.argv[2], int(sys.argv[3]))), daemon=True).start()
threading.Event().wait()
elif kind == "udp":
socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b"x", ("1.1.1.1", 53))
elif kind == "raw":
Expand Down Expand Up @@ -64,7 +81,14 @@ python3 -m http.server 18080 --bind 127.0.0.1 >/dev/null 2>&1 &
allowed_srv=$!
python3 -m http.server 18081 --bind 127.0.0.1 >/dev/null 2>&1 &
other_srv=$!
trap 'kill $allowed_srv $other_srv 2>/dev/null || true' EXIT
# A service that never accepts: its backlog is full, so connects to it hang.
python3 -c "
import socket, time
s = socket.socket(); s.bind(('127.0.0.1', 18082)); s.listen(0)
c = [socket.create_connection(('127.0.0.1', 18082)) for _ in range(2)]
time.sleep(3600)" &
stuck_srv=$!
trap 'kill $allowed_srv $other_srv $stuck_srv 2>/dev/null || true' EXIT
sleep 1

start() { # env assignments for the server...
Expand Down Expand Up @@ -112,6 +136,16 @@ expect "another port is refused" "err EACCES" "$(probe /v1 $TOKEN tcp 127.0.0.1
expect "an allowed hostname resolves and connects" "ok" "$(probe /v1 $TOKEN http https://huggingface.co/api/models?limit=1)"
expect "any other host is refused" "err*" "$(probe /v1 $TOKEN http https://example.com)"
expect "udp stays refused" "err EACCES" "$(probe /v1 $TOKEN udp)"
expect "epoll registered before connect() sees it complete" "ok" "$(probe /v1 $TOKEN epoll 127.0.0.1 18080)"
expect "dup'd descriptors share the connection, EISCONN works" "ok" "$(probe /v1 $TOKEN dup 127.0.0.1 18080)"
threads() { sed -n 's/^Threads:[[:space:]]*//p' "/proc/$server/status"; }
before=$(threads)
curl -s -m 30 -H "X-Sandbox-Token: $TOKEN" -X POST "$U/v1/exec" \
-d '{"cmd":["/usr/local/bin/sbxprobe","hang","127.0.0.1","18082"],"timeout":1}' >/tmp/hang
grep -q '"timed_out":true' /tmp/hang && pass "pending connects do not outlive a timeout" || fail "hang: $(cat /tmp/hang)"
sleep 1
expect "the server holds no thread for them" "$before" "$(threads)"
expect "no supervisor is left behind" "0" "$(ps -eo args | grep -c '^/.*sbx-server --net-supervise')"
grep -q 'huggingface.co' /etc/hosts && pass "hostname pinned in /etc/hosts" || fail "/etc/hosts not pinned"
stop

Expand Down Expand Up @@ -139,6 +173,8 @@ expect "allowlisted sandbox reaches its service" "ok" \
"$(probe /v1/sandboxes/$(id "$allow_box") "$(tok "$allow_box")" tcp 127.0.0.1 18080)"
expect "allowlisted sandbox is refused elsewhere" "err EACCES" \
"$(probe /v1/sandboxes/$(id "$allow_box") "$(tok "$allow_box")" tcp 127.0.0.1 18081)"
expect "allowlisted sandbox: epoll and dup'd descriptors work" "ok ok" \
"$(probe /v1/sandboxes/$(id "$allow_box") "$(tok "$allow_box")" epoll 127.0.0.1 18080) $(probe /v1/sandboxes/$(id "$allow_box") "$(tok "$allow_box")" dup 127.0.0.1 18080)"
code=$(curl -s -o /dev/null -w '%{http_code}' -H "X-Sandbox-Token: $TOKEN" -X POST "$U/v1/sandboxes" \
-d '{"network":{"allow":["10.0.0.0/33"]}}')
expect "an invalid policy is a 400" "400" "$code"
Expand Down
36 changes: 20 additions & 16 deletions src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,24 @@ fn spawn(spec: &ExecSpec, tx: SyncSender<Event>) -> Result<SpawnedCommand, Strin
if deleted.as_ref().is_some_and(|guard| **guard) {
return Err("sandbox has been deleted".to_string());
}
let mut command = Command::new(&spec.argv[0]);
// An allowlist needs a connect supervisor between the server and the
// command: the server runs itself again as the command's parent, inside
// the sandbox (see the network module). `"none"` needs no supervisor.
let supervised = spec.network.as_ref().filter(|policy| policy.needs_supervisor());
let mut command = match supervised {
Some(policy) => {
let mut command = Command::new(crate::network::server_exe()?);
command.arg(crate::network::SUPERVISOR_FLAG).arg(policy.resolved_allowlist()).arg("--");
command.args(&spec.argv);
command
}
None => {
let mut command = Command::new(&spec.argv[0]);
command.args(&spec.argv[1..]);
command
}
};
command
.args(&spec.argv[1..])
.stdin(if spec.stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
Expand All @@ -227,11 +242,9 @@ fn spawn(spec: &ExecSpec, tx: SyncSender<Event>) -> Result<SpawnedCommand, Strin
}
command.envs(&spec.env);
// Registered last, so it runs after the sandbox's own isolation hook.
let network = match &spec.network {
Some(policy) => Some(crate::network::Prepared::new(policy)?),
None => None,
};
if let Some(network) = &network {
// With a supervisor, the supervisor applies it to the command instead.
if let Some(policy) = spec.network.as_ref().filter(|_| supervised.is_none()) {
let network = crate::network::Prepared::new(policy)?;
unsafe { command.pre_exec(network.hook()) };
}
// The orphan reaper shares this lock: even an instantly exiting child is
Expand All @@ -241,15 +254,6 @@ fn spawn(spec: &ExecSpec, tx: SyncSender<Event>) -> Result<SpawnedCommand, Strin
owned.get_or_insert_with(Default::default).insert(child.id());
let handle = Arc::new(ProcHandle::open(child.id()));
drop(owned);
if let (Some(network), Some(policy)) = (network, &spec.network) {
if let Err(e) = network.start(Arc::clone(policy), spec.sandbox.as_ref().map(|s| s.uid)) {
// Without a supervisor its connects fail closed (ENOSYS); stop it anyway.
handle.kill_tree(libc::SIGKILL, None);
let _ = child.wait();
untrack_owned(child.id());
return Err(e);
}
}

// Optional one-shot stdin payload: write it then drop the pipe (-> EOF).
if let Some(input) = &spec.stdin {
Expand Down
6 changes: 6 additions & 0 deletions src/landlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,12 @@ pub fn system_dir_rules() -> &'static [(RawFd, u64)] {
rules.push((fd, dev_node));
}
}
// The server binary itself, run again as the connect supervisor of a
// sandbox with a network allowlist (see the network module). Read and
// execute only; it gives a sandbox nothing it could not run from its home.
if let Some(fd) = crate::network::server_exe().ok().and_then(|exe| open_o_path(&exe.to_string_lossy())) {
rules.push((fd, (FS_EXECUTE | FS_READ_FILE) & handled_fs));
}
// Directories: `/dev/pts` for pseudo-terminals, `/dev/fd` (a symlink to
// /proc/self/fd) and the std* symlinks under it for shell redirection.
for dir in ["/dev/pts", "/dev/fd", "/dev/shm/../fd"] {
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,11 @@ fn env_number<T: std::str::FromStr>(name: &str, default: T) -> T {
}

fn main() {
// `sbx-server --net-supervise ...`: the connect supervisor of one command
// under a network allowlist, started by the server itself (see network.rs).
if let Some(code) = network::supervisor_main() {
std::process::exit(code);
}
let port: u16 = env_number("SBX_PORT", 8000);
let token = std::env::var("SBX_TOKEN").ok().filter(|t| !t.is_empty());
// Don't leak the token to child processes.
Expand Down
Loading
Loading