Debian Codegraph @

testsuite/malicious-sender-delete-scope_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Malicious daemon-sender expands --delete scope by flipping an implied
3 # parent into a content-dir.
4 #
5 # Threat (Mitchell Benjamin report, May 2026; PoC 3):
6 # With `rsync -rR --delete rsync://host/m/dir/file dest/`, the client
7 # requests a single relative path. The sender's honest flow encodes
8 # implied parents with XMIT_TOP_DIR|XMIT_NO_CONTENT_DIR (flist.c:415
9 # in send_file_entry). A malicious daemon-sender that omits
10 # XMIT_NO_CONTENT_DIR on the implied parent "dir" makes the receiver
11 # set FLAG_CONTENT_DIR (flist.c:1095), and the generator then calls
12 # delete_in_dir("dest/dir") under --delete, sweeping pre-existing
13 # siblings the receiver expected to keep.
14 #
15 # The receiver-side fix (this branch) downgrades implied-parent dirs
16 # to non-content regardless of the sender's xflags byte, so
17 # delete_in_dir cannot run on a directory the implied_filter_list
18 # only knows as a parent.
19 #
20 # Test approach (Mitchell's PoC 3 adapted):
21 # We don't need a fake-daemon-protocol speaker. Instead, build a
22 # "malicious rsync" out of the same source tree by doing a one-line
23 # substring replacement in flist.c that strips XMIT_NO_CONTENT_DIR
24 # from the implied-parent encoding, then run the patched binary as
25 # the daemon-sender and the production rsync (the one under test)
26 # as the receiver. The receiver-side fix is what we're verifying.
27 #
28 # Honest-sender baseline (the production rsync as daemon-sender)
29 # exists implicitly: every other -rR --delete test in the suite
30 # already exercises that path, so we don't repeat it here. The
31 # patched-rsync arm is the one signal that distinguishes RED from
32 # GREEN.
33 #
34 # Build cost:
35 # make(1) is invoked inside a copied source tree, ~10-30s. We skip
36 # the test cleanly if SRCDIR isn't a writable build tree (e.g. when
37 # running an installed rsync from a binary package via --rsync-bin).
38 #
39 # Outcome:
40 # * dest/dir/keep.txt SURVIVES the pull -> fix is in place (PASS).
41 # * dest/dir/keep.txt is DELETED -> bug present (FAIL with leak
42 # diagnostic).
43
44 import os
45 import shlex
46 import shutil
47 import subprocess
48
49 from rsyncfns import (
50 SCRATCHDIR, SRCDIR, makepath, rmtree, rsync_argv,
51 test_fail, test_skipped, write_daemon_conf,
52 )
53
54 # Sanity gates ---------------------------------------------------------------
55 # Need a writable source tree we can copy and `make rsync` in.
56 if not (SRCDIR / 'flist.c').is_file() or not (SRCDIR / 'Makefile').is_file():
57 test_skipped("malicious-sender-delete-scope: needs a writable rsync "
58 f"source tree at SRCDIR={SRCDIR} with Makefile + flist.c; "
59 "the patched-sender build relies on it.")
60 if not shutil.which('make'):
61 test_skipped("malicious-sender-delete-scope: make(1) not on PATH")
62 if not shutil.which('gcc') and not shutil.which('cc'):
63 test_skipped("malicious-sender-delete-scope: no C compiler on PATH")
64
65
66 # -- Build the malicious sender ---------------------------------------------
67 # flist.c send_implied_dirs() sets up the flags an implied-parent will be
68 # encoded with via the FLAG_IMPLIED_DIR branch of send_file_entry's xflags
69 # computation (line ~415). Strip XMIT_NO_CONTENT_DIR from that one
70 # assignment so the implied parent is sent with XMIT_TOP_DIR ALONE. Every
71 # other encoding path is unchanged, so the resulting daemon-sender is
72 # honest about everything except the implied-parent encoding -- which is
73 # exactly the threat model.
74 mal_src = SCRATCHDIR / 'mal-rsync'
75 rmtree(mal_src)
76 shutil.copytree(SRCDIR, mal_src, symlinks=True,
77 ignore=shutil.ignore_patterns('testtmp', '.git', 'auto-build-save'))
78
79 flist_c = mal_src / 'flist.c'
80 PATCH_OLD = "xflags = XMIT_TOP_DIR | XMIT_NO_CONTENT_DIR;"
81 PATCH_NEW = "xflags = XMIT_TOP_DIR; /* malicious-sender PoC: drop NO_CONTENT_DIR */"
82 text = flist_c.read_text()
83 if PATCH_OLD not in text:
84 test_skipped(
85 "malicious-sender-delete-scope: could not find the implied-parent "
86 "encoding literal in flist.c -- upstream rename? Looking for: "
87 f"{PATCH_OLD!r}. Update PATCH_OLD in this test if the assignment "
88 "changed shape.")
89 flist_c.write_text(text.replace(PATCH_OLD, PATCH_NEW, 1))
90
91 # Build just the rsync binary in the copied tree. The copy includes
92 # config.h / Makefile so configure has already been done. Suppress
93 # stdout/stderr because a clean rebuild produces several screens of gcc
94 # output that aren't useful here.
95 build = subprocess.run(['make', '-j2', 'rsync'], cwd=str(mal_src),
96 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
97 text=True)
98 mal_rsync = mal_src / 'rsync'
99 if build.returncode != 0 or not mal_rsync.is_file() or not os.access(mal_rsync, os.X_OK):
100 test_skipped(
101 "malicious-sender-delete-scope: malicious-sender build failed. "
102 f"`make rsync` rc={build.returncode}. Tail of build output:\n"
103 + '\n'.join(build.stdout.splitlines()[-20:]))
104
105
106 # -- Set up source + dest, with the sentinel ----------------------------------
107 base = SCRATCHDIR / 'mal-test'
108 rmtree(base)
109 src = base / 'src'
110 dest = base / 'dest'
111 makepath(src / 'dir')
112 makepath(dest / 'dir')
113 (src / 'dir' / 'file').write_text("from server\n")
114 sentinel = dest / 'dir' / 'keep.txt'
115 sentinel.write_text("MUST_STAY\n")
116
117
118 # -- Wire up the malicious daemon via RSYNC_CONNECT_PROG ----------------------
119 # The runtests.py secure-default daemon transport uses RSYNC_CONNECT_PROG
120 # to fork a daemon over a private stdio pipe instead of binding a TCP
121 # socket. That seam lets us point the production rsync (the receiver)
122 # at the malicious binary as its daemon-sender without ever touching a
123 # listening port -- which also keeps the test compatible with the
124 # concurrent-j16 runner.
125 conf = write_daemon_conf(
126 [('m', {'path': str(src),
127 'read only': 'yes',
128 'use chroot': 'no'})],
129 name='mal-rsyncd.conf')
130 os.environ['RSYNC_CONNECT_PROG'] = f'{shlex.quote(str(mal_rsync))} --config={shlex.quote(str(conf))} --daemon'
131
132
133 # -- The attack pull: -rR --delete from the malicious daemon -----------------
134 # The receiver is the production rsync (which on the fix branches carries
135 # the implied-parent downgrade). Use --debug=del2 so we can grep the
136 # output for delete_in_dir() if we need to triangulate a failure later.
137 url = 'rsync://localhost/m/dir/file'
138 proc = subprocess.run(
139 rsync_argv('-rR', '--delete', '--debug=del2', url, str(dest) + '/'),
140 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
141
142
143 # -- The oracle --------------------------------------------------------------
144 # With the FIX: receiver recognises "dir" as an implied-parent-only entry,
145 # forces XMIT_NO_CONTENT_DIR back into the xflags before flag mapping, so
146 # FLAG_CONTENT_DIR is never set; delete_in_dir() never runs on dir;
147 # sentinel survives.
148 #
149 # Without the FIX: receiver trusts the malicious xflags byte, sets
150 # FLAG_CONTENT_DIR on "dir", generator runs delete_in_dir("dest/dir"),
151 # sweeps every entry that wasn't in the sender's list, sentinel is gone.
152 if not sentinel.is_file():
153 debug_tail = '\n'.join(proc.stdout.splitlines()[-30:])
154 test_fail(
155 f"malicious daemon-sender expanded --delete scope: "
156 f"{sentinel} was deleted by the receiver. This means the "
157 "implied parent 'dir' was flagged FLAG_CONTENT_DIR on the basis "
158 "of the sender's xflags byte (XMIT_TOP_DIR without "
159 "XMIT_NO_CONTENT_DIR), and delete_in_dir() ran on dest/dir. "
160 "Fix: the receiver must force XMIT_NO_CONTENT_DIR on any "
161 "directory entry that implied_filter_list only allowed as a "
162 "parent (flist.c recv_file_entry). Last 30 lines of receiver "
163 f"output:\n{debug_tail}")
164
165 # Also assert the file the sender legitimately offered did arrive --
166 # without this, a daemon that crashed before sending anything would also
167 # leave the sentinel alone and we'd false-pass.
168 delivered = dest / 'dir' / 'file'
169 if not delivered.is_file():
170 test_fail(
171 f"sentinel survived but the malicious daemon didn't deliver "
172 f"{delivered} either -- the test is vacuous. Receiver rc="
173 f"{proc.returncode}. Output tail:\n"
174 + '\n'.join(proc.stdout.splitlines()[-20:]))
175
176 print(
177 f"malicious-sender-delete-scope: receiver refused to expand --delete "
178 f"scope under a malicious sender that omitted XMIT_NO_CONTENT_DIR on "
179 f"the implied parent. {sentinel.name} survived, "
180 f"{delivered.relative_to(dest)} delivered.")