Debian Codegraph @

testsuite/files-from-leak_test.py

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