Debian Codegraph @

testsuite/daemon-chroot-acl_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Python rewrite of testsuite/daemon-chroot-acl.test.
3 #
4 # Regression test for GHSA-rjfm-3w2m-jf4f: a hostname-based "hosts deny"
5 # rule must still match when the daemon performs a 'daemon chroot' and
6 # the chroot does not contain the NSS files glibc needs for reverse
7 # DNS. Pre-fix, reverse DNS happened *after* the chroot, the lookup
8 # failed, client_name() returned "UNKNOWN", and a deny rule referring
9 # to the connecting hostname silently failed to match.
10
11 import os
12 import platform
13 import shutil
14 import subprocess
15 import sys
16
17 from rsyncfns import (
18 SCRATCHDIR, TODIR,
19 require_tcp, rmtree, rsync_argv, start_test_daemon, test_fail, test_skipped,
20 )
21
22
23 DAEMON_PORT = 12878
24
25 # This test fundamentally needs a real TCP peer address: the daemon reverse-
26 # resolves the connecting IP for a hostname-based "hosts deny" ACL check.
27 # The stdio-pipe transport has no peer IP, so only run under --use-tcp.
28 require_tcp("needs a real TCP peer address for reverse-DNS hostname ACL; "
29 "run with --use-tcp")
30
31 if platform.system() != 'Linux':
32 test_skipped("test is Linux-specific (uses chroot+unshare)")
33
34 # Need CAP_SYS_CHROOT. Re-exec under a user namespace if not root.
35 def _can_chroot() -> bool:
36 proc = subprocess.run(['chroot', '/', '/bin/true'],
37 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
38 return proc.returncode == 0
39
40
41 if not _can_chroot():
42 if not os.environ.get('RSYNC_UNSHARED'):
43 unshare = shutil.which('unshare')
44 if unshare is not None:
45 probe = subprocess.run(
46 [unshare, '--user', '--map-root-user', 'true'],
47 capture_output=True,
48 )
49 if probe.returncode == 0:
50 print("Re-running under unshare --user --map-root-user...")
51 env = os.environ.copy()
52 env['RSYNC_UNSHARED'] = '1'
53 os.execvpe(
54 unshare,
55 [unshare, '--user', '--map-root-user',
56 sys.executable, __file__],
57 env,
58 )
59 test_skipped("need CAP_SYS_CHROOT (root or unshare --user --map-root-user)")
60
61
62 # Find what 127.0.0.1 reverse-resolves to.
63 def _client_hostname() -> str:
64 try:
65 out = subprocess.check_output(['getent', 'hosts', '127.0.0.1'], text=True)
66 except (subprocess.CalledProcessError, FileNotFoundError):
67 return ''
68 for line in out.splitlines():
69 parts = line.split()
70 if len(parts) >= 2:
71 return parts[1]
72 return ''
73
74
75 client_hostname = _client_hostname()
76 if not client_hostname or client_hostname == '127.0.0.1':
77 test_skipped("no reverse DNS for 127.0.0.1")
78
79 chrootdir = SCRATCHDIR / 'chroot'
80 rmtree(chrootdir)
81 (chrootdir / 'modroot').mkdir(parents=True)
82 (chrootdir / 'modroot' / 'file1').write_text("from chroot\n")
83
84 conf = SCRATCHDIR / 'test-rsyncd.conf'
85 logfile = SCRATCHDIR / 'rsyncd.log'
86
87
88 def write_conf(global_rev: str, module_rev: str) -> None:
89 conf.write_text(f"""\
90 use chroot = no
91 log file = {logfile}
92 daemon chroot = {chrootdir}
93 reverse lookup = {global_rev}
94 hosts deny = {client_hostname}
95 max verbosity = 4
96
97 [chrootmod]
98 path = /modroot
99 read only = yes
100 reverse lookup = {module_rev}
101 """)
102
103
104 def run_check(label: str) -> bool:
105 if logfile.exists():
106 logfile.unlink()
107 rmtree(TODIR)
108 TODIR.mkdir()
109
110 # rsyncd re-reads its config file on each accepted connection, so
111 # rewriting `conf` between scenarios is enough -- we keep the one
112 # daemon for both.
113 proc = subprocess.run(
114 rsync_argv('-av', f'{url}chrootmod/', f'{TODIR}/'),
115 capture_output=True, text=True,
116 )
117 out = proc.stdout + proc.stderr
118
119 print(f"----- {label} (rsync exit {proc.returncode}):")
120 print(out)
121 print("----- daemon log:")
122 if logfile.exists():
123 print(logfile.read_text())
124 print("-----")
125
126 return '@ERROR' in out and 'access denied' in out
127
128
129 # Spin up the daemon once; we'll rewrite `conf` between scenarios and rely
130 # on rsyncd's per-connection re-read of the config file.
131 write_conf('yes', 'yes')
132 url = start_test_daemon(conf, DAEMON_PORT)
133
134 # Scenario A: global reverse lookup. Covered by b6abdb4c.
135 if not run_check("Scenario A (global reverse lookup = yes)"):
136 test_fail("Scenario A: hostname deny rule was bypassed")
137
138 # Scenario B: only per-module reverse-lookup enabled.
139 write_conf('no', 'yes')
140 if not run_check("Scenario B (per-module reverse lookup only)"):
141 test_fail(
142 "Scenario B: hostname deny rule was bypassed (per-module reverse "
143 "lookup with daemon chroot still has the bypass)"
144 )