fix(dns): validate forwarded DNS responses against the query and its target (#4671)

* fix(dns): accept forwarded DNS responses only from the target that was queried

Fixes #4670

- M1 PASS: RED run: org.opentest4j.AssertionFailedError: array contents differ at index [0], expected: <1> but was: <9>
- M2 PASS: gates green, last summary: [INFO] Tests run: 183, Failures: 0, Errors: 0, Skipped: 1
- M3 PASS: 2 file(s), all in scope
- M4 PASS: no new public members in main code
- M5 PASS: main diff 1 changed lines, limit 10
- M6 PASS: no em-dash in added lines
- A1 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());`
- A2 PASS: `src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java:676` `assertArrayEquals(new byte[] {1, 2, 3}, response);`
- A3 PASS: Test results: `[INFO] Tests run: 183, Failures: 0, Errors: 0, Skipped: 1`
- A4 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:607-615` (diff shows exactly one line added `+ fwd.connect(addr, target.port());` and zero changes to method signature, loop structure, timeout, fallback logic, or exception handling)
- G1 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());`
- G2 PASS: `src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java:676` `assertArrayEquals(new byte[] {1, 2, 3}, response);`
- G3 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:604-620` (diff modifies only line 608; `handleQuery`, `matchesSuffix`, `resolveARecord`, `planQuery`, `buildEmptyResponse`, `buildServerFailureResponse`, `resolveEc2PrivateDnsName`, `readName`, `buildAResponse`, `forwar
- G4 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());` (enforces source IP/port validation at OS level, matching AWS DNS resolver behavior)

* test(dns): give forwarding test replies valid DNS headers

The forwarding tests replied with filler bytes that are not a DNS response to the query. Build each reply from the query (same txId and question, QR bit set) so the tests keep passing once forwardToTargets validates responses. The large-response test keeps its 1500-byte size.

* fix(dns): discard forwarded DNS responses whose txId, QR bit or question don't match the query

Fixes #4670

- M1 PASS: RED run: org.opentest4j.AssertionFailedError: array contents differ at index [1], expected: <7> but was: <6>
- M2 PASS: gates green, last summary: [INFO] Tests run: 185, Failures: 0, Errors: 0, Skipped: 1
- M3 PASS: 2 file(s), all in scope
- M4 PASS: no new public members in main code
- M5 PASS: main diff 30 changed lines, limit 35
- M6 PASS: no em-dash in added lines
- A1 PASS: `"if (length < 12)"`, `"if (response[0] != query[0] || response[1] != query[1])"`, `"if ((response[2] & 0x80) == 0)"`, `"Arrays.equals(query, 12, query.length, response, 12, query.length)"`; `"while (true)"` loop with `"resp.setLength(buf.length)"` and `"fwd.receive(resp)"` before next deadline chec
- A2 PASS: `"long deadline = System.nanoTime() + FORWARD_TIMEOUT_MS * 1_000_000L;"` before loop; `"long remainingNs = deadline - System.nanoTime();"` and `"fwd.setSoTimeout((int) (remainingNs / 1_000_000L));"` inside loop
- A3 PASS: `forwardToTargets_discardsWrongTxIdDatagramBeforeRealAnswer`: `"badReply[1] ^= 0x01;"` sent first, then `"realReply"`, `"assertArrayEquals(realReply, response);"`
- A4 PASS: `forwardToTargets_discardsWrongQuestionDatagramBeforeRealAnswer`: `"byte[] wrongQuery = buildQuery("other.corp.internal", (short) 7);"`, `"byte[] badReply = replyTo(wrongQuery, wrongQuery.length);"` sent first, then `"realReply"`, `"assertArrayEquals(realReply, response);"`
- A5 PASS: Only `isValidResponse` (private static) added and `forwardToTargets` modified; `"fwd.connect(addr, target.port())"` stays; `Tests run: 185, Failures: 0, Errors: 0, Skipped: 1`
- G1 PASS: Replaces blind `"fwd.receive(resp); return ..."` with explicit DNS header/question validation loop matching diagnosis exactly
- G2 PASS: `"assertArrayEquals(realReply, response);"` asserts exact literal byte-for-byte match against setup fixture
- G3 PASS: Outer target iteration, `"last = e"` accumulation, and fallback paths untouched; validation loop is strictly contained within the per-target `try` block and does not mutate external state
- G4 PASS: Discards non-responses/mismatches, bounds wait to `FORWARD_TIMEOUT_MS`, throws `SocketTimeoutException` on expiry to trigger next target or fail, matching DNS resolver semantics and AWS upstream behavior

* fix(dns): match forwarded answers on question count and name ignoring case
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-10-08 22:08:18 -04:00
1 parent d22b4f107c
commit b6eeae92e1
2 files changed
+190 -10

No files matched your search

@@ -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;
}
}
@@ -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 IN
return 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);
}
}
}