Skip to content

Commit 84c9292

Browse files
committed
access: compare forward-DNS hostname matches in binary form
Address review feedback on the getaddrinfo conversion: parse the peer address once and compare each resolved address against it byte-wise within the same family, as match_address() does, instead of comparing inet_ntop() strings; keep the IPv6 cases under #ifdef INET6 so a --disable-ipv6 build compiles the IPv4 path only. Add daemon-access-hostname regressions: hostname-token allow and deny over IPv4 and IPv6 (with reverse lookup off, so only the forward path can match), forward lookup disabled, and unresolvable allow/deny tokens.
1 parent 51091fc commit 84c9292

2 files changed

Lines changed: 242 additions & 20 deletions

File tree

‎access.c‎

Lines changed: 53 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ extern const char undetermined_hostname[];
3030

3131
static int match_hostname(const char **host_ptr, const char *addr, const char *tok, int deny)
3232
{
33-
struct addrinfo hints, *res, *res0;
33+
struct addrinfo hints, *res, *res0, *resa = NULL;
34+
const char *a = NULL;
35+
int addrlen = 0;
3436
const char *host = *host_ptr;
3537
#ifdef SUPPORT_IDN
3638
char idn_tok[1024];
@@ -76,30 +78,61 @@ static int match_hostname(const char **host_ptr, const char *addr, const char *t
7678
return deny;
7779
}
7880

79-
for (res = res0; res; res = res->ai_next) {
80-
char res_addr[128];
81-
const void *src_addr;
82-
83-
switch (res->ai_family) {
84-
case AF_INET:
85-
src_addr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
81+
/* Parse the peer address once so the resolved addresses below can be
82+
* compared against it in binary form by family, as match_address()
83+
* does, rather than by comparing formatted strings. */
84+
memset(&hints, 0, sizeof hints);
85+
hints.ai_family = PF_UNSPEC;
86+
hints.ai_socktype = SOCK_STREAM;
87+
#ifdef AI_NUMERICHOST
88+
hints.ai_flags = AI_NUMERICHOST;
89+
#endif
90+
if (getaddrinfo(addr, NULL, &hints, &resa) == 0) {
91+
switch (resa->ai_family) {
92+
case PF_INET:
93+
a = (char *)&((struct sockaddr_in *)resa->ai_addr)->sin_addr;
94+
addrlen = 4;
8695
break;
87-
case AF_INET6:
88-
src_addr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
96+
#ifdef INET6
97+
case PF_INET6:
98+
a = (char *)&((struct sockaddr_in6 *)resa->ai_addr)->sin6_addr;
99+
addrlen = 16;
89100
break;
101+
#endif
90102
default:
91-
continue;
103+
break;
92104
}
93-
if (!inet_ntop(res->ai_family, src_addr, res_addr, sizeof res_addr))
94-
continue;
95-
if (strcmp(addr, res_addr) == 0) {
96-
/* If reverse lookups are off, we'll use the conf-specified
97-
* hostname in preference to UNDETERMINED. */
98-
if (host == undetermined_hostname)
99-
*host_ptr = strdup(tok);
100-
freeaddrinfo(res0);
101-
return 1;
105+
}
106+
107+
if (a) {
108+
for (res = res0; res; res = res->ai_next) {
109+
const char *t = NULL;
110+
111+
if (res->ai_family != resa->ai_family)
112+
continue;
113+
switch (res->ai_family) {
114+
case PF_INET:
115+
t = (char *)&((struct sockaddr_in *)res->ai_addr)->sin_addr;
116+
break;
117+
#ifdef INET6
118+
case PF_INET6:
119+
t = (char *)&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
120+
break;
121+
#endif
122+
default:
123+
continue;
124+
}
125+
if (memcmp(a, t, addrlen) == 0) {
126+
/* If reverse lookups are off, we'll use the conf-specified
127+
* hostname in preference to UNDETERMINED. */
128+
if (host == undetermined_hostname)
129+
*host_ptr = strdup(tok);
130+
freeaddrinfo(resa);
131+
freeaddrinfo(res0);
132+
return 1;
133+
}
102134
}
135+
freeaddrinfo(resa);
103136
}
104137

105138
freeaddrinfo(res0);
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
#!/usr/bin/env python3
2+
"""Daemon coverage: hosts allow / hosts deny hostname tokens matched by
3+
forward DNS (access.c match_hostname).
4+
5+
"reverse lookup" is off in every config below, so the daemon has no
6+
reverse-DNS name for the peer ("UNDETERMINED") and the reverse-name match
7+
in match_hostname() can never fire: only the forward-lookup path -- resolve
8+
the config's hostname token and compare the result against the peer's
9+
numeric address -- can match. The token is "localhost", which resolves to
10+
the loopback address in both families, so the same token exercises the
11+
IPv4 path against a 127.0.0.1 peer and the IPv6 path against a ::1 peer.
12+
13+
Also covered: "forward lookup = no" must disable the forward match, and a
14+
token that fails to resolve must fail CLOSED in a deny list (the peer is
15+
denied) while simply not matching in an allow list.
16+
17+
Like daemon-access-ip_test.py this needs a real TCP peer (--use-tcp), and
18+
the configs set no global hosts allow so each module's own patterns are
19+
the sole decider. The IPv6 daemon is spawned directly (the shared
20+
start_test_daemon helper binds 127.0.0.1 only) and its section is skipped
21+
with a note when this host or build has no IPv6 loopback.
22+
"""
23+
24+
import atexit
25+
import socket
26+
import subprocess
27+
import time
28+
29+
from rsyncfns import (
30+
FROMDIR, RSYNC_PEER, SCRATCHDIR,
31+
claim_ports, make_tree, require_tcp, rmtree, rsync_argv,
32+
split_rsync_cmd, start_test_daemon, test_fail,
33+
)
34+
35+
DAEMON_PORT = 12914
36+
V6_PORT = 12917
37+
UNRESOLVABLE = 'rsync-test-nonexistent.invalid'
38+
39+
require_tcp("hosts allow/deny forward-DNS matching needs a real TCP peer")
40+
41+
src = FROMDIR
42+
rmtree(src)
43+
make_tree(src, depth=2)
44+
45+
46+
def resolves_to(name, family, addr):
47+
"""True if `name` forward-resolves to the binary address `addr`."""
48+
try:
49+
infos = socket.getaddrinfo(name, None, family, socket.SOCK_STREAM)
50+
except socket.gaierror:
51+
return False
52+
return any(info[4][0] == addr for info in infos)
53+
54+
55+
def write_conf(path, modules, log, pidfile):
56+
lines = [
57+
'# autogenerated by daemon-access-hostname_test.py',
58+
f'pid file = {pidfile}',
59+
'use chroot = no',
60+
# No reverse-DNS name for the peer: only forward matching can fire.
61+
'reverse lookup = no',
62+
f'log file = {log}',
63+
'',
64+
]
65+
for mod, params in modules:
66+
lines.append(f'[{mod}]')
67+
lines.append(f'\tpath = {src}')
68+
lines.append('\tread only = yes')
69+
lines += [f'\t{k} = {v}' for k, v in params.items()]
70+
lines.append('')
71+
path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
72+
return path
73+
74+
75+
def connect(url, mod):
76+
"""Return rsync's exit code for listing the module over the daemon."""
77+
return subprocess.run(rsync_argv('-r', f'{url}{mod}/'),
78+
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
79+
text=True).returncode
80+
81+
82+
def allowed(url, mod, why):
83+
if connect(url, mod) != 0:
84+
test_fail(f"connection to {mod} should be ALLOWED ({why}) but was refused")
85+
86+
87+
def denied(url, mod, why):
88+
if connect(url, mod) == 0:
89+
test_fail(f"connection to {mod} should be DENIED ({why}) but succeeded")
90+
91+
92+
# --- IPv4 peer (127.0.0.1) -------------------------------------------------
93+
94+
if not resolves_to('localhost', socket.AF_INET, '127.0.0.1'):
95+
test_fail("this host does not resolve 'localhost' to 127.0.0.1; "
96+
"the forward-DNS cases cannot be constructed")
97+
98+
modules = [
99+
('plain', {}),
100+
('fwd-allow4', {'hosts allow': 'localhost'}),
101+
('fwd-deny4', {'hosts deny': 'localhost'}),
102+
('fwd-off', {'hosts allow': 'localhost', 'forward lookup': 'no'}),
103+
]
104+
# The unresolvable-token cases are only meaningful if the name really does
105+
# not resolve here (a wildcard resolver would defeat them).
106+
try:
107+
socket.getaddrinfo(UNRESOLVABLE, None, socket.AF_UNSPEC,
108+
socket.SOCK_STREAM)
109+
print(f"note: {UNRESOLVABLE} unexpectedly resolves here; "
110+
"unresolvable-token cases skipped")
111+
except socket.gaierror:
112+
modules += [
113+
('deny-unresolvable', {'hosts deny': UNRESOLVABLE}),
114+
('allow-unresolvable', {'hosts allow': UNRESOLVABLE}),
115+
]
116+
117+
conf = write_conf(SCRATCHDIR / 'access-hostname.conf', modules,
118+
SCRATCHDIR / 'rsyncd.log', SCRATCHDIR / 'rsyncd.pid')
119+
url = start_test_daemon(conf, DAEMON_PORT)
120+
121+
allowed(url, 'plain', "no hosts patterns on the module")
122+
allowed(url, 'fwd-allow4', "localhost forward-resolves to the 127.0.0.1 peer")
123+
denied(url, 'fwd-deny4', "localhost forward-resolves to the 127.0.0.1 peer")
124+
denied(url, 'fwd-off', "forward lookup is disabled for the module")
125+
if any(mod == 'deny-unresolvable' for mod, _ in modules):
126+
denied(url, 'deny-unresolvable',
127+
"an unresolvable deny token fails closed")
128+
denied(url, 'allow-unresolvable',
129+
"an unresolvable allow token does not match")
130+
131+
# --- IPv6 peer (::1) --------------------------------------------------------
132+
133+
v6_ok = resolves_to('localhost', socket.AF_INET6, '::1')
134+
if v6_ok:
135+
try:
136+
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
137+
s.bind(('::1', 0))
138+
except OSError:
139+
v6_ok = False
140+
141+
if not v6_ok:
142+
print("note: no IPv6 loopback for 'localhost' here; IPv6 cases skipped")
143+
else:
144+
modules6 = [
145+
('plain6', {}),
146+
('fwd-allow6', {'hosts allow': 'localhost'}),
147+
('fwd-deny6', {'hosts deny': 'localhost'}),
148+
]
149+
conf6 = write_conf(SCRATCHDIR / 'access-hostname6.conf', modules6,
150+
SCRATCHDIR / 'rsyncd6.log', SCRATCHDIR / 'rsyncd6.pid')
151+
claim_ports(V6_PORT)
152+
# start_test_daemon binds 127.0.0.1 only, so spawn the IPv6 daemon
153+
# directly, with the same flags start_rsyncd uses apart from --address.
154+
proc = subprocess.Popen(
155+
split_rsync_cmd(RSYNC_PEER) + [
156+
'--daemon', '--no-detach', '--address=::1',
157+
f'--port={V6_PORT}', f'--config={conf6}',
158+
],
159+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
160+
stderr=subprocess.DEVNULL)
161+
atexit.register(proc.terminate)
162+
deadline = time.monotonic() + 10
163+
up = False
164+
while time.monotonic() < deadline:
165+
if proc.poll() is not None:
166+
break
167+
try:
168+
with socket.create_connection(('::1', V6_PORT), timeout=0.5):
169+
up = True
170+
break
171+
except OSError:
172+
time.sleep(0.05)
173+
if not up:
174+
proc.terminate()
175+
print("note: rsyncd did not listen on ::1 (built without INET6?); "
176+
"IPv6 cases skipped")
177+
else:
178+
try:
179+
url6 = f'rsync://[::1]:{V6_PORT}/'
180+
allowed(url6, 'plain6', "no hosts patterns on the module")
181+
allowed(url6, 'fwd-allow6',
182+
"localhost forward-resolves to the ::1 peer")
183+
denied(url6, 'fwd-deny6',
184+
"localhost forward-resolves to the ::1 peer")
185+
finally:
186+
proc.terminate()
187+
proc.wait(timeout=5)
188+
189+
print("daemon-access-hostname: forward-DNS hosts allow/deny matching verified")

0 commit comments

Comments
 (0)