GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Bound domain-name decode buffer to avoid quadratic allocation · netty/netty@bccc62a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-dns/src
    • main/java/io/netty/handler/codec/dns
      • DnsCodecUtil.java
      • DnsMessageUtil.java
      • DnsResponseDecoder.java
    • test/java/io/netty/handler/codec/dns
      • DnsCodecUtilTest.java
      • DnsQueryTest.java
      • DnsResponseTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-dns/src/main/java/io/netty/handler/codec/dns/DnsCodecUtil.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/main/java/io/netty/handler/codec/dns/DnsCodecUtil.java
+51-10Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,21 @@
2525
import static io.netty.handler.codec.dns.DefaultDnsRecordDecoder.*;
2626

2727
final class DnsCodecUtil {
28+
29+
// See https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
30+
static final int MAX_DOMAIN_NAME_LENGTH = 255;
31+
32+
// A decoded name is at most 255 characters and every label contributes at least 2 ("x."), so a valid name has
33+
// at most 127 labels and therefore never needs to follow more compression pointers than that. Bounding the hops
34+
// per name keeps the decoding cost of each name constant instead of proportional to the message size.
35+
static final int MAX_COMPRESSION_POINTERS = 127;
36+
37+
// The RFC does not define a maximum number of records per section (the count is a 16-bit value). The cost of
38+
// decoding a single record is bounded (see MAX_DOMAIN_NAME_LENGTH and MAX_COMPRESSION_POINTERS), so this only
39+
// limits the total work per message. It is high enough that a full 64 KiB TCP message of minimal records with
40+
// compressed names (e.g. A records, 16 bytes each) still decodes.
41+
static final int MAX_RECORDS_PER_SECTION = 4096;
42+
2843
private DnsCodecUtil() {
2944
// Util class
3045
}
@@ -59,9 +74,9 @@ static void encodeDomainName(String name, ByteBuf buf) {
5974
"DNS label contains null byte at index " + idx);
6075
}
6176
totalLength += 1 + labelLen;
62-
if (totalLength > 255) {
77+
if (totalLength > MAX_DOMAIN_NAME_LENGTH) {
6378
throw new IllegalArgumentException(
64-
"DNS name exceeds maximum length of 255: " + name);
79+
"DNS name exceeds maximum length of " + MAX_DOMAIN_NAME_LENGTH + ": " + name);
6580
}
6681
buf.writeByte(labelLen);
6782
ByteBufUtil.writeAscii(buf, label);
@@ -70,9 +85,34 @@ static void encodeDomainName(String name, ByteBuf buf) {
7085
buf.writeByte(0); // marks end of name field
7186
}
7287

