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