@capybara-hq/plugin-sdk 0.1.0-rc.7 → 0.1.0-rc.70

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 (146) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +2 -0
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +76 -3
  13. package/agent-docs/plugin-format.md +51 -12
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +109 -1
  20. package/dist/bootstrap.js +185 -2
  21. package/dist/cards.d.ts +60 -13
  22. package/dist/cards.js +88 -18
  23. package/dist/channel.d.ts +128 -47
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +28 -6
  30. package/dist/config-ui.js +88 -25
  31. package/dist/config-url-fetch.d.ts +19 -0
  32. package/dist/config-url-fetch.js +43 -0
  33. package/dist/connector-auth.d.ts +13 -2
  34. package/dist/connector-auth.js +82 -8
  35. package/dist/connector.d.ts +74 -32
  36. package/dist/context.d.ts +40 -0
  37. package/dist/context.js +2 -0
  38. package/dist/ctx.d.ts +210 -30
  39. package/dist/ctx.js +9 -1
  40. package/dist/define-extension.d.ts +23 -13
  41. package/dist/define-extension.js +19 -5
  42. package/dist/device-denied-paths.d.ts +20 -0
  43. package/dist/device-denied-paths.js +118 -0
  44. package/dist/device-operation.d.ts +339 -0
  45. package/dist/device-operation.js +312 -0
  46. package/dist/device-protocol.d.ts +285 -50
  47. package/dist/device-protocol.js +755 -90
  48. package/dist/device-provider.d.ts +708 -0
  49. package/dist/device-provider.js +325 -0
  50. package/dist/device-service.d.ts +52 -0
  51. package/dist/device-service.js +105 -0
  52. package/dist/dial-in.d.ts +239 -0
  53. package/dist/dial-in.js +155 -0
  54. package/dist/directory.d.ts +15 -12
  55. package/dist/extension-point.d.ts +2 -0
  56. package/dist/extension-point.js +6 -2
  57. package/dist/field-meta.d.ts +19 -0
  58. package/dist/field-meta.js +54 -0
  59. package/dist/file-preview.d.ts +26 -10
  60. package/dist/git-hosts.d.ts +53 -0
  61. package/dist/git-hosts.js +98 -0
  62. package/dist/hooks.d.ts +125 -20
  63. package/dist/hooks.js +5 -0
  64. package/dist/http-access.d.ts +62 -0
  65. package/dist/http-access.js +12 -0
  66. package/dist/identity.d.ts +38 -9
  67. package/dist/identity.js +21 -1
  68. package/dist/index.d.ts +31 -4
  69. package/dist/index.js +31 -4
  70. package/dist/model-params.d.ts +41 -22
  71. package/dist/model-params.js +28 -15
  72. package/dist/model.d.ts +210 -75
  73. package/dist/model.js +152 -19
  74. package/dist/net.d.ts +52 -0
  75. package/dist/net.js +34 -0
  76. package/dist/network-classes.d.ts +98 -0
  77. package/dist/network-classes.js +291 -0
  78. package/dist/permissions.d.ts +65 -22
  79. package/dist/permissions.js +139 -43
  80. package/dist/platform-only.d.ts +27 -0
  81. package/dist/platform-only.js +35 -0
  82. package/dist/plugin-manifest.d.ts +40 -9
  83. package/dist/plugin-manifest.js +171 -60
  84. package/dist/plugin-package.d.ts +82 -39
  85. package/dist/plugin-package.js +68 -41
  86. package/dist/push.d.ts +75 -0
  87. package/dist/push.js +87 -0
  88. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  89. package/dist/sandbox-linux-runtime-source.js +2343 -0
  90. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  91. package/dist/sandbox-native-runtime-source.js +476 -0
  92. package/dist/sandbox-runtime-source.d.ts +47 -0
  93. package/dist/sandbox-runtime-source.js +73 -0
  94. package/dist/sandbox-write-denies.d.ts +139 -0
  95. package/dist/sandbox-write-denies.js +869 -0
  96. package/dist/secret.d.ts +8 -2
  97. package/dist/secret.js +11 -4
  98. package/dist/setup-check.d.ts +128 -0
  99. package/dist/setup-check.js +142 -0
  100. package/dist/setup-guide-parse.d.ts +121 -0
  101. package/dist/setup-guide-parse.js +356 -0
  102. package/dist/setup-guide-render.d.ts +45 -0
  103. package/dist/setup-guide-render.js +351 -0
  104. package/dist/setup-guide.d.ts +86 -72
  105. package/dist/setup-guide.js +340 -108
  106. package/dist/shell-capabilities.d.ts +211 -0
  107. package/dist/shell-capabilities.js +44 -0
  108. package/dist/shell-environment.d.ts +57 -0
  109. package/dist/shell-environment.js +21 -0
  110. package/dist/skill.d.ts +27 -17
  111. package/dist/skill.js +40 -26
  112. package/dist/storage.d.ts +52 -25
  113. package/dist/svg-viewbox.d.ts +10 -0
  114. package/dist/svg-viewbox.js +24 -0
  115. package/dist/theme-assets.d.ts +55 -0
  116. package/dist/theme-assets.js +489 -0
  117. package/dist/theme-readability.d.ts +37 -0
  118. package/dist/theme-readability.js +145 -0
  119. package/dist/theme-tokens.generated.d.ts +299 -0
  120. package/dist/theme-tokens.generated.js +184 -0
  121. package/dist/theme.d.ts +190 -0
  122. package/dist/theme.js +471 -0
  123. package/dist/tool.d.ts +104 -30
  124. package/dist/tool.js +29 -9
  125. package/dist/ui-parts.d.ts +23 -0
  126. package/dist/ui-parts.js +385 -0
  127. package/dist/ui-resolve.d.ts +35 -0
  128. package/dist/ui-resolve.js +42 -0
  129. package/dist/ui-slots.d.ts +65 -0
  130. package/dist/ui-slots.js +261 -0
  131. package/dist/ui.d.ts +221 -77
  132. package/dist/ui.js +104 -27
  133. package/dist/url.d.ts +4 -1
  134. package/dist/url.js +4 -1
  135. package/dist/web.d.ts +26 -20
  136. package/package.json +13 -1
  137. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  138. package/schemas/bootstrap.v1.schema.json +20 -0
  139. package/schemas/connector-template.v1.schema.json +62 -4
  140. package/schemas/plugin.v1.schema.json +93 -143
  141. package/schemas/theme.v1.schema.json +302 -0
  142. package/agent-docs/extension-points/sandbox.md +0 -15
  143. package/dist/org-access.d.ts +0 -27
  144. package/dist/org-access.js +0 -35
  145. package/dist/sandbox.d.ts +0 -254
  146. package/dist/sandbox.js +0 -153
