GeezerVison is showing github.com — Bound domain-name decode buffer to avoid quadratic allocation · netty/netty@bccc62a
File treeExpand file treeCollapse file tree Open diff view settings main/java/io/netty/handler/codec/dns test/java/io/netty/handler/codec/dns
Expand file treeCollapse file tree Open diff view settings Collapse file 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 number | Diff line number | Diff line change |
|---|
| 25 | 25 | import static io.netty.handler.codec.dns.DefaultDnsRecordDecoder.*; | 26 | 26 |
| 27 | 27 | 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 | + | 28 | 43 | private DnsCodecUtil() { | 29 | 44 | // Util class | 30 | 45 | } | @@ -59,9 +74,9 @@ static void encodeDomainName(String name, ByteBuf buf) { | 59 | 74 | "DNS label contains null byte at index " + idx); | 60 | 75 | } | 61 | 76 | totalLength += 1 + labelLen; | 62 | | - if (totalLength > 255) { | | 77 | + if (totalLength > MAX_DOMAIN_NAME_LENGTH) { | 63 | 78 | throw new IllegalArgumentException( | 64 | | - "DNS name exceeds maximum length of 255: " + name); | | 79 | + "DNS name exceeds maximum length of " + MAX_DOMAIN_NAME_LENGTH + ": " + name); | 65 | 80 | } | 66 | 81 | buf.writeByte(labelLen); | 67 | 82 | ByteBufUtil.writeAscii(buf, label); | @@ -70,9 +85,34 @@ static void encodeDomainName(String name, ByteBuf buf) { | 70 | 85 | buf.writeByte(0); // marks end of name field | 71 | 86 | } | 72 | 87 |
| | 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 | + | 73 | 113 | static String decodeDomainName(ByteBuf in) { | 74 | 114 | int position = -1; | 75 | | - int checked = 0; | | 115 | + int pointers = 0; | 76 | 116 | final int end = in.writerIndex(); | 77 | 117 | final int readable = in.readableBytes(); | 78 | 118 |
| @@ -87,7 +127,7 @@ static String decodeDomainName(ByteBuf in) { | 87 | 127 | return ROOT; | 88 | 128 | } | 89 | 129 |
| 90 | | - final StringBuilder name = new StringBuilder(readable << 1); | | 130 | + final StringBuilder name = new StringBuilder(calculateMaxNameLength(readable)); | 91 | 131 | while (in.isReadable()) { | 92 | 132 | final int len = in.readUnsignedByte(); | 93 | 133 | final boolean pointer = (len & 0xc0) == 0xc0; | @@ -106,10 +146,10 @@ static String decodeDomainName(ByteBuf in) { | 106 | 146 | } | 107 | 147 | in.readerIndex(next); | 108 | 148 |
| 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"); | 113 | 153 | } | 114 | 154 | } else if (len != 0) { | 115 | 155 | if (!in.isReadable(len)) { | @@ -122,8 +162,9 @@ static String decodeDomainName(ByteBuf in) { | 122 | 162 | name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.'); | 123 | 163 | in.skipBytes(len); | 124 | 164 | // 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()); | 127 | 168 | } | 128 | 169 | } else { // len == 0 | 129 | 170 | break; | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -185,10 +185,10 @@ static DnsQuery decodeDnsQuery(DnsRecordDecoder decoder, ByteBuf buf, DnsQueryFa | 185 | 185 | DnsQuery query = newQuery(buf, supplier); | 186 | 186 | boolean success = false; | 187 | 187 | 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()); | 192 | 192 | decodeQuestions(decoder, query, buf, questionCount); | 193 | 193 | decodeRecords(decoder, query, DnsSection.ANSWER, buf, answerCount); | 194 | 194 | decodeRecords(decoder, query, DnsSection.AUTHORITY, buf, authorityRecordCount); | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -55,10 +55,12 @@ final DnsResponse decode(A sender, A recipient, ByteBuf buffer) throws Exception | 55 | 55 |
| 56 | 56 | boolean success = false; | 57 | 57 | 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()); | 62 | 64 |
| 63 | 65 | decodeQuestions(response, buffer, questionCount); | 64 | 66 | if (!decodeRecords(response, DnsSection.ANSWER, buffer, answerCount)) { | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
| 17 | 17 |
| 18 | 18 | import io.netty.buffer.ByteBuf; | 19 | 19 | import io.netty.buffer.Unpooled; | | 20 | +import io.netty.handler.codec.CorruptedFrameException; | 20 | 21 | import io.netty.handler.codec.TooLongFrameException; | 21 | 22 | import org.junit.jupiter.api.Test; | 22 | 23 |
| | 24 | +import static org.junit.jupiter.api.Assertions.assertEquals; | 23 | 25 | import static org.junit.jupiter.api.Assertions.assertThrows; | 24 | 26 |
| 25 | 27 | public class DnsCodecUtilTest { | 26 | 28 |
| | 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 | + | 27 | 47 | @Test | 28 | 48 | void rejectTooLongLabelWhileDecoding() { | 29 | 49 | ByteBuf buf = Unpooled.buffer(256); | @@ -51,6 +71,57 @@ void rejectTooLongDomainNameWhileDecoding() { | 51 | 71 | buf.release(); | 52 | 72 | } | 53 | 73 |
| | 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 | + | 54 | 125 | @Test | 55 | 126 | void rejectTooLongLabelWhileEncoding() { | 56 | 127 | ByteBuf buf = Unpooled.buffer(256); | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
| 15 | 15 | */ | 16 | 16 | package io.netty.handler.codec.dns; | 17 | 17 |
| | 18 | +import io.netty.buffer.ByteBuf; | 18 | 19 | import io.netty.channel.embedded.EmbeddedChannel; | 19 | 20 |
| 20 | 21 | import io.netty.channel.socket.DatagramPacket; | | 22 | +import io.netty.handler.codec.TooLongFrameException; | 21 | 23 | import io.netty.util.internal.SocketUtils; | 22 | 24 | import org.junit.jupiter.api.Test; | 23 | 25 | import org.junit.jupiter.params.ParameterizedTest; | | 32 | 34 | import static org.junit.jupiter.api.Assertions.assertEquals; | 33 | 35 | import static org.junit.jupiter.api.Assertions.assertFalse; | 34 | 36 | import static org.junit.jupiter.api.Assertions.assertNull; | | 37 | +import static org.junit.jupiter.api.Assertions.assertThrows; | 35 | 38 | import static org.junit.jupiter.api.Assertions.assertTrue; | 36 | 39 |
| 37 | 40 | public class DnsQueryTest { | @@ -152,4 +155,23 @@ public void testOpCodeIsEncodedIntoBits14To11(DnsOpCode opCode, boolean recursio | 152 | 155 | assertTrue(packet.release()); | 153 | 156 | assertFalse(writeChannel.finish()); | 154 | 157 | } | | 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 | + } | 155 | 177 | } |
Collapse file 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 number | Diff line number | Diff line change |
|---|
| 21 | 21 | import io.netty.channel.embedded.EmbeddedChannel; | 22 | 22 | import io.netty.channel.socket.DatagramPacket; | 23 | 23 | import io.netty.handler.codec.CorruptedFrameException; | | 24 | +import io.netty.handler.codec.TooLongFrameException; | 24 | 25 | import org.junit.jupiter.api.Test; | 25 | 26 | import org.junit.jupiter.api.function.Executable; | 26 | 27 |
| | 31 | 32 | import static org.junit.jupiter.api.Assertions.assertInstanceOf; | 32 | 33 | import static org.junit.jupiter.api.Assertions.assertSame; | 33 | 34 | import static org.junit.jupiter.api.Assertions.assertThrows; | | 35 | +import static org.junit.jupiter.api.Assertions.assertTrue; | 34 | 36 |
| 35 | 37 | public class DnsResponseTest { | 36 | 38 |
| @@ -126,4 +128,38 @@ public void execute() { | 126 | 128 | assertFalse(embedder.finish()); | 127 | 129 | } | 128 | 130 | } | | 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 | + } | 129 | 165 | } |
|