]> git.ipfire.org Git - thirdparty/bind9.git/commitdiff
Switch UDP fetches to TCP on the first response with a wrong query id 12026/head
authorOndřej Surý <ondrej@isc.org>
Thu, 14 May 2026 10:20:19 +0000 (12:20 +0200)
committerOndřej Surý <ondrej@sury.org>
Fri, 15 May 2026 06:06:34 +0000 (08:06 +0200)
Until now, the dispatcher silently dropped UDP responses from the
expected peer that carried the wrong DNS message id and kept listening
for the correct id to arrive within the read timeout.  An off-path
attacker who knows the destination address and source port of an
outgoing fetch could exploit that quiet retry window to flood the
resolver with guessed responses; with a gigabit link the per-query
success probability grows linearly with the number of guesses that
arrive before the legitimate answer or the timeout.

Treat any such mismatch as a possible spoofing attempt and let the
resolver immediately retry the same query over TCP, the same control
path the truncation handler already uses.

Add a resolver statistics counter - exposed as 'queries retried over TCP
after a response with mismatched query id' in rndc stats and
'MismatchTCP' in the statistics channel

Assisted-by: Claude:claude-opus-4-7
(cherry picked from commit 11bca1051f6ef6658b3602c8d72a2f35abdbdd93)

bin/named/statschannel.c
bin/tests/system/mismatchtcp/ans2/ans.py [new file with mode: 0644]
bin/tests/system/mismatchtcp/ans2/example.db [new file with mode: 0644]
bin/tests/system/mismatchtcp/ns1/named.conf.j2 [new file with mode: 0644]
bin/tests/system/mismatchtcp/ns1/root.db [new file with mode: 0644]
bin/tests/system/mismatchtcp/tests_mismatchtcp.py [new file with mode: 0644]
lib/dns/dispatch.c
lib/dns/include/dns/stats.h
lib/dns/resolver.c
lib/isc/include/isc/result.h
lib/isc/result.c

index b2ef60ed3e7b5e8b3823fa88502de27410cc9ea0..8828c685869bd2474a5038fcfb49594d1486a1d3 100644 (file)
@@ -437,6 +437,10 @@ init_desc(void) {
                        "ClientQuota");
        SET_RESSTATDESC(nextitem, "waited for next item", "NextItem");
        SET_RESSTATDESC(priming, "priming queries", "Priming");
+       SET_RESSTATDESC(mismatchtcp,
+                       "queries retried over TCP after a response with "
+                       "mismatched query id",
+                       "MismatchTCP");
 
        INSIST(i == dns_resstatscounter_max);
 
