Debian Codegraph @

testsuite/batch-file-symlink_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # --write-batch / --read-batch must not follow planted symlinks at
3 # attacker-controlled path components.
4 #
5 # Threat: batch.c:232,238,242 call
6 # do_open() (plain open() under the hood) without O_NOFOLLOW. Two attacks:
7 #
8 # --write-batch: planted leaf symlink → root truncate+overwrite of an
9 # arbitrary file. Planted parent symlink → batch created
10 # inside an attacker-chosen dir.
11 #
12 # --read-batch: planted leaf symlink → rsync interprets attacker-chosen
13 # bytes as protocol data. Planted parent → same. Also: a
14 # planted FIFO/device at the read-batch path lets the
15 # attacker stream protocol bytes (the audit added a
16 # S_ISREG check on the opened fd as defense in depth).
17 #
18 # This test exercises both --write-batch variants (leaf and parent) where
19 # the leak signal is clear and direct: with the leak the victim file is
20 # truncated/overwritten or a new file appears under the planted parent;
21 # with the fix neither happens. --read-batch is covered by the same path-
22 # walk helper (the test for it would need a self-consistent batch payload
23 # to drive the receiver, which is excess machinery here).
24 #
25 # Requires root for the cross-uid plant; skips otherwise.
26
27 import os
28 import pwd
29 import subprocess
30
31 from rsyncfns import SCRATCHDIR, rmtree, rsync_argv, test_fail, test_skipped
32
33
34 if os.geteuid() != 0:
35 test_skipped("requires root to plant a symlink owned by a non-self uid "
36 "(the attacker simulation)")
37
38 NOBODY_UID = None
39 for name in ('nobody', 'nfsnobody', 'daemon'):
40 try:
41 u = pwd.getpwnam(name).pw_uid
42 if u != 0 and u != os.geteuid():
43 NOBODY_UID = u
44 break
45 except KeyError:
46 continue
47 if NOBODY_UID is None:
48 test_skipped("no untrusted-uid user available for cross-uid plant")
49
50
51 base = SCRATCHDIR / 'batch'
52 src = base / 'src'
53 dest = base / 'dest'
54 plants = base / 'plants'
55
56 rmtree(base)
57 src.mkdir(parents=True)
58 (src / 'f').write_text("payload\n")
59 dest.mkdir(parents=True)
60 plants.mkdir(parents=True)
61
62
63 def run_write_batch(batch_plant_path):
64 """Run rsync with --write-batch=batch_plant_path. The actual transfer
65 succeeds; we only care whether the batch open follows the planted symlink."""
66 # rsync writes both <name> and <name>.sh. Clean dest each run.
67 rmtree(dest); dest.mkdir(parents=True)
68 return subprocess.run(
69 rsync_argv('-a', '--write-batch=' + str(batch_plant_path),
70 f'{src}/', f'{dest}/'),
71 stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
72
73
74 # ---------------------------------------------------------------------------
75 # LEAF plant — --write-batch path is a symlink to a victim file. Without the
76 # fix, the O_TRUNC|O_WRONLY|O_CREAT open truncates the victim and writes the
77 # batch data into it.
78 # ---------------------------------------------------------------------------
79 victim = plants / 'sentinel_leaf'
80 INITIAL_BYTES = b"VICTIM_INITIAL_CONTENTS\n"
81 victim.write_bytes(INITIAL_BYTES)
82 os.chmod(victim, 0o600)
83
84 leaf_plant = plants / 'write_batch_leaf'
85 os.symlink(victim, leaf_plant)
86 os.lchown(leaf_plant, NOBODY_UID, NOBODY_UID)
87
88 run_write_batch(leaf_plant)
89
90 # Read as bytes — rsync's batch data is binary protocol, not text.
91 leaf_after = victim.read_bytes()
92 if leaf_after != INITIAL_BYTES:
93 test_fail(
94 f"--write-batch followed a planted LEAF symlink (owned by uid "
95 f"{NOBODY_UID}): victim {victim} was truncated/overwritten by the "
96 f"O_TRUNC open. {len(INITIAL_BYTES)} initial bytes replaced by "
97 f"{len(leaf_after)} bytes of attacker-influenceable batch data. "
98 f"Fix: refuse planted symlinks at --write-batch.")
99
100
101 # ---------------------------------------------------------------------------
102 # PARENT-component plant — --write-batch=plant/batchname where plant is a
103 # symlink to a victim dir. The kernel resolves the parent (symlink), creates
104 # the batch INSIDE the victim dir. Plain O_NOFOLLOW on the leaf does NOT
105 # defend this; only the path-walk's parent-symlink ownership check does.
106 # ---------------------------------------------------------------------------
107 real_target = plants / 'parent_real_target'
108 real_target.mkdir()
109
110 parent_plant = plants / 'parent_link'
111 os.symlink(real_target, parent_plant)
112 os.lchown(parent_plant, NOBODY_UID, NOBODY_UID)
113
114 run_write_batch(parent_plant / 'batchfile')
115
116 # Did rsync create the batch (and/or its .sh wrapper) inside the planted dir?
117 created = sorted(p.name for p in real_target.iterdir())
118 if created:
119 test_fail(
120 f"--write-batch followed a planted PARENT-component symlink (owned "
121 f"by uid {NOBODY_UID}): {parent_plant} -> {real_target} was "
122 f"traversed and rsync wrote batch artefact(s) into the victim dir: "
123 f"{created}. /tmp/somedir/-class parent-flip; plain O_NOFOLLOW does "
124 "NOT defend. Fix: per-component path walk with parent-symlink "
125 "ownership check.")
126
127
128 # ---------------------------------------------------------------------------
129 # --read-batch LEAF plant — the higher-power side of finding 1.6. Read-batch
130 # content drives the receiver's protocol parser, so a planted symlink lets the
131 # attacker stream arbitrary protocol bytes into the receiver and have it
132 # create / modify files anywhere the receiver can write. The leak signal in
133 # this test is direct: we first run a legitimate --write-batch to capture a
134 # real batch that creates a single canary file in the dest, then plant the
135 # read-batch path as a symlink to that legitimate batch. Without the fix,
136 # the planted symlink is followed, rsync replays the legitimate batch from
137 # the planted target, and the canary appears in the destination. With the
138 # fix, the planted symlink is refused (ELOOP via the owned-by-trusted-uid
139 # walk) and no canary appears.
140 # ---------------------------------------------------------------------------
141 legit_src = base / 'rb_src'
142 legit_src.mkdir()
143 (legit_src / 'rb_canary').write_bytes(b'AUDIT_READ_BATCH_LEAK_PAYLOAD')
144
145 # Capture a real batch by running write-batch normally (no symlinks in path).
146 legit_batch_dir = base / 'rb_legit_batch'
147 legit_batch_dir.mkdir()
148 legit_batch = legit_batch_dir / 'batch'
149 subprocess.run(
150 rsync_argv('-a', f'--write-batch={legit_batch}',
151 f'{legit_src}/', f'{dest}/rb_setup_unused/'),
152 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
153
154 # Now plant a symlink at the read-batch path, pointing at the legit batch.
155 rb_dest = base / 'rb_dest'
156 rmtree(rb_dest); rb_dest.mkdir()
157 rb_leaf_plant = plants / 'read_batch_leaf'
158 os.symlink(legit_batch, rb_leaf_plant)
159 os.lchown(rb_leaf_plant, NOBODY_UID, NOBODY_UID)
160
161 subprocess.run(
162 rsync_argv('-a', f'--read-batch={rb_leaf_plant}', str(rb_dest) + '/'),
163 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
164
165 if (rb_dest / 'rb_canary').exists():
166 test_fail(
167 f"--read-batch followed a planted LEAF symlink (owned by uid "
168 f"{NOBODY_UID}): rsync read the symlink's target as protocol data "
169 f"and replayed the legitimate batch from it, creating "
170 f"{rb_dest}/rb_canary in the destination. The leaked batch could "
171 "have written anywhere the receiver can write (higher-power "
172 "primitive than --write-batch). Fix: refuse planted symlinks at "
173 "--read-batch.")
174
175
176 # ---------------------------------------------------------------------------
177 # --read-batch S_ISREG defense-in-depth — even when no symlink is involved,
178 # a planted FIFO / device / socket at the read-batch path lets an attacker
179 # stream protocol bytes into the receiver. The audit's agreed defense is
180 # an fstat() S_ISREG check on the opened fd in addition to the path walk.
181 # We test it via a char-device node (a /dev/null clone) at the read-batch
182 # path: without the check rsync reads 0 bytes from the device and errors with
183 # a generic protocol message; with the check rsync errors with the specific
184 # "Batch file ... is not a regular file" message in stderr.
185 # ---------------------------------------------------------------------------
186 import stat as _stat
187
188 rb_dev = plants / 'read_batch_dev'
189 try:
190 # Recreate /dev/null with its REAL device number so the node is openable
191 # on every platform. A hardcoded makedev(1, 3) is only Linux's /dev/null;
192 # on BSD/Solaris that major/minor is an unconfigured device, so rsync would
193 # fail at open() (ENXIO) BEFORE reaching the S_ISREG check and the test
194 # would mis-report a defended path as a failure.
195 os.mknod(rb_dev, 0o600 | _stat.S_IFCHR, os.stat('/dev/null').st_rdev)
196 except OSError as e:
197 test_skipped(
198 f"cannot mknod a char device for S_ISREG sub-test ({e}); "
199 "likely no CAP_MKNOD or the filesystem disallows devnodes")
200
201 rb_dev_dest = base / 'rb_dev_dest'
202 rmtree(rb_dev_dest); rb_dev_dest.mkdir()
203 proc = subprocess.run(
204 rsync_argv('-a', f'--read-batch={rb_dev}', str(rb_dev_dest) + '/'),
205 stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
206
207 # The device must be refused. The S_ISREG check yields the specific "is not a
208 # regular file" message; on some platforms (e.g. OpenBSD) opening the device
209 # node fails first with ENXIO, which is an equally valid refusal at the open.
210 # A clean (returncode 0) run would be the real failure -- rsync accepting the
211 # device as a batch file.
212 refused = ('is not a regular file' in proc.stderr
213 or ('open error' in proc.stderr and proc.returncode != 0))
214 if not refused:
215 test_fail(
216 f"--read-batch did not refuse a non-regular batch path (char device at "
217 f"{rb_dev}). rsync returncode {proc.returncode}, stderr: "
218 f"{proc.stderr!r}. Fix: after the safe open, fstat() the fd and "
219 "refuse !S_ISREG.")