Debian Codegraph @

testsuite/copy-xattrs-symlink-race_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Symlink-race (TOCTOU) in a confined receiver's metadata xattr write.
3 #
4 # With -X and --copy-dest, when a basis file matches the source the generator
5 # copies it into place and then runs set_file_attrs(), which sets the xattrs/ACLs
6 # through a held O_NOFOLLOW fd (fsetxattr). When that held fd is unavailable --
7 # the held-dirfd cache misses, e.g. for a path deeper than the cache -- the
8 # unfixed code fell through to a path-based sys_lsetxattr(dest, ...). lsetxattr
9 # does not follow a *leaf* symlink, but the kernel's path walk follows symlinks
10 # in PARENT components, so a parent flipped to a symlink->outside in the window
11 # between the confined create and the setxattr redirected the attacker-chosen
12 # xattr onto a file OUTSIDE the destination tree (the attacker controls the
13 # bytes -- e.g. security.capabilities as root).
14 #
15 # RED before the fix (the marker xattr lands on an outside sentinel); GREEN once
16 # set_file_attrs() re-pins via the secure resolver (or refuses) so the write
17 # always uses fsetxattr on a confined fd, which a parent flip cannot redirect.
18 # The dest path is buried below the held-dirfd cache depth so the fd-less path is
19 # taken on EVERY push (see DEEP), making the flip the only race; a separate-
20 # process flipper wins it. No rsync instrumentation is needed.
21
22 import os
23 import platform
24 import subprocess
25 import time
26
27 from rsyncfns import (
28 race_budget, SCRATCHDIR, rmtree, rsync_argv, test_fail, test_skipped,
29 xattr_set, xattrs_supported,
30 )
31
32 MARKER = 'user.marker' # on-disk name we look for on the outside sentinels
33 N = 120
34
35 if platform.system() != 'Linux':
36 test_skipped("parent-flip xattr race is checked on Linux (os.*xattr)")
37 if not xattrs_supported():
38 test_skipped("rsync built without xattr support (or no xattr tooling)")
39
40 base = SCRATCHDIR / 'copy-xattrs-race'
41 src = base / 'src'
42 cdbasis = base / 'cdbasis' # absolute --copy-dest basis
43 dest = base / 'dest'
44 outside = base / 'outside'
45 # Bury the flipped dir below the receiver's held-dirfd cache depth (>64) so
46 # held_dfd_for()/vfs_cached_dirfd() returns -1 for EVERY file deterministically
47 # (not just on a cache-miss race): set_file_attrs() then takes the fd-less
48 # metadata path on every push, so the only remaining race is the flip landing
49 # during the lsetxattr -- a far stronger RED oracle, especially under -j load.
50 DEEP = '/'.join(['d'] * 70)
51
52 rmtree(base)
53 (src / DEEP / 'sub').mkdir(parents=True)
54 (cdbasis / DEEP / 'sub').mkdir(parents=True)
55 (dest / DEEP).mkdir(parents=True)
56 outside.mkdir()
57
58 # Source + matching copy-dest basis (same content/mtime/mode so the generator
59 # copies from the basis rather than transferring), both carrying the attacker-
60 # chosen marker xattr. A large payload widens the copy_file open->setxattr
61 # window so the separate-process flipper can land inside it.
62 payload = ('x' * 4096 + '\n') * 16 # ~64 KB: widens the per-file create->lsetxattr window
63 try:
64 for i in range(N):
65 s = src / DEEP / 'sub' / f'f{i}'
66 b = cdbasis / DEEP / 'sub' / f'f{i}'
67 s.write_text(payload)
68 b.write_text(payload)
69 os.chmod(s, 0o644)
70 os.chmod(b, 0o644)
71 st = s.stat()
72 os.utime(b, (st.st_atime, st.st_mtime))
73 xattr_set('marker', 'PWNED', s, b)
74 # Pre-create the outside sentinel the escaped lsetxattr would land on
75 # (lsetxattr on a missing path is a no-op ENOENT, not an escape).
76 (outside / f'f{i}').write_text('')
77 except OSError as e:
78 test_skipped(f"filesystem does not support user xattrs ({e})")
79
80 sub = dest / DEEP / 'sub' # the parent component the attacker flips
81 link = dest / DEEP / '.sublink' # symlink -> outside, swapped in for `sub`
82 link.symlink_to(outside)
83
84
85 def push():
86 subprocess.run(
87 rsync_argv('-rtpX', '--inplace', f'--copy-dest={cdbasis}',
88 f'{src}/', f'{dest}/'),
89 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
90 )
91
92
93 def outside_marked():
94 return sorted(p.name for p in outside.iterdir()
95 if p.is_file() and not p.is_symlink()
96 and MARKER in os.listxattr(str(p)))
97
98
99 # Positive control: a normal push copies the basis xattr into dest/sub, so the
100 # copy_xattrs path is genuinely exercised and the race below isn't vacuous.
101 rmtree(sub)
102 sub.mkdir()
103 push()
104 if MARKER not in os.listxattr(str(sub / 'f0')):
105 test_fail("positive control: a normal --copy-dest -X push did not copy the "
106 "basis marker xattr into dest/sub/f0, so the copy_xattrs race "
107 "window would be vacuous")
108 # Clear any marker the control might have left on the sentinels.
109 for i in range(N):
110 try:
111 os.removexattr(str(outside / f'f{i}'), MARKER)
112 except OSError:
113 pass
114
115 # Separate-process flipper: flip dest/sub between a real directory and the
116 # symlink->outside (atomic 3-rename swap), fast enough to win the window
117 # between the confined create and set_file_attrs' fd-less metadata setxattr. It self-
118 # terminates when the test process goes away (getppid changes) and after a
119 # hard deadline, so a killed test can't leak an orphan (see start_path_flipper).
120 flip_code = (
121 "import os, sys, time\n"
122 "sub, link = sys.argv[1], sys.argv[2]\n"
123 "scratch = sub + '.flip'\n"
124 "parent = os.getppid()\n"
125 "deadline = time.time() + 120\n"
126 "while time.time() < deadline and os.getppid() == parent:\n"
127 " try:\n"
128 " os.makedirs(sub, exist_ok=True)\n"
129 " os.rename(sub, scratch); os.rename(link, sub); os.rename(scratch, link)\n"
130 " os.rename(sub, scratch); os.rename(link, sub); os.rename(scratch, link)\n"
131 " except OSError:\n"
132 " pass\n"
133 )
134 flip = subprocess.Popen(['python3', '-c', flip_code, str(sub), str(link)])
135 try:
136 deadline = time.monotonic() + race_budget(10.0)
137 while time.monotonic() < deadline:
138 # Start each round from a real (absent->mkdir'd) dest/sub so the copy
139 # opens a real directory; the flip then happens during the copy.
140 rmtree(sub)
141 try:
142 sub.unlink()
143 except OSError:
144 pass
145 push()
146 marked = outside_marked()
147 if marked:
148 test_fail(
149 "metadata xattr parent-symlink race: the attacker-chosen marker "
150 f"xattr was written onto files OUTSIDE the destination tree "
151 f"({marked}) -- a confined receiver's set_file_attrs() fell back to "
152 "a path-based lsetxattr and followed a flipped dest/sub symlink.")
153 finally:
154 flip.terminate()
155 try:
156 flip.wait(timeout=5)
157 except subprocess.TimeoutExpired:
158 flip.kill()
159
160 # No escape within the race budget.