@capybara-hq/plugin-sdk 0.1.0-rc.38 → 0.1.0-rc.39

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.
@@ -7,7 +7,10 @@
7
7
  * network: {kind: "none" | "environment"} | {kind: "endpoints", endpoints: [{address, port}]},
8
8
  * reportFd, cwd?, env?, argv (exec), timeoutMs? (exec), native (native-files request),
9
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)}`.
10
+ * memfd, used instead of the file beside the launcher), writeDenies? (exec: absolute paths the
11
+ * consumer resolved for this operation, denied like `SANDBOX_SYSTEM_WRITE_DENIES`),
12
+ * filesLockFd? (exec: an inherited descriptor of the device's files lock, a regular file outside
13
+ * every root, shared by all operations of the device; see native-files.py DeviceFilesLock)}`.
11
14
  * Root descriptors are pinned once by the consumer and inherited; the launcher verifies their
12
15
  * identity and never reopens a root pathname. Landlock rules, broker metadata checks and the
13
16
  * native helper all use those same descriptors. JSON events (`launch`, `exit`, `refused`) go to
@@ -49,7 +52,9 @@ def protect_self():
49
52
 
50
53
  SELF_PROTECTION = protect_self()
51
54
 
55
+ import contextlib
52
56
  import errno
57
+ import fcntl
53
58
  import importlib.machinery
54
59
  import importlib.util
55
60
  import ipaddress
@@ -84,10 +89,19 @@ import time
84
89
  # /proc/self/fd and /proc/self/maps reads). hidepid needs a mount and PID namespaces need new
85
90
  # privileges, both outside this launcher's design. Consumers keep secrets out of command lines.
86
91
  # - Network none/allowlist: TCP sockets may bind and listen on loopback (127.0.0.1, ::1) only;
87
- # connections go only to the endpoints the consumer granted. Environment lifts that filter.
92
+ # connections go only to the endpoints the consumer granted. A command's own loopback listener
93
+ # is reachable from outside the sandbox, never from the command's own client: the broker cannot
94
+ # tell an own listener from another process's at the address dialled (a listener can be
95
+ # re-listened after another socket took its port, or share it through SO_REUSEPORT).
96
+ # SO_REUSEPORT and its group programs (SO_ATTACH_REUSEPORT_CBPF / EBPF) are refused (EPERM), and
97
+ # a socket with SO_REUSEPORT set never binds or listens: joining a foreign service's reuseport
98
+ # group would receive that service's connections. Environment lifts that filter.
88
99
  # - UNIX sockets in every network kind: stream/seqpacket only (datagram and raw are refused);
89
- # pathname connect/bind only to sockets inside the write roots, resolved through the pinned
90
- # descriptors; abstract and unnamed addresses are refused. socketpair() is unaffected.
100
+ # a pathname bind only inside the write roots, resolved through the pinned descriptors, and a
101
+ # pathname connect only to a socket this operation bound itself (its dev and inode recorded at
102
+ # the brokered bind), never to one another process made, even inside a write root (a user
103
+ # D-Bus, a rootless docker.sock, ssh-agent, tmux); abstract and unnamed addresses are refused.
104
+ # socketpair() is unaffected.
91
105
  # - The launcher makes itself non-dumpable before anything else (protect_self), so a same-uid
92
106
  # process outside the operation cannot ptrace it or read its mem, environ or fd afterwards.
93
107
  # The window between the interpreter's exec and that first statement remains: only a tracer
