Debian Codegraph @

testsuite/daemon-leaf-type-race-fchmod_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """A leaf type race must not make the receiver chmod a directory.
3
4 The secure resolver probes a non-directory leaf with ``O_DIRECTORY`` and then
5 opens it again with the caller's flags. A Darwin interposer pauses after the
6 second failed probe and asks a separately sandboxed path controller to replace
7 the regular file with a directory. The sandbox proves that the controller can
8 rename the entries but cannot chmod the directory itself. A vulnerable
9 receiver accepts the directory fd from the second open, changes it from 0755 to
10 0600, then leaves the change behind when its write-open fails with EISDIR.
11
12 Run via ``runtests.py --use-tcp`` outside an enclosing application sandbox.
13 """
14
15 from __future__ import annotations
16
17 import errno
18 import os
19 import platform
20 import select
21 import shlex
22 import socket
23 import stat
24 import subprocess
25 import sys
26 import time
27 from pathlib import Path
28
29
30 def racer_main(argv: list[str]) -> int:
31 if len(argv) != 5:
32 raise SystemExit("racer requires TARGET VICTIM OLD READY_FIFO DONE_FIFO")
33 target, victim, old, ready_fifo, done_fifo = map(Path, argv)
34
35 before = stat.S_IMODE(victim.stat().st_mode)
36 denied_errno = 0
37 try:
38 victim.chmod(0o600)
39 except OSError as exc:
40 denied_errno = exc.errno or 0
41 after = stat.S_IMODE(victim.stat().st_mode)
42 denied = denied_errno in (errno.EPERM, errno.EACCES) and after == before
43 print(
44 "RACER_DIRECT_CHMOD"
45 f" denied={denied} errno={denied_errno}"
46 f" before={before:04o} after={after:04o}",
47 flush=True,
48 )
49 if not denied:
50 return 2
51
52 with ready_fifo.open("rb", buffering=0) as ready:
53 if ready.read(1) != b"R":
54 return 3
55
56 target.rename(old)
57 victim.rename(target)
58 mode_at_swap = stat.S_IMODE(target.stat().st_mode)
59 print(
60 "RACER_SWAP target_to_old=True victim_to_target=True"
61 f" mode_before_ack={mode_at_swap:04o}",
62 flush=True,
63 )
64 if mode_at_swap != before:
65 return 4
66
67 with done_fifo.open("wb", buffering=0) as done:
68 done.write(b"D")
69 return 0
70
71
72 # Enter helper mode before importing the test harness, which requires runner
73 # environment variables and owns the daemon-port bookkeeping.
74 if len(sys.argv) > 1 and sys.argv[1] == "--racer":
75 sys.exit(racer_main(sys.argv[2:]))
76
77
78 from rsyncfns import ( # noqa: E402
79 RSYNC,
80 RSYNC_PEER,
81 SCRATCHDIR,
82 claim_ports,
83 require_tcp,
84 rmtree,
85 test_fail,
86 test_skipped, split_rsync_cmd,
87 )
88
89
90 PORT = 13213
91 SANDBOX_PROFILE = "(version 1)(allow default)(deny file-write-mode)"
92
93 INTERPOSER_SOURCE = r"""
94 #include <errno.h>
95 #include <fcntl.h>
96 #include <stdarg.h>
97 #include <stdint.h>
98 #include <stdio.h>
99 #include <stdlib.h>
100 #include <string.h>
101 #include <sys/syscall.h>
102 #include <unistd.h>
103
104 static int probes;
105 static int synchronizing;
106
107 __attribute__((constructor))
108 static void race_interposer_loaded(void)
109 {
110 static const char marker[] = "LEAF_TYPE_RACE interposer_loaded\n";
111 (void)write(STDERR_FILENO, marker, sizeof marker - 1);
112 }
113
114 static int real_openat(int dfd, const char *path, int flags, mode_t mode)
115 {
116 return (int)syscall(SYS_openat, dfd, path, flags, mode);
117 }
118
119 static int send_ready(const char *path)
120 {
121 char byte = 'R';
122 int fd = open(path, O_WRONLY);
123 int ok = fd >= 0 && write(fd, &byte, 1) == 1;
124 int saved = errno;
125 if (fd >= 0)
126 close(fd);
127 errno = saved;
128 return ok ? 0 : -1;
129 }
130
131 static int await_done(const char *path)
132 {
133 char byte;
134 int fd = open(path, O_RDONLY);
135 int ok = fd >= 0 && read(fd, &byte, 1) == 1 && byte == 'D';
136 int saved = errno;
137 if (fd >= 0)
138 close(fd);
139 errno = saved;
140 return ok ? 0 : -1;
141 }
142
143 static void synchronize_with_racer(void)
144 {
145 const char *ready = getenv("LEAF_TYPE_RACE_READY_FIFO");
146 const char *done = getenv("LEAF_TYPE_RACE_DONE_FIFO");
147 static const char probe[] = "LEAF_TYPE_RACE probe_returned\n";
148 static const char ack[] = "LEAF_TYPE_RACE racer_acknowledged\n";
149 static const char failed[] = "LEAF_TYPE_RACE synchronization_failed\n";
150
151 (void)write(STDERR_FILENO, probe, sizeof probe - 1);
152 if (!ready || !done || send_ready(ready) < 0 || await_done(done) < 0) {
153 (void)write(STDERR_FILENO, failed, sizeof failed - 1);
154 return;
155 }
156 (void)write(STDERR_FILENO, ack, sizeof ack - 1);
157 }
158
159 static int race_openat(int dfd, const char *path, int flags, ...)
160 {
161 const char *leaf = getenv("LEAF_TYPE_RACE_LEAF");
162 const char *trigger_text = getenv("LEAF_TYPE_RACE_TRIGGER");
163 mode_t mode = 0;
164 int rc, saved, trigger = trigger_text ? atoi(trigger_text) : 2;
165
166 if (flags & O_CREAT) {
167 va_list ap;
168 va_start(ap, flags);
169 mode = (mode_t)va_arg(ap, int);
170 va_end(ap);
171 }
172 rc = real_openat(dfd, path, flags, mode);
173 saved = errno;
174 if (!synchronizing && rc < 0 && (flags & O_DIRECTORY) && leaf
175 && strcmp(path, leaf) == 0 && ++probes == trigger) {
176 synchronizing = 1;
177 synchronize_with_racer();
178 synchronizing = 0;
179 }
180 errno = saved;
181 return rc;
182 }
183
184 __attribute__((used))
185 static const struct {
186 const void *replacement;
187 const void *replacee;
188 } race_openat_interpose __attribute__((section("__DATA,__interpose"))) = {
189 (const void *)(uintptr_t)&race_openat,
190 (const void *)(uintptr_t)&openat,
191 };
192 """
193
194
195 def wait_for_port(process: subprocess.Popen[bytes]) -> None:
196 deadline = time.monotonic() + 8
197 while time.monotonic() < deadline:
198 if process.poll() is not None:
199 raise RuntimeError(f"daemon exited during startup: {process.returncode}")
200 try:
201 with socket.create_connection(("127.0.0.1", PORT), timeout=0.1):
202 return
203 except OSError:
204 time.sleep(0.05)
205 raise RuntimeError("timeout waiting for daemon listener")
206
207
208 def stop_process(process: subprocess.Popen, timeout: float = 3) -> tuple:
209 if process.poll() is None:
210 process.terminate()
211 try:
212 return process.communicate(timeout=timeout)
213 except subprocess.TimeoutExpired:
214 process.kill()
215 return process.communicate(timeout=timeout)
216
217
218 if platform.system() != "Darwin":
219 test_skipped("leaf-type authority proof currently requires Darwin")
220 if os.geteuid() == 0:
221 test_skipped("leaf-type authority proof needs a non-root EACCES trigger")
222 sandbox_exec = Path("/usr/bin/sandbox-exec")
223 if not sandbox_exec.is_file():
224 test_skipped("/usr/bin/sandbox-exec is unavailable")
225
226 require_tcp("leaf-type race needs an injected real TCP daemon")
227 claim_ports(PORT)
228
229 module = SCRATCHDIR / "module"
230 source = SCRATCHDIR / "source"
231 # A prior vulnerable run intentionally leaves module/target as a mode-0600
232 # directory. Restore only that per-test object so a preserved scratch tree is
233 # removable on rerun.
234 if (module / "target").is_dir():
235 (module / "target").chmod(0o700)
236 rmtree(module)
237 rmtree(source)
238 module.mkdir(parents=True)
239 source.mkdir()
240 (source / "target").write_bytes(b"replacement data\n")
241 target = module / "target"
242 target.write_bytes(b"read-only basis\n")
243 target.chmod(0o400)
244 victim = module / "victim"
245 victim.mkdir()
246 victim.chmod(0o755)
247 (victim / "marker").write_text("protected directory\n", encoding="utf-8")
248 victim_inode = victim.stat().st_ino
249 old = module / "old"
250 ready_fifo = SCRATCHDIR / "ready.fifo"
251 done_fifo = SCRATCHDIR / "done.fifo"
252 ready_fifo.unlink(missing_ok=True)
253 done_fifo.unlink(missing_ok=True)
254 os.mkfifo(ready_fifo)
255 os.mkfifo(done_fifo)
256
257 interposer_source = SCRATCHDIR / "leaf_type_race_interposer.c"
258 interposer = SCRATCHDIR / "leaf_type_race_interposer.dylib"
259 interposer_source.write_text(INTERPOSER_SOURCE, encoding="utf-8")
260 compile_result = subprocess.run(
261 [
262 os.environ.get("CC", "cc"),
263 "-dynamiclib",
264 "-O2",
265 "-Wall",
266 "-Wextra",
267 "-o",
268 os.fspath(interposer),
269 os.fspath(interposer_source),
270 ],
271 stdout=subprocess.PIPE,
272 stderr=subprocess.PIPE,
273 text=True,
274 )
275 if compile_result.returncode != 0:
276 test_fail(f"interposer compilation failed: {compile_result.stderr}")
277
278 racer_command = [
279 os.fspath(sandbox_exec),
280 "-p",
281 SANDBOX_PROFILE,
282 sys.executable,
283 os.path.abspath(__file__),
284 "--racer",
285 os.fspath(target),
286 os.fspath(victim),
287 os.fspath(old),
288 os.fspath(ready_fifo.resolve()),
289 os.fspath(done_fifo.resolve()),
290 ]
291 racer = subprocess.Popen(
292 racer_command,
293 stdout=subprocess.PIPE,
294 stderr=subprocess.PIPE,
295 text=True,
296 bufsize=1,
297 )
298 assert racer.stdout is not None
299 readable, _, _ = select.select([racer.stdout], [], [], 5)
300 if not readable:
301 racer_stdout, racer_stderr = stop_process(racer)
302 test_fail(
303 "sandbox racer did not finish its authority preflight: "
304 f"stdout={racer_stdout!r} stderr={racer_stderr!r}"
305 )
306 preflight = racer.stdout.readline()
307 if "RACER_DIRECT_CHMOD denied=True" not in preflight:
308 racer_stdout, racer_stderr = stop_process(racer)
309 combined_stderr = racer_stderr or ""
310 if "sandbox_apply: Operation not permitted" in combined_stderr:
311 test_skipped("enclosing sandbox forbids nested sandbox-exec")
312 test_fail(
313 "sandbox racer retained chmod authority: "
314 f"preflight={preflight!r} stdout={racer_stdout!r}"
315 f" stderr={combined_stderr!r}"
316 )
317
318 config = SCRATCHDIR / "leaf-type-race.conf"
319 config.write_text(
320 f"pid file = {SCRATCHDIR / 'rsyncd.pid'}\n"
321 f"lock file = {SCRATCHDIR / 'rsyncd.lock'}\n"
322 f"log file = {SCRATCHDIR / 'rsyncd.log'}\n"
323 "address = 127.0.0.1\n"
324 f"port = {PORT}\n"
325 "use chroot = no\n"
326 "[mod]\n"
327 f" path = {module.resolve()}\n"
328 " read only = no\n"
329 " munge symlinks = no\n",
330 encoding="utf-8",
331 )
332
333 daemon_env = os.environ.copy()
334 daemon_env.update(
335 {
336 "DYLD_INSERT_LIBRARIES": os.fspath(interposer),
337 "DYLD_FORCE_FLAT_NAMESPACE": "1",
338 "LEAF_TYPE_RACE_LEAF": "target",
339 "LEAF_TYPE_RACE_TRIGGER": "2",
340 "LEAF_TYPE_RACE_READY_FIFO": os.fspath(ready_fifo.resolve()),
341 "LEAF_TYPE_RACE_DONE_FIFO": os.fspath(done_fifo.resolve()),
342 }
343 )
344 daemon_command = split_rsync_cmd(RSYNC_PEER) + [
345 "--daemon",
346 "--no-detach",
347 f"--config={config}",
348 ]
349 daemon = subprocess.Popen(
350 daemon_command,
351 stdout=subprocess.PIPE,
352 stderr=subprocess.PIPE,
353 env=daemon_env,
354 )
355
356 client = None
357 daemon_stdout = b""
358 daemon_stderr = b""
359 try:
360 wait_for_port(daemon)
361 client = subprocess.run(
362 split_rsync_cmd(RSYNC)
363 + [
364 "-rt",
365 "--inplace",
366 "--ignore-times",
367 "--contimeout=5",
368 os.fspath(source / "target"),
369 f"rsync://127.0.0.1:{PORT}/mod/target",
370 ],
371 stdout=subprocess.PIPE,
372 stderr=subprocess.STDOUT,
373 text=True,
374 timeout=20,
375 )
376 finally:
377 daemon_stdout, daemon_stderr = stop_process(daemon)
378
379 racer_tail, racer_stderr = stop_process(racer)
380 racer_stdout = preflight + (racer_tail or "")
381 daemon_text = (daemon_stderr or b"").decode("utf-8", "replace")
382 target_stat = target.stat() if target.exists() else None
383 target_mode = stat.S_IMODE(target_stat.st_mode) if target_stat else -1
384 result_line = (
385 "RACE_RESULT"
386 f" client_rc={client.returncode if client else 'missing'}"
387 f" target_type={'directory' if target.is_dir() else 'other'}"
388 f" target_mode={target_mode:04o}"
389 f" old_is_file={old.is_file()} victim_exists={victim.exists()}"
390 )
391
392 confirmed = (
393 client is not None
394 and client.returncode != 0
395 and "RACER_SWAP" in racer_stdout
396 and "mode_before_ack=0755" in racer_stdout
397 and "LEAF_TYPE_RACE probe_returned" in daemon_text
398 and "LEAF_TYPE_RACE racer_acknowledged" in daemon_text
399 and target.is_dir()
400 and target_mode == 0o600
401 and old.is_file()
402 and not victim.exists()
403 and target_stat is not None
404 and target_stat.st_ino == victim_inode
405 )
406
407 if confirmed:
408 test_fail(
409 "H013 CONFIRMED: a mode-denied path controller replaced the leaf after "
410 "the directory probe, and the receiver persistently chmodded the "
411 "substituted directory from 0755 to 0600\n"
412 f"{racer_stdout}{daemon_text}{client.stdout if client else ''}"
413 f"{result_line}\n"
414 )
415
416 if "LEAF_TYPE_RACE interposer_loaded" not in daemon_text:
417 test_fail("invalid leaf-type race control: the daemon did not load the interposer")
418 if "LEAF_TYPE_RACE synchronization_failed" in daemon_text:
419 test_fail(
420 "invalid leaf-type race control: synchronization failed\n"
421 f"{racer_stdout}{daemon_text}{result_line}\n"
422 )
423 if "LEAF_TYPE_RACE probe_returned" in daemon_text and "RACER_SWAP" not in racer_stdout:
424 test_fail(
425 "invalid leaf-type race control: the probe fired without a completed swap\n"
426 f"{racer_stdout}{daemon_text}{result_line}\n"
427 )
428 if "LEAF_TYPE_RACE probe_returned" not in daemon_text and (
429 not target.is_file()
430 or stat.S_IMODE(victim.stat().st_mode) != 0o755
431 ):
432 test_fail(
433 "invalid no-probe control: the old recovery path changed an entry\n"
434 f"{racer_stdout}{daemon_text}{client.stdout if client else ''}"
435 f"{result_line}\n"
436 )
437
438 if "RACER_SWAP" in racer_stdout and target_mode != 0o755:
439 test_fail(
440 "the raced victim directory changed unexpectedly: "
441 f"mode={target_mode:04o}\n{racer_stdout}{daemon_text}"
442 )
443
444 print("leaf type validation prevented chmod of the substituted directory")