Debian Codegraph @

testsuite/rename-fullpath-symlink-race_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Receiver write-escape via a symlink race on finish_transfer()'s tmp->final
3 # rename when an absolute --temp-dir (or --partial-dir) is in use.
4 #
5 # do_rename_at() (syscall.c) confines a rename relative to held dirfds, but it
6 # bailed out to the unconfined path-based do_rename() whenever EITHER path was
7 # absolute. With an absolute --temp-dir the receiver's temp file is an absolute
8 # path, so the tmp->final rename took that bail and re-resolved the destination
9 # from the path -- following a `dest/sub` component flipped from a directory to a
10 # symlink mid-transfer, landing the transferred file OUTSIDE the destination
11 # tree (an arbitrary write / LPE for a local attacker who can flip a dest parent).
12 #
13 # RED before the fix (files escape to outside/); GREEN once do_rename_at confines
14 # the relative destination even when the source temp path is absolute.
15 #
16 # Found by Omar Elsayed; this is the framework version of that demonstration,
17 # with no rsync.c instrumentation -- a separate-process flipper wins the race.
18
19 import os
20 import subprocess
21 import time
22
23 from rsyncfns import race_budget, SCRATCHDIR, rmtree, rsync_argv, test_fail
24
25 # Unique per-invocation base: this test's rename storm can corrupt the `dest`
26 # directory on some filesystems (OpenBSD FFS leaves an un-removable dir), and a
27 # fixed name would let that wreck block a later pass's setup. See _move_aside().
28 base = SCRATCHDIR / f'rename-fullpath-{os.getpid()}'
29 src = base / 'src'
30 dest = base / 'dest'
31 outside = base / 'outside'
32 tmpd = base / 'tmpd' # absolute --temp-dir, OUTSIDE the destination
33 rmtree(base)
34 (src / 'sub').mkdir(parents=True)
35 for i in range(40):
36 (src / 'sub' / f'f{i}').write_text('payload\n')
37 dest.mkdir()
38 outside.mkdir()
39 tmpd.mkdir()
40
41 sub = dest / 'sub' # the parent the attacker flips
42 link = dest / '.sublink' # a symlink -> outside, swapped in for `sub`
43 link.symlink_to(outside)
44
45
46 def push():
47 # --temp-dir must precede the paths: runtests runs with POSIXLY_CORRECT, which
48 # disables getopt permutation, so an option after the paths is treated as a path.
49 subprocess.run(
50 rsync_argv('-a', f'--temp-dir={tmpd}', f'{src}/', f'{dest}/'),
51 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
52 )
53
54
55 # Positive control: a normal push lands the files in dest/sub, so the temp+rename
56 # write path is genuinely exercised and the race below isn't vacuous.
57 rmtree(sub)
58 sub.mkdir()
59 push()
60 if not (sub / 'f0').is_file():
61 test_fail("positive control: a normal --temp-dir push did not write files "
62 "into dest/sub, so the rename race window would be vacuous")
63 for f in outside.iterdir():
64 f.unlink()
65
66 # Separate-process flipper: keep `sub` flipping between a real directory and the
67 # symlink->outside (an atomic 3-rename swap with `link`). A separate process is
68 # needed to flip fast enough to win the rename window. It self-terminates when
69 # the test process goes away (getppid changes) and after a hard deadline, so a
70 # killed test can't leak an orphan that poisons later tests (see start_path_flipper).
71 flip_code = (
72 "import os, sys, time\n"
73 "sub, link = sys.argv[1], sys.argv[2]\n"
74 "scratch = sub + '.flip'\n"
75 "parent = os.getppid()\n"
76 "deadline = time.time() + 120\n"
77 "while time.time() < deadline and os.getppid() == parent:\n"
78 " try:\n"
79 " os.makedirs(sub, exist_ok=True)\n"
80 " os.rename(sub, scratch); os.rename(link, sub); os.rename(scratch, link)\n"
81 " os.rename(sub, scratch); os.rename(link, sub); os.rename(scratch, link)\n"
82 " except OSError:\n"
83 " pass\n"
84 )
85 flip = subprocess.Popen(['python3', '-c', flip_code, str(sub), str(link)])
86 try:
87 deadline = time.monotonic() + race_budget(10.0)
88 while time.monotonic() < deadline:
89 # Start each round from a real (absent->mkdir'd) dest/sub so rsync sees a
90 # directory at flist time; the flip then happens during the file writes.
91 rmtree(sub)
92 try:
93 sub.unlink()
94 except OSError:
95 pass
96 push()
97 # Count only escaped regular files (the transferred payload); the
98 # flipper/reset churn can momentarily leave a dir or symlink in outside,
99 # which is harness noise, not a write escape.
100 escaped = sorted(p.name for p in outside.iterdir()
101 if p.is_file() and not p.is_symlink())
102 if escaped:
103 test_fail(
104 "rename-fullpath symlink race: files were written OUTSIDE the "
105 f"destination tree ({escaped}) -- finish_transfer's tmp->final "
106 "rename followed a flipped dest/sub symlink because an absolute "
107 "--temp-dir made do_rename_at fall back to the unconfined "
108 "do_rename().")
109 finally:
110 flip.terminate()
111 try:
112 flip.wait(timeout=5)
113 except subprocess.TimeoutExpired:
114 flip.kill()
115
116 # No escape within the race budget.