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