Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_sandbox_launcher.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 8 minutes ago History
object_sandbox_launcher.py · 28.0 KB · 681 lines
1"""The one privileged piece of user-object isolation: it starts sandbox
2workers as a dedicated unprivileged OS user, and does nothing else.
3
4Why this exists
5---------------
6Sandbox workers (object_sandbox.py) used to run as the server's own uid. A
7simulated customer then showed what Landlock cannot stop: it has no right
8for metadata changes, so ``os.chmod("/data/objects/users/1/vault.py", 0)``
9from user 2's object succeeded (the server owns every file, and so did the
10worker), user 1's object broke, and ``os.stat`` leaked other customers'
11file sizes, owners and mtimes. Same uid also means a worker may signal the
12server on kernels without Landlock signal scoping (ABI < 6). The answer is
13the old one (OpenSSH's privilege separation): run the untrusted part as a
14uid that owns nothing. The server stays unprivileged; this small launcher
15runs as root, because only root can switch to another uid.
16
17What it does, all of it
18-----------------------
191. Listens on a UNIX socket in a root-owned directory (``root:<server
20 group>``, 0750; the socket 0660), so only root and the server's group can
21 even reach it, and checks every connection's ``SO_PEERCRED`` uid against
22 the server's uid. Anyone else is logged and dropped without a reply.
232. Reads ONE request (length-prefixed JSON, at most 4 KiB, a 2 second
24 deadline), with exactly two pipe fds attached (``SCM_RIGHTS``): the read
25 end the worker will use as stdin and the write end it will use as stdout.
26 Only known fields are accepted (``v``, ``op``, ``env``, ``channel``); env
27 keys come from the same allow-list the server's scrubbed environment uses.
28 ``"channel": "socket"`` instead attaches exactly ONE fd, a connected
29 ``AF_UNIX`` stream socket, which becomes the worker's fd 0 and 1: a
30 per-user warm parent (object_sandbox's fork server) needs a channel that
31 can carry the per-call pipe fds it hands its children. Anything else is
32 refused and logged.
333. Starts the fixed worker entry point -- ``<python> -I -B <object_sandbox.py>
34 --worker``, both paths given on THIS process's command line by root's
35 configuration, never by the request -- in a new session, with fd 0/1 the
36 received pipes and fd 2 ``/dev/null``. Before exec the child: enters a
37 fresh network namespace when the launcher has ``CAP_SYS_ADMIN`` (a bare
38 VM; Docker's default capabilities lack it, and the layer is then skipped
39 and reported), sets ``PR_SET_NO_NEW_PRIVS``, drops to the sandbox user
40 (``setgroups([])``, ``setresgid``, ``setresuid``), and proves it cannot get
41 back (``setuid(0)`` must fail, all three uids/gids must match, no groups,
42 no capabilities), then asks to be killed if the launcher dies. Any
43 failure there aborts the spawn.
444. Replies ``{"ok": true, "pid": N, "netns": bool}`` and keeps the
45 connection open. The connection IS the worker's lifetime: when the server
46 closes it (or sends anything, or dies), the launcher SIGKILLs the
47 worker's process group and every other process still in its session, and
48 reaps it. The server cannot signal a process of another uid, so killing
49 is the launcher's job. The launcher is a child subreaper: a sandbox
50 process orphaned by its parent's death comes back to it and is reaped,
51 instead of piling up as a zombie under the container's PID 1.
525. If the worker ends by itself while the connection is open, the launcher
53 sends one more message on it, ``{"exited": true, "status": N}`` (N as
54 ``subprocess`` reports it: the exit status, or minus the signal number),
55 so the server can log why a worker died. Nothing else changes: the
56 connection stays open until the server closes it. A server that does
57 not read it loses nothing, and a launcher that does not send it (an
58 older one, or a kernel without pidfds) leaves the status unknown.
59
60The worker then boots exactly as before (rlimits, Landlock, the pipe
61protocol); the launcher never sees user code or the protocol.
62
63Why these choices
64-----------------
65- **The server passes its own pipe fds** rather than the launcher creating
66 pipes and sending fds back: one message each way, and the launcher never
67 holds a data channel to the worker.
68- **One connection per worker** instead of a pid-based "kill" request: a
69 pid can be reused, a connection cannot, and a server that dies takes all
70 of its workers with it.
71- **Single-threaded selector loop**: no threads, so forking is safe; a spawn
72 is a fork + exec (about a millisecond).
73- **The session, not just the process group, is what gets killed.** A
74 worker is a session leader. A fork server's children put themselves in a
75 group of their own before any user code runs (a group leader cannot
76 ``setsid()``), so every process a worker ever created stays in its
77 session; killing the group alone would miss them. Each is signalled
78 through a pidfd after re-checking its session, so a reused pid is never
79 hit.
80- **Nothing root executes is writable by the server**: deployments run this
81 file and the interpreter from root-owned copies (``python -I -S``), since a
82 launcher the server could edit would be root code the server controls.
83 The worker script and its interpreter may be server-owned: they run as
84 the sandbox user, which has less than the server already has.
85
86Linux only, stdlib only, run as root. ``--status`` style information is
87answered on the socket (``{"v": 1, "op": "status"}``) so the server can
88report uid separation and network isolation honestly.
89"""
90from __future__ import annotations
91
92import argparse
93import array
94import json
95import os
96import pwd
97import re
98import selectors
99import signal
100import socket
101import stat
102import struct
103import subprocess
104import sys
105import time
106
107PROTOCOL_VERSION = 1
108DEFAULT_SOCKET = "/run/dbbasic-sandbox/launcher.sock"
109MAX_REQUEST_BYTES = 4096
110REQUEST_TIMEOUT_SECONDS = 2.0
111MAX_WORKERS = 256
112_LENGTH = struct.Struct(">I")
113_CLONE_NEWNET = 0x40000000
114_PR_SET_NO_NEW_PRIVS = 38
115_PR_SET_PDEATHSIG = 1
116_PR_SET_CHILD_SUBREAPER = 36
117
118# Must match object_sandbox._ENV_ALLOW / _ENV_ALLOW_PREFIX (a test checks).
119ENV_ALLOW = ("PATH", "LANG", "TZ", "PYTHONHASHSEED", "PYTHONDONTWRITEBYTECODE")
120_LC_KEY = re.compile(r"LC_[A-Z]{1,20}")
121MAX_ENV_ITEMS = 32
122MAX_ENV_VALUE = 1024
123
124
125class Refused(Exception):
126 """A request (or peer) this launcher will not serve."""
127
128
129def log(message: str) -> None:
130 print(f"[dbbasic-sandbox-launcher] {message}", file=sys.stderr, flush=True)
131
132
133# ---------------------------------------------------------------------------
134# Request validation (pure; unit-tested everywhere)
135# ---------------------------------------------------------------------------
136
137
138def check_peer(peer_uid: int, server_uid: int) -> None:
139 if peer_uid != server_uid:
140 raise Refused(f"connection from uid {peer_uid}, not the server's uid {server_uid}")
141
142
143def _validate_env(env) -> dict[str, str]:
144 if not isinstance(env, dict) or len(env) > MAX_ENV_ITEMS:
145 raise Refused("env must be an object of at most 32 items")
146 clean = {}
147 for key, value in env.items():
148 if not isinstance(key, str) or not (key in ENV_ALLOW or _LC_KEY.fullmatch(key)):
149 raise Refused(f"env key {str(key)[:40]!r} is not allowed")
150 if not isinstance(value, str) or len(value) > MAX_ENV_VALUE or "\0" in value:
151 raise Refused(f"env value for {key} is not a short string")
152 clean[key] = value
153 clean.setdefault("PATH", "/usr/bin:/bin")
154 return clean
155
156
157def _is_pipe_end(fd: int, writable: bool) -> bool:
158 import fcntl
159
160 try:
161 if not stat.S_ISFIFO(os.fstat(fd).st_mode):
162 return False
163 mode = fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_ACCMODE
164 except OSError:
165 return False
166 return mode == (os.O_WRONLY if writable else os.O_RDONLY)
167
168
169def _is_stream_socket(fd: int) -> bool:
170 """A connected AF_UNIX stream socket (not a listener, not datagrams)."""
171 try:
172 if not stat.S_ISSOCK(os.fstat(fd).st_mode):
173 return False
174 probe = socket.socket(fileno=os.dup(fd))
175 except OSError:
176 return False
177 try:
178 if probe.family != socket.AF_UNIX or probe.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) != socket.SOCK_STREAM:
179 return False
180 probe.getpeername() # ENOTCONN for a listener or an unconnected socket
181 return True
182 except OSError:
183 return False
184 finally:
185 probe.close()
186
187
188def parse_request(body: bytes, fds: list[int]) -> dict:
189 """Validate one request. ``spawn`` needs exactly [read end, write end] of
190 two pipes, or with ``"channel": "socket"`` exactly one connected AF_UNIX
191 stream socket; ``status`` takes no fds. Anything else is ``Refused``."""
192 if len(body) > MAX_REQUEST_BYTES:
193 raise Refused(f"request of {len(body)} bytes exceeds {MAX_REQUEST_BYTES}")
194 try:
195 request = json.loads(body.decode("utf-8"))
196 except (ValueError, UnicodeDecodeError, RecursionError):
197 raise Refused("request is not JSON") from None
198 if not isinstance(request, dict) or request.get("v") != PROTOCOL_VERSION:
199 raise Refused("request is not a version-1 object")
200 op = request.get("op")
201 if op == "status":
202 if set(request) != {"v", "op"} or fds:
203 raise Refused("status takes no fields and no fds")
204 return {"op": "status"}
205 if op == "spawn":
206 known = {"v", "op", "env", "channel"}
207 if not set(request) <= known:
208 raise Refused(f"unknown spawn fields {sorted(set(request) - known)}")
209 channel = request.get("channel", "pipes")
210 if channel == "socket":
211 if len(fds) != 1 or not _is_stream_socket(fds[0]):
212 raise Refused("a socket spawn needs exactly one fd: a connected AF_UNIX stream socket")
213 elif channel == "pipes":
214 if len(fds) != 2 or not _is_pipe_end(fds[0], writable=False) or not _is_pipe_end(fds[1], writable=True):
215 raise Refused("spawn needs exactly two fds: a pipe's read end, then a pipe's write end")
216 else:
217 raise Refused(f"unknown channel {str(channel)[:40]!r}")
218 return {"op": "spawn", "env": _validate_env(request.get("env", {})), "channel": channel}
219 raise Refused(f"unknown op {str(op)[:40]!r}")
220
221
222def worker_argv(python: str, script: str) -> list[str]:
223 """The only program this launcher ever runs."""
224 return [python, "-I", "-B", script, "--worker"]
225
226
227# ---------------------------------------------------------------------------
228# Wire helpers
229# ---------------------------------------------------------------------------
230
231
232def _close_all(fds) -> None:
233 for fd in fds:
234 try:
235 os.close(fd)
236 except OSError:
237 pass
238
239
240def recv_request(conn: socket.socket, timeout: float = REQUEST_TIMEOUT_SECONDS) -> tuple[bytes, list[int]]:
241 """Read one length-prefixed request and the fds attached to it. More than
242 two fds, a truncated control message, an oversize length or a deadline
243 miss closes every received fd and refuses."""
244 deadline = time.monotonic() + timeout
245 data = bytearray()
246 fds: list[int] = []
247 flags = getattr(socket, "MSG_CMSG_CLOEXEC", 0)
248 try:
249 while True:
250 remaining = deadline - time.monotonic()
251 if remaining <= 0:
252 raise Refused("request deadline passed")
253 conn.settimeout(remaining)
254 need = 4 if len(data) < 4 else 4 + _LENGTH.unpack(bytes(data[:4]))[0]
255 try:
256 msg, ancdata, msg_flags, _addr = conn.recvmsg(need - len(data), socket.CMSG_SPACE(3 * 4), flags)
257 except socket.timeout:
258 raise Refused("request deadline passed") from None
259 for level, kind, cdata in ancdata:
260 if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
261 got = array.array("i")
262 got.frombytes(cdata[: len(cdata) - (len(cdata) % got.itemsize)])
263 fds.extend(got)
264 if msg_flags & getattr(socket, "MSG_CTRUNC", 0) or len(fds) > 2:
265 raise Refused("too many fds attached")
266 if not msg:
267 raise Refused("connection closed mid-request")
268 data.extend(msg)
269 if len(data) >= 4:
270 length = _LENGTH.unpack(bytes(data[:4]))[0]
271 if length > MAX_REQUEST_BYTES:
272 raise Refused(f"request of {length} bytes exceeds {MAX_REQUEST_BYTES}")
273 if len(data) == 4 + length:
274 return bytes(data[4:]), fds
275 except BaseException:
276 _close_all(fds)
277 raise
278
279
280def send_reply(conn: socket.socket, reply: dict) -> None:
281 body = json.dumps(reply, separators=(",", ":")).encode("utf-8")
282 conn.settimeout(REQUEST_TIMEOUT_SECONDS)
283 conn.sendall(_LENGTH.pack(len(body)) + body)
284
285
286def send_exit_notice(conn: socket.socket, returncode) -> bool:
287 """Tell the server how its worker ended. Never blocks and never raises:
288 the server may not be reading, or may be gone."""
289 if not isinstance(returncode, int) or isinstance(returncode, bool):
290 return False
291 body = json.dumps({"exited": True, "status": returncode}, separators=(",", ":")).encode("utf-8")
292 try:
293 conn.send(_LENGTH.pack(len(body)) + body, getattr(socket, "MSG_DONTWAIT", 0))
294 except (OSError, ValueError):
295 return False
296 return True
297
298
299def peer_uid(conn: socket.socket) -> int:
300 creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
301 _pid, uid, _gid = struct.unpack("3i", creds)
302 return uid
303
304
305# ---------------------------------------------------------------------------
306# Spawning
307# ---------------------------------------------------------------------------
308
309
310def _libc():
311 import ctypes
312
313 return ctypes.CDLL(None, use_errno=True)
314
315
316def _capabilities_zero() -> bool:
317 try:
318 with open("/proc/self/status") as handle:
319 for line in handle:
320 if line.startswith(("CapPrm:", "CapEff:", "CapAmb:")) and int(line.split()[1], 16):
321 return False
322 except OSError:
323 return False
324 return True
325
326
327def probe_network_namespace(libc=None) -> bool:
328 """Can a child of this process enter a fresh network namespace?"""
329 libc = libc or _libc()
330 pid = os.fork()
331 if pid == 0:
332 os._exit(0 if libc.unshare(_CLONE_NEWNET) == 0 else 1)
333 _pid, status = os.waitpid(pid, 0)
334 return os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0
335
336
337def probe_inet_sockets() -> bool:
338 """Can this process (and so its workers) create an IPv4 or IPv6 UDP
339 socket? False under systemd's RestrictAddressFamilies=AF_UNIX."""
340 for family in (socket.AF_INET, socket.AF_INET6):
341 try:
342 socket.socket(family, socket.SOCK_DGRAM).close()
343 except OSError:
344 continue
345 return True
346 return False
347
348
349def probe_interfaces() -> list[str]:
350 try:
351 return sorted(name for _index, name in socket.if_nameindex())
352 except OSError:
353 return []
354
355
356class Launcher:
357 def __init__(self, *, server_uid: int, sandbox_uid: int, sandbox_gid: int,
358 python: str, script: str, netns: bool, peer=peer_uid):
359 self.server_uid = server_uid
360 self.sandbox_uid = sandbox_uid
361 self.sandbox_gid = sandbox_gid
362 self.argv = worker_argv(python, script)
363 self.netns = netns
364 self.inet = probe_inet_sockets()
365 self.interfaces = probe_interfaces()
366 self._peer = peer
367 self._libc = _libc() if sys.platform.startswith("linux") else None
368 self.workers: dict[socket.socket, subprocess.Popen] = {}
369 self.exit_fds: dict[socket.socket, int] = {} # connection -> pidfd watched for the worker's exit
370
371 def status(self) -> dict:
372 return {"ok": True, "v": PROTOCOL_VERSION, "sandbox_uid": self.sandbox_uid,
373 "sandbox_gid": self.sandbox_gid, "netns": self.netns,
374 "inet_sockets": self.inet, "interfaces": self.interfaces,
375 "channels": ["pipes", "socket"]}
376
377 def _drop_privileges(self) -> None:
378 """preexec_fn: runs in the forked child, before exec. Raising here
379 aborts the spawn (Popen raises SubprocessError in the launcher)."""
380 uid, gid = self.sandbox_uid, self.sandbox_gid
381 if self.netns and self._libc.unshare(_CLONE_NEWNET) != 0:
382 raise OSError("unshare(CLONE_NEWNET) failed")
383 if self._libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
384 raise OSError("PR_SET_NO_NEW_PRIVS failed")
385 os.setgroups([])
386 os.setresgid(gid, gid, gid)
387 os.setresuid(uid, uid, uid)
388 if os.getresuid() != (uid, uid, uid) or os.getresgid() != (gid, gid, gid) or os.getgroups():
389 raise OSError("privileges did not drop")
390 for regain in (lambda: os.setuid(0), lambda: os.setgid(0), lambda: os.seteuid(0)):
391 try:
392 regain()
393 except PermissionError:
394 continue
395 raise OSError("dropped privileges could be regained")
396 if not _capabilities_zero():
397 raise OSError("capabilities survived the uid change")
398 # After the uid change, which clears it: a worker dies with its launcher.
399 if self._libc.prctl(_PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0:
400 raise OSError("PR_SET_PDEATHSIG failed")
401
402 def spawn(self, fds: list[int], env: dict[str, str]) -> subprocess.Popen:
403 stdin, stdout = (fds[0], fds[0]) if len(fds) == 1 else (fds[0], fds[1])
404 return subprocess.Popen(
405 self.argv, stdin=stdin, stdout=stdout, stderr=subprocess.DEVNULL,
406 env=env, cwd="/", close_fds=True, start_new_session=True,
407 preexec_fn=self._drop_privileges,
408 )
409
410 def accept(self, conn: socket.socket) -> subprocess.Popen | None:
411 """Serve one connection's request. Returns the worker to watch, or
412 None when the connection is finished (status, refusal)."""
413 try:
414 check_peer(self._peer(conn), self.server_uid)
415 except (Refused, OSError) as exc:
416 log(f"refused: {exc}")
417 conn.close()
418 return None
419 fds: list[int] = []
420 try:
421 body, fds = recv_request(conn)
422 request = parse_request(body, fds)
423 if request["op"] == "status":
424 send_reply(conn, self.status())
425 conn.close()
426 return None
427 if len(self.workers) >= MAX_WORKERS:
428 raise Refused(f"{MAX_WORKERS} workers already running")
429 proc = self.spawn(fds, request["env"])
430 except (Refused, OSError, subprocess.SubprocessError, ValueError) as exc:
431 log(f"refused: {type(exc).__name__}: {exc}")
432 try:
433 send_reply(conn, {"ok": False, "error": str(exc)[:500]})
434 except OSError:
435 pass
436 conn.close()
437 return None
438 finally:
439 _close_all(fds)
440 try:
441 send_reply(conn, {"ok": True, "pid": proc.pid, "netns": self.netns})
442 except OSError:
443 self.finish(conn, proc)
444 return None
445 self.workers[conn] = proc
446 return proc
447
448 def watch_exit(self, selector, conn: socket.socket, proc: subprocess.Popen) -> None:
449 """Have the loop wake when this worker ends by itself (a pidfd), so
450 its status reaches the server at once. Without pidfds nothing is
451 watched and the server is told nothing, as before."""
452 if not hasattr(os, "pidfd_open"):
453 return
454 try:
455 pidfd = os.pidfd_open(proc.pid) # not reaped yet, so the pid is still ours
456 except OSError:
457 return
458 try:
459 selector.register(pidfd, selectors.EVENT_READ, ("exit", conn, proc))
460 except (OSError, ValueError, KeyError):
461 os.close(pidfd)
462 return
463 self.exit_fds[conn] = pidfd
464
465 def unwatch_exit(self, selector, conn: socket.socket) -> None:
466 pidfd = self.exit_fds.pop(conn, None)
467 if pidfd is None:
468 return
469 try:
470 selector.unregister(pidfd)
471 except (OSError, ValueError, KeyError):
472 pass
473 try:
474 os.close(pidfd)
475 except OSError:
476 pass
477
478 def report_exit(self, selector, conn: socket.socket, proc: subprocess.Popen) -> None:
479 """The worker ended while the server still holds its connection:
480 say how. The connection and the session are finished as always,
481 when the server closes its end."""
482 self.unwatch_exit(selector, conn)
483 send_exit_notice(conn, proc.poll())
484
485 def finish(self, conn: socket.socket, proc: subprocess.Popen) -> None:
486 """The server is done with this worker (or gone): kill and reap it
487 and everything left in its session."""
488 self.workers.pop(conn, None)
489 if proc.poll() is None: # not reaped, so the pid is still ours
490 try:
491 os.killpg(proc.pid, signal.SIGKILL)
492 except ProcessLookupError:
493 pass
494 proc.wait()
495 conn.close()
496 # Whatever the worker left in its session has been reparented to
497 # this subreaper by now: kill it, wait for it to die, reap it.
498 kill_session(proc.pid)
499 self.reap_orphans()
500
501 def reap_orphans(self) -> None:
502 """Reap sandbox processes that came back to this subreaper when their
503 own parent died. A worker's pid is left to its Popen (reaping it
504 here would let a reused pid be mistaken for it)."""
505 for proc in list(self.workers.values()):
506 proc.poll()
507 tracked = {proc.pid for proc in self.workers.values()}
508 while True:
509 try:
510 info = os.waitid(os.P_ALL, 0, os.WEXITED | os.WNOHANG | os.WNOWAIT)
511 except ChildProcessError:
512 return
513 if info is None or info.si_pid in tracked:
514 return
515 try:
516 os.waitpid(info.si_pid, 0)
517 except ChildProcessError:
518 return
519
520 def serve(self, listener: socket.socket) -> None:
521 selector = selectors.DefaultSelector()
522 selector.register(listener, selectors.EVENT_READ, None)
523 while True:
524 for key, _events in selector.select(timeout=30):
525 if key.data is None:
526 try:
527 conn, _addr = listener.accept()
528 except OSError:
529 continue
530 conn.setblocking(True)
531 proc = self.accept(conn)
532 if proc is not None:
533 selector.register(conn, selectors.EVENT_READ, proc)
534 self.watch_exit(selector, conn, proc)
535 elif isinstance(key.data, tuple):
536 if key.data[1] in self.exit_fds: # not finished earlier in this batch
537 self.report_exit(selector, key.data[1], key.data[2])
538 else:
539 selector.unregister(key.fileobj)
540 self.unwatch_exit(selector, key.fileobj)
541 self.finish(key.fileobj, key.data)
542 self.reap_orphans() # and workers that exited by themselves
543
544 def shutdown(self) -> None:
545 for conn, proc in list(self.workers.items()):
546 self.finish(conn, proc)
547
548
549# ---------------------------------------------------------------------------
550# Setup
551# ---------------------------------------------------------------------------
552
553
554def _session_of(pid: int) -> int | None:
555 try:
556 with open(f"/proc/{pid}/stat", "rb") as handle:
557 data = handle.read()
558 except OSError:
559 return None
560 # pid (comm) state ppid pgrp session ...; comm may contain anything but ")"
561 fields = data[data.rfind(b")") + 2:].split()
562 try:
563 return int(fields[3])
564 except (IndexError, ValueError):
565 return None
566
567
568def kill_session(sid: int, wait: float = 1.0) -> int:
569 """SIGKILL every process whose session is ``sid`` (a worker that was
570 started with start_new_session). Each is opened as a pidfd and its
571 session re-checked before the signal, so a pid that was reused in the
572 meantime is never signalled; then wait up to ``wait`` seconds for them
573 to exit (so the caller can reap them). Returns how many were signalled."""
574 import select
575
576 if sid <= 1 or not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):
577 return 0
578 try:
579 names = os.listdir("/proc")
580 except OSError:
581 return 0
582 signalled: list[int] = []
583 for name in names:
584 if not name.isdigit() or _session_of(int(name)) != sid:
585 continue
586 try:
587 pidfd = os.pidfd_open(int(name))
588 except OSError:
589 continue
590 try:
591 if _session_of(int(name)) == sid:
592 signal.pidfd_send_signal(pidfd, signal.SIGKILL)
593 signalled.append(pidfd)
594 continue
595 except OSError:
596 pass
597 os.close(pidfd)
598 deadline = time.monotonic() + wait
599 pending = list(signalled)
600 while pending and time.monotonic() < deadline:
601 exited, _w, _x = select.select(pending, [], [], max(0.0, deadline - time.monotonic()))
602 pending = [fd for fd in pending if fd not in exited]
603 for pidfd in signalled:
604 os.close(pidfd)
605 return len(signalled)
606
607
608def _listen(path: str, server_gid: int) -> socket.socket:
609 directory = os.path.dirname(path)
610 os.makedirs(directory, mode=0o750, exist_ok=True)
611 info = os.lstat(directory)
612 if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0:
613 raise SystemExit(f"{directory} must be a directory owned by root")
614 os.chown(directory, 0, server_gid)
615 os.chmod(directory, 0o750)
616 try:
617 os.unlink(path)
618 except FileNotFoundError:
619 pass
620 listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
621 old = os.umask(0o117)
622 try:
623 listener.bind(path)
624 finally:
625 os.umask(old)
626 os.chown(path, 0, server_gid)
627 os.chmod(path, 0o660)
628 listener.listen(64)
629 listener.setblocking(False)
630 return listener
631
632
633def main(argv: list[str] | None = None) -> int:
634 parser = argparse.ArgumentParser(description="Start object sandbox workers as an unprivileged user.")
635 parser.add_argument("--socket", default=DEFAULT_SOCKET)
636 parser.add_argument("--server-user", required=True, help="the only user allowed to connect")
637 parser.add_argument("--sandbox-user", required=True, help="the user workers run as")
638 parser.add_argument("--python", required=True, help="interpreter for the worker")
639 parser.add_argument("--worker", required=True, help="path to object_sandbox.py")
640 parser.add_argument("--no-netns", action="store_true", help="never put workers in a network namespace")
641 args = parser.parse_args(argv)
642
643 if not sys.platform.startswith("linux") or os.geteuid() != 0:
644 log("must run as root on Linux")
645 return 2
646 server = pwd.getpwnam(args.server_user)
647 sandbox = pwd.getpwnam(args.sandbox_user)
648 if 0 in (sandbox.pw_uid, sandbox.pw_gid) or sandbox.pw_uid == server.pw_uid or sandbox.pw_gid == server.pw_gid:
649 log(f"refusing: {args.sandbox_user} must have its own non-root uid and gid, distinct from {args.server_user}")
650 return 2
651 for path in (args.python, args.worker):
652 if not os.path.isabs(path) or not os.path.isfile(path):
653 log(f"refusing: {path} is not an absolute path to a file")
654 return 2
655
656 netns = False if args.no_netns else probe_network_namespace()
657 # Orphaned sandbox processes come back here to be reaped (reap_orphans).
658 _libc().prctl(_PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)
659 launcher = Launcher(server_uid=server.pw_uid, sandbox_uid=sandbox.pw_uid, sandbox_gid=sandbox.pw_gid,
660 python=args.python, script=args.worker, netns=netns)
661 listener = _listen(args.socket, server.pw_gid)
662
663 def stop(_signum, _frame):
664 launcher.shutdown()
665 try:
666 os.unlink(args.socket)
667 except OSError:
668 pass
669 raise SystemExit(0)
670
671 signal.signal(signal.SIGTERM, stop)
672 signal.signal(signal.SIGINT, stop)
673 log(f"listening on {args.socket}: workers run as {args.sandbox_user} (uid {sandbox.pw_uid}); "
674 f"network namespace per worker: {'yes' if netns else 'no (needs CAP_SYS_ADMIN)'}; "
675 f"IP sockets: {'possible' if launcher.inet else 'blocked'}; only uid {server.pw_uid} may connect")
676 launcher.serve(listener)
677 return 0
678
679
680if __name__ == "__main__":
681 raise SystemExit(main())