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/spark-supervisor/blob/main/tests/probe.py # spark-supervisor Process supervisor and health monitor for sovereign daemons 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 `spark-supervisor / tests / probe.py` 199 lines ยท 8737 bytes Raw Blame History 1 #!/usr/bin/python3.12 -I 2 """Sandbox probe for aien-supervise (test oracle, not part of the supervisor). 3 4 Run inside a service sandbox it reports, for each systemd directive the sandbox replaces, whether the 5 process is confined. tests/sandbox.sh runs it three ways: 6 * under `aien-supervise-root run sup-probe`: every check must read `confined`; 7 * as the same user without the sandbox: every kind-d check must read `open`, which proves the 8 probe can see the property missing; 9 * under service files with one directive weakened: the matching check must read `open`. 10 Kind k checks are refused by the kernel to any unprivileged process as well; their negative 11 control is the per-directive mutation only. Python because these checks need raw syscalls that 12 Omega deliberately does not expose. 13 14 usage: probe.py UID NOFILE UMASK MEMMAX_MB HOSTNS_FILE 15 """ 16 import ctypes, errno, mmap, os, socket, sys, time, threading, resource 17 18 libc = ctypes.CDLL("libc.so.6", use_errno=True) 19 libc.syscall.restype = ctypes.c_long 20 results = [] 21 22 23 def report(name, confined, detail="", kind="d"): 24 results.append((name, confined)) 25 print(f"CHECK {name} {'confined' if confined else 'open'} {kind} {detail}".rstrip(), flush=True) 26 27 28 def sc(nr, *args): 29 ctypes.set_errno(0) 30 r = libc.syscall(ctypes.c_long(nr), *[ctypes.c_long(a) for a in args]) 31 return r, ctypes.get_errno() 32 33 34 def status_field(key): 35 for line in open("/proc/self/status"): 36 if line.startswith(key + ":"): 37 return line.split(":", 1)[1].strip() 38 return "" 39 40 41 def denied(nr, *args, want=errno.EPERM): 42 r, e = sc(nr, *args) 43 return r == -1 and e == want, f"r={r} errno={errno.errorcode.get(e, e)}" 44 45 46 def readonly_mount(path): 47 return bool(os.statvfs(path).f_flag & os.ST_RDONLY) 48 49 50 uid, nofile, want_umask, memmax_mb, hostns = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3], 8), int(sys.argv[4]), sys.argv[5] 51 host = dict(l.split() for l in open(hostns)) if os.path.exists(hostns) else {} 52 53 # Identity and privileges: User=, NoNewPrivileges=, CapabilityBoundingSet=, AmbientCapabilities= 54 report("User", os.getuid() == uid and os.geteuid() == uid and uid != 0, f"uid={os.getuid()}", "k") 55 report("NoNewPrivileges", status_field("NoNewPrivs") == "1") 56 report("CapabilityBoundingSet", int(status_field("CapBnd"), 16) == 0, "CapBnd=" + status_field("CapBnd")) 57 report("AmbientCapabilities", int(status_field("CapAmb"), 16) == 0 and int(status_field("CapInh"), 16) == 0, "", "k") 58 report("SystemCallFilter.active", status_field("Seccomp") == "2", "Seccomp=" + status_field("Seccomp")) 59 60 # PrivateUsers=: a user namespace with a single uid mapping (bwrap's --disable-userns adds a 61 # nested namespace, so the outside id shown is that of the intermediate one) 62 um = open("/proc/self/uid_map").read().split() 63 report("PrivateUsers", len(um) == 3 and um[0] == str(uid) and um[2] == "1", " ".join(um)) 64 65 # Namespaces differ from the host's 66 for ns, directive in (("ipc", "PrivateIPC"), ("uts", "ProtectHostname.utsns"), ("pid", "ProtectProc.pidns"), 67 ("cgroup", "ProtectControlGroups.cgroupns"), ("mnt", "ProtectSystem.mntns")): 68 mine = os.readlink(f"/proc/self/ns/{ns}") 69 report(directive, bool(host) and mine != host.get(ns), mine) 70 71 # Filesystem: ProtectSystem=strict, ProtectHome=, PrivateTmp=, PrivateDevices=, ProtectKernel* 72 report("ProtectSystem.usr", readonly_mount("/usr")) 73 report("ProtectSystem.etc", readonly_mount("/etc")) 74 report("ProtectHome", not os.path.exists("/home") and not os.path.exists("/root")) 75 report("PrivateTmp", not os.path.exists("/tmp/aien-sup-hostmarker")) 76 report("PrivateDevices", not any(os.path.exists(p) for p in ("/dev/nvme0n1", "/dev/sda", "/dev/mem", "/dev/nvidia0", "/dev/tpmrm0")) and os.path.exists("/dev/null")) 77 report("ProtectKernelTunables.sys", not os.path.exists("/sys/kernel")) 78 report("ProtectKernelTunables.procsys", readonly_mount("/proc/sys")) 79 report("ProtectControlGroups", not os.path.exists("/sys/fs/cgroup/cgroup.controllers")) 80 npids = len([p for p in os.listdir("/proc") if p.isdigit()]) 81 report("ProtectProc", npids < 20, f"pids={npids}") 82 report("ProtectKernelLogs.kmsg", not os.path.exists("/dev/kmsg")) 83 84 # Syscall filter. Numbers are Linux ARM64. 85 buf = mmap.mmap(-1, 4096) 86 addr = ctypes.addressof(ctypes.c_char.from_buffer(buf)) 87 vec = ctypes.create_string_buffer(1) 88 c, d = denied(232, addr, 4096, ctypes.addressof(vec)); report("SystemCallFilter.mincore", c, d) 89 c, d = denied(444, 0, 0, 1); report("SystemCallFilter.landlock", c, d) 90 c, d = denied(117, 16, `999999999`, 0, 0); report("SystemCallFilter.ptrace", c, d) 91 r, e = sc(222, 0, 4096, 3, 0x22, -1, 0) 92 report("SystemCallFilter.allows_basic_mmap", r > 0, f"r={r}", "k") 93 c, d = denied(40, 0, 0, 0, 0, 0); report("SystemCallFilter.mount", c, d, "k") 94 c, d = denied(116, 3, 0, 0); report("ProtectKernelLogs.syslog", c, d, "k") 95 c, d = denied(105, 0, 0, 0); report("ProtectKernelModules.init_module", c, d, "k") 96 c, d = denied(112, 0, 0); report("ProtectClock.clock_settime", c, d, "k") 97 name = ctypes.create_string_buffer(b"probe") 98 c, d = denied(161, ctypes.addressof(name), 5); report("ProtectHostname.sethostname", c, d, "k") 99 c, d = denied(97, 0x10000000); report("RestrictNamespaces.unshare", c, d) 100 c, d = denied(92, 0x0008) 101 report("LockPersonality", c, d) 102 sc(92, 0) 103 r, e = sc(92, 0xffffffff); report("LockPersonality.query_allowed", r >= 0, f"r={r}", "k") 104 c, d = denied(222, 0, 4096, 7, 0x22, -1, 0); report("MemoryDenyWriteExecute.mmap", c, d) 105 c, d = denied(226, addr, 4096, 5); report("MemoryDenyWriteExecute.mprotect", c, d) 106 fn = "/tmp/suid-probe" 107 open(fn, "w").close() 108 try: 109 os.chmod(fn, 0o4755) 110 report("RestrictSUIDSGID", False, "chmod u+s succeeded") 111 except PermissionError: 112 report("RestrictSUIDSGID", True, "EPERM") 113 os.unlink(fn) 114 param = ctypes.c_int(1) 115 c, d = denied(119, 0, 1, ctypes.addressof(param)); report("RestrictRealtime", c, d, "k") 116 try: 117 socket.socket(17, socket.SOCK_RAW) 118 report("RestrictAddressFamilies", False, "AF_PACKET opened") 119 except OSError as ex: 120 report("RestrictAddressFamilies", ex.errno == errno.EAFNOSUPPORT, errno.errorcode.get(ex.errno, "")) 121 122 # Resources: MemoryMax=, TasksMax=, CPUQuota=, LimitNOFILE=, UMask= 123 report("LimitNOFILE", resource.getrlimit(resource.RLIMIT_NOFILE)[0] == nofile, str(resource.getrlimit(resource.RLIMIT_NOFILE))) 124 report("UMask", os.umask(0o022) == want_umask) 125 report("RestrictRealtime.rlimit", resource.getrlimit(resource.RLIMIT_RTPRIO) == (0, 0), "", "k") 126 cg = open("/proc/self/cgroup").read().strip() 127 report("Cgroup.namespace", cg == "0::/", cg) 128 pid = os.fork() 129 if pid == 0: 130 try: 131 b = bytearray(memmax_mb * 2 * 1024 * 1024) 132 for i in range(0, len(b), 4096): 133 b[i] = 1 134 os._exit(0) 135 except MemoryError: 136 os._exit(3) 137 _, st = os.waitpid(pid, 0) 138 report("MemoryMax", os.WIFSIGNALED(st) and os.WTERMSIG(st) == 9, f"wait_status={st}") 139 kids, refused = [], 0 140 for _ in range(64): 141 try: 142 p = os.fork() 143 except BlockingIOError: 144 refused += 1 145 break 146 if p == 0: 147 time.sleep(2) 148 os._exit(0) 149 kids.append(p) 150 for p in kids: 151 os.waitpid(p, 0) 152 report("TasksMax", refused > 0, f"forked={len(kids)}") 153 stop = time.time() + 1.0 154 155 156 def spin(): 157 while time.time() < stop: 158 pass 159 160 161 t0 = time.process_time() 162 ts = [threading.Thread(target=spin) for _ in range(4)] 163 [t.start() for t in ts] 164 [t.join() for t in ts] 165 used = time.process_time() - t0 166 report("CPUQuota", used < 1.0, f"cpu_s={used:.2f} in 1 s wall with 4 spinners") 167 168 169 # Network: IPAddressDeny=/IPAddressAllow= through the per-uid nftables table 170 def connect(addr, port): 171 s = socket.socket() 172 s.settimeout(2) 173 try: 174 s.connect((addr, port)) 175 return "connected" 176 except OSError as ex: 177 return type(ex).__name__ + ":" + errno.errorcode.get(ex.errno or 0, "timeout") 178 finally: 179 s.close() 180 181 182 out = connect("1.1.1.1", 443) 183 report("IPAddressDeny.outbound", out != "connected", out) 184 out = connect("127.0.0.1", 18096) 185 report("IPAddressAllow.loopback", out == "connected", out, "k") 186 187 # Descriptors and environment: no leaked memfds; only the declared environment 188 fds = sorted(int(f) for f in os.listdir("/proc/self/fd")) 189 report("NoLeakedFds", fds[:3] == [0, 1, 2] and len(fds) <= 4, str(fds), "k") 190 report("Environment", "HOME" not in os.environ and os.environ.get("PROBE_ENV") == "set", ",".join(sorted(os.environ))) 191 cred = os.environ.get("CREDENTIALS_DIRECTORY") 192 try: 193 ok = bool(cred) and open(os.path.join(cred, "probe-secret")).read().strip() == "s3cret-probe" 194 except OSError: 195 ok = False 196 report("ImportCredential", ok, str(cred)) 197 198 n_open = sum(1 for _, c in results if not c) 199 print(f"PROBE {'CONFINED' if n_open == 0 else 'OPEN'} checks={len(results)} open={n_open}", flush=True)