Debian Codegraph @

testsuite/rrsync-specials-denied_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Finding [26]: support/rrsync leaves -D / --specials enabled in a restricted
3 # (non-"/") directory, so a restricted SSH user can have the spawned rsync
4 # create special files (FIFOs, sockets; device nodes too if the receiver is
5 # privileged) inside the served tree -- objects the forced-command policy did
6 # not intend to permit, and that the user cannot otherwise create through the
7 # wrapper (it only runs rsync, not a shell).
8 #
9 # Part 1 shows --specials is the toggle that enables special-file creation (a
10 # FIFO is created with it, skipped without it). Part 2 is the fix: a restricted
11 # rrsync no longer creates special files even when -D/--specials is requested.
12 #
13 # Rejecting -D outright broke plain `rsync -a` (which bundles -rlptgoD) for every
14 # restricted rrsync (see rrsync-archive-mode), so rather than reject the transfer
15 # the wrapper forces --drop-D, which refuses the creation (entries are skipped,
16 # exactly the part-1 "without --specials" behaviour) while the rest of the
17 # transfer proceeds. Runs at any uid.
18 #
19 # It is --drop-D and not --no-D because --no-D also clears the rdev fields that
20 # devices and special files carry on the wire, and the wrapper sets it on one
21 # end of the connection only: the client's -D sender then writes rdev the
22 # receiver never reads and the file list desynchronises. --drop-D withholds
23 # only the creation.
24 #
25 # The two directions are asserted separately, because they are not the same
26 # question. Creation happens where files are WRITTEN, so only the receiving
27 # side can create anything in the served tree, and only there is there anything
28 # to deny. Part 4 pins that down so the distinction cannot quietly collapse
29 # back into "forced everywhere".
30
31 import os
32 import shlex
33 import subprocess
34
35 from rsyncfns import (
36 RSYNC, RSYNC_PREFIX, SCRATCHDIR, patched_rrsync, rmtree, rsync_argv,
37 test_fail, xattr_set, xattrs_supported, rsync_path_arg,
38 )
39
40 base = SCRATCHDIR / 'rrsync-specials'
41 rmtree(base)
42 src = base / 'src'
43 src.mkdir(parents=True)
44 os.mkfifo(src / 'evil_fifo')
45 (src / 'ordinary').write_text('PLAIN\n')
46
47 # --- Part 1: --specials enables special-file creation in the destination.
48 withd = base / 'with'
49 withd.mkdir()
50 subprocess.run(rsync_argv('-rlptgo', '--specials', f'{src}/', f'{withd}/'),
51 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
52 if not (withd / 'evil_fifo').is_fifo():
53 test_fail("premise check failed: --specials should create the FIFO in the dest")
54 without = base / 'without'
55 without.mkdir()
56 subprocess.run(rsync_argv('-rlptgo', f'{src}/', f'{without}/'),
57 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
58 if (without / 'evil_fifo').exists():
59 test_fail("premise check failed: without --specials the FIFO should be skipped")
60
61 # --- Part 2: a restricted rrsync accepts -D/--specials but forces --drop-D, so
62 # the special-file creation shown in part 1 cannot be requested through the
63 # wrapper. Use an argv-recording stub rsync to confirm that the option is
64 # accepted (the `rsync -a` regression is gone), that --drop-D is forced, and
65 # that the client's own -D still reaches the server so both ends keep framing
66 # the file list the same way.
67 record = base / 'argv'
68 stub = base / 'rsync-record'
69 stub.write_text('#!/bin/sh\nprintf \'%s\\n\' "$@" >' + str(record) + '\n')
70 stub.chmod(0o755)
71 rrsync = patched_rrsync(base, rsync_path=str(stub))
72 restricted = base / 'restricted'
73 restricted.mkdir(exist_ok=True)
74
75 def forwarded_opts(cmd):
76 if record.exists():
77 record.unlink()
78 env = {**os.environ, 'SSH_ORIGINAL_COMMAND': cmd}
79 r = subprocess.run([str(rrsync), str(restricted)], env=env,
80 capture_output=True, text=True)
81 if r.returncode != 0:
82 test_fail(f"restricted rrsync rejected `{cmd}` instead of stripping "
83 f"the option (exit {r.returncode}): {r.stderr.strip()}")
84 return record.read_text().split('\n') if record.exists() else []
85
86
87 for opt in ('-D', '--specials'):
88 # Receiving side: this is the one that could create something here.
89 forwarded = forwarded_opts(f'rsync --server {opt} . .')
90 if '--drop-D' not in forwarded:
91 test_fail(f"restricted rrsync did not force --drop-D for `{opt}` on "
92 f"the receiving side, where creation happens: {forwarded}")
93 # ...and the client's own request must still reach the server, or the two
94 # ends frame the file list's rdev fields differently and it desynchronises.
95 if opt not in forwarded:
96 test_fail(f"restricted rrsync dropped `{opt}` instead of leaving it "
97 f"alongside --drop-D: {forwarded}")
98 if '--no-D' in forwarded:
99 test_fail(f"restricted rrsync forced --no-D for `{opt}`. That clears "
100 'preserve_devices/preserve_specials, which also frame the '
101 f'rdev fields, so the file list desynchronises: {forwarded}')
102
103 # --- Part 3: the property, not just the option ------------------------------
104 # Part 2 checks what rrsync forwards. This checks what that achieves: a push
105 # of a FIFO through a restricted rrsync must not create one in the tree.
106 served = base / 'served'
107 served.mkdir()
108 # A second wrapper in its own dir: patched_rrsync() always writes
109 # <workdir>/rrsync-under-test, and the one above is wired to the recording
110 # stub. This one drives the real rsync -- through a shim, because RSYNC may
111 # be a multi-word command (the runner's --protocol=N, or valgrind) while
112 # rrsync hands its RSYNC to execlp() as a single executable name.
113 pushwrap = base / 'pushwrap'
114 pushwrap.mkdir()
115 shim = base / 'rsync-shim'
116 shim.write_text('#!/bin/sh\nexec ' + rsync_path_arg(RSYNC) + ' "$@"\n')
117 shim.chmod(0o755)
118 rrsync_push = patched_rrsync(pushwrap, rsync_path=str(shim))
119 rsh = base / 'fake-rsh'
120 rsh.write_text(
121 '#!/bin/sh\n'
122 'shift\n'
123 'SSH_ORIGINAL_COMMAND="$*"\n'
124 'export SSH_ORIGINAL_COMMAND\n'
125 'exec %s %s\n' % (shlex.quote(str(rrsync_push)), shlex.quote(str(served))))
126 rsh.chmod(0o755)
127
128 proc = subprocess.run(
129 rsync_argv('-rlptgoD', '--specials', '-e', str(rsh), f'{src}/', 'dummy:.'),
130 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
131 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:300]!r}'
132 # Control: the FIFO's absence only means something if the push otherwise
133 # worked. A push that failed outright would "deny" the FIFO too.
134 landed = served / 'ordinary'
135 if not landed.is_file() or landed.read_text() != 'PLAIN\n':
136 test_fail(f'control failed: the push did not deliver an ordinary file, so '
137 f'the absence of the FIFO proves nothing ({ctx})')
138 if (served / 'evil_fifo').exists():
139 test_fail(f'a push through a restricted rrsync created a special file in '
140 f'the served tree ({ctx})')
141 # The claim is "denies creation while the rest proceeds normally", so a
142 # refusal that also breaks the transfer does not satisfy it.
143 if proc.returncode != 0:
144 test_fail(f'the FIFO was denied, but the transfer itself failed ({ctx})')
145
146 # --- Part 3b: a DEVICE, which breaks at every protocol ----------------------
147 # A device carries its rdev at every protocol version -- unlike a FIFO, whose
148 # rdev field stops existing at 31 -- so a receiver whose preserve_devices
149 # disagrees with the sender's desynchronises the file list even on current
150 # protocols. This needs no mknod privilege: rsync's own fake-super "%stat"
151 # xattr is what makes a file a device to rsync, at both ends.
152 #
153 # The RECEIVER runs --fake-super too, so it is able to record a device without
154 # privilege -- which is what makes this an assertion about DENIAL rather than
155 # about the transfer merely surviving. Without the wrapper's refusal it lands
156 # a placeholder named "achar"; with it, the entry is skipped and nothing of
157 # that name exists.
158 if xattrs_supported():
159 devsrc = base / 'devsrc'
160 devsrc.mkdir()
161 (devsrc / 'ordinary').write_text('PLAIN\n')
162 (devsrc / 'achar').write_bytes(b'')
163 try:
164 xattr_set(f'{RSYNC_PREFIX}.%stat', '20644 1,3 0:0', devsrc / 'achar')
165 made_dev = True
166 except Exception:
167 made_dev = False
168
169 if made_dev:
170 devserved = base / 'devserved'
171 devserved.mkdir()
172 # Its own wrapper, whose rsync runs --fake-super: patched_rrsync()
173 # writes one file per workdir, and the push wrapper above must stay
174 # ordinary.
175 devwrap = base / 'devwrap'
176 devwrap.mkdir()
177 devshim = base / 'rsync-shim-fake'
178 devshim.write_text('#!/bin/sh\nexec ' + rsync_path_arg(RSYNC) + ' --fake-super "$@"\n')
179 devshim.chmod(0o755)
180 rrsync_dev = patched_rrsync(devwrap, rsync_path=str(devshim))
181 devrsh = base / 'fake-rsh-dev'
182 devrsh.write_text(
183 '#!/bin/sh\n'
184 'shift\n'
185 'SSH_ORIGINAL_COMMAND="$*"\n'
186 'export SSH_ORIGINAL_COMMAND\n'
187 'exec %s %s\n' % (shlex.quote(str(rrsync_dev)),
188 shlex.quote(str(devserved))))
189 devrsh.chmod(0o755)
190 proc = subprocess.run(
191 rsync_argv('--fake-super', '-rlptgoD', '--specials', '-e',
192 str(devrsh), f'{devsrc}/', 'dummy:.'),
193 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
194 timeout=120)
195 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:300]!r}'
196 landed = devserved / 'ordinary'
197 if not landed.is_file() or landed.read_text() != 'PLAIN\n':
198 test_fail(f'control failed: pushing a tree containing a device did '
199 f'not deliver the ordinary file beside it, so nothing '
200 f'below proves anything. Clearing preserve_devices on '
201 f'the receiver alone desynchronises the file list at '
202 f'EVERY protocol, which fails the whole transfer ({ctx})')
203 if os.path.lexists(devserved / 'achar'):
204 test_fail(f'a push through a restricted rrsync recorded a device in '
205 f'the served tree ({ctx})')
206 if proc.returncode != 0:
207 test_fail(f'the device was denied, but the transfer itself failed '
208 f'({ctx})')
209
210 # --- Part 4: and NOT on the sending side ------------------------------------
211 # Forcing it there denies nothing (a sender creates nothing) while breaking the
212 # file list, because only one end of the connection gets the option.
213 for opt in ('-D', '--specials'):
214 forwarded = forwarded_opts(f'rsync --server --sender {opt} . .')
215 for forced in ('--drop-D', '--no-D'):
216 if forced in forwarded:
217 test_fail(f"restricted rrsync forced {forced} for `{opt}` on the "
218 'SENDING side, where there is nothing to deny: a sender '
219 'creates no device or special entry in the served tree '
220 f'({forwarded})')
221
222 print("rrsync-specials: --specials creates special files in the served tree; "
223 "a restricted rrsync forces --drop-D on the receiving side (a push can "
224 "create neither a special nor a device, and the transfer still "
225 "succeeds) and leaves the sending side alone")