View Javadoc
1   /*
2    * Copyright 2019 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.handler.codec.dns;
18  
19  import io.netty.buffer.ByteBuf;
20  import io.netty.buffer.ByteBufUtil;
21  import io.netty.handler.codec.CorruptedFrameException;
22  import io.netty.handler.codec.TooLongFrameException;
23  import io.netty.util.CharsetUtil;
24  import io.netty.util.internal.PlatformDependent;
25  
26  import static io.netty.handler.codec.dns.DefaultDnsRecordDecoder.*;
27  
28  final class DnsCodecUtil {
29  
30      // See https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
31      static final int MAX_DOMAIN_NAME_LENGTH = 255;
32  
33      // The length of a message that is sent over TCP is encoded in two bytes.
34      // See https://tools.ietf.org/html/rfc7766#section-8
35      static final int MAX_TCP_MESSAGE_LENGTH = 0xFFFF;
36  
37      // A decoded name is at most 255 characters and every label contributes at least 2 ("x."), so a valid name has
38      // at most 127 labels and therefore never needs to follow more compression pointers than that. Bounding the hops
39      // per name keeps the decoding cost of each name constant instead of proportional to the message size.
40      static final int MAX_COMPRESSION_POINTERS = 127;
41  
42      // The RFC does not define a maximum number of records per section (the count is a 16-bit value). The cost of
43      // decoding a single record is bounded (see MAX_DOMAIN_NAME_LENGTH and MAX_COMPRESSION_POINTERS), so this only
44      // limits the total work per message. It is high enough that a full 64 KiB TCP message of minimal records with
45      // compressed names (e.g. A records, 16 bytes each) still decodes.
46      static final int MAX_RECORDS_PER_SECTION = 4096;
47  
48      private DnsCodecUtil() {
49          // Util class
50      }
51  
52      /**
53       * Writes the length of the message into the first two bytes of the given {@link ByteBuf} which were reserved for
54       * it, as defined by <a href="https://tools.ietf.org/html/rfc7766#section-8">RFC 7766</a>.
55       *
56       * @throws IllegalArgumentException if the message is too large for the length to fit into two bytes.
57       */
58      static void setTcpMessageLength(ByteBuf buf) {
59          int length = buf.readableBytes() - 2;
60          if (length > MAX_TCP_MESSAGE_LENGTH) {
61              throw new IllegalArgumentException("DNS message length " + length + " exceeds the maximum of " +
62                      MAX_TCP_MESSAGE_LENGTH + " bytes that can be sent over TCP");
63          }
64          buf.setShort(0, length);
65      }
66  
67      static void encodeDomainName(String name, ByteBuf buf) {
68          if (ROOT.equals(name)) {
69              // Root domain
70              buf.writeByte(0);
71              return;
72          }
73  
74          int totalLength = 0;
75          final String[] labels = name.split("\\.");
76          for (int i = 0; i < labels.length; i++) {
77              String label = labels[i];
78              final int labelLen = label.length();
79              if (labelLen == 0) {
80                  if (i == labels.length - 1) {
81                      // zero-length label at the end means the end of the name.
82                      break;
83                  } else {
84                      throw new IllegalArgumentException("DNS name contains empty label: " + name);
85                  }
86              }
87              if (labelLen > 63) {
88                  throw new IllegalArgumentException(
89                          "DNS label length " + labelLen + " exceeds maximum of 63: " + name);
90              }
91              int idx = label.indexOf('\0');
92              if (idx != -1) {
93                  throw new IllegalArgumentException(
94                          "DNS label contains null byte at index " + idx);
95              }
96              totalLength += 1 + labelLen;
97              if (totalLength > MAX_DOMAIN_NAME_LENGTH) {
98                  throw new IllegalArgumentException(
99                          "DNS name exceeds maximum length of " + MAX_DOMAIN_NAME_LENGTH + ": " + name);
100             }
101             buf.writeByte(labelLen);
102             ByteBufUtil.writeAscii(buf, label);
103         }
104 
105         buf.writeByte(0); // marks end of name field
106     }
107 
108     /**
109      * Returns the initial capacity to use for the {@link StringBuilder} that accumulates a decoded domain name.
110      * A decoded name can never exceed {@link #MAX_DOMAIN_NAME_LENGTH} characters (see the check in
111      * {@link #decodeDomainName(ByteBuf)}), so the capacity must not scale with {@code readable}, the number of
112      * bytes left in the whole message: doing so would let a message with a huge amount of trailing data (e.g.
113      * many more records after this name) force an oversized allocation for every single name decoded from it.
114      */
115     static int calculateMaxNameLength(int readable) {
116         return Math.min(readable, MAX_DOMAIN_NAME_LENGTH);
117     }
118 
119     /**
120      * Ensures the record count of a section, as announced in the header of a DNS message, does not exceed
121      * {@link #MAX_RECORDS_PER_SECTION}.
122      *
123      * @throws TooLongFrameException if the count is too large.
124      */
125     static int checkRecordCount(DnsSection section, int count) {
126         if (count > MAX_RECORDS_PER_SECTION) {
127             throw new TooLongFrameException(
128                     section + " record count must be <= " + MAX_RECORDS_PER_SECTION + " but was " + count);
129         }
130         return count;
131     }
132 
133     static String decodeDomainName(ByteBuf in) {
134         int position = -1;
135         int pointers = 0;
136         final int end = in.writerIndex();
137         final int readable = in.readableBytes();
138 
139         // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
140         // some servers do not respect this for empty names. So just workaround this and return an empty name in this
141         // case.
142         //
143         // See:
144         // - https://github.com/netty/netty/issues/5014
145         // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
146         if (readable == 0) {
147             return ROOT;
148         }
149 
150         final StringBuilder name = new StringBuilder(calculateMaxNameLength(readable));
151         while (in.isReadable()) {
152             final int len = in.readUnsignedByte();
153             final boolean pointer = (len & 0xc0) == 0xc0;
154             if (pointer) {
155                 if (position == -1) {
156                     position = in.readerIndex() + 1;
157                 }
158 
159                 if (!in.isReadable()) {
160                     throw new CorruptedFrameException("truncated pointer in a name");
161                 }
162 
163                 final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
164                 if (next >= end) {
165                     throw new CorruptedFrameException("name has an out-of-range pointer");
166                 }
167                 in.readerIndex(next);
168 
169                 // Bounds the work per name, which also terminates loops.
170                 if (++pointers > MAX_COMPRESSION_POINTERS) {
171                     throw new CorruptedFrameException(
172                             "name contains more than " + MAX_COMPRESSION_POINTERS + " compression pointers");
173                 }
174             } else if (len != 0) {
175                 if (!in.isReadable(len)) {
176                     throw new CorruptedFrameException("truncated label in a name");
177                 }
178                 // See https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
179                 if (len > 63) {
180                     throw new TooLongFrameException("label must be <= 63 but was " + len);
181                 }
182                 name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
183                 in.skipBytes(len);
184                 // See https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
185                 if (name.length() > MAX_DOMAIN_NAME_LENGTH) {
186                     throw new TooLongFrameException(
187                             "domain name must be <= " + MAX_DOMAIN_NAME_LENGTH + " but was " + name.length());
188                 }
189             } else { // len == 0
190                 break;
191             }
192         }
193 
194         if (position != -1) {
195             in.readerIndex(position);
196         }
197 
198         if (name.length() == 0) {
199             return ROOT;
200         }
201 
202         if (name.charAt(name.length() - 1) != '.') {
203             name.append('.');
204         }
205 
206         return name.toString();
207     }
208 
209     /**
210      * Decompress pointer data.
211      * @param compression compressed data
212      * @return decompressed data
213      */
214     static ByteBuf decompressDomainName(ByteBuf compression) {
215         String domainName = decodeDomainName(compression);
216         ByteBuf result = compression.alloc().buffer(domainName.length() << 1);
217         try {
218             encodeDomainName(domainName, result);
219         } catch (Throwable cause) {
220             result.release();
221             PlatformDependent.throwException(cause);
222         }
223         return result;
224     }
225 }