Debian Codegraph @

testsuite/daemon-auth-users-comma-only_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """A leading comma in "auth users" must make splitting comma-only.
3
4 rsyncd.conf(5) documents that when the auth users value starts with a comma,
5 splitting is done on commas ALONE, so an entry may contain spaces -- which is
6 how an NSS group name with a space is written:
7
8 auth users = ,@Group Name:deny, alice:rw
9
10 auth_server() ignored that and always tokenised on commas AND whitespace
11 (strtok(users, " ,\\t")), so "@Group Name:deny" was torn into "@Group" and
12 "Name:deny": the group rule the administrator wrote never matched anything, and
13 a username rule they never wrote appeared out of its tail.
14
15 The reported impact is an authorization BYPASS: a member of a denied group
16 evades the deny and matches a later :rw entry. Both directions are covered.
17
18 "grpdeny" drives the reported one without needing an NSS group whose name
19 contains a space, which a test cannot create: "@[! []*" is a wildmatch class
20 holding a space that matches any ordinary group name -- one with no "/" in it,
21 which wildmatch treats as a path separator -- whose first character is neither
22 a space nor a "[". So the entry contains a space and still matches a real
23 group. The "[" is excluded so that the tail left by a whitespace split,
24 "[]*", is an unterminated class that can match no name at all: with the
25 simpler "[! ]*" the tail is "]*", which would match (and deny) any user whose
26 name began with "]", letting the buggy parser produce the right refusal for
27 the wrong reason.
28
29 "spaced" drives the identical defect in the direction that needs no groups:
30
31 auth users = ,@nosuchgroup alice:deny, alice:rw
32
33 * parsed as documented -- one entry "@nosuchgroup alice:deny" naming a group
34 that does not exist, so no match, then "alice:rw" grants access.
35 * parsed by splitting on whitespace -- "@nosuchgroup", then "alice:deny",
36 which matches the username and refuses the transfer that should succeed.
37
38 Either way the rule enforced is not the rule written. Each direction has its
39 own control module proving the credential and the transfer itself are fine, and
40 the deny is checked against the daemon log rather than the client's output,
41 because a client is told only "auth failed" for every server-side reason alike.
42 """
43
44 import os
45 import subprocess
46
47 from rsyncfns import (
48 SCRATCHDIR, makepath, rmtree, rsync_argv, start_test_daemon, test_fail,
49 write_daemon_conf,
50 )
51
52 PORT = 12949
53 USER = 'authuser'
54 PASSWORD = 'known-password'
55 DATA = 'AUTH-USERS-PARSE\n'
56
57 base = SCRATCHDIR / 'auth-users-comma-only'
58 rmtree(base)
59 src = base / 'src'
60 mod = base / 'mod'
61 ctrl = base / 'ctrl'
62 grp = base / 'grp'
63 grpc = base / 'grpc'
64 makepath(src, mod, ctrl, grp, grpc)
65 (src / 'f1').write_text(DATA)
66
67 # The group half needs an auth name the daemon can resolve to a real uid, or
68 # getallgroups() finds nothing and no group rule can ever match.
69 import pwd
70 REALUSER = pwd.getpwuid(os.geteuid()).pw_name
71
72 secrets = base / 'auth-users.secrets'
73 secrets.write_text(f'{USER}:{PASSWORD}\n{REALUSER}:{PASSWORD}\n')
74 secrets.chmod(0o600)
75 pwfile = base / 'auth-users.password'
76 pwfile.write_text(PASSWORD + '\n')
77 pwfile.chmod(0o600)
78
79 common = {
80 'read only': 'no',
81 'use chroot': 'no',
82 'secrets file': str(secrets),
83 }
84
85 conf = write_daemon_conf([
86 # The documented comma-only form. The first entry names a group that does
87 # not exist, so only the second entry may decide the outcome.
88 ('spaced', dict(common, path=str(mod),
89 **{'auth users': f',@nosuchgroup {USER}:deny, {USER}:rw'})),
90 # Control: same credential, same transfer, no space in any entry.
91 ('plain', dict(common, path=str(ctrl),
92 **{'auth users': f'{USER}:rw'})),
93 # The reported direction: a group rule containing a space must DENY a member.
94 # "[! []*" is a wildmatch class holding a space that matches any ordinary
95 # group name whose first character is neither a space nor a "[" -- i.e. a
96 # real group of REALUSER -- so the space is exercised without needing an
97 # NSS group named with one. (Ordinary: wildmatch reads "/" as a path
98 # separator, so a group name containing one would not match either.)
99 # documented parse: one entry "@[! []*:deny" -> the deny fires
100 # whitespace parse: "@[!" (an unterminated class, so no group) plus
101 # "[]*:deny" (likewise, so no user), and with neither
102 # matching the later ":rw" lets them in.
103 # Positive control for the group half: "@*" matches any group, so this
104 # only succeeds if the daemon resolved REALUSER to a uid, enumerated its
105 # groups, accepted its secret and could store the file. Without it a
106 # grpdeny refusal could be any of those failing instead of the deny.
107 ('grpctl', dict(common, path=str(grpc),
108 **{'auth users': f'@*:rw'})),
109 ('grpdeny', dict(common, path=str(grp),
110 **{'auth users': f',@[! []*:deny, {REALUSER}:rw'})),
111 ], name='auth-users-comma-only.conf')
112 url = start_test_daemon(conf, PORT)
113
114 os.environ['RSYNC_PASSWORD'] = 'wrong-environment-fallback'
115
116
117 def push(module, dest_dir, as_user=USER):
118 proc = subprocess.run(
119 rsync_argv('-r', f'--password-file={pwfile}', f'{src}/',
120 url.replace('rsync://', f'rsync://{as_user}@', 1) + module + '/'),
121 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
122 landed = dest_dir / 'f1'
123 return proc, landed
124
125
126 # Control first: if this fails, nothing below means anything.
127 proc, landed = push('plain', ctrl)
128 if proc.returncode != 0 or not landed.is_file() or landed.read_text() != DATA:
129 test_fail('positive control failed: the credential could not push to a '
130 f'module with a plain "auth users" (rc={proc.returncode}, '
131 f'output={proc.stdout.strip()[:300]!r})')
132
133 proc, landed = push('spaced', mod)
134 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:300]!r}'
135 if not landed.is_file():
136 test_fail('"auth users" starting with a comma was split on whitespace: the '
137 f'entry "@nosuchgroup {USER}:deny" names a group that does not '
138 f'exist and must not match, but its tail was read as a separate '
139 f'"{USER}:deny" rule and the transfer was refused ({ctx})')
140 if landed.read_text() != DATA:
141 test_fail(f'transfer was allowed but delivered the wrong content ({ctx})')
142 if proc.returncode != 0:
143 test_fail(f'transfer was allowed but failed ({ctx})')
144
145 # Group control: everything the group half depends on must work first.
146 proc, landed = push('grpctl', grpc, as_user=REALUSER)
147 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:300]!r}'
148 if proc.returncode != 0 or not landed.is_file():
149 test_fail(f'group positive control failed: "@*:rw" should admit {REALUSER} '
150 'via any of its groups. Either the daemon could not resolve that '
151 'name to a uid, could not enumerate its groups, rejected its '
152 f'secret, or could not store the file ({ctx})')
153
154 # The reported direction: the spaced group rule must actually DENY.
155 proc, landed = push('grpdeny', grp, as_user=REALUSER)
156 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:300]!r}'
157 if landed.is_file() or proc.returncode == 0:
158 test_fail('a group deny rule containing a space did not fire: '
159 f'"@[! []*:deny" must match a real group of {REALUSER} and '
160 'refuse the transfer, but the whitespace split turned it into '
161 f'"@[!" and "[]*:deny", neither of which matches, so the later '
162 f'"{REALUSER}:rw" granted access ({ctx})')
163 # ...and it must be refused BY THE DENY. A client is told only "auth failed"
164 # whatever the server decided: "denied by rule", "no matching rule" and
165 # "password mismatch" all reach it identically, so a parse yielding no rules at
166 # all would satisfy a check on the client output while the deny never matched
167 # anything. Only the daemon log names the reason.
168 logfile = SCRATCHDIR / 'rsyncd.log'
169 log = logfile.read_text(errors='replace') if logfile.is_file() else ''
170 if not [ln for ln in log.splitlines()
171 if 'auth failed on module grpdeny' in ln
172 and f'for {REALUSER}: denied by rule' in ln]:
173 test_fail('the transfer was refused, but not by the deny rule: the daemon '
174 f'log has no "auth failed on module grpdeny ... for {REALUSER}: '
175 'denied by rule". A refusal for any other reason -- above all '
176 '"no matching rule", which is what a parse yielding no rules at '
177 'all produces -- would make this case pass without the deny ever '
178 f'matching ({ctx}, log={log.strip()[-500:]!r})')
179
180 print('a leading comma in "auth users" splits on commas alone')