Debian Codegraph @

testsuite/proxy-host-crlf_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Regression test: with RSYNC_PROXY set, a daemon host containing CR/LF must be
3 # rejected before the HTTP CONNECT request is formatted, so an attacker can't
4 # smuggle extra header/request lines into the client->proxy stream.
5
6 import os
7 import socket
8 import subprocess
9
10 from rsyncfns import SCRATCHDIR, rmtree, rsync_argv, test_fail, test_skipped
11
12 base = SCRATCHDIR / 'proxy-crlf'
13 rmtree(base)
14 base.mkdir(parents=True)
15
16 # A throwaway proxy listener on an OS-assigned localhost port.
17 try:
18 lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
19 lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
20 lsock.bind(('127.0.0.1', 0))
21 lsock.listen(1)
22 except OSError as e:
23 test_skipped(f"cannot bind a localhost proxy listener: {e}")
24 proxy_port = lsock.getsockname()[1]
25
26 env = os.environ.copy()
27 env['RSYNC_PROXY'] = f'127.0.0.1:{proxy_port}'
28
29 # Daemon host with an embedded CRLF and an injected marker (no ':' so it is not
30 # mistaken for a host:port split). Pre-fix this lands verbatim in the
31 # "CONNECT <host>:873 HTTP/1.0" request line sent to the proxy.
32 marker = 'INJECTEDLINE'
33 host = f'evilhost\r\n{marker}'
34
35 proc = subprocess.Popen(
36 rsync_argv(f'rsync://{host}/mod/', str(base / 'out')),
37 stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
38
39 received = b''
40 try:
41 lsock.settimeout(10)
42 conn, _ = lsock.accept()
43 conn.settimeout(5)
44 try:
45 while True:
46 chunk = conn.recv(4096)
47 if not chunk:
48 break
49 received += chunk
50 if b'\r\n\r\n' in received or len(received) > 65536:
51 break
52 except socket.timeout:
53 pass
54 conn.close()
55 except socket.timeout:
56 # Fix path: rsync may reject before connecting at all.
57 pass
58 finally:
59 lsock.close()
60
61 out = proc.communicate(timeout=30)
62 out = (out[0] or '') + (out[1] or '')
63
64 if marker.encode() in received:
65 test_fail("CRLF-injected marker reached the proxy CONNECT stream:\n"
66 + repr(received))
67 if proc.returncode == 0:
68 test_fail("malicious proxy host unexpectedly produced a successful transfer")
69
70 print("proxy-host-crlf: control characters in the daemon host are rejected")