diff --git a/bin/tests/system/mismatchtcp/ans2/ans.py b/bin/tests/system/mismatchtcp/ans2/ans.py
new file mode 100644 (file)
index 0000000..365a6f2
--- /dev/null
@@ -0,0 +1,66 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0.  If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+"""
+Authoritative server that simulates Kaminsky-style off-path spoofing on UDP:
+for every UDP query for trigger.example./A it sends one response with a
+deliberately flipped DNS message id.  A resolver that escalates to TCP on
+the first id mismatch will still get the correct answer over TCP, which
+this server serves normally.
+"""
+
+from collections.abc import AsyncGenerator
+
+import dns.name
+import dns.rdatatype
+
+from isctest.asyncserver import (
+    AsyncDnsServer,
+    DnsProtocol,
+    DnsResponseSend,
+    QueryContext,
+    ResponseAction,
+    ResponseHandler,
+)
+
+
+class MismatchOnUdpHandler(ResponseHandler):
+    """
+    Spoof UDP queries for trigger.example./A with a properly-formed
+    response whose DNS message id does not match the request.  Answer
+    the same query normally on TCP using the zone data prepared by the
+    framework.
+    """
+
+    def __init__(self) -> None:
+        self._trigger = dns.name.from_text("trigger.example.")
+
+    def match(self, qctx: QueryContext) -> bool:
+        return qctx.qname == self._trigger and qctx.qtype == dns.rdatatype.A
+
+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[ResponseAction, None]:
+        if qctx.protocol == DnsProtocol.UDP:
+            qctx.response.id = qctx.query.id ^ 0xFFFF
+            yield DnsResponseSend(qctx.response)
+        else:
+            yield DnsResponseSend(qctx.response)
+
+
+def main() -> None:
+    server = AsyncDnsServer()
+    server.install_response_handler(MismatchOnUdpHandler())
+    server.run()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/bin/tests/system/mismatchtcp/ans2/example.db b/bin/tests/system/mismatchtcp/ans2/example.db
new file mode 100644 (file)
index 0000000..47d0234
--- /dev/null
@@ -0,0 +1,16 @@
+; Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+;
+; SPDX-License-Identifier: MPL-2.0
+;
+; This Source Code Form is subject to the terms of the Mozilla Public
+; License, v. 2.0.  If a copy of the MPL was not distributed with this
+; file, you can obtain one at https://mozilla.org/MPL/2.0/.
+;
+; See the COPYRIGHT file distributed with this work for additional
+; information regarding copyright ownership.
+
+$TTL 300
+example.       SOA     ns.example. . 0 0 0 0 0
+example.       NS      ns.example.
+ns.example.    A       10.53.0.2
+trigger.example.       A       192.0.2.42
diff --git a/bin/tests/system/mismatchtcp/ns1/named.conf.j2 b/bin/tests/system/mismatchtcp/ns1/named.conf.j2
new file mode 100644 (file)
index 0000000..f83cb2c
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0.  If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+include "../../_common/rndc.key";
+
+controls {
+       inet 10.53.0.1 port @CONTROLPORT@ allow { any; } keys { rndc_key; };
+};
+
+options {
+       port @PORT@;
+       pid-file "named.pid";
+       listen-on { 10.53.0.1; };
+       listen-on-v6 { none; };
+       query-source address 10.53.0.1;
+       recursion yes;
+       dnssec-validation no;
+};
+
+zone "." {
+       type primary;
+       file "root.db";
+};
diff --git a/bin/tests/system/mismatchtcp/ns1/root.db b/bin/tests/system/mismatchtcp/ns1/root.db
new file mode 100644 (file)
index 0000000..7ebebea
--- /dev/null
@@ -0,0 +1,17 @@
+; Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+;
+; SPDX-License-Identifier: MPL-2.0
+;
+; This Source Code Form is subject to the terms of the Mozilla Public
+; License, v. 2.0.  If a copy of the MPL was not distributed with this
+; file, you can obtain one at https://mozilla.org/MPL/2.0/.
+;
+; See the COPYRIGHT file distributed with this work for additional
+; information regarding copyright ownership.
+
+$TTL 300
+.              SOA     . . 0 0 0 0 0
+.              NS      ns.nil.
+ns.nil.                A       10.53.0.1
+example.       NS      ns.example.
+ns.example.    A       10.53.0.2
diff --git a/bin/tests/system/mismatchtcp/tests_mismatchtcp.py b/bin/tests/system/mismatchtcp/tests_mismatchtcp.py
new file mode 100644 (file)
index 0000000..25fa0fa
--- /dev/null
@@ -0,0 +1,88 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0.  If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+"""
+End-to-end check for the immediate UDP-to-TCP fallback on a query-id
+mismatch.
+
+The fake authoritative server at 10.53.0.2 answers every UDP query for
+trigger.example./A with a response whose DNS message id has been flipped.
+The resolver at 10.53.0.1 must escalate to TCP on the first such response
+and return the correct A record that the fake server serves over TCP.
+"""
+
+from pathlib import Path
+
+import dns.message
+import dns.rdatatype
+import pytest
+
+import isctest
+
+pytestmark = pytest.mark.extra_artifacts(
+    [
+        "ans*/ans.run",
+        "ns*/named.stats*",
+    ]
+)
+
+
+MISMATCH_LABEL = "mismatch responses received"
+MISMATCHTCP_LABEL = "queries retried over TCP after a response with mismatched query id"
+
+
+def _named_stats(ns1) -> str:
+    stats_path = Path("ns1") / "named.stats"
+    if stats_path.exists():
+        stats_path.unlink()
+    ns1.rndc("stats")
+    return stats_path.read_text(encoding="utf-8")
+
+
+def _counter(stats: str, label: str) -> int:
+    for line in stats.splitlines():
+        line = line.strip()
+        if line.endswith(label):
+            return int(line.split()[0])
+    return 0
+
+
+def test_mismatch_tcp_fallback(ns1):
+    """
+    Issue a single recursive query for a name whose UDP responses are
+    being spoofed.  The resolver must escalate to TCP on the first
+    near-miss and return the correct A record.
+    """
+    msg = dns.message.make_query("trigger.example.", dns.rdatatype.A, want_dnssec=False)
+    res = isctest.query.udp(msg, ns1.ip, timeout=10)
+    isctest.check.noerror(res)
+
+    answers = [rrset for rrset in res.answer if rrset.rdtype == dns.rdatatype.A]
+    assert answers, f"no A RRset in response: {res}"
+    addresses = {item.address for rrset in answers for item in rrset}
+    assert "192.0.2.42" in addresses, f"unexpected answer: {addresses}"
+
+
+def test_mismatch_counter(ns1):
+    """
+    After the spoofed exchange completes the resolver's existing
+    "mismatch responses received" counter must be non-zero, confirming
+    the dispatcher actually saw the wrong-id response, and the new
+    "queries retried over TCP after a response with mismatched query
+    id" counter must also be non-zero, confirming that the TCP
+    fallback path actually fired in response to that mismatch.
+    """
+    msg = dns.message.make_query("trigger.example.", dns.rdatatype.A, want_dnssec=False)
+    isctest.query.udp(msg, ns1.ip, timeout=10)
+
+    stats = _named_stats(ns1)
+    assert _counter(stats, MISMATCH_LABEL) > 0, stats
+    assert _counter(stats, MISMATCHTCP_LABEL) > 0, stats
index bd53763755f0a5a27868e94174053654ccc9965e..672cc1567575ae2dad580e8cd0d0bbb1a256f9da 100644 (file)
@@ -592,12 +592,17 @@ udp_recv(isc_nmhandle_t *handle, isc_result_t eresult, isc_region_t *region,
        }
 
        /*
-        * The QID and the address must match the expected ones.
+        * The QID and the address must match the expected ones.  A
+        * mismatch can happen during normal operation only when a stale
+        * response from a previous query arrives late, which is rare in
+        * practice; treat any mismatch as a possible spoofing attempt and
+        * let the caller retry over TCP to prevent off-path spoofing.
         */
        if (resp->id != id || !isc_sockaddr_equal(&peer, &resp->peer)) {
                dispentry_log(resp, LVL(90), "response doesn't match");
                inc_stats(disp->mgr, dns_resstatscounter_mismatch);
-               goto next;
+               eresult = DNS_R_MISMATCH;
+               goto done;
        }
 
        /*
index 3ea39560f09e69be198c6bc0c8d74ca065b13413..23ab31f51c1dc910548041148e94eca74daae57b 100644 (file)
@@ -72,7 +72,8 @@ enum {
        dns_resstatscounter_clientquota = 43,
        dns_resstatscounter_nextitem = 44,
        dns_resstatscounter_priming = 45,
-       dns_resstatscounter_max = 46,
+       dns_resstatscounter_mismatchtcp = 46,
+       dns_resstatscounter_max = 47,
 
        /*
         * DNSSEC stats.
index 2fa71eb31158cfa2b1d75fc11bfb35a63ca81fd0..47ffaab807a93b603b92400b60360a8853394095 100644 (file)
@@ -8485,6 +8485,22 @@ rctx_dispfail(respctx_t *rctx) {
                rctx->finish = NULL;
                rctx->no_response = true;
                break;
+       case DNS_R_MISMATCH:
+               /*
+                * The dispatcher saw a UDP response from the expected peer with
+                * the wrong DNS message id.  Retry the same query over TCP.
+                */
+               if ((rctx->retryopts & DNS_FETCHOPT_TCP) == 0) {
+                       rctx->retryopts |= DNS_FETCHOPT_TCP;
+                       rctx->resend = true;
+                       rctx->next_server = false;
+                       inc_stats(fctx->res, dns_resstatscounter_mismatchtcp);
+                       FCTXTRACE3("mismatched response; retrying over TCP",
+                                  rctx->result);
+                       rctx_done(rctx, ISC_R_SUCCESS);
+                       return ISC_R_COMPLETE;
+               }
+               break;
        default:
                break;
        }
