Debian Codegraph @

internal/unpack/unpack.go

raw
1 package unpack
2
3 import (
4 "bytes"
5 "encoding/base32"
6 "encoding/base64"
7 "encoding/hex"
8 "net"
9 "net/netip"
10
11 "codeberg.org/miekg/dns/internal/ddd"
12 "codeberg.org/miekg/dns/pkg/pool"
13 "golang.org/x/crypto/cryptobyte"
14 )
15
16 const (
17 maxNameWireOctets = 255 // See RFC 1035 section 2.3.4
18
19 // This is the maximum length of a domain name in presentation format. The
20 // maximum wire length of a domain name is 255 octets (see above), with the
21 // maximum label length being 63. The wire format requires one extra byte over
22 // the presentation format.
23 maxNamePresentationLength = maxNameWireOctets - 1
24 )
25
26 func A(s *cryptobyte.String) (netip.Addr, error) {
27 var in []byte
28 if !s.ReadBytes(&in, net.IPv4len) {
29 return netip.Addr{}, &Error{"overflow A"}
30 }
31 return netip.AddrFrom4(*(*[4]byte)(in)), nil
32 }
33
34 func AAAA(s *cryptobyte.String) (netip.Addr, error) {
35 var in []byte
36 if !s.ReadBytes(&in, net.IPv6len) {
37 return netip.Addr{}, &Error{"overflow AAAA"}
38 }
39 return netip.AddrFrom16(*(*[16]byte)(in)), nil
40 }
41
42 // See [pack.StringAny].
43 func StringAny(s *cryptobyte.String, len int) (string, error) {
44 var b []byte
45 if !s.ReadBytes(&b, len) {
46 return "", &Error{"overflow string anything"}
47 }
48 return string(b), nil
49 }
50
51 func Strings(s *cryptobyte.String) ([]string, error) {
52 var strs []string
53 for !s.Empty() {
54 str, err := String(s)
55 if err != nil {
56 return strs, err
57 }
58 strs = append(strs, str)
59 }
60 return strs, nil
61 }
62
63 func String(s *cryptobyte.String) (string, error) {
64 var txt cryptobyte.String
65 if !s.ReadUint8LengthPrefixed(&txt) {
66 return "", &Error{"overflow string"}
67 }
68
69 sb := builderPool.Get()
70 consumed := 0
71 for i, b := range txt {
72 switch {
73 case b == '"' || b == '\\':
74 if consumed == 0 {
75 sb.Grow(len(txt) * 2)
76 }
77 sb.Write(txt[consumed:i])
78 sb.WriteByte('\\')
79 sb.WriteByte(b)
80 consumed = i + 1
81 case b < ' ' || b > '~': // unprintable
82 if consumed == 0 {
83 sb.Grow(len(txt) * 2)
84 }
85 sb.Write(txt[consumed:i])
86 sb.WriteString(ddd.Escape(b))
87 consumed = i + 1
88 }
89 }
90 if consumed == 0 { // no escaping needed
91 return string(txt), nil
92 }
93 sb.Write(txt[consumed:])
94 t := sb.String()
95 builderPool.Put(sb)
96 return t, nil
97 }
98
99 // Name unpacks a domain name.
100 // In addition to the simple sequences of counted strings above, domain names are allowed to refer to strings elsewhere in the
101 // packet, to avoid repeating common suffixes when returning many entries in a single domain. The pointers are marked
102 // by a length byte with the top two bits set. Ignoring those two bits, that byte and the next give a 14 bit offset from into msg
103 // where we should pick up the trail.
104 // Note that if we jump elsewhere in the packet, we record the last offset we read from when we found the first pointer,
105 // which is where the next record or record field will start. We enforce that pointers always point backwards into the message.
106
107 // Name unpacks a name in a cryptobyte.String.
108 func Name(s *cryptobyte.String, msgBuf []byte) (string, error) {
109 name := make([]byte, 0, maxNamePresentationLength)
110 var ptrs bool
111
112 // If we never see a pointer, we need to ensure that we advance s to our final position.
113 cs := *s
114
115 var c byte
116 for {
117 if !cs.ReadUint8(&c) {
118 return "", &Error{"overflow name"}
119 }
120 switch c & 0xC0 {
121 case 0x00: // literal string
122 if c == 0 { // If we see a zero-length label (root label), this is the end of the name.
123 if !ptrs {
124 *s = cs
125 }
126 if len(name) == 0 {
127 return ".", nil
128 }
129 return string(name), nil
130 }
131
132 if len(name)+int(c) >= maxNamePresentationLength {
133 return "", &Error{"name exceeded max wire-format octets"}
134 }
135
136 ln := len(name)
137 name = name[:ln+int(c)+1] // extend slice
138 cs.CopyBytes(name[ln : ln+int(c)]) // copy label into correct place
139 name[ln+int(c)] = '.'
140
141 case 0xC0: // pointer
142 if msgBuf == nil {
143 return "", &Error{"pointer in uncompressable name"}
144 }
145 var c1 byte
146 if !cs.ReadUint8(&c1) {
147 return "", &Error{"overflow name"}
148 }
149 // If this is the first pointer we've seen, we need to advance s to our current position.
150 if !ptrs {
151 *s = cs
152 }
153 // The pointer should always point backwards to an earlier part of the message. Technically it could work pointing
154 // forwards, but we choose not to support that as RFC 1035 specifically refers to a "prior
155 // occurrence".
156 off := uint16(c&^0xC0)<<8 | uint16(c1)
157 if int(off) >= Offset(cs, msgBuf)-2 {
158 return "", &Error{"pointer not to prior occurrence of name"}
159 }
160 // Jump to the offset in msgBuf. We carry msgBuf around with us solely for this line.
161 cs = msgBuf[off:]
162 ptrs = true
163
164 default: // 0x80 and 0x40 are reserved
165 return "", &Error{"reserved domain name label type"}
166 }
167 }
168 }
169
170 // MName unpacks a name in a cryptobyte.String, while also taking care of escaped dots (\.).
171 func MName(s *cryptobyte.String, msgBuf []byte) (string, error) {
172 name := make([]byte, 0, maxNamePresentationLength*2) // everything can be escaped...
173 var ptrs bool
174
175 // If we never see a pointer, we need to ensure that we advance s to our final position.
176 cs := *s
177
178 var c byte
179 for {
180 if !cs.ReadUint8(&c) {
181 return "", &Error{"overflow name"}
182 }
183 switch c & 0xC0 {
184 case 0x00: // literal string
185 if c == 0 { // If we see a zero-length label (root label), this is the end of the name.
186 if !ptrs {
187 *s = cs
188 }
189 if len(name) == 0 {
190 return ".", nil
191 }
192 return string(name), nil
193 }
194
195 if len(name)+int(c) >= maxNamePresentationLength {
196 return "", &Error{"name exceeded max wire-format octets: " + string(*s)}
197 }
198
199 ln := len(name)
200 name = name[:ln+int(c)+1] // extend slice
201 cs.CopyBytes(name[ln : ln+int(c)]) // copy label into correct place
202
203 // if this names contains dots, it's embedded and should be escaped.
204 dots := bytes.Count(name[ln:], []byte{'.'})
205 if dots == 0 {
206 name[ln+int(c)] = '.'
207 break
208 }
209
210 // Add the backslash at the right point. We walk the name from the back by creating juts enough
211 // room to add (mutiple) '\' is we see a dot. We copy the current character to the back while
212 // keeping track of the dots we saw.
213 name = name[:ln+int(c)+dots+1]
214 dot := 0
215 for k := ln + int(c); k > ln; k-- {
216 name[k+dots-dot] = name[k]
217 if name[k] == '.' {
218 dot++
219 name[k+dots-dot] = '\\'
220 }
221 }
222 name[ln+int(c)+dots] = '.'
223
224 case 0xC0: // pointer
225 if msgBuf == nil {
226 return "", &Error{"pointer in uncompressable name"}
227 }
228 var c1 byte
229 if !cs.ReadUint8(&c1) {
230 return "", &Error{"overflow name"}
231 }
232 // If this is the first pointer we've seen, we need to advance s to our current position.
233 if !ptrs {
234 *s = cs
235 }
236 // The pointer should always point backwards to an earlier part of the message. Technically it could work pointing
237 // forwards, but we choose not to support that as RFC 1035 specifically refers to a "prior
238 // occurrence".
239 off := uint16(c&^0xC0)<<8 | uint16(c1)
240 if int(off) >= Offset(cs, msgBuf)-2 {
241 return "", &Error{"pointer not to prior occurrence of name"}
242 }
243 // Jump to the offset in msgBuf. We carry msgBuf around with us solely for this line.
244 cs = msgBuf[off:]
245 ptrs = true
246
247 default: // 0x80 and 0x40 are reserved
248 return "", &Error{"reserved domain name label type"}
249 }
250 }
251 }
252
253 // Offset reports the offset of data into buf.
254 func Offset(data, buf []byte) int { return len(buf) - len(data) }
255
256 func StringBase32(s *cryptobyte.String, len int) (string, error) {
257 var b []byte
258 if !s.ReadBytes(&b, len) {
259 return "", ErrOverflow
260 }
261 return Base32(b), nil
262 }
263
264 func StringBase64(s *cryptobyte.String, len int) (string, error) {
265 var b []byte
266 if !s.ReadBytes(&b, len) {
267 return "", ErrOverflow
268 }
269 return Base64(b), nil
270 }
271
272 func Base32(b []byte) string {
273 return base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString(b)
274 }
275 func Base64(b []byte) string { return base64.StdEncoding.EncodeToString(b) }
276
277 func StringHex(s *cryptobyte.String, len int) (string, error) {
278 var b []byte
279 if !s.ReadBytes(&b, len) {
280 return "", ErrOverflow
281 }
282 return hex.EncodeToString(b), nil
283 }
284
285 func Names(s *cryptobyte.String, msgBuf []byte) ([]string, error) {
286 var names []string
287 for !s.Empty() {
288 name, err := Name(s, msgBuf)
289 if err != nil {
290 return names, err
291 }
292 names = append(names, name)
293 }
294 return names, nil
295 }
296
297 var builderPool = pool.NewBuilder()