Skip to content

Commit 24283c1

Browse files
rzikmCopilot
andcommitted
Address DNS resolver review feedback
- Preserve an earlier failure reason when a retry attempt is rejected without a specific error, so the surfaced exception is not lost. - Normalize the synchronous per-attempt timed-out SocketException to the same TimeoutException produced by the asynchronous cancellation path. - Validate the echoed question CLASS (IN) in addition to type and name, and fold the reader creation into the guard. - Treat an early TCP EOF as a retryable transport failure (IOException) instead of a malformed response. - Widen non-ASCII response label bytes deterministically instead of relying on Ascii.ToUtf16, whose output is undefined for such input. - Add unit tests for excessive/truncated compression pointers and non-ASCII label decoding. Co-authored-by: Copilot <[email protected]> Copilot-Session: db7d5bba-0fcb-4a39-bbe2-fc24b2092abf
1 parent 0ea1731 commit 24283c1

4 files changed

Lines changed: 72 additions & 8 deletions

File tree

‎src/libraries/System.Net.NameResolution/src/Resources/Strings.resx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@
6363
<data name="net_completed_result" xml:space="preserve">
6464
<value>This operation cannot be performed on a completed asynchronous result object.</value>
6565
</data>
66+
<data name="net_io_eof" xml:space="preserve">
67+
<value>Received an unexpected EOF or 0 bytes from the transport stream.</value>
68+
</data>
6669
<data name="net_io_invalidasyncresult" xml:space="preserve">
6770
<value>The IAsyncResult object was not returned from the corresponding asynchronous method on this class.</value>
6871
</data>

‎src/libraries/System.Net.NameResolution/src/System/Net/DnsEncodedName.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,14 @@ private bool TryDecodeAscii(Span<char> destination, out int charsWritten)
394394
return false;
395395
}
396396

397-
Ascii.ToUtf16(label, destination.Slice(charsWritten, label.Length), out _);
397+
// Response labels are only validated structurally (validateContent: false), so a
398+
// label may contain bytes outside the ASCII range. Widen each byte directly
399+
// instead of using Ascii.ToUtf16, whose result would be undefined for such input.
400+
Span<char> labelChars = destination.Slice(charsWritten, label.Length);
401+
for (int i = 0; i < label.Length; i++)
402+
{
403+
labelChars[i] = (char)label[i];
404+
}
398405
charsWritten += label.Length;
399406
}
400407

