From 6aee2a45f870c1ba3df829decde359ff01f01922 Mon Sep 17 00:00:00 2001 From: pedro Date: Wed, 2 Dec 2026 22:32:55 +0000 Subject: [PATCH] Fix UDP upstream socket bind before connect Connecting an unbound UDP socket implicitly assigns a local address and port. A subsequent bind() fails with EINVAL when min-port, max-port or an explicit source address requires local_bind() to bind the socket. Bind the local socket and set the outgoing interface before connecting to the upstream server. Preserve the existing error reporting. Fixes: cc32bce779f2 ("connect() UDP sockets to upstream DNS servers to mitigate SAD DNS attack.") --- src/forward.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/forward.c b/src/forward.c index 7bae488..4133c1e 100644 --- a/src/forward.c +++ b/src/forward.c @@ -2847,10 +2847,13 @@ static int random_sock(struct server *s) } } - if (connect(fd, &s->addr.sa, sa_len(&s->addr)) == -1) - connecterr = 1; - else if (local_bind(fd, &s->source_addr, s->interface, s->ifindex, 0)) - return fd; + if (local_bind(fd, &s->source_addr, s->interface, s->ifindex, 0)) + { + if (connect(fd, &s->addr.sa, sa_len(&s->addr)) == -1) + connecterr = 1; + else + return fd; + } /* don't log errors due to running out of available ports, we handle those. */ if (connecterr || !sockaddr_isnull(&s->source_addr) || errno != EADDRINUSE)