@capybara-hq/plugin-sdk 0.1.0-rc.6 → 0.1.0-rc.61

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