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/tests/test_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, 19 minutes ago History
test_object_sandbox_launcher.py · 30.7 KB · 779 lines
1"""The root sandbox launcher (object_sandbox_launcher) and what uid
2separation closes.
3
4Why it matters: a simulated customer's object ran
5``os.chmod("/data/objects/users/1/vault.py", 0)`` and user 1's object
6stopped working; ``os.stat`` told it the size, owner and mtime of other
7customers' files. Landlock has no right for metadata, and the worker was the
8server's uid, which owns everything. The launcher starts workers as a uid
9that owns nothing; it runs as root, so every request it accepts is a
10privilege boundary and is checked strictly.
11
12Two halves:
13
14- **Protocol** (peer check, request validation, fd checks, the fixed entry
15 point) is pure code and runs everywhere, including macOS.
16- **The real thing** needs Linux, Landlock ABI >= 4 and a launcher running
17 as root. Those tests skip elsewhere. To run them in Linux Docker, start the
18 image's entrypoint as root (it starts the launcher, then drops to
19 ``dbbasic``) with the checkout mounted and pytest installed::
20
21 docker build -t dbos-privsep-test .
22 # an image with pytest on top: FROM dbos-privsep-test / RUN pip install pytest
23 docker run --rm -v "$PWD":/src:ro -w /src dbos-privsep-test:pytest \\
24 python -m pytest -q -p no:cacheprovider tests/test_object_sandbox_launcher.py
25"""
26from __future__ import annotations
27
28import json
29import os
30import socket
31import stat
32import struct
33import sys
34import time
35
36import pytest
37
38import object_sandbox
39import object_sandbox_launcher as launcher
40from runtime_modes import configure, run_object, write_object
41
42LENGTH = struct.Struct(">I")
43
44
45def frame(obj) -> bytes:
46 body = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
47 return LENGTH.pack(len(body)) + body
48
49
50@pytest.fixture
51def pipes():
52 to_r, to_w = os.pipe()
53 from_r, from_w = os.pipe()
54 yield to_r, to_w, from_r, from_w
55 for fd in (to_r, to_w, from_r, from_w):
56 try:
57 os.close(fd)
58 except OSError:
59 pass
60
61
62# -- protocol: runs everywhere --------------------------------------------------
63
64
65def test_only_the_server_uid_may_connect():
66 launcher.check_peer(999, 999)
67 with pytest.raises(launcher.Refused, match="uid 1000"):
68 launcher.check_peer(1000, 999)
69 with pytest.raises(launcher.Refused):
70 launcher.check_peer(0, 999) # not even root: nobody but the server asks
71
72
73@pytest.mark.parametrize("body, why", [
74 (b"not json", "not JSON"),
75 (b"\xff\xfe", "not JSON"),
76 (b"[1, 2]", "version-1"),
77 (json.dumps({"op": "spawn"}).encode(), "version-1"),
78 (json.dumps({"v": 2, "op": "spawn"}).encode(), "version-1"),
79 (json.dumps({"v": 1, "op": "exec", "argv": ["/bin/sh"]}).encode(), "unknown op"),
80 (json.dumps({"v": 1, "op": "spawn", "argv": ["/bin/sh"]}).encode(), "unknown spawn fields"),
81 (json.dumps({"v": 1, "op": "spawn", "python": "/bin/sh"}).encode(), "unknown spawn fields"),
82 (json.dumps({"v": 1, "op": "spawn", "env": {"LD_PRELOAD": "/tmp/x.so"}}).encode(), "not allowed"),
83 (json.dumps({"v": 1, "op": "spawn", "env": {"DBBASIC_ADMIN_TOKEN": "x"}}).encode(), "not allowed"),
84 (json.dumps({"v": 1, "op": "spawn", "env": {"PATH": 7}}).encode(), "short string"),
85 (json.dumps({"v": 1, "op": "spawn", "env": {"PATH": "a" * 2000}}).encode(), "short string"),
86 (json.dumps({"v": 1, "op": "spawn", "env": {"PATH": "a\0b"}}).encode(), "short string"),
87 (json.dumps({"v": 1, "op": "spawn", "env": ["PATH"]}).encode(), "env must be"),
88 (json.dumps({"v": 1, "op": "status", "extra": 1}).encode(), "status takes"),
89 (b"x" * (launcher.MAX_REQUEST_BYTES + 1), "exceeds"),
90])
91def test_malformed_requests_are_refused(pipes, body, why):
92 to_r, _to_w, _from_r, from_w = pipes
93 with pytest.raises(launcher.Refused, match=why):
94 launcher.parse_request(body, [to_r, from_w])
95
96
97def test_spawn_needs_exactly_a_read_end_then_a_write_end(pipes, tmp_path):
98 to_r, to_w, from_r, from_w = pipes
99 body = json.dumps({"v": 1, "op": "spawn"}).encode()
100 for fds in ([], [to_r], [to_r, from_w, from_r], [from_w, to_r], [to_w, from_w], [to_r, from_r]):
101 with pytest.raises(launcher.Refused, match="two fds"):
102 launcher.parse_request(body, fds)
103 regular = os.open(tmp_path / "file", os.O_CREAT | os.O_RDWR)
104 try:
105 with pytest.raises(launcher.Refused, match="two fds"):
106 launcher.parse_request(body, [regular, from_w])
107 finally:
108 os.close(regular)
109 status = json.dumps({"v": 1, "op": "status"}).encode()
110 with pytest.raises(launcher.Refused, match="no fds"):
111 launcher.parse_request(status, [to_r, from_w])
112
113
114def test_valid_requests_parse_to_known_fields_only(pipes):
115 to_r, _to_w, _from_r, from_w = pipes
116 assert launcher.parse_request(b'{"v": 1, "op": "status"}', []) == {"op": "status"}
117 spawn = launcher.parse_request(
118 json.dumps({"v": 1, "op": "spawn", "env": {"LANG": "C.UTF-8", "LC_ALL": "C", "TZ": "UTC"}}).encode(),
119 [to_r, from_w])
120 assert spawn == {"op": "spawn", "channel": "pipes",
121 "env": {"LANG": "C.UTF-8", "LC_ALL": "C", "TZ": "UTC", "PATH": "/usr/bin:/bin"}}
122
123
124def test_a_socket_spawn_needs_exactly_one_connected_unix_stream_socket(pipes):
125 """The fork server's channel: one connected AF_UNIX stream socket, and
126 nothing else is mistaken for one."""
127 to_r, _to_w, _from_r, from_w = pipes
128 body = json.dumps({"v": 1, "op": "spawn", "channel": "socket"}).encode()
129 a, b = socket.socketpair()
130 c, d = socket.socketpair()
131 dgram_a, dgram_b = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM)
132 listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
133 inet = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
134 try:
135 assert launcher.parse_request(body, [b.fileno()]) == {"op": "spawn", "channel": "socket",
136 "env": {"PATH": "/usr/bin:/bin"}}
137 for fds in ([], [b.fileno(), d.fileno()], [to_r], [to_r, from_w], [dgram_b.fileno()],
138 [listener.fileno()], [inet.fileno()]):
139 with pytest.raises(launcher.Refused, match="exactly one fd"):
140 launcher.parse_request(body, fds)
141 # ... and a pipe spawn still takes pipes only, never the socket
142 with pytest.raises(launcher.Refused, match="two fds"):
143 launcher.parse_request(json.dumps({"v": 1, "op": "spawn"}).encode(), [b.fileno(), b.fileno()])
144 with pytest.raises(launcher.Refused, match="unknown channel"):
145 launcher.parse_request(json.dumps({"v": 1, "op": "spawn", "channel": "tty"}).encode(), [b.fileno()])
146 finally:
147 for sock in (a, b, c, d, dgram_a, dgram_b, listener, inet):
148 sock.close()
149
150
151def test_launcher_and_server_agree_on_the_environment_allow_list():
152 assert set(launcher.ENV_ALLOW) == set(object_sandbox._ENV_ALLOW)
153 assert object_sandbox._ENV_ALLOW_PREFIX == ("LC_",)
154
155
156def test_recv_request_refuses_oversize_lengths_and_extra_fds(pipes):
157 to_r, _to_w, from_r, from_w = pipes
158 a, b = socket.socketpair()
159 with a, b:
160 a.sendall(LENGTH.pack(launcher.MAX_REQUEST_BYTES + 1))
161 with pytest.raises(launcher.Refused, match="exceeds"):
162 launcher.recv_request(b, timeout=1)
163 a, b = socket.socketpair()
164 with a, b:
165 import array
166
167 a.sendmsg([frame({"v": 1, "op": "spawn"})],
168 [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [to_r, from_w, from_r]))])
169 with pytest.raises(launcher.Refused):
170 launcher.recv_request(b, timeout=1)
171 a, b = socket.socketpair()
172 with a, b:
173 a.sendall(LENGTH.pack(50) + b"{")
174 a.shutdown(socket.SHUT_WR)
175 with pytest.raises(launcher.Refused, match="closed mid-request"):
176 launcher.recv_request(b, timeout=1)
177 a, b = socket.socketpair()
178 with a, b:
179 a.sendall(LENGTH.pack(50))
180 started = time.monotonic()
181 with pytest.raises(launcher.Refused, match="deadline"):
182 launcher.recv_request(b, timeout=0.3)
183 assert time.monotonic() - started < 2
184
185
186def test_received_fds_arrive_with_the_request(pipes):
187 import array
188
189 to_r, _to_w, _from_r, from_w = pipes
190 a, b = socket.socketpair()
191 with a, b:
192 a.sendmsg([frame({"v": 1, "op": "spawn"})],
193 [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [to_r, from_w]))])
194 body, fds = launcher.recv_request(b, timeout=1)
195 try:
196 assert json.loads(body) == {"v": 1, "op": "spawn"}
197 assert len(fds) == 2 and stat.S_ISFIFO(os.fstat(fds[0]).st_mode)
198 assert launcher.parse_request(body, fds)["op"] == "spawn"
199 finally:
200 launcher._close_all(fds)
201
202
203class _FakePopen:
204 calls: list = []
205
206 def __init__(self, argv, **kwargs):
207 _FakePopen.calls.append((argv, kwargs))
208 self.pid = 4242
209
210 def poll(self):
211 return None
212
213 def wait(self):
214 return 0
215
216
217def _launcher(monkeypatch, peer_uid=999):
218 monkeypatch.setattr(launcher, "_libc", lambda: None)
219 return launcher.Launcher(server_uid=999, sandbox_uid=64999, sandbox_gid=64999,
220 python="/usr/bin/python3", script="/opt/x/object_sandbox.py",
221 netns=False, peer=lambda conn: peer_uid)
222
223
224def _reply(sock):
225 length = LENGTH.unpack(sock.recv(4))[0]
226 return json.loads(sock.recv(length))
227
228
229def test_only_the_fixed_worker_entry_point_is_ever_started(monkeypatch, pipes):
230 """Whatever the request says, the launcher starts <python> -I -B
231 <object_sandbox.py> --worker, dropping privileges before exec."""
232 import array
233
234 to_r, _to_w, _from_r, from_w = pipes
235 _FakePopen.calls = []
236 monkeypatch.setattr(launcher.subprocess, "Popen", _FakePopen)
237 run = _launcher(monkeypatch)
238 a, b = socket.socketpair()
239 with a:
240 a.sendmsg([frame({"v": 1, "op": "spawn", "env": {"LANG": "C"}})],
241 [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [to_r, from_w]))])
242 proc = run.accept(b)
243 assert proc is not None and proc.pid == 4242
244 assert _reply(a) == {"ok": True, "pid": 4242, "netns": False}
245 [(argv, kwargs)] = _FakePopen.calls
246 assert argv == ["/usr/bin/python3", "-I", "-B", "/opt/x/object_sandbox.py", "--worker"]
247 assert kwargs["preexec_fn"] == run._drop_privileges
248 assert kwargs["start_new_session"] and kwargs["close_fds"]
249 assert kwargs["env"] == {"LANG": "C", "PATH": "/usr/bin:/bin"}
250 b.close()
251
252
253def test_a_socket_channel_becomes_the_workers_stdin_and_stdout(monkeypatch):
254 import array
255
256 _FakePopen.calls = []
257 monkeypatch.setattr(launcher.subprocess, "Popen", _FakePopen)
258 run = _launcher(monkeypatch)
259 a, b = socket.socketpair()
260 server_end, worker_end = socket.socketpair()
261 with a, server_end, worker_end:
262 a.sendmsg([frame({"v": 1, "op": "spawn", "channel": "socket"})],
263 [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [worker_end.fileno()]))])
264 assert run.accept(b) is not None
265 assert _reply(a)["ok"] is True
266 [(argv, kwargs)] = _FakePopen.calls
267 assert argv[-1] == "--worker"
268 assert kwargs["stdin"] == kwargs["stdout"]
269 assert kwargs["preexec_fn"] == run._drop_privileges
270 b.close()
271
272
273needs_proc = pytest.mark.skipif(
274 not sys.platform.startswith("linux") or not hasattr(os, "pidfd_open"),
275 reason="needs Linux /proc and pidfd_open")
276
277SESSION_TREE = r'''
278import os, sys, time
279pid = os.fork()
280if pid == 0:
281 os.setpgid(0, 0) # its own group, as a fork server's child: killpg of the leader misses it
282 print(os.getpid(), flush=True)
283 time.sleep(60)
284 os._exit(0)
285time.sleep(60)
286'''
287
288
289@needs_proc
290def test_kill_session_reaches_a_process_in_its_own_group():
291 """A fork server's child sits in a group of its own, out of reach of
292 killpg on the worker; the session sweep still reaches it."""
293 import subprocess
294
295 leader = subprocess.Popen([sys.executable, "-c", SESSION_TREE], stdout=subprocess.PIPE,
296 start_new_session=True, text=True)
297 try:
298 child = int(leader.stdout.readline())
299 assert launcher._session_of(child) == leader.pid
300 assert os.getpgid(child) != leader.pid
301 os.killpg(leader.pid, 9)
302 leader.wait(5)
303 os.kill(child, 0) # survived the group kill
304 assert launcher.kill_session(leader.pid) == 1
305 # kill_session waits for what it killed: dead on return (gone, or a
306 # zombie waiting for its reaper -- the launcher reaps right after).
307 # Its reaper can be mid-reap, when the state reads X (dead), or finish
308 # between the open and the read, which fails with ESRCH: both are
309 # "gone" as well.
310 try:
311 with open(f"/proc/{child}/stat") as handle:
312 assert handle.read().split(")")[-1].split()[0] in ("Z", "X", "x")
313 except (FileNotFoundError, ProcessLookupError):
314 pass
315 finally:
316 leader.kill()
317 leader.wait()
318 assert launcher.kill_session(1) == 0 and launcher.kill_session(0) == 0 # never init, never "all"
319
320
321@needs_proc
322def test_orphans_are_reaped_but_a_tracked_worker_is_left_to_its_popen(monkeypatch):
323 import subprocess
324
325 run = _launcher(monkeypatch)
326 tracked = subprocess.Popen([sys.executable, "-c", "pass"])
327 orphan = os.fork()
328 if orphan == 0:
329 os._exit(7)
330 tracked_conn = object()
331 run.workers[tracked_conn] = tracked
332 deadline = time.monotonic() + 5
333 while time.monotonic() < deadline:
334 run.reap_orphans()
335 try:
336 if os.waitpid(orphan, os.WNOHANG) == (0, 0):
337 time.sleep(0.02)
338 continue
339 except ChildProcessError:
340 break # reaped by reap_orphans
341 pytest.fail("the orphan was left for the test to reap")
342 else:
343 pytest.fail("the orphan was never reaped")
344 tracked.wait(5)
345 assert tracked.returncode == 0 # its own Popen got the real status
346
347
348def test_status_advertises_the_socket_channel(monkeypatch):
349 run = _launcher(monkeypatch)
350 assert run.status()["channels"] == ["pipes", "socket"]
351
352
353def test_a_stranger_gets_no_reply_and_no_worker(monkeypatch, capsys):
354 _FakePopen.calls = []
355 monkeypatch.setattr(launcher.subprocess, "Popen", _FakePopen)
356 run = _launcher(monkeypatch, peer_uid=1000)
357 a, b = socket.socketpair()
358 with a:
359 a.sendall(frame({"v": 1, "op": "status"}))
360 assert run.accept(b) is None
361 try:
362 assert a.recv(10) == b"" # closed, nothing said
363 except ConnectionResetError:
364 pass # Linux resets a connection closed with its request unread
365 assert _FakePopen.calls == []
366 assert "refused" in capsys.readouterr().err
367
368
369def test_a_malformed_request_is_refused_and_logged(monkeypatch, capsys):
370 _FakePopen.calls = []
371 monkeypatch.setattr(launcher.subprocess, "Popen", _FakePopen)
372 run = _launcher(monkeypatch)
373 a, b = socket.socketpair()
374 with a:
375 a.sendall(frame({"v": 1, "op": "spawn", "argv": ["/bin/sh", "-c", "id"]}))
376 assert run.accept(b) is None
377 assert _reply(a)["ok"] is False
378 assert _FakePopen.calls == []
379 assert "unknown spawn fields" in capsys.readouterr().err
380
381
382def test_status_reports_the_sandbox_user_and_network_layers(monkeypatch):
383 run = _launcher(monkeypatch)
384 a, b = socket.socketpair()
385 with a:
386 a.sendall(frame({"v": 1, "op": "status"}))
387 assert run.accept(b) is None
388 reply = _reply(a)
389 assert reply["ok"] is True and reply["sandbox_uid"] == 64999 and reply["netns"] is False
390 assert set(reply) >= {"inet_sockets", "interfaces"}
391
392
393def test_launcher_refuses_to_start_unprivileged_or_misconfigured():
394 if sys.platform.startswith("linux") and os.geteuid() == 0:
395 pytest.skip("running as root: the refusal under test is for non-root")
396 assert launcher.main(["--server-user", "nobody", "--sandbox-user", "nobody",
397 "--python", sys.executable, "--worker", object_sandbox.__file__]) == 2
398
399
400# -- the real thing: Linux, Landlock >= 4, a root launcher running ----------------
401
402HAS_LAUNCHER = (
403 sys.platform.startswith("linux")
404 and object_sandbox.landlock_abi() >= object_sandbox.MIN_LANDLOCK_ABI
405 and os.geteuid() != 0
406 and object_sandbox.launcher_info() is not None
407)
408needs_launcher = pytest.mark.skipif(
409 not HAS_LAUNCHER,
410 reason="needs Linux with Landlock ABI >= 4, a non-root server user and the root launcher running "
411 "(Linux Docker; see the module docstring)",
412)
413
414
415@pytest.fixture
416def walled(monkeypatch):
417 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
418 yield
419 object_sandbox.shutdown()
420
421
422def _status_ids(pid):
423 with open(f"/proc/{pid}/status") as handle:
424 fields = dict(line.split(":", 1) for line in handle if ":" in line)
425 return ([int(x) for x in fields["Uid"].split()], [int(x) for x in fields["Gid"].split()],
426 fields["Groups"].split(), fields["CapEff"].strip())
427
428
429@needs_launcher
430def test_launched_worker_runs_as_the_sandbox_user_with_nothing_else(walled):
431 info = object_sandbox.launcher_info()
432 worker = object_sandbox._Worker(object_sandbox._boot_config(), launched=True)
433 try:
434 worker.wait_ready(time.monotonic() + 10)
435 uids, gids, groups, caps = _status_ids(worker.pid)
436 assert uids == [info["sandbox_uid"]] * 4
437 assert gids == [info["sandbox_gid"]] * 4
438 assert groups == [] and int(caps, 16) == 0
439 assert info["sandbox_uid"] != os.getuid()
440 finally:
441 worker.kill()
442
443
444@needs_launcher
445def test_closing_the_connection_kills_the_worker(walled):
446 worker = object_sandbox._Worker(object_sandbox._boot_config(), launched=True)
447 worker.wait_ready(time.monotonic() + 10)
448 pid = worker.pid
449 worker.kill()
450 deadline = time.monotonic() + 5
451 while time.monotonic() < deadline:
452 try:
453 os.kill(pid, 0)
454 except ProcessLookupError:
455 return
456 except PermissionError:
457 pass
458 time.sleep(0.02)
459 pytest.fail(f"worker {pid} outlived its connection")
460
461
462EXPLOIT = '''
463import os, errno
464
465def _try(fn):
466 try:
467 value = fn()
468 except OSError as exc:
469 return "denied: " + errno.errorcode.get(exc.errno, str(exc.errno))
470 return "ALLOWED " + repr(value)[:60]
471
472def GET(request):
473 out = {}
474 for label, path in TARGETS.items():
475 out["chmod " + label] = _try(lambda: os.chmod(path, 0))
476 out["utime " + label] = _try(lambda: os.utime(path, (0, 0)))
477 out["chown " + label] = _try(lambda: os.chown(path, os.getuid(), -1))
478 out["stat " + label] = _try(lambda: os.stat(path).st_size)
479 out["kill server"] = _try(lambda: os.kill(SERVER_PID, 0))
480 out["uid"] = os.getuid()
481 return out
482'''
483
484
485@pytest.fixture
486def open_parent(monkeypatch):
487 """A deployment-shaped layout: /data-like parent that anyone may
488 traverse, with the data and objects directories inside, created 0755 as
489 a umask-022 server would. pytest's own tmp dirs are 0700 and would hide
490 the very thing under test."""
491 import shutil
492 import tempfile
493
494 parent = tempfile.mkdtemp(prefix="dbbasic-privsep-")
495 os.chmod(parent, 0o755)
496 try:
497 yield __import__("pathlib").Path(parent)
498 finally:
499 shutil.rmtree(parent, ignore_errors=True)
500
501
502@needs_launcher
503def test_the_chmod_exploit_and_its_relatives_now_fail(open_parent, monkeypatch, walled):
504 """The verified exploit (chmod another customer's object to 0), its
505 relatives (utime, chown, stat) on another customer's object and on
506 server files, and signalling the server: all refused, and a file that
507 exists cannot be told apart from one that does not."""
508 data_dir, root = configure(monkeypatch, open_parent)
509 data_dir.mkdir()
510 os.chmod(data_dir, 0o755)
511 os.chmod(root, 0o755)
512 vault = write_object(root, "u_1_vault", "def GET(request):\n return {'vault': 'intact'}\n")
513 state = data_dir / "state" / "u_1_vault" / "state.tsv"
514 state.parent.mkdir(parents=True)
515 state.write_text("balance\t100\t0\n")
516 token = data_dir / "admin_token"
517 token.write_text("unit-test-only")
518 # Server code: world-readable in a traversable directory, as on a real
519 # install. (Not this checkout's own file: through a Docker Desktop /
520 # OrbStack bind mount any container uid may chmod it, which says
521 # nothing about a real filesystem -- and mount the checkout read-only.)
522 code = open_parent / "code"
523 code.mkdir()
524 server_code = str(code / "object_server.py")
525 (code / "object_server.py").write_text("# server code\n")
526 os.chmod(server_code, 0o644)
527 targets = {
528 "other user's object": str(vault),
529 "other user's missing object": str(vault.parent / "nothere.py"),
530 "other user's state": str(state),
531 "admin token": str(token),
532 "objects root": str(root),
533 "server code": server_code,
534 }
535 assert object_sandbox.protect_private_dirs() is None # what every run does first
536 before = {path: os.stat(path) for path in targets.values() if os.path.exists(path)}
537 source = EXPLOIT.replace("TARGETS", repr(targets)).replace("SERVER_PID", str(os.getpid()))
538 write_object(root, "u_2_evil", source)
539
540 result = run_object("in_process", root, "u_2_evil")
541 assert result.ok, result.error
542 out = result.result
543 assert out.pop("uid") == object_sandbox.launcher_info()["sandbox_uid"]
544 allowed = {k: v for k, v in out.items() if not v.startswith("denied")
545 and k not in ("stat server code", "stat objects root")} # see docs: these two stat
546 assert allowed == {}, f"the sandbox user could still: {allowed}"
547 # Existence does not leak: the same answer for a file that exists and one that does not.
548 for verb in ("chmod", "utime", "stat"):
549 assert out[f"{verb} other user's object"] == out[f"{verb} other user's missing object"]
550 # EPERM when the sandbox user can reach the file but doesn't own it; EACCES when it
551 # can't even reach it (e.g. pytest's private temp dirs). Both are refusals.
552 assert out["chmod server code"] in ("denied: EPERM", "denied: EACCES")
553 assert out["kill server"] == "denied: EPERM"
554 for path, info in before.items():
555 assert os.stat(path).st_mode == info.st_mode, path
556 assert os.stat(path).st_mtime_ns == info.st_mtime_ns, path
557 victim = run_object("in_process", root, "u_1_vault")
558 assert victim.ok and victim.result == {"vault": "intact"}
559 # It was the server closing its directories that did it, not luck.
560 assert os.stat(root).st_mode & 0o777 == 0o700
561 assert os.stat(data_dir).st_mode & 0o777 == 0o700
562
563
564@needs_launcher
565def test_network_namespace_when_the_launcher_has_one(tmp_path, monkeypatch, walled):
566 """With CAP_SYS_ADMIN the worker has no interfaces but its own down
567 loopback; without it the layer is skipped and the status says so."""
568 info = object_sandbox.launcher_info()
569 _data_dir, root = configure(monkeypatch, tmp_path)
570 write_object(root, "u_7_net", "import socket\ndef GET(r):\n return sorted(n for _i, n in socket.if_nameindex())\n")
571 result = run_object("in_process", root, "u_7_net")
572 assert result.ok, result.error
573 status = object_sandbox.isolation_status()
574 assert status["network_namespace"] is bool(info["netns"])
575 if info["netns"]:
576 assert result.result == ["lo"]
577 assert status["udp"].startswith("blocked")
578
579
580ABI4_CHILD = r'''
581import json, os, socket, sys
582sys.path.insert(0, REPO)
583import object_sandbox
584object_sandbox._apply_landlock(object_sandbox._python_read_paths([REPO, TMP]), 4)
585out = {}
586def _try(name, fn):
587 try:
588 fn()
589 out[name] = "ALLOWED"
590 except OSError:
591 out[name] = "denied"
592_try("read repo", lambda: open(os.path.join(REPO, "object_server.py")).read())
593_try("write tmp", lambda: open(os.path.join(TMP, "x"), "w").write("x"))
594_try("tcp connect", lambda: socket.create_connection(("127.0.0.1", PORT), timeout=2))
595_try("tcp bind", lambda: socket.socket().bind(("127.0.0.1", 0)))
596print(json.dumps(out))
597'''
598
599
600@pytest.mark.skipif(not sys.platform.startswith("linux") or object_sandbox.landlock_abi() < 4,
601 reason="needs Linux with Landlock ABI >= 4")
602def test_an_abi_4_ruleset_still_denies_files_and_tcp(tmp_path):
603 """Ubuntu 24.04's kernel (6.8) has ABI 4: no signal or abstract-socket
604 scoping (the launcher's separate uid covers signals to the server), but
605 the ruleset an ABI-4 kernel accepts must still deny files and TCP.
606 Applied here with the ABI-4 structure on whatever newer kernel runs it."""
607 import subprocess
608
609 listener = socket.socket()
610 listener.bind(("127.0.0.1", 0))
611 listener.listen(1)
612 repo = os.path.dirname(os.path.realpath(object_sandbox.__file__))
613 code = (ABI4_CHILD.replace("REPO", repr(repo)).replace("TMP", repr(str(tmp_path)))
614 .replace("PORT", str(listener.getsockname()[1])))
615 try:
616 done = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, timeout=30)
617 finally:
618 listener.close()
619 assert done.returncode == 0, done.stderr
620 assert json.loads(done.stdout) == {"read repo": "denied", "write tmp": "denied",
621 "tcp connect": "denied", "tcp bind": "denied"}
622
623
624# -- how a launched worker ended ------------------------------------------------
625#
626# The launcher reaps its workers, so the server could not say why one died:
627# "exit status unknown", and no hint when it was the memory limit. The
628# launcher now says so on the worker's own connection.
629
630
631def test_only_a_well_formed_exit_message_gives_a_status():
632 parse = object_sandbox._parse_launcher_exit
633 assert parse(b'{"exited":true,"status":3}') == 3
634 assert parse(b'{"exited":true,"status":-9}') == -9
635 assert parse(b'{"exited":true,"status":0}') == 0
636 for body in (b"", b"not json", b"[]", b'"x"', b'{"status":3}', b'{"exited":false,"status":3}',
637 b'{"exited":1,"status":3}', b'{"exited":true}', b'{"exited":true,"status":"9"}',
638 b'{"exited":true,"status":true}', b'{"exited":true,"status":1.5}',
639 b'{"exited":true,"status":4096}', b'{"exited":true,"status":-4096}', b"\xff\xfe"):
640 assert parse(body) is None, body
641
642
643def _launched_worker(conn):
644 """A _Worker as the launcher path leaves it, without starting anything."""
645 worker = object.__new__(object_sandbox._Worker)
646 worker.process = None
647 worker.conn = conn
648 worker._launcher_status = None
649 worker._launcher_buffer = bytearray()
650 worker._stderr = None
651 return worker
652
653
654def test_the_server_reads_what_the_launcher_says_about_a_dead_worker():
655 ours, theirs = socket.socketpair()
656 try:
657 worker = _launched_worker(ours)
658 assert worker.alive()
659 assert worker.status_now() is None # still running: nothing said
660 assert launcher.send_exit_notice(theirs, -9) is True
661 assert worker.status_now(1.0) == -9
662 assert worker.status_now() == -9 # remembered
663 assert not worker.alive() # read or not, it has ended
664 finally:
665 ours.close()
666 theirs.close()
667
668
669def test_an_exit_message_that_arrives_in_pieces_is_still_read():
670 ours, theirs = socket.socketpair()
671 try:
672 worker = _launched_worker(ours)
673 data = frame({"exited": True, "status": 3})
674 theirs.sendall(data[:5])
675 assert worker.status_now(0.05) is None
676 theirs.sendall(data[5:])
677 assert worker.status_now(1.0) == 3
678 finally:
679 ours.close()
680 theirs.close()
681
682
683@pytest.mark.parametrize("sent", [None, b"", frame(b"not json"), frame({"ok": True}), LENGTH.pack(1 << 30)])
684def test_a_launcher_that_says_nothing_useful_leaves_the_status_unknown(sent):
685 """An older launcher never sends the message; one that is gone closes."""
686 ours, theirs = socket.socketpair()
687 try:
688 worker = _launched_worker(ours)
689 if sent == b"":
690 theirs.close()
691 elif sent is not None:
692 theirs.sendall(sent)
693 started = time.monotonic()
694 assert worker.status_now(0.05) is None
695 assert time.monotonic() - started < 1.0
696 assert object_sandbox._describe_status(worker.status_now()) == "exit status unknown"
697 finally:
698 ours.close()
699 theirs.close()
700
701
702def test_the_exit_notice_never_raises_and_only_sends_a_real_status():
703 ours, theirs = socket.socketpair()
704 assert launcher.send_exit_notice(theirs, None) is False # not reaped: nothing to say
705 assert launcher.send_exit_notice(theirs, True) is False
706 ours.close()
707 theirs.close()
708 assert launcher.send_exit_notice(theirs, 1) is False # the server is gone
709
710
711def test_a_launched_workers_death_is_logged_with_its_status_and_the_hint(caplog):
712 import logging
713
714 object_sandbox._WORKER_LOG.reset()
715 caplog.set_level(logging.WARNING, logger="dbbasic.object_sandbox")
716 ours, theirs = socket.socketpair()
717 try:
718 worker = _launched_worker(ours)
719 worker.pid = 4242
720 worker.ready = True
721 worker.started = time.monotonic()
722 worker.memory_limit = 512 * 1024 * 1024
723 launcher.send_exit_notice(theirs, -9)
724 object_sandbox._log_worker_death("fork server", worker, "stopped answering", status=worker.status_now(1.0))
725 finally:
726 ours.close()
727 theirs.close()
728 object_sandbox._WORKER_LOG.reset()
729 [line] = [r.getMessage() for r in caplog.records if r.name == "dbbasic.object_sandbox"]
730 assert "fork server (pid 4242) stopped answering: killed by SIGKILL" in line
731 assert "memory limit 512 MiB" in line and object_sandbox.MEMORY_MB_ENV in line
732
733
734@needs_proc
735def test_the_launcher_reports_a_worker_that_ends_by_itself(monkeypatch):
736 import selectors
737 import signal
738 import subprocess
739
740 box = _launcher(monkeypatch)
741 selector = selectors.DefaultSelector()
742 ours, theirs = socket.socketpair()
743 proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
744 try:
745 box.workers[theirs] = proc
746 box.watch_exit(selector, theirs, proc)
747 assert theirs in box.exit_fds
748 assert selector.select(timeout=0.2) == [] # still running: nothing to report
749 proc.send_signal(signal.SIGKILL)
750 [(key, _events)] = selector.select(timeout=5)
751 assert key.data == ("exit", theirs, proc)
752 box.report_exit(selector, theirs, proc)
753 assert box.exit_fds == {}
754 assert _launched_worker(ours).status_now(1.0) == -signal.SIGKILL
755 assert theirs in box.workers # the connection is still the server's to close
756 finally:
757 box.unwatch_exit(selector, theirs)
758 proc.kill()
759 proc.wait()
760 selector.close()
761 ours.close()
762 theirs.close()
763
764
765@needs_launcher
766def test_a_launched_worker_that_dies_has_a_known_status(walled):
767 worker = object_sandbox._Worker(object_sandbox._boot_config(), launched=True)
768 try:
769 worker.wait_ready(time.monotonic() + 10)
770 os.close(worker.write_fd) # end of its input: it exits by itself, status 0
771 worker.write_fd = -1
772 deadline = time.monotonic() + 5
773 status = None
774 while status is None and time.monotonic() < deadline:
775 status = worker.status_now(0.2)
776 assert status == 0
777 assert not worker.alive()
778 finally:
779 worker.kill()