Debian Codegraph @

testsuite/filter-leak_test.py

raw symbols SCIP
1 import os
2 import subprocess
3 import time
4 from pathlib import Path
5
6 from rsyncfns import (
7 SCRATCHDIR, race_budget, find_attacker_uid, rmtree, rsync_argv,
8 start_c_flipper, stop_flipper, test_fail, test_skipped, start_test_daemon,
9 write_daemon_conf,
10 )
11
12 # A daemon serving a writable, non-chrooted module creates --backup-dir backups
13 # with its own (root) ownership. A parent-swap race can leave a root-owned
14 # backup symlink whose target escapes the module. Because open_no_attacker_symlinks()
15 # follows a symlink owned by uid 0 / the euid, a later --filter=:LIST that names
16 # that backup symlink would read an out-of-module file's content as the filter list --
17 # unless the filter open is module-root confined. RED before that confinement,
18 # GREEN after.
19
20 PORT = 13333
21
22 if os.geteuid() != 0:
23 test_skipped("requires root to plant a backup-dir symlink owned by a non-self uid")
24
25 ATT_UID = find_attacker_uid()
26 if ATT_UID is None:
27 test_skipped("no untrusted-uid user available for cross-uid plant")
28
29 SECRET = "NO_ONE_SHOULD_README\n"
30 NFILES = 80
31 root = SCRATCHDIR / 'filter'
32 root.mkdir()
33 base = root / 'base'
34 outside = base / 'outside'
35 src = base / 'src'
36 dest = base / 'dest'
37 backup = base / 'backup'
38 sub = backup / 'sub'
39 sublink = backup / '.sublink'
40 filter_arg = ""
41
42 secret = root / 'secret'
43 secret.write_text(SECRET)
44
45
46 def build():
47 """Reset the workspace. Call only while the flipper is stopped."""
48 rmtree(base)
49 for d in (src / 'sub', dest / 'sub', backup, outside):
50 d.mkdir(parents=True, exist_ok=True)
51
52 # Distinct source and destination symlink values so each transfer overwrites
53 # the destination symlink and thus triggers a backup of the old one.
54 for i in range(NFILES):
55 (src / 'sub' / f'f{i}').symlink_to('test')
56 (dest / 'sub' / f'f{i}').symlink_to(f'{secret}')
57 os.lchown(src / 'sub' / f'f{i}', ATT_UID, ATT_UID)
58 os.lchown(dest / 'sub' / f'f{i}', ATT_UID, ATT_UID)
59
60 # The attacker-owned parent-swap target: a symlink to the outside directory.
61 os.symlink(str(outside), sublink)
62 os.lchown(sublink, ATT_UID, ATT_UID)
63 sub.mkdir(parents=True, exist_ok=True)
64
65
66 def push():
67 """Blocking rsync push that backs up the old destination symlinks."""
68 return subprocess.run(
69 rsync_argv('-a', '-b', '--backup-dir=/backup/',
70 f'{src}/', f'rsync://127.0.0.1:{PORT}/m/dest/'),
71 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
72 )
73
74
75 def leak():
76 """Attempt to read a secret via filter through the root-owned symlink."""
77
78 proc = subprocess.run(
79 rsync_argv('-a', f'--filter=: {filter_arg}',
80 f'rsync://127.0.0.1:{PORT}/m/backup/sub/', f'{dest}/'),
81 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
82 )
83 if "NO_ONE_SHOULD" in proc.stdout:
84 test_fail(f"{secret.name} is leaked!\n\nOutput: {proc.stdout}")
85
86
87 def normalize_sub():
88 """If the flipper stopped with `sub` as the attacker symlink while the real
89 backup directory sits at `.sublink`, put the real dir back at `sub` so the
90 daemon path backup/sub/<name> (and our scandir) see the real backups.
91
92 Best-effort only: the non-atomic (non-Linux) flipper swaps via a `sub.flip`
93 scratch name and can be killed mid-rename, leaving `sub` absent or the real
94 dir parked at `.flip`. Any state we can't cleanly settle is left as-is and
95 treated by the caller as 'no win this round'."""
96 try:
97 if sub.is_symlink() and sublink.is_dir() and not sublink.is_symlink():
98 sub.unlink()
99 sublink.rename(sub)
100 except OSError:
101 pass
102
103
104 def root_owned_backup_symlink():
105 """Return the name of a root-owned backup symlink directly in `sub`, or "".
106
107 Never raises: a swap killed mid-rename can leave `sub` absent or a symlink,
108 which just means no usable win this round -- the caller rebuilds and retries."""
109 normalize_sub()
110 try:
111 if sub.is_symlink() or not sub.is_dir():
112 return ""
113 with os.scandir(sub) as it:
114 for entry in it:
115 if entry.is_symlink() and entry.stat(follow_symlinks=False).st_uid == 0:
116 return entry.name
117 except (FileNotFoundError, NotADirectoryError):
118 return ""
119 return ""
120
121
122 # Positive control: a clean run (no flipper) must back the old destination
123 # symlink into the backup tree, proving this transfer shape exercises the backup
124 # symlink path. A broken fixture or an rsync that errors early fails here loudly
125 # instead of passing the race vacuously.
126 conf = write_daemon_conf(
127 [('m', {'path': str(base), 'read only': 'no', 'use chroot': 'no'})],
128 name='filter-rsyncd.conf',
129 )
130 start_test_daemon(conf, PORT)
131
132 build()
133 proc = push()
134 if proc.returncode != 0:
135 test_fail(f"positive control: clean --backup-dir run failed (rc={proc.returncode})")
136 if not (sub / 'f0').is_symlink() or os.readlink(sub / 'f0') != f'{secret}':
137 test_fail(
138 "positive control: the old destination symlink was not backed up into "
139 f"{sub}; the backup symlink path was not exercised"
140 )
141
142
143 # ---- THE LIVE RACE ---------------------------------------------------------
144 # Repeatedly push under the parent-swap flipper until a root-owned backup symlink
145 # lands in `sub`. Reset the workspace only while the flipper is quiet so build()'s
146 # rmtree/mkdir can't race the swapper.
147
148 deadline = time.monotonic() + race_budget(10.0)
149 flip = None
150 try:
151 while time.monotonic() < deadline:
152 if flip is not None:
153 stop_flipper(flip)
154 flip = None
155
156 filter_arg = root_owned_backup_symlink()
157 if filter_arg:
158 break
159
160 build()
161 flip = start_c_flipper(sub, sublink)
162 push()
163 finally:
164 if flip is not None:
165 stop_flipper(flip)
166
167 if not filter_arg:
168 # The leak needs a root-owned backup symlink, which only appears when the
169 # parent-swap race makes make_backup() fall back to creating the symlink
170 # itself. Winning that window reliably needs the atomic renameat2(EXCHANGE)
171 # flipper (Linux); on platforms that fall back to the non-atomic flipper the
172 # window may never be hit within the budget. Can't mount the attack here, so
173 # there's nothing to assert -- skip rather than fail.
174 test_skipped("race did not produce a root-owned backup symlink (no atomic flipper?)")
175
176 # Non-vacuous GREEN precondition: the symlink we exploit must genuinely target a
177 # secret OUTSIDE the module, so marker-absence proves module-root confinement
178 # refused it -- not that the attack was never mounted.
179 tgt = os.readlink(sub / filter_arg)
180 if os.path.realpath(tgt) != os.path.realpath(str(secret)):
181 test_fail(f"setup failed: backup symlink {filter_arg} -> {tgt}, not the out-of-module secret")
182
183 leak()