‎src/libraries/System.Net.NameResolution/src/System/Net/DnsResolverPal.Managed.cs‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,9 @@ private static async Task<DnsResponse> SendQuery(IList<IPEndPoint> servers, bool
393393

394394
if (validation == ResponseValidation.Retry)
395395
{
396-
lastException = validationError;
396+
// Preserve an earlier failure reason when this attempt was
397+
// rejected without a specific error (e.g. an ID mismatch).
398+
lastException = validationError ?? lastException;
397399
continue;
398400
}
399401

@@ -436,7 +438,12 @@ private static async Task<DnsResponse> SendQuery(IList<IPEndPoint> servers, bool
436438
}
437439
catch (SocketException ex)
438440
{
439-
lastException = ex;
441+
// Normalize the synchronous per-attempt timeout (surfaced as a
442+
// timed-out SocketException) to the same TimeoutException produced
443+
// by the asynchronous path's cancellation.
444+
lastException = ex.SocketErrorCode == SocketError.TimedOut
445+
? new TimeoutException()
446+
: ex;
440447
}
441448
catch (IOException ex)
442449
{
@@ -505,13 +512,15 @@ private static bool ValidateResponseQuestion(
505512
return false;
506513
}
507514

508-
DnsMessageReader.TryCreate(response, out DnsMessageReader reader);
509-
if (!reader.TryReadQuestion(out DnsQuestion question))
515+
if (!DnsMessageReader.TryCreate(response, out DnsMessageReader reader) ||
516+
!reader.TryReadQuestion(out DnsQuestion question))
510517
{
511518
return false;
512519
}
513520

514-
return question.Type == expectedType && question.Name.Equals(expectedName);
521+
return question.Type == expectedType
522+
&& question.Class == DnsRecordClass.Internet
523+
&& question.Name.Equals(expectedName);
515524
}
516525

517526
private static unsafe int WriteQuery(ushort queryId, string name, DnsRecordType type, Span<byte> destination)
@@ -672,7 +681,9 @@ private static async Task ReceiveExactAsync(DnsSocket socket, Memory<byte> buffe
672681
int received = await socket.ReceiveAsync(buffer[totalReceived..], cancellationToken).ConfigureAwait(false);
673682
if (received == 0)
674683
{
675-
ThrowMalformedResponse();
684+
// The peer closed the connection before sending the full message. Treat this
685+
// as a transport failure so the query is retried against the next server.
686+
throw new IOException(SR.net_io_eof);
676687
}
677688
totalReceived += received;
678689
}
@@ -686,7 +697,9 @@ private static void ReceiveExactSync(DnsSocket socket, Span<byte> buffer)
686697
int received = socket.Receive(buffer.Slice(totalReceived));
687698
if (received == 0)
688699
{
689-
ThrowMalformedResponse();
700+
// The peer closed the connection before sending the full message. Treat this
701+
// as a transport failure so the query is retried against the next server.
702+
throw new IOException(SR.net_io_eof);
690703
}
691704
totalReceived += received;
692705
}

‎src/libraries/System.Net.NameResolution/tests/UnitTests/DnsEncodedNameTests.cs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,47 @@ public void CompressionPointer_SelfJump_TryParseFails()
321321
Assert.False(DnsEncodedName.TryParse(message, 0, out _, out _));
322322
}
323323

324+
[Fact]
325+
public void CompressionPointer_Truncated_TryParseFails()
326+
{
327+
// A compression pointer needs two bytes but only one is present.
328+
byte[] message = [0xC0];
329+
Assert.False(DnsEncodedName.TryParse(message, 0, out _, out _));
330+
}
331+
332+
[Fact]
333+
public void CompressionPointer_ExceedsMaxHops_TryParseFails()
334+
{
335+
// Build a long chain of strictly-backward pointers. Each hop is legal on its own
336+
// (points to a lower offset), but the chain length exceeds the pointer-hop limit,
337+
// so a malicious response cannot force unbounded work.
338+
const int PointerCount = 20;
339+
byte[] message = new byte[1 + PointerCount * 2];
340+
message[0] = 0; // root label
341+
342+
for (int k = 1; k <= PointerCount; k++)
343+
{
344+
int offset = 2 * k - 1;
345+
int target = k == 1 ? 0 : 2 * (k - 1) - 1;
346+
message[offset] = (byte)(0xC0 | (target >> 8));
347+
message[offset + 1] = (byte)(target & 0xFF);
348+
}
349+
350+
Assert.False(DnsEncodedName.TryParse(message, 2 * PointerCount - 1, out _, out _));
351+
}
352+
353+
[Fact]
354+
public void TryDecode_NonAsciiLabelByte_WidensWithoutGarbage()
355+
{
356+
// Response names are validated structurally only, so a label may contain bytes
357+
// outside the ASCII range. Decoding must widen each byte deterministically rather
358+
// than emitting undefined characters.
359+
byte[] message = [1, 0xFF, 0];
360+
Assert.True(DnsEncodedName.TryParse(message, 0, out DnsEncodedName name, out _));
361+
Assert.Equal("\u00FF", name.ToString());
362+
Assert.Equal(1, name.GetFormattedLength());
363+
}
364+
324365
[Fact]
325366
public void TryCreate_TrailingDoubleDot_ReturnsInvalidData()
326367
{

0 commit comments

Comments
 (0)