Debian Codegraph @

testsuite/daemon-exec-singlequote-injection_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """PoC: shell-escaped %RSYNC_USER_NAME% is unsafe inside single quotes.
3
4 expand_vars_shell_escape() produces a shell word of the form 'value'. That is
5 safe when substituted into an unquoted command, but a common hook such as
6
7 pre-xfer exec = printf '%RSYNC_USER_NAME%' >/dev/null
8
9 already supplies single quotes. The generated quotes cancel those quotes and
10 leave an authenticated client's username in shell syntax context.
11 """
12
13 import os
14 import subprocess
15 from pathlib import Path
16
17 from rsyncfns import (
18 FROMDIR, SCRATCHDIR, make_tree, makepath, rmtree, rsync_argv,
19 start_test_daemon, test_fail, write_daemon_conf,
20 )
21
22 PORT = 12939
23
24 src = FROMDIR
25 rmtree(src)
26 make_tree(src, depth=1)
27 dest = SCRATCHDIR / 'exec-singlequote-dest'
28 rmtree(dest)
29 makepath(dest)
30
31 # A slash would be interpreted as the URL's module separator before the client
32 # sends the username, so create the marker in the daemon's inherited cwd.
33 sentinel = Path.cwd() / 'exec-singlequote-pwned'
34 if sentinel.exists():
35 sentinel.unlink()
36
37 # No spaces or ':' are needed in the wire username. ${IFS} becomes a shell
38 # separator only after the broken quote composition exposes the value.
39 user = f';touch${{IFS}}{sentinel.name};true'
40 password = 'known-password'
41
42 secrets = SCRATCHDIR / 'exec-singlequote.secrets'
43 secrets.write_text(f'{user}:{password}\n')
44 secrets.chmod(0o600)
45 pwfile = SCRATCHDIR / 'exec-singlequote.password'
46 pwfile.write_text(password + '\n')
47 pwfile.chmod(0o600)
48
49 conf = write_daemon_conf([
50 ('hook', {
51 'path': str(dest),
52 'read only': 'no',
53 'use chroot': 'no',
54 'auth users': '*',
55 'secrets file': str(secrets),
56 'pre-xfer exec': "printf '%RSYNC_USER_NAME%' >/dev/null",
57 }),
58 ], name='exec-singlequote.conf')
59 url = start_test_daemon(conf, PORT)
60
61 os.environ['RSYNC_PASSWORD'] = 'wrong-environment-fallback'
62 user_url = url.replace('rsync://', f'rsync://{user}@', 1) + 'hook/'
63 proc = subprocess.run(
64 rsync_argv('-r', f'--password-file={pwfile}', f'{src}/', user_url),
65 stdout=subprocess.PIPE,
66 stderr=subprocess.PIPE,
67 text=True,
68 )
69
70 if sentinel.exists():
71 test_fail(
72 "authenticated metacharacter username executed through a "
73 f"single-quoted %RSYNC_USER_NAME% hook (rc={proc.returncode}):\n"
74 f"{proc.stderr}"
75 )
76 # The username carries shell syntax, so the daemon refuses it rather than
77 # trying to quote it; the transfer must fail closed.
78 if proc.returncode == 0:
79 test_fail(
80 "daemon accepted an authenticated username holding shell syntax "
81 f"(rc={proc.returncode}):\n{proc.stderr}"
82 )
83
84 print("single-quoted daemon hook refused a username holding shell syntax")