-
Notifications
You must be signed in to change notification settings - Fork 18
/
dnsrewrite.go
504 lines (427 loc) · 12.3 KB
/
dnsrewrite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package rules
import (
"fmt"
"net/netip"
"strconv"
"strings"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/urlfilter/filterutil"
"github.com/miekg/dns"
)
// RCode is a semantic alias for int when used as a DNS response code RCODE.
type RCode = int
// RRType is a semantic alias for uint16 when used as a DNS resource record (RR)
// type.
type RRType = uint16
// RRValue is the value of a resource record. Depending on the [RRType], it
// will have different types:
// - [netip.Addr] for [dns.TypeA] and [dns.TypeAAAA];
// - non-nil [*DNSMX] for [dns.TypeMX];
// - string for [dns.TypePTR] (it's also a valid FQDN);
// - string for [dns.TypeTXT];
// - non-nil [*DNSSVCB] for [dns.TypeHTTPS] and [dns.TypeSVCB];
// - non-nil [*DNSSRV] for [dns.TypeSRV];
// - nil otherwise, but new types may be added in the future.
type RRValue = any
// DNSRewrite is a DNS rewrite ($dnsrewrite) rule.
type DNSRewrite struct {
// Value is the value for the record. See [RRValue] documentation for more
// details.
Value RRValue
// NewCNAME is the new CNAME. If set, clients must ignore other fields,
// resolve the CNAME, and set the new records accordingly.
NewCNAME string
// RCode is the new DNS RCODE.
RCode RCode
// RRType is the new DNS resource record (RR) type. It is only non-zero
// if RCode is dns.RCodeSuccess.
RRType RRType
}
// loadDNSRewrite loads the $dnsrewrite modifier.
func loadDNSRewrite(s string) (rewrite *DNSRewrite, err error) {
parts := strings.SplitN(s, ";", 3)
switch len(parts) {
case 1:
return loadDNSRewriteShort(s)
case 2:
return nil, errors.Error("invalid dnsrewrite: expected zero or two delimiters")
case 3:
return loadDNSRewriteNormal(parts[0], parts[1], parts[2])
default:
// TODO(a.garipov): Use panic("unreachable") instead?
return nil, fmt.Errorf("SplitN returned %d parts", len(parts))
}
}
// allUppercaseASCII returns true if s is not empty and all characters in s are
// uppercase ASCII letters.
func allUppercaseASCII(s string) (ok bool) {
if s == "" {
return false
}
for _, r := range s {
if r < 'A' || r > 'Z' {
return false
}
}
return true
}
// isValidHostRune returns true if r is a valid rune for a hostname part.
func isValidHostRune(r rune) (ok bool) {
return r == '-' || isValidHostFirstRune(r)
}
// isValidHostFirstRune returns true if r is a valid first rune for a hostname
// part.
func isValidHostFirstRune(r rune) (ok bool) {
return (r >= 'a' && r <= 'z') ||
(r >= 'A' && r <= 'Z') ||
(r >= '0' && r <= '9')
}
const invalidCharMsg = "invalid hostname part at index %d: invalid char %q at index %d"
// validateHost validates the host in accordance to RFC-952 with RFC-1123's
// inclusion of digits at the start of the host. It also doesn't validate
// against two or more hyphens to allow punycode and internationalized domains.
func validateHost(host string) (err error) {
l := len(host)
if l == 0 || l > 63 {
return fmt.Errorf("invalid hostname length: %d", l)
}
parts := strings.Split(host, ".")
for i, p := range parts {
if len(p) == 0 {
return fmt.Errorf("empty hostname part at index %d", i)
}
if r := p[0]; !isValidHostFirstRune(rune(r)) {
return fmt.Errorf(invalidCharMsg, i, r, 0)
}
for j, r := range p[1:] {
if !isValidHostRune(r) {
return fmt.Errorf(invalidCharMsg, i, r, j+1)
}
}
}
return nil
}
// loadDNSRewritesShort loads the shorthand version of the $dnsrewrite modifier.
func loadDNSRewriteShort(s string) (rewrite *DNSRewrite, err error) {
if s == "" {
// Return an empty DNSRewrite, because an empty string most probably
// means that this is a disabling allowlist case.
return &DNSRewrite{}, nil
}
if allUppercaseASCII(s) {
switch s {
case
"NOERROR",
"SERVFAIL",
"NXDOMAIN",
"REFUSED":
return &DNSRewrite{
RCode: dns.StringToRcode[s],
}, nil
default:
return nil, fmt.Errorf("unknown keyword: %q", s)
}
}
if filterutil.IsProbablyIP(s) {
if ip, parseErr := netip.ParseAddr(s); parseErr == nil {
if ip.Is4() {
return &DNSRewrite{
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
Value: ip,
}, nil
}
return &DNSRewrite{
RCode: dns.RcodeSuccess,
RRType: dns.TypeAAAA,
Value: ip,
}, nil
}
}
err = validateHost(s)
if err != nil {
return nil, fmt.Errorf("invalid shorthand hostname %q: %w", s, err)
}
return &DNSRewrite{
NewCNAME: s,
}, nil
}
// DNSMX is the type of RRValue values returned for MX records in DNS rewrites.
type DNSMX struct {
Exchange string
Preference uint16
}
// DNSSRV is the type of RRValue values returned for SRV records in DNS rewrites.
type DNSSRV struct {
Target string
Priority uint16
Weight uint16
Port uint16
}
// DNSSVCB is the type of RRValue values returned for HTTPS and SVCB records in
// dns rewrites.
//
// See https://tools.ietf.org/html/draft-ietf-dnsop-svcb-https-02.
type DNSSVCB struct {
Params map[string]string
Target string
Priority uint16
}
// dnsRewriteRRHandler is a function that parses values for specific resource
// record types.
//
// TODO(e.burkov): Since these functions are used here only as values of
// [dnsRewriteRRHandlers] map, which has a key of [RRType], the rr parameter
// appears useless in most cases except for [svcbDNSRewriteRRHandler].
type dnsRewriteRRHandler func(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error)
// cnameDNSRewriteRRHandler is a DNS rewrite handler that parses full-form CNAME
// rewrites.
func cnameDNSRewriteRRHandler(_ RCode, _ RRType, valStr string) (dnsr *DNSRewrite, err error) {
err = validateHost(valStr)
if err != nil {
return nil, fmt.Errorf("invalid cname host: %w", err)
}
return &DNSRewrite{
NewCNAME: valStr,
}, nil
}
// ptrDNSRewriteRRHandler is a DNS rewrite handler that parses PTR rewrites.
func ptrDNSRewriteRRHandler(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
// Accept both vanilla domain names and FQDNs.
var fqdn string
if l := len(valStr); l > 0 && valStr[l-1] == '.' {
fqdn = valStr
valStr = valStr[:l-1]
} else {
fqdn = dns.Fqdn(valStr)
}
err = validateHost(valStr)
if err != nil {
return nil, fmt.Errorf("invalid ptr host: %w", err)
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: fqdn,
}, nil
}
// strDNSRewriteRRHandler is a simple DNS rewrite handler that returns
// a *DNSRewrite with Value st to valStr.
func strDNSRewriteRRHandler(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: valStr,
}, nil
}
// srvDNSRewriteRRHandler is a DNS rewrite handler that parses SRV rewrites.
func srvDNSRewriteRRHandler(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
fields := strings.Split(valStr, " ")
if len(fields) < 4 {
return nil, fmt.Errorf("invalid srv %q: need four fields", valStr)
}
var prio64 uint64
prio64, err = strconv.ParseUint(fields[0], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid srv priority: %w", err)
}
var weight64 uint64
weight64, err = strconv.ParseUint(fields[1], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid srv weight: %w", err)
}
var port64 uint64
port64, err = strconv.ParseUint(fields[2], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid srv port: %w", err)
}
target := fields[3]
// From RFC 2782:
//
// A Target of "." means that the service is decidedly not available
// at this domain.
//
if target != "." {
err = validateHost(target)
if err != nil {
return nil, fmt.Errorf("invalid srv target: %w", err)
}
}
v := &DNSSRV{
Target: target,
Priority: uint16(prio64),
Weight: uint16(weight64),
Port: uint16(port64),
}
dnsr = &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: v,
}
return dnsr, nil
}
// svcbDNSRewriteRRHandler is a DNS rewrite handler that parses SVCB and HTTPS
// rewrites.
//
// See https://tools.ietf.org/html/draft-ietf-dnsop-svcb-https-02.
//
// TODO(a.garipov): Currently, we only support the contiguous type of
// char-string values from the RFC.
func svcbDNSRewriteRRHandler(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
var name string
switch rr {
case dns.TypeHTTPS:
name = "https"
case dns.TypeSVCB:
name = "svcb"
default:
return nil, fmt.Errorf("unsupported svcb-like rr type: %d", rr)
}
fields := strings.Split(valStr, " ")
if len(fields) < 2 {
return nil, fmt.Errorf("invalid %s %q: need at least two fields", name, valStr)
}
var prio64 uint64
prio64, err = strconv.ParseUint(fields[0], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid %s priority: %w", name, err)
}
target := fields[1]
// From the IETF draft:
//
// If TargetName has the value "." (represented in the wire format as
// a zero-length label), special rules apply.
//
if target != "." {
err = validateHost(target)
if err != nil {
return nil, fmt.Errorf("invalid %s target: %w", name, err)
}
}
if len(fields) == 2 {
v := &DNSSVCB{
Priority: uint16(prio64),
Target: target,
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: v,
}, nil
}
params := make(map[string]string, len(fields)-2)
for i, pair := range fields[2:] {
kv := strings.Split(pair, "=")
if l := len(kv); l != 2 {
err = fmt.Errorf("invalid %s param at index %d: got %d fields", name, i, l)
return nil, err
}
// TODO(a.garipov): Validate for uniqueness? Validate against
// the currently specified list of params from the RFC?
params[kv[0]] = kv[1]
}
v := &DNSSVCB{
Priority: uint16(prio64),
Target: target,
Params: params,
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: v,
}, nil
}
// dnsRewriteRRHandlers are the supported resource record types' rewrite
// handlers.
var dnsRewriteRRHandlers = map[RRType]dnsRewriteRRHandler{
dns.TypeA: func(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
var ip netip.Addr
if !filterutil.IsProbablyIP(valStr) {
return nil, fmt.Errorf("%q is not a valid ipv4", valStr)
} else if ip, err = netip.ParseAddr(valStr); err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
} else if !ip.Is4() {
return nil, fmt.Errorf("%q is not a valid ipv4", valStr)
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: ip,
}, nil
},
dns.TypeAAAA: func(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
var ip netip.Addr
if !filterutil.IsProbablyIP(valStr) {
return nil, fmt.Errorf("%q is not a valid ipv6", valStr)
} else if ip, err = netip.ParseAddr(valStr); err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
} else if !ip.Is6() {
return nil, fmt.Errorf("%q is an ipv4, not an ipv6", valStr)
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: ip,
}, nil
},
dns.TypeCNAME: cnameDNSRewriteRRHandler,
dns.TypeMX: func(rcode RCode, rr RRType, valStr string) (dnsr *DNSRewrite, err error) {
parts := strings.SplitN(valStr, " ", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid mx: %q", valStr)
}
var pref64 uint64
pref64, err = strconv.ParseUint(parts[0], 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid mx preference: %w", err)
}
exch := parts[1]
err = validateHost(exch)
if err != nil {
return nil, fmt.Errorf("invalid mx exchange: %w", err)
}
v := &DNSMX{
Exchange: exch,
Preference: uint16(pref64),
}
return &DNSRewrite{
RCode: rcode,
RRType: rr,
Value: v,
}, nil
},
dns.TypePTR: ptrDNSRewriteRRHandler,
dns.TypeTXT: strDNSRewriteRRHandler,
dns.TypeHTTPS: svcbDNSRewriteRRHandler,
dns.TypeSVCB: svcbDNSRewriteRRHandler,
dns.TypeSRV: srvDNSRewriteRRHandler,
}
// loadDNSRewritesNormal loads the normal version for of the $dnsrewrite
// modifier.
func loadDNSRewriteNormal(rcodeStr, rrStr, valStr string) (rewrite *DNSRewrite, err error) {
rcode, ok := dns.StringToRcode[strings.ToUpper(rcodeStr)]
if !ok {
return nil, fmt.Errorf("unknown rcode: %q", rcodeStr)
}
if rcode != dns.RcodeSuccess || (rrStr == "" && valStr == "") {
return &DNSRewrite{
RCode: rcode,
}, nil
}
var rr RRType
rr, err = strToRRType(rrStr)
if err != nil {
return nil, err
}
var handler dnsRewriteRRHandler
handler, ok = dnsRewriteRRHandlers[rr]
if !ok {
return &DNSRewrite{
RCode: rcode,
RRType: rr,
}, nil
}
return handler(rcode, rr, valStr)
}