@capybara-hq/plugin-sdk 0.1.0-rc.26 → 0.1.0-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/agent-docs/extension-points/model-provider.md +1 -1
  2. package/dist/cards.d.ts +17 -8
  3. package/dist/cards.js +21 -10
  4. package/dist/channel.d.ts +91 -47
  5. package/dist/channel.js +10 -5
  6. package/dist/connector-auth.d.ts +5 -2
  7. package/dist/connector-auth.js +14 -8
  8. package/dist/connector.d.ts +67 -32
  9. package/dist/ctx.d.ts +41 -23
  10. package/dist/define-extension.d.ts +21 -11
  11. package/dist/define-extension.js +10 -4
  12. package/dist/device-protocol.d.ts +2 -1
  13. package/dist/extension-point.js +1 -1
  14. package/dist/identity.d.ts +22 -9
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/model-params.d.ts +41 -22
  18. package/dist/model-params.js +28 -15
  19. package/dist/model.d.ts +96 -64
  20. package/dist/model.js +25 -14
  21. package/dist/permissions.d.ts +6 -6
  22. package/dist/permissions.js +8 -32
  23. package/dist/plugin-package.d.ts +79 -38
  24. package/dist/plugin-package.js +57 -29
  25. package/dist/sandbox-linux-runtime-source.d.ts +15 -0
  26. package/dist/sandbox-linux-runtime-source.js +1421 -0
  27. package/dist/sandbox-runtime-source.d.ts +9 -3
  28. package/dist/sandbox-runtime-source.js +16 -4
  29. package/dist/sandbox.d.ts +4 -1
  30. package/dist/sandbox.js +7 -3
  31. package/dist/secret.d.ts +4 -1
  32. package/dist/secret.js +4 -1
  33. package/dist/setup-guide.d.ts +1 -1
  34. package/dist/setup-guide.js +1 -1
  35. package/dist/skill.d.ts +27 -17
  36. package/dist/skill.js +39 -25
  37. package/dist/storage.d.ts +45 -25
  38. package/dist/tool.d.ts +51 -23
  39. package/dist/tool.js +21 -9
  40. package/dist/ui-resolve.d.ts +2 -7
  41. package/dist/ui-resolve.js +7 -19
  42. package/dist/ui-slots.d.ts +1 -3
  43. package/dist/ui-slots.js +0 -9
  44. package/dist/ui.d.ts +63 -49
  45. package/dist/ui.js +36 -22
  46. package/dist/url.d.ts +4 -1
  47. package/dist/url.js +4 -1
  48. package/package.json +1 -1
