From b19fa031a8bab8c4afacb40f7dbf090f82bbf3ab Mon Sep 17 00:00:00 2001
From: Vladimir Dubrovin <3proxy@3proxy.ru>
Date: Fri, 27 Nov 2026 16:42:39 +0300
Subject: [PATCH] dnspr: access rules match the name asked about, parent extip
binds the query socket
---
doc/changelog/2/0/0 | 1 +
doc/html/man5/3proxy.cfg.5.html | 13 ++-
src/dnspr.c | 17 +++-
src/redirect.c | 9 +-
tests/cases/dnspr_rules.py | 161 ++++++++++++++++++++++++++++++++
5 files changed, 195 insertions(+), 6 deletions(-)
create mode 100644 tests/cases/dnspr_rules.py
diff --git a/doc/changelog/2/0/0 b/doc/changelog/2/0/0
index a975c21..0c96a65 100644
--- a/doc/changelog/2/0/0
+++ b/doc/changelog/2/0/0
@@ -1,3 +1,4 @@
! Fix: a TLS connection was closed when a read needed to write or a write needed to read, as when TLS 1.3 answers a key update while the socket cannot take more data
! Fix: FilePlugin could crash on a TLS connection
- Plugins have to be built with the same version of 3proxy they are loaded by: the structures shared with them are not kept compatible. The socket functions a plugin may replace no longer wait: _poll is replaced by _prepoll, which only tells what the plugin knows to be ready or how the socket is to be waited for, the wait itself being done by 3proxy
++ dnspr: an access rule's targetlist is matched against the name asked about, as for the other services; parent extip is the address a query to a name server leaves from, and extport limits the port of those queries to a range, while a parent of another kind, having nowhere to connect a query to, is passed over
diff --git a/doc/html/man5/3proxy.cfg.5.html b/doc/html/man5/3proxy.cfg.5.html
index f7a7dee..aa623e9 100644
--- a/doc/html/man5/3proxy.cfg.5.html
+++ b/doc/html/man5/3proxy.cfg.5.html
@@ -815,7 +815,12 @@ beginning and at the end of the hostname, e.g. *badsite.com
or *badcontent*. The hostname is only checked if a hostname
is present in the request. Targetportlist may contain ports
(X) or port ranges lists (X-Y). For any field * sign means
-ANY. If access list is empty it´s assumed to be
+ANY. A query to dnspr carries a hostname but no
+destination address and no port: its rules are matched
+against the name asked about, and a rule naming a target
+port never matches a query, since the port of a name server
+is not what the client chose. If access list is empty
+it´s assumed to be
allow *
If access list is not empty last item in access list is
assumed to be
@@ -933,7 +938,11 @@ extip does not actually redirect the request; it sets
the external address for this request to <ip>.
It can be chained with another parent type. It’s
useful to set the external IP based on ACL or make it
-random.
+random. For dnspr, the address given is the one its
+queries to the name servers leave from, and extport
+limits the port of those queries to a range; a parent of
+another kind, having nowhere to connect a query to, is
+passed over and the resolver goes on without it.
extport does not redirect the request; it sets the range
the local port of outgoing connections is taken from, given
as FIRST-LAST inclusive in place of the port
diff --git a/src/dnspr.c b/src/dnspr.c
index da93118..4a6bc89 100644
--- a/src/dnspr.c
+++ b/src/dnspr.c
@@ -171,8 +171,13 @@ static int dnsforward(struct udploop *u, struct udpsession *ss){
#else
fcntl(param->remsock, F_SETFL, O_NONBLOCK | fcntl(param->remsock, F_GETFL));
#endif
- memset(¶m->sinsl, 0, sizeof(param->sinsl));
- *SAFAMILY(¶m->sinsl) = *SAFAMILY(&ns[q->server].addr);
+ /* the local address of the socket, as a parent's extip set it;
+ the port is the kernel's to choose */
+ if(SAISNULL(¶m->sinsl) || *SAFAMILY(¶m->sinsl) != *SAFAMILY(&ns[q->server].addr)){
+ memset(¶m->sinsl, 0, sizeof(param->sinsl));
+ *SAFAMILY(¶m->sinsl) = *SAFAMILY(&ns[q->server].addr);
+ }
+ *SAPORT(¶m->sinsl) = 0;
if(bindwithrange(param, param->remsock, ¶m->sinsl, param->extport)) continue;
param->sinsr = ns[q->server].addr;
ss->idle = 0;
@@ -223,8 +228,9 @@ static int dnsprfirst(struct udploop *u, struct udpsession *ss, unsigned char *q
buf[BUFSIZE - 1] = 0;
param->sincl = param->srv->intsa;
param->operation = DNSRESOLVE;
- if((res = (*param->srv->authfunc)(param))) { free(buf); return (param->res = res); }
+ /* the question is read before the rules run, so that a rule can be
+ written against the name asked about */
if(buf[4]!=0 || buf[5]!=1) { free(buf); return (param->res = 816); }
for(len = 12; len (i-4)) { free(buf); return (param->res = 817); }
if(!(q->host = strdup((char *)buf+13))) { free(buf); return (param->res = 21); }
+ /* the name of the query, for the rules; one too long for the field
+ leaves them none to match */
+ if(PARAMSTR(param, hostname, q->host)) *param->hostname = 0;
for(s2 = buf + 12; (s1 = (unsigned char *)strchr((char *)s2 + 1, '.')); s2 = s1)*s2 = (unsigned char)((s1 - s2) - 1);
*s2 = (len - (int)(s2 - buf)) - 1;
@@ -246,6 +255,8 @@ static int dnsprfirst(struct udploop *u, struct udpsession *ss, unsigned char *q
q->cid[0] = q->query[2];
q->cid[1] = q->query[3];
q->ttl = 3600;
+ if((res = (*param->srv->authfunc)(param))) { free(buf); return (param->res = res); }
+
if(q->type==0x01 && param->srv->fakeip){
ip = 1;
*(uint32_t *)q->addr = param->srv->fakeip;
diff --git a/src/redirect.c b/src/redirect.c
index 9e04eb3..589dffc 100644
--- a/src/redirect.c
+++ b/src/redirect.c
@@ -362,7 +362,10 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
struct chain * redir = NULL;
int saved = 0;
- if((SAISNULL(¶m->req) || !*SAPORT(¶m->req)) && param->operation != UDPASSOC) {
+ /* a query has no destination an ACL entry carries: what binds its
+ outgoing socket is all a chain can set for it */
+ if((SAISNULL(¶m->req) || !*SAPORT(¶m->req)) &&
+ param->operation != UDPASSOC && param->operation != DNSRESOLVE) {
return 100;
}
@@ -376,6 +379,10 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
if(exhausted) return 13;
if(!sel) continue;
cur = sel;
+ /* nothing to connect for a name server's query: a parent of
+ another kind is passed over rather than made to fail it */
+ if(param->operation == DNSRESOLVE && cur->type != R_EXTIP &&
+ cur->type != R_EXTPORT && cur->type != R_INTPORT) continue;
if(cur->type != R_EXTIP && cur->type != R_HA &&
cur->type != R_EXTPORT && cur->type != R_INTPORT) param->redirected++;
if(!connected){
diff --git a/tests/cases/dnspr_rules.py b/tests/cases/dnspr_rules.py
new file mode 100644
index 0000000..f871779
--- /dev/null
+++ b/tests/cases/dnspr_rules.py
@@ -0,0 +1,161 @@
+"""dnspr: rules by the name asked about, and a parent's extip for the socket
+a query leaves from.
+
+Access rules accumulate until "flush": each service here stands alone.
+"""
+
+import socket
+import struct
+import threading
+import time
+
+
+class NameServer:
+ """Answers an A record for every name, and remembers the address each
+ query came from."""
+
+ def __init__(self):
+ self.sources = []
+ self.lock = threading.Lock()
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.bind(("127.0.0.1", 0))
+ self.port = self.sock.getsockname()[1]
+ self.thread = threading.Thread(target=self.serve, daemon=True)
+
+ def serve(self):
+ while True:
+ try:
+ data, addr = self.sock.recvfrom(65536)
+ except OSError:
+ return
+ with self.lock:
+ self.sources.append(addr[0])
+ if len(data) >= 12:
+ self.sock.sendto(self.reply(data), addr)
+
+ def reply(self, query):
+ return (query[:2] + struct.pack("!HHHHH", 0x8180, 1, 1, 0, 0)
+ + query[12:]
+ + b"\xc0\x0c" + struct.pack("!HHIH", 1, 1, 60, 4)
+ + socket.inet_aton("127.0.0.1"))
+
+ def start(self):
+ self.thread.start()
+ return self
+
+
+def wait_service(t, port, name):
+ """Bound by the clock, not by a number of attempts: a server that
+ answers nothing costs seconds rather than minutes."""
+ deadline = time.time() + 5
+ while time.time() < deadline:
+ if t.dns_query(port, name) is not None:
+ return
+ t.fail("the dnspr service never answered",
+ f"no answer from port {port} within 5 seconds")
+
+
+def bindable_extip():
+ """An address a socket can be bound to whose source differs from what
+ the kernel would pick on its own.
+
+ Toward a name server on the loopback the kernel picks 127.0.0.1, so
+ 127.0.0.2 tells the difference; the whole 127/8 is bindable on Linux
+ and Windows, but on macOS only the addresses assigned to lo0 are, and
+ that one alone. The address of a real interface does there: bound
+ explicitly, it is the source even towards the loopback.
+ """
+ for candidate in ("127.0.0.2", "route"):
+ if candidate == "route":
+ # no datagram leaves: a connected UDP socket only learns the
+ # route's own end of it
+ probe = None
+ try:
+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ probe.connect(("192.0.2.1", 9))
+ candidate = probe.getsockname()[0]
+ except OSError:
+ return None
+ finally:
+ if probe is not None:
+ probe.close()
+ if candidate == "127.0.0.1":
+ continue
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ sock.bind((candidate, 0))
+ return candidate
+ except OSError:
+ continue
+ finally:
+ sock.close()
+ return None
+
+
+def run(t):
+ # --- the targetlist is the name asked about ---------------------------
+ port = t.free_port()
+ t.start("dnspr_names", f"""
+ log
+ flush
+ nserver 127.0.0.1
+ nscache 1024
+ nsrecord here.test 10.11.12.13
+ auth iponly
+ allow * 127.0.0.1 here.test
+ deny *
+ dnspr -p{port}
+ """)
+
+ wait_service(t, port, "here.test")
+ t.eq(["10.11.12.13"], t.dns_query(port, "here.test"),
+ "a name a rule allows is answered")
+
+ # nothing answers a name no rule allows: not the address of another
+ # name, not an error, the query is dropped
+ t.eq(None, t.dns_query(port, "there.test"),
+ "a name no rule allows is not answered at all")
+
+ # --- a parent's extip is the address a query leaves from ---------------
+ extip = bindable_extip()
+ if not extip:
+ t.skip("no address on this machine can be bound as an extip")
+ return
+
+ ns = NameServer().start()
+ qport = t.free_port()
+ t.start("dnspr_extip", f"""
+ log
+ flush
+ nserver 127.0.0.1:{ns.port}
+ auth iponly
+ allow *
+ parent 1000 extip {extip} 0
+ dnspr -p{qport}
+ """)
+
+ wait_service(t, qport, "from.test")
+ t.eq(["127.0.0.1"], t.dns_query(qport, "from.test"),
+ "a query through extip is answered")
+
+ with ns.lock:
+ sources = list(ns.sources)
+ t.ne([], sources, "the name server was asked")
+ t.eq([], [s for s in sources if s != extip],
+ "every query left from the extip address")
+
+ # a parent of a kind with nowhere to connect a query is passed over,
+ # and the resolver goes on without it
+ oport = t.free_port()
+ t.start("dnspr_otherparent", f"""
+ log
+ flush
+ nserver 127.0.0.1:{ns.port}
+ auth iponly
+ allow *
+ parent 1000 socks5 192.0.2.1 1080
+ dnspr -p{oport}
+ """)
+ wait_service(t, oport, "any.test")
+ t.eq(["127.0.0.1"], t.dns_query(oport, "any.test"),
+ "a parent of another kind does not stop the resolver")