88+
/**
89+
* Returns the initial capacity to use for the {@link StringBuilder} that accumulates a decoded domain name.
90+
* A decoded name can never exceed {@link #MAX_DOMAIN_NAME_LENGTH} characters (see the check in
91+
* {@link #decodeDomainName(ByteBuf)}), so the capacity must not scale with {@code readable}, the number of
92+
* bytes left in the whole message: doing so would let a message with a huge amount of trailing data (e.g.
93+
* many more records after this name) force an oversized allocation for every single name decoded from it.
94+
*/
95+
static int calculateMaxNameLength(int readable) {
96+
return Math.min(readable, MAX_DOMAIN_NAME_LENGTH);
97+
}
98+
99+
/**
100+
* Ensures the record count of a section, as announced in the header of a DNS message, does not exceed
101+
* {@link #MAX_RECORDS_PER_SECTION}.
102+
*
103+
* @throws TooLongFrameException if the count is too large.
104+
*/
105+
static int checkRecordCount(DnsSection section, int count) {
106+
if (count > MAX_RECORDS_PER_SECTION) {
107+
throw new TooLongFrameException(
108+
section + " record count must be <= " + MAX_RECORDS_PER_SECTION + " but was " + count);
109+
}
110+
return count;
111+
}
112+
73113
static String decodeDomainName(ByteBuf in) {
74114
int position = -1;
75-
int checked = 0;
115+
int pointers = 0;
76116
final int end = in.writerIndex();
77117
final int readable = in.readableBytes();
78118

@@ -87,7 +127,7 @@ static String decodeDomainName(ByteBuf in) {
87127
return ROOT;
88128
}
89129

90-
final StringBuilder name = new StringBuilder(readable << 1);
130+
final StringBuilder name = new StringBuilder(calculateMaxNameLength(readable));
91131
while (in.isReadable()) {
92132
final int len = in.readUnsignedByte();
93133
final boolean pointer = (len & 0xc0) == 0xc0;
@@ -106,10 +146,10 @@ static String decodeDomainName(ByteBuf in) {
106146
}
107147
in.readerIndex(next);
108148

109-
// check for loops
110-
checked += 2;
111-
if (checked >= end) {
112-
throw new CorruptedFrameException("name contains a loop.");
149+
// Bounds the work per name, which also terminates loops.
150+
if (++pointers > MAX_COMPRESSION_POINTERS) {
151+
throw new CorruptedFrameException(
152+
"name contains more than " + MAX_COMPRESSION_POINTERS + " compression pointers");
113153
}
114154
} else if (len != 0) {
115155
if (!in.isReadable(len)) {
@@ -122,8 +162,9 @@ static String decodeDomainName(ByteBuf in) {
122162
name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
123163
in.skipBytes(len);
124164
// See https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
125-
if (name.length() > 255) {
126-
throw new TooLongFrameException("domain name must be <= 255 but was " + name.length());
165+
if (name.length() > MAX_DOMAIN_NAME_LENGTH) {
166+
throw new TooLongFrameException(
167+
"domain name must be <= " + MAX_DOMAIN_NAME_LENGTH + " but was " + name.length());
127168
}
128169
} else { // len == 0
129170
break;
Collapse file

‎codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,10 @@ static DnsQuery decodeDnsQuery(DnsRecordDecoder decoder, ByteBuf buf, DnsQueryFa
185185
DnsQuery query = newQuery(buf, supplier);
186186
boolean success = false;
187187
try {
188-
int questionCount = buf.readUnsignedShort();
189-
int answerCount = buf.readUnsignedShort();
190-
int authorityRecordCount = buf.readUnsignedShort();
191-
int additionalRecordCount = buf.readUnsignedShort();
188+
int questionCount = DnsCodecUtil.checkRecordCount(DnsSection.QUESTION, buf.readUnsignedShort());
189+
int answerCount = DnsCodecUtil.checkRecordCount(DnsSection.ANSWER, buf.readUnsignedShort());
190+
int authorityRecordCount = DnsCodecUtil.checkRecordCount(DnsSection.AUTHORITY, buf.readUnsignedShort());
191+
int additionalRecordCount = DnsCodecUtil.checkRecordCount(DnsSection.ADDITIONAL, buf.readUnsignedShort());
192192
decodeQuestions(decoder, query, buf, questionCount);
193193
decodeRecords(decoder, query, DnsSection.ANSWER, buf, answerCount);
194194
decodeRecords(decoder, query, DnsSection.AUTHORITY, buf, authorityRecordCount);
Collapse file

‎codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseDecoder.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseDecoder.java
+6-4Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,12 @@ final DnsResponse decode(A sender, A recipient, ByteBuf buffer) throws Exception
5555

5656
boolean success = false;
5757
try {
58-
final int questionCount = buffer.readUnsignedShort();
59-
final int answerCount = buffer.readUnsignedShort();
60-
final int authorityRecordCount = buffer.readUnsignedShort();
61-
final int additionalRecordCount = buffer.readUnsignedShort();
58+
final int questionCount = DnsCodecUtil.checkRecordCount(DnsSection.QUESTION, buffer.readUnsignedShort());
59+
final int answerCount = DnsCodecUtil.checkRecordCount(DnsSection.ANSWER, buffer.readUnsignedShort());
60+
final int authorityRecordCount =
61+
DnsCodecUtil.checkRecordCount(DnsSection.AUTHORITY, buffer.readUnsignedShort());
62+
final int additionalRecordCount =
63+
DnsCodecUtil.checkRecordCount(DnsSection.ADDITIONAL, buffer.readUnsignedShort());
6264

6365
decodeQuestions(response, buffer, questionCount);
6466
if (!decodeRecords(response, DnsSection.ANSWER, buffer, answerCount)) {
Collapse file

‎codec-dns/src/test/java/io/netty/handler/codec/dns/DnsCodecUtilTest.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/test/java/io/netty/handler/codec/dns/DnsCodecUtilTest.java
+71Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,33 @@
1717

1818
import io.netty.buffer.ByteBuf;
1919
import io.netty.buffer.Unpooled;
20+
import io.netty.handler.codec.CorruptedFrameException;
2021
import io.netty.handler.codec.TooLongFrameException;
2122
import org.junit.jupiter.api.Test;
2223

24+
import static org.junit.jupiter.api.Assertions.assertEquals;
2325
import static org.junit.jupiter.api.Assertions.assertThrows;
2426

2527
public class DnsCodecUtilTest {
2628

29+
@Test
30+
void calculateMaxNameLengthIsBoundedRegardlessOfRemainingBytes() {
31+
// A decoded name can never exceed MAX_DOMAIN_NAME_LENGTH characters, so the working buffer must stay
32+
// bounded even when the message has a huge number of bytes still readable after the name (e.g. many
33+
// more records in a large DNS message). Without this bound, a single message could force an oversized
34+
// allocation for every name decoded from it.
35+
assertEquals(DnsCodecUtil.MAX_DOMAIN_NAME_LENGTH,
36+
DnsCodecUtil.calculateMaxNameLength(Integer.MAX_VALUE));
37+
assertEquals(DnsCodecUtil.MAX_DOMAIN_NAME_LENGTH,
38+
DnsCodecUtil.calculateMaxNameLength(8 * 1024 * 1024));
39+
assertEquals(DnsCodecUtil.MAX_DOMAIN_NAME_LENGTH,
40+
DnsCodecUtil.calculateMaxNameLength(DnsCodecUtil.MAX_DOMAIN_NAME_LENGTH + 1));
41+
42+
// For buffers that cannot possibly contain more than a valid name, behavior is unchanged.
43+
assertEquals(5, DnsCodecUtil.calculateMaxNameLength(5));
44+
assertEquals(0, DnsCodecUtil.calculateMaxNameLength(0));
45+
}
46+
2747
@Test
2848
void rejectTooLongLabelWhileDecoding() {
2949
ByteBuf buf = Unpooled.buffer(256);
@@ -51,6 +71,57 @@ void rejectTooLongDomainNameWhileDecoding() {
5171
buf.release();
5272
}
5373

74+
@Test
75+
void acceptMaxCompressionPointers() {
76+
ByteBuf buf = newPointerChain(DnsCodecUtil.MAX_COMPRESSION_POINTERS);
77+
try {
78+
assertEquals("abc.", DnsCodecUtil.decodeDomainName(buf));
79+
// The reader index must be just after the first pointer.
80+
assertEquals(buf.writerIndex(), buf.readerIndex());
81+
} finally {
82+
buf.release();
83+
}
84+
}
85+
86+
@Test
87+
void rejectTooManyCompressionPointers() {
88+
ByteBuf buf = newPointerChain(DnsCodecUtil.MAX_COMPRESSION_POINTERS + 1);
89+
try {
90+
assertThrows(CorruptedFrameException.class, () -> DnsCodecUtil.decodeDomainName(buf));
91+
} finally {
92+
buf.release();
93+
}
94+
}
95+
96+
@Test
97+
void rejectCompressionPointerLoop() {
98+
ByteBuf buf = Unpooled.buffer();
99+
// A pointer to itself.
100+
buf.writeShort(0xc000);
101+
try {
102+
assertThrows(CorruptedFrameException.class, () -> DnsCodecUtil.decodeDomainName(buf));
103+
} finally {
104+
buf.release();
105+
}
106+
}
107+
108+
/**
109+
* Writes the name {@code abc.} followed by a chain of {@code pointers} compression pointers, each pointing to the
110+
* previous one, and positions the reader index at the last pointer so that decoding it follows all of them.
111+
*/
112+
private static ByteBuf newPointerChain(int pointers) {
113+
ByteBuf buf = Unpooled.buffer();
114+
buf.writeByte(3).writeBytes(new byte[] { 'a', 'b', 'c' }).writeByte(0);
115+
int previous = 0;
116+
for (int i = 0; i < pointers; i++) {
117+
int current = buf.writerIndex();
118+
buf.writeShort(0xc000 | previous);
119+
previous = current;
120+
}
121+
buf.readerIndex(previous);
122+
return buf;
123+
}
124+
54125
@Test
55126
void rejectTooLongLabelWhileEncoding() {
56127
ByteBuf buf = Unpooled.buffer(256);
Collapse file

‎codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java
+22Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
*/
1616
package io.netty.handler.codec.dns;
1717

18+
import io.netty.buffer.ByteBuf;
1819
import io.netty.channel.embedded.EmbeddedChannel;
1920

2021
import io.netty.channel.socket.DatagramPacket;
22+
import io.netty.handler.codec.TooLongFrameException;
2123
import io.netty.util.internal.SocketUtils;
2224
import org.junit.jupiter.api.Test;
2325
import org.junit.jupiter.params.ParameterizedTest;
@@ -32,6 +34,7 @@
3234
import static org.junit.jupiter.api.Assertions.assertEquals;
3335
import static org.junit.jupiter.api.Assertions.assertFalse;
3436
import static org.junit.jupiter.api.Assertions.assertNull;
37+
import static org.junit.jupiter.api.Assertions.assertThrows;
3538
import static org.junit.jupiter.api.Assertions.assertTrue;
3639

3740
public class DnsQueryTest {
@@ -152,4 +155,23 @@ public void testOpCodeIsEncodedIntoBits14To11(DnsOpCode opCode, boolean recursio
152155
assertTrue(packet.release());
153156
assertFalse(writeChannel.finish());
154157
}
158+
159+
@Test
160+
public void rejectTooManyRecordsInQuery() {
161+
// QDCOUNT, ANCOUNT, NSCOUNT, ARCOUNT
162+
for (int section = 0; section < 4; section++) {
163+
final EmbeddedChannel channel = new EmbeddedChannel(new DatagramDnsQueryDecoder());
164+
ByteBuf buf = channel.alloc().buffer(12);
165+
buf.writeShort(1).writeShort(0);
166+
for (int i = 0; i < 4; i++) {
167+
buf.writeShort(i == section ? DnsCodecUtil.MAX_RECORDS_PER_SECTION + 1 : 0);
168+
}
169+
final DatagramPacket packet = new DatagramPacket(buf, null, new InetSocketAddress(0));
170+
try {
171+
assertThrows(TooLongFrameException.class, () -> channel.writeInbound(packet));
172+
} finally {
173+
assertFalse(channel.finish());
174+
}
175+
}
176+
}
155177
}
Collapse file

‎codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java‎

Copy file name to clipboardExpand all lines: codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
+36Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import io.netty.channel.embedded.EmbeddedChannel;
2222
import io.netty.channel.socket.DatagramPacket;
2323
import io.netty.handler.codec.CorruptedFrameException;
24+
import io.netty.handler.codec.TooLongFrameException;
2425
import org.junit.jupiter.api.Test;
2526
import org.junit.jupiter.api.function.Executable;
2627

@@ -31,6 +32,7 @@
3132
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
3233
import static org.junit.jupiter.api.Assertions.assertSame;
3334
import static org.junit.jupiter.api.Assertions.assertThrows;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
3436

3537
public class DnsResponseTest {
3638

@@ -126,4 +128,38 @@ public void execute() {
126128
assertFalse(embedder.finish());
127129
}
128130
}
131+
132+
@Test
133+
public void rejectTooManyRecordsInResponse() {
134+
// QDCOUNT, ANCOUNT, NSCOUNT, ARCOUNT
135+
for (int section = 0; section < 4; section++) {
136+
final EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
137+
final ByteBuf packet = newHeader(embedder, 0x8000, section, DnsCodecUtil.MAX_RECORDS_PER_SECTION + 1);
138+
try {
139+
assertThrows(TooLongFrameException.class,
140+
() -> embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))));
141+
} finally {
142+
assertFalse(embedder.finish());
143+
}
144+
}
145+
}
146+
147+
@Test
148+
public void acceptMaxRecordsInResponse() {
149+
EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
150+
// No records follow the header, so the response is considered truncated but must not be rejected.
151+
ByteBuf packet = newHeader(embedder, 0x8000, 1, DnsCodecUtil.MAX_RECORDS_PER_SECTION);
152+
assertTrue(embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))));
153+
((DatagramDnsResponse) embedder.readInbound()).release();
154+
assertFalse(embedder.finish());
155+
}
156+
157+
private static ByteBuf newHeader(EmbeddedChannel channel, int flags, int section, int count) {
158+
ByteBuf buf = channel.alloc().buffer(12);
159+
buf.writeShort(1).writeShort(flags);
160+
for (int i = 0; i < 4; i++) {
161+
buf.writeShort(i == section ? count : 0);
162+
}
163+
return buf;
164+
}
129165
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.