Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,10 @@ class DnsMessageReader(
return result.readUtf8()
}

// TODO: don't infinite loop
private tailrec fun BufferedSource.readName(sink: Buffer) {
private tailrec fun BufferedSource.readName(
sink: Buffer,
maxOffset: Int = Int.MAX_VALUE,
) {
while (true) {
val labelTypeAndLength = readByte().toUByte().toInt()
val labelType = labelTypeAndLength and 0b11000000
Expand All @@ -123,10 +125,16 @@ class DnsMessageReader(

// Compressed suffix.
0b11_000000 -> {
val offsetLength = (labelLength shl 8) or readByte().toUByte().toInt()
val offset = (labelLength shl 8) or readByte().toUByte().toInt()

// Pointers may only refer to prior occurrences.
if (offset >= maxOffset) {
throw ProtocolException("malformed DNS message")
}

val offsetSource = sourceOffsetZero.peek()
offsetSource.skip(offsetLength.toLong())
return offsetSource.readName(sink)
offsetSource.skip(offset.toLong())
return offsetSource.readName(sink, maxOffset = offset)
}

0b01_000000, 0b10_000000 -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
package okhttp3.dnsoverhttps.internal

import assertk.assertThat
import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo
import java.net.InetAddress
import java.net.ProtocolException
import kotlin.test.Test
import kotlin.test.assertFailsWith
import okio.Buffer
import okio.ByteString.Companion.decodeHex

Expand Down Expand Up @@ -134,6 +137,22 @@ class DnsMessageReaderWriterTest {
)
}

@Test
fun `unbounded name compression`() {
val buffer = Buffer()
buffer.write(
"000081800001000100000000066c7973696e65c00c000100010363646ec00c000100010000000000040a141e28"
.decodeHex(),
)

val reader = DnsMessageReader(buffer)
val e =
assertFailsWith<ProtocolException> {
reader.read()
}
assertThat(e).hasMessage("malformed DNS message")
}

private fun assertRoundTrip(message: DnsMessage) {
val buffer = Buffer()
DnsMessageWriter(buffer).write(message)
Expand Down
Loading