Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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)
Expand All @@ -87,8 +88,42 @@ 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 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. 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:

- 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.
- 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
Expand Down
210 changes: 210 additions & 0 deletions scripts/network-regression.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
#!/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 == "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":
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=$!
# 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...
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)"
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')"
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

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
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)"
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" \
-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; }
Loading
Loading