@@ -130,6 +144,7 @@ ARCHES = {
130
144
  "lremovexattr": 15, "fremovexattr": 16, "ioctl": 29, "fchmod": 52, "fchmodat": 53,
131
145
  "fchownat": 54, "fchown": 55, "utimensat": 88, "unshare": 97, "setsid": 157,
132
146
  "socket": 198, "socketpair": 199, "bind": 200, "listen": 201, "connect": 203, "sendto": 206,
147
+ "setsockopt": 208,
133
148
  "sendmsg": 211, "add_key": 217, "request_key": 218, "keyctl": 219, "clone": 220,
134
149
  "setns": 268, "sendmmsg": 269, "userfaultfd": 282,
135
150
  "mknodat": 33, "mkdirat": 34, "unlinkat": 35, "symlinkat": 36, "linkat": 37,
@@ -142,7 +157,7 @@ ARCHES = {
142
157
  "x32": True,
143
158
  "nr": {
144
159
  "ioctl": 16, "socket": 41, "connect": 42, "sendto": 44, "sendmsg": 46, "bind": 49,
145
- "listen": 50, "socketpair": 53, "clone": 56, "chmod": 90, "fchmod": 91, "chown": 92, "fchown": 93,
160
+ "listen": 50, "socketpair": 53, "setsockopt": 54, "clone": 56, "chmod": 90, "fchmod": 91, "chown": 92, "fchown": 93,
146
161
  "lchown": 94, "setsid": 112, "utime": 132, "uselib": 134, "setxattr": 188,
147
162
  "lsetxattr": 189, "fsetxattr": 190, "removexattr": 197, "lremovexattr": 198,
148
163
  "fremovexattr": 199, "utimes": 235, "add_key": 248, "request_key": 249,
@@ -207,6 +222,14 @@ AF_UNSPEC, AF_UNIX, AF_INET, AF_INET6, AF_NETLINK = 0, 1, 2, 10, 16
207
222
  SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET = 1, 2, 5
208
223
  SOCK_NONBLOCK, SOCK_CLOEXEC = 0o4000, 0o2000000
209
224
  SOL_SOCKET, SO_DOMAIN, IPPROTO_TCP = 1, 39, 6
225
+ SO_REUSEPORT, SO_ATTACH_REUSEPORT_CBPF, SO_ATTACH_REUSEPORT_EBPF = 15, 51, 52
226
+ LOOPBACK = ("127.0.0.1", "::1")
227
+ # How long a guarded directory move waits for the device's other writes (a FIFO open waiting
228
+ # for its peer holds them) before it fails with EBUSY.
229
+ EXCLUSIVE_WAIT_S = 5
230
+ # The faultInjection seam's pause before a named mkdir, and the marker announcing it.
231
+ PAUSE_S = 2
232
+ PAUSE_MARKER = ".capybara-test-paused"
210
233
  AT_FDCWD = -100
211
234
  AT_SYMLINK_NOFOLLOW = 0x100
212
235
  AT_EMPTY_PATH = 0x1000
@@ -376,10 +399,25 @@ def build_filter(table, network_mediated, brokered):
376
399
  p.jeq(nr["unshare"], "namespaces")
377
400
  p.jeq(nr["clone"], "namespaces")
378
401
  if network_mediated:
402
+ p.jeq(nr["setsockopt"], "setsockopt")
379
403
  p.jeq(nr["sendto"], "fastopen3")
380
404
  p.jeq(nr["sendmmsg"], "fastopen3")
381
405
  p.jeq(nr["sendmsg"], "fastopen2")
382
406
  p.ret(RET_ALLOW)
407
+ if network_mediated:
408
+ # SO_REUSEPORT and its group programs: joining a foreign service's reuseport group would
409
+ # receive that service's connections (kept close to the dispatch: jumps reach 255 at most)
410
+ p.label("setsockopt")
411
+ p.ld_arg(1)
412
+ p.jeq(SOL_SOCKET, "sockopt_name")
413
+ p.ret(RET_ALLOW)
414
+ p.label("sockopt_name")
415
+ p.ld_arg(2)
416
+ for option in (SO_REUSEPORT, SO_ATTACH_REUSEPORT_CBPF, SO_ATTACH_REUSEPORT_EBPF):
417
+ p.jeq(option, "sockopt_eperm")
418
+ p.ret(RET_ALLOW)
419
+ p.label("sockopt_eperm")
420
+ p.ret(RET_ERRNO(errno.EPERM))
383
421
  for number, action in simple.items():
384
422
  p.label("r%d" % number)
385
423
  p.ret(action)
@@ -552,8 +590,8 @@ def socket_domain(fd):
552
590
  return struct.unpack("i", socket_option(fd, SOL_SOCKET, SO_DOMAIN))[0]
553
591
 
554
592
 
555
- def socket_name(fd):
556
- """The bound IP address of a broker-owned socket (0.0.0.0 / :: when unbound)."""
593
+ def socket_address(fd):
594
+ """The bound (IP address, port) of a broker-owned socket ((0.0.0.0 / ::, 0) when unbound)."""
557
595
  buffer = ctypes.create_string_buffer(128)
558
596
  length = ctypes.c_uint32(128)
559
597
  if libc.getsockname(fd, buffer, ctypes.byref(length)) < 0:
@@ -561,22 +599,110 @@ def socket_name(fd):
561
599
  raise OSError(code, os.strerror(code))
562
600
  raw = buffer.raw[:length.value]
563
601
  family = struct.unpack("H", raw[:2])[0]
602
+ port = struct.unpack(">H", raw[2:4])[0]
564
603
  if family == AF_INET:
565
- return str(ipaddress.ip_address(raw[4:8]))
604
+ return str(ipaddress.ip_address(raw[4:8])), port
566
605
  if family == AF_INET6:
567
- return str(ipaddress.ip_address(raw[8:24]))
568
- return None
606
+ return str(ipaddress.ip_address(raw[8:24])), port
607
+ return None, None
608
+
609
+
610
+ def socket_name(fd):
611
+ """The bound IP address of a broker-owned socket (0.0.0.0 / :: when unbound)."""
612
+ return socket_address(fd)[0]
613
+
614
+
615
+ def socket_int(fd, name):
616
+ return struct.unpack("i", socket_option(fd, SOL_SOCKET, name))[0]
617
+
618
+
619
+ def add_write_denies(paths, *modules):
620
+ """Absolute write denies the consumer resolved for this operation (a protected home location
621
+ reached through a link, at its resolved target): denied with everything beneath them, and
622
+ guarded against a prepared directory or a link moved onto a proper prefix, exactly like
623
+ SYSTEM_WRITE_DENIES. Extends the policy of this process and of the given modules (one
624
+ operation per launcher process)."""
625
+ if not isinstance(paths, list) or not all(
626
+ isinstance(p, str) and p.startswith("/") and os.path.normpath(p) == p for p in paths):
627
+ raise Refused("INVALID_REQUEST", "Supply absolute normalized write denies")
628
+ folded = [_fold_parts(p) for p in paths]
629
+ for policy in (globals(),) + tuple(vars(m) for m in modules):
630
+ if "SYSTEM_WRITE_DENIES" in policy and "PREFIX_GUARDED" in policy:
631
+ policy["SYSTEM_WRITE_DENIES"].extend(folded)
632
+ policy["PREFIX_GUARDED"].extend((names, True) for names in folded)
633
+
634
+
635
+ class SharedLock:
636
+ """Many shared holders or one exclusive holder. New shared holders are not held back by a
637
+ waiting exclusive one: a shared holder may wait long (a FIFO open waiting for its peer)."""
638
+
639
+ def __init__(self):
640
+ self.condition = threading.Condition()
641
+ self.readers = 0
642
+ self.writer = False
643
+
644
+ @contextlib.contextmanager
645
+ def shared(self):
646
+ with self.condition:
647
+ while self.writer:
648
+ self.condition.wait()
649
+ self.readers += 1
650
+ try:
651
+ yield
652
+ finally:
653
+ with self.condition:
654
+ self.readers -= 1
655
+ self.condition.notify_all()
656
+
657
+ @contextlib.contextmanager
658
+ def exclusive(self, timeout):
659
+ """Raises EBUSY when the shared holders do not leave within timeout seconds."""
660
+ deadline = time.monotonic() + timeout
661
+ with self.condition:
662
+ while self.writer or self.readers:
663
+ left = deadline - time.monotonic()
664
+ if left <= 0:
665
+ raise OSError(errno.EBUSY, "The operation's other writes did not finish")
666
+ self.condition.wait(left)
667
+ self.writer = True
668
+ try:
669
+ yield
670
+ finally:
671
+ with self.condition:
672
+ self.writer = False
673
+ self.condition.notify_all()
674
+
675
+
676
+ class NeedsExclusive(Exception):
677
+ """A directory move into a guarded prefix: redone holding the files lock exclusively."""
569
678
 
570
679
 
571
680
  class Broker:
572
- def __init__(self, native, roots, table, endpoints, listener):
681
+ def __init__(self, native, roots, table, endpoints, listener, files_lock=None):
573
682
  self.native = native
574
683
  self.files = native.NativeFiles(roots)
575
684
  self.names = {number: name for name, number in dict(table["nr"], **COMMON).items()}
576
685
  self.endpoints = endpoints
577
686
  self.listener = listener
578
687
  self.sockets = {}
688
+ # (st_dev, st_ino) of every pathname UNIX socket this operation bound through the broker:
689
+ # the only sockets a pathname connect may reach. A socket another process made, even one
690
+ # inside a write root (a user D-Bus, a rootless docker.sock, ssh-agent, tmux), stays
691
+ # unreachable, as no sandboxed client connects to a foreign loopback listener either.
692
+ self.unix_bound = set()
579
693
  self.lock = threading.Lock()
694
+ # Every mutating file operation holds this shared; a directory move into a guarded prefix
695
+ # holds it exclusively (staging, listing and the final rename). With the consumer's
696
+ # "filesLockFd" it is the device's lock, so the exclusion spans every operation of the
697
+ # device; without one it spans this operation only.
698
+ self.files_lock = files_lock or SharedLock()
699
+ # A failure the broker could not undo: the supervisor ends the operation and reports it.
700
+ self.fatal = None
701
+ # A test fixture's injected faults (request "faultInjection"); never set in production:
702
+ # fault "fail" fails a staged move; pause_mkdir names a mkdir that, once checked, marks its
703
+ # parent (PAUSE_MARKER) and waits PAUSE_S before its effect.
704
+ self.fault = None
705
+ self.pause_mkdir = None
580
706
  self.counts = {}
581
707
  # Creation modes are the command's (its umask is applied explicitly), never the broker's.
582
708
  os.umask(0)
@@ -751,13 +877,18 @@ class Broker:
751
877
  if name == "listen":
752
878
  return self.listen(ident, pid, args)
753
879
  mem = self.memory(pid, ident)
754
- if name in FILE_OPS:
755
- return self.file_op(ident, pid, mem, name, args)
756
880
  if name == "connect":
757
881
  return self.connect(ident, pid, mem, args)
758
- if name == "bind":
759
- return self.bind(ident, pid, mem, args)
760
- return self.metadata(ident, pid, mem, name, args)
882
+ try:
883
+ with self.files_lock.shared():
884
+ if name in FILE_OPS:
885
+ return self.file_op(ident, pid, mem, name, args)
886
+ if name == "bind":
887
+ return self.bind(ident, pid, mem, args)
888
+ return self.metadata(ident, pid, mem, name, args)
889
+ except NeedsExclusive:
890
+ with self.files_lock.exclusive(EXCLUSIVE_WAIT_S):
891
+ return self.file_op(ident, pid, mem, name, args, exclusive=True)
761
892
  except Denied:
762
893
  return None, errno.EACCES
763
894
  except OSError as error:
@@ -920,6 +1051,162 @@ class Broker:
920
1051
  if creates_entry and _fold_parts(name) == [".git"]:
921
1052
  raise Denied()
922
1053
 
1054
+ # ---- post-effect verification ------------------------------------------------------------
1055
+ # A write is checked on the path its parent descriptor had, then applied through that
1056
+ # descriptor. The device's files lock keeps every sandboxed guarded move out of that window,
1057
+ # but a process outside the sandbox can still move the parent meanwhile. So after each
1058
+ # descriptor-relative create or rename the broker reads where the parent sits now and, when
1059
+ # the entry landed at a denied path, undoes the effect and refuses; an effect it cannot undo
1060
+ # ends the operation (fail).
1061
+
1062
+ def placed(self, parent, name):
1063
+ """name below the parent descriptor, at the parent's current path (rebased onto the
1064
+ pinned roots' recorded paths); None when the parent is no longer reachable."""
1065
+ try:
1066
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % parent))
1067
+ except OSError:
1068
+ return None
1069
+ if not where.startswith("/") or where.endswith(" (deleted)"):
1070
+ return None
1071
+ return where.rstrip("/") + "/" + name
1072
+
1073
+ def verify(self, denied, undo, what):
1074
+ """Undoes an applied effect and refuses it when denied() says it landed somewhere denied
1075
+ (denied reads the entry's current place); an undo that fails ends the operation."""
1076
+ try:
1077
+ if not denied():
1078
+ return
1079
+ except Denied:
1080
+ pass
1081
+ try:
1082
+ undo()
1083
+ except OSError as error:
1084
+ self.fail("%s landed at a protected path after its check and could not be undone (%s)"
1085
+ % (what, error.strerror))
1086
+ raise Denied()
1087
+
1088
+ def created_denied(self, parent, name, creates_entry=False, link=False):
1089
+ """Whether the entry name below parent now sits at a path the write policy denies."""
1090
+ now = self.placed(parent, name)
1091
+ if now is None:
1092
+ return False
1093
+ if write_denied(now) or (creates_entry and _fold_parts(name) == [".git"]):
1094
+ return True
1095
+ return link and bool(_prefix_next(_fold_parts(now)))
1096
+
1097
+ @staticmethod
1098
+ def remove_own(parent, name, ident, is_dir=False):
1099
+ """Removes the entry the broker just made (ident: its (st_dev, st_ino)), never another."""
1100
+ info = os.stat(name, dir_fd=parent, follow_symlinks=False)
1101
+ if (info.st_dev, info.st_ino) != ident:
1102
+ raise OSError(errno.ESTALE, "The created entry was replaced")
1103
+ if is_dir:
1104
+ os.rmdir(name, dir_fd=parent)
1105
+ else:
1106
+ os.unlink(name, dir_fd=parent)
1107
+
1108
+ @staticmethod
1109
+ def identity(parent, name):
1110
+ info = os.stat(name, dir_fd=parent, follow_symlinks=False)
1111
+ return info.st_dev, info.st_ino
1112
+
1113
+ def moved_denied(self, sparent, sname, dparent, dname, kinds):
1114
+ """Whether a rename, judged at its parents' current places, broke the write policy:
1115
+ kinds lists ((parent, name), is_dir) of each entry that moved, by its source."""
1116
+ source, destination = self.placed(sparent, sname), self.placed(dparent, dname)
1117
+ if source is None or destination is None:
1118
+ return False
1119
+ ends = {(sparent, sname): (source, destination), (dparent, dname): (destination, source)}
1120
+ for key, is_dir in kinds:
1121
+ origin, to = ends[key]
1122
+ # an unstaged directory landing at a guarded place was never listed there
1123
+ if move_denied(origin, to, is_dir) or (is_dir and _prefix_next(_fold_parts(to))):
1124
+ return True
1125
+ return write_denied(source) or write_denied(destination)
1126
+
1127
+ @staticmethod
1128
+ def move_back(sparent, sname, dparent, dname, flags):
1129
+ """Reverses a rename: an exchange is exchanged again, a move moved back (never replacing)."""
1130
+ back = RENAME_EXCHANGE if flags & RENAME_EXCHANGE else RENAME_NOREPLACE
1131
+ if libc.renameat2(dparent, os.fsencode(dname), sparent, os.fsencode(sname),
1132
+ ctypes.c_uint(back)) < 0:
1133
+ code = ctypes.get_errno()
1134
+ raise OSError(code, os.strerror(code))
1135
+
1136
+ def staged_move(self, sparent, sname, dparent, dname, origin, to):
1137
+ """A directory move into a guarded place (a proper prefix of a multi-component deny). The
1138
+ directory is first renamed to a fresh reserved staging name beside it, which the write
1139
+ policy denies to every sandboxed write, so no process of this or another operation can add
1140
+ the guarded next component while it is listed and checked there; it is then renamed into
1141
+ place with NOREPLACE. A refused or failed step moves it back to its source; when that
1142
+ fails too (its name was taken meanwhile) it goes to a quarantine name, also reserved, and
1143
+ the operation ends with the failure reported."""
1144
+ fault = self.fault == "fail"
1145
+ stage = RESERVED_NAME_PREFIX + os.urandom(8).hex()
1146
+ if libc.renameat2(sparent, os.fsencode(sname), sparent, os.fsencode(stage),
1147
+ ctypes.c_uint(RENAME_NOREPLACE)) < 0:
1148
+ return None, ctypes.get_errno()
1149
+ entries = self.listing(sparent, stage)
1150
+ if entries is None or move_denied(origin, to, True, entries):
1151
+ code = errno.EACCES
1152
+ elif fault:
1153
+ code = errno.EIO
1154
+ elif libc.renameat2(sparent, os.fsencode(stage), dparent, os.fsencode(dname),
1155
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0:
1156
+ def placed_denied():
1157
+ now = self.placed(dparent, dname)
1158
+ return now is not None and move_denied(origin, now, True,
1159
+ self.listing(dparent, dname))
1160
+ self.verify(placed_denied,
1161
+ lambda: self.move_back(sparent, sname, dparent, dname, 0), "A moved directory")
1162
+ return 0, 0
1163
+ else:
1164
+ code = ctypes.get_errno()
1165
+ if not fault and libc.renameat2(sparent, os.fsencode(stage), sparent, os.fsencode(sname),
1166
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0:
1167
+ return None, code
1168
+ quarantine = RESERVED_NAME_PREFIX + "quarantine-" + os.urandom(8).hex()
1169
+ moved = libc.renameat2(sparent, os.fsencode(stage), sparent, os.fsencode(quarantine),
1170
+ ctypes.c_uint(RENAME_NOREPLACE)) == 0
1171
+ try:
1172
+ where = self.rebase(os.readlink("/proc/self/fd/%d" % sparent))
1173
+ except OSError:
1174
+ where = os.path.dirname(origin)
1175
+ self.fail("A directory bound for %s could be moved neither into place nor back; it is in "
1176
+ "quarantine as %s" % (to, os.path.join(where, quarantine if moved else stage)))
1177
+ return None, code
1178
+
1179
+ @staticmethod
1180
+ def pause(parent):
1181
+ """The test seam's pause between a write's check and its effect, announced by a marker
1182
+ the broker creates in the parent it holds."""
1183
+ os.close(os.open(PAUSE_MARKER, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o644,
1184
+ dir_fd=parent))
1185
+ time.sleep(PAUSE_S)
1186
+
1187
+ def fail(self, message):
1188
+ """Ends the operation for a failure the broker could not undo: the supervisor kills the
1189
+ whole tree (as for a cancel) and reports the message in its exit event."""
1190
+ if self.fatal is None:
1191
+ self.fatal = message
1192
+ os.kill(os.getpid(), signal.SIGTERM)
1193
+
1194
+ @staticmethod
1195
+ def listing(parent, name):
1196
+ """The names in the directory name below parent, opened without following a link; None
1197
+ when it cannot be listed."""
1198
+ try:
1199
+ fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC,
1200
+ dir_fd=parent)
1201
+ except OSError:
1202
+ return None
1203
+ try:
1204
+ return os.listdir(fd)
1205
+ except OSError:
1206
+ return None
1207
+ finally:
1208
+ os.close(fd)
1209
+
923
1210
  def send_fd(self, ident, fd, cloexec):
924
1211
  data = struct.pack("QIIII", ident, ADDFD_SEND, fd, 0, os.O_CLOEXEC if cloexec else 0)
925
1212
  buffer = ctypes.create_string_buffer(data, len(data))
@@ -985,7 +1272,7 @@ class Broker:
985
1272
  os.set_blocking(fd, True)
986
1273
  return fd
987
1274
 
988
- def file_op(self, ident, pid, mem, name, args):
1275
+ def file_op(self, ident, pid, mem, name, args, exclusive=False):
989
1276
  if name in ("open", "openat", "creat"):
990
1277
  if name == "open":
991
1278
  dirfd, address, flags, mode = AT_FDCWD, args[0], args[1], args[2]
@@ -1010,9 +1297,35 @@ class Broker:
1010
1297
  parent, final, resolved = self.entry(path)
1011
1298
  else:
1012
1299
  parent, final, resolved = self.followed(path)
1300
+ tmpfile = flags & O_TMPFILE_BIT
1301
+ # truncation waits for the post-effect check (a read-only open truncates itself)
1302
+ truncate = flags & os.O_TRUNC and flags & os.O_ACCMODE != os.O_RDONLY
1013
1303
  try:
1014
- self.refuse(resolved, final, not flags & O_TMPFILE_BIT)
1015
- fd = self.open_entry(ident, parent, final, flags, mode & 0o7777 & ~umask)
1304
+ self.refuse(resolved, final, not tmpfile)
1305
+ try:
1306
+ before = os.stat(final, dir_fd=parent, follow_symlinks=False)
1307
+ except FileNotFoundError:
1308
+ before = None
1309
+ fd = self.open_entry(ident, parent, final, flags & ~os.O_TRUNC if truncate
1310
+ else flags, mode & 0o7777 & ~umask)
1311
+ try:
1312
+ if tmpfile:
1313
+ # no name was made: the file vanishes with its descriptor
1314
+ self.verify(lambda: self.created_denied(parent, final),
1315
+ lambda: None, "A temporary file")
1316
+ else:
1317
+ info = os.fstat(fd)
1318
+ made = before is None and flags & os.O_CREAT
1319
+ self.verify(
1320
+ lambda: self.created_denied(parent, final, True),
1321
+ (lambda: self.remove_own(parent, final, (info.st_dev, info.st_ino)))
1322
+ if made else (lambda: None),
1323
+ "A created file" if made else "An opened file")
1324
+ if truncate and stat.S_ISREG(os.fstat(fd).st_mode):
1325
+ os.ftruncate(fd, 0)
1326
+ except BaseException:
1327
+ os.close(fd)
1328
+ raise
1016
1329
  finally:
1017
1330
  os.close(parent)
1018
1331
  try:
@@ -1030,13 +1343,21 @@ class Broker:
1030
1343
  try:
1031
1344
  if name.startswith("mkdir"):
1032
1345
  self.refuse(resolved, final)
1346
+ if self.pause_mkdir is not None and final == self.pause_mkdir:
1347
+ self.pause(parent)
1033
1348
  os.mkdir(final, mode & 0o7777 & ~umask, dir_fd=parent)
1349
+ made = self.identity(parent, final)
1350
+ self.verify(lambda: self.created_denied(parent, final),
1351
+ lambda: self.remove_own(parent, final, made, True), "A directory")
1034
1352
  else:
1035
1353
  kind = stat.S_IFMT(mode) or stat.S_IFREG
1036
1354
  if kind not in (stat.S_IFREG, stat.S_IFIFO, stat.S_IFSOCK):
1037
1355
  return None, errno.EPERM
1038
1356
  self.refuse(resolved, final, True)
1039
1357
  os.mknod(final, kind | (mode & 0o7777 & ~umask), 0, dir_fd=parent)
1358
+ made = self.identity(parent, final)
1359
+ self.verify(lambda: self.created_denied(parent, final, True),
1360
+ lambda: self.remove_own(parent, final, made), "A created node")
1040
1361
  finally:
1041
1362
  os.close(parent)
1042
1363
  return 0, 0
@@ -1067,7 +1388,15 @@ class Broker:
1067
1388
  parent, final, resolved = self.entry(self.path_arg(pid, ident, mem, dirfd, address))
1068
1389
  try:
1069
1390
  self.refuse(resolved, final, True)
1391
+ # a link named for a proper prefix of a multi-component deny (.config, .claude)
1392
+ # would redirect the protected entry beneath it; move_denied refuses moving one
1393
+ # there too
1394
+ if _prefix_next(_fold_parts(resolved)):
1395
+ raise Denied()
1070
1396
  os.symlink(target, final, dir_fd=parent)
1397
+ made = self.identity(parent, final)
1398
+ self.verify(lambda: self.created_denied(parent, final, True, link=True),
1399
+ lambda: self.remove_own(parent, final, made), "A symbolic link")
1071
1400
  finally:
1072
1401
  os.close(parent)
1073
1402
  return 0, 0
@@ -1093,6 +1422,16 @@ class Broker:
1093
1422
  raise Denied()
1094
1423
  os.link(sname, dname, src_dir_fd=sparent, dst_dir_fd=dparent,
1095
1424
  follow_symlinks=False)
1425
+ made = self.identity(dparent, dname)
1426
+
1427
+ def linked_denied():
1428
+ source_now = self.placed(sparent, sname)
1429
+ target_now = self.placed(dparent, dname)
1430
+ return self.created_denied(dparent, dname, True) or (
1431
+ source_now is not None and target_now is not None
1432
+ and move_denied(source_now, target_now, False))
1433
+ self.verify(linked_denied, lambda: self.remove_own(dparent, dname, made),
1434
+ "A hard link")
1096
1435
  finally:
1097
1436
  os.close(dparent)
1098
1437
  finally:
@@ -1116,20 +1455,37 @@ class Broker:
1116
1455
  try:
1117
1456
  self.refuse(sresolved, sname)
1118
1457
  self.refuse(dresolved, dname)
1119
- moves = [(sparent, sname, sresolved, dresolved)]
1458
+ moves = [((sparent, sname), sresolved, dresolved)]
1120
1459
  if flags & RENAME_EXCHANGE:
1121
- moves.append((dparent, dname, dresolved, sresolved))
1122
- for parent, entry, origin, to in moves:
1460
+ moves.append(((dparent, dname), dresolved, sresolved))
1461
+ staged = None
1462
+ kinds = []
1463
+ for (parent, entry), origin, to in moves:
1123
1464
  try:
1124
1465
  info = os.stat(entry, dir_fd=parent, follow_symlinks=False)
1125
1466
  except FileNotFoundError:
1126
1467
  continue
1468
+ is_dir = stat.S_ISDIR(info.st_mode)
1469
+ kinds.append(((parent, entry), is_dir))
1470
+ if is_dir and _prefix_next(_fold_parts(to)):
1471
+ # a directory bound for a guarded place: checked in staging
1472
+ if flags & RENAME_EXCHANGE:
1473
+ raise Denied()
1474
+ if not exclusive:
1475
+ raise NeedsExclusive()
1476
+ staged = (origin, to)
1477
+ continue
1127
1478
  # nothing leaves a protected name, nor is a directory moved under one
1128
- if move_denied(origin, to, stat.S_ISDIR(info.st_mode)):
1479
+ if move_denied(origin, to, is_dir):
1129
1480
  raise Denied()
1481
+ if staged is not None:
1482
+ return self.staged_move(sparent, sname, dparent, dname, *staged)
1130
1483
  if libc.renameat2(sparent, os.fsencode(sname), dparent, os.fsencode(dname),
1131
1484
  ctypes.c_uint(flags)) < 0:
1132
1485
  return None, ctypes.get_errno()
1486
+ self.verify(lambda: self.moved_denied(sparent, sname, dparent, dname, kinds),
1487
+ lambda: self.move_back(sparent, sname, dparent, dname, flags),
1488
+ "A move")
1133
1489
  finally:
1134
1490
  os.close(dparent)
1135
1491
  finally:
@@ -1142,6 +1498,13 @@ class Broker:
1142
1498
  try:
1143
1499
  self.refuse(resolved, final)
1144
1500
  fd = os.open(final, os.O_WRONLY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent)
1501
+ try:
1502
+ # checked again at the parent's current place before the effect
1503
+ self.verify(lambda: self.created_denied(parent, final), lambda: None,
1504
+ "A truncation")
1505
+ except BaseException:
1506
+ os.close(fd)
1507
+ raise
1145
1508
  finally:
1146
1509
  os.close(parent)
1147
1510
  try:
@@ -1261,15 +1624,20 @@ class Broker:
1261
1624
  buffer, length = self.unix_address(target)
1262
1625
  if libc.bind(own, buffer, ctypes.c_uint32(length)) < 0:
1263
1626
  return None, ctypes.get_errno()
1627
+ # the socket file bind created, through the same pinned parent descriptor
1628
+ created = os.lstat(target)
1629
+ with self.lock:
1630
+ self.unix_bound.add((created.st_dev, created.st_ino))
1264
1631
  return 0, 0
1265
1632
  finally:
1266
1633
  os.close(handle)
1267
1634
  _, address, _, _ = self.inet_address(raw, size)
1268
1635
  # Restricted none/allowlist listens on loopback only (product decision); environment
1269
1636
  # 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")):
1637
+ if address is None or (self.endpoints is not None and str(address) not in LOOPBACK):
1272
1638
  return None, errno.EACCES
1639
+ if self.endpoints is not None and socket_int(own, SO_REUSEPORT):
1640
+ return None, errno.EPERM # never into a foreign service's reuseport group
1273
1641
  copied = ctypes.create_string_buffer(raw, size)
1274
1642
  if libc.bind(own, copied, ctypes.c_uint32(size)) < 0:
1275
1643
  return None, ctypes.get_errno()
@@ -1290,6 +1658,10 @@ class Broker:
1290
1658
  host = socket_name(own)
1291
1659
  if host not in ("127.0.0.1", "::1"):
1292
1660
  return None, errno.EACCES
1661
+ if self.endpoints is not None and socket_domain(own) != AF_UNIX \
1662
+ and socket_int(own, SO_REUSEPORT):
1663
+ self.release(inode)
1664
+ return None, errno.EPERM # never into a foreign service's reuseport group
1293
1665
  result = libc.listen(own, ctypes.c_int(args[1] & 0xFFFFFFFF))
1294
1666
  code = ctypes.get_errno() if result < 0 else 0
1295
1667
  # A listening socket never connects; drop the broker's reference so close semantics
@@ -1308,6 +1680,13 @@ class Broker:
1308
1680
  if socket_domain(own) == AF_UNIX:
1309
1681
  handle, target = self.unix_target(pid, ident, raw, False)
1310
1682
  try:
1683
+ # only a socket this operation bound itself: the descriptor pins the inode, and
1684
+ # the connect goes through it, so a swapped path cannot change what is reached
1685
+ found = os.fstat(handle)
1686
+ with self.lock:
1687
+ own_socket = (found.st_dev, found.st_ino) in self.unix_bound
1688
+ if not own_socket:
1689
+ return None, errno.EACCES
1311
1690
  buffer, length = self.unix_address(target)
1312
1691
  result = libc.connect(own, buffer, ctypes.c_uint32(length))
1313
1692
  code = ctypes.get_errno() if result < 0 else 0
@@ -1363,6 +1742,13 @@ class Broker:
1363
1742
  # shared mutable state across its steps (socket ownership is locked): every check is made on
1364
1743
  # the broker's own resolution, and every effect is one syscall on descriptors that handler
1365
1744
  # holds, so concurrent notifications interleave only as the kernel would interleave the calls.
1745
+ # The one multi-step check, a directory move into a guarded prefix (staging, listing, rename),
1746
+ # holds the files lock exclusively (waiting at most EXCLUSIVE_WAIT_S, then EBUSY) while every
1747
+ # other write holds it shared from its check to its effect. With the consumer's device lock
1748
+ # this spans every operation of the device: no write of another operation can be checked
1749
+ # against a parent that such a move relocates before the write's effect (its staging name is
1750
+ # reserved too, so no path-based write reaches it). Each create or rename is then verified at
1751
+ # its parent's current place (verify), which covers moves made outside every sandbox.
1366
1752
  def loop(self, stop):
1367
1753
  poller = select.poll()
1368
1754
  poller.register(self.listener, select.POLLIN)
@@ -1480,6 +1866,39 @@ def endpoints_of(network):
1480
1866
  raise Refused("INVALID_REQUEST", "Unknown network kind")
1481
1867
 
1482
1868
 
1869
+ def device_files_lock(request, roots, system_roots):
1870
+ """The inherited descriptor of the device's files lock ("filesLockFd", exec mode), or None.
1871
+
1872
+ It must be a regular file outside every root this command reads or writes (and every system
1873
+ root): the restricted command could otherwise open it and hold it, stalling the device's
1874
+ writes. The descriptor itself never reaches the command (close_except before exec)."""
1875
+ fd = request.get("filesLockFd")
1876
+ if fd is None:
1877
+ return None
1878
+ if request.get("mode") != "exec" or not isinstance(fd, int) or isinstance(fd, bool) or fd < 3:
1879
+ raise Refused("INVALID_REQUEST", "A files lock descriptor serves exec mode only")
1880
+ try:
1881
+ info = os.fstat(fd)
1882
+ where = os.readlink("/proc/self/fd/%d" % fd)
1883
+ except OSError:
1884
+ raise Refused("INVALID_REQUEST", "The files lock descriptor is not open")
1885
+ if not stat.S_ISREG(info.st_mode) or not where.startswith("/") or where.endswith(" (deleted)"):
1886
+ raise Refused("INVALID_REQUEST", "The files lock is not a regular file")
1887
+ reach = [r["path"] for r in roots["read"] + roots["write"]] + list(system_roots)
1888
+ for entry in roots["read"] + roots["write"]:
1889
+ try:
1890
+ reach.append(os.readlink("/proc/self/fd/%d" % entry["fd"]))
1891
+ except OSError:
1892
+ pass
1893
+ for root in reach:
1894
+ root = os.path.normpath(root)
1895
+ if root == "/" or where == root or where.startswith(root + "/"):
1896
+ raise Refused("SCOPE_DENIED", "The device's files lock is inside the granted root %s"
1897
+ % root)
1898
+ os.set_inheritable(fd, False)
1899
+ return fd
1900
+
1901
+
1483
1902
  def restrict_child(table, ruleset, network_mediated, brokered, channel):
1484
1903
  """Runs in the forked child before exec: session, Landlock, seccomp, listener hand-off."""
1485
1904
  if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS
@@ -1604,6 +2023,7 @@ def run(request, report):
1604
2023
  if status:
1605
2024
  raise Refused("UNAVAILABLE", status)
1606
2025
  roots, seen = verify_roots(native, request)
2026
+ add_write_denies(request.get("writeDenies", []), native)
1607
2027
  network = request.get("network", {"kind": "none"})
1608
2028
  endpoints = endpoints_of(network)
1609
2029
  network_mediated = endpoints is not None
@@ -1619,6 +2039,7 @@ def run(request, report):
1619
2039
  system_roots = list(request.get("systemRoots", DEFAULT_SYSTEM_ROOTS))
1620
2040
  if request.get("nativeFd") is None:
1621
2041
  system_roots.append(os.path.dirname(native_path))
2042
+ files_lock = device_files_lock(request, roots, system_roots)
1622
2043
  ruleset = landlock_ruleset(roots, system_roots, network_mediated or mode == "native",
1623
2044
  mode == "exec")
1624
2045
  pinned_fds = [r["fd"] for r in roots["read"] + roots["write"]]
@@ -1706,7 +2127,13 @@ def run(request, report):
1706
2127
  if not fds:
1707
2128
  kill_tree()
1708
2129
  raise Refused("UNAVAILABLE", "The restricted child did not hand over its listener")
1709
- broker = Broker(native, roots, table, endpoints, fds[0])
2130
+ broker = Broker(native, roots, table, endpoints, fds[0],
2131
+ native.DeviceFilesLock(files_lock) if files_lock is not None else None)
2132
+ fault = request.get("faultInjection")
2133
+ if isinstance(fault, dict) and fault.get("stagedMove") == "fail":
2134
+ broker.fault = "fail" # a test fixture's seam
2135
+ if isinstance(fault, dict) and isinstance(fault.get("pauseBeforeMkdir"), str):
2136
+ broker.pause_mkdir = fault["pauseBeforeMkdir"] # a test fixture's seam
1710
2137
  thread = threading.Thread(target=broker.loop, args=(stop_r,), daemon=True)
1711
2138
  thread.start()
1712
2139
  # Reported only once every restriction is installed and the broker holds the listener.
@@ -1746,11 +2173,16 @@ def supervise(pid, request, report, broker, thread, stop_w, cancellation):
1746
2173
  if thread is not None:
1747
2174
  thread.join()
1748
2175
  counts = {}
2176
+ fatal = None
1749
2177
  if broker is not None:
1750
2178
  counts = dict(broker.counts)
2179
+ fatal = broker.fatal
1751
2180
  broker.close()
1752
- report.write({"event": "exit", "exitCode": exit_code, "timedOut": timed_out,
1753
- "cancelled": bool(cancelled), "killed": survivors, "brokered": counts})
2181
+ event = {"event": "exit", "exitCode": exit_code, "timedOut": timed_out,
2182
+ "cancelled": bool(cancelled), "killed": survivors, "brokered": counts}
2183
+ if fatal is not None:
2184
+ event["fatal"] = fatal
2185
+ report.write(event)
1754
2186
  if exit_code is None:
1755
2187
  return 124 if timed_out else 143
1756
2188
  return exit_code if exit_code >= 0 else 128 - exit_code