Debian Codegraph @

testsuite/rrsync-backup-dir-inband-pivot_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """rrsync must not let one transfer create and consume an option-path symlink."""
3
4 import os
5 import shlex
6 import signal
7 import subprocess
8 import sys
9
10 signal.signal(signal.SIGUSR1, signal.SIG_IGN)
11 signal.signal(signal.SIGUSR2, signal.SIG_IGN)
12 if '--shell' in sys.argv:
13 index = sys.argv.index('--shell') + 2
14 env = {**os.environ, 'SSH_ORIGINAL_COMMAND': ' '.join(sys.argv[index:])}
15 signal.signal(signal.SIGUSR1, signal.SIG_DFL)
16 signal.signal(signal.SIGUSR2, signal.SIG_DFL)
17 wrapper = env['RRSYNC_WRAPPER']
18 root = env['RRSYNC_ROOT']
19 os.execve(wrapper, [wrapper, '-wo', root], env)
20
21 from rsyncfns import (RSYNC, SCRATCHDIR, makepath, patched_rrsync,
22 proc_self_fd_pins, rmtree, rsync_argv, rsync_path_arg,
23 )
24
25 # Handing rsync an inode instead of a name needs the /proc/self/fd primitive.
26 # Where it is missing there is no safe way to pass a peer-suppliable option
27 # path, so rrsync refuses it outright -- the escape is blocked either way, but
28 # only the pinning answer also keeps first use working.
29 PINS = proc_self_fd_pins()
30
31 base = SCRATCHDIR / 'rrsync-backup-dir-inband-pivot'
32 rmtree(base)
33 stage = base / 'attacker-stage'
34 src = base / 'attacker-next'
35 root = base / 'restricted'
36 outside = base / 'outside'
37 makepath(stage, src, root, outside)
38
39 (stage / 'authorized_keys').write_bytes(b'ATTACKER-SSH-KEY\n')
40 (src / 'authorized_keys').write_bytes(b'NEW-IN-TREE-CONTENT\n')
41 os.symlink('../outside', src / 'a')
42 (outside / 'authorized_keys').write_bytes(b'ADMIN-SSH-KEY\n')
43
44 # RSYNC may be a multi-word command (the runner's --protocol=N, or valgrind)
45 # while rrsync hands its RSYNC to execlp() as a single executable name, so it
46 # has to be wrapped before patched_rrsync() sees it.
47 shim = base / 'rsync-shim'
48 shim.write_text('#!/bin/sh\nexec ' + rsync_path_arg(RSYNC) + ' "$@"\n')
49 shim.chmod(0o755)
50 wrapper = patched_rrsync(base, rsync_path=str(shim))
51 rsh = f'{shlex.quote(sys.executable)} {shlex.quote(os.path.abspath(__file__))} --shell'
52 env = {**os.environ, 'RRSYNC_WRAPPER': str(wrapper), 'RRSYNC_ROOT': str(root)}
53
54 seed = subprocess.run(
55 rsync_argv('-rlI', '-e', rsh, f'{stage}/authorized_keys', 'ignored:'),
56 env=env, capture_output=True, text=True, timeout=20)
57 assert seed.returncode == 0
58 assert (root / 'authorized_keys').read_bytes() == b'ATTACKER-SSH-KEY\n'
59 assert not (root / 'a').exists()
60
61 os.symlink('../outside', root / 'a')
62 blocked = subprocess.run(
63 rsync_argv('-rlbI', '--backup-dir=a', '-e', rsh,
64 f'{src}/', 'ignored:'),
65 env=env, capture_output=True, text=True, timeout=20)
66 assert blocked.returncode != 0
67 assert (outside / 'authorized_keys').read_bytes() == b'ADMIN-SSH-KEY\n'
68 (root / 'a').unlink()
69
70 seed = subprocess.run(
71 rsync_argv('-rlI', '-e', rsh, f'{stage}/authorized_keys', 'ignored:'),
72 env=env, capture_output=True, text=True, timeout=20)
73 assert seed.returncode == 0
74
75 got = subprocess.run(
76 rsync_argv('-rlbI', '--backup-dir=a', '-e', rsh,
77 f'{src}/', 'ignored:'),
78 env=env, capture_output=True, text=True, timeout=20)
79
80 escaped = outside / 'authorized_keys'
81 pivot = os.readlink(root / 'a') if (root / 'a').is_symlink() else None
82 print(f'seed_rc={seed.returncode}, rc={got.returncode}, pivot={pivot!r}, '
83 f'escaped={escaped.read_bytes()!r}, stderr={got.stderr!r}', flush=True)
84 assert escaped.read_bytes() == b'ADMIN-SSH-KEY\n', (
85 'rrsync followed a backup-dir symlink created by the same transfer and '
86 'replaced an existing file outside its restricted directory')
87 # ...and it has to be blocked by THIS policy. "the outside file is unchanged"
88 # is also satisfied by any unrelated failure, so require a nonzero status plus
89 # the evidence of the mechanism that produced it.
90 assert got.returncode != 0, (
91 f'the pivot did not overwrite the outside file, but the transfer also did '
92 f'not fail, so nothing stopped it: rc={got.returncode}, '
93 f'stderr={got.stderr!r}')
94 if PINS:
95 # rrsync created the backup dir itself before exec, so the transfer's own
96 # symlink could only unlink that name, not redirect the held inode -- which
97 # is why the backup fails instead of escaping. The symlink must actually
98 # have been planted, or the pivot was never attempted.
99 assert pivot == '../outside', (
100 f'the transfer did not plant the pivot symlink, so the run proves '
101 f'nothing: pivot={pivot!r}')
102 assert '/proc/self/fd/' in got.stderr, (
103 'the transfer failed, but not through the pinned backup dir: an '
104 f'unrelated failure would satisfy the check above: stderr={got.stderr!r}')
105 else:
106 assert 'receiver option path does not exist' in got.stderr, (
107 'the transfer failed, but not with the missing-option-path refusal: '
108 f'an unrelated failure would satisfy the check above: '
109 f'stderr={got.stderr!r}')
110
111 # --temp-dir: rsync does not create it, so a missing one is refused on every
112 # platform rather than being conjured up.
113 tmpdir = subprocess.run(
114 rsync_argv('-rlI', '--temp-dir=no-such-tmp', '-e', rsh,
115 f'{src}/authorized_keys', 'ignored:'),
116 env=env, capture_output=True, text=True, timeout=20)
117 assert tmpdir.returncode != 0 and 'receiver option path does not exist' in tmpdir.stderr, (
118 f'a missing --temp-dir was not refused: rc={tmpdir.returncode}, '
119 f'stderr={tmpdir.stderr!r}')
120 assert not (root / 'no-such-tmp').exists(), (
121 'a missing --temp-dir must not be created either')
122
123 if not PINS:
124 # Without the pin primitive every peer-suppliable option path whose leaf is
125 # missing is refused, so the first-use cases below cannot apply. Check the
126 # refusal itself and stop: the escape was already shown blocked above.
127 for opt in ('--backup-dir=fresh-backup', '--partial-dir=.rsync-partial',
128 '--link-dest=no-such-basis'):
129 r = subprocess.run(
130 rsync_argv('-rlbI', opt, '-e', rsh, f'{src}/authorized_keys', 'ignored:'),
131 env=env, capture_output=True, text=True, timeout=20)
132 assert r.returncode != 0 and 'receiver option path does not exist' in r.stderr, (
133 f'{opt} was neither pinned nor refused without /proc/self/fd: '
134 f'rc={r.returncode}, stderr={r.stderr!r}')
135 sys.exit(0)
136
137 # Controls come after the security assertions on purpose: an environment where
138 # a control fails for an unrelated reason must not be able to mask the escape
139 # check above by aborting first.
140 def reseed():
141 r = subprocess.run(
142 rsync_argv('-rlI', '-e', rsh, f'{stage}/authorized_keys', 'ignored:'),
143 env=env, capture_output=True, text=True, timeout=20)
144 assert r.returncode == 0, f'reseed failed: stderr={r.stderr!r}'
145 assert (root / 'authorized_keys').read_bytes() == b'ATTACKER-SSH-KEY\n'
146
147
148 reseed()
149
150 # An ordinary in-tree backup into a directory that already exists.
151 (root / 'backup').mkdir()
152 normal = subprocess.run(
153 rsync_argv('-rlbI', '--backup-dir=backup', '-e', rsh,
154 f'{src}/authorized_keys', 'ignored:'),
155 env=env, capture_output=True, text=True, timeout=20)
156 assert normal.returncode == 0, f"ordinary in-tree backup failed: stderr={normal.stderr!r}"
157 assert (root / 'backup' / 'authorized_keys').read_bytes() == b'ATTACKER-SSH-KEY\n'
158
159 # A first-use --backup-dir must still WORK: rrsync creates the missing leaf
160 # under the pinned parent rather than refusing it, so dated/rotating backup
161 # directory names keep working through a restricted account.
162 reseed()
163 firstuse = subprocess.run(
164 rsync_argv('-rlbI', '--backup-dir=fresh-backup', '-e', rsh,
165 f'{src}/authorized_keys', 'ignored:'),
166 env=env, capture_output=True, text=True, timeout=20)
167 assert firstuse.returncode == 0, (
168 f'a first-use --backup-dir was refused: rc={firstuse.returncode}, '
169 f'stderr={firstuse.stderr!r}')
170 fresh = root / 'fresh-backup'
171 assert fresh.is_dir() and not fresh.is_symlink(), (
172 f'first-use --backup-dir did not leave a real directory: {fresh}')
173 assert (fresh / 'authorized_keys').read_bytes() == b'ATTACKER-SSH-KEY\n', (
174 'the backup did not land in the created backup dir, so the run above '
175 'proves nothing about --backup-dir working')
176
177 # A first-use --backup-dir may also name a whole missing hierarchy: rsync
178 # builds one itself (make_bak_dir()), so rrsync has to as well rather than
179 # stopping at "the immediate parent must exist".
180 reseed()
181 nested = subprocess.run(
182 rsync_argv('-rlbI', '--backup-dir=bak/2026/07', '-e', rsh,
183 f'{src}/authorized_keys', 'ignored:'),
184 env=env, capture_output=True, text=True, timeout=20)
185 assert nested.returncode == 0, (
186 f'a nested first-use --backup-dir was refused: rc={nested.returncode}, '
187 f'stderr={nested.stderr!r}')
188 assert (root / 'bak' / '2026' / '07' / 'authorized_keys').exists(), (
189 'the nested backup dir was accepted but the backup did not land in it')
190
191 # Same for a first-use --partial-dir, the resumable-upload idiom -- and it must
192 # be created 0700 as rsync creates it (util1.c), not 0777&~umask: a partial
193 # file is an incomplete copy of the peer's data and is not for the rest of the
194 # machine to read.
195 partial = subprocess.run(
196 rsync_argv('-rlI', '--partial', '--partial-dir=.rsync-partial', '-e', rsh,
197 f'{src}/authorized_keys', 'ignored:'),
198 env=env, capture_output=True, text=True, timeout=20)
199 assert partial.returncode == 0, (
200 f'a first-use --partial-dir was refused: rc={partial.returncode}, '
201 f'stderr={partial.stderr!r}')
202 pdir = root / '.rsync-partial'
203 assert pdir.is_dir() and not pdir.is_symlink(), (
204 f'first-use --partial-dir did not leave a real directory: {pdir}')
205 mode = pdir.stat().st_mode & 0o777
206 assert mode == 0o700, (
207 f'the partial dir was created {mode:04o}, not 0700: partial files would be '
208 'readable by other users on the server')
209
210 # A missing alt-dest is neither created nor refused: naming a basis directory
211 # that does not exist yet is the ordinary first-run case. rrsync stands in an
212 # empty unlinked directory, so the lookup finds nothing and no name is left for
213 # an in-band symlink to take over (see rrsync-alt-dest-inband-pivot).
214 altdest = subprocess.run(
215 rsync_argv('-rlI', '--link-dest=no-such-basis', '-e', rsh,
216 f'{src}/authorized_keys', 'ignored:'),
217 env=env, capture_output=True, text=True, timeout=20)
218 assert altdest.returncode == 0, (
219 f'a first-run --link-dest was refused: rc={altdest.returncode}, '
220 f'stderr={altdest.stderr!r}')
221 assert not (root / 'no-such-basis').exists(), (
222 'a missing --link-dest must not be created')
223 assert not list(root.glob('.rrsync-empty-basis*')), (
224 'the basis placeholder was left behind in the restricted dir')