From 369ad10fb7551dea49db0e78de23a916d01e3aec Mon Sep 17 00:00:00 2001 From: Wauplin Date: Wed, 4 Nov 2026 15:42:04 +0100 Subject: [PATCH 1/5] feat: per-sandbox network policies (no egress, or an allowlist) Commands run under a network policy get a seccomp filter (TCP-only IP sockets, no UDP/raw/io_uring/TFO/ptrace) and a Landlock ruleset that refuses every TCP connect. With an allowlist, connect() is routed to the server, which checks the destination, connects its own socket and installs it in the sandbox (SECCOMP_IOCTL_NOTIF_ADDFD). Hostnames are resolved by the server and pinned in /etc/hosts. Dedicated mode: SBX_NETWORK. Host mode: `network` on POST /v1/sandboxes, echoed back in the response. The server also marks itself non-dumpable so sandboxed root code cannot act through it. Co-Authored-By: Claude Opus 5.5 --- README.md | 35 +- scripts/network-regression.sh | 147 ++++++ src/exec.rs | 23 + src/landlock.rs | 24 + src/main.rs | 43 ++ src/network.rs | 817 ++++++++++++++++++++++++++++++++++ src/proxy.rs | 1 + src/sandboxes.rs | 34 +- 8 files changed, 1120 insertions(+), 4 deletions(-) create mode 100644 scripts/network-regression.sh create mode 100644 src/network.rs diff --git a/README.md b/README.md index b6c9224..eacd42d 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ ABI-6 abstract-socket scoping). ``` GET /health no auth → {"status","protocol"} with a valid token → adds version, - uptime_ms, sandboxes, mode, auth, landlock{abi,features} + uptime_ms, sandboxes, mode, auth, landlock{abi,features}, network POST /v1/exec {cmd, shell?, env?, cwd?, timeout?, stdin?, background?, tag?} foreground → NDJSON stream: start / stdout / stderr / ping / exit background → {"id", "pid", "tag"} @@ -60,7 +60,8 @@ DELETE /v1/files/delete?path=&recursive= POST /v1/files/mkdir?path= # host mode (many sandboxes per job) -POST /v1/sandboxes {count?, env?, max_procs?, max_mem_mb?} → {"sandboxes":[{id,token,uid,home}]} +POST /v1/sandboxes {count?, env?, max_procs?, max_mem_mb?, network?} + → {"sandboxes":[{id,token,uid,home,confinement,network}]} GET /v1/sandboxes → live sandbox list DELETE /v1/sandboxes → delete all DELETE /v1/sandboxes/{id} → delete one (frees the uid) @@ -87,8 +88,38 @@ the home, and it assigns ownership through the resulting descriptor rather than | `SBX_IDLE_TIMEOUT` | unset | seconds of inactivity (no authed request, no running process) before clean exit | | `SBX_CAPACITY` | `64` | host mode: max concurrent sandboxes. Refuses to start if unparseable (it used to fall back to unlimited) | | `SBX_MAX_CONNECTIONS` | `512` | max concurrent connections; past it the server answers 503 without spawning a worker | +| `SBX_NETWORK` | unset | dedicated mode: network policy for every command, `none` or `{"allow": [...]}` (see [Network policies](#network-policies)). The server refuses to start if it cannot parse or enforce it. Host mode takes `network` per sandbox instead | | `SBX_MIN_LANDLOCK_ABI` | `6` | host mode: minimum Landlock ABI to start with. 4 adds TCP-bind denial, 6 adds abstract-socket scoping — both are part of the documented model, so the default requires them. Lower it to accept a reduced set (`/health` reports what is in force) | +## Network policies + +A sandbox can run without network access, or with access to an allowlist only. The policy applies to the commands the server runs, never to the server itself, so the server keeps serving the API and mounted volumes keep working (the platform mounts them outside the container). + +``` +"none" no outbound access at all +{"allow": ["10.0.0.0/8", an address range + "203.0.113.10:443", one address, one port + "[2001:db8::1]:8000", "2001:db8::/32", + "huggingface.co", "vllm.internal:8000"]} hostnames, with an optional port +``` + +Dedicated mode reads it from `SBX_NETWORK`. In host mode, pass `network` to `POST /v1/sandboxes`, so isolated and connected sandboxes can share a host. The create response and `/health` echo the policy back: an older server ignores the field and echoes nothing, so a client can tell. + +How it works (`src/network.rs`). Both layers are inherited by every descendant and cannot be removed, even by root in the sandbox: + +- 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. +- 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`. +- 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. +- In host mode, a sandbox with network can pass a connected socket to a restricted one over a unix socket, if both cooperate. Pooled sandboxes share one trust boundary (see below). + ## Security model The dedicated routes (`/v1/exec`, `/v1/files/*`, `/v1/processes`, `/v1/proxy`) act with the diff --git a/scripts/network-regression.sh b/scripts/network-regression.sh new file mode 100644 index 0000000..597daa5 --- /dev/null +++ b/scripts/network-regression.sh @@ -0,0 +1,147 @@ +#!/bin/sh +# Live regression for network policies (`SBX_NETWORK`, `network` on create). +# +# The property under test: a command run under a policy reaches exactly the +# destinations the policy allows -- nothing with "none" -- while the server, +# unix sockets and local listening keep working. Needs root and Landlock ABI 4. +# +# docker run --rm -v "$PWD:/src" -w /src ubuntu:24.04 sh scripts/network-regression.sh +set -eu + +BIN=${BIN:-target/x86_64-unknown-linux-musl/release/sbx-server} +PORT=${PORT:-49601} +TOKEN=t +U="http://127.0.0.1:$PORT" +failures=0 + +say() { printf '\n=== %s\n' "$1"; } +pass() { printf ' ok %s\n' "$1"; } +fail() { printf ' FAIL %s\n' "$1"; failures=$((failures + 1)); } + +command -v curl >/dev/null && command -v python3 >/dev/null || + { apt-get update -qq && apt-get install -y -qq curl python3 ca-certificates >/dev/null; } +[ -f "$BIN" ] || cargo build --release --target x86_64-unknown-linux-musl + +# Probes live in a system dir, which pooled sandboxes can read under Landlock. +cat >/usr/local/bin/sbxprobe <<'EOF' +#!/usr/bin/env python3 +import asyncio, errno, socket, sys, urllib.request +kind = sys.argv[1] +try: + if kind == "tcp": + socket.create_connection((sys.argv[2], int(sys.argv[3])), timeout=5).close() + elif kind == "async": + async def main(): + r, w = await asyncio.wait_for(asyncio.open_connection(sys.argv[2], int(sys.argv[3])), 5) + 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 == "udp": + socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b"x", ("1.1.1.1", 53)) + elif kind == "raw": + socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) + elif kind == "ptrace": + import ctypes + libc = ctypes.CDLL(None, use_errno=True) + if libc.ptrace(16, int(sys.argv[2]), 0, 0) != 0: # PTRACE_ATTACH + raise OSError(ctypes.get_errno(), "ptrace") + elif kind == "unix": + a, b = socket.socketpair(); a.send(b"x"); assert b.recv(1) == b"x" + elif kind == "listen": + s = socket.socket(); s.bind(("127.0.0.1", 0)); s.listen() + elif kind == "http": + urllib.request.urlopen(sys.argv[2], timeout=10).read(1) + print("ok") +except OSError as e: + print("err", errno.errorcode.get(e.errno, e)) +except Exception as e: + print("err", type(e).__name__, e) +EOF +chmod 755 /usr/local/bin/sbxprobe + +# Two local services outside any sandbox: one to allow, one to keep out. +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 +sleep 1 + +start() { # env assignments for the server... + env SBX_PORT=$PORT SBX_TOKEN=$TOKEN "$@" "$BIN" >/tmp/net.log 2>&1 & + server=$! + sleep 1 +} +stop() { kill "$server" 2>/dev/null || true; wait "$server" 2>/dev/null || true; } + +# probe PATH_PREFIX TOKEN ARGS... -> the probe's one-line verdict +probe() { + prefix=$1 tok=$2 + shift 2 + args=$(printf '"%s",' "$@") + curl -s -m 60 -H "X-Sandbox-Token: $tok" -X POST "$U$prefix/exec" \ + -d "{\"cmd\":[\"/usr/local/bin/sbxprobe\",${args%,}]}" | + sed -n 's/^{"data":"\([^"]*\)\\n","event":"stdout"}$/\1/p' +} + +expect() { # description expected actual + case $3 in + $2) pass "$1" ;; + *) fail "$1: got '$3'" ;; + esac +} + +say "dedicated, network=none" +start SBX_NETWORK=none +expect "tcp to a local service is refused" "err EACCES" "$(probe /v1 $TOKEN tcp 127.0.0.1 18080)" +expect "https to the internet is refused" "err*" "$(probe /v1 $TOKEN http https://huggingface.co)" +expect "udp is refused" "err EACCES" "$(probe /v1 $TOKEN udp)" +expect "raw sockets are refused, even to root" "err EACCES" "$(probe /v1 $TOKEN raw)" +expect "the server cannot be ptraced" "err EPERM" "$(probe /v1 $TOKEN ptrace "$server")" +expect "unix sockets work" "ok" "$(probe /v1 $TOKEN unix)" +expect "listening on tcp works (port proxy)" "ok" "$(probe /v1 $TOKEN listen)" +curl -s -H "X-Sandbox-Token: $TOKEN" "$U/health" | grep -q '"network":"none"' && + pass "/health reports the policy" || fail "/health has no network policy" +stop + +say "dedicated, allowlist" +start SBX_NETWORK='{"allow":["127.0.0.1:18080","huggingface.co:443"]}' +expect "tcp to the allowed service works" "ok" "$(probe /v1 $TOKEN tcp 127.0.0.1 18080)" +expect "non-blocking connect + request work" "ok" "$(probe /v1 $TOKEN async 127.0.0.1 18080)" +expect "another port is refused" "err EACCES" "$(probe /v1 $TOKEN tcp 127.0.0.1 18081)" +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)" +grep -q 'huggingface.co' /etc/hosts && pass "hostname pinned in /etc/hosts" || fail "/etc/hosts not pinned" +stop + +say "dedicated, a policy that cannot be applied stops the server" +start SBX_NETWORK=everything +sleep 1 +kill -0 "$server" 2>/dev/null && { fail "server started with an invalid policy"; stop; } || pass "invalid policy refused at startup" + +say "host mode, a policy per sandbox" +start SBX_HOST_MODE=1 SBX_MIN_LANDLOCK_ABI=4 +create() { + curl -s -H "X-Sandbox-Token: $TOKEN" -X POST "$U/v1/sandboxes" -d "$1" +} +open_box=$(create '{"count":1}') +none_box=$(create '{"count":1,"network":"none"}') +allow_box=$(create '{"count":1,"network":{"allow":["127.0.0.1:18080"]}}') +id() { echo "$1" | sed 's/.*"id":"\([^"]*\)".*/\1/'; } +tok() { echo "$1" | sed 's/.*"token":"\([^"]*\)".*/\1/'; } +echo "$none_box" | grep -q '"network":"none"' && pass "create echoes the policy" || fail "no policy echo: $none_box" +expect "unrestricted sandbox reaches the other service" "ok" \ + "$(probe /v1/sandboxes/$(id "$open_box") "$(tok "$open_box")" tcp 127.0.0.1 18081)" +expect "isolated sandbox is refused" "err EACCES" \ + "$(probe /v1/sandboxes/$(id "$none_box") "$(tok "$none_box")" tcp 127.0.0.1 18080)" +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)" +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" +stop + +[ "$failures" -eq 0 ] && echo "\nall network checks passed" || { echo "\n$failures failure(s)"; exit 1; } diff --git a/src/exec.rs b/src/exec.rs index feb7a2e..aad297e 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -84,6 +84,9 @@ pub struct ExecSpec { /// When set, the command runs inside that sandbox: its uid, its home as cwd, /// a scrubbed environment and per-sandbox rlimits (see sandboxes module). pub sandbox: Option>, + /// Network policy for the command: the sandbox's in host mode, the job's + /// (`SBX_NETWORK`) in dedicated mode. None means unrestricted. + pub network: Option>, } struct SpawnedCommand { @@ -126,6 +129,7 @@ impl ExecSpec { background: body.get("background").and_then(|v| v.as_bool()).unwrap_or(false), tag: body.get("tag").and_then(|v| v.as_str()).map(String::from), sandbox: None, + network: None, }) } } @@ -222,6 +226,14 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result Some(crate::network::Prepared::new(policy)?), + None => None, + }; + if let Some(network) = &network { + unsafe { command.pre_exec(network.hook()) }; + } // The orphan reaper shares this lock: even an instantly exiting child is // registered before it can be mistaken for an orphan. let mut owned = OWNED_PIDS.lock().unwrap(); @@ -229,6 +241,15 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result EOF). if let Some(input) = &spec.stdin { @@ -624,6 +645,7 @@ pub fn handle_exec( Ok(s) => s, Err(e) => return resp.error(400, &e), }; + spec.network = sandbox.as_ref().map_or_else(|| state.network.clone(), |s| s.network.clone()); spec.sandbox = sandbox; if spec.background { @@ -696,6 +718,7 @@ pub fn handle_process_start( Err(e) => return resp.error(400, &e), }; spec.background = true; + spec.network = sandbox.as_ref().map_or_else(|| state.network.clone(), |s| s.network.clone()); spec.sandbox = sandbox; match start_background(state, &spec) { Ok(proc) => resp.json( diff --git a/src/landlock.rs b/src/landlock.rs index 7b56509..37ec4d4 100644 --- a/src/landlock.rs +++ b/src/landlock.rs @@ -50,6 +50,7 @@ const FS_BASE: u64 = (1 << 13) - 1; // access_net bits const NET_BIND_TCP: u64 = 1 << 0; +const NET_CONNECT_TCP: u64 = 1 << 1; // scoped bits (ABI 6) const SCOPED_ABSTRACT_UNIX_SOCKET: u64 = 1 << 0; @@ -275,6 +276,29 @@ pub fn build_ruleset(home: &str) -> std::io::Result { Ok(ruleset_fd) } +/// A ruleset that refuses every TCP connect and nothing else, layered on the +/// commands of a sandbox with a network policy (see the network module). Built +/// once and shared: it has no per-sandbox rule. Needs ABI 4. +pub fn connect_ruleset() -> std::io::Result { + static FD: OnceLock> = OnceLock::new(); + FD.get_or_init(|| { + let abi = cached_abi(); + if abi < 4 { + return Err(format!("needs Landlock ABI 4 or newer, this kernel has {abi}")); + } + let attr = RulesetAttr { handled_access_fs: 0, handled_access_net: NET_CONNECT_TCP, scoped: 0 }; + let fd = unsafe { + libc::syscall(SYS_LANDLOCK_CREATE_RULESET, &attr as *const _ as *const libc::c_void, std::mem::size_of::(), 0u32) + }; + if fd < 0 { + return Err(std::io::Error::last_os_error().to_string()); + } + Ok(fd as RawFd) + }) + .clone() + .map_err(std::io::Error::other) +} + /// Enforce the ruleset on the current thread and its future children/execve. /// Must be called with NO_NEW_PRIVS already set (Landlock requires it for /// unprivileged callers). Returns Ok only if the kernel confirms enforcement. diff --git a/src/main.rs b/src/main.rs index 4f3fc78..3ce1674 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod files; mod fsutil; mod http; mod landlock; +mod network; mod proxy; mod sandboxes; @@ -80,6 +81,8 @@ pub struct State { /// sandbox). Picks the idle policy: per-sandbox eviction + empty-host shutdown, vs /// the whole-job activity watchdog. pub host_mode: bool, + /// Dedicated mode: the network policy every command runs under (`SBX_NETWORK`). + pub network: Option>, } /// Constant-time string comparison. @@ -206,6 +209,8 @@ fn authenticated_health(state: &State) -> serde_json::Value { "abi": landlock::abi(), "features": landlock::features(landlock::abi()), }, + // Dedicated mode's network policy (pooled sandboxes report theirs individually). + "network": sandboxes::network_spec(&state.network), }) } @@ -473,6 +478,42 @@ fn main() { // a kernel that cannot deliver them, rather than silently dropping them. let min_abi: i32 = env_number("SBX_MIN_LANDLOCK_ABI", landlock::FULL_ABI); + // Dedicated mode's network policy: `"none"` or `{"allow": [...]}` as JSON. + // Applied to every command, never to the server itself. A policy that does + // not parse, or that this kernel cannot enforce, stops the server: running + // the sandbox with its network would be the opposite of what was asked. + let network = match std::env::var("SBX_NETWORK") { + Err(_) => None, + Ok(raw) => { + std::env::remove_var("SBX_NETWORK"); + if host_mode { + eprintln!("sbx-server: SBX_NETWORK is for dedicated mode; host mode takes `network` per sandbox"); + std::process::exit(1); + } + let value = serde_json::from_str(&raw).unwrap_or(serde_json::Value::String(raw)); + let policy = network::Policy::parse(&value).and_then(|policy| { + landlock::connect_ruleset().map_err(|e| format!("cannot restrict the network: {e}"))?; + Ok(policy) + }); + match policy { + Ok(policy) => { + policy.pin_hostnames(); + Some(Arc::new(policy)) + } + Err(e) => { + eprintln!("sbx-server: SBX_NETWORK: {e}"); + std::process::exit(1); + } + } + } + }; + // Sandboxed code must not be able to act through the server, which keeps + // its network: not by ptrace, not through /proc//mem, and not by + // reading the token from /proc//environ. Dedicated commands run as + // root too, so the uid alone does not stop them; a non-dumpable process + // can only be inspected with CAP_SYS_PTRACE, which Jobs do not grant. + unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) }; + // Orphaned grandchildren re-parent to us (we are typically PID 1 in the // container) and would otherwise pile up as zombies for the job's lifetime. exec::spawn_orphan_reaper(); @@ -484,6 +525,7 @@ fn main() { procs: exec::ProcRegistry::default(), sandboxes: sandboxes::SandboxRegistry::new(capacity, allow_unconfined), host_mode, + network, }); // Idle watchdog: stop billing for an abandoned sandbox/host before the job timeout. @@ -605,6 +647,7 @@ mod tests { procs: exec::ProcRegistry::default(), sandboxes: sandboxes::SandboxRegistry::new(4, true), host_mode: true, + network: None, } } diff --git a/src/network.rs b/src/network.rs new file mode 100644 index 0000000..a78e512 --- /dev/null +++ b/src/network.rs @@ -0,0 +1,817 @@ +//! Per-sandbox network policy: no outbound access, or only an allowlist. +//! +//! Jobs give the container its network, and the container cannot drop it +//! (no `CAP_NET_ADMIN`, no namespaces). What the server *can* do is take the +//! network away from the commands it starts, and only from them: the server +//! keeps its own connection (it needs it to serve the API), mounted volumes are +//! provided by the platform outside the container, so they keep working. +//! +//! Two kernel mechanisms, both inherited by every descendant and impossible to +//! remove, even for root inside the sandbox: +//! +//! - A **seccomp filter** limits which sockets can exist. `AF_UNIX` and +//! `AF_NETLINK` stay allowed (local IPC, interface queries). `AF_INET` and +//! `AF_INET6` are allowed for TCP only, so UDP, ICMP, raw sockets, SCTP and +//! every other family (packet, vsock, ...) are refused. It also refuses TCP +//! Fast Open (a `sendto` that connects without calling `connect`), io_uring +//! (it issues socket calls without going through seccomp), and the syscalls +//! that let a process act through another one (`ptrace`, +//! `process_vm_writev`, `pidfd_getfd`). +//! - A **Landlock** ruleset that handles `CONNECT_TCP` with no rule, so the +//! sandbox cannot connect any TCP socket itself, loopback included. Binding +//! and listening stay allowed, so the port proxy still reaches servers that +//! run in a dedicated sandbox. +//! +//! With `"none"`, that is all. With an allowlist, the seccomp filter also +//! sends every `connect()` to the server (`SECCOMP_RET_USER_NOTIF`). The +//! server reads the destination, checks it against the allowlist and, if it +//! matches, creates a socket of its own, connects it and installs it in place +//! of the sandbox's socket (`SECCOMP_IOCTL_NOTIF_ADDFD`). The server connects +//! the address it read, not whatever the sandbox's memory holds by the time the +//! kernel would re-read it, so there is no time-of-check/time-of-use gap. A +//! `connect()` on a non-IP socket (unix) is let through unchanged: the kernel +//! re-reads the address, but if it was swapped for an IP one the Landlock rule +//! refuses it. +//! +//! Hostnames in the allowlist are resolved once, by the server, and pinned in +//! `/etc/hosts`, so the sandbox resolves them without DNS (it cannot send UDP) +//! and reaches exactly the addresses that were allowed. +//! +//! Implemented with raw syscalls to stay a zero-dependency static binary. + +use std::collections::BTreeSet; +use std::io::Write; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::fs::FileExt; +use std::os::unix::io::RawFd; +use std::sync::{Arc, Mutex}; + +/// Most allowlist entries accepted in one policy. +const MAX_RULES: usize = 256; +/// Largest `sockaddr` the supervisor reads from a sandbox (`sockaddr_storage`). +const MAX_SOCKADDR: usize = 128; +const HOSTS_FILE: &str = "/etc/hosts"; +const HOSTS_MARKER: &str = "# sbx-server network allowlist"; + +// --------------------------------------------------------------------------- +// Policy +// --------------------------------------------------------------------------- + +/// One allowed destination: an address range and an optional port. +#[derive(Debug, Clone, PartialEq)] +struct Rule { + addr: IpAddr, + prefix: u8, + port: Option, +} + +impl Rule { + fn matches(&self, ip: IpAddr, port: u16) -> bool { + if self.port.is_some_and(|p| p != port) { + return false; + } + match (self.addr, ip) { + (IpAddr::V4(net), IpAddr::V4(ip)) => prefix_match(&net.octets(), &ip.octets(), self.prefix), + (IpAddr::V6(net), IpAddr::V6(ip)) => prefix_match(&net.octets(), &ip.octets(), self.prefix), + _ => false, + } + } +} + +fn prefix_match(net: &[u8], ip: &[u8], prefix: u8) -> bool { + let full = (prefix / 8) as usize; + let rest = prefix % 8; + if net[..full] != ip[..full] { + return false; + } + rest == 0 || (net[full] ^ ip[full]) & (0xff << (8 - rest)) == 0 +} + +/// A network policy, as applied to every command a sandbox runs. +#[derive(Debug)] +pub struct Policy { + /// Allowed TCP destinations. Empty means no outbound access at all. + rules: Vec, + /// Hostnames from the allowlist and the addresses they resolved to. + hosts: Vec<(String, Vec)>, + /// The value the client sent, echoed back so it can check it was applied. + pub spec: serde_json::Value, +} + +impl Policy { + /// Parse a policy: `"none"`, or `{"allow": ["10.0.0.0/8", "1.2.3.4:443", "huggingface.co", ...]}`. + /// + /// Hostnames are resolved here, so a name that does not resolve is an + /// error now rather than a sandbox that cannot reach it later. + pub fn parse(value: &serde_json::Value) -> Result { + Self::parse_with(value, resolve) + } + + fn parse_with( + value: &serde_json::Value, + resolve: fn(&str) -> Result, String>, + ) -> Result { + let entries = match value { + serde_json::Value::String(s) if s == "none" => Vec::new(), + serde_json::Value::Object(map) if map.len() == 1 && map.contains_key("allow") => { + let Some(items) = map["allow"].as_array() else { + return Err("network.allow must be an array of strings".into()); + }; + if items.len() > MAX_RULES { + return Err(format!("network.allow has {} entries, max {MAX_RULES}", items.len())); + } + items + .iter() + .map(|v| v.as_str().map(str::to_string).ok_or("network.allow must be an array of strings")) + .collect::, _>>()? + } + _ => return Err("network must be \"none\" or {\"allow\": [...]}".into()), + }; + let mut rules = Vec::new(); + let mut hosts = Vec::new(); + for entry in &entries { + match parse_entry(entry)? { + Target::Net(addr, prefix, port) => rules.push(Rule { addr, prefix, port }), + Target::Host(name, port) => { + let ips = resolve(&name)?; + rules.extend(ips.iter().map(|&ip| Rule { addr: ip, prefix: full_prefix(ip), port })); + hosts.push((name, ips)); + } + } + } + Ok(Policy { rules, hosts, spec: value.clone() }) + } + + /// Whether a sandbox may connect to `ip:port`. + pub fn allows(&self, ip: IpAddr, port: u16) -> bool { + let ip = match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip), + v4 => v4, + }; + self.rules.iter().any(|rule| rule.matches(ip, port)) + } + + /// Whether `connect()` has to go through the server (anything allowed at all). + fn needs_supervisor(&self) -> bool { + !self.rules.is_empty() + } + + /// Pin the allowlisted hostnames in `/etc/hosts`, so the sandbox resolves + /// them without DNS to the same addresses the allowlist holds. + /// + /// Best effort: an image whose `/etc/hosts` is read-only still enforces + /// the allowlist, its sandboxes just have to connect by address. + pub fn pin_hostnames(&self) { + static LOCK: Mutex<()> = Mutex::new(()); + if self.hosts.is_empty() { + return; + } + let _guard = LOCK.lock().unwrap(); + let existing = std::fs::read_to_string(HOSTS_FILE).unwrap_or_default(); + let known: BTreeSet<&str> = existing.lines().map(str::trim).collect(); + let mut missing = String::new(); + for (name, ips) in &self.hosts { + for ip in ips { + let line = format!("{ip}\t{name}"); + if !known.contains(line.as_str()) { + missing.push_str(&line); + missing.push('\n'); + } + } + } + if missing.is_empty() { + return; + } + let header = if existing.contains(HOSTS_MARKER) { String::new() } else { format!("{HOSTS_MARKER}\n") }; + let separator = if existing.is_empty() || existing.ends_with('\n') { "" } else { "\n" }; + let result = std::fs::OpenOptions::new() + .append(true) + .open(HOSTS_FILE) + .and_then(|mut f| f.write_all(format!("{separator}{header}{missing}").as_bytes())); + if let Err(e) = result { + eprintln!("sbx-server: cannot pin allowlisted hostnames in {HOSTS_FILE}: {e}"); + } + } +} + +enum Target { + Net(IpAddr, u8, Option), + Host(String, Option), +} + +fn full_prefix(ip: IpAddr) -> u8 { + if ip.is_ipv4() { + 32 + } else { + 128 + } +} + +/// Parse one allowlist entry: `IP`, `IP/PREFIX`, `IP:PORT`, `[IPv6]:PORT`, +/// `HOST` or `HOST:PORT`. A bare IPv6 address takes no port (wrap it in brackets). +fn parse_entry(entry: &str) -> Result { + let invalid = |why: &str| format!("invalid network.allow entry {entry:?}: {why}"); + let (host, port) = if let Some(rest) = entry.strip_prefix('[') { + let (inner, after) = rest.split_once(']').ok_or_else(|| invalid("missing ']'"))?; + match after { + "" => (inner, None), + _ => (inner, Some(after.strip_prefix(':').ok_or_else(|| invalid("expected ':PORT' after ']'"))?)), + } + } else if entry.matches(':').count() > 1 { + (entry, None) // bare IPv6 + } else { + match entry.split_once(':') { + Some((host, port)) => (host, Some(port)), + None => (entry, None), + } + }; + let port = match port { + None => None, + Some(p) => match p.parse::() { + Ok(p) if p > 0 => Some(p), + _ => return Err(invalid("port must be 1-65535")), + }, + }; + if let Some((ip, prefix)) = host.split_once('/') { + let ip: IpAddr = ip.parse().map_err(|_| invalid("a range must be IP/PREFIX"))?; + let prefix: u8 = prefix.parse().map_err(|_| invalid("bad prefix length"))?; + if prefix > full_prefix(ip) { + return Err(invalid("prefix length too long")); + } + return Ok(Target::Net(ip, prefix, port)); + } + if let Ok(ip) = host.parse::() { + return Ok(Target::Net(ip, full_prefix(ip), port)); + } + let valid_host = !host.is_empty() + && host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + && !label.starts_with('-') + }); + if !valid_host { + return Err(invalid("not an IP, a range or a hostname")); + } + Ok(Target::Host(host.to_ascii_lowercase(), port)) +} + +fn resolve(host: &str) -> Result, String> { + let ips: BTreeSet = (host, 0) + .to_socket_addrs() + .map_err(|e| format!("cannot resolve {host:?}: {e}"))? + .map(|addr| addr.ip()) + .collect(); + if ips.is_empty() { + return Err(format!("{host:?} resolved to no address")); + } + Ok(ips.into_iter().collect()) +} + +// --------------------------------------------------------------------------- +// Seccomp filter +// --------------------------------------------------------------------------- + +const AUDIT_ARCH_X86_64: u32 = 0xC000_003E; +const X32_SYSCALL_BIT: u32 = 0x4000_0000; + +const RET_ALLOW: u32 = 0x7fff_0000; +const RET_ERRNO: u32 = 0x0005_0000; +const RET_USER_NOTIF: u32 = 0x7fc0_0000; + +const BPF_LD_W_ABS: u16 = 0x20; +const BPF_ALU_AND_K: u16 = 0x54; +const BPF_JEQ_K: u16 = 0x15; +const BPF_JGE_K: u16 = 0x35; +const BPF_JSET_K: u16 = 0x45; +const BPF_RET_K: u16 = 0x06; + +/// Offsets into `struct seccomp_data`. +const DATA_NR: u32 = 0; +const DATA_ARCH: u32 = 4; +fn data_arg(i: u32) -> u32 { + 16 + 8 * i // low 32 bits on little-endian; every argument we test is an int +} + +const MSG_FASTOPEN: u32 = 0x2000_0000; + +/// A jump target while assembling: the next instruction, or a named label. +#[derive(Clone, Copy)] +enum To { + Next, + L(&'static str), +} + +/// A tiny BPF assembler with named labels, so the filter reads top to bottom. +#[derive(Default)] +struct Asm { + code: Vec<(u16, u32, To, To)>, + labels: Vec<(&'static str, usize)>, +} + +impl Asm { + fn stmt(&mut self, code: u16, k: u32) -> &mut Self { + self.code.push((code, k, To::Next, To::Next)); + self + } + fn jump(&mut self, code: u16, k: u32, jt: To, jf: To) -> &mut Self { + self.code.push((code, k, jt, jf)); + self + } + fn ret(&mut self, k: u32) -> &mut Self { + self.stmt(BPF_RET_K, k) + } + fn label(&mut self, name: &'static str) -> &mut Self { + self.labels.push((name, self.code.len())); + self + } + fn assemble(&self) -> Vec { + let offset = |at: usize, to: To| -> u8 { + let target = match to { + To::Next => at + 1, + To::L(name) => self.labels.iter().find(|(n, _)| *n == name).expect("unknown label").1, + }; + // BPF jumps are forward-only, relative and 8-bit. + let distance = target.checked_sub(at + 1).expect("BPF cannot jump backwards"); + u8::try_from(distance).expect("BPF jump out of range") + }; + self.code + .iter() + .enumerate() + .map(|(i, &(code, k, jt, jf))| libc::sock_filter { code, jt: offset(i, jt), jf: offset(i, jf), k }) + .collect() + } +} + +fn errno(e: i32) -> u32 { + RET_ERRNO | (e as u32 & 0xffff) +} + +/// The filter installed in every command of a restricted sandbox. +fn build_filter(notify_connect: bool) -> Vec { + use To::*; + let nr = |n: libc::c_long| n as u32; + let mut a = Asm::default(); + // Only native x86_64 syscalls: the i386 entry point has `socketcall`, which + // multiplexes every socket call behind one number, and x32 has its own table. + a.stmt(BPF_LD_W_ABS, DATA_ARCH) + .jump(BPF_JEQ_K, AUDIT_ARCH_X86_64, Next, L("deny")) + .stmt(BPF_LD_W_ABS, DATA_NR) + .jump(BPF_JGE_K, X32_SYSCALL_BIT, L("deny"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_socket), L("socket"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_socketpair), L("socketpair"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_connect), L("connect"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_sendto), L("arg3_flags"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_sendmmsg), L("arg3_flags"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_sendmsg), L("arg2_flags"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_io_uring_setup), L("enosys"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_ptrace), L("deny"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_process_vm_writev), L("deny"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_pidfd_getfd), L("deny"), L("allow")); + + // socket(domain, type, protocol): local families, or TCP over IPv4/IPv6. + a.label("socket") + .stmt(BPF_LD_W_ABS, data_arg(0)) + .jump(BPF_JEQ_K, libc::AF_UNIX as u32, L("allow"), Next) + .jump(BPF_JEQ_K, libc::AF_NETLINK as u32, L("allow"), Next) + .jump(BPF_JEQ_K, libc::AF_INET as u32, L("inet"), Next) + .jump(BPF_JEQ_K, libc::AF_INET6 as u32, L("inet"), L("eacces")) + .label("inet") + .stmt(BPF_LD_W_ABS, data_arg(1)) + .stmt(BPF_ALU_AND_K, 0xf) // strip SOCK_NONBLOCK / SOCK_CLOEXEC + .jump(BPF_JEQ_K, libc::SOCK_STREAM as u32, Next, L("eacces")) + .stmt(BPF_LD_W_ABS, data_arg(2)) + .jump(BPF_JEQ_K, 0, L("allow"), Next) + .jump(BPF_JEQ_K, libc::IPPROTO_TCP as u32, L("allow"), L("eacces")); + + a.label("socketpair").stmt(BPF_LD_W_ABS, data_arg(0)).jump( + BPF_JEQ_K, + libc::AF_UNIX as u32, + L("allow"), + L("eacces"), + ); + + // Without an allowlist, Landlock alone refuses every TCP connect. + a.label("connect").ret(if notify_connect { RET_USER_NOTIF } else { RET_ALLOW }); + + // TCP Fast Open connects from sendto/sendmsg, without the connect() hook. + a.label("arg3_flags").stmt(BPF_LD_W_ABS, data_arg(3)).jump(BPF_JSET_K, MSG_FASTOPEN, L("eacces"), L("allow")); + a.label("arg2_flags").stmt(BPF_LD_W_ABS, data_arg(2)).jump(BPF_JSET_K, MSG_FASTOPEN, L("eacces"), L("allow")); + + // BPF only jumps forward, so every verdict sits at the end. + a.label("allow").ret(RET_ALLOW); + a.label("eacces").ret(errno(libc::EACCES)); + a.label("enosys").ret(errno(libc::ENOSYS)); + a.label("deny").ret(errno(libc::EPERM)); + a.assemble() +} + +// --------------------------------------------------------------------------- +// Applying a policy to a spawned command +// --------------------------------------------------------------------------- + +const SECCOMP_SET_MODE_FILTER: libc::c_ulong = 1; +const SECCOMP_FILTER_FLAG_NEW_LISTENER: libc::c_ulong = 1 << 3; + +/// Everything the exec child needs, prepared before `fork` (the child must not allocate). +pub struct Prepared { + filter: Vec, + landlock_fd: RawFd, + /// Socket pair used to hand the seccomp listener from the child to the + /// server: (server end, child end). Only with an allowlist. + channel: Option<(OwnedFd, OwnedFd)>, +} + +impl Prepared { + pub fn new(policy: &Policy) -> Result { + let landlock_fd = crate::landlock::connect_ruleset().map_err(|e| format!("cannot restrict network: {e}"))?; + let channel = if policy.needs_supervisor() { + let mut fds = [0; 2]; + if unsafe { + libc::socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()) + } != 0 + { + return Err(format!("socketpair: {}", std::io::Error::last_os_error())); + } + Some(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) + } else { + None + }; + Ok(Prepared { filter: build_filter(policy.needs_supervisor()), landlock_fd, channel }) + } + + /// The pre-exec hook: confine the child, then (with an allowlist) send the + /// seccomp listener to the server. Runs between fork and exec, so it only + /// makes syscalls on memory prepared beforehand. + pub fn hook(&self) -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static { + let filter = self.filter.clone(); + let landlock_fd = self.landlock_fd; + let child_end = self.channel.as_ref().map(|(_, child)| child.as_raw_fd()); + move || unsafe { + if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + crate::landlock::restrict_self(landlock_fd)?; + let prog = libc::sock_fprog { len: filter.len() as u16, filter: filter.as_ptr() as *mut _ }; + let flags = if child_end.is_some() { SECCOMP_FILTER_FLAG_NEW_LISTENER } else { 0 }; + let listener = libc::syscall(libc::SYS_seccomp, SECCOMP_SET_MODE_FILTER, flags, &prog); + if listener < 0 { + return Err(std::io::Error::last_os_error()); + } + if let Some(sock) = child_end { + let sent = send_fd(sock, listener as RawFd); + libc::close(listener as RawFd); + sent?; + } + Ok(()) + } + } + + /// After a successful spawn: receive the listener and start answering + /// the child's `connect()` calls. `uid` is the sandbox uid in host mode. + pub fn start(self, policy: Arc, uid: Option) -> Result<(), String> { + let Some((server_end, child_end)) = self.channel else { + return Ok(()); + }; + drop(child_end); + let listener = recv_fd(server_end.as_raw_fd()).map_err(|e| format!("no seccomp listener from child: {e}"))?; + std::thread::spawn(move || supervise(Arc::new(listener), policy, uid)); + Ok(()) + } +} + +/// Send `fd` over a unix socket. Async-signal-safe: no allocation. +unsafe fn send_fd(sock: RawFd, fd: RawFd) -> std::io::Result<()> { + #[repr(C, align(8))] + struct Cmsg([u8; 32]); + let mut byte = [0u8; 1]; + let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 }; + let mut buf = Cmsg([0; 32]); + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = buf.0.as_mut_ptr().cast(); + msg.msg_controllen = libc::CMSG_SPACE(std::mem::size_of::() as u32) as _; + let cmsg = libc::CMSG_FIRSTHDR(&msg); + (*cmsg).cmsg_level = libc::SOL_SOCKET; + (*cmsg).cmsg_type = libc::SCM_RIGHTS; + (*cmsg).cmsg_len = libc::CMSG_LEN(std::mem::size_of::() as u32) as _; + std::ptr::write_unaligned(libc::CMSG_DATA(cmsg).cast::(), fd); + if libc::sendmsg(sock, &msg, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) +} + +fn recv_fd(sock: RawFd) -> std::io::Result { + #[repr(C, align(8))] + struct Cmsg([u8; 32]); + let mut byte = [0u8; 1]; + let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 }; + let mut buf = Cmsg([0; 32]); + unsafe { + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = buf.0.as_mut_ptr().cast(); + msg.msg_controllen = buf.0.len() as _; + // The child sent it before exec, and spawn only returns after exec. + if libc::recvmsg(sock, &mut msg, libc::MSG_DONTWAIT | libc::MSG_CMSG_CLOEXEC) < 0 { + return Err(std::io::Error::last_os_error()); + } + let cmsg = libc::CMSG_FIRSTHDR(&msg); + if cmsg.is_null() || (*cmsg).cmsg_level != libc::SOL_SOCKET || (*cmsg).cmsg_type != libc::SCM_RIGHTS { + return Err(std::io::Error::other("message carried no descriptor")); + } + Ok(OwnedFd::from_raw_fd(std::ptr::read_unaligned(libc::CMSG_DATA(cmsg).cast::()))) + } +} + +// --------------------------------------------------------------------------- +// Connect supervisor +// --------------------------------------------------------------------------- + +#[repr(C)] +#[derive(Clone, Copy)] +struct SeccompData { + nr: i32, + arch: u32, + instruction_pointer: u64, + args: [u64; 6], +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Notif { + id: u64, + pid: u32, + flags: u32, + data: SeccompData, +} + +#[repr(C)] +struct NotifResp { + id: u64, + val: i64, + error: i32, + flags: u32, +} + +#[repr(C)] +struct NotifAddfd { + id: u64, + flags: u32, + srcfd: u32, + newfd: u32, + newfd_flags: u32, +} + +// _IOWR('!', 0, struct seccomp_notif), _IOWR('!', 1, struct seccomp_notif_resp), +// _IOW('!', 2, __u64), _IOW('!', 3, struct seccomp_notif_addfd) +const SECCOMP_IOCTL_NOTIF_RECV: u32 = 0xc050_2100; +const SECCOMP_IOCTL_NOTIF_SEND: u32 = 0xc018_2101; +const SECCOMP_IOCTL_NOTIF_ID_VALID: u32 = 0x4008_2102; +const SECCOMP_IOCTL_NOTIF_ADDFD: u32 = 0x4018_2103; +const SECCOMP_USER_NOTIF_FLAG_CONTINUE: u32 = 1; +const SECCOMP_ADDFD_FLAG_SETFD: u32 = 1; + +/// Answer the `connect()` calls of one spawned command (and its descendants) +/// until all of them have exited. +fn supervise(listener: Arc, policy: Arc, uid: Option) { + let fd = listener.as_raw_fd(); + loop { + let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; + if unsafe { libc::poll(&mut pfd, 1, -1) } < 0 { + if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { + continue; + } + return; + } + if pfd.revents & libc::POLLIN == 0 { + return; // POLLHUP: no process uses this filter any more + } + let mut req: Notif = unsafe { std::mem::zeroed() }; + if unsafe { libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_RECV as libc::Ioctl, &mut req) } != 0 { + continue; // the caller died or was interrupted in the meantime + } + // One thread per call: a blocking connect must not hold up the others. + let (listener, policy) = (Arc::clone(&listener), Arc::clone(&policy)); + std::thread::spawn(move || answer(&listener, &req, &policy, uid)); + } +} + +/// What to tell the kernel about one intercepted `connect()`. +enum Verdict { + /// Run the syscall as the sandbox asked (a non-IP socket). + Continue, + /// Return this from the syscall: 0, or a negative errno. + Return(i32), +} + +fn answer(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) { + let verdict = decide(listener, req, policy, uid); + let (val, error, flags) = match verdict { + Verdict::Continue => (0, 0, SECCOMP_USER_NOTIF_FLAG_CONTINUE), + Verdict::Return(rc) => (0, rc.min(0), 0), + }; + let mut resp = NotifResp { id: req.id, val, error, flags }; + unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_SEND as libc::Ioctl, &mut resp) }; +} + +fn last_errno() -> i32 { + -std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO) +} + +fn decide(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) -> Verdict { + // Read the sandbox's memory as the sandbox's uid, so the kernel's ptrace + // access check passes in host mode. Only the filesystem ids change: the + // thread keeps its real uid, so a sandbox cannot signal it. + if let Some(uid) = uid { + unsafe { + libc::syscall(libc::SYS_setfsgid, uid); + libc::syscall(libc::SYS_setfsuid, uid); + } + } + let [fd, addr_ptr, addr_len, ..] = req.data.args; + let len = addr_len as usize; + if !(2..=MAX_SOCKADDR).contains(&len) { + return Verdict::Return(-libc::EINVAL); + } + let mut addr = [0u8; MAX_SOCKADDR]; + let read = std::fs::File::open(format!("/proc/{}/mem", req.pid)) + .and_then(|mem| mem.read_exact_at(&mut addr[..len], addr_ptr)); + // The pid may have been reused since the notification was queued; only + // trust what we read if the notification is still alive. + let mut id = req.id; + if unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ID_VALID as libc::Ioctl, &mut id) } != 0 { + return Verdict::Return(-libc::EINTR); + } + if let Err(e) = read { + eprintln!("sbx-server: network: cannot read connect() address of pid {}: {e}", req.pid); + return Verdict::Return(-libc::EACCES); + } + let Some(dest) = parse_sockaddr(&addr[..len]) else { + // Not an IP destination. If the address is swapped for an IP one before + // the kernel re-reads it, Landlock refuses the connect. + return Verdict::Continue; + }; + if !policy.allows(dest.ip(), dest.port()) { + return Verdict::Return(-libc::EACCES); + } + // Keep the sandbox's O_NONBLOCK and O_CLOEXEC on the replacement socket. + let fdinfo = std::fs::read_to_string(format!("/proc/{}/fdinfo/{fd}", req.pid)).unwrap_or_default(); + let fd_flags = fdinfo + .lines() + .find_map(|l| l.strip_prefix("flags:")) + .and_then(|v| i32::from_str_radix(v.trim(), 8).ok()) + .unwrap_or(0); + let family = if dest.is_ipv4() && addr[..2] == (libc::AF_INET as u16).to_ne_bytes() { + libc::AF_INET + } else { + libc::AF_INET6 + }; + let sock = unsafe { libc::socket(family, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) }; + if sock < 0 { + return Verdict::Return(last_errno()); + } + let sock = unsafe { OwnedFd::from_raw_fd(sock) }; + if fd_flags & libc::O_NONBLOCK != 0 { + unsafe { libc::fcntl(sock.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; + } + // Connect the address we checked, from our own copy of it. + let rc = unsafe { libc::connect(sock.as_raw_fd(), addr.as_ptr().cast(), len as libc::socklen_t) }; + let result = if rc == 0 { 0 } else { last_errno() }; + if result != 0 && result != -libc::EINPROGRESS { + return Verdict::Return(result); + } + let mut addfd = NotifAddfd { + id: req.id, + flags: SECCOMP_ADDFD_FLAG_SETFD, + srcfd: sock.as_raw_fd() as u32, + newfd: fd as u32, + newfd_flags: (fd_flags & libc::O_CLOEXEC) as u32, + }; + if unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ADDFD as libc::Ioctl, &mut addfd) } < 0 { + return Verdict::Return(last_errno()); + } + Verdict::Return(result) +} + +/// The IP destination of a `sockaddr`, or None for any other family. +fn parse_sockaddr(raw: &[u8]) -> Option { + let family = u16::from_ne_bytes([raw[0], raw[1]]) as i32; + match family { + libc::AF_INET if raw.len() >= 8 => { + let port = u16::from_be_bytes([raw[2], raw[3]]); + Some(SocketAddr::from((Ipv4Addr::new(raw[4], raw[5], raw[6], raw[7]), port))) + } + libc::AF_INET6 if raw.len() >= 24 => { + let port = u16::from_be_bytes([raw[2], raw[3]]); + let octets: [u8; 16] = raw[8..24].try_into().unwrap(); + Some(SocketAddr::from((Ipv6Addr::from(octets), port))) + } + // A short IP sockaddr: let the kernel reject it (EINVAL). + libc::AF_INET | libc::AF_INET6 => Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn fake_resolve(host: &str) -> Result, String> { + match host { + "vllm.internal" => Ok(vec!["10.0.3.7".parse().unwrap()]), + _ => Err(format!("cannot resolve {host:?}")), + } + } + + fn policy(entries: &[&str]) -> Policy { + Policy::parse_with(&json!({"allow": entries}), fake_resolve).unwrap() + } + + fn allows(p: &Policy, dest: &str) -> bool { + let dest: SocketAddr = dest.parse().unwrap(); + p.allows(dest.ip(), dest.port()) + } + + #[test] + fn none_allows_nothing() { + let p = Policy::parse(&json!("none")).unwrap(); + assert!(!p.needs_supervisor()); + assert!(!allows(&p, "127.0.0.1:80")); + assert!(!allows(&p, "[::1]:80")); + } + + #[test] + fn ranges_addresses_ports_and_hostnames() { + let p = + policy(&["10.0.0.0/8", "203.0.113.10:443", "[2001:db8::1]:8000", "2001:db8:1::/48", "vllm.internal:8000"]); + assert!(p.needs_supervisor()); + assert!(allows(&p, "10.1.2.3:22")); + assert!(!allows(&p, "11.0.0.1:22")); + assert!(allows(&p, "203.0.113.10:443")); + assert!(!allows(&p, "203.0.113.10:80")); + assert!(allows(&p, "[2001:db8::1]:8000")); + assert!(!allows(&p, "[2001:db8::1]:8001")); + assert!(allows(&p, "[2001:db8:1:ffff::5]:1")); + // An IPv4-mapped IPv6 destination is checked as the IPv4 address it is. + assert!(allows(&p, "[::ffff:10.0.0.1]:80")); + assert!(!allows(&p, "[::ffff:11.0.0.1]:80")); + // A hostname allows the addresses it resolved to, on its port only. + assert!(allows(&p, "10.0.3.7:8000")); + assert_eq!(p.hosts, vec![("vllm.internal".to_string(), vec!["10.0.3.7".parse().unwrap()])]); + } + + #[test] + fn prefixes_that_are_not_byte_aligned() { + let p = policy(&["192.168.4.0/22"]); + assert!(allows(&p, "192.168.7.255:1")); + assert!(!allows(&p, "192.168.8.0:1")); + assert!(allows(&policy(&["0.0.0.0/0"]), "8.8.8.8:53")); + } + + #[test] + fn invalid_policies_are_rejected() { + for bad in [ + json!("all"), + json!({"allow": "10.0.0.0/8"}), + json!({"allow": [1]}), + json!({"allow": [], "deny": []}), + json!({"allow": ["10.0.0.0/33"]}), + json!({"allow": ["10.0.0.1:0"]}), + json!({"allow": ["10.0.0.1:http"]}), + json!({"allow": ["[::1"]}), + json!({"allow": ["bad host"]}), + json!({"allow": ["unknown.internal"]}), + ] { + assert!(Policy::parse_with(&bad, fake_resolve).is_err(), "{bad} should be rejected"); + } + } + + #[test] + fn the_filter_assembles() { + // Every jump must land inside the program, which `assemble` asserts. + for notify in [false, true] { + let prog = build_filter(notify); + assert!(prog.len() < 64); + assert_eq!(prog.last().unwrap().code, BPF_RET_K); + } + } + + #[test] + fn sockaddrs_are_decoded() { + let mut v4 = [0u8; 16]; + v4[..2].copy_from_slice(&(libc::AF_INET as u16).to_ne_bytes()); + v4[2..4].copy_from_slice(&443u16.to_be_bytes()); + v4[4..8].copy_from_slice(&[10, 0, 3, 7]); + assert_eq!(parse_sockaddr(&v4), Some("10.0.3.7:443".parse().unwrap())); + let mut unix = [0u8; 16]; + unix[..2].copy_from_slice(&(libc::AF_UNIX as u16).to_ne_bytes()); + assert_eq!(parse_sockaddr(&unix), None); + } +} diff --git a/src/proxy.rs b/src/proxy.rs index fb78954..68cbe06 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -298,6 +298,7 @@ mod tests { token: "sandbox-capability-token".to_string(), confinement: crate::sandboxes::Confinement::UidOnly, deleted: std::sync::Mutex::new(false), + network: None, last_activity_ms: AtomicI64::new(0), idle_timeout_ms: 0, } diff --git a/src/sandboxes.rs b/src/sandboxes.rs index 59e77a0..64feec8 100644 --- a/src/sandboxes.rs +++ b/src/sandboxes.rs @@ -82,6 +82,8 @@ pub struct SandboxEntry { pub last_activity_ms: AtomicI64, /// Evict the sandbox after this many ms with no activity (0 = never). pub idle_timeout_ms: i64, + /// Network policy applied to every command it runs. None = unrestricted. + pub network: Option>, } /// How a sandbox is confined. @@ -274,6 +276,7 @@ impl SandboxRegistry { max_procs: Option, max_mem_mb: Option, idle_timeout_ms: i64, + network: Option>, ) -> Result, CreateError> { // Reserve a slot before doing any work, so two concurrent creates can't both // squeeze past the last free slot. @@ -290,7 +293,7 @@ impl SandboxRegistry { eprintln!("sbx-server: uid range exhausted; reporting this host as full"); return Err(CreateError::Full); }; - match self.create_inner(uid, env, max_procs, max_mem_mb, idle_timeout_ms) { + match self.create_inner(uid, env, max_procs, max_mem_mb, idle_timeout_ms, network) { Ok(entry) => Ok(entry), Err(e) => { self.reserved.fetch_sub(1, Ordering::SeqCst); // release the slot we couldn't fill @@ -308,6 +311,7 @@ impl SandboxRegistry { max_procs: Option, max_mem_mb: Option, idle_timeout_ms: i64, + network: Option>, ) -> std::io::Result> { let id = random_hex(8)?; let token = random_hex(32)?; @@ -355,6 +359,7 @@ impl SandboxRegistry { deleted: Mutex::new(false), last_activity_ms: AtomicI64::new(now_ms()), idle_timeout_ms, + network, }); self.map.lock().unwrap().insert(id, Arc::clone(&entry)); Ok(entry) @@ -432,6 +437,7 @@ impl SandboxRegistry { "home": s.home, "created_at_ms": s.created_at_ms, "confinement": s.confinement.label(), + "network": network_spec(&s.network), }) }) .collect(), @@ -509,6 +515,11 @@ fn pids_of_uid(uid: u32) -> Vec { pids } +/// How a network policy is reported back: the value the client sent, or null. +pub fn network_spec(policy: &Option>) -> serde_json::Value { + policy.as_ref().map_or(serde_json::Value::Null, |p| p.spec.clone()) +} + /// Applied to the child between fork and exec (see exec::spawn). pub fn pre_exec_isolation(entry: &SandboxEntry) -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static { let max_procs = entry.max_procs; @@ -637,13 +648,29 @@ pub fn handle_create( } other => other, }; + // Network policy, shared by the `count` sandboxes. Parsed (and its hostnames + // resolved) once per request. + let network = match json.get("network") { + None | Some(serde_json::Value::Null) => None, + Some(value) => match crate::network::Policy::parse(value) { + Ok(policy) => { + // The policy needs Landlock for TCP connects; a uid-only host cannot apply it. + if let Err(e) = crate::landlock::connect_ruleset() { + return resp.error(400, &format!("this host cannot restrict the network: {e}")); + } + policy.pin_hostnames(); + Some(Arc::new(policy)) + } + Err(e) => return resp.error(400, &e), + }, + }; // Per-sandbox idle timeout (the host has its own, for when it's empty). 0 = never. let idle_timeout_ms = json.get("idle_timeout_secs").and_then(|v| v.as_i64()).unwrap_or(0) * 1000; let mut created = Vec::with_capacity(count); let mut rejected = 0usize; for _ in 0..count { - match state.sandboxes.create(env.clone(), max_procs, max_mem_mb, idle_timeout_ms) { + match state.sandboxes.create(env.clone(), max_procs, max_mem_mb, idle_timeout_ms, network.clone()) { Ok(entry) => created.push( serde_json::json!({ "id": entry.id, @@ -651,6 +678,9 @@ pub fn handle_create( "uid": entry.uid, "home": entry.home, "confinement": entry.confinement.label(), + // Echoed so a client can tell this server applied it: an + // older one ignores the field and returns no `network`. + "network": network_spec(&entry.network), }), ), // Host full: report how many we couldn't place so the client packs them From b8e77c0626b7fc64d4ed31d24ebac85c63187751 Mon Sep 17 00:00:00 2001 From: Wauplin Date: Wed, 4 Nov 2026 16:34:06 +0100 Subject: [PATCH 2/5] 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 --- README.md | 6 +- scripts/network-regression.sh | 38 ++- src/exec.rs | 36 +-- src/landlock.rs | 6 + src/main.rs | 5 + src/network.rs | 527 ++++++++++++++++++++++++++++------ 6 files changed, 515 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index eacd42d..c11318e 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/scripts/network-regression.sh b/scripts/network-regression.sh index 597daa5..9b63a59 100644 --- a/scripts/network-regression.sh +++ b/scripts/network-regression.sh @@ -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": @@ -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... @@ -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 @@ -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" diff --git a/src/exec.rs b/src/exec.rs index aad297e..3a2513b 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -206,9 +206,24 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result { + 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()) @@ -227,11 +242,9 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result 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 @@ -241,15 +254,6 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result EOF). if let Some(input) = &spec.stdin { diff --git a/src/landlock.rs b/src/landlock.rs index 37ec4d4..b263789 100644 --- a/src/landlock.rs +++ b/src/landlock.rs @@ -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"] { diff --git a/src/main.rs b/src/main.rs index 3ce1674..1e0dbab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -427,6 +427,11 @@ fn env_number(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. diff --git a/src/network.rs b/src/network.rs index a78e512..1ff5b10 100644 --- a/src/network.rs +++ b/src/network.rs @@ -22,16 +22,16 @@ //! and listening stay allowed, so the port proxy still reaches servers that //! run in a dedicated sandbox. //! -//! With `"none"`, that is all. With an allowlist, the seccomp filter also -//! sends every `connect()` to the server (`SECCOMP_RET_USER_NOTIF`). The -//! server reads the destination, checks it against the allowlist and, if it -//! matches, creates a socket of its own, connects it and installs it in place -//! of the sandbox's socket (`SECCOMP_IOCTL_NOTIF_ADDFD`). The server connects -//! the address it read, not whatever the sandbox's memory holds by the time the -//! kernel would re-read it, so there is no time-of-check/time-of-use gap. A -//! `connect()` on a non-IP socket (unix) is let through unchanged: the kernel -//! re-reads the address, but if it was swapped for an IP one the Landlock rule -//! refuses it. +//! With `"none"`, that is all. With an allowlist, the seccomp filter sends the +//! sandbox's IP `socket()`, `connect()` and `listen()` calls to a supervisor +//! (`SECCOMP_RET_USER_NOTIF`): the server binary run again as the command's +//! parent, inside the sandbox (see "Connect supervisor" below). The supervisor +//! creates every IP socket the sandbox asks for and keeps a handle on it. On +//! `connect()`, it reads the destination, checks it against the allowlist and +//! connects its handle, which is the sandbox's own socket, to the address it +//! read. Changing the sandbox's memory after the check has no effect. A +//! `connect()` to a non-IP address (unix) is let through unchanged: the kernel +//! re-reads the address, but if it was swapped for an IP one, Landlock refuses it. //! //! Hostnames in the allowlist are resolved once, by the server, and pinned in //! `/etc/hosts`, so the sandbox resolves them without DNS (it cannot send UDP) @@ -39,13 +39,16 @@ //! //! Implemented with raw syscalls to stay a zero-dependency static binary. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; use std::io::Write; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::os::unix::fs::FileExt; use std::os::unix::io::RawFd; -use std::sync::{Arc, Mutex}; +use std::os::unix::process::CommandExt; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; /// Most allowlist entries accepted in one policy. const MAX_RULES: usize = 256; @@ -152,11 +155,6 @@ impl Policy { self.rules.iter().any(|rule| rule.matches(ip, port)) } - /// Whether `connect()` has to go through the server (anything allowed at all). - fn needs_supervisor(&self) -> bool { - !self.rules.is_empty() - } - /// Pin the allowlisted hostnames in `/etc/hosts`, so the sandbox resolves /// them without DNS to the same addresses the allowlist holds. /// @@ -350,7 +348,10 @@ fn errno(e: i32) -> u32 { } /// The filter installed in every command of a restricted sandbox. -fn build_filter(notify_connect: bool) -> Vec { +/// +/// With `supervised`, the IP sockets the sandbox creates, its `connect()` and +/// `listen()` calls go to the connect supervisor instead of the kernel. +fn build_filter(supervised: bool) -> Vec { use To::*; let nr = |n: libc::c_long| n as u32; let mut a = Asm::default(); @@ -362,7 +363,8 @@ fn build_filter(notify_connect: bool) -> Vec { .jump(BPF_JGE_K, X32_SYSCALL_BIT, L("deny"), Next) .jump(BPF_JEQ_K, nr(libc::SYS_socket), L("socket"), Next) .jump(BPF_JEQ_K, nr(libc::SYS_socketpair), L("socketpair"), Next) - .jump(BPF_JEQ_K, nr(libc::SYS_connect), L("connect"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_connect), L("supervised"), Next) + .jump(BPF_JEQ_K, nr(libc::SYS_listen), L("supervised"), Next) .jump(BPF_JEQ_K, nr(libc::SYS_sendto), L("arg3_flags"), Next) .jump(BPF_JEQ_K, nr(libc::SYS_sendmmsg), L("arg3_flags"), Next) .jump(BPF_JEQ_K, nr(libc::SYS_sendmsg), L("arg2_flags"), Next) @@ -383,8 +385,8 @@ fn build_filter(notify_connect: bool) -> Vec { .stmt(BPF_ALU_AND_K, 0xf) // strip SOCK_NONBLOCK / SOCK_CLOEXEC .jump(BPF_JEQ_K, libc::SOCK_STREAM as u32, Next, L("eacces")) .stmt(BPF_LD_W_ABS, data_arg(2)) - .jump(BPF_JEQ_K, 0, L("allow"), Next) - .jump(BPF_JEQ_K, libc::IPPROTO_TCP as u32, L("allow"), L("eacces")); + .jump(BPF_JEQ_K, 0, L("supervised"), Next) + .jump(BPF_JEQ_K, libc::IPPROTO_TCP as u32, L("supervised"), L("eacces")); a.label("socketpair").stmt(BPF_LD_W_ABS, data_arg(0)).jump( BPF_JEQ_K, @@ -394,7 +396,7 @@ fn build_filter(notify_connect: bool) -> Vec { ); // Without an allowlist, Landlock alone refuses every TCP connect. - a.label("connect").ret(if notify_connect { RET_USER_NOTIF } else { RET_ALLOW }); + a.label("supervised").ret(if supervised { RET_USER_NOTIF } else { RET_ALLOW }); // TCP Fast Open connects from sendto/sendmsg, without the connect() hook. a.label("arg3_flags").stmt(BPF_LD_W_ABS, data_arg(3)).jump(BPF_JSET_K, MSG_FASTOPEN, L("eacces"), L("allow")); @@ -470,14 +472,14 @@ impl Prepared { } /// After a successful spawn: receive the listener and start answering - /// the child's `connect()` calls. `uid` is the sandbox uid in host mode. - pub fn start(self, policy: Arc, uid: Option) -> Result<(), String> { + /// the child's `connect()` calls (only with an allowlist). + fn start(self, policy: Arc) -> Result<(), String> { let Some((server_end, child_end)) = self.channel else { return Ok(()); }; drop(child_end); let listener = recv_fd(server_end.as_raw_fd()).map_err(|e| format!("no seccomp listener from child: {e}"))?; - std::thread::spawn(move || supervise(Arc::new(listener), policy, uid)); + std::thread::spawn(move || supervise(Arc::new(listener), policy)); Ok(()) } } @@ -532,6 +534,145 @@ fn recv_fd(sock: RawFd) -> std::io::Result { // --------------------------------------------------------------------------- // Connect supervisor // --------------------------------------------------------------------------- +// +// With an allowlist, the server does not run the command directly. It runs +// itself again (`sbx-server --net-supervise RULES -- ARGV...`) with the +// sandbox's uid, home, rlimits and Landlock domain, and that process starts +// the command and answers its socket calls: +// +// - It creates the sandbox's IP sockets and installs them as the result of +// `socket()` (`SECCOMP_ADDFD_FLAG_SEND`), so it holds the same open file as +// the sandbox. Connecting that handle connects the sandbox's socket: epoll +// registrations, duplicated descriptors, socket options and EISCONN behave +// as they do without a policy. (`pidfd_getfd` would avoid holding handles, +// but the Jobs seccomp profile refuses it without CAP_SYS_PTRACE.) +// - It lives in the command's process group and under the sandbox's limits: +// a timeout or kill ends it together with the command, and its threads +// count against the sandbox's RLIMIT_NPROC, not the server's. +// - It is a subreaper, so orphaned descendants stay under it while the +// command runs. When the command exits, the supervisor exits too, and +// leftover background processes lose their allowlisted access (ENOSYS). +// - It is not dumpable, so the sandbox (same uid) cannot ptrace it or write +// to its memory. It can kill it; then connects fail (ENOSYS): closed. + +/// argv[1] that turns the binary into a connect supervisor. +pub const SUPERVISOR_FLAG: &str = "--net-supervise"; + +/// Concurrent `connect()` calls one supervisor handles; past it they fail with EAGAIN. +const MAX_PENDING_CONNECTS: usize = 64; + +impl Policy { + /// The rules as allowlist entries with every hostname already resolved, + /// to hand to a supervisor without resolving anything again. + pub fn resolved_allowlist(&self) -> String { + let entries: Vec = self + .rules + .iter() + .map(|rule| { + let net = format!("{}/{}", rule.addr, rule.prefix); + match (rule.port, rule.addr) { + (None, _) => net, + (Some(port), IpAddr::V4(_)) => format!("{net}:{port}"), + (Some(port), IpAddr::V6(_)) => format!("[{net}]:{port}"), + } + }) + .collect(); + serde_json::json!({ "allow": entries }).to_string() + } + + /// Whether commands run through a connect supervisor (anything allowed at all). + pub fn needs_supervisor(&self) -> bool { + !self.rules.is_empty() + } +} + +/// The path of this binary, which is run again as a connect supervisor. +pub fn server_exe() -> Result<&'static std::path::Path, String> { + static EXE: OnceLock> = OnceLock::new(); + EXE.get_or_init(|| std::env::current_exe().map_err(|e| format!("cannot locate the server binary: {e}"))) + .as_deref() + .map_err(Clone::clone) +} + +/// Entry point of `sbx-server --net-supervise ...`; None when not invoked that way. +pub fn supervisor_main() -> Option { + let args: Vec = std::env::args().collect(); + if args.get(1).map(String::as_str) != Some(SUPERVISOR_FLAG) { + return None; + } + Some(run_supervisor(&args[2..])) +} + +fn run_supervisor(args: &[String]) -> i32 { + let (Some(rules), Some("--"), Some(program)) = (args.first(), args.get(1).map(String::as_str), args.get(2)) else { + eprintln!("usage: sbx-server {SUPERVISOR_FLAG} RULES -- PROGRAM [ARGS...]"); + return 2; + }; + unsafe { + libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0); + libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); + } + let policy = serde_json::from_str(rules) + .map_err(|e| e.to_string()) + .and_then(|value| Policy::parse_with(&value, |host| Err(format!("unresolved hostname {host:?}")))); + let policy = match policy { + Ok(policy) if policy.needs_supervisor() => Arc::new(policy), + Ok(_) => { + eprintln!("sbx-server: {SUPERVISOR_FLAG} needs a non-empty allowlist"); + return 2; + } + Err(e) => { + eprintln!("sbx-server: {SUPERVISOR_FLAG}: {e}"); + return 2; + } + }; + let prepared = match Prepared::new(&policy) { + Ok(prepared) => prepared, + Err(e) => { + eprintln!("sbx-server: {e}"); + return 126; + } + }; + let mut command = std::process::Command::new(program); + command.args(&args[3..]); + unsafe { command.pre_exec(prepared.hook()) }; + let child = match command.spawn() { + Ok(child) => child, + Err(e) => { + eprintln!("sbx-server: failed to spawn '{program}': {e}"); + return if e.kind() == std::io::ErrorKind::NotFound { 127 } else { 126 }; + } + }; + let main_pid = child.id() as libc::pid_t; + if let Err(e) = prepared.start(policy) { + eprintln!("sbx-server: {e}"); + unsafe { libc::kill(main_pid, libc::SIGKILL) }; + } + // Reap whatever ends up under us (we are a subreaper) until the command + // exits, then exit the same way so the server reports its status. + loop { + let mut status = 0; + let pid = unsafe { libc::waitpid(-1, &mut status, 0) }; + if pid < 0 { + if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { + continue; + } + return 1; + } + if pid != main_pid { + continue; + } + if libc::WIFSIGNALED(status) { + let signal = libc::WTERMSIG(status); + unsafe { + libc::signal(signal, libc::SIG_DFL); + libc::raise(signal); + } + return 128 + signal; + } + return libc::WEXITSTATUS(status); + } +} #[repr(C)] #[derive(Clone, Copy)] @@ -575,11 +716,115 @@ const SECCOMP_IOCTL_NOTIF_SEND: u32 = 0xc018_2101; const SECCOMP_IOCTL_NOTIF_ID_VALID: u32 = 0x4008_2102; const SECCOMP_IOCTL_NOTIF_ADDFD: u32 = 0x4018_2103; const SECCOMP_USER_NOTIF_FLAG_CONTINUE: u32 = 1; -const SECCOMP_ADDFD_FLAG_SETFD: u32 = 1; +const SECCOMP_ADDFD_FLAG_SEND: u32 = 1 << 1; -/// Answer the `connect()` calls of one spawned command (and its descendants) -/// until all of them have exited. -fn supervise(listener: Arc, policy: Arc, uid: Option) { +/// How often handles on sockets nobody uses any more are dropped. +const SWEEP_INTERVAL: Duration = Duration::from_secs(1); +/// A socket younger than this is never swept: it may not be in the caller's +/// descriptor table yet. +const SWEEP_GRACE: Duration = Duration::from_secs(2); + +/// The supervisor's handles on the IP sockets of the sandbox, by inode. +/// +/// Every IP socket the sandbox has was created here and handed over with +/// `SECCOMP_ADDFD_FLAG_SEND`, so the handle and the sandbox's descriptor are +/// the same open file: connecting the handle connects the sandbox's socket, +/// with its epoll registrations, duplicates and options. A handle is dropped +/// once it is not needed (connected, listening, or closed by the sandbox), so +/// the supervisor never keeps a socket alive that the sandbox closed for longer +/// than one sweep. +#[derive(Default)] +struct Sockets { + /// Not connected yet: (handle, created at). + open: Mutex>, + /// Connected and released; a new connect() on them is EISCONN. + connected: Mutex>, +} + +impl Sockets { + fn handle(&self, inode: u64) -> Option { + self.open.lock().unwrap().get(&inode).and_then(|(fd, _)| fd.try_clone().ok()) + } + + fn release(&self, inode: u64, connected: bool) { + self.open.lock().unwrap().remove(&inode); + if connected { + self.connected.lock().unwrap().insert(inode); + } + } + + /// Drop the handles that are no longer needed. + fn sweep(&self) { + let now = Instant::now(); + let candidates: Vec<(u64, RawFd)> = { + let open = self.open.lock().unwrap(); + if open.is_empty() && self.connected.lock().unwrap().is_empty() { + return; + } + open.iter() + .filter(|(_, (_, at))| now - *at >= SWEEP_GRACE) + .map(|(&ino, (fd, _))| (ino, fd.as_raw_fd())) + .collect() + }; + let in_use = sandbox_socket_inodes(); + let mut open = self.open.lock().unwrap(); + let mut connected = self.connected.lock().unwrap(); + for (inode, fd) in candidates { + if is_connected(fd) { + connected.insert(inode); + open.remove(&inode); + } else if !in_use.contains(&inode) { + open.remove(&inode); + } + } + connected.retain(|inode| in_use.contains(inode)); + } +} + +fn is_connected(fd: RawFd) -> bool { + let mut addr: libc::sockaddr_storage = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + unsafe { libc::getpeername(fd, (&mut addr as *mut libc::sockaddr_storage).cast(), &mut len) == 0 } +} + +/// Inodes of every socket in the descriptor table of a process we can see, +/// other than ourselves. +fn sandbox_socket_inodes() -> BTreeSet { + let me = std::process::id().to_string(); + let mut inodes = BTreeSet::new(); + let Ok(procs) = std::fs::read_dir("/proc") else { return inodes }; + for proc in procs.flatten() { + let name = proc.file_name(); + let Some(pid) = name.to_str().filter(|n| n.bytes().all(|b| b.is_ascii_digit()) && *n != me) else { + continue; + }; + let Ok(fds) = std::fs::read_dir(format!("/proc/{pid}/fd")) else { continue }; + for fd in fds.flatten() { + if let Some(inode) = std::fs::read_link(fd.path()).ok().and_then(|link| socket_inode_of(&link)) { + inodes.insert(inode); + } + } + } + inodes +} + +/// `socket:[12345]` -> 12345. +fn socket_inode_of(link: &std::path::Path) -> Option { + link.to_str()?.strip_prefix("socket:[")?.strip_suffix(']')?.parse().ok() +} + +/// Answer the calls of the command (and its descendants) until all of them +/// have exited. +fn supervise(listener: Arc, policy: Arc) { + static PENDING: AtomicUsize = AtomicUsize::new(0); + let sockets = Arc::new(Sockets::default()); + { + let sockets = Arc::clone(&sockets); + std::thread::spawn(move || loop { + std::thread::sleep(SWEEP_INTERVAL); + sockets.sweep(); + }); + } let fd = listener.as_raw_fd(); loop { let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; @@ -596,44 +841,111 @@ fn supervise(listener: Arc, policy: Arc, uid: Option) { if unsafe { libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_RECV as libc::Ioctl, &mut req) } != 0 { continue; // the caller died or was interrupted in the meantime } - // One thread per call: a blocking connect must not hold up the others. - let (listener, policy) = (Arc::clone(&listener), Arc::clone(&policy)); - std::thread::spawn(move || answer(&listener, &req, &policy, uid)); + // One thread per call, so a slow connect does not hold up the others, + // but a bounded number of them. + if PENDING.fetch_add(1, Ordering::SeqCst) >= MAX_PENDING_CONNECTS { + PENDING.fetch_sub(1, Ordering::SeqCst); + respond(&listener, req.id, Verdict::Return(-libc::EAGAIN)); + continue; + } + let (worker_listener, policy, sockets) = (Arc::clone(&listener), Arc::clone(&policy), Arc::clone(&sockets)); + let spawned = std::thread::Builder::new().spawn(move || { + let verdict = match req.data.nr as libc::c_long { + libc::SYS_socket => on_socket(&worker_listener, &req, &sockets), + libc::SYS_listen => on_listen(&req, &sockets), + _ => on_connect(&worker_listener, &req, &policy, &sockets), + }; + respond(&worker_listener, req.id, verdict); + PENDING.fetch_sub(1, Ordering::SeqCst); + }); + if spawned.is_err() { + PENDING.fetch_sub(1, Ordering::SeqCst); + respond(&listener, req.id, Verdict::Return(-libc::EAGAIN)); + } } } -/// What to tell the kernel about one intercepted `connect()`. +/// What to tell the kernel about one intercepted call. enum Verdict { - /// Run the syscall as the sandbox asked (a non-IP socket). + /// Run the syscall as the sandbox asked. Continue, /// Return this from the syscall: 0, or a negative errno. Return(i32), + /// Already answered (by `SECCOMP_ADDFD_FLAG_SEND`). + Answered, } -fn answer(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) { - let verdict = decide(listener, req, policy, uid); - let (val, error, flags) = match verdict { - Verdict::Continue => (0, 0, SECCOMP_USER_NOTIF_FLAG_CONTINUE), - Verdict::Return(rc) => (0, rc.min(0), 0), +fn respond(listener: &OwnedFd, id: u64, verdict: Verdict) { + let (error, flags) = match verdict { + Verdict::Continue => (0, SECCOMP_USER_NOTIF_FLAG_CONTINUE), + Verdict::Return(rc) => (rc.min(0), 0), + Verdict::Answered => return, }; - let mut resp = NotifResp { id: req.id, val, error, flags }; + let mut resp = NotifResp { id, val: 0, error, flags }; unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_SEND as libc::Ioctl, &mut resp) }; } +/// Whether the intercepted call is still waiting for an answer. Also proves +/// that what was read through the notification's pid came from the caller. +fn still_pending(listener: &OwnedFd, id: u64) -> bool { + let mut id = id; + unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ID_VALID as libc::Ioctl, &mut id) == 0 } +} + fn last_errno() -> i32 { -std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO) } -fn decide(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) -> Verdict { - // Read the sandbox's memory as the sandbox's uid, so the kernel's ptrace - // access check passes in host mode. Only the filesystem ids change: the - // thread keeps its real uid, so a sandbox cannot signal it. - if let Some(uid) = uid { - unsafe { - libc::syscall(libc::SYS_setfsgid, uid); - libc::syscall(libc::SYS_setfsuid, uid); - } +/// `socket()` for TCP over IP (the filter refused everything else): create it +/// here, keep a handle, and install it as the call's result. +fn on_socket(listener: &OwnedFd, req: &Notif, sockets: &Sockets) -> Verdict { + let [domain, kind, protocol, ..] = req.data.args.map(|arg| arg as libc::c_int); + let fd = unsafe { libc::socket(domain, kind | libc::SOCK_CLOEXEC, protocol) }; + if fd < 0 { + return Verdict::Return(last_errno()); + } + let sock = unsafe { OwnedFd::from_raw_fd(fd) }; + let mut stat: libc::stat = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstat(fd, &mut stat) } != 0 { + return Verdict::Return(last_errno()); } + let inode = stat.st_ino as u64; + let mut addfd = NotifAddfd { + id: req.id, + flags: SECCOMP_ADDFD_FLAG_SEND, + srcfd: fd as u32, + newfd: 0, + newfd_flags: if kind & libc::SOCK_CLOEXEC != 0 { libc::O_CLOEXEC as u32 } else { 0 }, + }; + // Registered before the caller can see it, so its connect() finds it. + sockets.connected.lock().unwrap().remove(&inode); + sockets.open.lock().unwrap().insert(inode, (sock, Instant::now())); + if unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ADDFD as libc::Ioctl, &mut addfd) } < 0 { + let err = last_errno(); + sockets.release(inode, false); + return Verdict::Return(err); + } + Verdict::Answered +} + +/// The inode of the socket at `fd` in process `pid`. +fn caller_socket(pid: u32, fd: u64) -> Result { + match std::fs::read_link(format!("/proc/{pid}/fd/{fd}")) { + Ok(link) => socket_inode_of(&link).ok_or(-libc::ENOTSOCK), + Err(_) => Err(-libc::EBADF), + } +} + +/// `listen()`: a listening socket will not connect, so stop holding it (a +/// held listener would stay bound after the sandbox closed it). +fn on_listen(req: &Notif, sockets: &Sockets) -> Verdict { + if let Ok(inode) = caller_socket(req.pid, req.data.args[0]) { + sockets.release(inode, false); + } + Verdict::Continue +} + +fn on_connect(listener: &OwnedFd, req: &Notif, policy: &Policy, sockets: &Sockets) -> Verdict { let [fd, addr_ptr, addr_len, ..] = req.data.args; let len = addr_len as usize; if !(2..=MAX_SOCKADDR).contains(&len) { @@ -642,10 +954,10 @@ fn decide(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) -> let mut addr = [0u8; MAX_SOCKADDR]; let read = std::fs::File::open(format!("/proc/{}/mem", req.pid)) .and_then(|mem| mem.read_exact_at(&mut addr[..len], addr_ptr)); + let inode = caller_socket(req.pid, fd); // The pid may have been reused since the notification was queued; only - // trust what we read if the notification is still alive. - let mut id = req.id; - if unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ID_VALID as libc::Ioctl, &mut id) } != 0 { + // trust what we read through it if the notification is still alive. + if !still_pending(listener, req.id) { return Verdict::Return(-libc::EINTR); } if let Err(e) = read { @@ -660,43 +972,90 @@ fn decide(listener: &OwnedFd, req: &Notif, policy: &Policy, uid: Option) -> if !policy.allows(dest.ip(), dest.port()) { return Verdict::Return(-libc::EACCES); } - // Keep the sandbox's O_NONBLOCK and O_CLOEXEC on the replacement socket. - let fdinfo = std::fs::read_to_string(format!("/proc/{}/fdinfo/{fd}", req.pid)).unwrap_or_default(); - let fd_flags = fdinfo - .lines() - .find_map(|l| l.strip_prefix("flags:")) - .and_then(|v| i32::from_str_radix(v.trim(), 8).ok()) - .unwrap_or(0); - let family = if dest.is_ipv4() && addr[..2] == (libc::AF_INET as u16).to_ne_bytes() { - libc::AF_INET - } else { - libc::AF_INET6 + let inode = match inode { + Ok(inode) => inode, + Err(err) => return Verdict::Return(err), }; - let sock = unsafe { libc::socket(family, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) }; - if sock < 0 { - return Verdict::Return(last_errno()); + let Some(sock) = sockets.handle(inode) else { + // Already connected, or a socket this supervisor did not create. + let connected = sockets.connected.lock().unwrap().contains(&inode); + return Verdict::Return(if connected { -libc::EISCONN } else { -libc::EACCES }); + }; + // Connect the caller's own socket to the address we checked, from our + // copy of it: changing the sandbox's memory now has no effect. If fd now + // names another socket, we still connect one of the sandbox's sockets to + // an allowed address. + let rc = connect_like_caller(listener, req.id, &sock, &addr[..len]); + if rc == 0 { + sockets.release(inode, true); } - let sock = unsafe { OwnedFd::from_raw_fd(sock) }; - if fd_flags & libc::O_NONBLOCK != 0 { - unsafe { libc::fcntl(sock.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; + Verdict::Return(rc) +} + +/// `connect()` the caller's socket, with the semantics the caller expects. +/// +/// A non-blocking socket is connected as is: the result (EINPROGRESS, +/// EALREADY, EISCONN, ...) is exactly what the caller would have got. A +/// blocking one is connected without blocking, then waited for here, so the +/// wait ends as soon as the caller goes away (killed, timed out, interrupted) +/// and honors the socket's SO_SNDTIMEO like a kernel blocking connect. +fn connect_like_caller(listener: &OwnedFd, id: u64, sock: &OwnedFd, addr: &[u8]) -> i32 { + let fd = sock.as_raw_fd(); + let connect = || { + let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), addr.len() as libc::socklen_t) }; + if rc == 0 { + 0 + } else { + last_errno() + } + }; + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if flags < 0 { + return last_errno(); } - // Connect the address we checked, from our own copy of it. - let rc = unsafe { libc::connect(sock.as_raw_fd(), addr.as_ptr().cast(), len as libc::socklen_t) }; - let result = if rc == 0 { 0 } else { last_errno() }; - if result != 0 && result != -libc::EINPROGRESS { - return Verdict::Return(result); + if flags & libc::O_NONBLOCK != 0 { + return connect(); } - let mut addfd = NotifAddfd { - id: req.id, - flags: SECCOMP_ADDFD_FLAG_SETFD, - srcfd: sock.as_raw_fd() as u32, - newfd: fd as u32, - newfd_flags: (fd_flags & libc::O_CLOEXEC) as u32, + // The flag is on the shared open file description; restore it once done. + unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) }; + let result = (|| { + let rc = connect(); + if rc != -libc::EINPROGRESS { + return rc; + } + let deadline = send_timeout(fd).map(|timeout| Instant::now() + timeout); + loop { + let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; + if unsafe { libc::poll(&mut pfd, 1, 100) } > 0 { + break; + } + if !still_pending(listener, id) { + return -libc::EINTR; + } + if deadline.is_some_and(|deadline| Instant::now() >= deadline) { + return -libc::EINPROGRESS; // what a timed-out blocking connect returns + } + } + let mut err: libc::c_int = 0; + let mut len = std::mem::size_of::() as libc::socklen_t; + unsafe { + libc::getsockopt(fd, libc::SOL_SOCKET, libc::SO_ERROR, (&mut err as *mut libc::c_int).cast(), &mut len) + }; + -err + })(); + unsafe { libc::fcntl(fd, libc::F_SETFL, flags) }; + result +} + +/// The socket's SO_SNDTIMEO, which bounds a blocking connect; None if unset. +fn send_timeout(fd: RawFd) -> Option { + let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 }; + let mut len = std::mem::size_of::() as libc::socklen_t; + let rc = unsafe { + libc::getsockopt(fd, libc::SOL_SOCKET, libc::SO_SNDTIMEO, (&mut tv as *mut libc::timeval).cast(), &mut len) }; - if unsafe { libc::ioctl(listener.as_raw_fd(), SECCOMP_IOCTL_NOTIF_ADDFD as libc::Ioctl, &mut addfd) } < 0 { - return Verdict::Return(last_errno()); - } - Verdict::Return(result) + let timeout = Duration::new(tv.tv_sec as u64, tv.tv_usec as u32 * 1000); + (rc == 0 && !timeout.is_zero()).then_some(timeout) } /// The IP destination of a `sockaddr`, or None for any other family. From 1321e3e77bfecd5a3571e1800b00bf0554f5b48d Mon Sep 17 00:00:00 2001 From: Wauplin Date: Thu, 5 Nov 2026 01:41:27 +0100 Subject: [PATCH 3/5] fix: exec the connect supervisor through /proc/self/exe In dedicated mode the sandbox runs as root and can replace the server binary at its path on disk. The supervisor was exec'd by that path and runs without the sandbox's restrictions, so the next allowlisted command got an unrestricted parent of the sandbox's choosing, with full network access. /proc/self/exe always resolves to the inode the server was started from. Adds the reproduction to scripts/network-regression.sh (fails before, passes after). Co-Authored-By: Claude Opus 5.5 --- scripts/network-regression.sh | 19 +++++++++++++++++++ src/exec.rs | 2 +- src/network.rs | 11 ++++++++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/scripts/network-regression.sh b/scripts/network-regression.sh index 9b63a59..c85b2b1 100644 --- a/scripts/network-regression.sh +++ b/scripts/network-regression.sh @@ -149,6 +149,25 @@ expect "no supervisor is left behind" "0" "$(ps -eo args | grep -c '^/.*sbx-serv grep -q 'huggingface.co' /etc/hosts && pass "hostname pinned in /etc/hosts" || fail "/etc/hosts not pinned" stop +say "dedicated, allowlist: root in the sandbox replaces the server binary" +# The supervisor runs without the sandbox's restrictions: it must not be +# whatever file sits at the server's path when the next command starts. +cp "$BIN" /tmp/sbx-server-copy +BIN_SAVED=$BIN BIN=/tmp/sbx-server-copy +start SBX_NETWORK='{"allow":["127.0.0.1:18080"]}' +cat >/usr/local/bin/sbxswap <<'EOF2' +#!/bin/sh +# Replace the server binary with a "supervisor" that runs the command unsupervised. +printf '#!/bin/sh\nshift 3\nexec "$@"\n' >/tmp/fake && chmod +x /tmp/fake && mv /tmp/fake "$1" +EOF2 +chmod 755 /usr/local/bin/sbxswap +curl -s -m 30 -H "X-Sandbox-Token: $TOKEN" -X POST "$U/v1/exec" \ + -d '{"cmd":["/usr/local/bin/sbxswap","/tmp/sbx-server-copy"]}' >/dev/null +head -c 9 /tmp/sbx-server-copy | grep -q '^#!/bin/sh' && pass "(the sandbox replaced the binary)" || fail "replacement did not happen" +expect "the next command is still supervised" "err EACCES" "$(probe /v1 $TOKEN tcp 127.0.0.1 18081)" +stop +BIN=$BIN_SAVED + say "dedicated, a policy that cannot be applied stops the server" start SBX_NETWORK=everything sleep 1 diff --git a/src/exec.rs b/src/exec.rs index 3a2513b..0cf5c4e 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -212,7 +212,7 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result { - let mut command = Command::new(crate::network::server_exe()?); + let mut command = Command::new(crate::network::SUPERVISOR_EXE); command.arg(crate::network::SUPERVISOR_FLAG).arg(policy.resolved_allowlist()).arg("--"); command.args(&spec.argv); command diff --git a/src/network.rs b/src/network.rs index 1ff5b10..4f47f61 100644 --- a/src/network.rs +++ b/src/network.rs @@ -586,7 +586,16 @@ impl Policy { } } -/// The path of this binary, which is run again as a connect supervisor. +/// What the server runs as a connect supervisor: its own image, through the +/// `/proc/self/exe` magic link rather than its path on disk. In dedicated mode +/// the sandbox runs as root and can replace the file at that path, and the +/// supervisor runs without the sandbox's restrictions: exec'ing the path would +/// hand the next allowlisted command an unrestricted parent of its choosing. +/// The link always resolves to the inode the server was started from. +pub const SUPERVISOR_EXE: &str = "/proc/self/exe"; + +/// The path of this binary on disk (Landlock lets host-mode sandboxes execute it, +/// as their supervisor; see `SUPERVISOR_EXE` for why it is not exec'd by path). pub fn server_exe() -> Result<&'static std::path::Path, String> { static EXE: OnceLock> = OnceLock::new(); EXE.get_or_init(|| std::env::current_exe().map_err(|e| format!("cannot locate the server binary: {e}"))) From a3d56faf8466fe322682759f0d6fe25828f9cb82 Mon Sep 17 00:00:00 2001 From: Wauplin Date: Thu, 5 Nov 2026 10:01:40 +0100 Subject: [PATCH 4/5] fix: limit an allowlist once hostnames are resolved, at creation The 256-entry limit was checked on the entries sent, then again by the supervisor of every command on the resolved rules: a few CDN hostnames passed creation, then made every command exit with code 2. The limit is now 1024 and also applies to the resolved rules when the sandbox is created (1024 rules stay well under the 128 KiB argument limit). Also give supervisor workers a 256 KiB stack, so 64 of them fit under a small memory limit, explain why a connect could not be checked, and document the limits of the supervisor (held sockets, other users, background processes, pending calls). Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +++++--- src/network.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c11318e..9908013 100644 --- a/README.md +++ b/README.md @@ -110,13 +110,15 @@ 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 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. +- The supervisor is in the command's process group, so a timeout or a kill ends it with the command. It runs one thread per pending socket call, which counts against the sandbox's process limit (`max_procs` in host mode), not the server's. It handles at most 64 pending calls at a time (`socket()`, `connect()` and `listen()`, unix sockets included); past that they fail with `EAGAIN`. 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: -- 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. +- With an allowlist, background processes that outlive the command that started them lose their socket access when it exits: `connect()` and `listen()` then fail with `ENOSYS` for every socket, unix sockets included, and so does creating a TCP socket. 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, and notices a close within about 3 seconds. Until then, a socket the sandbox closed keeps its local port: code that picks a free port by binding port 0, closing the socket and binding the port again can fail with `EADDRINUSE`. A connection closed before its non-blocking `connect()` completed can also be shut down late. +- With an allowlist, a process that runs as another user than the command, or that makes itself non-dumpable, cannot connect: the supervisor cannot read its `connect()` arguments without `CAP_SYS_PTRACE`. This affects programs that drop privileges (`apt-get` downloads as `_apt`: pass `-o APT::Sandbox::User=root`), `su`, `gosu`, and agents such as `ssh-agent`. +- An allowlist holds at most 1024 rules, counting every address its hostnames resolve to. - 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. diff --git a/src/network.rs b/src/network.rs index 4f47f61..110f799 100644 --- a/src/network.rs +++ b/src/network.rs @@ -50,8 +50,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; -/// Most allowlist entries accepted in one policy. -const MAX_RULES: usize = 256; +/// Most rules in one policy: allowlist entries as sent, and again once every +/// hostname has expanded to all of its addresses. The resolved rules reach the +/// supervisor as one argument, which must stay under the kernel's 128 KiB +/// limit: a rule takes at most ~50 bytes, so 1024 of them fit with room to spare. +const MAX_RULES: usize = 1024; /// Largest `sockaddr` the supervisor reads from a sandbox (`sockaddr_storage`). const MAX_SOCKADDR: usize = 128; const HOSTS_FILE: &str = "/etc/hosts"; @@ -143,6 +146,15 @@ impl Policy { } } } + // Checked here, when the sandbox is created, rather than by the supervisor + // of every command, so a hostname that resolves to many addresses is a + // clear error now and not a sandbox whose commands all fail. + if rules.len() > MAX_RULES { + return Err(format!( + "network.allow resolves to {} addresses, max {MAX_RULES}: use IP ranges, or fewer hostnames", + rules.len() + )); + } Ok(Policy { rules, hosts, spec: value.clone() }) } @@ -558,6 +570,8 @@ fn recv_fd(sock: RawFd) -> std::io::Result { /// argv[1] that turns the binary into a connect supervisor. pub const SUPERVISOR_FLAG: &str = "--net-supervise"; +/// Stack size of the supervisor's worker threads (one per pending call). +const WORKER_STACK: usize = 256 * 1024; /// Concurrent `connect()` calls one supervisor handles; past it they fail with EAGAIN. const MAX_PENDING_CONNECTS: usize = 64; @@ -858,7 +872,10 @@ fn supervise(listener: Arc, policy: Arc) { continue; } let (worker_listener, policy, sockets) = (Arc::clone(&listener), Arc::clone(&policy), Arc::clone(&sockets)); - let spawned = std::thread::Builder::new().spawn(move || { + // A small stack: the supervisor runs under the sandbox's memory limit + // (RLIMIT_AS), and the default 2 MiB per thread adds up to 128 MiB at + // MAX_PENDING_CONNECTS. A call only needs a few small buffers. + let spawned = std::thread::Builder::new().stack_size(WORKER_STACK).spawn(move || { let verdict = match req.data.nr as libc::c_long { libc::SYS_socket => on_socket(&worker_listener, &req, &sockets), libc::SYS_listen => on_listen(&req, &sockets), @@ -970,7 +987,12 @@ fn on_connect(listener: &OwnedFd, req: &Notif, policy: &Policy, sockets: &Socket return Verdict::Return(-libc::EINTR); } if let Err(e) = read { - eprintln!("sbx-server: network: cannot read connect() address of pid {}: {e}", req.pid); + // Usually a process that changed user or made itself non-dumpable (see the README). + eprintln!( + "sbx-server: network: connect() refused, cannot check its address (pid {}: {e}). A process that \ + runs as another user or is not dumpable cannot connect under a network allowlist.", + req.pid + ); return Verdict::Return(-libc::EACCES); } let Some(dest) = parse_sockaddr(&addr[..len]) else { @@ -1094,6 +1116,8 @@ mod tests { fn fake_resolve(host: &str) -> Result, String> { match host { "vllm.internal" => Ok(vec!["10.0.3.7".parse().unwrap()]), + // A CDN name: many addresses for one entry. + "cdn.example" => Ok((0..=255).map(|i| IpAddr::from([198, 51, 100, i])).collect()), _ => Err(format!("cannot resolve {host:?}")), } } @@ -1107,6 +1131,23 @@ mod tests { p.allows(dest.ip(), dest.port()) } + #[test] + fn resolved_rules_are_limited_at_creation() { + // Each `cdn.example` entry expands to 256 rules: 4 of them fit, 5 do not. + let fits = vec!["cdn.example"; 4]; + let p = policy(&fits); + // What the supervisor of every command parses must parse too. + let resolved: serde_json::Value = serde_json::from_str(&p.resolved_allowlist()).unwrap(); + assert!(Policy::parse_with(&resolved, |h| Err(h.to_string())).is_ok()); + assert!(p.resolved_allowlist().len() < 128 * 1024); + let err = Policy::parse_with(&json!({"allow": vec!["cdn.example"; 5]}), fake_resolve).unwrap_err(); + assert!(err.contains("resolves to 1280 addresses"), "{err}"); + // The longest rules still fit in one argument at the limit. + let v6 = vec!["[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128]:65535"; MAX_RULES]; + let p = Policy::parse_with(&json!({"allow": v6}), fake_resolve).unwrap(); + assert!(p.resolved_allowlist().len() < 128 * 1024); + } + #[test] fn none_allows_nothing() { let p = Policy::parse(&json!("none")).unwrap(); From a50c1189ce0cfc391fbd5438bb7b076624603eaa Mon Sep 17 00:00:00 2001 From: Wauplin Date: Thu, 5 Nov 2026 10:23:49 +0100 Subject: [PATCH 5/5] fix: report supervisor setup errors as spawn errors With an allowlist, a command the supervisor could not start (a missing program, for example) used to look like the command's own result: exit code 126/127 and a message in its stderr. Without a policy, the same mistake is a 400 "failed to spawn". The supervisor now reports its setup on a pipe the server reads until the command is started, so both cases fail the same way. The pipe is passed to the supervisor only (close-on-exec everywhere else), and the command does not inherit it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- scripts/network-regression.sh | 8 +++ src/exec.rs | 20 ++++++- src/network.rs | 101 ++++++++++++++++++++++++++-------- 4 files changed, 106 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 9908013..75bc462 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ 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 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. It runs one thread per pending socket call, which counts against the sandbox's process limit (`max_procs` in host mode), not the server's. It handles at most 64 pending calls at a time (`socket()`, `connect()` and `listen()`, unix sockets included); past that they fail with `EAGAIN`. A blocking `connect()` stops waiting as soon as the caller is gone. +- The supervisor is in the command's process group, so a timeout or a kill ends it with the command. It runs one thread per pending socket call, which counts against the sandbox's process limit (`max_procs` in host mode), not the server's. It handles at most 64 pending calls at a time (`socket()`, `connect()` and `listen()`, unix sockets included); past that they fail with `EAGAIN`. A blocking `connect()` stops waiting as soon as the caller is gone. If the supervisor cannot start the command (a missing program, for example), it tells the server, and the request fails with the same error as without a policy. - 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: diff --git a/scripts/network-regression.sh b/scripts/network-regression.sh index c85b2b1..14e1ca3 100644 --- a/scripts/network-regression.sh +++ b/scripts/network-regression.sh @@ -146,6 +146,11 @@ grep -q '"timed_out":true' /tmp/hang && pass "pending connects do not outlive a 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')" +missing() { # PATH_PREFIX TOKEN -> HTTP status and error of exec'ing a program that does not exist + curl -s -m 30 -H "X-Sandbox-Token: $2" -X POST "$U$1/exec" -d '{"cmd":["/no/such/program"]}' -w ' %{http_code}' +} +expect "a missing program is a spawn error, as without a policy" \ + "*failed to spawn '/no/such/program': No such file or directory*400" "$(missing /v1 $TOKEN)" grep -q 'huggingface.co' /etc/hosts && pass "hostname pinned in /etc/hosts" || fail "/etc/hosts not pinned" stop @@ -192,6 +197,9 @@ 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: a missing program is a spawn error" \ + "*failed to spawn '/no/such/program': No such file or directory*400" \ + "$(missing /v1/sandboxes/$(id "$allow_box") "$(tok "$allow_box")")" 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" \ diff --git a/src/exec.rs b/src/exec.rs index 0cf5c4e..7773670 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::io::{BufReader, Read, Write}; use std::net::TcpStream; +use std::os::fd::AsRawFd; use std::os::unix::process::CommandExt; use std::os::unix::process::ExitStatusExt; use std::process::{Child, Command, Stdio}; @@ -210,10 +211,15 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result { let mut command = Command::new(crate::network::SUPERVISOR_EXE); - command.arg(crate::network::SUPERVISOR_FLAG).arg(policy.resolved_allowlist()).arg("--"); + let status_fd = status_pipe.as_ref().map(|(_, write)| write.as_raw_fd()).unwrap_or(-1); + command.arg(crate::network::SUPERVISOR_FLAG).arg(policy.resolved_allowlist()); + command.arg(status_fd.to_string()).arg("--"); command.args(&spec.argv); command } @@ -247,6 +253,9 @@ fn spawn(spec: &ExecSpec, tx: SyncSender) -> Result) -> Result EOF). if let Some(input) = &spec.stdin { diff --git a/src/network.rs b/src/network.rs index 110f799..ef3ac36 100644 --- a/src/network.rs +++ b/src/network.rs @@ -40,7 +40,7 @@ //! Implemented with raw syscalls to stay a zero-dependency static binary. use std::collections::{BTreeSet, HashMap}; -use std::io::Write; +use std::io::{Read, Write}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::os::unix::fs::FileExt; @@ -567,6 +567,54 @@ fn recv_fd(sock: RawFd) -> std::io::Result { // - It is not dumpable, so the sandbox (same uid) cannot ptrace it or write // to its memory. It can kill it; then connects fail (ENOSYS): closed. +/// Exit code of a supervisor whose setup failed (the server reports the error itself). +const SETUP_FAILED: i32 = 126; +/// How long the server waits for a supervisor to start its command. +const SETUP_TIMEOUT_MS: i32 = 30_000; + +/// A pipe a supervisor reports its setup on: (read end, write end), both +/// close-on-exec. The server clears the flag on the write end in the +/// supervisor's child only (`inherit_fd`), so no other command inherits it. +pub fn status_pipe() -> Result<(OwnedFd, OwnedFd), String> { + let mut fds = [0; 2]; + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } != 0 { + return Err(format!("pipe: {}", std::io::Error::last_os_error())); + } + Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) +} + +/// Pre-exec hook that lets the exec'd program inherit `fd`. +pub fn inherit_fd(fd: RawFd) -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static { + move || { + if unsafe { libc::fcntl(fd, libc::F_SETFD, 0) } != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } +} + +/// Wait until a supervisor has started its command (EOF on the status pipe), +/// or return the setup error it reported. +pub fn await_supervisor(status: OwnedFd) -> Result<(), String> { + let mut pfd = libc::pollfd { fd: status.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + let deadline = Instant::now() + Duration::from_millis(SETUP_TIMEOUT_MS as u64); + loop { + let left = deadline.saturating_duration_since(Instant::now()).as_millis() as i32; + match unsafe { libc::poll(&mut pfd, 1, left) } { + 0 => return Err("network supervisor did not start the command in time".into()), + n if n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted => continue, + _ => break, + } + } + let mut message = String::new(); + let _ = std::io::Read::take(std::fs::File::from(status), 4096).read_to_string(&mut message); + if message.is_empty() { + Ok(()) + } else { + Err(message) + } +} + /// argv[1] that turns the binary into a connect supervisor. pub const SUPERVISOR_FLAG: &str = "--net-supervise"; @@ -627,50 +675,57 @@ pub fn supervisor_main() -> Option { } fn run_supervisor(args: &[String]) -> i32 { - let (Some(rules), Some("--"), Some(program)) = (args.first(), args.get(1).map(String::as_str), args.get(2)) else { - eprintln!("usage: sbx-server {SUPERVISOR_FLAG} RULES -- PROGRAM [ARGS...]"); + let (Some(rules), Some(status_fd), Some("--"), Some(program)) = ( + args.first(), + args.get(1).and_then(|fd| fd.parse::().ok()), + args.get(2).map(String::as_str), + args.get(3), + ) else { + eprintln!("usage: sbx-server {SUPERVISOR_FLAG} RULES STATUS_FD -- PROGRAM [ARGS...]"); return 2; }; unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0); libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); + // The command must not inherit it: the server reads it until it closes. + libc::fcntl(status_fd, libc::F_SETFD, libc::FD_CLOEXEC); } + let status = unsafe { OwnedFd::from_raw_fd(status_fd) }; + // A setup error goes to the server, which reports it as the spawn error it + // would have been without a supervisor, instead of as the command's output. + let fail = |message: String| { + // One write: the pipe holds far more than any message. + unsafe { libc::write(status.as_raw_fd(), message.as_ptr().cast(), message.len()) }; + SETUP_FAILED + }; let policy = serde_json::from_str(rules) .map_err(|e| e.to_string()) .and_then(|value| Policy::parse_with(&value, |host| Err(format!("unresolved hostname {host:?}")))); let policy = match policy { Ok(policy) if policy.needs_supervisor() => Arc::new(policy), - Ok(_) => { - eprintln!("sbx-server: {SUPERVISOR_FLAG} needs a non-empty allowlist"); - return 2; - } - Err(e) => { - eprintln!("sbx-server: {SUPERVISOR_FLAG}: {e}"); - return 2; - } + Ok(_) => return fail("network supervisor: needs a non-empty allowlist".into()), + Err(e) => return fail(format!("network supervisor: {e}")), }; let prepared = match Prepared::new(&policy) { Ok(prepared) => prepared, - Err(e) => { - eprintln!("sbx-server: {e}"); - return 126; - } + Err(e) => return fail(format!("network supervisor: {e}")), }; let mut command = std::process::Command::new(program); - command.args(&args[3..]); + command.args(&args[4..]); unsafe { command.pre_exec(prepared.hook()) }; - let child = match command.spawn() { + let mut child = match command.spawn() { Ok(child) => child, - Err(e) => { - eprintln!("sbx-server: failed to spawn '{program}': {e}"); - return if e.kind() == std::io::ErrorKind::NotFound { 127 } else { 126 }; - } + // Worded like the server's own spawn error. + Err(e) => return fail(format!("failed to spawn '{program}': {e}")), }; let main_pid = child.id() as libc::pid_t; if let Err(e) = prepared.start(policy) { - eprintln!("sbx-server: {e}"); - unsafe { libc::kill(main_pid, libc::SIGKILL) }; + let _ = child.kill(); + let _ = child.wait(); + return fail(format!("network supervisor: {e}")); } + // EOF on the status pipe: the command runs, supervised. + drop(status); // Reap whatever ends up under us (we are a subreaper) until the command // exits, then exit the same way so the server reports its status. loop {