@@ -0,0 +1,1421 @@
1
+ /**
2
+ * Private Python 3 restricted Linux launcher and syscall broker (`linux-sandbox.py`), staged
3
+ * beside `native-files.py` by a trusted consumer that verifies both digests.
4
+ *
5
+ * Transport: `python3 -I linux-sandbox.py probe` prints the capability report. Otherwise one JSON
6
+ * request on stdin: `{mode: "exec" | "native", roots: {read, write: [{path, fd, dev, ino}]},
7
+ * network: {kind: "none" | "environment"} | {kind: "endpoints", endpoints: [{address, port}]},
8
+ * reportFd, cwd?, env?, argv (exec), timeoutMs? (exec), native (native-files request)}`.
9
+ * Root descriptors are pinned once by the consumer and inherited; the launcher verifies their
10
+ * identity and never reopens a root pathname. Landlock rules, broker metadata checks and the
11
+ * native helper all use those same descriptors. JSON events (`launch`, `exit`, `refused`) go to
12
+ * reportFd, which the restricted child cannot write. SIGTERM cancels the whole owned tree.
13
+ * Full access never uses this launcher: it has no restricted filters.
14
+ */
15
+ export const LINUX_SANDBOX_SOURCE = String.raw `import ctypes
16
+ import errno
17
+ import importlib.util
18
+ import ipaddress
19
+ import json
20
+ import os
21
+ import platform
22
+ import select
23
+ import signal
24
+ import socket
25
+ import stat
26
+ import struct
27
+ import sys
28
+ import threading
29
+ import time
30
+
31
+ # Restricted Linux launcher and syscall broker. The trusted consumer pins every granted root once
32
+ # (an inherited directory descriptor plus its device/inode identity) and passes it here. Landlock
33
+ # rules, the broker's metadata checks and the native-file helper all use exactly those
34
+ # descriptors; root pathnames are never reopened. Anything unsupported reports unavailable.
35
+ #
36
+ # Documented behaviour of restricted execution:
37
+ # - Metadata reads outside the roots are not mediated: stat/statx, access, readlink, getxattr,
38
+ # listxattr, statfs, inotify marks and other processes' /proc cmdline can reveal names, sizes,
39
+ # times, link targets and xattr values. File contents, writes and metadata changes are confined.
40
+ # - Known limitation: /proc stays a read root, so a restricted command can read the world-readable
41
+ # entries of other processes of the same uid, including /proc/<pid>/cmdline of a concurrent Full
42
+ # command (secrets inlined in a command line are visible). Ptrace-guarded entries (environ, mem,
43
+ # maps, fd) stay closed by Landlock's ptrace scoping. Landlock cannot narrow /proc to the
44
+ # command's own tree: /proc/self resolves to per-process directories that exist only after the
45
+ # rules are set, so dropping /proc (keeping cpuinfo, meminfo, stat and the like) also denies a
46
+ # process its own /proc/self, which ordinary tools need (Node's process.memoryUsage(), Python's
47
+ # /proc/self/fd and /proc/self/maps reads). hidepid needs a mount and PID namespaces need new
48
+ # privileges, both outside this launcher's design. Consumers keep secrets out of command lines.
49
+ # - Network none/allowlist: TCP sockets may bind and listen on loopback (127.0.0.1, ::1) only;
50
+ # connections go only to the endpoints the consumer granted. Environment lifts that filter.
51
+ # - UNIX sockets in every network kind: stream/seqpacket only (datagram and raw are refused);
52
+ # pathname connect/bind only to sockets inside the write roots, resolved through the pinned
53
+ # descriptors; abstract and unnamed addresses are refused. socketpair() is unaffected.
54
+ # - The launcher creates one closed session (setsid is denied inside it) and reports it in a
55
+ # "session" event; if the supervisor is lost, the consumer runs "reap" with that event to end
56
+ # every owned process. Brokered calls fail (ENOSYS) once the broker is gone.
57
+ #
58
+ # Architecture validation: an architecture reports restricted support only when it is listed in
59
+ # VALIDATED_ARCHES, which an evidence commit changes after the real-kernel conformance suite
60
+ # passed on that architecture (the commit cites the run). Until then a consumer may pass
61
+ # "candidateArch" (probe --candidate-arch) to run the reviewed table for evidence collection
62
+ # only; production consumers never set it.
63
+
64
+ LANDLOCK_ABI_REQUIRED = 6
65
+ # aarch64: Docker 29.9.3 on Linux 7.0.14-linuxkit (Landlock ABI 8), reviewed conformance runs.
66
+ # x86_64: GitHub Actions run 43906202355 on Linux 7.0.0-1019-azure, LSM list with landlock,
67
+ # Docker builtin seccomp, image capybara-sandbox@sha256:0473fbbc... amd64: 19 passed, 1 guard
68
+ # skipped, with CAPYBARA_TEST_REQUIRE_LINUX_RESTRICTED=1 (no mechanism test skipped).
69
+ VALIDATED_ARCHES = ("aarch64", "x86_64")
70
+ # Every syscall above this number (newer than the reviewed inventory) fails with ENOSYS.
71
+ MAX_KNOWN_SYSCALL = 469
72
+
73
+ ARCHES = {
74
+ "aarch64": {
75
+ "audit": 0xC00000B7,
76
+ "seccomp": 277,
77
+ "nr": {
78
+ "setxattr": 5, "lsetxattr": 6, "fsetxattr": 7, "removexattr": 14,
79
+ "lremovexattr": 15, "fremovexattr": 16, "ioctl": 29, "fchmod": 52, "fchmodat": 53,
80
+ "fchownat": 54, "fchown": 55, "utimensat": 88, "unshare": 97, "setsid": 157,
81
+ "socket": 198, "socketpair": 199, "bind": 200, "listen": 201, "connect": 203, "sendto": 206,
82
+ "sendmsg": 211, "add_key": 217, "request_key": 218, "keyctl": 219, "clone": 220,
83
+ "setns": 268, "sendmmsg": 269, "userfaultfd": 282,
84
+ },
85
+ },
86
+ "x86_64": {
87
+ "audit": 0xC000003E,
88
+ "seccomp": 317,
89
+ "x32": True,
90
+ "nr": {
91
+ "ioctl": 16, "socket": 41, "connect": 42, "sendto": 44, "sendmsg": 46, "bind": 49,
92
+ "listen": 50, "socketpair": 53, "clone": 56, "chmod": 90, "fchmod": 91, "chown": 92, "fchown": 93,
93
+ "lchown": 94, "setsid": 112, "utime": 132, "uselib": 134, "setxattr": 188,
94
+ "lsetxattr": 189, "fsetxattr": 190, "removexattr": 197, "lremovexattr": 198,
95
+ "fremovexattr": 199, "utimes": 235, "add_key": 248, "request_key": 249,
96
+ "keyctl": 250, "fchownat": 260, "futimesat": 261, "fchmodat": 268, "unshare": 272,
97
+ "utimensat": 280, "sendmmsg": 307, "setns": 308, "userfaultfd": 323,
98
+ },
99
+ },
100
+ }
101
+ COMMON = {"io_uring_setup": 425, "io_uring_enter": 426, "io_uring_register": 427,
102
+ "clone3": 435, "fchmodat2": 452, "setxattrat": 463, "removexattrat": 466,
103
+ "file_setattr": 469}
104
+ NR_CLOSE_RANGE = 436
105
+ # CLONE_NEWNS | NEWCGROUP | NEWUTS | NEWIPC | NEWUSER | NEWPID | NEWNET | NEWTIME
106
+ NAMESPACE_FLAGS = 0x7E020080
107
+ NR_PIDFD_OPEN = 434
108
+ NR_PIDFD_SEND_SIGNAL = 424
109
+ NR_LANDLOCK_CREATE = 444
110
+ NR_LANDLOCK_ADD = 445
111
+ NR_LANDLOCK_RESTRICT = 446
112
+
113
+ FS_EXECUTE, FS_WRITE_FILE, FS_READ_FILE, FS_READ_DIR = 1, 2, 4, 8
114
+ FS_TRUNCATE, FS_IOCTL_DEV = 1 << 14, 1 << 15
115
+ FS_ALL = (1 << 16) - 1
116
+ FS_READ = FS_EXECUTE | FS_READ_FILE | FS_READ_DIR
117
+ FS_DEVICE = FS_READ_FILE | FS_WRITE_FILE | FS_TRUNCATE | FS_IOCTL_DEV
118
+ NET_CONNECT_TCP = 2
119
+ # LANDLOCK_ACCESS_NET_BIND_TCP | CONNECT_TCP: only the broker binds or connects TCP sockets.
120
+ NET_MEDIATED = 1 | 2
121
+ SCOPE_ALL = 1 | 2 # abstract UNIX sockets and signals stay inside the domain
122
+ DEFAULT_SYSTEM_ROOTS = ("/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc", "/proc")
123
+ DEVICE_FILES = ("/dev/null", "/dev/zero", "/dev/full", "/dev/random", "/dev/urandom", "/dev/tty")
124
+
125
+ RET_ALLOW, RET_NOTIFY, RET_KILL = 0x7FFF0000, 0x7FC00000, 0x80000000
126
+ def RET_ERRNO(code):
127
+ return 0x00050000 | code
128
+
129
+ # File-attribute, encryption-policy and terminal-injection ioctls that mutate an object the
130
+ # descriptor may only read. Landlock's IOCTL_DEV right does not cover regular files.
131
+ DENIED_IOCTLS = (0x5412, 0x541C, 0x40086602, 0x40046602, 0x401C5820, 0x40087602, 0x40047602,
132
+ 0x800C6613, 0xC0406618, 0xC0186619, 0xC040661A)
133
+ MSG_FASTOPEN = 0x20000000
134
+ # Linux socket ABI values (identical on every architecture this launcher knows).
135
+ AF_UNSPEC, AF_UNIX, AF_INET, AF_INET6, AF_NETLINK = 0, 1, 2, 10, 16
136
+ SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET = 1, 2, 5
137
+ SOCK_NONBLOCK, SOCK_CLOEXEC = 0o4000, 0o2000000
138
+ SOL_SOCKET, SO_DOMAIN, IPPROTO_TCP = 1, 39, 6
139
+ AT_FDCWD = -100
140
+ AT_SYMLINK_NOFOLLOW = 0x100
141
+ AT_EMPTY_PATH = 0x1000
142
+ NOTIF_RECV, NOTIF_SEND, NOTIF_ID_VALID, NOTIF_ADDFD = 0xC0502100, 0xC0182101, 0x40082102, 0x40182103
143
+ ADDFD_SEND = 2
144
+
145
+ libc = ctypes.CDLL(None, use_errno=True)
146
+ libc.syscall.restype = ctypes.c_long
147
+ libc.ioctl.restype = ctypes.c_int
148
+ libc.ioctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_void_p)
149
+
150
+
151
+ class Refused(Exception):
152
+ def __init__(self, code, message):
153
+ super().__init__(message)
154
+ self.code = code
155
+
156
+
157
+ def syscall(nr, *args):
158
+ result = libc.syscall(ctypes.c_long(nr), *[ctypes.c_long(a) if isinstance(a, int) else a
159
+ for a in args])
160
+ if result < 0:
161
+ code = ctypes.get_errno()
162
+ raise OSError(code, os.strerror(code))
163
+ return result
164
+
165
+
166
+ def ioctl(fd, request, buffer):
167
+ if libc.ioctl(fd, request, buffer) < 0:
168
+ code = ctypes.get_errno()
169
+ raise OSError(code, os.strerror(code))
170
+
171
+
172
+ def load_native():
173
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "native-files.py")
174
+ spec = importlib.util.spec_from_file_location("capybara_native_files", path)
175
+ module = importlib.util.module_from_spec(spec)
176
+ spec.loader.exec_module(module)
177
+ return module, path
178
+
179
+
180
+ def arch():
181
+ machine = platform.machine()
182
+ return machine, ARCHES.get(machine)
183
+
184
+
185
+ def landlock_abi():
186
+ value = libc.syscall(ctypes.c_long(NR_LANDLOCK_CREATE), None, ctypes.c_long(0),
187
+ ctypes.c_long(1))
188
+ return value if value > 0 else 0
189
+
190
+
191
+ # ---- seccomp filter -----------------------------------------------------------------------
192
+
193
+ class Program:
194
+ def __init__(self):
195
+ self.code = []
196
+ self.labels = {}
197
+
198
+ def label(self, name):
199
+ self.labels[name] = len(self.code)
200
+
201
+ def ld(self, offset):
202
+ self.code.append((0x20, 0, 0, offset))
203
+
204
+ def ld_nr(self):
205
+ self.ld(0)
206
+
207
+ def ld_arg(self, index):
208
+ self.ld(16 + 8 * index)
209
+
210
+ def ret(self, value):
211
+ self.code.append((0x06, 0, 0, value))
212
+
213
+ def alu_and(self, value):
214
+ self.code.append((0x54, 0, 0, value))
215
+
216
+ def jump(self, op, value, true, false=None):
217
+ self.code.append((op, true, false, value))
218
+
219
+ def jeq(self, value, true, false=None):
220
+ self.jump(0x15, value, true, false)
221
+
222
+ def jgt(self, value, true, false=None):
223
+ self.jump(0x25, value, true, false)
224
+
225
+ def jge(self, value, true, false=None):
226
+ self.jump(0x35, value, true, false)
227
+
228
+ def jset(self, value, true, false=None):
229
+ self.jump(0x45, value, true, false)
230
+
231
+ def assemble(self):
232
+ out = bytearray()
233
+ for index, (code, true, false, value) in enumerate(self.code):
234
+ def target(name):
235
+ if name is None:
236
+ return 0
237
+ offset = self.labels[name] - index - 1
238
+ if not 0 <= offset <= 255:
239
+ raise ValueError("seccomp jump out of range")
240
+ return offset
241
+ if code & 0x07 == 0x05:
242
+ out += struct.pack("HBBI", code, target(true), target(false), value)
243
+ else:
244
+ out += struct.pack("HBBI", code, 0, 0, value)
245
+ return bytes(out)
246
+
247
+
248
+ def build_filter(table, network_mediated, brokered):
249
+ """The restricted child's filter. Brokered calls go to the supervisor (EACCES without one)."""
250
+ nr = dict(table["nr"], **COMMON)
251
+ notify = RET_NOTIFY if brokered else RET_ERRNO(errno.EACCES)
252
+ p = Program()
253
+ p.ld(4)
254
+ p.jeq(table["audit"], "arch_ok")
255
+ p.ret(RET_KILL)
256
+ p.label("arch_ok")
257
+ p.ld_nr()
258
+ if table.get("x32"):
259
+ p.jge(0x40000000, "enosys")
260
+ p.jgt(MAX_KNOWN_SYSCALL, "enosys")
261
+ simple = {}
262
+ for name in ("io_uring_setup", "io_uring_enter", "io_uring_register", "userfaultfd",
263
+ "setxattrat", "removexattrat", "file_setattr", "utime", "utimes", "futimesat",
264
+ "uselib", "clone3"):
265
+ if name in nr:
266
+ simple[nr[name]] = RET_ERRNO(errno.ENOSYS)
267
+ # Sessions, keyrings and namespaces stay the launcher's; Landlock does not cover keyrings.
268
+ for name in ("setsid", "keyctl", "add_key", "request_key", "setns"):
269
+ simple[nr[name]] = RET_ERRNO(errno.EPERM)
270
+ for name in ("chmod", "fchmod", "fchmodat", "fchmodat2", "chown", "fchown", "lchown",
271
+ "fchownat", "utimensat", "setxattr", "lsetxattr", "fsetxattr", "removexattr",
272
+ "lremovexattr", "fremovexattr", "connect", "listen"):
273
+ if name in nr:
274
+ simple[nr[name]] = notify
275
+ if network_mediated:
276
+ simple[nr["bind"]] = notify
277
+ for number in simple:
278
+ p.jeq(number, "r%d" % number)
279
+ p.jeq(nr["ioctl"], "ioctl")
280
+ p.jeq(nr["socket"], "socket")
281
+ p.jeq(nr["socketpair"], "socketpair")
282
+ p.jeq(nr["unshare"], "namespaces")
283
+ p.jeq(nr["clone"], "namespaces")
284
+ if network_mediated:
285
+ p.jeq(nr["sendto"], "fastopen3")
286
+ p.jeq(nr["sendmmsg"], "fastopen3")
287
+ p.jeq(nr["sendmsg"], "fastopen2")
288
+ p.ret(RET_ALLOW)
289
+ for number, action in simple.items():
290
+ p.label("r%d" % number)
291
+ p.ret(action)
292
+ p.label("enosys")
293
+ p.ret(RET_ERRNO(errno.ENOSYS))
294
+ p.label("ioctl")
295
+ p.ld_arg(1)
296
+ for request in DENIED_IOCTLS:
297
+ p.jeq(request, "eperm")
298
+ p.ret(RET_ALLOW)
299
+ p.label("namespaces")
300
+ p.ld_arg(0)
301
+ p.jset(NAMESPACE_FLAGS, "eperm")
302
+ p.ret(RET_ALLOW)
303
+ p.label("eperm")
304
+ p.ret(RET_ERRNO(errno.EPERM))
305
+ p.label("socket")
306
+ p.ld_arg(0)
307
+ p.jeq(AF_UNIX, "unix")
308
+ p.jeq(AF_NETLINK, "netlink")
309
+ p.jeq(AF_INET, "inet")
310
+ p.jeq(AF_INET6, "inet")
311
+ p.ret(RET_ERRNO(errno.EAFNOSUPPORT))
312
+ p.label("netlink")
313
+ p.ld_arg(2)
314
+ p.jeq(0, "allow") # NETLINK_ROUTE only: interface queries, no egress
315
+ p.ret(RET_ERRNO(errno.EACCES))
316
+ p.label("socketpair")
317
+ # A datagram socketpair honours an explicit sendto() address: connection-oriented only.
318
+ p.ld_arg(0)
319
+ p.jeq(AF_UNIX, "pair_unix")
320
+ p.ret(RET_ERRNO(errno.EACCES))
321
+ p.label("pair_unix")
322
+ p.ld_arg(1)
323
+ p.alu_and(0xF)
324
+ p.jeq(SOCK_STREAM, "allow")
325
+ p.jeq(SOCK_SEQPACKET, "allow")
326
+ p.ret(RET_ERRNO(errno.EACCES))
327
+ p.label("unix")
328
+ # Connection-oriented UNIX sockets only, created by the broker so it can mediate their
329
+ # pathname connect/bind; datagram and raw (which the kernel maps to datagram) are refused.
330
+ p.ld_arg(1)
331
+ p.alu_and(0xF)
332
+ p.jeq(SOCK_STREAM, "inet")
333
+ p.jeq(SOCK_SEQPACKET, "inet")
334
+ p.ret(RET_ERRNO(errno.EACCES))
335
+ p.label("inet")
336
+ p.ret(notify)
337
+ if network_mediated:
338
+ p.label("fastopen3")
339
+ p.ld_arg(3)
340
+ p.jset(MSG_FASTOPEN, "eacces")
341
+ p.ret(RET_ALLOW)
342
+ p.label("fastopen2")
343
+ p.ld_arg(2)
344
+ p.jset(MSG_FASTOPEN, "eacces")
345
+ p.ret(RET_ALLOW)
346
+ p.label("eacces")
347
+ p.ret(RET_ERRNO(errno.EACCES))
348
+ p.label("allow")
349
+ p.ret(RET_ALLOW)
350
+ return p.assemble()
351
+
352
+
353
+ def install_filter(table, program, listener):
354
+ buffer = ctypes.create_string_buffer(program, len(program))
355
+ fprog = struct.pack("HxxxxxxQ", len(program) // 8, ctypes.addressof(buffer))
356
+ fprog_buffer = ctypes.create_string_buffer(fprog, len(fprog))
357
+ flags = 8 if listener else 0 # SECCOMP_FILTER_FLAG_NEW_LISTENER
358
+ return syscall(table["seccomp"], 1, flags, fprog_buffer)
359
+
360
+
361
+ # ---- roots and Landlock -------------------------------------------------------------------
362
+
363
+ def verify_roots(native, request):
364
+ """Validates pinned descriptors against their recorded identity without reopening paths."""
365
+ result = {"read": [], "write": []}
366
+ seen = []
367
+ for kind in ("read", "write"):
368
+ for entry in request.get("roots", {}).get(kind, []):
369
+ path, fd = entry.get("path"), entry.get("fd")
370
+ if not isinstance(path, str) or type(fd) is not int or not native.valid_path(path) \
371
+ or os.path.normpath(path) != path:
372
+ raise Refused("INVALID_REQUEST", "Supply canonical roots with pinned descriptors")
373
+ try:
374
+ info = os.fstat(fd)
375
+ where = os.readlink("/proc/self/fd/%d" % fd)
376
+ except OSError:
377
+ raise Refused("ROOT_CHANGED", "A pinned root descriptor is not available")
378
+ identity = [entry.get("dev"), entry.get("ino")]
379
+ if not stat.S_ISDIR(info.st_mode) or identity != [info.st_dev, info.st_ino] \
380
+ or where != path:
381
+ raise Refused("ROOT_CHANGED", "A pinned root no longer names its recorded object")
382
+ os.set_inheritable(fd, False)
383
+ result[kind].append({"path": path, "fd": fd})
384
+ seen.append({"kind": kind, "path": path, "fd": fd, "dev": info.st_dev,
385
+ "ino": info.st_ino})
386
+ if not result["write"]:
387
+ raise Refused("INVALID_REQUEST", "Restricted execution needs at least one write root")
388
+ return result, seen
389
+
390
+
391
+ def landlock_ruleset(roots, system_roots, network_mediated):
392
+ attr = struct.pack("QQQ", FS_ALL, NET_MEDIATED if network_mediated else 0, SCOPE_ALL)
393
+ attr_buffer = ctypes.create_string_buffer(attr, len(attr))
394
+ ruleset = syscall(NR_LANDLOCK_CREATE, attr_buffer, len(attr), 0)
395
+ os.set_inheritable(ruleset, False)
396
+
397
+ def rule(fd, access):
398
+ data = struct.pack("<Qi", access, fd)
399
+ syscall(NR_LANDLOCK_ADD, ruleset, 1, ctypes.create_string_buffer(data, len(data)), 0)
400
+
401
+ # The rules use the caller's pinned descriptors themselves.
402
+ for root in roots["read"]:
403
+ rule(root["fd"], FS_READ)
404
+ for root in roots["write"]:
405
+ rule(root["fd"], FS_ALL)
406
+ opened = []
407
+ try:
408
+ for path in system_roots:
409
+ try:
410
+ fd = os.open(path, os.O_PATH | os.O_CLOEXEC)
411
+ except FileNotFoundError:
412
+ continue
413
+ opened.append(fd)
414
+ rule(fd, FS_READ if stat.S_ISDIR(os.fstat(fd).st_mode) else FS_READ & ~FS_READ_DIR)
415
+ for path in DEVICE_FILES:
416
+ try:
417
+ fd = os.open(path, os.O_PATH | os.O_CLOEXEC)
418
+ except OSError:
419
+ continue
420
+ opened.append(fd)
421
+ if stat.S_ISCHR(os.fstat(fd).st_mode):
422
+ rule(fd, FS_DEVICE)
423
+ finally:
424
+ for fd in opened:
425
+ os.close(fd)
426
+ return ruleset
427
+
428
+
429
+ # ---- broker -------------------------------------------------------------------------------
430
+
431
+ class Denied(Exception):
432
+ pass
433
+
434
+
435
+ def socket_option(fd, level, name, size=4):
436
+ value = ctypes.create_string_buffer(size)
437
+ length = ctypes.c_uint32(size)
438
+ if libc.getsockopt(fd, level, name, value, ctypes.byref(length)) < 0:
439
+ code = ctypes.get_errno()
440
+ raise OSError(code, os.strerror(code))
441
+ return value.raw[:length.value]
442
+
443
+
444
+ def socket_domain(fd):
445
+ return struct.unpack("i", socket_option(fd, SOL_SOCKET, SO_DOMAIN))[0]
446
+
447
+
448
+ def socket_name(fd):
449
+ """The bound IP address of a broker-owned socket (0.0.0.0 / :: when unbound)."""
450
+ buffer = ctypes.create_string_buffer(128)
451
+ length = ctypes.c_uint32(128)
452
+ if libc.getsockname(fd, buffer, ctypes.byref(length)) < 0:
453
+ code = ctypes.get_errno()
454
+ raise OSError(code, os.strerror(code))
455
+ raw = buffer.raw[:length.value]
456
+ family = struct.unpack("H", raw[:2])[0]
457
+ if family == AF_INET:
458
+ return str(ipaddress.ip_address(raw[4:8]))
459
+ if family == AF_INET6:
460
+ return str(ipaddress.ip_address(raw[8:24]))
461
+ return None
462
+
463
+
464
+ class Broker:
465
+ def __init__(self, native, roots, table, endpoints, listener):
466
+ self.native = native
467
+ self.files = native.NativeFiles(roots)
468
+ self.names = {number: name for name, number in dict(table["nr"], **COMMON).items()}
469
+ self.endpoints = endpoints
470
+ self.listener = listener
471
+ self.sockets = {}
472
+ self.lock = threading.Lock()
473
+ self.counts = {}
474
+
475
+ # Target memory and descriptors are opened first and then checked with ID_VALID, so a
476
+ # recycled PID can never be read in place of the notifying task.
477
+ def valid(self, ident):
478
+ value = ctypes.c_uint64(ident)
479
+ try:
480
+ ioctl(self.listener, NOTIF_ID_VALID, ctypes.byref(value))
481
+ return True
482
+ except OSError:
483
+ return False
484
+
485
+ def memory(self, pid, ident):
486
+ fd = os.open("/proc/%d/mem" % pid, os.O_RDONLY | os.O_CLOEXEC)
487
+ if not self.valid(ident):
488
+ os.close(fd)
489
+ raise OSError(errno.ESRCH, "Target exited")
490
+ return fd
491
+
492
+ @staticmethod
493
+ def read(mem, address, size):
494
+ try:
495
+ data = os.pread(mem, size, address)
496
+ except OSError:
497
+ raise OSError(errno.EFAULT, "Bad address")
498
+ if len(data) != size:
499
+ raise OSError(errno.EFAULT, "Bad address")
500
+ return data
501
+
502
+ @staticmethod
503
+ def string(mem, address, limit=4096):
504
+ if address == 0:
505
+ raise OSError(errno.EFAULT, "Bad address")
506
+ out = bytearray()
507
+ while len(out) < limit:
508
+ chunk = 4096 - (address + len(out)) % 4096
509
+ try:
510
+ data = os.pread(mem, min(chunk, limit - len(out)), address + len(out))
511
+ except OSError:
512
+ raise OSError(errno.EFAULT, "Bad address")
513
+ if not data:
514
+ raise OSError(errno.EFAULT, "Bad address")
515
+ end = data.find(b"\0")
516
+ if end >= 0:
517
+ return bytes(out + data[:end])
518
+ out += data
519
+ raise OSError(errno.ENAMETOOLONG, "Path too long")
520
+
521
+ def target_link(self, pid, ident, name):
522
+ value = os.readlink("/proc/%d/%s" % (pid, name))
523
+ if not self.valid(ident):
524
+ raise OSError(errno.ESRCH, "Target exited")
525
+ return value
526
+
527
+ # Every mutation is applied to an O_PATH descriptor resolved from the pinned write roots by
528
+ # the native helper's own no-follow traversal, never to a string the target can change.
529
+ def resolve(self, path, follow):
530
+ if not path.startswith("/"):
531
+ raise Denied()
532
+ path = os.path.normpath(path)
533
+ try:
534
+ if follow:
535
+ parent, name, _, _ = self.files.resolve(path, True, False, 0, True)
536
+ else:
537
+ head, name = os.path.split(path)
538
+ if not name:
539
+ parent, name, _, _ = self.files.resolve(path, True, False, 0, True)
540
+ else:
541
+ dparent, dname, _, _ = self.files.resolve(head, True, False, 0, True)
542
+ try:
543
+ parent = os.open(dname, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
544
+ | os.O_CLOEXEC, dir_fd=dparent)
545
+ finally:
546
+ os.close(dparent)
547
+ except self.native.ScopeDenied:
548
+ raise Denied()
549
+ except ValueError:
550
+ raise Denied()
551
+ try:
552
+ return os.open(name, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent)
553
+ finally:
554
+ os.close(parent)
555
+
556
+ def in_scope(self, obj):
557
+ where = os.readlink("/proc/self/fd/%d" % obj)
558
+ if not where.startswith("/") or where.endswith(" (deleted)"):
559
+ raise Denied()
560
+ candidate = self.resolve(where, False)
561
+ try:
562
+ a, b = os.fstat(obj), os.fstat(candidate)
563
+ finally:
564
+ os.close(candidate)
565
+ if (a.st_dev, a.st_ino) != (b.st_dev, b.st_ino):
566
+ raise Denied()
567
+
568
+ def object(self, pid, ident, mem, dirfd, address, flags, follow_default=True):
569
+ dirfd = ctypes.c_int32(dirfd & 0xFFFFFFFF).value
570
+ follow = follow_default and not (flags & AT_SYMLINK_NOFOLLOW)
571
+ path = None if address == 0 else os.fsdecode(self.string(mem, address))
572
+ if path is None or (path == "" and flags & AT_EMPTY_PATH):
573
+ if dirfd == AT_FDCWD:
574
+ link = "cwd"
575
+ elif dirfd >= 0:
576
+ link = "fd/%d" % dirfd
577
+ else:
578
+ raise OSError(errno.EBADF, "Bad descriptor")
579
+ obj = os.open("/proc/%d/%s" % (pid, link), os.O_PATH | os.O_CLOEXEC)
580
+ if not self.valid(ident):
581
+ os.close(obj)
582
+ raise OSError(errno.ESRCH, "Target exited")
583
+ try:
584
+ self.in_scope(obj)
585
+ except BaseException:
586
+ os.close(obj)
587
+ raise
588
+ return obj
589
+ if path == "":
590
+ raise OSError(errno.ENOENT, "Empty path")
591
+ if not path.startswith("/"):
592
+ if dirfd == AT_FDCWD:
593
+ base = self.target_link(pid, ident, "cwd")
594
+ elif dirfd >= 0:
595
+ base = self.target_link(pid, ident, "fd/%d" % dirfd)
596
+ else:
597
+ raise OSError(errno.EBADF, "Bad descriptor")
598
+ if not base.startswith("/") or base.endswith(" (deleted)"):
599
+ raise Denied()
600
+ path = base.rstrip("/") + "/" + path
601
+ return self.resolve(path, follow)
602
+
603
+ def apply_path(self, obj, op):
604
+ return op("/proc/self/fd/%d" % obj)
605
+
606
+ def handle(self, ident, pid, nr, args):
607
+ name = self.names.get(nr)
608
+ with self.lock:
609
+ self.counts[name] = self.counts.get(name, 0) + 1
610
+ mem = None
611
+ try:
612
+ if name == "socket":
613
+ return self.socket(ident, args)
614
+ if name == "listen":
615
+ return self.listen(ident, pid, args)
616
+ mem = self.memory(pid, ident)
617
+ if name == "connect":
618
+ return self.connect(ident, pid, mem, args)
619
+ if name == "bind":
620
+ return self.bind(ident, pid, mem, args)
621
+ return self.metadata(ident, pid, mem, name, args)
622
+ except Denied:
623
+ return None, errno.EACCES
624
+ except OSError as error:
625
+ return None, error.errno or errno.EACCES
626
+ finally:
627
+ if mem is not None:
628
+ os.close(mem)
629
+
630
+ def metadata(self, ident, pid, mem, name, args):
631
+ if name in ("chmod", "fchmodat", "fchmodat2", "fchmod"):
632
+ if name == "chmod":
633
+ dirfd, address, mode, flags = AT_FDCWD, args[0], args[1], 0
634
+ elif name == "fchmod":
635
+ dirfd, address, mode, flags = args[0], 0, args[1], AT_EMPTY_PATH
636
+ else:
637
+ dirfd, address, mode = args[0], args[1], args[2]
638
+ flags = args[3] if name == "fchmodat2" else 0
639
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
640
+ return None, errno.EINVAL
641
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
642
+ try:
643
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
644
+ return None, errno.EOPNOTSUPP
645
+ self.apply_path(obj, lambda p: os.chmod(p, mode & 0o7777))
646
+ finally:
647
+ os.close(obj)
648
+ return 0, 0
649
+ if name in ("chown", "lchown", "fchownat", "fchown"):
650
+ if name in ("chown", "lchown"):
651
+ dirfd, address, owner, group = AT_FDCWD, args[0], args[1], args[2]
652
+ flags = AT_SYMLINK_NOFOLLOW if name == "lchown" else 0
653
+ elif name == "fchown":
654
+ dirfd, address, owner, group, flags = args[0], 0, args[1], args[2], AT_EMPTY_PATH
655
+ else:
656
+ dirfd, address, owner, group, flags = args[:5]
657
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
658
+ return None, errno.EINVAL
659
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
660
+ try:
661
+ if libc.fchownat(obj, b"", ctypes.c_uint32(owner & 0xFFFFFFFF),
662
+ ctypes.c_uint32(group & 0xFFFFFFFF), AT_EMPTY_PATH) < 0:
663
+ return None, ctypes.get_errno()
664
+ finally:
665
+ os.close(obj)
666
+ return 0, 0
667
+ if name == "utimensat":
668
+ dirfd, address, times, flags = args[0], args[1], args[2], args[3]
669
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
670
+ return None, errno.EINVAL
671
+ value = None if times == 0 else self.read(mem, times, 32)
672
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
673
+ try:
674
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
675
+ return None, errno.EOPNOTSUPP
676
+ buffer = None if value is None else ctypes.create_string_buffer(value, 32)
677
+ if libc.utimensat(AT_FDCWD, os.fsencode("/proc/self/fd/%d" % obj), buffer, 0) < 0:
678
+ return None, ctypes.get_errno()
679
+ finally:
680
+ os.close(obj)
681
+ return 0, 0
682
+ if name in ("setxattr", "lsetxattr", "fsetxattr", "removexattr", "lremovexattr",
683
+ "fremovexattr"):
684
+ fd_based = name.startswith("f")
685
+ nofollow = name.startswith("l")
686
+ address = 0 if fd_based else args[0]
687
+ dirfd = args[0] if fd_based else AT_FDCWD
688
+ flags = AT_EMPTY_PATH if fd_based else (AT_SYMLINK_NOFOLLOW if nofollow else 0)
689
+ attribute = self.string(mem, args[1], 256)
690
+ if name.endswith("setxattr"):
691
+ size = args[3]
692
+ if size > 65536:
693
+ return None, errno.E2BIG
694
+ value = self.read(mem, args[2], size) if size else b""
695
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
696
+ try:
697
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
698
+ return None, errno.EPERM
699
+ target = "/proc/self/fd/%d" % obj
700
+ if name.endswith("setxattr"):
701
+ os.setxattr(target, attribute, value, args[4] & 0xFFFFFFFF)
702
+ else:
703
+ os.removexattr(target, attribute)
704
+ finally:
705
+ os.close(obj)
706
+ return 0, 0
707
+ return None, errno.ENOSYS
708
+
709
+ def socket(self, ident, args):
710
+ domain = args[0] & 0xFFFFFFFF
711
+ kind = args[1] & 0xFFFFFFFF
712
+ protocol = args[2] & 0xFFFFFFFF
713
+ base = kind & 0xF
714
+ if kind & ~(0xF | SOCK_NONBLOCK | SOCK_CLOEXEC):
715
+ return None, errno.EINVAL
716
+ if domain == AF_UNIX:
717
+ if base not in (SOCK_STREAM, SOCK_SEQPACKET) or protocol != 0:
718
+ return None, errno.EACCES
719
+ elif domain in (AF_INET, AF_INET6):
720
+ if self.endpoints is not None and (
721
+ base != SOCK_STREAM or protocol not in (0, IPPROTO_TCP)):
722
+ return None, errno.EACCES
723
+ else:
724
+ return None, errno.EAFNOSUPPORT
725
+ # The broker creates and keeps the original socket so a later connect/bind is performed
726
+ # on an object it owns, with an address it copied; the target receives an alias.
727
+ fd = libc.socket(domain, base | (kind & SOCK_NONBLOCK), protocol)
728
+ if fd < 0:
729
+ return None, ctypes.get_errno()
730
+ inode = os.fstat(fd).st_ino
731
+ # Record ownership before the alias exists: the target may connect the moment ADDFD
732
+ # completes its socket() call, possibly from another thread.
733
+ with self.lock:
734
+ self.sockets[inode] = fd
735
+ data = struct.pack("QIIII", ident, ADDFD_SEND, fd, 0,
736
+ os.O_CLOEXEC if kind & SOCK_CLOEXEC else 0)
737
+ buffer = ctypes.create_string_buffer(data, len(data))
738
+ if libc.ioctl(self.listener, NOTIF_ADDFD, buffer) < 0:
739
+ code = ctypes.get_errno()
740
+ self.release(inode)
741
+ return None, code
742
+ return "sent", 0
743
+
744
+ def owned(self, pid, ident, target_fd):
745
+ link = self.target_link(pid, ident, "fd/%d" % (target_fd & 0xFFFFFFFF))
746
+ if not link.startswith("socket:[") or not link.endswith("]"):
747
+ return None, None
748
+ inode = int(link[8:-1])
749
+ with self.lock:
750
+ return self.sockets.get(inode), inode
751
+
752
+ def release(self, inode):
753
+ with self.lock:
754
+ fd = self.sockets.pop(inode, None)
755
+ if fd is not None:
756
+ os.close(fd)
757
+
758
+ def unix_target(self, pid, ident, raw, create):
759
+ """A pathname UNIX address resolved from the pinned write roots, as a /proc path."""
760
+ name = raw[2:].split(b"\0", 1)[0]
761
+ if len(raw) <= 2 or raw[2:3] == b"\0" or not name:
762
+ raise Denied() # abstract and unnamed addresses stay inside nobody's grant
763
+ path = os.fsdecode(name)
764
+ if not path.startswith("/"):
765
+ base = self.target_link(pid, ident, "cwd")
766
+ if not base.startswith("/") or base.endswith(" (deleted)"):
767
+ raise Denied()
768
+ path = base.rstrip("/") + "/" + path
769
+ path = os.path.normpath(path)
770
+ if not create:
771
+ obj = self.resolve(path, True)
772
+ if not stat.S_ISSOCK(os.fstat(obj).st_mode):
773
+ os.close(obj)
774
+ raise OSError(errno.ECONNREFUSED, "Not a socket")
775
+ return obj, "/proc/self/fd/%d" % obj
776
+ try:
777
+ parent, final, _, _ = self.files.resolve(path, True, False, 0, False)
778
+ except (self.native.ScopeDenied, ValueError):
779
+ raise Denied()
780
+ return parent, "/proc/self/fd/%d/%s" % (parent, final)
781
+
782
+ @staticmethod
783
+ def unix_address(path):
784
+ encoded = os.fsencode(path)
785
+ if len(encoded) >= 108:
786
+ raise OSError(errno.ENAMETOOLONG, "Socket path too long")
787
+ address = struct.pack("H", AF_UNIX) + encoded + b"\0"
788
+ return ctypes.create_string_buffer(address, len(address)), len(address)
789
+
790
+ def inet_address(self, raw, size):
791
+ family = struct.unpack("H", raw[:2])[0]
792
+ if family == AF_INET and size >= 16:
793
+ return family, ipaddress.ip_address(raw[4:8]), struct.unpack(">H", raw[2:4])[0], 0
794
+ if family == AF_INET6 and size >= 28:
795
+ address = ipaddress.ip_address(raw[8:24])
796
+ scope = struct.unpack("I", raw[24:28])[0]
797
+ if address.ipv4_mapped:
798
+ return family, address.ipv4_mapped, struct.unpack(">H", raw[2:4])[0], 0
799
+ return family, address, struct.unpack(">H", raw[2:4])[0], scope
800
+ return family, None, None, None
801
+
802
+ def bind(self, ident, pid, mem, args):
803
+ size = args[2] & 0xFFFFFFFF
804
+ if size < 2 or size > 128:
805
+ return None, errno.EINVAL
806
+ raw = self.read(mem, args[1], size)
807
+ own, inode = self.owned(pid, ident, args[0])
808
+ if own is None:
809
+ return None, errno.EACCES if inode is not None else errno.ENOTSOCK
810
+ if socket_domain(own) == AF_UNIX:
811
+ handle, target = self.unix_target(pid, ident, raw, True)
812
+ try:
813
+ buffer, length = self.unix_address(target)
814
+ if libc.bind(own, buffer, ctypes.c_uint32(length)) < 0:
815
+ return None, ctypes.get_errno()
816
+ return 0, 0
817
+ finally:
818
+ os.close(handle)
819
+ _, address, _, _ = self.inet_address(raw, size)
820
+ # Restricted none/allowlist listens on loopback only (product decision).
821
+ if address is None or str(address) not in ("127.0.0.1", "::1"):
822
+ return None, errno.EACCES
823
+ copied = ctypes.create_string_buffer(raw, size)
824
+ if libc.bind(own, copied, ctypes.c_uint32(size)) < 0:
825
+ return None, ctypes.get_errno()
826
+ return 0, 0
827
+
828
+ def listen(self, ident, pid, args):
829
+ own, inode = self.owned(pid, ident, args[0])
830
+ if own is None:
831
+ # Broker ownership ends only with a successful connect, so an unowned socket is
832
+ # connected (or accepted, or a socketpair end): it cannot legitimately listen. Under
833
+ # none/allowlist refuse it; never let listen() autobind an unowned TCP socket to every
834
+ # interface. listen() carries no pointer, so CONTINUE is safe for environment.
835
+ if self.endpoints is not None:
836
+ return None, errno.EACCES
837
+ return "continue", 0
838
+ if self.endpoints is not None and socket_domain(own) != AF_UNIX:
839
+ # An unbound TCP socket would autobind to every interface on listen().
840
+ host = socket_name(own)
841
+ if host not in ("127.0.0.1", "::1"):
842
+ return None, errno.EACCES
843
+ result = libc.listen(own, ctypes.c_int(args[1] & 0xFFFFFFFF))
844
+ code = ctypes.get_errno() if result < 0 else 0
845
+ # A listening socket never connects; drop the broker's reference so close semantics
846
+ # remain the target's own.
847
+ self.release(inode)
848
+ return (None, code) if code else (0, 0)
849
+
850
+ def connect(self, ident, pid, mem, args):
851
+ size = args[2] & 0xFFFFFFFF
852
+ if size < 2 or size > 128:
853
+ return None, errno.EINVAL
854
+ raw = self.read(mem, args[1], size)
855
+ own, inode = self.owned(pid, ident, args[0])
856
+ if own is None:
857
+ return None, errno.EACCES if inode is not None else errno.ENOTSOCK
858
+ if socket_domain(own) == AF_UNIX:
859
+ handle, target = self.unix_target(pid, ident, raw, False)
860
+ try:
861
+ buffer, length = self.unix_address(target)
862
+ result = libc.connect(own, buffer, ctypes.c_uint32(length))
863
+ code = ctypes.get_errno() if result < 0 else 0
864
+ finally:
865
+ os.close(handle)
866
+ if code == 0:
867
+ self.release(inode)
868
+ return (None, code) if code else (0, 0)
869
+ family, address, port, scope = self.inet_address(raw, size)
870
+ if family != AF_UNSPEC: # AF_UNSPEC only dissolves an existing association
871
+ if address is None:
872
+ return None, errno.EACCES
873
+ if self.endpoints is not None and (str(address), port, scope) not in self.endpoints:
874
+ return None, errno.EACCES
875
+ # Connect with the broker's own copy of the checked address on the broker-owned object.
876
+ copied = ctypes.create_string_buffer(raw, size)
877
+ if libc.connect(own, copied, ctypes.c_uint32(size)) < 0:
878
+ code = ctypes.get_errno()
879
+ if code == errno.EINPROGRESS:
880
+ threading.Thread(target=self.settle, args=(own, inode), daemon=True).start()
881
+ # A refused or dissolved association keeps the broker's ownership: an unconnected
882
+ # unowned socket could otherwise listen() on every interface.
883
+ return None, code
884
+ if family != AF_UNSPEC:
885
+ self.release(inode)
886
+ return 0, 0
887
+
888
+ def settle(self, fd, inode):
889
+ poller = select.poll()
890
+ poller.register(fd, select.POLLOUT)
891
+ poller.poll()
892
+ if struct.unpack("i", socket_option(fd, SOL_SOCKET, 4))[0] == 0: # SO_ERROR
893
+ self.release(inode)
894
+
895
+ def respond(self, ident, value, code, flags=0):
896
+ data = struct.pack("QqiI", ident, value or 0, -code if code else 0, flags)
897
+ try:
898
+ ioctl(self.listener, NOTIF_SEND, ctypes.create_string_buffer(data, len(data)))
899
+ except OSError:
900
+ pass
901
+
902
+ def serve_one(self, ident, pid, nr, args):
903
+ try:
904
+ value, code = self.handle(ident, pid, nr, args)
905
+ except Exception:
906
+ value, code = None, errno.EACCES
907
+ if value == "continue":
908
+ self.respond(ident, 0, 0, 1) # SECCOMP_USER_NOTIF_FLAG_CONTINUE
909
+ elif value != "sent":
910
+ self.respond(ident, value, code)
911
+
912
+ def loop(self, stop):
913
+ poller = select.poll()
914
+ poller.register(self.listener, select.POLLIN)
915
+ poller.register(stop, select.POLLIN)
916
+ while True:
917
+ events = dict(poller.poll())
918
+ if stop in events:
919
+ return
920
+ event = events.get(self.listener, 0)
921
+ if event & select.POLLIN:
922
+ buffer = ctypes.create_string_buffer(80)
923
+ if libc.ioctl(self.listener, NOTIF_RECV, buffer) < 0:
924
+ continue
925
+ ident, pid, _, nr, _, _ = struct.unpack_from("QIIiIQ", buffer.raw)
926
+ args = struct.unpack_from("6Q", buffer.raw, 32)
927
+ threading.Thread(target=self.serve_one, args=(ident, pid, nr, args),
928
+ daemon=True).start()
929
+ elif event & (select.POLLHUP | select.POLLERR):
930
+ return
931
+
932
+ def close(self):
933
+ with self.lock:
934
+ fds = list(self.sockets.values())
935
+ self.sockets.clear()
936
+ for fd in fds:
937
+ os.close(fd)
938
+
939
+
940
+ # ---- supervision --------------------------------------------------------------------------
941
+
942
+ def descendants():
943
+ found = []
944
+ pending = [os.getpid()]
945
+ while pending:
946
+ pid = pending.pop()
947
+ try:
948
+ tasks = os.listdir("/proc/%d/task" % pid)
949
+ except OSError:
950
+ continue
951
+ for task in tasks:
952
+ try:
953
+ with open("/proc/%d/task/%s/children" % (pid, task)) as handle:
954
+ children = [int(value) for value in handle.read().split()]
955
+ except OSError:
956
+ continue
957
+ for child in children:
958
+ found.append((child, pid))
959
+ pending.append(child)
960
+ return found
961
+
962
+
963
+ def parent_of(pid):
964
+ with open("/proc/%d/stat" % pid) as handle:
965
+ data = handle.read()
966
+ return int(data[data.rindex(")") + 2:].split()[1])
967
+
968
+
969
+ def kill_tree():
970
+ """SIGKILLs every descendant by kernel parentage (the supervisor is their subreaper)."""
971
+ killed = set()
972
+ while True:
973
+ tree = descendants()
974
+ known = {os.getpid()} | {pid for pid, _ in tree}
975
+ for pid, _ in tree:
976
+ try:
977
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
978
+ except OSError:
979
+ continue
980
+ try:
981
+ # The pidfd pins the process; confirm it is still inside our tree before signalling.
982
+ if parent_of(pid) in known:
983
+ syscall(NR_PIDFD_SEND_SIGNAL, handle, signal.SIGKILL, None, 0)
984
+ killed.add(pid)
985
+ except OSError:
986
+ pass
987
+ finally:
988
+ os.close(handle)
989
+ try:
990
+ os.waitpid(-1, 0)
991
+ except ChildProcessError:
992
+ return len(killed)
993
+
994
+
995
+ class Report:
996
+ def __init__(self, fd):
997
+ self.fd = fd
998
+
999
+ def write(self, event):
1000
+ if self.fd is None:
1001
+ return
1002
+ data = (json.dumps(event) + "\n").encode()
1003
+ while data:
1004
+ data = data[os.write(self.fd, data):]
1005
+
1006
+
1007
+ def endpoints_of(network):
1008
+ kind = network.get("kind")
1009
+ if kind == "environment":
1010
+ return None
1011
+ if kind == "none":
1012
+ return set()
1013
+ if kind == "endpoints":
1014
+ allowed = set()
1015
+ for endpoint in network.get("endpoints", []):
1016
+ address = ipaddress.ip_address(endpoint["address"])
1017
+ port = endpoint["port"]
1018
+ scope = endpoint.get("scopeId", 0)
1019
+ if type(port) is not int or not 0 < port < 65536 or type(scope) is not int:
1020
+ raise Refused("INVALID_REQUEST", "Supply numeric endpoint ports and scope IDs")
1021
+ if address.version == 6 and address.ipv4_mapped:
1022
+ address, scope = address.ipv4_mapped, 0
1023
+ # A link-local IPv6 grant names one interface: the scope ID is part of the endpoint.
1024
+ allowed.add((str(address), port, scope if address.version == 6 else 0))
1025
+ return allowed
1026
+ raise Refused("INVALID_REQUEST", "Unknown network kind")
1027
+
1028
+
1029
+ def restrict_child(table, ruleset, network_mediated, brokered, channel):
1030
+ """Runs in the forked child before exec: session, Landlock, seccomp, listener hand-off."""
1031
+ if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS
1032
+ raise OSError(ctypes.get_errno(), "no_new_privs")
1033
+ syscall(NR_LANDLOCK_RESTRICT, ruleset, 0)
1034
+ listener = install_filter(table, build_filter(table, network_mediated, brokered), brokered)
1035
+ if brokered:
1036
+ socket.send_fds(channel, [b"L"], [listener])
1037
+ os.close(listener)
1038
+
1039
+
1040
+ def close_except(keep):
1041
+ """close_range() over every descriptor from 3 up except the kept ones."""
1042
+ low = 3
1043
+ for fd in sorted(set(fd for fd in keep if fd >= 3)):
1044
+ if fd > low:
1045
+ syscall(NR_CLOSE_RANGE, low, fd - 1, 0)
1046
+ low = fd + 1
1047
+ syscall(NR_CLOSE_RANGE, low, 0xFFFFFFFF, 0)
1048
+
1049
+
1050
+ class Cancellation:
1051
+ """SIGTERM/SIGINT handling installed (and the signals blocked) before any fork."""
1052
+
1053
+ def __init__(self):
1054
+ self.signals = []
1055
+ self.wake_r, self.wake_w = os.pipe()
1056
+ os.set_blocking(self.wake_w, False)
1057
+ signal.signal(signal.SIGTERM, self.cancel)
1058
+ signal.signal(signal.SIGINT, self.cancel)
1059
+
1060
+ def cancel(self, signum, _frame):
1061
+ self.signals.append(signum)
1062
+ try:
1063
+ os.write(self.wake_w, b"x")
1064
+ except OSError:
1065
+ pass
1066
+
1067
+
1068
+ CANCEL_SIGNALS = {signal.SIGTERM, signal.SIGINT}
1069
+
1070
+
1071
+ def start_time(pid):
1072
+ with open("/proc/%d/stat" % pid) as handle:
1073
+ data = handle.read()
1074
+ return int(data[data.rindex(")") + 2:].split()[19])
1075
+
1076
+
1077
+ def reap(session):
1078
+ """Consumer-side cleanup after a lost supervisor: SIGKILL the launcher's closed session.
1079
+
1080
+ The session ID is the restricted child's PID and setsid() is denied inside it, so membership
1081
+ is kernel-maintained and closed. Linux keeps a PID number reserved while it names a live
1082
+ session, so the session is ours while a process holding that PID still has the recorded start
1083
+ time, or no process holds it. Each member is pinned with a pidfd, then re-checked: still in the
1084
+ session, started no earlier than the leader, and the leader's PID not taken by another process
1085
+ since. A PID reuse within one scan can therefore only skip a process, never signal a stranger.
1086
+ """
1087
+ sid, started = int(session["sid"]), int(session["start"])
1088
+ killed = set()
1089
+
1090
+ def leader_reused():
1091
+ try:
1092
+ return start_time(sid) != started
1093
+ except OSError:
1094
+ return False # The leader exited; its PID stays reserved while members remain.
1095
+
1096
+ while True:
1097
+ if leader_reused():
1098
+ return len(killed)
1099
+ members = []
1100
+ for entry in os.listdir("/proc"):
1101
+ if not entry.isdigit():
1102
+ continue
1103
+ try:
1104
+ with open("/proc/%s/stat" % entry) as handle:
1105
+ data = handle.read()
1106
+ except OSError:
1107
+ continue
1108
+ fields = data[data.rindex(")") + 2:].split()
1109
+ # Zombies hold no grant and cannot be killed again; they only await their reaper.
1110
+ if int(fields[3]) == sid and fields[0] not in ("Z", "X"):
1111
+ members.append(int(entry))
1112
+ if not members:
1113
+ return len(killed)
1114
+ for pid in members:
1115
+ try:
1116
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
1117
+ except OSError:
1118
+ continue
1119
+ try:
1120
+ # The pidfd pins the process; confirm it still belongs to our session.
1121
+ with open("/proc/%d/stat" % pid) as stat_file:
1122
+ data = stat_file.read()
1123
+ fields = data[data.rindex(")") + 2:].split()
1124
+ if int(fields[3]) == sid and int(fields[19]) >= started and not leader_reused():
1125
+ syscall(NR_PIDFD_SEND_SIGNAL, handle, signal.SIGKILL, None, 0)
1126
+ killed.add(pid)
1127
+ except OSError:
1128
+ pass
1129
+ finally:
1130
+ os.close(handle)
1131
+ # Wait for the signalled process to be gone (or a zombie) before rescanning.
1132
+ poller = select.poll()
1133
+ try:
1134
+ waiter = syscall(NR_PIDFD_OPEN, pid, 0)
1135
+ except OSError:
1136
+ continue
1137
+ try:
1138
+ poller.register(waiter, select.POLLIN)
1139
+ poller.poll()
1140
+ finally:
1141
+ os.close(waiter)
1142
+
1143
+
1144
+ def run(request, report):
1145
+ machine, table = arch()
1146
+ native, native_path = load_native()
1147
+ status = probe_static(table, request.get("candidateArch") is True)
1148
+ if status:
1149
+ raise Refused("UNAVAILABLE", status)
1150
+ roots, seen = verify_roots(native, request)
1151
+ network = request.get("network", {"kind": "none"})
1152
+ endpoints = endpoints_of(network)
1153
+ network_mediated = endpoints is not None
1154
+ mode = request.get("mode")
1155
+ files = native.NativeFiles(roots)
1156
+ cwd_path = request.get("cwd") or roots["write"][0]["path"]
1157
+ try:
1158
+ cwd = files.open(cwd_path, directory=True)
1159
+ except (OSError, ValueError, native.ScopeDenied):
1160
+ raise Refused("SCOPE_DENIED", "The working directory is outside the pinned roots")
1161
+ os.set_inheritable(cwd, False)
1162
+ # The staged runtime directory (trusted, consumer-verified) stays readable for the helper.
1163
+ system_roots = list(request.get("systemRoots", DEFAULT_SYSTEM_ROOTS))
1164
+ system_roots.append(os.path.dirname(native_path))
1165
+ ruleset = landlock_ruleset(roots, system_roots, network_mediated or mode == "native")
1166
+ pinned_fds = [r["fd"] for r in roots["read"] + roots["write"]]
1167
+ launch = {"event": "launch", "arch": machine, "validated": machine in VALIDATED_ARCHES,
1168
+ "landlockAbi": landlock_abi(), "roots": seen,
1169
+ "ruleFds": [entry["fd"] for entry in seen], "brokerFds": pinned_fds,
1170
+ "nativeFds": pinned_fds if mode == "native" else [],
1171
+ "cwd": [os.fstat(cwd).st_dev, os.fstat(cwd).st_ino]}
1172
+ brokered = mode == "exec"
1173
+ parent_sock, child_sock = socket.socketpair()
1174
+ libc.prctl(36, 1, 0, 0, 0) # PR_SET_CHILD_SUBREAPER
1175
+ native_in = None
1176
+ if mode == "native":
1177
+ native_in, native_out = os.pipe()
1178
+ elif mode != "exec":
1179
+ raise Refused("INVALID_REQUEST", "Unknown mode")
1180
+ parent = os.getpid()
1181
+ # Cancellation is armed before the fork: a SIGTERM during setup cancels instead of killing
1182
+ # the supervisor by default action and orphaning the child.
1183
+ cancellation = Cancellation()
1184
+ signal.pthread_sigmask(signal.SIG_BLOCK, CANCEL_SIGNALS)
1185
+ pid = os.fork()
1186
+ if pid == 0:
1187
+ try:
1188
+ libc.prctl(1, signal.SIGKILL, 0, 0, 0) # PR_SET_PDEATHSIG
1189
+ if os.getppid() != parent:
1190
+ os._exit(125)
1191
+ os.setsid()
1192
+ signal.signal(signal.SIGTERM, signal.SIG_DFL)
1193
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
1194
+ os.fchdir(cwd)
1195
+ parent_sock.close()
1196
+ if mode == "native":
1197
+ os.dup2(native_in, 0)
1198
+ keep = [r["fd"] for r in roots["read"] + roots["write"]]
1199
+ else:
1200
+ null = os.open("/dev/null", os.O_RDONLY)
1201
+ os.dup2(null, 0)
1202
+ keep = []
1203
+ restrict_child(table, ruleset, network_mediated or mode == "native", brokered,
1204
+ child_sock)
1205
+ # No restricted code runs before the supervisor has recorded the session and holds
1206
+ # the listener: wait for its acknowledgement (EOF if it was lost).
1207
+ if child_sock.recv(1) != b"A":
1208
+ os._exit(125)
1209
+ child_sock.close()
1210
+ # Only stdio (and, for the native helper, the same pinned roots) survive exec.
1211
+ close_except(keep)
1212
+ for fd in keep:
1213
+ os.set_inheritable(fd, True)
1214
+ env = request.get("env") or {"PATH": "/usr/local/bin:/usr/bin:/bin"}
1215
+ if mode == "native":
1216
+ argv = [sys.executable, "-I", native_path]
1217
+ else:
1218
+ argv = request["argv"]
1219
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, CANCEL_SIGNALS)
1220
+ os.execve(argv[0], argv, env)
1221
+ except BaseException as error:
1222
+ try:
1223
+ os.write(2, ("restricted launch failed: %s\n" % error).encode())
1224
+ finally:
1225
+ os._exit(126)
1226
+ # The consumer needs the closed session's identity before anything else can go wrong.
1227
+ try:
1228
+ report.write({"event": "session", "sid": pid, "start": start_time(pid)})
1229
+ finally:
1230
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, CANCEL_SIGNALS)
1231
+ child_sock.close()
1232
+ os.close(ruleset)
1233
+ os.close(cwd)
1234
+ if native_in is not None:
1235
+ os.close(native_in)
1236
+ body = dict(request.get("native", {}))
1237
+ body["roots"] = roots
1238
+ data = json.dumps(body).encode()
1239
+ while data:
1240
+ data = data[os.write(native_out, data):]
1241
+ os.close(native_out)
1242
+ broker = None
1243
+ stop_r, stop_w = os.pipe()
1244
+ thread = None
1245
+ if brokered:
1246
+ message, fds, _, _ = socket.recv_fds(parent_sock, 1, 1)
1247
+ if not fds:
1248
+ kill_tree()
1249
+ raise Refused("UNAVAILABLE", "The restricted child did not hand over its listener")
1250
+ broker = Broker(native, roots, table, endpoints, fds[0])
1251
+ thread = threading.Thread(target=broker.loop, args=(stop_r,), daemon=True)
1252
+ thread.start()
1253
+ # Reported only once every restriction is installed and the broker holds the listener.
1254
+ report.write(launch)
1255
+ parent_sock.send(b"A")
1256
+ parent_sock.close()
1257
+ return supervise(pid, request, report, broker, thread, stop_w, cancellation)
1258
+
1259
+
1260
+ def supervise(pid, request, report, broker, thread, stop_w, cancellation):
1261
+ wake_r = cancellation.wake_r
1262
+ cancelled = cancellation.signals
1263
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
1264
+ deadline = None
1265
+ if request.get("timeoutMs"):
1266
+ deadline = time.monotonic() + request["timeoutMs"] / 1000
1267
+ poller = select.poll()
1268
+ poller.register(handle, select.POLLIN)
1269
+ poller.register(wake_r, select.POLLIN)
1270
+ exit_code = None
1271
+ timed_out = False
1272
+ while True:
1273
+ timeout = None if deadline is None else max(0, int((deadline - time.monotonic()) * 1000))
1274
+ events = dict(poller.poll(timeout))
1275
+ if handle in events:
1276
+ _, status = os.waitpid(pid, 0)
1277
+ exit_code = os.waitstatus_to_exitcode(status)
1278
+ break
1279
+ if cancelled:
1280
+ break
1281
+ if deadline is not None and time.monotonic() >= deadline:
1282
+ timed_out = True
1283
+ break
1284
+ # Restricted descendants never outlive their supervisor: kill the remaining owned tree.
1285
+ survivors = kill_tree()
1286
+ os.write(stop_w, b"x")
1287
+ if thread is not None:
1288
+ thread.join()
1289
+ counts = {}
1290
+ if broker is not None:
1291
+ counts = dict(broker.counts)
1292
+ broker.close()
1293
+ report.write({"event": "exit", "exitCode": exit_code, "timedOut": timed_out,
1294
+ "cancelled": bool(cancelled), "killed": survivors, "brokered": counts})
1295
+ if exit_code is None:
1296
+ return 124 if timed_out else 143
1297
+ return exit_code if exit_code >= 0 else 128 - exit_code
1298
+
1299
+
1300
+ # ---- capability probe ---------------------------------------------------------------------
1301
+
1302
+ def probe_static(table, candidate=False):
1303
+ machine = platform.machine()
1304
+ if platform.system() != "Linux":
1305
+ return "Restricted Linux execution requires Linux"
1306
+ if table is None:
1307
+ return "No syscall inventory exists for %s" % machine
1308
+ if machine not in VALIDATED_ARCHES and not candidate:
1309
+ return "The syscall inventory is not validated on %s" % machine
1310
+ abi = landlock_abi()
1311
+ if abi < LANDLOCK_ABI_REQUIRED:
1312
+ return "Landlock ABI %d is below the required %d" % (abi, LANDLOCK_ABI_REQUIRED)
1313
+ if not os.path.exists("/proc/self/task/%d/children" % os.getpid()):
1314
+ return "The kernel does not expose child lists for exact supervision"
1315
+ return None
1316
+
1317
+
1318
+ def probe(candidate=False):
1319
+ """Never raises: any failure is restricted unavailable with its reason.
1320
+
1321
+ "restricted" is non-null only on a validated architecture. With candidate set on an
1322
+ unvalidated one, the primitives' result is reported separately under "candidate" (evidence
1323
+ collection only) and "restricted" stays null, so no consumer can read it as support.
1324
+ """
1325
+ machine = platform.machine()
1326
+ try:
1327
+ result = probe_primitives(candidate)
1328
+ except BaseException as error:
1329
+ return {"restricted": None, "arch": machine,
1330
+ "reason": "The probe failed: %s" % type(error).__name__}
1331
+ if candidate and machine not in VALIDATED_ARCHES:
1332
+ return {"restricted": None, "arch": machine, "validated": False,
1333
+ "reason": "The syscall inventory is not validated on %s" % machine,
1334
+ "candidate": result}
1335
+ return result
1336
+
1337
+
1338
+ def probe_primitives(candidate):
1339
+ """Exercises the real primitives: Landlock, a seccomp listener, ADDFD and target memory."""
1340
+ machine, table = arch()
1341
+ reason = probe_static(table, candidate)
1342
+ if reason:
1343
+ return {"restricted": None, "reason": reason, "arch": machine}
1344
+ parent_sock, child_sock = socket.socketpair()
1345
+ pid = os.fork()
1346
+ if pid == 0:
1347
+ try:
1348
+ parent_sock.close()
1349
+ if libc.prctl(38, 1, 0, 0, 0) != 0:
1350
+ os._exit(3)
1351
+ attr = struct.pack("QQQ", FS_ALL, NET_CONNECT_TCP, SCOPE_ALL)
1352
+ ruleset = syscall(NR_LANDLOCK_CREATE, ctypes.create_string_buffer(attr, 24), 24, 0)
1353
+ syscall(NR_LANDLOCK_RESTRICT, ruleset, 0)
1354
+ listener = install_filter(table, build_filter(table, True, True), True)
1355
+ socket.send_fds(child_sock, [b"L"], [listener])
1356
+ os.close(listener)
1357
+ probe_socket = socket.socket(AF_INET, SOCK_STREAM)
1358
+ child_sock.send(b"ok" if probe_socket.fileno() >= 0 else b"no")
1359
+ os._exit(0)
1360
+ except BaseException:
1361
+ os._exit(4)
1362
+ child_sock.close()
1363
+ try:
1364
+ _, fds, _, _ = socket.recv_fds(parent_sock, 1, 1)
1365
+ if not fds:
1366
+ raise OSError(errno.EPERM, "The seccomp listener is not available")
1367
+ buffer = ctypes.create_string_buffer(80)
1368
+ ioctl(fds[0], NOTIF_RECV, buffer)
1369
+ ident, target, _, nr, _, _ = struct.unpack_from("QIIiIQ", buffer.raw)
1370
+ mem = os.open("/proc/%d/mem" % target, os.O_RDONLY)
1371
+ os.close(mem)
1372
+ own = socket.socket(AF_INET, SOCK_STREAM)
1373
+ data = struct.pack("QIIII", ident, ADDFD_SEND, own.fileno(), 0, 0)
1374
+ ioctl(fds[0], NOTIF_ADDFD, ctypes.create_string_buffer(data, len(data)))
1375
+ own.close()
1376
+ answer = parent_sock.recv(2)
1377
+ _, status = os.waitpid(pid, 0)
1378
+ if answer != b"ok" or os.waitstatus_to_exitcode(status) != 0:
1379
+ raise OSError(errno.EPERM, "The brokered socket did not reach the child")
1380
+ handle = syscall(NR_PIDFD_OPEN, os.getpid(), 0)
1381
+ os.close(handle)
1382
+ except OSError as error:
1383
+ try:
1384
+ os.kill(pid, signal.SIGKILL)
1385
+ os.waitpid(pid, 0)
1386
+ except OSError:
1387
+ pass
1388
+ return {"restricted": None, "arch": machine,
1389
+ "reason": "A required primitive failed: %s" % error.strerror}
1390
+ return {"restricted": {"filesystem": True, "network": True, "native": True,
1391
+ "concurrentScopes": True},
1392
+ "arch": machine, "validated": machine in VALIDATED_ARCHES,
1393
+ "landlockAbi": landlock_abi()}
1394
+
1395
+
1396
+ def main():
1397
+ report = Report(None)
1398
+ try:
1399
+ if len(sys.argv) > 1 and sys.argv[1] == "probe":
1400
+ print(json.dumps(probe("--candidate-arch" in sys.argv[2:])), flush=True)
1401
+ return 0
1402
+ if len(sys.argv) > 1 and sys.argv[1] == "reap":
1403
+ print(json.dumps({"killed": reap(json.load(sys.stdin))}), flush=True)
1404
+ return 0
1405
+ request = json.load(sys.stdin)
1406
+ report = Report(request.get("reportFd"))
1407
+ if report.fd is not None:
1408
+ os.set_inheritable(report.fd, False)
1409
+ return run(request, report)
1410
+ except Refused as error:
1411
+ report.write({"event": "refused", "code": error.code, "message": str(error)})
1412
+ return 125
1413
+ except Exception as error:
1414
+ report.write({"event": "refused", "code": "INVALID_REQUEST",
1415
+ "message": "Restricted launch failed: %s" % type(error).__name__})
1416
+ return 125
1417
+
1418
+
1419
+ if __name__ == "__main__":
1420
+ sys.exit(main())
1421
+ `;