mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+128
-7
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user