Debian Codegraph @

testsuite/daemon-proxy-protocol_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Exercise the daemon's HAProxy PROXY-protocol parser (clientname.c
3 # read_proxy_protocol_header), the trusted-peer gate
4 # (clientserver.c proxy_peer_allowed -> access.c allow_proxy_protocol_peer),
5 # and that the proxied source address is what hosts-allow checks against.
6 #
7 # Needs a real TCP socket: read_proxy_protocol_header() runs only when
8 # lp_proxy_protocol() is set, and it reads from the socket BEFORE the
9 # @RSYNCD greeting -- there is no pipe-transport equivalent.
10
11 import socket
12 import struct
13
14 from rsyncfns import (
15 SCRATCHDIR, claim_ports, makepath, require_tcp, start_rsyncd, test_fail,
16 write_daemon_conf,
17 )
18
19 PORT_OK = 19873 # proxy protocol hosts = 127.0.0.0/8 (we match)
20 PORT_NOHOSTS = 19874 # proxy protocol = yes but NO proxy protocol hosts
21
22 require_tcp("PROXY-protocol header is read from a real TCP socket; run with --use-tcp")
23 claim_ports(PORT_OK, PORT_NOHOSTS)
24
25 base = SCRATCHDIR / 'proxy-protocol'
26 makepath(base / 'mod')
27
28
29 # Daemon 1: trusted proxy at 127.0.0.0/8. Module only allows the *proxied*
30 # 10.0.0.0/8 (and an IPv6 ULA), so a successful module-list proves the daemon
31 # is checking the proxied addr, not the socket peer (127.0.0.1).
32 conf_ok = write_daemon_conf(
33 [('mod', {
34 'path': str(base / 'mod'),
35 'read only': 'yes',
36 'use chroot': 'no',
37 'hosts allow': '10.0.0.0/8, fd00::/8',
38 })],
39 globals={
40 'proxy protocol': 'yes',
41 'proxy protocol hosts': '127.0.0.0/8',
42 # The proxied addrs are not in DNS -- skip name lookup so the test
43 # does not block on a slow reverse-DNS timeout.
44 'reverse lookup': 'no',
45 # Override the write_daemon_conf default (localhost 127/8) -- with the
46 # proxy header in play we want hosts-allow to be per-module only.
47 'hosts allow': '',
48 },
49 name='proxyproto.conf',
50 )
51 start_rsyncd(conf_ok, PORT_OK)
52
53 # Daemon 2: proxy protocol = yes but NO `proxy protocol hosts` -> every peer
54 # is untrusted (allow_proxy_protocol_peer returns 0 on empty list), the
55 # connection is dropped before the header is even read.
56 conf_nohosts = write_daemon_conf(
57 [('mod', {'path': str(base / 'mod'), 'read only': 'yes', 'use chroot': 'no'})],
58 globals={
59 'proxy protocol': 'yes',
60 'reverse lookup': 'no',
61 'hosts allow': '',
62 # Second daemon in one test -> distinct pid/log so we don't collide
63 # with daemon 1's lock.
64 'pid file': str(SCRATCHDIR / 'rsyncd-nohosts.pid'),
65 'log file': str(SCRATCHDIR / 'rsyncd-nohosts.log'),
66 },
67 name='proxyproto-nohosts.conf',
68 )
69 start_rsyncd(conf_nohosts, PORT_NOHOSTS)
70
71
72 # --- PROXY header encoders (mirror clientname.c constants) ------------------
73
74 V2_SIG = b'\r\n\r\n\x00\r\nQUIT\n' # 12 bytes
75 CMD_LOCAL, CMD_PROXY = 0, 1
76 FAM_TCPv4, FAM_TCPv6 = 0x11, 0x21
77
78
79 def v1(line):
80 return (b'PROXY ' + line.encode('ascii') + b'\r\n')
81
82
83 def v2(cmd, fam, addr):
84 return (V2_SIG
85 + bytes([(2 << 4) | cmd, fam])
86 + struct.pack('>H', len(addr))
87 + addr)
88
89
90 def v2_ip4(src, dst='127.0.0.1', sport=40000, dport=PORT_OK):
91 a = (socket.inet_pton(socket.AF_INET, src)
92 + socket.inet_pton(socket.AF_INET, dst)
93 + struct.pack('>HH', sport, dport))
94 return v2(CMD_PROXY, FAM_TCPv4, a)
95
96
97 def v2_ip6(src, dst='::1', sport=40000, dport=PORT_OK):
98 a = (socket.inet_pton(socket.AF_INET6, src)
99 + socket.inet_pton(socket.AF_INET6, dst)
100 + struct.pack('>HH', sport, dport))
101 return v2(CMD_PROXY, FAM_TCPv6, a)
102
103
104 # --- driver: send proxy header then a minimal @RSYNCD module-list -----------
105
106 def probe(port, hdr, label, *, want):
107 """Connect, send `hdr`, then attempt an @RSYNCD module-list of [mod].
108
109 `want` is one of:
110 'ok' -- daemon answers @RSYNCD: OK (proxied IP passed hosts-allow)
111 'denied' -- daemon answers @ERROR: access denied (proxied IP rejected
112 by per-module hosts-allow)
113 'drop' -- daemon closes the socket without an @RSYNCD greeting
114 (proxy header rejected or untrusted peer)
115 """
116 s = socket.create_connection(('127.0.0.1', port), timeout=10)
117 s.settimeout(10)
118 out = b''
119 try:
120 if hdr:
121 s.sendall(hdr)
122 # @RSYNCD client greeting + module name + a single sender-side
123 # list-only request. Protocol 30, no capabilities, no auth.
124 s.sendall(b'@RSYNCD: 30.0\nmod\n')
125 # Slurp everything the daemon writes before it closes.
126 try:
127 s.shutdown(socket.SHUT_WR)
128 except OSError:
129 pass
130 while True:
131 try:
132 chunk = s.recv(4096)
133 except OSError:
134 break
135 if not chunk:
136 break
137 out += chunk
138 except OSError:
139 # A 'drop' daemon closes the connection, which can surface as
140 # EPIPE/ECONNRESET on our sendall() before we ever read -- a timing
141 # race seen on some CI runners. Leave `out` empty and let the
142 # want-check below decide: for want='drop' the absent greeting is the
143 # expected outcome; for want='ok'/'denied' it still fails correctly.
144 pass
145 finally:
146 s.close()
147
148 got_greeting = out.startswith(b'@RSYNCD:')
149 if want == 'drop':
150 if got_greeting:
151 test_fail(f"{label}: expected drop, got greeting: {out!r}")
152 return
153 if not got_greeting:
154 test_fail(f"{label}: expected @RSYNCD greeting, got: {out!r}")
155 if want == 'denied':
156 if b'@ERROR' not in out or b'access denied' not in out:
157 test_fail(f"{label}: expected access-denied, got: {out!r}")
158 return
159 if want == 'ok':
160 # After greeting + module name the daemon answers @RSYNCD: OK then
161 # waits for client args -- but we sent SHUT_WR so it sees EOF on the
162 # args read and closes. Seeing OK (not @ERROR) is the success signal.
163 if b'@ERROR' in out:
164 test_fail(f"{label}: expected OK, got error: {out!r}")
165 if b'@RSYNCD: OK' not in out:
166 test_fail(f"{label}: expected @RSYNCD: OK, got: {out!r}")
167 return
168 test_fail(f"{label}: bad want={want!r}")
169
170
171 # === V1 text header =========================================================
172
173 # Proxied src in 10.0.0.0/8 -> module hosts-allow matches.
174 probe(PORT_OK, v1('TCP4 10.1.2.3 127.0.0.1 40000 873'), 'v1 TCP4 allow', want='ok')
175
176 # Proxied src outside 10.0.0.0/8 -> module hosts-allow rejects (proves the
177 # daemon checked the *proxied* addr, not the socket peer 127.0.0.1).
178 probe(PORT_OK, v1('TCP4 192.168.1.1 127.0.0.1 40000 873'), 'v1 TCP4 deny', want='denied')
179
180 # IPv6 source in fd00::/8 -> matches the ULA hosts-allow entry.
181 probe(PORT_OK, v1('TCP6 fd00::1234 ::1 40000 873'), 'v1 TCP6 allow', want='ok')
182
183 # UNKNOWN -> parser returns 1 with ipaddr_buf unset, so the daemon falls back
184 # to the socket peer (127.0.0.1), which is NOT in 10.0.0.0/8 -> denied.
185 probe(PORT_OK, v1('UNKNOWN'), 'v1 UNKNOWN', want='denied')
186
187 # Malformed v1: missing dst -> parser returns 0 -> drop.
188 probe(PORT_OK, v1('TCP4 10.1.2.3'), 'v1 short', want='drop')
189
190 # Malformed v1: bad family token.
191 probe(PORT_OK, v1('TCP9 10.1.2.3 127.0.0.1 40000 873'), 'v1 bad-fam', want='drop')
192
193 # Malformed v1: non-numeric port.
194 probe(PORT_OK, v1('TCP4 10.1.2.3 127.0.0.1 abc 873'), 'v1 bad-port', want='drop')
195
196 # Malformed v1: line longer than the 108-byte buffer with no \n -> drop.
197 probe(PORT_OK, b'PROXY TCP4 ' + b'1' * 200, 'v1 overlong', want='drop')
198
199 # Neither v2 sig nor "PROXY" prefix -> drop.
200 probe(PORT_OK, b'GET / HTTP/1.0\r\n\r\n', 'no proxy hdr', want='drop')
201
202
203 # === V2 binary header =======================================================
204
205 probe(PORT_OK, v2_ip4('10.9.8.7'), 'v2 TCPv4 allow', want='ok')
206 probe(PORT_OK, v2_ip4('172.16.0.1'), 'v2 TCPv4 deny', want='denied')
207 probe(PORT_OK, v2_ip6('fd00::abcd'), 'v2 TCPv6 allow', want='ok')
208
209 # CMD_LOCAL: parser returns 1, ipaddr_buf unset -> socket peer 127.0.0.1
210 # checked against hosts-allow -> denied.
211 probe(PORT_OK, v2(CMD_LOCAL, 0, b''), 'v2 LOCAL', want='denied')
212
213 # Unsupported family with CMD_PROXY -> "ignore proxy data, accept" branch.
214 probe(PORT_OK, v2(CMD_PROXY, 0x31, b'\0' * 4), 'v2 unsupp-fam', want='denied')
215
216 # Bad version nibble -> drop.
217 probe(PORT_OK, V2_SIG + bytes([(3 << 4) | CMD_PROXY, FAM_TCPv4]) + b'\x00\x0c'
218 + b'\0' * 12, 'v2 bad-ver', want='drop')
219
220 # Declared size larger than the union -> drop.
221 probe(PORT_OK, V2_SIG + bytes([(2 << 4) | CMD_PROXY, FAM_TCPv4]) + b'\x10\x00'
222 + b'\0' * 12, 'v2 oversize', want='drop')
223
224 # TCPv4 with size != 12 -> drop.
225 probe(PORT_OK, v2(CMD_PROXY, FAM_TCPv4, b'\0' * 8), 'v2 ip4 bad-len', want='drop')
226
227 # Unknown cmd -> drop.
228 probe(PORT_OK, v2(7, FAM_TCPv4, b'\0' * 12), 'v2 bad-cmd', want='drop')
229
230
231 # === Untrusted-peer gate (no `proxy protocol hosts`) ========================
232
233 # allow_proxy_protocol_peer() returns 0 on an empty/NULL list; the daemon
234 # drops the connection BEFORE reading any proxy header.
235 probe(PORT_NOHOSTS, v2_ip4('10.1.2.3'), 'untrusted v2', want='drop')
236 probe(PORT_NOHOSTS, v1('TCP4 10.1.2.3 127.0.0.1 40000 873'), 'untrusted v1', want='drop')
237 probe(PORT_NOHOSTS, b'', 'untrusted empty', want='drop')
238
239 print("PASS daemon-proxy-protocol: 22 cases")