@capybara-hq/plugin-sdk 0.1.0-rc.62 → 0.1.0-rc.63

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