Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dns): validate forwarded DNS responses against the query and its target (#4671)
Sam Fakhreddineb6eeae92e17f
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.javaindex 2df2b7aa7b..508823dba7 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java@@ -19,6 +19,7 @@ import org.jboss.logging.Logger;import java.io.IOException;import java.net.DatagramPacket;import java.net.InetAddress;+import java.net.SocketTimeoutException;import java.nio.ByteBuffer;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -667,13 +668,25 @@ public class EmbeddedDnsServer {Exception last = null;for (DnsForwardingRule.Target target : targets) {try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) {- fwd.setSoTimeout(FORWARD_TIMEOUT_MS);InetAddress addr = InetAddress.getByName(target.address());+ fwd.connect(addr, target.port());fwd.send(new DatagramPacket(query, query.length, addr, target.port()));+ long deadline = System.nanoTime() + FORWARD_TIMEOUT_MS * 1_000_000L;byte[] buf = new byte[MAX_DNS_UDP_RESPONSE];DatagramPacket resp = new DatagramPacket(buf, buf.length);- fwd.receive(resp);- return Arrays.copyOf(resp.getData(), resp.getLength());+ while (true) {+ long remainingNs = deadline - System.nanoTime();+ if (remainingNs <= 0) {+ throw new SocketTimeoutException("DNS forward timeout");+ }+ resp.setLength(buf.length);+ // setSoTimeout(0) means wait forever, so never let the rounding reach 0.+ fwd.setSoTimeout((int) Math.max(1, remainingNs / 1_000_000L));+ fwd.receive(resp);+ if (isValidResponse(query, resp.getData(), resp.getLength())) {+ return Arrays.copyOf(resp.getData(), resp.getLength());+ }+ }} catch (Exception e) {last = e;LOG.debugv("DNS forward to {0} failed: {1}", target.address(), e.getMessage());@@ -730,4 +743,50 @@ public class EmbeddedDnsServer {}return servers;}++ /**+ * True when the datagram answers this query: same transaction ID, QR bit set, the same question+ * count, and the query's question echoed back. The name is compared ignoring ASCII case, like+ * glibc and c-ares, since a resolver may echo it case-folded. Only the question is compared:+ * clients usually append an EDNS OPT record to the query, and the answer section takes its place+ * in the response.+ */+ private static boolean isValidResponse(byte[] query, byte[] response, int length) {+ int questionEnd = questionEnd(query);+ // Also stops the question comparison reading stale buffer bytes past a short datagram.+ if (questionEnd < 0 || length < questionEnd) {+ return false;+ }+ if (response[0] != query[0] || response[1] != query[1]) {+ return false;+ }+ if ((response[2] & 0x80) == 0) {+ return false;+ }+ if (response[4] != query[4] || response[5] != query[5]) {+ return false;+ }+ int nameEnd = questionEnd - 4;+ for (int i = 12; i < nameEnd; i++) {+ if (asciiLower(response[i]) != asciiLower(query[i])) {+ return false;+ }+ }+ return Arrays.equals(query, nameEnd, questionEnd, response, nameEnd, questionEnd);+ }++ /** Label length bytes are below 64, so lowering every byte of the name only touches letters. */+ private static byte asciiLower(byte b) {+ return b >= 'A' && b <= 'Z' ? (byte) (b + ('a' - 'A')) : b;+ }++ /** End offset of the query's single question (name, type, class), or -1 if it is malformed. */+ private static int questionEnd(byte[] query) {+ int pos = 12;+ while (pos < query.length && query[pos] != 0) {+ pos += 1 + (query[pos] & 0xFF);+ }+ int end = pos + 1 + 4;+ return end <= query.length ? end : -1;+ }}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.javaindex fceab727e4..722f94c52c 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java@@ -650,14 +650,14 @@ class EmbeddedDnsServerTest {void forwardToUpstreams_returnsResponseLargerThan512BytesIntact() throws Exception {// Regression guard: a 512-byte receive buffer silently truncated EDNS0 responses from// CDN-backed public hosts, corrupting the answer forwarded back to the Lambda container.- byte[] bigResponse = new byte[1500];- for (int i = 0; i < bigResponse.length; i++) {+ byte[] query = buildQuery("business-api.tiktok.com", (short) 0x1234);+ byte[] bigResponse = replyTo(query, 1500);+ for (int i = query.length; i < bigResponse.length; i++) {bigResponse[i] = (byte) (i & 0xFF);}try (DatagramSocket responder = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {startResponder(responder, bigResponse);- byte[] query = buildQuery("business-api.tiktok.com", (short) 0x1234);byte[] response = dns.forwardToUpstreams(query, List.of("127.0.0.1"), responder.getLocalPort());@@ -700,14 +700,16 @@ class EmbeddedDnsServerTest {}}- /** Replies to the first datagram received with a fixed payload, on a daemon thread. */- private void startResponder(DatagramSocket responder, byte[] responsePayload) {+ /** Replies to the first datagram received with the given payloads, in order, on a daemon thread. */+ private void startResponder(DatagramSocket responder, byte[]... responsePayloads) {Thread t = new Thread(() -> {try {DatagramPacket req = new DatagramPacket(new byte[4096], 4096);responder.receive(req);- responder.send(new DatagramPacket(- responsePayload, responsePayload.length, req.getAddress(), req.getPort()));+ for (byte[] payload : responsePayloads) {+ responder.send(new DatagramPacket(+ payload, payload.length, req.getAddress(), req.getPort()));+ }} catch (Exception ignored) {// socket closed when the test completes}@@ -732,6 +734,13 @@ class EmbeddedDnsServerTest {return buf;}+ /** A response to {@code query}: same txId and question, QR bit set, zero-padded to {@code length}. */+ private byte[] replyTo(byte[] query, int length) {+ byte[] reply = Arrays.copyOf(query, length);+ reply[2] |= (byte) 0x80;+ return reply;+ }+private byte[] buildQuery(String name, short txId) {byte[] encodedName = encodeName(name);// header(12) + name + type(2) + class(2)@@ -747,4 +756,116 @@ class EmbeddedDnsServerTest {buf.putShort((short) 1); // class INreturn buf.array();}++ @Test+ void forwardToTargets_discardsForgedAnswerFromAnotherPortBeforeRealAnswer() throws Exception {+ // Catches: a datagram from a port other than the queried target is relayed as the answer+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"));+ DatagramSocket spoof = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ byte[] query = buildQuery("db.corp.internal", (short) 7);+ byte[] realReply = replyTo(query, query.length);+ // Same txId and question as the real answer; only the rcode (NXDOMAIN) differs.+ byte[] forgedReply = replyTo(query, query.length);+ forgedReply[3] = 3;+ DnsForwardingRule.Target target = new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort());++ Thread t = new Thread(() -> {+ try {+ DatagramPacket req = new DatagramPacket(new byte[4096], 4096);+ real.receive(req);+ spoof.send(new DatagramPacket(forgedReply, forgedReply.length, req.getAddress(), req.getPort()));+ real.send(new DatagramPacket(realReply, realReply.length, req.getAddress(), req.getPort()));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ });+ t.setDaemon(true);+ t.start();++ byte[] response = EmbeddedDnsServer.forwardToTargets(query, List.of(target));+ assertArrayEquals(realReply, response);+ }+ }++ @Test+ void forwardToTargets_discardsWrongTxIdDatagramBeforeRealAnswer() throws Exception {+ // Catches: a datagram with a wrong transaction ID is relayed as the answer+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ byte[] query = buildQuery("db.corp.internal", (short) 7);+ byte[] realReply = replyTo(query, query.length);+ byte[] badReply = replyTo(query, query.length);+ badReply[1] ^= 0x01;+ startResponder(real, badReply, realReply);++ byte[] response = EmbeddedDnsServer.forwardToTargets(+ query, List.of(new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort())));+ assertArrayEquals(realReply, response);+ }+ }++ @Test+ void forwardToTargets_acceptsAnswerToQueryCarryingAnEdnsOptRecord() throws Exception {+ // Catches: validation compares bytes past the question (the client's OPT record), so every+ // real answer to an EDNS query is discarded and forwarding times out+ byte[] plain = buildQuery("db.corp.internal", (short) 7);+ byte[] query = Arrays.copyOf(plain, plain.length + 11);+ query[11] = 1; // arcount+ ByteBuffer.wrap(query, plain.length, 11)+ .put((byte) 0).putShort((short) 41).putShort((short) 4096).putInt(0).putShort((short) 0);+ byte[] answer = replyTo(plain, plain.length);+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ startResponder(real, answer);++ byte[] response = EmbeddedDnsServer.forwardToTargets(+ query, List.of(new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort())));++ assertArrayEquals(answer, response);+ }+ }++ @Test+ void forwardToTargets_discardsWrongQuestionDatagramBeforeRealAnswer() throws Exception {+ // Catches: a datagram with a matching txId but different question section is relayed as the answer+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ byte[] query = buildQuery("db.corp.internal", (short) 7);+ byte[] realReply = replyTo(query, query.length);+ byte[] wrongQuery = buildQuery("other.corp.internal", (short) 7);+ byte[] badReply = replyTo(wrongQuery, wrongQuery.length);+ startResponder(real, badReply, realReply);++ byte[] response = EmbeddedDnsServer.forwardToTargets(+ query, List.of(new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort())));+ assertArrayEquals(realReply, response);+ }+ }++ @Test+ void forwardToTargets_discardsZeroQuestionDatagramBeforeRealAnswer() throws Exception {+ // Catches: a datagram declaring QDCOUNT 0 but carrying copied question bytes is relayed as the answer+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ byte[] query = buildQuery("db.corp.internal", (short) 7);+ byte[] realReply = replyTo(query, query.length);+ byte[] noQuestionReply = replyTo(query, query.length);+ noQuestionReply[5] = 0; // qdcount+ startResponder(real, noQuestionReply, realReply);++ byte[] response = EmbeddedDnsServer.forwardToTargets(+ query, List.of(new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort())));+ assertArrayEquals(realReply, response);+ }+ }++ @Test+ void forwardToTargets_acceptsAnswerThatEchoesTheNameInDifferentCase() throws Exception {+ // Catches: a resolver that case-folds the echoed name has every answer dropped+ try (DatagramSocket real = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {+ byte[] query = buildQuery("db.corp.internal", (short) 7);+ byte[] upperReply = replyTo(buildQuery("DB.CORP.INTERNAL", (short) 7), query.length);+ startResponder(real, upperReply);++ byte[] response = EmbeddedDnsServer.forwardToTargets(+ query, List.of(new DnsForwardingRule.Target("127.0.0.1", real.getLocalPort())));+ assertArrayEquals(upperReply, response);+ }+ }}