@@ -0,0 +1,2343 @@
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
+ * readFiles? (exec only: single regular files granted read without their directory; one
8
+ * renamed, deleted or hard-linked since the pin is skipped, a wrong type or identity refused)},
9
+ * network: {kind: "none" | "environment"} | {kind: "endpoints", endpoints: [{address, port}]},
10
+ * reportFd, cwd?, env?, argv (exec), timeoutMs? (exec), native (native-files request),
11
+ * nativeFd? (exec: an inherited, consumer-verified descriptor of native-files.py, e.g. a sealed
12
+ * memfd, used instead of the file beside the launcher), writeDenies? (exec: absolute paths the
13
+ * consumer resolved for this operation, denied like `SANDBOX_SYSTEM_WRITE_DENIES`),
14
+ * filesLockFd? (exec: an inherited descriptor of the device's files lock, a regular file outside
15
+ * every root, shared by all operations of the device; see native-files.py DeviceFilesLock)}`.
16
+ * Root descriptors are pinned once by the consumer and inherited; the launcher verifies their
17
+ * identity and never reopens a root pathname. Landlock rules, broker metadata checks and the
18
+ * native helper all use those same descriptors. A file root (`readFiles`) is an O_PATH, no-follow
19
+ * descriptor of the regular file itself; it becomes one Landlock rule granting file reads only
20
+ * (no directory listing, no execution) and never reaches the broker or the native helper. JSON events (`launch`, `exit`, `refused`) go to
21
+ * reportFd, which the restricted child cannot write. SIGTERM cancels the whole owned tree.
22
+ * Full access never uses this launcher: it has no restricted filters.
23
+ *
24
+ * Exec mode brokers every filesystem write: write roots grant the command read access only in
25
+ * Landlock, and each write-capable open, create, mkdir, mknod, unlink, rename, link, symlink,
26
+ * truncate and metadata change is performed by the broker on its own no-follow resolution from
27
+ * the pinned descriptors, refusing the mandatory write denies (`sandbox-write-denies.ts`).
28
+ */
29
+ import { SANDBOX_WRITE_POLICY_PYTHON } from "./sandbox-write-denies.js";
30
+ export const LINUX_SANDBOX_SOURCE = String.raw `import ctypes
31
+ import sys
32
+
33
+
34
+ def protect_self():
35
+ """Makes this process (launcher, supervisor and broker thread) non-dumpable, first thing.
36
+
37
+ execve resets dumpability, and without Yama a same-uid process (another session's Full work)
38
+ could otherwise ptrace the launcher or open its /proc/<pid>/mem, environ and fd. Non-dumpable,
39
+ those need CAP_SYS_PTRACE; fork inherits it, so the pre-exec child is covered until its own
40
+ execve. Only a tracer still attached at this point is detected (and refused); see the
41
+ documented exec-to-prctl window below for what is not.
42
+ """
43
+ if not sys.platform.startswith("linux"):
44
+ return None
45
+ if ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) != 0: # PR_SET_DUMPABLE 0
46
+ return "The launcher could not make itself non-dumpable"
47
+ try:
48
+ with open("/proc/self/status") as handle:
49
+ for line in handle:
50
+ if line.startswith("TracerPid:") and int(line.split()[1]) != 0:
51
+ return "The launcher was traced before it became non-dumpable"
52
+ except (OSError, ValueError):
53
+ return "The launcher could not confirm that it is not traced"
54
+ return None
55
+
56
+
57
+ SELF_PROTECTION = protect_self()
58
+
59
+ import contextlib
60
+ import errno
61
+ import fcntl
62
+ import importlib.machinery
63
+ import importlib.util
64
+ import ipaddress
65
+ import json
66
+ import os
67
+ import platform
68
+ import select
69
+ import signal
70
+ import socket
71
+ import stat
72
+ import struct
73
+ import sys
74
+ import threading
75
+ import time
76
+
77
+ # Restricted Linux launcher and syscall broker. The trusted consumer pins every granted root once
78
+ # (an inherited directory descriptor plus its device/inode identity) and passes it here. Landlock
79
+ # rules, the broker's metadata checks and the native-file helper all use exactly those
80
+ # descriptors; root pathnames are never reopened. Anything unsupported reports unavailable.
81
+ #
82
+ # Documented behaviour of restricted execution:
83
+ # - Metadata reads outside the roots are not mediated: stat/statx, access, readlink, getxattr,
84
+ # listxattr, statfs, inotify marks and other processes' /proc cmdline can reveal names, sizes,
85
+ # times, link targets and xattr values. File contents, writes and metadata changes are confined.
86
+ # - Known limitation: /proc stays a read root, so a restricted command can read the world-readable
87
+ # entries of other processes of the same uid, including /proc/<pid>/cmdline of a concurrent Full
88
+ # command (secrets inlined in a command line are visible). Ptrace-guarded entries (environ, mem,
89
+ # maps, fd) stay closed by Landlock's ptrace scoping. Landlock cannot narrow /proc to the
90
+ # command's own tree: /proc/self resolves to per-process directories that exist only after the
91
+ # rules are set, so dropping /proc (keeping cpuinfo, meminfo, stat and the like) also denies a
92
+ # process its own /proc/self, which ordinary tools need (Node's process.memoryUsage(), Python's
93
+ # /proc/self/fd and /proc/self/maps reads). hidepid needs a mount and PID namespaces need new
94
+ # privileges, both outside this launcher's design. Consumers keep secrets out of command lines.
95
+ # - Network none/allowlist: TCP sockets may bind and listen on loopback (127.0.0.1, ::1) only;
96
+ # connections go only to the endpoints the consumer granted. A command's own loopback listener
97
+ # is reachable from outside the sandbox, never from the command's own client: the broker cannot
98
+ # tell an own listener from another process's at the address dialled (a listener can be
99
+ # re-listened after another socket took its port, or share it through SO_REUSEPORT).
100
+ # SO_REUSEPORT and its group programs (SO_ATTACH_REUSEPORT_CBPF / EBPF) are refused (EPERM), and
101
+ # a socket with SO_REUSEPORT set never binds or listens: joining a foreign service's reuseport
102
+ # group would receive that service's connections. Environment lifts that filter.
103
+ # - UNIX sockets in every network kind: stream/seqpacket only (datagram and raw are refused);
104
+ # a pathname bind only inside the write roots, resolved through the pinned descriptors, and a
105
+ # pathname connect only to a socket this operation bound itself (its dev and inode recorded at
106
+ # the brokered bind), never to one another process made, even inside a write root (a user
107
+ # D-Bus, a rootless docker.sock, ssh-agent, tmux); abstract and unnamed addresses are refused.
108
+ # socketpair() is unaffected.
109
+ # - The launcher makes itself non-dumpable before anything else (protect_self), so a same-uid
110
+ # process outside the operation cannot ptrace it or read its mem, environ or fd afterwards.
111
+ # The window between the interpreter's exec and that first statement remains: only a tracer
112
+ # still attached when protect_self runs is detected (the launcher then refuses). Anything done
113
+ # or opened in the window is not detected: a /proc/<pid>/mem descriptor (read or write) keeps
114
+ # working, and writes through it, process_vm_writev or pidfd_getfd made then leave no trace.
115
+ # Closing the window needs a separate uid for Full work, or a non-dumpable zygote that the
116
+ # consumer starts once and that forks a fresh launcher per operation (no exec in between).
117
+ # - The restricted command and the native helper are dumpable again after their own execve: the
118
+ # broker must read the command's memory. Their memory and /proc/<pid>/environ stay readable,
119
+ # and they stay ptraceable, by same-uid Full work on the device; consumers must not pass
120
+ # per-session secrets through the command's environment or arguments. A consumer that signals
121
+ # or inspects a launcher uses the pid and start time it recorded (the "session" event, its own
122
+ # child), never a process found by an environment marker, which any same-uid process can copy.
123
+ # - The launcher creates one closed session (setsid is denied inside it) and reports it in a
124
+ # "session" event; if the supervisor is lost, the consumer runs "reap" with that event to end
125
+ # every owned process. Brokered calls fail (ENOSYS) once the broker is gone.
126
+ #
127
+ # Architecture validation: an architecture reports restricted support only when it is listed in
128
+ # VALIDATED_ARCHES, which an evidence commit changes after the real-kernel conformance suite
129
+ # passed on that architecture (the commit cites the run). Until then a consumer may pass
130
+ # "candidateArch" (probe --candidate-arch) to run the reviewed table for evidence collection
131
+ # only; production consumers never set it.
132
+
133
+ LANDLOCK_ABI_REQUIRED = 6
134
+ # aarch64: Docker 29.9.3 on Linux 7.0.14-linuxkit (Landlock ABI 8), reviewed conformance runs.
135
+ # x86_64: GitHub Actions run 43906202355 on Linux 7.0.0-1019-azure, LSM list with landlock,
136
+ # Docker builtin seccomp, image capybara-sandbox@sha256:0473fbbc... amd64: 19 passed, 1 guard
137
+ # skipped, with CAPYBARA_TEST_REQUIRE_LINUX_RESTRICTED=1 (no mechanism test skipped).
138
+ VALIDATED_ARCHES = ("aarch64", "x86_64")
139
+ # Every syscall above this number (newer than the reviewed inventory) fails with ENOSYS.
140
+ MAX_KNOWN_SYSCALL = 469
141
+
142
+ ARCHES = {
143
+ "aarch64": {
144
+ "audit": 0xC00000B7,
145
+ "seccomp": 277,
146
+ "nr": {
147
+ "setxattr": 5, "lsetxattr": 6, "fsetxattr": 7, "removexattr": 14,
148
+ "lremovexattr": 15, "fremovexattr": 16, "ioctl": 29, "fchmod": 52, "fchmodat": 53,
149
+ "fchownat": 54, "fchown": 55, "utimensat": 88, "unshare": 97, "setsid": 157,
150
+ "socket": 198, "socketpair": 199, "bind": 200, "listen": 201, "connect": 203, "sendto": 206,
151
+ "setsockopt": 208,
152
+ "sendmsg": 211, "add_key": 217, "request_key": 218, "keyctl": 219, "clone": 220,
153
+ "setns": 268, "sendmmsg": 269, "userfaultfd": 282,
154
+ "mknodat": 33, "mkdirat": 34, "unlinkat": 35, "symlinkat": 36, "linkat": 37,
155
+ "renameat": 38, "truncate": 45, "openat": 56, "renameat2": 276,
156
+ },
157
+ },
158
+ "x86_64": {
159
+ "audit": 0xC000003E,
160
+ "seccomp": 317,
161
+ "x32": True,
162
+ "nr": {
163
+ "ioctl": 16, "socket": 41, "connect": 42, "sendto": 44, "sendmsg": 46, "bind": 49,
164
+ "listen": 50, "socketpair": 53, "setsockopt": 54, "clone": 56, "chmod": 90, "fchmod": 91, "chown": 92, "fchown": 93,
165
+ "lchown": 94, "setsid": 112, "utime": 132, "uselib": 134, "setxattr": 188,
166
+ "lsetxattr": 189, "fsetxattr": 190, "removexattr": 197, "lremovexattr": 198,
167
+ "fremovexattr": 199, "utimes": 235, "add_key": 248, "request_key": 249,
168
+ "keyctl": 250, "fchownat": 260, "futimesat": 261, "fchmodat": 268, "unshare": 272,
169
+ "utimensat": 280, "sendmmsg": 307, "setns": 308, "userfaultfd": 323,
170
+ "open": 2, "truncate": 76, "rename": 82, "mkdir": 83, "rmdir": 84, "creat": 85,
171
+ "link": 86, "unlink": 87, "symlink": 88, "mknod": 133, "openat": 257, "mkdirat": 258,
172
+ "mknodat": 259, "unlinkat": 263, "renameat": 264, "linkat": 265, "symlinkat": 266,
173
+ "renameat2": 316,
174
+ },
175
+ },
176
+ }
177
+ COMMON = {"io_uring_setup": 425, "io_uring_enter": 426, "io_uring_register": 427,
178
+ "clone3": 435, "openat2": 437, "fchmodat2": 452, "setxattrat": 463, "removexattrat": 466,
179
+ "file_setattr": 469}
180
+ NR_CLOSE_RANGE = 436
181
+ # CLONE_NEWNS | NEWCGROUP | NEWUTS | NEWIPC | NEWUSER | NEWPID | NEWNET | NEWTIME
182
+ NAMESPACE_FLAGS = 0x7E020080
183
+ NR_PIDFD_OPEN = 434
184
+ NR_PIDFD_SEND_SIGNAL = 424
185
+ NR_LANDLOCK_CREATE = 444
186
+ NR_LANDLOCK_ADD = 445
187
+ NR_LANDLOCK_RESTRICT = 446
188
+
189
+ FS_EXECUTE, FS_WRITE_FILE, FS_READ_FILE, FS_READ_DIR = 1, 2, 4, 8
190
+ FS_TRUNCATE, FS_IOCTL_DEV = 1 << 14, 1 << 15
191
+ FS_ALL = (1 << 16) - 1
192
+ FS_READ = FS_EXECUTE | FS_READ_FILE | FS_READ_DIR
193
+ FS_DEVICE = FS_READ_FILE | FS_WRITE_FILE | FS_TRUNCATE | FS_IOCTL_DEV
194
+ NET_CONNECT_TCP = 2
195
+ # LANDLOCK_ACCESS_NET_BIND_TCP | CONNECT_TCP: only the broker binds or connects TCP sockets.
196
+ NET_MEDIATED = 1 | 2
197
+ SCOPE_ALL = 1 | 2 # abstract UNIX sockets and signals stay inside the domain
198
+ DEFAULT_SYSTEM_ROOTS = ("/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc", "/proc")
199
+ DEVICE_FILES = ("/dev/null", "/dev/zero", "/dev/full", "/dev/random", "/dev/urandom", "/dev/tty")
200
+
201
+ RET_ALLOW, RET_NOTIFY, RET_KILL = 0x7FFF0000, 0x7FC00000, 0x80000000
202
+ # O_WRONLY | O_RDWR | O_CREAT | O_TRUNC | __O_TMPFILE (generic values on both architectures)
203
+ WRITE_OPEN_FLAGS = 0o20001103
204
+ O_TMPFILE_BIT = 0o20000000
205
+ AT_REMOVEDIR, AT_SYMLINK_FOLLOW = 0x200, 0x400
206
+ RENAME_NOREPLACE, RENAME_EXCHANGE = 1, 2
207
+ FILE_OPS = ("open", "openat", "creat", "mkdir", "mkdirat", "mknod", "mknodat", "rmdir", "unlink",
208
+ "unlinkat", "symlink", "symlinkat", "link", "linkat", "rename", "renameat",
209
+ "renameat2", "truncate")
210
+ STD_STREAMS = {"/dev/stdin": 0, "/dev/stdout": 1, "/dev/stderr": 2}
211
+
212
+
213
+ # The write policy shared with every consumer (sandbox-write-denies.ts): write_denied(path) and
214
+ # move_denied(source, destination, is_dir).
215
+ ${SANDBOX_WRITE_POLICY_PYTHON}
216
+ def RET_ERRNO(code):
217
+ return 0x00050000 | code
218
+
219
+ # File-attribute, encryption-policy and terminal-injection ioctls that mutate an object the
220
+ # descriptor may only read. Landlock's IOCTL_DEV right does not cover regular files.
221
+ DENIED_IOCTLS = (0x5412, 0x541C, 0x40086602, 0x40046602, 0x401C5820, 0x40087602, 0x40047602,
222
+ 0x800C6613, 0xC0406618, 0xC0186619, 0xC040661A)
223
+ MSG_FASTOPEN = 0x20000000
224
+ # Linux socket ABI values (identical on every architecture this launcher knows).
225
+ AF_UNSPEC, AF_UNIX, AF_INET, AF_INET6, AF_NETLINK = 0, 1, 2, 10, 16
226
+ SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET = 1, 2, 5
227
+ SOCK_NONBLOCK, SOCK_CLOEXEC = 0o4000, 0o2000000
228
+ SOL_SOCKET, SO_DOMAIN, IPPROTO_TCP = 1, 39, 6
229
+ SO_REUSEPORT, SO_ATTACH_REUSEPORT_CBPF, SO_ATTACH_REUSEPORT_EBPF = 15, 51, 52
230
+ LOOPBACK = ("127.0.0.1", "::1")
231
+ # How long a guarded directory move waits for the device's other writes (a FIFO open waiting
232
+ # for its peer holds them) before it fails with EBUSY.
233
+ EXCLUSIVE_WAIT_S = 5
234
+ # The faultInjection seam's pause before a named mkdir, and the marker announcing it.
235
+ PAUSE_S = 2
236
+ PAUSE_MARKER = ".capybara-test-paused"
237
+ AT_FDCWD = -100
238
+ AT_SYMLINK_NOFOLLOW = 0x100
239
+ AT_EMPTY_PATH = 0x1000
240
+ NOTIF_RECV, NOTIF_SEND, NOTIF_ID_VALID, NOTIF_ADDFD = 0xC0502100, 0xC0182101, 0x40082102, 0x40182103
241
+ ADDFD_SEND = 2
242
+
243
+ libc = ctypes.CDLL(None, use_errno=True)
244
+ libc.syscall.restype = ctypes.c_long
245
+ libc.ioctl.restype = ctypes.c_int
246
+ libc.ioctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_void_p)
247
+
248
+
249
+ class Refused(Exception):
250
+ def __init__(self, code, message):
251
+ super().__init__(message)
252
+ self.code = code
253
+
254
+
255
+ def syscall(nr, *args):
256
+ result = libc.syscall(ctypes.c_long(nr), *[ctypes.c_long(a) if isinstance(a, int) else a
257
+ for a in args])
258
+ if result < 0:
259
+ code = ctypes.get_errno()
260
+ raise OSError(code, os.strerror(code))
261
+ return result
262
+
263
+
264
+ def ioctl(fd, request, buffer):
265
+ if libc.ioctl(fd, request, buffer) < 0:
266
+ code = ctypes.get_errno()
267
+ raise OSError(code, os.strerror(code))
268
+
269
+
270
+ def load_native(fd=None):
271
+ """The native helper beside this file, or (exec mode) from a sealed descriptor the consumer
272
+ verified, so the bytes it checked are the bytes that run."""
273
+ if fd is not None:
274
+ if type(fd) is not int or fd < 3:
275
+ raise Refused("INVALID_REQUEST", "Supply an inherited native helper descriptor")
276
+ os.set_inheritable(fd, False)
277
+ path = "/proc/self/fd/%d" % fd
278
+ else:
279
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "native-files.py")
280
+ # an explicit source loader: a descriptor path has no .py suffix to infer one from
281
+ spec = importlib.util.spec_from_loader(
282
+ "capybara_native_files",
283
+ importlib.machinery.SourceFileLoader("capybara_native_files", path))
284
+ module = importlib.util.module_from_spec(spec)
285
+ spec.loader.exec_module(module)
286
+ return module, path
287
+
288
+
289
+ def arch():
290
+ machine = platform.machine()
291
+ return machine, ARCHES.get(machine)
292
+
293
+
294
+ def landlock_abi():
295
+ value = libc.syscall(ctypes.c_long(NR_LANDLOCK_CREATE), None, ctypes.c_long(0),
296
+ ctypes.c_long(1))
297
+ return value if value > 0 else 0
298
+
299
+
300
+ # ---- seccomp filter -----------------------------------------------------------------------
301
+
302
+ class Program:
303
+ def __init__(self):
304
+ self.code = []
305
+ self.labels = {}
306
+
307
+ def label(self, name):
308
+ self.labels[name] = len(self.code)
309
+
310
+ def ld(self, offset):
311
+ self.code.append((0x20, 0, 0, offset))
312
+
313
+ def ld_nr(self):
314
+ self.ld(0)
315
+
316
+ def ld_arg(self, index):
317
+ self.ld(16 + 8 * index)
318
+
319
+ def ret(self, value):
320
+ self.code.append((0x06, 0, 0, value))
321
+
322
+ def alu_and(self, value):
323
+ self.code.append((0x54, 0, 0, value))
324
+
325
+ def jump(self, op, value, true, false=None):
326
+ self.code.append((op, true, false, value))
327
+
328
+ def jeq(self, value, true, false=None):
329
+ self.jump(0x15, value, true, false)
330
+
331
+ def jgt(self, value, true, false=None):
332
+ self.jump(0x25, value, true, false)
333
+
334
+ def jge(self, value, true, false=None):
335
+ self.jump(0x35, value, true, false)
336
+
337
+ def jset(self, value, true, false=None):
338
+ self.jump(0x45, value, true, false)
339
+
340
+ def assemble(self):
341
+ out = bytearray()
342
+ for index, (code, true, false, value) in enumerate(self.code):
343
+ def target(name):
344
+ if name is None:
345
+ return 0
346
+ offset = self.labels[name] - index - 1
347
+ if not 0 <= offset <= 255:
348
+ raise ValueError("seccomp jump out of range")
349
+ return offset
350
+ if code & 0x07 == 0x05:
351
+ out += struct.pack("HBBI", code, target(true), target(false), value)
352
+ else:
353
+ out += struct.pack("HBBI", code, 0, 0, value)
354
+ return bytes(out)
355
+
356
+
357
+ def build_filter(table, network_mediated, brokered):
358
+ """The restricted child's filter. Brokered calls go to the supervisor (EACCES without one)."""
359
+ nr = dict(table["nr"], **COMMON)
360
+ notify = RET_NOTIFY if brokered else RET_ERRNO(errno.EACCES)
361
+ p = Program()
362
+ p.ld(4)
363
+ p.jeq(table["audit"], "arch_ok")
364
+ p.ret(RET_KILL)
365
+ p.label("arch_ok")
366
+ p.ld_nr()
367
+ if table.get("x32"):
368
+ p.jge(0x40000000, "enosys")
369
+ p.jgt(MAX_KNOWN_SYSCALL, "enosys")
370
+ simple = {}
371
+ for name in ("io_uring_setup", "io_uring_enter", "io_uring_register", "userfaultfd",
372
+ "setxattrat", "removexattrat", "file_setattr", "utime", "utimes", "futimesat",
373
+ "uselib", "clone3"):
374
+ if name in nr:
375
+ simple[nr[name]] = RET_ERRNO(errno.ENOSYS)
376
+ # Sessions, keyrings and namespaces stay the launcher's; Landlock does not cover keyrings.
377
+ for name in ("setsid", "keyctl", "add_key", "request_key", "setns"):
378
+ simple[nr[name]] = RET_ERRNO(errno.EPERM)
379
+ for name in ("chmod", "fchmod", "fchmodat", "fchmodat2", "chown", "fchown", "lchown",
380
+ "fchownat", "utimensat", "setxattr", "lsetxattr", "fsetxattr", "removexattr",
381
+ "lremovexattr", "fremovexattr", "connect", "listen"):
382
+ if name in nr:
383
+ simple[nr[name]] = notify
384
+ if network_mediated or brokered:
385
+ # a pathname UNIX bind creates a file: the broker makes it (and checks the denies)
386
+ simple[nr["bind"]] = notify
387
+ if brokered:
388
+ # Every filesystem write goes through the broker (Landlock grants the command read
389
+ # access to its write roots only, so anything left unmediated fails closed).
390
+ for name in FILE_OPS:
391
+ if name in nr and name not in ("open", "openat"):
392
+ simple[nr[name]] = RET_NOTIFY
393
+ simple[nr["openat2"]] = RET_ERRNO(errno.ENOSYS) # its flags sit behind a pointer
394
+ for number in simple:
395
+ p.jeq(number, "r%d" % number)
396
+ if brokered:
397
+ p.jeq(nr["openat"], "openat")
398
+ if "open" in nr:
399
+ p.jeq(nr["open"], "open")
400
+ p.jeq(nr["ioctl"], "ioctl")
401
+ p.jeq(nr["socket"], "socket")
402
+ p.jeq(nr["socketpair"], "socketpair")
403
+ p.jeq(nr["unshare"], "namespaces")
404
+ p.jeq(nr["clone"], "namespaces")
405
+ if network_mediated:
406
+ p.jeq(nr["setsockopt"], "setsockopt")
407
+ p.jeq(nr["sendto"], "fastopen3")
408
+ p.jeq(nr["sendmmsg"], "fastopen3")
409
+ p.jeq(nr["sendmsg"], "fastopen2")
410
+ p.ret(RET_ALLOW)
411
+ if network_mediated:
412
+ # SO_REUSEPORT and its group programs: joining a foreign service's reuseport group would
413
+ # receive that service's connections (kept close to the dispatch: jumps reach 255 at most)
414
+ p.label("setsockopt")
415
+ p.ld_arg(1)
416
+ p.jeq(SOL_SOCKET, "sockopt_name")
417
+ p.ret(RET_ALLOW)
418
+ p.label("sockopt_name")
419
+ p.ld_arg(2)
420
+ for option in (SO_REUSEPORT, SO_ATTACH_REUSEPORT_CBPF, SO_ATTACH_REUSEPORT_EBPF):
421
+ p.jeq(option, "sockopt_eperm")
422
+ p.ret(RET_ALLOW)
423
+ p.label("sockopt_eperm")
424
+ p.ret(RET_ERRNO(errno.EPERM))
425
+ for number, action in simple.items():
426
+ p.label("r%d" % number)
427
+ p.ret(action)
428
+ p.label("enosys")
429
+ p.ret(RET_ERRNO(errno.ENOSYS))
430
+ if brokered:
431
+ p.label("openat")
432
+ p.ld_arg(2)
433
+ p.jset(WRITE_OPEN_FLAGS, "notify")
434
+ p.ret(RET_ALLOW)
435
+ if "open" in nr:
436
+ p.label("open")
437
+ p.ld_arg(1)
438
+ p.jset(WRITE_OPEN_FLAGS, "notify")
439
+ p.ret(RET_ALLOW)
440
+ p.label("notify")
441
+ p.ret(RET_NOTIFY)
442
+ p.label("ioctl")
443
+ p.ld_arg(1)
444
+ for request in DENIED_IOCTLS:
445
+ p.jeq(request, "eperm")
446
+ p.ret(RET_ALLOW)
447
+ p.label("namespaces")
448
+ p.ld_arg(0)
449
+ p.jset(NAMESPACE_FLAGS, "eperm")
450
+ p.ret(RET_ALLOW)
451
+ p.label("eperm")
452
+ p.ret(RET_ERRNO(errno.EPERM))
453
+ p.label("socket")
454
+ p.ld_arg(0)
455
+ p.jeq(AF_UNIX, "unix")
456
+ p.jeq(AF_NETLINK, "netlink")
457
+ p.jeq(AF_INET, "inet")
458
+ p.jeq(AF_INET6, "inet")
459
+ p.ret(RET_ERRNO(errno.EAFNOSUPPORT))
460
+ p.label("netlink")
461
+ p.ld_arg(2)
462
+ p.jeq(0, "allow") # NETLINK_ROUTE only: interface queries, no egress
463
+ p.ret(RET_ERRNO(errno.EACCES))
464
+ p.label("socketpair")
465
+ # A datagram socketpair honours an explicit sendto() address: connection-oriented only.
466
+ p.ld_arg(0)
467
+ p.jeq(AF_UNIX, "pair_unix")
468
+ p.ret(RET_ERRNO(errno.EACCES))
469
+ p.label("pair_unix")
470
+ p.ld_arg(1)
471
+ p.alu_and(0xF)
472
+ p.jeq(SOCK_STREAM, "allow")
473
+ p.jeq(SOCK_SEQPACKET, "allow")
474
+ p.ret(RET_ERRNO(errno.EACCES))
475
+ p.label("unix")
476
+ # Connection-oriented UNIX sockets only, created by the broker so it can mediate their
477
+ # pathname connect/bind; datagram and raw (which the kernel maps to datagram) are refused.
478
+ p.ld_arg(1)
479
+ p.alu_and(0xF)
480
+ p.jeq(SOCK_STREAM, "inet")
481
+ p.jeq(SOCK_SEQPACKET, "inet")
482
+ p.ret(RET_ERRNO(errno.EACCES))
483
+ p.label("inet")
484
+ p.ret(notify)
485
+ if network_mediated:
486
+ p.label("fastopen3")
487
+ p.ld_arg(3)
488
+ p.jset(MSG_FASTOPEN, "eacces")
489
+ p.ret(RET_ALLOW)
490
+ p.label("fastopen2")
491
+ p.ld_arg(2)
492
+ p.jset(MSG_FASTOPEN, "eacces")
493
+ p.ret(RET_ALLOW)
494
+ p.label("eacces")
495
+ p.ret(RET_ERRNO(errno.EACCES))
496
+ p.label("allow")
497
+ p.ret(RET_ALLOW)
498
+ return p.assemble()
499
+
500
+
501
+ def install_filter(table, program, listener):
502
+ buffer = ctypes.create_string_buffer(program, len(program))
503
+ fprog = struct.pack("HxxxxxxQ", len(program) // 8, ctypes.addressof(buffer))
504
+ fprog_buffer = ctypes.create_string_buffer(fprog, len(fprog))
505
+ flags = 8 if listener else 0 # SECCOMP_FILTER_FLAG_NEW_LISTENER
506
+ return syscall(table["seccomp"], 1, flags, fprog_buffer)
507
+
508
+
509
+ # ---- roots and Landlock -------------------------------------------------------------------
510
+
511
+ def verify_roots(native, request):
512
+ """Validates pinned descriptors against their recorded identity without reopening paths.
513
+ Read and write roots are directories; a file root (readFiles, exec mode only) is a regular
514
+ file whose descriptor the consumer opened O_PATH | O_NOFOLLOW, so a symbolic link, directory,
515
+ FIFO, socket or device given as a file root is refused here, as is a wrong recorded identity.
516
+ A file root whose pinned file no longer sits at its path (renamed or deleted since the pin:
517
+ editors and atomic saves do this) or has more than one name (a hard link could share a denied
518
+ file's inode) is skipped: no rule, no refusal, the path stays unreadable."""
519
+ result = {"read": [], "write": [], "readFiles": []}
520
+ seen = []
521
+ if request.get("roots", {}).get("readFiles") and request.get("mode") != "exec":
522
+ raise Refused("INVALID_REQUEST", "File roots serve exec mode only")
523
+ for kind in ("read", "write", "readFiles"):
524
+ for entry in request.get("roots", {}).get(kind, []):
525
+ path, fd = entry.get("path"), entry.get("fd")
526
+ if not isinstance(path, str) or type(fd) is not int or not native.valid_path(path) \
527
+ or os.path.normpath(path) != path:
528
+ raise Refused("INVALID_REQUEST", "Supply canonical roots with pinned descriptors")
529
+ try:
530
+ info = os.fstat(fd)
531
+ where = os.readlink("/proc/self/fd/%d" % fd)
532
+ except OSError:
533
+ raise Refused("ROOT_CHANGED", "A pinned root descriptor is not available")
534
+ identity = [entry.get("dev"), entry.get("ino")]
535
+ os.set_inheritable(fd, False)
536
+ if kind == "readFiles":
537
+ if not stat.S_ISREG(info.st_mode):
538
+ raise Refused("ROOT_CHANGED", "A pinned file root is not a regular file")
539
+ if identity != [info.st_dev, info.st_ino]:
540
+ raise Refused("ROOT_CHANGED", "A pinned root no longer names its recorded object")
541
+ if where != path or info.st_nlink != 1:
542
+ # renamed, deleted or given a second name since the pin: grant nothing for it
543
+ continue
544
+ elif not stat.S_ISDIR(info.st_mode) or identity != [info.st_dev, info.st_ino] \
545
+ or where != path:
546
+ raise Refused("ROOT_CHANGED", "A pinned root no longer names its recorded object")
547
+ result[kind].append({"path": path, "fd": fd})
548
+ seen.append({"kind": kind, "path": path, "fd": fd, "dev": info.st_dev,
549
+ "ino": info.st_ino})
550
+ if not result["write"]:
551
+ raise Refused("INVALID_REQUEST", "Restricted execution needs at least one write root")
552
+ return result, seen
553
+
554
+
555
+ def landlock_ruleset(roots, system_roots, network_mediated, brokered_writes=False):
556
+ attr = struct.pack("QQQ", FS_ALL, NET_MEDIATED if network_mediated else 0, SCOPE_ALL)
557
+ attr_buffer = ctypes.create_string_buffer(attr, len(attr))
558
+ ruleset = syscall(NR_LANDLOCK_CREATE, attr_buffer, len(attr), 0)
559
+ os.set_inheritable(ruleset, False)
560
+
561
+ def rule(fd, access):
562
+ data = struct.pack("<Qi", access, fd)
563
+ syscall(NR_LANDLOCK_ADD, ruleset, 1, ctypes.create_string_buffer(data, len(data)), 0)
564
+
565
+ # The rules use the caller's pinned descriptors themselves.
566
+ for root in roots["read"]:
567
+ rule(root["fd"], FS_READ)
568
+ for root in roots["write"]:
569
+ # Brokered: the command reads its write roots; the broker performs every write.
570
+ rule(root["fd"], FS_READ if brokered_writes else FS_ALL)
571
+ for root in roots["readFiles"]:
572
+ # The file's own inode, read only: no READ_DIR (a file has no listing to grant, and its
573
+ # directory gets no rule from it) and no EXECUTE.
574
+ rule(root["fd"], FS_READ_FILE)
575
+ opened = []
576
+ try:
577
+ for path in system_roots:
578
+ try:
579
+ fd = os.open(path, os.O_PATH | os.O_CLOEXEC)
580
+ except FileNotFoundError:
581
+ continue
582
+ opened.append(fd)
583
+ rule(fd, FS_READ if stat.S_ISDIR(os.fstat(fd).st_mode) else FS_READ & ~FS_READ_DIR)
584
+ for path in DEVICE_FILES:
585
+ try:
586
+ fd = os.open(path, os.O_PATH | os.O_CLOEXEC)
587
+ except OSError:
588
+ continue
589
+ opened.append(fd)
590
+ if stat.S_ISCHR(os.fstat(fd).st_mode):
591
+ rule(fd, FS_DEVICE)
592
+ finally:
593
+ for fd in opened:
594
+ os.close(fd)
595
+ return ruleset
596
+
597
+
598
+ # ---- broker -------------------------------------------------------------------------------
599
+
600
+ class Denied(Exception):
601
+ pass
602
+
603
+
604
+ def socket_option(fd, level, name, size=4):
605
+ value = ctypes.create_string_buffer(size)
606
+ length = ctypes.c_uint32(size)
607
+ if libc.getsockopt(fd, level, name, value, ctypes.byref(length)) < 0:
608
+ code = ctypes.get_errno()
609
+ raise OSError(code, os.strerror(code))
610
+ return value.raw[:length.value]
611
+
612
+
613
+ def socket_domain(fd):
614
+ return struct.unpack("i", socket_option(fd, SOL_SOCKET, SO_DOMAIN))[0]
615
+
616
+
617
+ def socket_address(fd):
618
+ """The bound (IP address, port) of a broker-owned socket ((0.0.0.0 / ::, 0) when unbound)."""
619
+ buffer = ctypes.create_string_buffer(128)
620
+ length = ctypes.c_uint32(128)
621
+ if libc.getsockname(fd, buffer, ctypes.byref(length)) < 0:
622
+ code = ctypes.get_errno()
623
+ raise OSError(code, os.strerror(code))
624
+ raw = buffer.raw[:length.value]
625
+ family = struct.unpack("H", raw[:2])[0]
626
+ port = struct.unpack(">H", raw[2:4])[0]
627
+ if family == AF_INET:
628
+ return str(ipaddress.ip_address(raw[4:8])), port
629
+ if family == AF_INET6:
630
+ return str(ipaddress.ip_address(raw[8:24])), port
631
+ return None, None
632
+
633
+
634
+ def socket_name(fd):
635
+ """The bound IP address of a broker-owned socket (0.0.0.0 / :: when unbound)."""
636
+ return socket_address(fd)[0]
637
+
638
+
639
+ def socket_int(fd, name):
640
+ return struct.unpack("i", socket_option(fd, SOL_SOCKET, name))[0]
641
+
642
+
643
+ def add_write_denies(paths, *modules):
644
+ """Absolute write denies the consumer resolved for this operation (a protected home location
645
+ reached through a link, at its resolved target): denied with everything beneath them, and
646
+ guarded against a prepared directory or a link moved onto a proper prefix, exactly like
647
+ SYSTEM_WRITE_DENIES. Extends the policy of this process and of the given modules (one
648
+ operation per launcher process)."""
649
+ if not isinstance(paths, list) or not all(
650
+ isinstance(p, str) and p.startswith("/") and os.path.normpath(p) == p for p in paths):
651
+ raise Refused("INVALID_REQUEST", "Supply absolute normalized write denies")
652
+ folded = [_fold_parts(p) for p in paths]
653
+ for policy in (globals(),) + tuple(vars(m) for m in modules):
654
+ if "SYSTEM_WRITE_DENIES" in policy and "PREFIX_GUARDED" in policy:
655
+ policy["SYSTEM_WRITE_DENIES"].extend(folded)
656
+ policy["PREFIX_GUARDED"].extend((names, True) for names in folded)
657
+
658
+
659
+ class SharedLock:
660
+ """Many shared holders or one exclusive holder. New shared holders are not held back by a
661
+ waiting exclusive one: a shared holder may wait long (a FIFO open waiting for its peer)."""
662
+
663
+ def __init__(self):
664
+ self.condition = threading.Condition()
665
+ self.readers = 0
666
+ self.writer = False
667
+
668
+ @contextlib.contextmanager
669
+ def shared(self):
670
+ with self.condition:
671
+ while self.writer:
672
+ self.condition.wait()
673
+ self.readers += 1
674
+ try:
675
+ yield
676
+ finally:
677
+ with self.condition:
678
+ self.readers -= 1
679
+ self.condition.notify_all()
680
+
681
+ @contextlib.contextmanager
682
+ def exclusive(self, timeout):
683
+ """Raises EBUSY when the shared holders do not leave within timeout seconds."""
684
+ deadline = time.monotonic() + timeout
685
+ with self.condition:
686
+ while self.writer or self.readers:
687
+ left = deadline - time.monotonic()
688
+ if left <= 0:
689
+ raise OSError(errno.EBUSY, "The operation's other writes did not finish")
690
+ self.condition.wait(left)
691
+ self.writer = True
692
+ try:
693
+ yield
694
+ finally:
695
+ with self.condition:
696
+ self.writer = False
697
+ self.condition.notify_all()
698
+
699
+
700
+ class NeedsExclusive(Exception):
701
+ """A directory move into a guarded prefix: redone holding the files lock exclusively."""
702
+
703
+
704
+ class Broker:
705
+ def __init__(self, native, roots, table, endpoints, listener, files_lock=None):
706
+ self.native = native
707
+ self.files = native.NativeFiles(roots)
708
+ self.names = {number: name for name, number in dict(table["nr"], **COMMON).items()}
709
+ self.endpoints = endpoints
710
+ self.listener = listener
711
+ self.sockets = {}
712
+ # (st_dev, st_ino) of every pathname UNIX socket this operation bound through the broker:
713
+ # the only sockets a pathname connect may reach. A socket another process made, even one
714
+ # inside a write root (a user D-Bus, a rootless docker.sock, ssh-agent, tmux), stays
715
+ # unreachable, as no sandboxed client connects to a foreign loopback listener either.
716
+ self.unix_bound = set()
717
+ self.lock = threading.Lock()
718
+ # Every mutating file operation holds this shared; a directory move into a guarded prefix
719
+ # holds it exclusively (staging, listing and the final rename). With the consumer's
720
+ # "filesLockFd" it is the device's lock, so the exclusion spans every operation of the
721
+ # device; without one it spans this operation only.
722
+ self.files_lock = files_lock or SharedLock()
723
+ # A failure the broker could not undo: the supervisor ends the operation and reports it.
724
+ self.fatal = None
725
+ # A test fixture's injected faults (request "faultInjection"); never set in production:
726
+ # fault "fail" fails a staged move; pause_mkdir names a mkdir that, once checked, marks its
727
+ # parent (PAUSE_MARKER) and waits PAUSE_S before its effect.
728
+ self.fault = None
729
+ self.pause_mkdir = None
730
+ self.counts = {}
731
+ # Creation modes are the command's (its umask is applied explicitly), never the broker's.
732
+ os.umask(0)
733
+
734
+ # Target memory and descriptors are opened first and then checked with ID_VALID, so a
735
+ # recycled PID can never be read in place of the notifying task.
736
+ def valid(self, ident):
737
+ value = ctypes.c_uint64(ident)
738
+ try:
739
+ ioctl(self.listener, NOTIF_ID_VALID, ctypes.byref(value))
740
+ return True
741
+ except OSError:
742
+ return False
743
+
744
+ def memory(self, pid, ident):
745
+ fd = os.open("/proc/%d/mem" % pid, os.O_RDONLY | os.O_CLOEXEC)
746
+ if not self.valid(ident):
747
+ os.close(fd)
748
+ raise OSError(errno.ESRCH, "Target exited")
749
+ return fd
750
+
751
+ @staticmethod
752
+ def read(mem, address, size):
753
+ try:
754
+ data = os.pread(mem, size, address)
755
+ except OSError:
756
+ raise OSError(errno.EFAULT, "Bad address")
757
+ if len(data) != size:
758
+ raise OSError(errno.EFAULT, "Bad address")
759
+ return data
760
+
761
+ @staticmethod
762
+ def string(mem, address, limit=4096):
763
+ if address == 0:
764
+ raise OSError(errno.EFAULT, "Bad address")
765
+ out = bytearray()
766
+ while len(out) < limit:
767
+ chunk = 4096 - (address + len(out)) % 4096
768
+ try:
769
+ data = os.pread(mem, min(chunk, limit - len(out)), address + len(out))
770
+ except OSError:
771
+ raise OSError(errno.EFAULT, "Bad address")
772
+ if not data:
773
+ raise OSError(errno.EFAULT, "Bad address")
774
+ end = data.find(b"\0")
775
+ if end >= 0:
776
+ return bytes(out + data[:end])
777
+ out += data
778
+ raise OSError(errno.ENAMETOOLONG, "Path too long")
779
+
780
+ def target_link(self, pid, ident, name):
781
+ value = os.readlink("/proc/%d/%s" % (pid, name))
782
+ if not self.valid(ident):
783
+ raise OSError(errno.ESRCH, "Target exited")
784
+ return self.rebase(value)
785
+
786
+ def rebase(self, path):
787
+ """A location the kernel reports (a cwd, a descriptor) in terms of the pinned roots'
788
+ recorded paths: a root renamed during the operation keeps its grant, as in Landlock,
789
+ and resolution continues from its pinned descriptor."""
790
+ if not path.startswith("/"):
791
+ return path
792
+ best = None
793
+ for root in self.files.roots["read"] + self.files.roots["write"]:
794
+ try:
795
+ now = os.readlink("/proc/self/fd/%d" % root["fd"])
796
+ except OSError:
797
+ continue
798
+ if now == path or path.startswith(now.rstrip("/") + "/"):
799
+ if best is None or len(now) > best[0]:
800
+ best = (len(now), root["path"].rstrip("/") + path[len(now.rstrip("/")):])
801
+ return best[1] if best else path
802
+
803
+ # Every mutation is applied to an O_PATH descriptor resolved from the pinned write roots by
804
+ # the native helper's own no-follow traversal, never to a string the target can change.
805
+ def resolve(self, path, follow):
806
+ if not path.startswith("/"):
807
+ raise Denied()
808
+ path = os.path.normpath(path)
809
+ try:
810
+ if follow:
811
+ parent, name, _, _ = self.files.resolve(path, True, False, 0, True)
812
+ else:
813
+ head, name = os.path.split(path)
814
+ if not name:
815
+ parent, name, _, _ = self.files.resolve(path, True, False, 0, True)
816
+ else:
817
+ dparent, dname, _, _ = self.files.resolve(head, True, False, 0, True)
818
+ try:
819
+ parent = os.open(dname, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
820
+ | os.O_CLOEXEC, dir_fd=dparent)
821
+ finally:
822
+ os.close(dparent)
823
+ except self.native.ScopeDenied:
824
+ raise Denied()
825
+ except ValueError:
826
+ raise Denied()
827
+ try:
828
+ return os.open(name, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent)
829
+ finally:
830
+ os.close(parent)
831
+
832
+ def in_scope(self, obj):
833
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % obj))
834
+ if not where.startswith("/") or where.endswith(" (deleted)"):
835
+ raise Denied()
836
+ candidate = self.resolve(where, False)
837
+ try:
838
+ a, b = os.fstat(obj), os.fstat(candidate)
839
+ finally:
840
+ os.close(candidate)
841
+ if (a.st_dev, a.st_ino) != (b.st_dev, b.st_ino):
842
+ raise Denied()
843
+
844
+ def object(self, pid, ident, mem, dirfd, address, flags, follow_default=True):
845
+ """The O_PATH object a metadata change applies to; a mandatory write deny is refused."""
846
+ obj = self.object_unchecked(pid, ident, mem, dirfd, address, flags, follow_default)
847
+ try:
848
+ if write_denied(self.rebase(os.readlink("/proc/self/fd/%d" % obj))):
849
+ raise Denied()
850
+ except BaseException:
851
+ os.close(obj)
852
+ raise
853
+ return obj
854
+
855
+ def object_unchecked(self, pid, ident, mem, dirfd, address, flags, follow_default=True):
856
+ dirfd = ctypes.c_int32(dirfd & 0xFFFFFFFF).value
857
+ follow = follow_default and not (flags & AT_SYMLINK_NOFOLLOW)
858
+ path = None if address == 0 else os.fsdecode(self.string(mem, address))
859
+ if path is None or (path == "" and flags & AT_EMPTY_PATH):
860
+ if dirfd == AT_FDCWD:
861
+ link = "cwd"
862
+ elif dirfd >= 0:
863
+ link = "fd/%d" % dirfd
864
+ else:
865
+ raise OSError(errno.EBADF, "Bad descriptor")
866
+ obj = os.open("/proc/%d/%s" % (pid, link), os.O_PATH | os.O_CLOEXEC)
867
+ if not self.valid(ident):
868
+ os.close(obj)
869
+ raise OSError(errno.ESRCH, "Target exited")
870
+ try:
871
+ self.in_scope(obj)
872
+ except BaseException:
873
+ os.close(obj)
874
+ raise
875
+ return obj
876
+ if path == "":
877
+ raise OSError(errno.ENOENT, "Empty path")
878
+ if not path.startswith("/"):
879
+ if dirfd == AT_FDCWD:
880
+ base = self.target_link(pid, ident, "cwd")
881
+ elif dirfd >= 0:
882
+ base = self.target_link(pid, ident, "fd/%d" % dirfd)
883
+ else:
884
+ raise OSError(errno.EBADF, "Bad descriptor")
885
+ if not base.startswith("/") or base.endswith(" (deleted)"):
886
+ raise Denied()
887
+ path = base.rstrip("/") + "/" + path
888
+ return self.resolve(path, follow)
889
+
890
+ def apply_path(self, obj, op):
891
+ return op("/proc/self/fd/%d" % obj)
892
+
893
+ def handle(self, ident, pid, nr, args):
894
+ name = self.names.get(nr)
895
+ with self.lock:
896
+ self.counts[name] = self.counts.get(name, 0) + 1
897
+ mem = None
898
+ try:
899
+ if name == "socket":
900
+ return self.socket(ident, args)
901
+ if name == "listen":
902
+ return self.listen(ident, pid, args)
903
+ mem = self.memory(pid, ident)
904
+ if name == "connect":
905
+ return self.connect(ident, pid, mem, args)
906
+ try:
907
+ with self.files_lock.shared():
908
+ if name in FILE_OPS:
909
+ return self.file_op(ident, pid, mem, name, args)
910
+ if name == "bind":
911
+ return self.bind(ident, pid, mem, args)
912
+ return self.metadata(ident, pid, mem, name, args)
913
+ except NeedsExclusive:
914
+ with self.files_lock.exclusive(EXCLUSIVE_WAIT_S):
915
+ return self.file_op(ident, pid, mem, name, args, exclusive=True)
916
+ except Denied:
917
+ return None, errno.EACCES
918
+ except OSError as error:
919
+ return None, error.errno or errno.EACCES
920
+ finally:
921
+ if mem is not None:
922
+ os.close(mem)
923
+
924
+ def metadata(self, ident, pid, mem, name, args):
925
+ if name in ("chmod", "fchmodat", "fchmodat2", "fchmod"):
926
+ if name == "chmod":
927
+ dirfd, address, mode, flags = AT_FDCWD, args[0], args[1], 0
928
+ elif name == "fchmod":
929
+ dirfd, address, mode, flags = args[0], 0, args[1], AT_EMPTY_PATH
930
+ else:
931
+ dirfd, address, mode = args[0], args[1], args[2]
932
+ flags = args[3] if name == "fchmodat2" else 0
933
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
934
+ return None, errno.EINVAL
935
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
936
+ try:
937
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
938
+ return None, errno.EOPNOTSUPP
939
+ self.apply_path(obj, lambda p: os.chmod(p, mode & 0o7777))
940
+ finally:
941
+ os.close(obj)
942
+ return 0, 0
943
+ if name in ("chown", "lchown", "fchownat", "fchown"):
944
+ if name in ("chown", "lchown"):
945
+ dirfd, address, owner, group = AT_FDCWD, args[0], args[1], args[2]
946
+ flags = AT_SYMLINK_NOFOLLOW if name == "lchown" else 0
947
+ elif name == "fchown":
948
+ dirfd, address, owner, group, flags = args[0], 0, args[1], args[2], AT_EMPTY_PATH
949
+ else:
950
+ dirfd, address, owner, group, flags = args[:5]
951
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
952
+ return None, errno.EINVAL
953
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
954
+ try:
955
+ if libc.fchownat(obj, b"", ctypes.c_uint32(owner & 0xFFFFFFFF),
956
+ ctypes.c_uint32(group & 0xFFFFFFFF), AT_EMPTY_PATH) < 0:
957
+ return None, ctypes.get_errno()
958
+ finally:
959
+ os.close(obj)
960
+ return 0, 0
961
+ if name == "utimensat":
962
+ dirfd, address, times, flags = args[0], args[1], args[2], args[3]
963
+ if flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH):
964
+ return None, errno.EINVAL
965
+ value = None if times == 0 else self.read(mem, times, 32)
966
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
967
+ try:
968
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
969
+ return None, errno.EOPNOTSUPP
970
+ buffer = None if value is None else ctypes.create_string_buffer(value, 32)
971
+ if libc.utimensat(AT_FDCWD, os.fsencode("/proc/self/fd/%d" % obj), buffer, 0) < 0:
972
+ return None, ctypes.get_errno()
973
+ finally:
974
+ os.close(obj)
975
+ return 0, 0
976
+ if name in ("setxattr", "lsetxattr", "fsetxattr", "removexattr", "lremovexattr",
977
+ "fremovexattr"):
978
+ fd_based = name.startswith("f")
979
+ nofollow = name.startswith("l")
980
+ address = 0 if fd_based else args[0]
981
+ dirfd = args[0] if fd_based else AT_FDCWD
982
+ flags = AT_EMPTY_PATH if fd_based else (AT_SYMLINK_NOFOLLOW if nofollow else 0)
983
+ attribute = self.string(mem, args[1], 256)
984
+ if name.endswith("setxattr"):
985
+ size = args[3]
986
+ if size > 65536:
987
+ return None, errno.E2BIG
988
+ value = self.read(mem, args[2], size) if size else b""
989
+ obj = self.object(pid, ident, mem, dirfd, address, flags)
990
+ try:
991
+ if stat.S_ISLNK(os.fstat(obj).st_mode):
992
+ return None, errno.EPERM
993
+ target = "/proc/self/fd/%d" % obj
994
+ if name.endswith("setxattr"):
995
+ os.setxattr(target, attribute, value, args[4] & 0xFFFFFFFF)
996
+ else:
997
+ os.removexattr(target, attribute)
998
+ finally:
999
+ os.close(obj)
1000
+ return 0, 0
1001
+ return None, errno.ENOSYS
1002
+
1003
+ # ---- brokered filesystem writes ---------------------------------------------------------
1004
+ # The command's path is copied once; every step after that works on the broker's own
1005
+ # descriptors (pinned roots, no-follow traversal) and the deny check applies to the broker's
1006
+ # resolution, so nothing the command changes afterwards can redirect a write.
1007
+
1008
+ def umask_of(self, pid, ident):
1009
+ with open("/proc/%d/status" % pid) as handle:
1010
+ text = handle.read()
1011
+ if not self.valid(ident):
1012
+ raise OSError(errno.ESRCH, "Target exited")
1013
+ for line in text.splitlines():
1014
+ if line.startswith("Umask:"):
1015
+ return int(line.split()[1], 8)
1016
+ return 0o022
1017
+
1018
+ def path_arg(self, pid, ident, mem, dirfd, address):
1019
+ dirfd = ctypes.c_int32(dirfd & 0xFFFFFFFF).value
1020
+ path = os.fsdecode(self.string(mem, address))
1021
+ if path == "":
1022
+ raise OSError(errno.ENOENT, "Empty path")
1023
+ if not path.startswith("/"):
1024
+ if dirfd == AT_FDCWD:
1025
+ base = self.target_link(pid, ident, "cwd")
1026
+ elif dirfd >= 0:
1027
+ base = self.target_link(pid, ident, "fd/%d" % dirfd)
1028
+ else:
1029
+ raise OSError(errno.EBADF, "Bad descriptor")
1030
+ if not base.startswith("/") or base.endswith(" (deleted)"):
1031
+ raise Denied()
1032
+ path = base.rstrip("/") + "/" + path
1033
+ return path
1034
+
1035
+ def entry(self, path):
1036
+ """(parent descriptor, final name, resolved path) of path's last component, unfollowed.
1037
+ The parent is resolved inside the pinned write roots, following in-scope links."""
1038
+ path = os.path.normpath(path)
1039
+ head, name = os.path.split(path)
1040
+ if not name or name in (".", ".."):
1041
+ raise OSError(errno.EBUSY, "Not an entry")
1042
+ try:
1043
+ dparent, dname, resolved, _ = self.files.resolve(head, True, False, 0, True)
1044
+ try:
1045
+ parent = os.open(dname, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
1046
+ | os.O_CLOEXEC, dir_fd=dparent)
1047
+ finally:
1048
+ os.close(dparent)
1049
+ except (self.native.ScopeDenied, ValueError):
1050
+ raise Denied()
1051
+ return parent, name, resolved.rstrip("/") + "/" + name
1052
+
1053
+ def followed(self, path):
1054
+ """entry() after following final in-scope links (a dangling one names its target)."""
1055
+ parent, name, resolved = self.entry(path)
1056
+ for _ in range(40):
1057
+ try:
1058
+ info = os.stat(name, dir_fd=parent, follow_symlinks=False)
1059
+ except FileNotFoundError:
1060
+ return parent, name, resolved
1061
+ if not stat.S_ISLNK(info.st_mode):
1062
+ return parent, name, resolved
1063
+ target = os.readlink(name, dir_fd=parent)
1064
+ os.close(parent)
1065
+ parent, name, resolved = self.entry(
1066
+ os.path.join(os.path.dirname(resolved), target))
1067
+ os.close(parent)
1068
+ raise OSError(errno.ELOOP, "Too many links")
1069
+
1070
+ @staticmethod
1071
+ def refuse(resolved, name, creates_entry=False):
1072
+ if write_denied(resolved):
1073
+ raise Denied()
1074
+ # a non-directory named .git is a gitdir pointer to configuration written elsewhere
1075
+ if creates_entry and _fold_parts(name) == [".git"]:
1076
+ raise Denied()
1077
+
1078
+ # ---- post-effect verification ------------------------------------------------------------
1079
+ # A write is checked on the path its parent descriptor had, then applied through that
1080
+ # descriptor. The device's files lock keeps every sandboxed guarded move out of that window,
1081
+ # but a process outside the sandbox can still move the parent meanwhile. So after each
1082
+ # descriptor-relative create or rename the broker reads where the parent sits now and, when
1083
+ # the entry landed at a denied path, undoes the effect and refuses; an effect it cannot undo
1084
+ # ends the operation (fail).
1085
+
1086
+ def placed(self, parent, name):
1087
+ """name below the parent descriptor, at the parent's current path (rebased onto the
1088
+ pinned roots' recorded paths); None when the parent is no longer reachable."""
1089
+ try:
1090
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % parent))
1091
+ except OSError:
1092
+ return None
1093
+ if not where.startswith("/") or where.endswith(" (deleted)"):
1094
+ return None
1095
+ return where.rstrip("/") + "/" + name
1096
+
1097
+ def verify(self, denied, undo, what):
1098
+ """Undoes an applied effect and refuses it when denied() says it landed somewhere denied
1099
+ (denied reads the entry's current place); an undo that fails ends the operation."""
1100
+ try:
1101
+ if not denied():
1102
+ return
1103
+ except Denied:
1104
+ pass
1105
+ try:
1106
+ undo()
1107
+ except OSError as error:
1108
+ self.fail("%s landed at a protected path after its check and could not be undone (%s)"
1109
+ % (what, error.strerror))
1110
+ raise Denied()
1111
+
1112
+ def created_denied(self, parent, name, creates_entry=False, link=False):
1113
+ """Whether the entry name below parent now sits at a path the write policy denies."""
1114
+ now = self.placed(parent, name)
1115
+ if now is None:
1116
+ return False
1117
+ if write_denied(now) or (creates_entry and _fold_parts(name) == [".git"]):
1118
+ return True
1119
+ return link and bool(_prefix_next(_fold_parts(now)))
1120
+
1121
+ @staticmethod
1122
+ def remove_own(parent, name, ident, is_dir=False):
1123
+ """Removes the entry the broker just made (ident: its (st_dev, st_ino)), never another."""
1124
+ info = os.stat(name, dir_fd=parent, follow_symlinks=False)
1125
+ if (info.st_dev, info.st_ino) != ident:
1126
+ raise OSError(errno.ESTALE, "The created entry was replaced")
1127
+ if is_dir:
1128
+ os.rmdir(name, dir_fd=parent)
1129
+ else:
1130
+ os.unlink(name, dir_fd=parent)
1131
+
1132
+ @staticmethod
1133
+ def identity(parent, name):
1134
+ info = os.stat(name, dir_fd=parent, follow_symlinks=False)
1135
+ return info.st_dev, info.st_ino
1136
+
1137
+ def moved_denied(self, sparent, sname, dparent, dname, kinds):
1138
+ """Whether a rename, judged at its parents' current places, broke the write policy:
1139
+ kinds lists ((parent, name), is_dir) of each entry that moved, by its source."""
1140
+ source, destination = self.placed(sparent, sname), self.placed(dparent, dname)
1141
+ if source is None or destination is None:
1142
+ return False
1143
+ ends = {(sparent, sname): (source, destination), (dparent, dname): (destination, source)}
1144
+ for key, is_dir in kinds:
1145
+ origin, to = ends[key]
1146
+ # an unstaged directory landing at a guarded place was never listed there
1147
+ if move_denied(origin, to, is_dir) or (is_dir and _prefix_next(_fold_parts(to))):
1148
+ return True
1149
+ return write_denied(source) or write_denied(destination)
1150
+
1151
+ @staticmethod
1152
+ def move_back(sparent, sname, dparent, dname, flags):
1153
+ """Reverses a rename: an exchange is exchanged again, a move moved back (never replacing)."""
1154
+ back = RENAME_EXCHANGE if flags & RENAME_EXCHANGE else RENAME_NOREPLACE
1155
+ if libc.renameat2(dparent, os.fsencode(dname), sparent, os.fsencode(sname),
1156
+ ctypes.c_uint(back)) < 0:
1157
+ code = ctypes.get_errno()
1158
+ raise OSError(code, os.strerror(code))
1159
+
1160
+ def staged_move(self, sparent, sname, dparent, dname, origin, to):
1161
+ """A directory move into a guarded place (a proper prefix of a multi-component deny). The
1162
+ directory is first renamed to a fresh reserved staging name beside it, which the write
1163
+ policy denies to every sandboxed write, so no process of this or another operation can add
1164
+ the guarded next component while it is listed and checked there; it is then renamed into
1165
+ place with NOREPLACE. A refused or failed step moves it back to its source; when that
1166
+ fails too (its name was taken meanwhile) it goes to a quarantine name, also reserved, and
1167
+ the operation ends with the failure reported."""
1168
+ fault = self.fault == "fail"
1169
+ stage = RESERVED_NAME_PREFIX + os.urandom(8).hex()
1170
+ if libc.renameat2(sparent, os.fsencode(sname), sparent, os.fsencode(stage),
1171
+ ctypes.c_uint(RENAME_NOREPLACE)) < 0:
1172
+ return None, ctypes.get_errno()
1173
+ entries = self.listing(sparent, stage)
1174
+ if entries is None or move_denied(origin, to, True, entries):
1175
+ code = errno.EACCES
1176
+ elif fault:
1177
+ code = errno.EIO
1178
+ elif libc.renameat2(sparent, os.fsencode(stage), dparent, os.fsencode(dname),
1179
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0:
1180
+ def placed_denied():
1181
+ now = self.placed(dparent, dname)
1182
+ return now is not None and move_denied(origin, now, True,
1183
+ self.listing(dparent, dname))
1184
+ self.verify(placed_denied,
1185
+ lambda: self.move_back(sparent, sname, dparent, dname, 0), "A moved directory")
1186
+ return 0, 0
1187
+ else:
1188
+ code = ctypes.get_errno()
1189
+ if not fault and libc.renameat2(sparent, os.fsencode(stage), sparent, os.fsencode(sname),
1190
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0:
1191
+ return None, code
1192
+ quarantine = RESERVED_NAME_PREFIX + "quarantine-" + os.urandom(8).hex()
1193
+ moved = libc.renameat2(sparent, os.fsencode(stage), sparent, os.fsencode(quarantine),
1194
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0
1195
+ try:
1196
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % sparent))
1197
+ except OSError:
1198
+ where = os.path.dirname(origin)
1199
+ self.fail("A directory bound for %s could be moved neither into place nor back; it is in "
1200
+ "quarantine as %s" % (to, os.path.join(where, quarantine if moved else stage)))
1201
+ return None, code
1202
+
1203
+ @staticmethod
1204
+ def pause(parent):
1205
+ """The test seam's pause between a write's check and its effect, announced by a marker
1206
+ the broker creates in the parent it holds."""
1207
+ os.close(os.open(PAUSE_MARKER, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o644,
1208
+ dir_fd=parent))
1209
+ time.sleep(PAUSE_S)
1210
+
1211
+ def fail(self, message):
1212
+ """Ends the operation for a failure the broker could not undo: the supervisor kills the
1213
+ whole tree (as for a cancel) and reports the message in its exit event."""
1214
+ if self.fatal is None:
1215
+ self.fatal = message
1216
+ os.kill(os.getpid(), signal.SIGTERM)
1217
+
1218
+ @staticmethod
1219
+ def listing(parent, name):
1220
+ """The names in the directory name below parent, opened without following a link; None
1221
+ when it cannot be listed."""
1222
+ try:
1223
+ fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC,
1224
+ dir_fd=parent)
1225
+ except OSError:
1226
+ return None
1227
+ try:
1228
+ return os.listdir(fd)
1229
+ except OSError:
1230
+ return None
1231
+ finally:
1232
+ os.close(fd)
1233
+
1234
+ def send_fd(self, ident, fd, cloexec):
1235
+ data = struct.pack("QIIII", ident, ADDFD_SEND, fd, 0, os.O_CLOEXEC if cloexec else 0)
1236
+ buffer = ctypes.create_string_buffer(data, len(data))
1237
+ if libc.ioctl(self.listener, NOTIF_ADDFD, buffer) < 0:
1238
+ return None, ctypes.get_errno()
1239
+ return "sent", 0
1240
+
1241
+ def special_open(self, ident, pid, path, flags):
1242
+ """Device files and the command's own descriptors outside the roots, or None."""
1243
+ reopen = flags & ~(os.O_CREAT | os.O_EXCL | O_TMPFILE_BIT) | os.O_CLOEXEC
1244
+ if path == "/dev/tty":
1245
+ raise OSError(errno.ENXIO, "No controlling terminal")
1246
+ if path in DEVICE_FILES:
1247
+ fd = os.open(path, reopen | os.O_NOFOLLOW)
1248
+ if not stat.S_ISCHR(os.fstat(fd).st_mode):
1249
+ os.close(fd)
1250
+ raise Denied()
1251
+ return fd
1252
+ number = STD_STREAMS.get(path)
1253
+ parts = path.split("/")
1254
+ if number is None and len(parts) == 4 and parts[1] == "dev" and parts[2] == "fd":
1255
+ number = parts[3]
1256
+ elif (number is None and len(parts) == 5 and parts[1] == "proc" and parts[3] == "fd"
1257
+ and (parts[2] in ("self", "thread-self") or parts[2] == str(pid))):
1258
+ number = parts[4]
1259
+ if number is None:
1260
+ return None
1261
+ if not str(number).isdigit():
1262
+ raise OSError(errno.ENOENT, "No such descriptor")
1263
+ obj = os.open("/proc/%d/fd/%d" % (pid, int(number)), os.O_PATH | os.O_CLOEXEC)
1264
+ try:
1265
+ if not self.valid(ident):
1266
+ raise OSError(errno.ESRCH, "Target exited")
1267
+ mode = os.fstat(obj).st_mode
1268
+ if stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode) or stat.S_ISCHR(mode):
1269
+ # The command's own pipe or terminal: reopening it widens nothing.
1270
+ return os.open("/proc/self/fd/%d" % obj, reopen)
1271
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % obj))
1272
+ finally:
1273
+ os.close(obj)
1274
+ return where # a file: resolved like any other path
1275
+
1276
+ def open_entry(self, ident, parent, final, flags, mode):
1277
+ """Opens the resolved entry. A FIFO is opened without blocking this broker thread on a
1278
+ peer that may never come: it is retried while the notifying call is still waiting."""
1279
+ flags |= os.O_NOFOLLOW | os.O_CLOEXEC
1280
+ try:
1281
+ info = os.stat(final, dir_fd=parent, follow_symlinks=False)
1282
+ except FileNotFoundError:
1283
+ info = None
1284
+ if info is None or not stat.S_ISFIFO(info.st_mode) or flags & os.O_NONBLOCK:
1285
+ return os.open(final, flags, mode, dir_fd=parent)
1286
+ while True:
1287
+ try:
1288
+ fd = os.open(final, flags | os.O_NONBLOCK, mode, dir_fd=parent)
1289
+ except OSError as error:
1290
+ if error.errno != errno.ENXIO:
1291
+ raise
1292
+ if not self.valid(ident):
1293
+ raise OSError(errno.EINTR, "The call was abandoned")
1294
+ time.sleep(0.05)
1295
+ continue
1296
+ os.set_blocking(fd, True)
1297
+ return fd
1298
+
1299
+ def file_op(self, ident, pid, mem, name, args, exclusive=False):
1300
+ if name in ("open", "openat", "creat"):
1301
+ if name == "open":
1302
+ dirfd, address, flags, mode = AT_FDCWD, args[0], args[1], args[2]
1303
+ elif name == "openat":
1304
+ dirfd, address, flags, mode = args[0], args[1], args[2], args[3]
1305
+ else:
1306
+ dirfd, address, mode = AT_FDCWD, args[0], args[1]
1307
+ flags = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
1308
+ flags &= 0xFFFFFFFF
1309
+ path = self.path_arg(pid, ident, mem, dirfd, address)
1310
+ special = self.special_open(ident, pid, os.path.normpath(path), flags)
1311
+ if isinstance(special, int):
1312
+ try:
1313
+ return self.send_fd(ident, special, flags & os.O_CLOEXEC)
1314
+ finally:
1315
+ os.close(special)
1316
+ if isinstance(special, str):
1317
+ path = special
1318
+ umask = self.umask_of(pid, ident)
1319
+ exclusive = flags & os.O_CREAT and flags & os.O_EXCL
1320
+ if flags & O_TMPFILE_BIT or exclusive or flags & os.O_NOFOLLOW:
1321
+ parent, final, resolved = self.entry(path)
1322
+ else:
1323
+ parent, final, resolved = self.followed(path)
1324
+ tmpfile = flags & O_TMPFILE_BIT
1325
+ # truncation waits for the post-effect check (a read-only open truncates itself)
1326
+ truncate = flags & os.O_TRUNC and flags & os.O_ACCMODE != os.O_RDONLY
1327
+ try:
1328
+ self.refuse(resolved, final, not tmpfile)
1329
+ try:
1330
+ before = os.stat(final, dir_fd=parent, follow_symlinks=False)
1331
+ except FileNotFoundError:
1332
+ before = None
1333
+ fd = self.open_entry(ident, parent, final, flags & ~os.O_TRUNC if truncate
1334
+ else flags, mode & 0o7777 & ~umask)
1335
+ try:
1336
+ if tmpfile:
1337
+ # no name was made: the file vanishes with its descriptor
1338
+ self.verify(lambda: self.created_denied(parent, final),
1339
+ lambda: None, "A temporary file")
1340
+ else:
1341
+ info = os.fstat(fd)
1342
+ made = before is None and flags & os.O_CREAT
1343
+ self.verify(
1344
+ lambda: self.created_denied(parent, final, True),
1345
+ (lambda: self.remove_own(parent, final, (info.st_dev, info.st_ino)))
1346
+ if made else (lambda: None),
1347
+ "A created file" if made else "An opened file")
1348
+ if truncate and stat.S_ISREG(os.fstat(fd).st_mode):
1349
+ os.ftruncate(fd, 0)
1350
+ except BaseException:
1351
+ os.close(fd)
1352
+ raise
1353
+ finally:
1354
+ os.close(parent)
1355
+ try:
1356
+ return self.send_fd(ident, fd, flags & os.O_CLOEXEC)
1357
+ finally:
1358
+ os.close(fd)
1359
+ if name in ("mkdir", "mkdirat", "mknod", "mknodat"):
1360
+ if name in ("mkdir", "mknod"):
1361
+ dirfd, address, rest = AT_FDCWD, args[0], args[1:]
1362
+ else:
1363
+ dirfd, address, rest = args[0], args[1], args[2:]
1364
+ mode = rest[0] & 0xFFFFFFFF
1365
+ umask = self.umask_of(pid, ident)
1366
+ parent, final, resolved = self.entry(self.path_arg(pid, ident, mem, dirfd, address))
1367
+ try:
1368
+ if name.startswith("mkdir"):
1369
+ self.refuse(resolved, final)
1370
+ if self.pause_mkdir is not None and final == self.pause_mkdir:
1371
+ self.pause(parent)
1372
+ os.mkdir(final, mode & 0o7777 & ~umask, dir_fd=parent)
1373
+ made = self.identity(parent, final)
1374
+ self.verify(lambda: self.created_denied(parent, final),
1375
+ lambda: self.remove_own(parent, final, made, True), "A directory")
1376
+ else:
1377
+ kind = stat.S_IFMT(mode) or stat.S_IFREG
1378
+ if kind not in (stat.S_IFREG, stat.S_IFIFO, stat.S_IFSOCK):
1379
+ return None, errno.EPERM
1380
+ self.refuse(resolved, final, True)
1381
+ os.mknod(final, kind | (mode & 0o7777 & ~umask), 0, dir_fd=parent)
1382
+ made = self.identity(parent, final)
1383
+ self.verify(lambda: self.created_denied(parent, final, True),
1384
+ lambda: self.remove_own(parent, final, made), "A created node")
1385
+ finally:
1386
+ os.close(parent)
1387
+ return 0, 0
1388
+ if name in ("rmdir", "unlink", "unlinkat"):
1389
+ if name == "unlinkat":
1390
+ dirfd, address, flags = args[0], args[1], args[2]
1391
+ if flags & ~AT_REMOVEDIR:
1392
+ return None, errno.EINVAL
1393
+ else:
1394
+ dirfd, address = AT_FDCWD, args[0]
1395
+ flags = AT_REMOVEDIR if name == "rmdir" else 0
1396
+ parent, final, resolved = self.entry(self.path_arg(pid, ident, mem, dirfd, address))
1397
+ try:
1398
+ self.refuse(resolved, final)
1399
+ if flags & AT_REMOVEDIR:
1400
+ os.rmdir(final, dir_fd=parent)
1401
+ else:
1402
+ os.unlink(final, dir_fd=parent)
1403
+ finally:
1404
+ os.close(parent)
1405
+ return 0, 0
1406
+ if name in ("symlink", "symlinkat"):
1407
+ target = os.fsdecode(self.string(mem, args[0]))
1408
+ if name == "symlink":
1409
+ dirfd, address = AT_FDCWD, args[1]
1410
+ else:
1411
+ dirfd, address = args[1], args[2]
1412
+ parent, final, resolved = self.entry(self.path_arg(pid, ident, mem, dirfd, address))
1413
+ try:
1414
+ self.refuse(resolved, final, True)
1415
+ # a link named for a proper prefix of a multi-component deny (.config, .claude)
1416
+ # would redirect the protected entry beneath it; move_denied refuses moving one
1417
+ # there too
1418
+ if _prefix_next(_fold_parts(resolved)):
1419
+ raise Denied()
1420
+ os.symlink(target, final, dir_fd=parent)
1421
+ made = self.identity(parent, final)
1422
+ self.verify(lambda: self.created_denied(parent, final, True, link=True),
1423
+ lambda: self.remove_own(parent, final, made), "A symbolic link")
1424
+ finally:
1425
+ os.close(parent)
1426
+ return 0, 0
1427
+ if name in ("link", "linkat"):
1428
+ if name == "link":
1429
+ odir, oaddr, ndir, naddr, flags = AT_FDCWD, args[0], AT_FDCWD, args[1], 0
1430
+ else:
1431
+ odir, oaddr, ndir, naddr, flags = args[:5]
1432
+ if flags & AT_EMPTY_PATH:
1433
+ return None, errno.ENOENT # needs CAP_DAC_READ_SEARCH, which commands lack
1434
+ if flags & ~AT_SYMLINK_FOLLOW:
1435
+ return None, errno.EINVAL
1436
+ source = self.path_arg(pid, ident, mem, odir, oaddr)
1437
+ sparent, sname, sresolved = (self.followed(source) if flags & AT_SYMLINK_FOLLOW
1438
+ else self.entry(source))
1439
+ try:
1440
+ self.refuse(sresolved, sname)
1441
+ dparent, dname, dresolved = self.entry(
1442
+ self.path_arg(pid, ident, mem, ndir, naddr))
1443
+ try:
1444
+ self.refuse(dresolved, dname, True)
1445
+ if move_denied(sresolved, dresolved, False):
1446
+ raise Denied()
1447
+ os.link(sname, dname, src_dir_fd=sparent, dst_dir_fd=dparent,
1448
+ follow_symlinks=False)
1449
+ made = self.identity(dparent, dname)
1450
+
1451
+ def linked_denied():
1452
+ source_now = self.placed(sparent, sname)
1453
+ target_now = self.placed(dparent, dname)
1454
+ return self.created_denied(dparent, dname, True) or (
1455
+ source_now is not None and target_now is not None
1456
+ and move_denied(source_now, target_now, False))
1457
+ self.verify(linked_denied, lambda: self.remove_own(dparent, dname, made),
1458
+ "A hard link")
1459
+ finally:
1460
+ os.close(dparent)
1461
+ finally:
1462
+ os.close(sparent)
1463
+ return 0, 0
1464
+ if name in ("rename", "renameat", "renameat2"):
1465
+ if name == "rename":
1466
+ odir, oaddr, ndir, naddr, flags = AT_FDCWD, args[0], AT_FDCWD, args[1], 0
1467
+ elif name == "renameat":
1468
+ odir, oaddr, ndir, naddr = args[:4]
1469
+ flags = 0
1470
+ else:
1471
+ odir, oaddr, ndir, naddr, flags = args[:5]
1472
+ flags &= 0xFFFFFFFF
1473
+ if flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE):
1474
+ return None, errno.EINVAL
1475
+ sparent, sname, sresolved = self.entry(self.path_arg(pid, ident, mem, odir, oaddr))
1476
+ try:
1477
+ dparent, dname, dresolved = self.entry(
1478
+ self.path_arg(pid, ident, mem, ndir, naddr))
1479
+ try:
1480
+ self.refuse(sresolved, sname)
1481
+ self.refuse(dresolved, dname)
1482
+ moves = [((sparent, sname), sresolved, dresolved)]
1483
+ if flags & RENAME_EXCHANGE:
1484
+ moves.append(((dparent, dname), dresolved, sresolved))
1485
+ staged = None
1486
+ kinds = []
1487
+ for (parent, entry), origin, to in moves:
1488
+ try:
1489
+ info = os.stat(entry, dir_fd=parent, follow_symlinks=False)
1490
+ except FileNotFoundError:
1491
+ continue
1492
+ is_dir = stat.S_ISDIR(info.st_mode)
1493
+ kinds.append(((parent, entry), is_dir))
1494
+ if is_dir and _prefix_next(_fold_parts(to)):
1495
+ # a directory bound for a guarded place: checked in staging
1496
+ if flags & RENAME_EXCHANGE:
1497
+ raise Denied()
1498
+ if not exclusive:
1499
+ raise NeedsExclusive()
1500
+ staged = (origin, to)
1501
+ continue
1502
+ # nothing leaves a protected name, nor is a directory moved under one
1503
+ if move_denied(origin, to, is_dir):
1504
+ raise Denied()
1505
+ if staged is not None:
1506
+ return self.staged_move(sparent, sname, dparent, dname, *staged)
1507
+ if libc.renameat2(sparent, os.fsencode(sname), dparent, os.fsencode(dname),
1508
+ ctypes.c_uint(flags)) < 0:
1509
+ return None, ctypes.get_errno()
1510
+ self.verify(lambda: self.moved_denied(sparent, sname, dparent, dname, kinds),
1511
+ lambda: self.move_back(sparent, sname, dparent, dname, flags),
1512
+ "A move")
1513
+ finally:
1514
+ os.close(dparent)
1515
+ finally:
1516
+ os.close(sparent)
1517
+ return 0, 0
1518
+ if name == "truncate":
1519
+ length = ctypes.c_int64(args[1]).value
1520
+ parent, final, resolved = self.followed(self.path_arg(pid, ident, mem, AT_FDCWD,
1521
+ args[0]))
1522
+ try:
1523
+ self.refuse(resolved, final)
1524
+ fd = os.open(final, os.O_WRONLY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent)
1525
+ try:
1526
+ # checked again at the parent's current place before the effect
1527
+ self.verify(lambda: self.created_denied(parent, final), lambda: None,
1528
+ "A truncation")
1529
+ except BaseException:
1530
+ os.close(fd)
1531
+ raise
1532
+ finally:
1533
+ os.close(parent)
1534
+ try:
1535
+ os.ftruncate(fd, length)
1536
+ finally:
1537
+ os.close(fd)
1538
+ return 0, 0
1539
+ return None, errno.ENOSYS
1540
+
1541
+ def socket(self, ident, args):
1542
+ domain = args[0] & 0xFFFFFFFF
1543
+ kind = args[1] & 0xFFFFFFFF
1544
+ protocol = args[2] & 0xFFFFFFFF
1545
+ base = kind & 0xF
1546
+ if kind & ~(0xF | SOCK_NONBLOCK | SOCK_CLOEXEC):
1547
+ return None, errno.EINVAL
1548
+ if domain == AF_UNIX:
1549
+ if base not in (SOCK_STREAM, SOCK_SEQPACKET) or protocol != 0:
1550
+ return None, errno.EACCES
1551
+ elif domain in (AF_INET, AF_INET6):
1552
+ if self.endpoints is not None and (
1553
+ base != SOCK_STREAM or protocol not in (0, IPPROTO_TCP)):
1554
+ return None, errno.EACCES
1555
+ else:
1556
+ return None, errno.EAFNOSUPPORT
1557
+ # The broker creates and keeps the original socket so a later connect/bind is performed
1558
+ # on an object it owns, with an address it copied; the target receives an alias.
1559
+ fd = libc.socket(domain, base | (kind & SOCK_NONBLOCK), protocol)
1560
+ if fd < 0:
1561
+ return None, ctypes.get_errno()
1562
+ inode = os.fstat(fd).st_ino
1563
+ # Record ownership before the alias exists: the target may connect the moment ADDFD
1564
+ # completes its socket() call, possibly from another thread.
1565
+ with self.lock:
1566
+ self.sockets[inode] = fd
1567
+ data = struct.pack("QIIII", ident, ADDFD_SEND, fd, 0,
1568
+ os.O_CLOEXEC if kind & SOCK_CLOEXEC else 0)
1569
+ buffer = ctypes.create_string_buffer(data, len(data))
1570
+ if libc.ioctl(self.listener, NOTIF_ADDFD, buffer) < 0:
1571
+ code = ctypes.get_errno()
1572
+ self.release(inode)
1573
+ return None, code
1574
+ return "sent", 0
1575
+
1576
+ def owned(self, pid, ident, target_fd):
1577
+ link = self.target_link(pid, ident, "fd/%d" % (target_fd & 0xFFFFFFFF))
1578
+ if not link.startswith("socket:[") or not link.endswith("]"):
1579
+ return None, None
1580
+ inode = int(link[8:-1])
1581
+ with self.lock:
1582
+ return self.sockets.get(inode), inode
1583
+
1584
+ def release(self, inode):
1585
+ with self.lock:
1586
+ fd = self.sockets.pop(inode, None)
1587
+ if fd is not None:
1588
+ os.close(fd)
1589
+
1590
+ def unix_target(self, pid, ident, raw, create):
1591
+ """A pathname UNIX address resolved from the pinned write roots, as a /proc path."""
1592
+ name = raw[2:].split(b"\0", 1)[0]
1593
+ if len(raw) <= 2 or raw[2:3] == b"\0" or not name:
1594
+ raise Denied() # abstract and unnamed addresses stay inside nobody's grant
1595
+ path = os.fsdecode(name)
1596
+ if not path.startswith("/"):
1597
+ base = self.target_link(pid, ident, "cwd")
1598
+ if not base.startswith("/") or base.endswith(" (deleted)"):
1599
+ raise Denied()
1600
+ path = base.rstrip("/") + "/" + path
1601
+ path = os.path.normpath(path)
1602
+ if not create:
1603
+ obj = self.resolve(path, True)
1604
+ if not stat.S_ISSOCK(os.fstat(obj).st_mode):
1605
+ os.close(obj)
1606
+ raise OSError(errno.ECONNREFUSED, "Not a socket")
1607
+ return obj, "/proc/self/fd/%d" % obj
1608
+ try:
1609
+ parent, final, resolved, _ = self.files.resolve(path, True, False, 0, False)
1610
+ except (self.native.ScopeDenied, ValueError):
1611
+ raise Denied()
1612
+ if write_denied(resolved):
1613
+ os.close(parent)
1614
+ raise Denied()
1615
+ return parent, "/proc/self/fd/%d/%s" % (parent, final)
1616
+
1617
+ @staticmethod
1618
+ def unix_address(path):
1619
+ encoded = os.fsencode(path)
1620
+ if len(encoded) >= 108:
1621
+ raise OSError(errno.ENAMETOOLONG, "Socket path too long")
1622
+ address = struct.pack("H", AF_UNIX) + encoded + b"\0"
1623
+ return ctypes.create_string_buffer(address, len(address)), len(address)
1624
+
1625
+ def inet_address(self, raw, size):
1626
+ family = struct.unpack("H", raw[:2])[0]
1627
+ if family == AF_INET and size >= 16:
1628
+ return family, ipaddress.ip_address(raw[4:8]), struct.unpack(">H", raw[2:4])[0], 0
1629
+ if family == AF_INET6 and size >= 28:
1630
+ address = ipaddress.ip_address(raw[8:24])
1631
+ scope = struct.unpack("I", raw[24:28])[0]
1632
+ if address.ipv4_mapped:
1633
+ return family, address.ipv4_mapped, struct.unpack(">H", raw[2:4])[0], 0
1634
+ return family, address, struct.unpack(">H", raw[2:4])[0], scope
1635
+ return family, None, None, None
1636
+
1637
+ def bind(self, ident, pid, mem, args):
1638
+ size = args[2] & 0xFFFFFFFF
1639
+ if size < 2 or size > 128:
1640
+ return None, errno.EINVAL
1641
+ raw = self.read(mem, args[1], size)
1642
+ own, inode = self.owned(pid, ident, args[0])
1643
+ if own is None:
1644
+ return None, errno.EACCES if inode is not None else errno.ENOTSOCK
1645
+ if socket_domain(own) == AF_UNIX:
1646
+ handle, target = self.unix_target(pid, ident, raw, True)
1647
+ try:
1648
+ buffer, length = self.unix_address(target)
1649
+ if libc.bind(own, buffer, ctypes.c_uint32(length)) < 0:
1650
+ return None, ctypes.get_errno()
1651
+ # the socket file bind created, through the same pinned parent descriptor
1652
+ created = os.lstat(target)
1653
+ with self.lock:
1654
+ self.unix_bound.add((created.st_dev, created.st_ino))
1655
+ return 0, 0
1656
+ finally:
1657
+ os.close(handle)
1658
+ _, address, _, _ = self.inet_address(raw, size)
1659
+ # Restricted none/allowlist listens on loopback only (product decision); environment
1660
+ # lifts only the network filter.
1661
+ if address is None or (self.endpoints is not None and str(address) not in LOOPBACK):
1662
+ return None, errno.EACCES
1663
+ if self.endpoints is not None and socket_int(own, SO_REUSEPORT):
1664
+ return None, errno.EPERM # never into a foreign service's reuseport group
1665
+ copied = ctypes.create_string_buffer(raw, size)
1666
+ if libc.bind(own, copied, ctypes.c_uint32(size)) < 0:
1667
+ return None, ctypes.get_errno()
1668
+ return 0, 0
1669
+
1670
+ def listen(self, ident, pid, args):
1671
+ own, inode = self.owned(pid, ident, args[0])
1672
+ if own is None:
1673
+ # Broker ownership ends only with a successful connect, so an unowned socket is
1674
+ # connected (or accepted, or a socketpair end): it cannot legitimately listen. Under
1675
+ # none/allowlist refuse it; never let listen() autobind an unowned TCP socket to every
1676
+ # interface. listen() carries no pointer, so CONTINUE is safe for environment.
1677
+ if self.endpoints is not None:
1678
+ return None, errno.EACCES
1679
+ return "continue", 0
1680
+ if self.endpoints is not None and socket_domain(own) != AF_UNIX:
1681
+ # An unbound TCP socket would autobind to every interface on listen().
1682
+ host = socket_name(own)
1683
+ if host not in ("127.0.0.1", "::1"):
1684
+ return None, errno.EACCES
1685
+ if self.endpoints is not None and socket_domain(own) != AF_UNIX \
1686
+ and socket_int(own, SO_REUSEPORT):
1687
+ self.release(inode)
1688
+ return None, errno.EPERM # never into a foreign service's reuseport group
1689
+ result = libc.listen(own, ctypes.c_int(args[1] & 0xFFFFFFFF))
1690
+ code = ctypes.get_errno() if result < 0 else 0
1691
+ # A listening socket never connects; drop the broker's reference so close semantics
1692
+ # remain the target's own.
1693
+ self.release(inode)
1694
+ return (None, code) if code else (0, 0)
1695
+
1696
+ def connect(self, ident, pid, mem, args):
1697
+ size = args[2] & 0xFFFFFFFF
1698
+ if size < 2 or size > 128:
1699
+ return None, errno.EINVAL
1700
+ raw = self.read(mem, args[1], size)
1701
+ own, inode = self.owned(pid, ident, args[0])
1702
+ if own is None:
1703
+ return None, errno.EACCES if inode is not None else errno.ENOTSOCK
1704
+ if socket_domain(own) == AF_UNIX:
1705
+ handle, target = self.unix_target(pid, ident, raw, False)
1706
+ try:
1707
+ # only a socket this operation bound itself: the descriptor pins the inode, and
1708
+ # the connect goes through it, so a swapped path cannot change what is reached
1709
+ found = os.fstat(handle)
1710
+ with self.lock:
1711
+ own_socket = (found.st_dev, found.st_ino) in self.unix_bound
1712
+ if not own_socket:
1713
+ return None, errno.EACCES
1714
+ buffer, length = self.unix_address(target)
1715
+ result = libc.connect(own, buffer, ctypes.c_uint32(length))
1716
+ code = ctypes.get_errno() if result < 0 else 0
1717
+ finally:
1718
+ os.close(handle)
1719
+ if code == 0:
1720
+ self.release(inode)
1721
+ return (None, code) if code else (0, 0)
1722
+ family, address, port, scope = self.inet_address(raw, size)
1723
+ if family != AF_UNSPEC: # AF_UNSPEC only dissolves an existing association
1724
+ if address is None:
1725
+ return None, errno.EACCES
1726
+ if self.endpoints is not None and (str(address), port, scope) not in self.endpoints:
1727
+ return None, errno.EACCES
1728
+ # Connect with the broker's own copy of the checked address on the broker-owned object.
1729
+ copied = ctypes.create_string_buffer(raw, size)
1730
+ if libc.connect(own, copied, ctypes.c_uint32(size)) < 0:
1731
+ code = ctypes.get_errno()
1732
+ if code == errno.EINPROGRESS:
1733
+ threading.Thread(target=self.settle, args=(own, inode), daemon=True).start()
1734
+ # A refused or dissolved association keeps the broker's ownership: an unconnected
1735
+ # unowned socket could otherwise listen() on every interface.
1736
+ return None, code
1737
+ if family != AF_UNSPEC:
1738
+ self.release(inode)
1739
+ return 0, 0
1740
+
1741
+ def settle(self, fd, inode):
1742
+ poller = select.poll()
1743
+ poller.register(fd, select.POLLOUT)
1744
+ poller.poll()
1745
+ if struct.unpack("i", socket_option(fd, SOL_SOCKET, 4))[0] == 0: # SO_ERROR
1746
+ self.release(inode)
1747
+
1748
+ def respond(self, ident, value, code, flags=0):
1749
+ data = struct.pack("QqiI", ident, value or 0, -code if code else 0, flags)
1750
+ try:
1751
+ ioctl(self.listener, NOTIF_SEND, ctypes.create_string_buffer(data, len(data)))
1752
+ except OSError:
1753
+ pass
1754
+
1755
+ def serve_one(self, ident, pid, nr, args):
1756
+ try:
1757
+ value, code = self.handle(ident, pid, nr, args)
1758
+ except Exception:
1759
+ value, code = None, errno.EACCES
1760
+ if value == "continue":
1761
+ self.respond(ident, 0, 0, 1) # SECCOMP_USER_NOTIF_FLAG_CONTINUE
1762
+ elif value != "sent":
1763
+ self.respond(ident, value, code)
1764
+
1765
+ # Each notification is served on its own thread. That is sound because no handler keeps
1766
+ # shared mutable state across its steps (socket ownership is locked): every check is made on
1767
+ # the broker's own resolution, and every effect is one syscall on descriptors that handler
1768
+ # holds, so concurrent notifications interleave only as the kernel would interleave the calls.
1769
+ # The one multi-step check, a directory move into a guarded prefix (staging, listing, rename),
1770
+ # holds the files lock exclusively (waiting at most EXCLUSIVE_WAIT_S, then EBUSY) while every
1771
+ # other write holds it shared from its check to its effect. With the consumer's device lock
1772
+ # this spans every operation of the device: no write of another operation can be checked
1773
+ # against a parent that such a move relocates before the write's effect (its staging name is
1774
+ # reserved too, so no path-based write reaches it). Each create or rename is then verified at
1775
+ # its parent's current place (verify), which covers moves made outside every sandbox.
1776
+ def loop(self, stop):
1777
+ poller = select.poll()
1778
+ poller.register(self.listener, select.POLLIN)
1779
+ poller.register(stop, select.POLLIN)
1780
+ while True:
1781
+ events = dict(poller.poll())
1782
+ if stop in events:
1783
+ return
1784
+ event = events.get(self.listener, 0)
1785
+ if event & select.POLLIN:
1786
+ buffer = ctypes.create_string_buffer(80)
1787
+ if libc.ioctl(self.listener, NOTIF_RECV, buffer) < 0:
1788
+ continue
1789
+ ident, pid, _, nr, _, _ = struct.unpack_from("QIIiIQ", buffer.raw)
1790
+ args = struct.unpack_from("6Q", buffer.raw, 32)
1791
+ threading.Thread(target=self.serve_one, args=(ident, pid, nr, args),
1792
+ daemon=True).start()
1793
+ elif event & (select.POLLHUP | select.POLLERR):
1794
+ return
1795
+
1796
+ def close(self):
1797
+ with self.lock:
1798
+ fds = list(self.sockets.values())
1799
+ self.sockets.clear()
1800
+ for fd in fds:
1801
+ os.close(fd)
1802
+
1803
+
1804
+ # ---- supervision --------------------------------------------------------------------------
1805
+
1806
+ def descendants():
1807
+ found = []
1808
+ pending = [os.getpid()]
1809
+ while pending:
1810
+ pid = pending.pop()
1811
+ try:
1812
+ tasks = os.listdir("/proc/%d/task" % pid)
1813
+ except OSError:
1814
+ continue
1815
+ for task in tasks:
1816
+ try:
1817
+ with open("/proc/%d/task/%s/children" % (pid, task)) as handle:
1818
+ children = [int(value) for value in handle.read().split()]
1819
+ except OSError:
1820
+ continue
1821
+ for child in children:
1822
+ found.append((child, pid))
1823
+ pending.append(child)
1824
+ return found
1825
+
1826
+
1827
+ def parent_of(pid):
1828
+ with open("/proc/%d/stat" % pid) as handle:
1829
+ data = handle.read()
1830
+ return int(data[data.rindex(")") + 2:].split()[1])
1831
+
1832
+
1833
+ def kill_tree():
1834
+ """SIGKILLs every descendant by kernel parentage (the supervisor is their subreaper)."""
1835
+ killed = set()
1836
+ while True:
1837
+ tree = descendants()
1838
+ known = {os.getpid()} | {pid for pid, _ in tree}
1839
+ for pid, _ in tree:
1840
+ try:
1841
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
1842
+ except OSError:
1843
+ continue
1844
+ try:
1845
+ # The pidfd pins the process; confirm it is still inside our tree before signalling.
1846
+ if parent_of(pid) in known:
1847
+ syscall(NR_PIDFD_SEND_SIGNAL, handle, signal.SIGKILL, None, 0)
1848
+ killed.add(pid)
1849
+ except OSError:
1850
+ pass
1851
+ finally:
1852
+ os.close(handle)
1853
+ try:
1854
+ os.waitpid(-1, 0)
1855
+ except ChildProcessError:
1856
+ return len(killed)
1857
+
1858
+
1859
+ class Report:
1860
+ def __init__(self, fd):
1861
+ self.fd = fd
1862
+
1863
+ def write(self, event):
1864
+ if self.fd is None:
1865
+ return
1866
+ data = (json.dumps(event) + "\n").encode()
1867
+ while data:
1868
+ data = data[os.write(self.fd, data):]
1869
+
1870
+
1871
+ def endpoints_of(network):
1872
+ kind = network.get("kind")
1873
+ if kind == "environment":
1874
+ return None
1875
+ if kind == "none":
1876
+ return set()
1877
+ if kind == "endpoints":
1878
+ allowed = set()
1879
+ for endpoint in network.get("endpoints", []):
1880
+ address = ipaddress.ip_address(endpoint["address"])
1881
+ port = endpoint["port"]
1882
+ scope = endpoint.get("scopeId", 0)
1883
+ if type(port) is not int or not 0 < port < 65536 or type(scope) is not int:
1884
+ raise Refused("INVALID_REQUEST", "Supply numeric endpoint ports and scope IDs")
1885
+ if address.version == 6 and address.ipv4_mapped:
1886
+ address, scope = address.ipv4_mapped, 0
1887
+ # A link-local IPv6 grant names one interface: the scope ID is part of the endpoint.
1888
+ allowed.add((str(address), port, scope if address.version == 6 else 0))
1889
+ return allowed
1890
+ raise Refused("INVALID_REQUEST", "Unknown network kind")
1891
+
1892
+
1893
+ def device_files_lock(request, roots, system_roots):
1894
+ """The inherited descriptor of the device's files lock ("filesLockFd", exec mode), or None.
1895
+
1896
+ It must be a regular file outside every root this command reads or writes (and every system
1897
+ root): the restricted command could otherwise open it and hold it, stalling the device's
1898
+ writes. The descriptor itself never reaches the command (close_except before exec)."""
1899
+ fd = request.get("filesLockFd")
1900
+ if fd is None:
1901
+ return None
1902
+ if request.get("mode") != "exec" or not isinstance(fd, int) or isinstance(fd, bool) or fd < 3:
1903
+ raise Refused("INVALID_REQUEST", "A files lock descriptor serves exec mode only")
1904
+ try:
1905
+ info = os.fstat(fd)
1906
+ where = os.readlink("/proc/self/fd/%d" % fd)
1907
+ except OSError:
1908
+ raise Refused("INVALID_REQUEST", "The files lock descriptor is not open")
1909
+ if not stat.S_ISREG(info.st_mode) or not where.startswith("/") or where.endswith(" (deleted)"):
1910
+ raise Refused("INVALID_REQUEST", "The files lock is not a regular file")
1911
+ granted = roots["read"] + roots["write"] + roots["readFiles"]
1912
+ reach = [r["path"] for r in granted] + list(system_roots)
1913
+ for entry in granted:
1914
+ try:
1915
+ reach.append(os.readlink("/proc/self/fd/%d" % entry["fd"]))
1916
+ except OSError:
1917
+ pass
1918
+ for root in reach:
1919
+ root = os.path.normpath(root)
1920
+ if root == "/" or where == root or where.startswith(root + "/"):
1921
+ raise Refused("SCOPE_DENIED", "The device's files lock is inside the granted root %s"
1922
+ % root)
1923
+ os.set_inheritable(fd, False)
1924
+ return fd
1925
+
1926
+
1927
+ def restrict_child(table, ruleset, network_mediated, brokered, channel):
1928
+ """Runs in the forked child before exec: session, Landlock, seccomp, listener hand-off."""
1929
+ if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS
1930
+ raise OSError(ctypes.get_errno(), "no_new_privs")
1931
+ syscall(NR_LANDLOCK_RESTRICT, ruleset, 0)
1932
+ listener = install_filter(table, build_filter(table, network_mediated, brokered), brokered)
1933
+ if brokered:
1934
+ socket.send_fds(channel, [b"L"], [listener])
1935
+ os.close(listener)
1936
+
1937
+
1938
+ def close_except(keep):
1939
+ """close_range() over every descriptor from 3 up except the kept ones."""
1940
+ low = 3
1941
+ for fd in sorted(set(fd for fd in keep if fd >= 3)):
1942
+ if fd > low:
1943
+ syscall(NR_CLOSE_RANGE, low, fd - 1, 0)
1944
+ low = fd + 1
1945
+ syscall(NR_CLOSE_RANGE, low, 0xFFFFFFFF, 0)
1946
+
1947
+
1948
+ class Cancellation:
1949
+ """SIGTERM/SIGINT handling installed (and the signals blocked) before any fork."""
1950
+
1951
+ def __init__(self):
1952
+ self.signals = []
1953
+ self.wake_r, self.wake_w = os.pipe()
1954
+ os.set_blocking(self.wake_w, False)
1955
+ signal.signal(signal.SIGTERM, self.cancel)
1956
+ signal.signal(signal.SIGINT, self.cancel)
1957
+
1958
+ def cancel(self, signum, _frame):
1959
+ self.signals.append(signum)
1960
+ try:
1961
+ os.write(self.wake_w, b"x")
1962
+ except OSError:
1963
+ pass
1964
+
1965
+
1966
+ CANCEL_SIGNALS = {signal.SIGTERM, signal.SIGINT}
1967
+
1968
+
1969
+ def start_time(pid):
1970
+ with open("/proc/%d/stat" % pid) as handle:
1971
+ data = handle.read()
1972
+ return int(data[data.rindex(")") + 2:].split()[19])
1973
+
1974
+
1975
+ def reap(session):
1976
+ """Consumer-side cleanup after a lost supervisor: SIGKILL the launcher's closed session.
1977
+
1978
+ The session ID is the restricted child's PID and setsid() is denied inside it, so membership
1979
+ is kernel-maintained and closed. Linux keeps a PID number reserved while it names a live
1980
+ session, so the session is ours while a process holding that PID still has the recorded start
1981
+ time, or no process holds it. Each member is pinned with a pidfd, then re-checked: still in the
1982
+ session, started no earlier than the leader, and the leader's PID not taken by another process
1983
+ since. A PID reuse within one scan can therefore only skip a process, never signal a stranger.
1984
+ """
1985
+ sid, started = int(session["sid"]), int(session["start"])
1986
+ killed = set()
1987
+
1988
+ def leader_reused():
1989
+ try:
1990
+ return start_time(sid) != started
1991
+ except OSError:
1992
+ return False # The leader exited; its PID stays reserved while members remain.
1993
+
1994
+ while True:
1995
+ if leader_reused():
1996
+ return len(killed)
1997
+ members = []
1998
+ for entry in os.listdir("/proc"):
1999
+ if not entry.isdigit():
2000
+ continue
2001
+ try:
2002
+ with open("/proc/%s/stat" % entry) as handle:
2003
+ data = handle.read()
2004
+ except OSError:
2005
+ continue
2006
+ fields = data[data.rindex(")") + 2:].split()
2007
+ # Zombies hold no grant and cannot be killed again; they only await their reaper.
2008
+ if int(fields[3]) == sid and fields[0] not in ("Z", "X"):
2009
+ members.append(int(entry))
2010
+ if not members:
2011
+ return len(killed)
2012
+ for pid in members:
2013
+ try:
2014
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
2015
+ except OSError:
2016
+ continue
2017
+ try:
2018
+ # The pidfd pins the process; confirm it still belongs to our session.
2019
+ with open("/proc/%d/stat" % pid) as stat_file:
2020
+ data = stat_file.read()
2021
+ fields = data[data.rindex(")") + 2:].split()
2022
+ if int(fields[3]) == sid and int(fields[19]) >= started and not leader_reused():
2023
+ syscall(NR_PIDFD_SEND_SIGNAL, handle, signal.SIGKILL, None, 0)
2024
+ killed.add(pid)
2025
+ except OSError:
2026
+ pass
2027
+ finally:
2028
+ os.close(handle)
2029
+ # Wait for the signalled process to be gone (or a zombie) before rescanning.
2030
+ poller = select.poll()
2031
+ try:
2032
+ waiter = syscall(NR_PIDFD_OPEN, pid, 0)
2033
+ except OSError:
2034
+ continue
2035
+ try:
2036
+ poller.register(waiter, select.POLLIN)
2037
+ poller.poll()
2038
+ finally:
2039
+ os.close(waiter)
2040
+
2041
+
2042
+ def run(request, report):
2043
+ machine, table = arch()
2044
+ if request.get("nativeFd") is not None and request.get("mode") != "exec":
2045
+ raise Refused("INVALID_REQUEST", "A native helper descriptor serves exec mode only")
2046
+ native, native_path = load_native(request.get("nativeFd"))
2047
+ status = probe_static(table, request.get("candidateArch") is True)
2048
+ if status:
2049
+ raise Refused("UNAVAILABLE", status)
2050
+ roots, seen = verify_roots(native, request)
2051
+ add_write_denies(request.get("writeDenies", []), native)
2052
+ network = request.get("network", {"kind": "none"})
2053
+ endpoints = endpoints_of(network)
2054
+ network_mediated = endpoints is not None
2055
+ mode = request.get("mode")
2056
+ files = native.NativeFiles(roots)
2057
+ cwd_path = request.get("cwd") or roots["write"][0]["path"]
2058
+ try:
2059
+ cwd = files.open(cwd_path, directory=True)
2060
+ except (OSError, ValueError, native.ScopeDenied):
2061
+ raise Refused("SCOPE_DENIED", "The working directory is outside the pinned roots")
2062
+ os.set_inheritable(cwd, False)
2063
+ # The staged runtime directory (trusted, consumer-verified) stays readable for the helper.
2064
+ system_roots = list(request.get("systemRoots", DEFAULT_SYSTEM_ROOTS))
2065
+ if request.get("nativeFd") is None:
2066
+ system_roots.append(os.path.dirname(native_path))
2067
+ files_lock = device_files_lock(request, roots, system_roots)
2068
+ ruleset = landlock_ruleset(roots, system_roots, network_mediated or mode == "native",
2069
+ mode == "exec")
2070
+ pinned_fds = [r["fd"] for r in roots["read"] + roots["write"]]
2071
+ launch = {"event": "launch", "arch": machine, "validated": machine in VALIDATED_ARCHES,
2072
+ "landlockAbi": landlock_abi(), "roots": seen,
2073
+ "ruleFds": [entry["fd"] for entry in seen], "brokerFds": pinned_fds,
2074
+ "nativeFds": pinned_fds if mode == "native" else [],
2075
+ "cwd": [os.fstat(cwd).st_dev, os.fstat(cwd).st_ino]}
2076
+ brokered = mode == "exec"
2077
+ parent_sock, child_sock = socket.socketpair()
2078
+ libc.prctl(36, 1, 0, 0, 0) # PR_SET_CHILD_SUBREAPER
2079
+ native_in = None
2080
+ if mode == "native":
2081
+ native_in, native_out = os.pipe()
2082
+ elif mode != "exec":
2083
+ raise Refused("INVALID_REQUEST", "Unknown mode")
2084
+ parent = os.getpid()
2085
+ # Cancellation is armed before the fork: a SIGTERM during setup cancels instead of killing
2086
+ # the supervisor by default action and orphaning the child.
2087
+ cancellation = Cancellation()
2088
+ signal.pthread_sigmask(signal.SIG_BLOCK, CANCEL_SIGNALS)
2089
+ pid = os.fork()
2090
+ if pid == 0:
2091
+ try:
2092
+ libc.prctl(1, signal.SIGKILL, 0, 0, 0) # PR_SET_PDEATHSIG
2093
+ if os.getppid() != parent:
2094
+ os._exit(125)
2095
+ os.setsid()
2096
+ signal.signal(signal.SIGTERM, signal.SIG_DFL)
2097
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
2098
+ os.fchdir(cwd)
2099
+ parent_sock.close()
2100
+ if mode == "native":
2101
+ os.dup2(native_in, 0)
2102
+ keep = [r["fd"] for r in roots["read"] + roots["write"]]
2103
+ else:
2104
+ null = os.open("/dev/null", os.O_RDONLY)
2105
+ os.dup2(null, 0)
2106
+ keep = []
2107
+ restrict_child(table, ruleset, network_mediated or mode == "native", brokered,
2108
+ child_sock)
2109
+ # No restricted code runs before the supervisor has recorded the session and holds
2110
+ # the listener: wait for its acknowledgement (EOF if it was lost).
2111
+ if child_sock.recv(1) != b"A":
2112
+ os._exit(125)
2113
+ child_sock.close()
2114
+ # Only stdio (and, for the native helper, the same pinned roots) survive exec.
2115
+ close_except(keep)
2116
+ for fd in keep:
2117
+ os.set_inheritable(fd, True)
2118
+ env = request.get("env") or {"PATH": "/usr/local/bin:/usr/bin:/bin"}
2119
+ if mode == "native":
2120
+ argv = [sys.executable, "-I", native_path]
2121
+ else:
2122
+ argv = request["argv"]
2123
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, CANCEL_SIGNALS)
2124
+ os.execve(argv[0], argv, env)
2125
+ except BaseException as error:
2126
+ try:
2127
+ os.write(2, ("restricted launch failed: %s\n" % error).encode())
2128
+ finally:
2129
+ os._exit(126)
2130
+ # The consumer needs the closed session's identity before anything else can go wrong.
2131
+ try:
2132
+ report.write({"event": "session", "sid": pid, "start": start_time(pid)})
2133
+ finally:
2134
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, CANCEL_SIGNALS)
2135
+ child_sock.close()
2136
+ os.close(ruleset)
2137
+ os.close(cwd)
2138
+ if native_in is not None:
2139
+ os.close(native_in)
2140
+ body = dict(request.get("native", {}))
2141
+ # restricted native writes honour the mandatory write denies too
2142
+ body["roots"] = dict(roots, denyWrites=True)
2143
+ data = json.dumps(body).encode()
2144
+ while data:
2145
+ data = data[os.write(native_out, data):]
2146
+ os.close(native_out)
2147
+ broker = None
2148
+ stop_r, stop_w = os.pipe()
2149
+ thread = None
2150
+ if brokered:
2151
+ message, fds, _, _ = socket.recv_fds(parent_sock, 1, 1)
2152
+ if not fds:
2153
+ kill_tree()
2154
+ raise Refused("UNAVAILABLE", "The restricted child did not hand over its listener")
2155
+ broker = Broker(native, roots, table, endpoints, fds[0],
2156
+ native.DeviceFilesLock(files_lock) if files_lock is not None else None)
2157
+ fault = request.get("faultInjection")
2158
+ if isinstance(fault, dict) and fault.get("stagedMove") == "fail":
2159
+ broker.fault = "fail" # a test fixture's seam
2160
+ if isinstance(fault, dict) and isinstance(fault.get("pauseBeforeMkdir"), str):
2161
+ broker.pause_mkdir = fault["pauseBeforeMkdir"] # a test fixture's seam
2162
+ thread = threading.Thread(target=broker.loop, args=(stop_r,), daemon=True)
2163
+ thread.start()
2164
+ # Reported only once every restriction is installed and the broker holds the listener.
2165
+ report.write(launch)
2166
+ parent_sock.send(b"A")
2167
+ parent_sock.close()
2168
+ return supervise(pid, request, report, broker, thread, stop_w, cancellation)
2169
+
2170
+
2171
+ def supervise(pid, request, report, broker, thread, stop_w, cancellation):
2172
+ wake_r = cancellation.wake_r
2173
+ cancelled = cancellation.signals
2174
+ handle = syscall(NR_PIDFD_OPEN, pid, 0)
2175
+ deadline = None
2176
+ if request.get("timeoutMs"):
2177
+ deadline = time.monotonic() + request["timeoutMs"] / 1000
2178
+ poller = select.poll()
2179
+ poller.register(handle, select.POLLIN)
2180
+ poller.register(wake_r, select.POLLIN)
2181
+ exit_code = None
2182
+ timed_out = False
2183
+ while True:
2184
+ timeout = None if deadline is None else max(0, int((deadline - time.monotonic()) * 1000))
2185
+ events = dict(poller.poll(timeout))
2186
+ if handle in events:
2187
+ _, status = os.waitpid(pid, 0)
2188
+ exit_code = os.waitstatus_to_exitcode(status)
2189
+ break
2190
+ if cancelled:
2191
+ break
2192
+ if deadline is not None and time.monotonic() >= deadline:
2193
+ timed_out = True
2194
+ break
2195
+ # Restricted descendants never outlive their supervisor: kill the remaining owned tree.
2196
+ survivors = kill_tree()
2197
+ os.write(stop_w, b"x")
2198
+ if thread is not None:
2199
+ thread.join()
2200
+ counts = {}
2201
+ fatal = None
2202
+ if broker is not None:
2203
+ counts = dict(broker.counts)
2204
+ fatal = broker.fatal
2205
+ broker.close()
2206
+ event = {"event": "exit", "exitCode": exit_code, "timedOut": timed_out,
2207
+ "cancelled": bool(cancelled), "killed": survivors, "brokered": counts}
2208
+ if fatal is not None:
2209
+ event["fatal"] = fatal
2210
+ report.write(event)
2211
+ if exit_code is None:
2212
+ return 124 if timed_out else 143
2213
+ return exit_code if exit_code >= 0 else 128 - exit_code
2214
+
2215
+
2216
+ # ---- capability probe ---------------------------------------------------------------------
2217
+
2218
+ def probe_static(table, candidate=False):
2219
+ machine = platform.machine()
2220
+ if platform.system() != "Linux":
2221
+ return "Restricted Linux execution requires Linux"
2222
+ if table is None:
2223
+ return "No syscall inventory exists for %s" % machine
2224
+ if SELF_PROTECTION:
2225
+ return SELF_PROTECTION
2226
+ if machine not in VALIDATED_ARCHES and not candidate:
2227
+ return "The syscall inventory is not validated on %s" % machine
2228
+ abi = landlock_abi()
2229
+ if abi < LANDLOCK_ABI_REQUIRED:
2230
+ return "Landlock ABI %d is below the required %d" % (abi, LANDLOCK_ABI_REQUIRED)
2231
+ if not os.path.exists("/proc/self/task/%d/children" % os.getpid()):
2232
+ return "The kernel does not expose child lists for exact supervision"
2233
+ return None
2234
+
2235
+
2236
+ def probe(candidate=False):
2237
+ """Never raises: any failure is restricted unavailable with its reason.
2238
+
2239
+ "restricted" is non-null only on a validated architecture. With candidate set on an
2240
+ unvalidated one, the primitives' result is reported separately under "candidate" (evidence
2241
+ collection only) and "restricted" stays null, so no consumer can read it as support.
2242
+ """
2243
+ machine = platform.machine()
2244
+ try:
2245
+ result = probe_primitives(candidate)
2246
+ except BaseException as error:
2247
+ return {"restricted": None, "arch": machine,
2248
+ "reason": "The probe failed: %s" % type(error).__name__}
2249
+ if candidate and machine not in VALIDATED_ARCHES:
2250
+ return {"restricted": None, "arch": machine, "validated": False,
2251
+ "reason": "The syscall inventory is not validated on %s" % machine,
2252
+ "candidate": result}
2253
+ return result
2254
+
2255
+
2256
+ def probe_primitives(candidate):
2257
+ """Exercises the real primitives: Landlock, a seccomp listener, ADDFD and target memory."""
2258
+ machine, table = arch()
2259
+ reason = probe_static(table, candidate)
2260
+ if reason:
2261
+ return {"restricted": None, "reason": reason, "arch": machine}
2262
+ parent_sock, child_sock = socket.socketpair()
2263
+ pid = os.fork()
2264
+ if pid == 0:
2265
+ try:
2266
+ parent_sock.close()
2267
+ # Dumpable like a real restricted child after its execve, so the broker's memory read
2268
+ # is exercised as in a launch (fork inherited non-dumpable; the probe holds no secret).
2269
+ if libc.prctl(4, 1, 0, 0, 0) != 0: # PR_SET_DUMPABLE 1
2270
+ os._exit(3)
2271
+ if libc.prctl(38, 1, 0, 0, 0) != 0:
2272
+ os._exit(3)
2273
+ attr = struct.pack("QQQ", FS_ALL, NET_CONNECT_TCP, SCOPE_ALL)
2274
+ ruleset = syscall(NR_LANDLOCK_CREATE, ctypes.create_string_buffer(attr, 24), 24, 0)
2275
+ syscall(NR_LANDLOCK_RESTRICT, ruleset, 0)
2276
+ listener = install_filter(table, build_filter(table, True, True), True)
2277
+ socket.send_fds(child_sock, [b"L"], [listener])
2278
+ os.close(listener)
2279
+ probe_socket = socket.socket(AF_INET, SOCK_STREAM)
2280
+ child_sock.send(b"ok" if probe_socket.fileno() >= 0 else b"no")
2281
+ os._exit(0)
2282
+ except BaseException:
2283
+ os._exit(4)
2284
+ child_sock.close()
2285
+ try:
2286
+ _, fds, _, _ = socket.recv_fds(parent_sock, 1, 1)
2287
+ if not fds:
2288
+ raise OSError(errno.EPERM, "The seccomp listener is not available")
2289
+ buffer = ctypes.create_string_buffer(80)
2290
+ ioctl(fds[0], NOTIF_RECV, buffer)
2291
+ ident, target, _, nr, _, _ = struct.unpack_from("QIIiIQ", buffer.raw)
2292
+ mem = os.open("/proc/%d/mem" % target, os.O_RDONLY)
2293
+ os.close(mem)
2294
+ own = socket.socket(AF_INET, SOCK_STREAM)
2295
+ data = struct.pack("QIIII", ident, ADDFD_SEND, own.fileno(), 0, 0)
2296
+ ioctl(fds[0], NOTIF_ADDFD, ctypes.create_string_buffer(data, len(data)))
2297
+ own.close()
2298
+ answer = parent_sock.recv(2)
2299
+ _, status = os.waitpid(pid, 0)
2300
+ if answer != b"ok" or os.waitstatus_to_exitcode(status) != 0:
2301
+ raise OSError(errno.EPERM, "The brokered socket did not reach the child")
2302
+ handle = syscall(NR_PIDFD_OPEN, os.getpid(), 0)
2303
+ os.close(handle)
2304
+ except OSError as error:
2305
+ try:
2306
+ os.kill(pid, signal.SIGKILL)
2307
+ os.waitpid(pid, 0)
2308
+ except OSError:
2309
+ pass
2310
+ return {"restricted": None, "arch": machine,
2311
+ "reason": "A required primitive failed: %s" % error.strerror}
2312
+ return {"restricted": {"filesystem": True, "network": True, "native": True,
2313
+ "concurrentScopes": True},
2314
+ "arch": machine, "validated": machine in VALIDATED_ARCHES,
2315
+ "landlockAbi": landlock_abi()}
2316
+
2317
+
2318
+ def main():
2319
+ report = Report(None)
2320
+ try:
2321
+ if len(sys.argv) > 1 and sys.argv[1] == "probe":
2322
+ print(json.dumps(probe("--candidate-arch" in sys.argv[2:])), flush=True)
2323
+ return 0
2324
+ if len(sys.argv) > 1 and sys.argv[1] == "reap":
2325
+ print(json.dumps({"killed": reap(json.load(sys.stdin))}), flush=True)
2326
+ return 0
2327
+ request = json.load(sys.stdin)
2328
+ report = Report(request.get("reportFd"))
2329
+ if report.fd is not None:
2330
+ os.set_inheritable(report.fd, False)
2331
+ return run(request, report)
2332
+ except Refused as error:
2333
+ report.write({"event": "refused", "code": error.code, "message": str(error)})
2334
+ return 125
2335
+ except Exception as error:
2336
+ report.write({"event": "refused", "code": "INVALID_REQUEST",
2337
+ "message": "Restricted launch failed: %s" % type(error).__name__})
2338
+ return 125
2339
+
2340
+
2341
+ if __name__ == "__main__":
2342
+ sys.exit(main())
2343
+ `;