interplane.Get Omega
Read in your language

spark-supervisor

Process supervisor and health monitor for sovereign daemons

Brought by drakestapleton

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
4Run inside a service sandbox it reports, for each systemd directive the sandbox replaces, whether the
5process 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`.
10Kind k checks are refused by the kernel to any unprivileged process as well; their negative
11control is the per-directive mutation only. Python because these checks need raw syscalls that
12Omega deliberately does not expose.
13
14usage: probe.py UID NOFILE UMASK MEMMAX_MB HOSTNS_FILE
15"""
16import ctypes, errno, mmap, os, socket, sys, time, threading, resource
17
18libc = ctypes.CDLL("libc.so.6", use_errno=True)
19libc.syscall.restype = ctypes.c_long
20results = []
21
22
23def 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
28def 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
34def 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
41def 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
46def readonly_mount(path):
47 return bool(os.statvfs(path).f_flag & os.ST_RDONLY)
48
49
50uid, 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]
51host = dict(l.split() for l in open(hostns)) if os.path.exists(hostns) else {}
52
53# Identity and privileges: User=, NoNewPrivileges=, CapabilityBoundingSet=, AmbientCapabilities=
54report("User", os.getuid() == uid and os.geteuid() == uid and uid != 0, f"uid={os.getuid()}", "k")
55report("NoNewPrivileges", status_field("NoNewPrivs") == "1")
56report("CapabilityBoundingSet", int(status_field("CapBnd"), 16) == 0, "CapBnd=" + status_field("CapBnd"))
57report("AmbientCapabilities", int(status_field("CapAmb"), 16) == 0 and int(status_field("CapInh"), 16) == 0, "", "k")
58report("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)
62um = open("/proc/self/uid_map").read().split()
63report("PrivateUsers", len(um) == 3 and um[0] == str(uid) and um[2] == "1", " ".join(um))
64
65# Namespaces differ from the host's
66for 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*
72report("ProtectSystem.usr", readonly_mount("/usr"))
73report("ProtectSystem.etc", readonly_mount("/etc"))
74report("ProtectHome", not os.path.exists("/home") and not os.path.exists("/root"))
75report("PrivateTmp", not os.path.exists("/tmp/aien-sup-hostmarker"))
76report("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"))
77report("ProtectKernelTunables.sys", not os.path.exists("/sys/kernel"))
78report("ProtectKernelTunables.procsys", readonly_mount("/proc/sys"))
79report("ProtectControlGroups", not os.path.exists("/sys/fs/cgroup/cgroup.controllers"))
80npids = len([p for p in os.listdir("/proc") if p.isdigit()])
81report("ProtectProc", npids < 20, f"pids={npids}")
82report("ProtectKernelLogs.kmsg", not os.path.exists("/dev/kmsg"))
83
84# Syscall filter. Numbers are Linux ARM64.
85buf = mmap.mmap(-1, 4096)
86addr = ctypes.addressof(ctypes.c_char.from_buffer(buf))
87vec = ctypes.create_string_buffer(1)
88c, d = denied(232, addr, 4096, ctypes.addressof(vec)); report("SystemCallFilter.mincore", c, d)
89c, d = denied(444, 0, 0, 1); report("SystemCallFilter.landlock", c, d)
90c, d = denied(117, 16, 999999999, 0, 0); report("SystemCallFilter.ptrace", c, d)
91r, e = sc(222, 0, 4096, 3, 0x22, -1, 0)
92report("SystemCallFilter.allows_basic_mmap", r > 0, f"r={r}", "k")
93c, d = denied(40, 0, 0, 0, 0, 0); report("SystemCallFilter.mount", c, d, "k")
94c, d = denied(116, 3, 0, 0); report("ProtectKernelLogs.syslog", c, d, "k")
95c, d = denied(105, 0, 0, 0); report("ProtectKernelModules.init_module", c, d, "k")
96c, d = denied(112, 0, 0); report("ProtectClock.clock_settime", c, d, "k")
97name = ctypes.create_string_buffer(b"probe")
98c, d = denied(161, ctypes.addressof(name), 5); report("ProtectHostname.sethostname", c, d, "k")
99c, d = denied(97, 0x10000000); report("RestrictNamespaces.unshare", c, d)
100c, d = denied(92, 0x0008)
101report("LockPersonality", c, d)
102sc(92, 0)
103r, e = sc(92, 0xffffffff); report("LockPersonality.query_allowed", r >= 0, f"r={r}", "k")
104c, d = denied(222, 0, 4096, 7, 0x22, -1, 0); report("MemoryDenyWriteExecute.mmap", c, d)
105c, d = denied(226, addr, 4096, 5); report("MemoryDenyWriteExecute.mprotect", c, d)
106fn = "/tmp/suid-probe"
107open(fn, "w").close()
108try:
109 os.chmod(fn, 0o4755)
110 report("RestrictSUIDSGID", False, "chmod u+s succeeded")
111except PermissionError:
112 report("RestrictSUIDSGID", True, "EPERM")
113os.unlink(fn)
114param = ctypes.c_int(1)
115c, d = denied(119, 0, 1, ctypes.addressof(param)); report("RestrictRealtime", c, d, "k")
116try:
117 socket.socket(17, socket.SOCK_RAW)
118 report("RestrictAddressFamilies", False, "AF_PACKET opened")
119except OSError as ex:
120 report("RestrictAddressFamilies", ex.errno == errno.EAFNOSUPPORT, errno.errorcode.get(ex.errno, ""))
121
122# Resources: MemoryMax=, TasksMax=, CPUQuota=, LimitNOFILE=, UMask=
123report("LimitNOFILE", resource.getrlimit(resource.RLIMIT_NOFILE)[0] == nofile, str(resource.getrlimit(resource.RLIMIT_NOFILE)))
124report("UMask", os.umask(0o022) == want_umask)
125report("RestrictRealtime.rlimit", resource.getrlimit(resource.RLIMIT_RTPRIO) == (0, 0), "", "k")
126cg = open("/proc/self/cgroup").read().strip()
127report("Cgroup.namespace", cg == "0::/", cg)
128pid = os.fork()
129if 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)
138report("MemoryMax", os.WIFSIGNALED(st) and os.WTERMSIG(st) == 9, f"wait_status={st}")
139kids, refused = [], 0
140for _ 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)
150for p in kids:
151 os.waitpid(p, 0)
152report("TasksMax", refused > 0, f"forked={len(kids)}")
153stop = time.time() + 1.0
154
155
156def spin():
157 while time.time() < stop:
158 pass
159
160
161t0 = time.process_time()
162ts = [threading.Thread(target=spin) for _ in range(4)]
163[t.start() for t in ts]
164[t.join() for t in ts]
165used = time.process_time() - t0
166report("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
170def 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
182out = connect("1.1.1.1", 443)
183report("IPAddressDeny.outbound", out != "connected", out)
184out = connect("127.0.0.1", 18096)
185report("IPAddressAllow.loopback", out == "connected", out, "k")
186
187# Descriptors and environment: no leaked memfds; only the declared environment
188fds = sorted(int(f) for f in os.listdir("/proc/self/fd"))
189report("NoLeakedFds", fds[:3] == [0, 1, 2] and len(fds) <= 4, str(fds), "k")
190report("Environment", "HOME" not in os.environ and os.environ.get("PROBE_ENV") == "set", ",".join(sorted(os.environ)))
191cred = os.environ.get("CREDENTIALS_DIRECTORY")
192try:
193 ok = bool(cred) and open(os.path.join(cred, "probe-secret")).read().strip() == "s3cret-probe"
194except OSError:
195 ok = False
196report("ImportCredential", ok, str(cred))
197
198n_open = sum(1 for _, c in results if not c)
199print(f"PROBE {'CONFINED' if n_open == 0 else 'OPEN'} checks={len(results)} open={n_open}", flush=True)