Debian Codegraph @

testsuite/malicious-server-partial-basis-symlink-overwrite_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """A malicious pull server must not redirect an in-place partial update.
3
4 Protocol-30 peers advertise support for updating a partial basis in place. The
5 sender controls the response's basis-type byte. A relative --partial-dir path
6 contains peer-named components, so treating the entire path as operator-trusted
7 lets a server-planted, receiver-owned symlink redirect the basis/output open to
8 an arbitrary client-local file outside the destination.
9 """
10
11 import hashlib
12 import os
13 import socket
14 import struct
15 import subprocess
16 import threading
17 import time
18
19 from rsyncfns import (
20 SCRATCHDIR, claim_ports, makepath, require_tcp, rmtree, rsync_argv,
21 test_fail,
22 )
23 import rsync_proto as rp
24
25 PORT = 13153
26 CF_INPLACE_PARTIAL_DIR = 1 << 6
27 FNAMECMP_PARTIAL_DIR = 0x81
28 PAYLOAD = b'MALICIOUS-SERVER-OVERWRITE\n'
29 ORIGINAL = b'CLIENT-LOCAL-OUTSIDE-VICTIM\n'
30
31 require_tcp('the malicious sender needs a real TCP socket; run with --use-tcp')
32 claim_ports(PORT)
33
34 base = SCRATCHDIR / 'malicious-server-partial-basis-symlink-overwrite'
35 rmtree(base)
36 dest = base / 'dest'
37 outside = base / 'outside'
38 makepath(dest / 'escape', outside)
39 victim = outside / 'victim'
40 victim.write_bytes(ORIGINAL)
41
42 # This symlink can be left by the same pull server in an earlier transfer. It
43 # is owned by the receiver's euid, which is trusted by operator-path resolution
44 # but must not be trusted for the peer-derived tail of a partial-dir path.
45 partial_link = dest / 'escape' / '.rsync-partial'
46 os.symlink(str(outside), partial_link)
47 if os.lstat(partial_link).st_uid != os.geteuid():
48 test_fail('setup did not create a receiver-euid-owned partial-dir symlink')
49
50 lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
51 lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
52 lsock.bind(('127.0.0.1', PORT))
53 lsock.listen(1)
54 lsock.settimeout(30)
55 state = {}
56
57
58 def serve():
59 try:
60 csock, _ = lsock.accept()
61 peer = rp.DaemonReceiver(csock)
62 peer.handshake(compat_flags=CF_INPLACE_PARTIAL_DIR)
63 # The helper intentionally leaves the client argv unread because most
64 # malicious-server tests do not need the reverse stream. Consume its
65 # NUL-separated argv here so we can inspect the later multiplexed
66 # generator request and prove that the response is solicited.
67 nul_run = 0
68 while nul_run < 2:
69 b = peer._recv_exact(1)
70 nul_run = nul_run + 1 if b == b'\0' else 0
71 parent = rp.FileEntry(
72 'escape', mode=rp.S_IFDIR | 0o755,
73 extra_flags=rp.XMIT_TOP_DIR | rp.XMIT_NO_CONTENT_DIR,
74 modtime=1700000000,
75 )
76 entry = rp.FileEntry(
77 'escape/victim', mode=rp.S_IFREG | 0o644,
78 length=len(PAYLOAD), modtime=1700000000,
79 )
80 peer.send_data(parent.encode() + entry.encode() + rp.end_of_flist())
81
82 # Wait for the client's generator to request this exact file, and
83 # read the request properly rather than hunting for a byte pattern:
84 # the generator first sends its filter list (rsync auto-adds a
85 # perishable exclude for the partial dir, "-p .rsync-partial/"), and
86 # only then the index and its item flags.
87 #
88 # Which basis the generator names varies between environments, and
89 # both outcomes are worth driving:
90 #
91 # * no ITEM_BASIS_TYPE_FOLLOWS -- it asked for a plain new-file
92 # transfer, so the forged response below SUBSTITUTES a partial
93 # basis it never requested. That is the unbound-basis-type bug.
94 # * ITEM_BASIS_TYPE_FOLLOWS + FNAMECMP_PARTIAL_DIR -- it noticed the
95 # planted partial file and asked for that basis itself, so the
96 # response is no longer substituting anything and the test instead
97 # proves the receiver CONFINES a basis it did request.
98 #
99 # Either way the receiver must not follow the symlink, which is what
100 # the assertions after the transfer check. Anything else named as the
101 # basis means the fixture changed under us and is a failure.
102 # DaemonReceiver speaks the raw socket; the de-multiplexing and the
103 # primitive reads live on DaemonClient, so spell the few we need here.
104 mux = bytearray()
105
106 def read_data(n):
107 while len(mux) < n:
108 word = struct.unpack('<I', peer._recv_exact(4))[0]
109 payload = peer._recv_exact(word & 0xFFFFFF)
110 if (word >> 24) - rp.MPLEX_BASE == rp.MSG_DATA:
111 mux.extend(payload)
112 # anything else is a log/info frame: not part of the stream
113 out = bytes(mux[:n])
114 del mux[:n]
115 return out
116
117 def r_int():
118 return struct.unpack('<i', read_data(4))[0]
119
120 def r_shortint():
121 return struct.unpack('<H', read_data(2))[0]
122
123 def r_byte():
124 return read_data(1)[0]
125
126 def r_ndx():
127 # io.c read_ndx() at protocol >= 30, for the first positive index
128 # only: this reads one request and never resumes, so it needs no
129 # running previous-index state.
130 b0 = read_data(1)[0]
131 if b0 == 0:
132 raise RuntimeError('generator sent NDX_DONE before requesting '
133 'anything')
134 if b0 == 0xFF:
135 raise RuntimeError('generator sent a negative index first')
136 if b0 == 0xFE:
137 b = read_data(2)
138 if b[0] & 0x80:
139 rest = read_data(2)
140 return (((b[0] & 0x7F) << 24) | b[1]
141 | (rest[0] << 8) | (rest[1] << 16))
142 return (b[0] << 8) + b[1] - 1
143 return b0 - 1
144
145 peer.sock.settimeout(10)
146 try:
147 # The filter list: int32 length + payload, terminated by a zero.
148 while True:
149 n = r_int()
150 if n == 0:
151 break
152 if not 0 < n <= 4096:
153 raise RuntimeError(f'implausible filter-rule length {n}')
154 read_data(n)
155
156 ndx = r_ndx()
157 if ndx != 1:
158 raise RuntimeError(f'generator asked for index {ndx}, not 1')
159 iflags = r_shortint()
160 if not (iflags & rp.ITEM_TRANSFER):
161 raise RuntimeError(
162 f'generator did not ask to transfer index 1 '
163 f'(item flags 0x{iflags:04x})')
164 requested_basis = rp.FNAMECMP_FNAME
165 if iflags & rp.ITEM_BASIS_TYPE_FOLLOWS:
166 requested_basis = r_byte()
167 if requested_basis != FNAMECMP_PARTIAL_DIR:
168 raise RuntimeError(
169 'generator named basis type '
170 f'0x{requested_basis:02x}, expected either none or '
171 f'FNAMECMP_PARTIAL_DIR (0x{FNAMECMP_PARTIAL_DIR:02x})')
172 if iflags & rp.ITEM_XNAME_FOLLOWS:
173 ln = r_byte()
174 if ln == 0xFF:
175 ln = r_byte() + 0x80
176 read_data(ln)
177 except TimeoutError as exc:
178 raise RuntimeError(
179 'generator never requested index 1'
180 ) from exc
181
182 response = bytearray()
183 response += peer.w_ndx(1)
184 response += rp.w_shortint(
185 rp.ITEM_TRANSFER | rp.ITEM_BASIS_TYPE_FOLLOWS)
186 response += rp.w_byte(FNAMECMP_PARTIAL_DIR)
187 response += rp.w_sum_head(0, 0, 0, 0)
188 response += rp.w_int(len(PAYLOAD)) + PAYLOAD
189 response += rp.w_int(0)
190 response += hashlib.md5(PAYLOAD).digest()
191 response += peer.w_ndx(rp.NDX_DONE)
192 response += peer.w_ndx(rp.NDX_DONE)
193 response += peer.w_ndx(rp.NDX_DONE)
194 peer.send_data(response)
195 time.sleep(2)
196 peer.close()
197 except Exception as exc: # noqa: BLE001
198 state['err'] = repr(exc)
199
200
201 thread = threading.Thread(target=serve, daemon=True)
202 thread.start()
203 proc = subprocess.run(
204 rsync_argv('-R', '--no-implied-dirs', '--partial-dir=.rsync-partial',
205 '--no-whole-file',
206 f'rsync://127.0.0.1:{PORT}/mod/', str(dest) + '/'),
207 stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=20,
208 )
209 thread.join(timeout=5)
210 lsock.close()
211
212 output = (proc.stdout or '') + (proc.stderr or '')
213 if state.get('err'):
214 test_fail(f'Python sender failed: {state["err"]}\n{output}')
215 if not victim.exists():
216 test_fail(
217 'malicious pull server made partial-basis cleanup follow a '
218 'receiver-owned symlink and delete an arbitrary client-local file '
219 'outside the destination tree'
220 )
221 after = victim.read_bytes()
222 if after == PAYLOAD:
223 test_fail(
224 'malicious pull server made an in-place partial-basis update follow '
225 'a receiver-owned symlink and overwrite an arbitrary client-local '
226 'file outside the destination tree'
227 )
228 if after != ORIGINAL:
229 test_fail(f'outside victim changed unexpectedly: {after!r}\n{output}')
230
231 print('malicious-server-partial-basis-symlink-overwrite: outside victim survived')