Debian Codegraph @

testsuite/daemon-refuse-compress-threads-alias_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """``refuse options = compress-threads`` must also refuse its ``--zt`` alias.
3
4 set_refuse_options() stopped after the first exact long-option match, so the
5 canonical compress-threads entry was disabled but its later zt alias stayed
6 accepted. Both halves here build the daemon argv by hand -- a stock client
7 does not forward this option at all unless asked to with -M, and the raw
8 protocol is what preserves the exact spelling under test.
9
10 The oracle is the refusal itself: the alias connection must be torn down and
11 the daemon must log "configured to refuse --zt". It is deliberately NOT the
12 worker count. An accepted --zt that happens to produce few threads is still a
13 defeated refuse rule, and several unrelated things bound that count -- a
14 separate daemon worker cap (see the Zstandard thread-cap change), a libzstd
15 built without multithreading, or a process/thread limit -- so a count-based
16 assertion goes green while the rule is bypassed. The count is still measured,
17 but only to say how much capability the bypass delivered.
18 """
19
20 import json
21 import os
22 import re
23 import subprocess
24 import sys
25 import time
26
27 from rsyncfns import (
28 SCRATCHDIR, claim_ports, require_tcp, rmtree, run_rsync,
29 start_rsyncd, test_fail, test_skipped,
30 )
31 import rsync_proto as rp
32
33 PORT = 13121
34 REQUESTED_THREADS = 256
35 MAX_SAFE_THREADS = 64
36
37 require_tcp("the malicious receiver needs a real TCP daemon; run with --use-tcp")
38 claim_ports(PORT)
39
40 version = json.loads(run_rsync('-VV', check=True, capture_output=True).stdout)
41 if 'zstd' not in version.get('compress_list', []):
42 test_skipped('this build does not include Zstandard')
43
44 base = SCRATCHDIR / 'daemon-refuse-compress-threads-alias'
45 rmtree(base)
46 mod = base / 'module'
47 mod.mkdir(parents=True)
48 (mod / 'f').write_bytes(os.urandom(2 * 1024 * 1024))
49
50 log = base / 'rsyncd.log'
51 conf = base / 'rsyncd.conf'
52 conf.write_text(f"""\
53 pid file = {base}/rsyncd.pid
54 log file = {log}
55 use chroot = no
56
57 [mod]
58 path = {mod}
59 refuse options = compress-threads
60 """)
61 start_rsyncd(conf, PORT)
62
63
64 def refusal_logged(spelling):
65 needle = f'configured to refuse --{spelling}'
66 for _ in range(100):
67 if log.exists() and needle in log.read_text(errors='replace'):
68 return True
69 time.sleep(0.02)
70 return False
71
72
73 # Control: preserve the canonical spelling in a hand-built daemon argv and
74 # verify that the configured rule rejects it before any file list is served.
75 control = rp.DaemonClient('127.0.0.1', PORT)
76 control_rejected = False
77 try:
78 control.handshake(
79 'mod',
80 [
81 '--server', '--sender', '-e.LsfxCIu', '--compress',
82 '--compress-choice=zstd', '--compress-threads=2', '.', 'mod/f',
83 ],
84 greeting_version=30,
85 )
86 control.recv_flist(preserve_links=False)
87 except (rp.ProtocolError, OSError):
88 control_rejected = True
89 finally:
90 control.close()
91 if not control_rejected or not refusal_logged('compress-threads'):
92 test_fail('canonical --compress-threads unexpectedly bypassed its refuse rule')
93
94 # Attack: preserve the accepted alias spelling in a hand-built daemon argv.
95 c = rp.DaemonClient('127.0.0.1', PORT)
96 try:
97 c.handshake(
98 'mod',
99 [
100 '--server', '--sender', '-e.LsfxCIu', '--compress',
101 '--compress-choice=zstd', f'--zt={REQUESTED_THREADS}', '.', 'mod/f',
102 ],
103 greeting_version=30,
104 )
105 entries = rp.sort_entries(c.recv_flist(preserve_links=False))
106 except (rp.ProtocolError, OSError):
107 c.close()
108 if not refusal_logged('zt'):
109 test_fail('the alias connection ended, but the daemon never logged a '
110 '--zt refusal, so it was not the refuse rule that stopped it')
111 print('daemon refuse rule rejected both --compress-threads and --zt')
112 sys.exit(0)
113
114 # Reaching here means the daemon served a file list for --zt: the refuse rule
115 # did not fire and the capability was delivered. That is the bug, whatever
116 # the worker count turns out to be. Measure it anyway, to report what the
117 # bypass was worth.
118 ndx = next(i for i, entry in enumerate(entries) if entry.name == b'f')
119 c.send_data(c.make_request(ndx) + c.w_ndx(rp.NDX_DONE))
120
121 child_pid = None
122 for _ in range(100):
123 matches = re.findall(r'\[(\d+)\] rsync on mod/f',
124 log.read_text(errors='replace') if log.exists() else '')
125 if matches:
126 child_pid = int(matches[-1])
127 break
128 time.sleep(0.02)
129 if child_pid is None:
130 c.close()
131 test_fail('could not identify the per-connection daemon sender')
132
133
134 def thread_count(pid):
135 if sys.platform == 'darwin':
136 proc = subprocess.run(['ps', '-M', str(pid)], capture_output=True,
137 text=True)
138 return max(0, len(proc.stdout.splitlines()) - 1)
139 if sys.platform.startswith('linux'):
140 try:
141 status = open(f'/proc/{pid}/status').read()
142 except OSError:
143 return 0
144 match = re.search(r'^Threads:\s+(\d+)', status, re.M)
145 return int(match.group(1)) if match else 0
146 return -1
147
148
149 observed = 0
150 for _ in range(100):
151 observed = max(observed, thread_count(child_pid))
152 if observed >= REQUESTED_THREADS:
153 break
154 time.sleep(0.02)
155 c.close()
156
157 how_many = (f'and it created {observed} worker threads'
158 if observed > 0 else
159 'though its thread count could not be read here')
160 test_fail(f'canonical --compress-threads was refused but its --zt alias was '
161 f'accepted: the daemon served the file list {how_many}. A refuse '
162 f'rule naming one spelling of an option must cover every spelling '
163 f'of it')