askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
signal_helper.py · 4.9 KB · 135 lines
| 1 | """Test-only root helper: signal one sandbox-user process for a test. |
| 2 | |
| 3 | Under the real setup the tests run as the server user and user-code workers |
| 4 | run as the sandbox user, started by the root launcher. The server user |
| 5 | cannot signal them, so the tests that kill a worker to see what the server |
| 6 | does next could not run there. This helper is root and sends the signal for |
| 7 | them. It exists only in the test image (tests/linux_sandbox/Dockerfile); the |
| 8 | real image has no such thing and the server has no code that talks to it. |
| 9 | |
| 10 | It is root, so it checks everything, and does as little as possible: |
| 11 | |
| 12 | - only the one client uid may connect (SO_PEERCRED), on a socket in a |
| 13 | directory only that uid can enter; |
| 14 | - a request is one short JSON object, ``{"pid": <int>, "signal": <name>}``; |
| 15 | - the signal is SIGKILL or SIGSTOP, nothing else; |
| 16 | - every uid of the target (real, effective, saved, filesystem) must be the |
| 17 | sandbox uid. The process is opened as a pidfd first and checked after, and |
| 18 | the signal goes to the pidfd, so a recycled pid is never signalled. |
| 19 | |
| 20 | Standard library only; run with ``python -I -S``. |
| 21 | """ |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import argparse |
| 25 | import json |
| 26 | import os |
| 27 | import pwd |
| 28 | import signal |
| 29 | import socket |
| 30 | import struct |
| 31 | import sys |
| 32 | |
| 33 | ALLOWED = {"SIGKILL": signal.SIGKILL, "SIGSTOP": signal.SIGSTOP} |
| 34 | MAX_REQUEST = 256 |
| 35 | |
| 36 | |
| 37 | def target_uids(pid: int) -> list[int]: |
| 38 | with open(f"/proc/{pid}/status") as handle: |
| 39 | for line in handle: |
| 40 | if line.startswith("Uid:"): |
| 41 | return [int(part) for part in line.split()[1:]] |
| 42 | raise ValueError("no Uid line") |
| 43 | |
| 44 | |
| 45 | def handle(body: bytes, sandbox_uid: int) -> str: |
| 46 | """Do one request; return "ok" or the reason it was refused.""" |
| 47 | try: |
| 48 | request = json.loads(body) |
| 49 | except ValueError: |
| 50 | return "refused: not JSON" |
| 51 | if not isinstance(request, dict) or set(request) != {"pid", "signal"}: |
| 52 | return "refused: expected exactly pid and signal" |
| 53 | pid, name = request["pid"], request["signal"] |
| 54 | if type(pid) is not int or pid <= 1: |
| 55 | return "refused: pid must be an integer above 1" |
| 56 | if not isinstance(name, str) or name not in ALLOWED: |
| 57 | return "refused: signal must be SIGKILL or SIGSTOP" |
| 58 | try: |
| 59 | pidfd = os.pidfd_open(pid) |
| 60 | except OSError as exc: |
| 61 | return f"refused: no such process ({exc.strerror})" |
| 62 | try: |
| 63 | try: |
| 64 | uids = target_uids(pid) |
| 65 | except (OSError, ValueError): |
| 66 | return "refused: cannot read the process's uids" |
| 67 | if len(uids) != 4 or any(uid != sandbox_uid for uid in uids): |
| 68 | return "refused: the process is not the sandbox user's" |
| 69 | try: |
| 70 | signal.pidfd_send_signal(pidfd, ALLOWED[name]) |
| 71 | except OSError as exc: |
| 72 | return f"refused: {exc.strerror}" |
| 73 | return "ok" |
| 74 | finally: |
| 75 | os.close(pidfd) |
| 76 | |
| 77 | |
| 78 | def peer_uid(conn: socket.socket) -> int: |
| 79 | creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")) |
| 80 | _pid, uid, _gid = struct.unpack("3i", creds) |
| 81 | return uid |
| 82 | |
| 83 | |
| 84 | def serve(path: str, client_uid: int, client_gid: int, sandbox_uid: int) -> None: |
| 85 | directory = os.path.dirname(path) |
| 86 | os.makedirs(directory, mode=0o700, exist_ok=True) |
| 87 | os.chown(directory, client_uid, client_gid) |
| 88 | os.chmod(directory, 0o700) |
| 89 | try: |
| 90 | os.unlink(path) |
| 91 | except FileNotFoundError: |
| 92 | pass |
| 93 | server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 94 | server.bind(path) |
| 95 | os.chown(path, client_uid, client_gid) |
| 96 | os.chmod(path, 0o600) |
| 97 | server.listen(8) |
| 98 | while True: |
| 99 | conn, _ = server.accept() |
| 100 | with conn: |
| 101 | try: |
| 102 | conn.settimeout(2.0) |
| 103 | if peer_uid(conn) != client_uid: |
| 104 | continue # a stranger gets no reply |
| 105 | body = conn.recv(MAX_REQUEST + 1) |
| 106 | if len(body) > MAX_REQUEST: |
| 107 | reply = "refused: request too long" |
| 108 | else: |
| 109 | reply = handle(body, sandbox_uid) |
| 110 | print(f"[dbbasic-test-signal] {body[:MAX_REQUEST]!r}: {reply}", file=sys.stderr, flush=True) |
| 111 | conn.sendall(reply.encode()) |
| 112 | except OSError: |
| 113 | continue |
| 114 | |
| 115 | |
| 116 | def main(argv: list[str] | None = None) -> int: |
| 117 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 118 | parser.add_argument("--socket", required=True) |
| 119 | parser.add_argument("--client-user", required=True) |
| 120 | parser.add_argument("--target-user", required=True) |
| 121 | args = parser.parse_args(argv) |
| 122 | if os.geteuid() != 0: |
| 123 | print("the signal helper must run as root", file=sys.stderr) |
| 124 | return 2 |
| 125 | client = pwd.getpwnam(args.client_user) |
| 126 | sandbox = pwd.getpwnam(args.target_user) |
| 127 | if 0 in (client.pw_uid, sandbox.pw_uid) or client.pw_uid == sandbox.pw_uid: |
| 128 | print("the client and target users must be two different non-root users", file=sys.stderr) |
| 129 | return 2 |
| 130 | serve(args.socket, client.pw_uid, client.pw_gid, sandbox.pw_uid) |
| 131 | return 0 |
| 132 | |
| 133 | |
| 134 | if __name__ == "__main__": |
| 135 | sys.exit(main()) |