mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
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:
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user