Debian Codegraph @

testsuite/bare-do-open-symlink-race_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Python rewrite of testsuite/bare-do-open-symlink-race.test.
3 #
4 # Codex audit Findings 3b, 3c-symlink and 3c-mknod: bare do_open /
5 # do_symlink / do_mknod paths on the receiver follow parent symlinks
6 # unrestrictedly. Three scenarios are exercised; each must leave the
7 # outside-the-module sentinel unchanged.
8
9 import filecmp
10 import os
11 import shutil
12 import stat
13 import subprocess
14
15 from rsyncfns import (
16 SCRATCHDIR,
17 get_rootgid, get_rootuid, get_testuid,
18 rmtree, rsync_argv, start_test_daemon, test_fail, test_skipped,
19 )
20
21
22 DAEMON_PORT = 12884
23
24
25 mod = SCRATCHDIR / 'module'
26 outside = SCRATCHDIR / 'outside'
27 src = SCRATCHDIR / 'src_files'
28 conf = SCRATCHDIR / 'test-rsyncd.conf'
29 outside_pristine = SCRATCHDIR / 'outside-pristine.txt'
30
31
32 def setup():
33 for d in (mod, outside, src):
34 rmtree(d)
35 d.mkdir(parents=True)
36 (outside / 'target.txt').write_text("OUTSIDE_PROTECTED_DATA\n")
37 os.chmod(outside / 'target.txt', 0o644)
38 shutil.copy2(outside / 'target.txt', outside_pristine)
39 os.symlink(str(outside), mod / 'cd')
40
41
42 def verify_outside_unchanged(label: str) -> None:
43 mode = (outside / 'target.txt').stat().st_mode & 0o777
44 if mode != 0o644:
45 test_fail(f"{label}: outside/target.txt mode changed from 644 to {oct(mode)[2:]}")
46 if not filecmp.cmp(outside / 'target.txt', outside_pristine, shallow=False):
47 test_fail(f"{label}: outside/target.txt content changed -- daemon followed the cd symlink")
48
49
50 def verify_outside_unchanged_or_absent(label: str, target: str) -> None:
51 if (outside / target).exists() or (outside / target).is_symlink():
52 test_fail(f"{label}: outside/{target} was created -- daemon followed the cd symlink")
53
54
55 my_uid = get_testuid()
56 root_uid = get_rootuid()
57 root_gid = get_rootgid()
58 uid_line = f"uid = {root_uid}"
59 gid_line = f"gid = {root_gid}"
60 if my_uid != root_uid:
61 uid_line = '#' + uid_line
62 gid_line = '#' + gid_line
63
64
65 # All three scenarios use the same daemon -- they just target a different
66 # module. Write both modules up-front so the daemon doesn't need to be
67 # restarted between scenarios.
68 conf.write_text(f"""\
69 use chroot = no
70 {uid_line}
71 {gid_line}
72 log file = {SCRATCHDIR}/rsyncd.log
73 [upload]
74 path = {mod}
75 use chroot = no
76 read only = no
77
78 [upload_fake]
79 path = {mod}
80 use chroot = no
81 read only = no
82 fake super = yes
83 """)
84 daemon_url = start_test_daemon(conf, DAEMON_PORT).rstrip('/')
85
86
87 def run_attack(args):
88 """Run the (expected-to-be-contained) attack transfer and return its exit
89 code; output is discarded since the security assertion is on the filesystem."""
90 return subprocess.run(
91 rsync_argv(*args),
92 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
93 ).returncode
94
95
96 def positive_control():
97 """Confirm the upload module accepts an ordinary write. Without this, every
98 scenario below would also pass if the daemon refused (or failed) before the
99 vulnerable code ran -- the sentinel-unchanged check alone can't tell a
100 securely-contained attack from one that never reached the receiver path."""
101 for d in (mod, src):
102 rmtree(d)
103 d.mkdir(parents=True)
104 (src / 'legit.txt').write_text("LEGIT_IN_MODULE\n")
105 rc = run_attack(['-t', f'{src}/legit.txt', f'{daemon_url}/upload/legit.txt'])
106 if rc != 0 or not (mod / 'legit.txt').is_file() \
107 or (mod / 'legit.txt').read_text() != "LEGIT_IN_MODULE\n":
108 test_fail(f"positive control: upload module did not accept a normal "
109 f"write (rc={rc}); attack scenarios would be vacuous")
110
111
112 positive_control()
113
114
115 # Scenario 3b: --inplace --backup --backup-dir=cd
116 setup()
117 (mod / 'target.txt').write_text("EXISTING_MODULE_DATA\n")
118 os.chmod(mod / 'target.txt', 0o666)
119 (src / 'target.txt').write_text("NEW_DATA_FROM_SENDER\n")
120 os.chmod(src / 'target.txt', 0o644)
121
122 rc = run_attack([
123 '--inplace', '--backup', '--backup-dir=cd',
124 f'{src}/target.txt', f'{daemon_url}/upload/target.txt',
125 ])
126 if rc >= 128:
127 test_fail(f"3b inplace+backup-dir=cd: rsync died from a signal (rc={rc})")
128 verify_outside_unchanged("3b inplace+backup-dir=cd")
129
130
131 # Scenario 3c-symlink: fake-super symlink push, parent-symlinked path
132 setup()
133 (src / 'cd').mkdir()
134 os.symlink('/etc/passwd', src / 'cd' / 'sym')
135
136 rc = run_attack(['-rl', f'{src}/', f'{daemon_url}/upload_fake/'])
137 if rc >= 128:
138 test_fail(f"3c-symlink: rsync died from a signal (rc={rc})")
139 verify_outside_unchanged_or_absent("3c-symlink fake-super symlink push", "sym")
140
141
142 # Scenario 3c-mknod: fake-super FIFO push, parent-symlinked path
143 setup()
144 (src / 'cd').mkdir()
145 try:
146 os.mkfifo(src / 'cd' / 'fifo')
147 except OSError:
148 test_skipped("mkfifo unavailable; cannot exercise 3c-mknod")
149
150 if not stat.S_ISFIFO((src / 'cd' / 'fifo').stat().st_mode):
151 test_skipped("mkfifo unavailable; cannot exercise 3c-mknod")
152
153 rc = run_attack(['-rD', f'{src}/', f'{daemon_url}/upload_fake/'])
154 if rc >= 128:
155 test_fail(f"3c-mknod: rsync died from a signal (rc={rc})")
156 verify_outside_unchanged_or_absent("3c-mknod fake-super FIFO push", "fifo")