@capybara-hq/plugin-sdk 0.1.0-rc.30 → 0.1.0-rc.32
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/dist/ctx.d.ts +47 -3
- package/dist/device-protocol-v3.d.ts +117 -0
- package/dist/device-protocol-v3.js +409 -0
- package/dist/device-protocol.d.ts +11 -0
- package/dist/device-protocol.js +8 -0
- package/dist/hooks.d.ts +67 -8
- package/dist/index.d.ts +3 -1
- package/dist/index.js +4 -1
- package/dist/model.d.ts +85 -2
- package/dist/model.js +103 -0
- package/dist/permissions.d.ts +3 -2
- package/dist/permissions.js +2 -2
- package/dist/sandbox-linux-runtime-source.d.ts +0 -14
- package/dist/sandbox-linux-runtime-source.js +482 -17
- package/dist/sandbox-native-runtime-source.js +20 -2
- package/dist/sandbox-runtime-source.js +2 -2
- package/dist/sandbox-write-denies.d.ts +60 -0
- package/dist/sandbox-write-denies.js +630 -0
- package/package.json +1 -1
|
@@ -5,15 +5,52 @@
|
|
|
5
5
|
* Transport: `python3 -I linux-sandbox.py probe` prints the capability report. Otherwise one JSON
|
|
6
6
|
* request on stdin: `{mode: "exec" | "native", roots: {read, write: [{path, fd, dev, ino}]},
|
|
7
7
|
* network: {kind: "none" | "environment"} | {kind: "endpoints", endpoints: [{address, port}]},
|
|
8
|
-
* reportFd, cwd?, env?, argv (exec), timeoutMs? (exec), native (native-files request)
|
|
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)}`.
|
|
9
11
|
* Root descriptors are pinned once by the consumer and inherited; the launcher verifies their
|
|
10
12
|
* identity and never reopens a root pathname. Landlock rules, broker metadata checks and the
|
|
11
13
|
* native helper all use those same descriptors. JSON events (`launch`, `exit`, `refused`) go to
|
|
12
14
|
* reportFd, which the restricted child cannot write. SIGTERM cancels the whole owned tree.
|
|
13
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`).
|
|
14
21
|
*/
|
|
22
|
+
import { SANDBOX_WRITE_POLICY_PYTHON } from "./sandbox-write-denies.js";
|
|
15
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
|
+
|
|
16
52
|
import errno
|
|
53
|
+
import importlib.machinery
|
|
17
54
|
import importlib.util
|
|
18
55
|
import ipaddress
|
|
19
56
|
import json
|
|
@@ -51,6 +88,20 @@ import time
|
|
|
51
88
|
# - UNIX sockets in every network kind: stream/seqpacket only (datagram and raw are refused);
|
|
52
89
|
# pathname connect/bind only to sockets inside the write roots, resolved through the pinned
|
|
53
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.
|
|
54
105
|
# - The launcher creates one closed session (setsid is denied inside it) and reports it in a
|
|
55
106
|
# "session" event; if the supervisor is lost, the consumer runs "reap" with that event to end
|
|
56
107
|
# every owned process. Brokered calls fail (ENOSYS) once the broker is gone.
|
|
@@ -81,6 +132,8 @@ ARCHES = {
|
|
|
81
132
|
"socket": 198, "socketpair": 199, "bind": 200, "listen": 201, "connect": 203, "sendto": 206,
|
|
82
133
|
"sendmsg": 211, "add_key": 217, "request_key": 218, "keyctl": 219, "clone": 220,
|
|
83
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,
|
|
84
137
|
},
|
|
85
138
|
},
|
|
86
139
|
"x86_64": {
|
|
@@ -95,11 +148,15 @@ ARCHES = {
|
|
|
95
148
|
"fremovexattr": 199, "utimes": 235, "add_key": 248, "request_key": 249,
|
|
96
149
|
"keyctl": 250, "fchownat": 260, "futimesat": 261, "fchmodat": 268, "unshare": 272,
|
|
97
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,
|
|
98
155
|
},
|
|
99
156
|
},
|
|
100
157
|
}
|
|
101
158
|
COMMON = {"io_uring_setup": 425, "io_uring_enter": 426, "io_uring_register": 427,
|
|
102
|
-
"clone3": 435, "fchmodat2": 452, "setxattrat": 463, "removexattrat": 466,
|
|
159
|
+
"clone3": 435, "openat2": 437, "fchmodat2": 452, "setxattrat": 463, "removexattrat": 466,
|
|
103
160
|
"file_setattr": 469}
|
|
104
161
|
NR_CLOSE_RANGE = 436
|
|
105
162
|
# CLONE_NEWNS | NEWCGROUP | NEWUTS | NEWIPC | NEWUSER | NEWPID | NEWNET | NEWTIME
|
|
@@ -123,6 +180,20 @@ DEFAULT_SYSTEM_ROOTS = ("/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc", "/pro
|
|
|
123
180
|
DEVICE_FILES = ("/dev/null", "/dev/zero", "/dev/full", "/dev/random", "/dev/urandom", "/dev/tty")
|
|
124
181
|
|
|
125
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}
|
|
126
197
|
def RET_ERRNO(code):
|
|
127
198
|
return 0x00050000 | code
|
|
128
199
|
|
|
@@ -169,9 +240,20 @@ def ioctl(fd, request, buffer):
|
|
|
169
240
|
raise OSError(code, os.strerror(code))
|
|
170
241
|
|
|
171
242
|
|
|
172
|
-
def load_native():
|
|
173
|
-
|
|
174
|
-
|
|
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))
|
|
175
257
|
module = importlib.util.module_from_spec(spec)
|
|
176
258
|
spec.loader.exec_module(module)
|
|
177
259
|
return module, path
|
|
@@ -272,10 +354,22 @@ def build_filter(table, network_mediated, brokered):
|
|
|
272
354
|
"lremovexattr", "fremovexattr", "connect", "listen"):
|
|
273
355
|
if name in nr:
|
|
274
356
|
simple[nr[name]] = notify
|
|
275
|
-
if network_mediated:
|
|
357
|
+
if network_mediated or brokered:
|
|
358
|
+
# a pathname UNIX bind creates a file: the broker makes it (and checks the denies)
|
|
276
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
|
|
277
367
|
for number in simple:
|
|
278
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")
|
|
279
373
|
p.jeq(nr["ioctl"], "ioctl")
|
|
280
374
|
p.jeq(nr["socket"], "socket")
|
|
281
375
|
p.jeq(nr["socketpair"], "socketpair")
|
|
@@ -291,6 +385,18 @@ def build_filter(table, network_mediated, brokered):
|
|
|
291
385
|
p.ret(action)
|
|
292
386
|
p.label("enosys")
|
|
293
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)
|
|
294
400
|
p.label("ioctl")
|
|
295
401
|
p.ld_arg(1)
|
|
296
402
|
for request in DENIED_IOCTLS:
|
|
@@ -388,7 +494,7 @@ def verify_roots(native, request):
|
|
|
388
494
|
return result, seen
|
|
389
495
|
|
|
390
496
|
|
|
391
|
-
def landlock_ruleset(roots, system_roots, network_mediated):
|
|
497
|
+
def landlock_ruleset(roots, system_roots, network_mediated, brokered_writes=False):
|
|
392
498
|
attr = struct.pack("QQQ", FS_ALL, NET_MEDIATED if network_mediated else 0, SCOPE_ALL)
|
|
393
499
|
attr_buffer = ctypes.create_string_buffer(attr, len(attr))
|
|
394
500
|
ruleset = syscall(NR_LANDLOCK_CREATE, attr_buffer, len(attr), 0)
|
|
@@ -402,7 +508,8 @@ def landlock_ruleset(roots, system_roots, network_mediated):
|
|
|
402
508
|
for root in roots["read"]:
|
|
403
509
|
rule(root["fd"], FS_READ)
|
|
404
510
|
for root in roots["write"]:
|
|
405
|
-
|
|
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)
|
|
406
513
|
opened = []
|
|
407
514
|
try:
|
|
408
515
|
for path in system_roots:
|
|
@@ -471,6 +578,8 @@ class Broker:
|
|
|
471
578
|
self.sockets = {}
|
|
472
579
|
self.lock = threading.Lock()
|
|
473
580
|
self.counts = {}
|
|
581
|
+
# Creation modes are the command's (its umask is applied explicitly), never the broker's.
|
|
582
|
+
os.umask(0)
|
|
474
583
|
|
|
475
584
|
# Target memory and descriptors are opened first and then checked with ID_VALID, so a
|
|
476
585
|
# recycled PID can never be read in place of the notifying task.
|
|
@@ -522,7 +631,24 @@ class Broker:
|
|
|
522
631
|
value = os.readlink("/proc/%d/%s" % (pid, name))
|
|
523
632
|
if not self.valid(ident):
|
|
524
633
|
raise OSError(errno.ESRCH, "Target exited")
|
|
525
|
-
return value
|
|
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
|
|
526
652
|
|
|
527
653
|
# Every mutation is applied to an O_PATH descriptor resolved from the pinned write roots by
|
|
528
654
|
# the native helper's own no-follow traversal, never to a string the target can change.
|
|
@@ -554,7 +680,7 @@ class Broker:
|
|
|
554
680
|
os.close(parent)
|
|
555
681
|
|
|
556
682
|
def in_scope(self, obj):
|
|
557
|
-
where = os.readlink("/proc/self/fd/%d" % obj)
|
|
683
|
+
where = self.rebase(os.readlink("/proc/self/fd/%d" % obj))
|
|
558
684
|
if not where.startswith("/") or where.endswith(" (deleted)"):
|
|
559
685
|
raise Denied()
|
|
560
686
|
candidate = self.resolve(where, False)
|
|
@@ -566,6 +692,17 @@ class Broker:
|
|
|
566
692
|
raise Denied()
|
|
567
693
|
|
|
568
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):
|
|
569
706
|
dirfd = ctypes.c_int32(dirfd & 0xFFFFFFFF).value
|
|
570
707
|
follow = follow_default and not (flags & AT_SYMLINK_NOFOLLOW)
|
|
571
708
|
path = None if address == 0 else os.fsdecode(self.string(mem, address))
|
|
@@ -614,6 +751,8 @@ class Broker:
|
|
|
614
751
|
if name == "listen":
|
|
615
752
|
return self.listen(ident, pid, args)
|
|
616
753
|
mem = self.memory(pid, ident)
|
|
754
|
+
if name in FILE_OPS:
|
|
755
|
+
return self.file_op(ident, pid, mem, name, args)
|
|
617
756
|
if name == "connect":
|
|
618
757
|
return self.connect(ident, pid, mem, args)
|
|
619
758
|
if name == "bind":
|
|
@@ -706,6 +845,312 @@ class Broker:
|
|
|
706
845
|
return 0, 0
|
|
707
846
|
return None, errno.ENOSYS
|
|
708
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
|
+
|
|
709
1154
|
def socket(self, ident, args):
|
|
710
1155
|
domain = args[0] & 0xFFFFFFFF
|
|
711
1156
|
kind = args[1] & 0xFFFFFFFF
|
|
@@ -774,9 +1219,12 @@ class Broker:
|
|
|
774
1219
|
raise OSError(errno.ECONNREFUSED, "Not a socket")
|
|
775
1220
|
return obj, "/proc/self/fd/%d" % obj
|
|
776
1221
|
try:
|
|
777
|
-
parent, final,
|
|
1222
|
+
parent, final, resolved, _ = self.files.resolve(path, True, False, 0, False)
|
|
778
1223
|
except (self.native.ScopeDenied, ValueError):
|
|
779
1224
|
raise Denied()
|
|
1225
|
+
if write_denied(resolved):
|
|
1226
|
+
os.close(parent)
|
|
1227
|
+
raise Denied()
|
|
780
1228
|
return parent, "/proc/self/fd/%d/%s" % (parent, final)
|
|
781
1229
|
|
|
782
1230
|
@staticmethod
|
|
@@ -817,8 +1265,10 @@ class Broker:
|
|
|
817
1265
|
finally:
|
|
818
1266
|
os.close(handle)
|
|
819
1267
|
_, address, _, _ = self.inet_address(raw, size)
|
|
820
|
-
# Restricted none/allowlist listens on loopback only (product decision)
|
|
821
|
-
|
|
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")):
|
|
822
1272
|
return None, errno.EACCES
|
|
823
1273
|
copied = ctypes.create_string_buffer(raw, size)
|
|
824
1274
|
if libc.bind(own, copied, ctypes.c_uint32(size)) < 0:
|
|
@@ -909,6 +1359,10 @@ class Broker:
|
|
|
909
1359
|
elif value != "sent":
|
|
910
1360
|
self.respond(ident, value, code)
|
|
911
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.
|
|
912
1366
|
def loop(self, stop):
|
|
913
1367
|
poller = select.poll()
|
|
914
1368
|
poller.register(self.listener, select.POLLIN)
|
|
@@ -1143,7 +1597,9 @@ def reap(session):
|
|
|
1143
1597
|
|
|
1144
1598
|
def run(request, report):
|
|
1145
1599
|
machine, table = arch()
|
|
1146
|
-
|
|
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"))
|
|
1147
1603
|
status = probe_static(table, request.get("candidateArch") is True)
|
|
1148
1604
|
if status:
|
|
1149
1605
|
raise Refused("UNAVAILABLE", status)
|
|
@@ -1161,8 +1617,10 @@ def run(request, report):
|
|
|
1161
1617
|
os.set_inheritable(cwd, False)
|
|
1162
1618
|
# The staged runtime directory (trusted, consumer-verified) stays readable for the helper.
|
|
1163
1619
|
system_roots = list(request.get("systemRoots", DEFAULT_SYSTEM_ROOTS))
|
|
1164
|
-
|
|
1165
|
-
|
|
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")
|
|
1166
1624
|
pinned_fds = [r["fd"] for r in roots["read"] + roots["write"]]
|
|
1167
1625
|
launch = {"event": "launch", "arch": machine, "validated": machine in VALIDATED_ARCHES,
|
|
1168
1626
|
"landlockAbi": landlock_abi(), "roots": seen,
|
|
@@ -1234,7 +1692,8 @@ def run(request, report):
|
|
|
1234
1692
|
if native_in is not None:
|
|
1235
1693
|
os.close(native_in)
|
|
1236
1694
|
body = dict(request.get("native", {}))
|
|
1237
|
-
|
|
1695
|
+
# restricted native writes honour the mandatory write denies too
|
|
1696
|
+
body["roots"] = dict(roots, denyWrites=True)
|
|
1238
1697
|
data = json.dumps(body).encode()
|
|
1239
1698
|
while data:
|
|
1240
1699
|
data = data[os.write(native_out, data):]
|
|
@@ -1305,6 +1764,8 @@ def probe_static(table, candidate=False):
|
|
|
1305
1764
|
return "Restricted Linux execution requires Linux"
|
|
1306
1765
|
if table is None:
|
|
1307
1766
|
return "No syscall inventory exists for %s" % machine
|
|
1767
|
+
if SELF_PROTECTION:
|
|
1768
|
+
return SELF_PROTECTION
|
|
1308
1769
|
if machine not in VALIDATED_ARCHES and not candidate:
|
|
1309
1770
|
return "The syscall inventory is not validated on %s" % machine
|
|
1310
1771
|
abi = landlock_abi()
|
|
@@ -1346,6 +1807,10 @@ def probe_primitives(candidate):
|
|
|
1346
1807
|
if pid == 0:
|
|
1347
1808
|
try:
|
|
1348
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)
|
|
1349
1814
|
if libc.prctl(38, 1, 0, 0, 0) != 0:
|
|
1350
1815
|
os._exit(3)
|
|
1351
1816
|
attr = struct.pack("QQQ", FS_ALL, NET_CONNECT_TCP, SCOPE_ALL)
|