index a43772e941273d2dc8070ca6cde53edfc17f35bc..78fa2cbeb4070e05c78c0dcd94b4f15cdfa423c3 100644 (file)
@@ -224,6 +224,7 @@ typedef enum isc_result {
        DNS_R_NSEC3RESALT,
        DNS_R_INCONSISTENTRR,
        DNS_R_NOALPN,
+       DNS_R_MISMATCH,
 
        DST_R_UNSUPPORTEDALG,
        DST_R_CRYPTOFAILURE,
index dbd0431df86a008e061c5e9139a73e6bea32051d..83e8cfeed71d7e4b70446ebd4317db4347161b41 100644 (file)
@@ -223,6 +223,7 @@ static const char *description[ISC_R_NRESULTS] = {
        [DNS_R_NSEC3RESALT] = "NSEC3 resalt",
        [DNS_R_INCONSISTENTRR] = "inconsistent resource record",
        [DNS_R_NOALPN] = "no ALPN",
+       [DNS_R_MISMATCH] = "response with mismatched query id",
 
        [DST_R_UNSUPPORTEDALG] = "algorithm is unsupported",
        [DST_R_CRYPTOFAILURE] = "crypto failure",
@@ -473,6 +474,7 @@ static const char *identifier[ISC_R_NRESULTS] = {
        [DNS_R_NSEC3RESALT] = "DNS_R_NSEC3RESALT",
        [DNS_R_INCONSISTENTRR] = "DNS_R_INCONSISTENTRR",
        [DNS_R_NOALPN] = "DNS_R_NOALPN",
+       [DNS_R_MISMATCH] = "DNS_R_MISMATCH",
 
        [DST_R_UNSUPPORTEDALG] = "DST_R_UNSUPPORTEDALG",
        [DST_R_CRYPTOFAILURE] = "DST_R_CRYPTOFAILURE",