Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/science/launch.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / science / launch.py` 118 lines ยท 5325 bytes Raw Blame History 1 #!/usr/bin/python3.12 -I 2 """Launcher for allen-science: run as the allen-science user (never root) by the supervisor. 3 4 It binds the one listening socket, 127.0.0.1:18113, in the host network namespace, then execs 5 bubblewrap so the service runs in an empty network namespace holding only that inherited socket: 6 the gateway can connect in over loopback, the service cannot open any connection out (not to 7 loopback, the tailnet or the internet). Inside: a read-only root built from the Python interpreter, 8 its standard library, the shared libraries they, bwrap and prlimit load (resolved with ldd at 9 launch), bwrap and prlimit themselves (for the per-request sandbox) and /opt/allen-science; private 10 tmpfs /tmp and HOME; a cleared environment; no capabilities; its own pid, ipc, uts and cgroup 11 namespaces. Nothing from /etc, /home, /root, /var or /run is mounted. Every inherited descriptor 12 other than stdin, stdout and stderr is closed first, so the listener on fd 3 is the only one the 13 service receives. The launcher writes nothing; output goes to the supervisor. 14 """ 15 16 import argparse 17 import glob 18 import os 19 import socket 20 import subprocess 21 import sys 22 23 PYTHON = "/usr/bin/python3.12" 24 BWRAP = "/usr/bin/bwrap" 25 PRLIMIT = "/usr/bin/prlimit" 26 LDD = "/usr/bin/ldd" 27 STDLIB = "/usr/lib/python3.12" 28 ROOT = "/opt/allen-science" 29 HOME = "/home/allen-science" 30 LISTEN_FD = 3 31 32 33 def libraries(binaries): 34 """{path inside the sandbox: real host file} for every shared object the binaries load.""" 35 found = {} 36 for b in binaries: 37 out = subprocess.run([LDD, b], capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, 38 timeout=20).stdout 39 for line in out.splitlines(): 40 parts = line.split() 41 path = parts[2] if "=>" in parts and len(parts) > 2 else parts[0] if parts else "" 42 if not path.startswith("/"): 43 continue 44 # /lib is a symlink to usr/lib on this host; the sandbox recreates that symlink. 45 dest = "/usr" + path if path.startswith("/lib/") else path 46 found[dest] = os.path.realpath(path) 47 return found 48 49 50 def sandbox_argv(root, service_args): 51 dynload = sorted(glob.glob(STDLIB + "/lib-dynload/*.so")) 52 argv = [ 53 BWRAP, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", 54 "--cap-drop", "ALL", 55 "--ro-bind", PYTHON, PYTHON, "--ro-bind", BWRAP, BWRAP, "--ro-bind", PRLIMIT, PRLIMIT, 56 "--ro-bind", STDLIB, STDLIB, 57 ] 58 for dest, src in sorted(libraries([PYTHON, BWRAP, PRLIMIT] + dynload).items()): 59 argv += ["--ro-bind", src, dest] 60 argv += [ 61 "--symlink", "usr/lib", "/lib", "--symlink", "usr/bin", "/bin", 62 "--ro-bind", root, ROOT, 63 # The per-request bwrap writes its uid map under /proc: a fresh proc for this pid namespace. 64 "--proc", "/proc", "--dev", "/dev", 65 "--size", str(32 << 20), "--tmpfs", "/tmp", 66 "--size", str(4 << 20), "--tmpfs", "/home", "--dir", HOME, 67 "--remount-ro", "/", "--chdir", HOME, 68 "--setenv", "HOME", HOME, "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "LANG", "C.UTF-8", 69 "--", PYTHON, "-I", ROOT + "/allen_science.py", "--listen-fd", str(LISTEN_FD), 70 ] + service_args 71 return argv 72 73 74 def close_fds_except(keep): 75 """Close every open descriptor above 2 that is not in keep. Enumerates /proc/self/fd, so a 76 descriptor numbered above a lowered RLIMIT_NOFILE is closed too; refuses to start without it.""" 77 try: 78 fds = [int(n) for n in os.listdir("/proc/self/fd")] 79 except OSError as e: 80 sys.exit("allen-science launch: cannot list /proc/self/fd (%s); refusing to start" % e) 81 for fd in fds: 82 if fd > 2 and fd not in keep: 83 try: 84 os.close(fd) 85 except OSError: 86 pass # the directory descriptor listdir used is already closed 87 88 89 def main(): 90 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) 91 ap.add_argument("--listen", default="127.0.0.1:18113", help="loopback HOST:PORT (127.0.0.1 only)") 92 ap.add_argument("--root", default=ROOT, help="directory bound read-only at " + ROOT) 93 ap.add_argument("service_args", nargs="*", help="passed to allen_science.py after --") 94 a = ap.parse_args() 95 if os.geteuid() == 0 or os.getuid() == 0: 96 sys.exit("allen-science launch: refusing to run as root; the supervisor drops to allen-science") 97 host, _, port = a.listen.rpartition(":") 98 if host != "127.0.0.1" or not port.isdigit(): 99 sys.exit("allen-science launch: --listen must be 127.0.0.1:PORT") 100 if not os.path.isfile(os.path.join(a.root, "allen_science.py")): 101 sys.exit("allen-science launch: %s/allen_science.py missing" % a.root) 102 # Only stdin, stdout, stderr and the listener may cross into the service. 103 close_fds_except(()) 104 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 105 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 106 s.bind((host, int(port))) 107 s.listen(64) 108 if s.fileno() != LISTEN_FD: 109 os.dup2(s.fileno(), LISTEN_FD) 110 s.close() 111 os.set_inheritable(LISTEN_FD, True) 112 argv = sandbox_argv(os.path.realpath(a.root), a.service_args) 113 close_fds_except((LISTEN_FD,)) 114 os.execv(BWRAP, argv) 115 116 117 if __name__ == "__main__": 118 main()