-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_ns_zone.go
706 lines (593 loc) · 15.2 KB
/
cache_ns_zone.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
package resolver
import (
"context"
"net/netip"
"sort"
"sync"
"time"
"github.com/miekg/dns"
"darvaza.org/core"
"darvaza.org/resolver/pkg/client"
"darvaza.org/resolver/pkg/errors"
"darvaza.org/resolver/pkg/exdns"
)
const (
// MinimumNSCacheTTL tells the minimum time, in seconds,
// entries remain in the cache
MinimumNSCacheTTL = 10
)
// NSCacheZone represents the NS data and glue for a domain name.
type NSCacheZone struct {
mu sync.Mutex
name string
ns []string
sortedNS []string
glue map[string][]netip.Addr
ttl uint32
until time.Time
halfLife time.Time
attempts int
deadline time.Duration
interval time.Duration
s *Pool
}
// Name returns the domain name associated to these servers.
func (zone *NSCacheZone) Name() string {
return zone.name
}
// Expire tells when this information is no long valid.
func (zone *NSCacheZone) Expire() time.Time {
return zone.until
}
// TTL returns the number of seconds the data has to live.
func (zone *NSCacheZone) TTL() uint32 {
now := time.Now()
duration := now.Sub(zone.until)
if duration > 0 {
return uint32(duration / time.Second)
}
return 0
}
// OriginalTTL returns the number of seconds the data was
// set to live initially.
func (zone *NSCacheZone) OriginalTTL() uint32 {
return zone.ttl
}
// NeedsRefresh tells when this information should be refreshed.
func (zone *NSCacheZone) NeedsRefresh() bool {
return time.Now().After(zone.halfLife)
}
// Len returns the number of dns.RR entries stored.
func (zone *NSCacheZone) Len() int {
return len(zone.ns) + len(zone.glue)
}
// IsValid tells if a zone can be stored.
func (zone *NSCacheZone) IsValid() bool {
switch {
case zone == nil || len(zone.ns) == 0 || len(zone.glue) == 0:
return false
case zone.name == "":
return false
default:
return true
}
}
// SetResilience specifies retry parameters to use when doing an Exchange.
func (zone *NSCacheZone) SetResilience(attempts int, deadline, interval time.Duration) {
if attempts == 0 {
attempts = 1
}
zone.mu.Lock()
defer zone.mu.Unlock()
zone.attempts = attempts
zone.deadline = deadline
zone.interval = interval
if zone.s != nil {
zone.s.Attempts = attempts
zone.s.Deadline = deadline
zone.s.Interval = interval
}
}
// SetTTL sets the expiration and half-life times in
// seconds from Now.
func (zone *NSCacheZone) SetTTL(ttl, half uint32) {
switch {
case ttl == 0 && half == 0:
// apply defaults
ttl = MinimumNSCacheTTL
half = ttl / 2
case ttl < MinimumNSCacheTTL:
// too short, but preserve the half-life value.
ttl = MinimumNSCacheTTL
}
if half >= ttl {
// half-life needs to be lower than the maximum.
half = ttl / 2
}
zone.mu.Lock()
defer zone.mu.Unlock()
zone.unsafeSetTTL(ttl, half)
}
func (zone *NSCacheZone) unsafeSetTTL(ttl, half uint32) {
now := time.Now().UTC()
zone.ttl = ttl
zone.until = now.Add(time.Duration(ttl) * time.Second)
zone.halfLife = now.Add(time.Duration(half) * time.Second)
}
// Index processes the zone data and prepares it to be used.
func (zone *NSCacheZone) Index() {
zone.mu.Lock()
defer zone.mu.Unlock()
if zone.s == nil {
zone.unsafeIndex()
}
}
func (zone *NSCacheZone) unsafeIndex() {
if zone.ttl == 0 {
zone.unsafeSetTTL(MinimumNSCacheTTL, MinimumNSCacheTTL/2)
}
zone.sortedNS = make([]string, len(zone.ns))
copy(zone.sortedNS, zone.ns)
sort.Strings(zone.sortedNS)
for k, addrs := range zone.glue {
zone.glue[k] = nsCacheSortAddr(addrs)
}
zone.s = nsCacheGlueMap(zone.glue)
zone.s.Attempts = zone.attempts
zone.s.Interval = zone.interval
zone.s.Deadline = zone.deadline
}
// ReplyNS produces a response message equivalent to
// an NS request for the cache domain, including the
// known glue and current TTL.
func (zone *NSCacheZone) ReplyNS(req *dns.Msg) *dns.Msg {
ttl := zone.TTL()
zone.mu.Lock()
defer zone.mu.Unlock()
resp := new(dns.Msg)
resp.SetReply(req)
resp.Question = []dns.Question{
{
Name: zone.name,
Qclass: dns.ClassINET,
Qtype: dns.TypeNS,
},
}
resp.Answer = zone.unsafeExportNS(ttl)
resp.Extra = zone.unsafeExportGlue(ttl)
return resp
}
// ExportNS produces a [dns.RR] slice containing all the NS
// entries
func (zone *NSCacheZone) ExportNS() []dns.RR {
ttl := zone.TTL()
zone.mu.Lock()
defer zone.mu.Unlock()
return zone.unsafeExportNS(ttl)
}
func (zone *NSCacheZone) unsafeExportNS(ttl uint32) []dns.RR {
out := make([]dns.RR, len(zone.ns))
for i, name := range zone.ns {
out[i] = &dns.NS{
Hdr: dns.RR_Header{
Name: zone.name,
Class: dns.ClassINET,
Rrtype: dns.TypeNS,
Ttl: ttl,
},
Ns: name,
}
}
return out
}
// ExportGlue produces a [dns.RR] slice containing all the
// A/AAAA entries known for this zone.
func (zone *NSCacheZone) ExportGlue() []dns.RR {
ttl := zone.TTL()
zone.mu.Lock()
defer zone.mu.Unlock()
return zone.unsafeExportGlue(ttl)
}
func (zone *NSCacheZone) unsafeExportGlue(ttl uint32) []dns.RR {
var out []dns.RR
for _, name := range zone.sortedNS {
for _, ip := range zone.glue[name] {
rr, ok := newGlueRR(name, ttl, ip)
if ok {
out = append(out, rr)
}
}
}
return out
}
func newGlueRR(name string, ttl uint32, ip netip.Addr) (dns.RR, bool) {
var rr dns.RR
switch {
case !ip.IsValid():
// skip
case ip.Is6():
rr = &dns.AAAA{
Hdr: dns.RR_Header{
Name: name,
Class: dns.ClassINET,
Rrtype: dns.TypeAAAA,
Ttl: ttl,
},
AAAA: ip.AsSlice(),
}
default:
rr = &dns.A{
Hdr: dns.RR_Header{
Name: name,
Class: dns.ClassINET,
Rrtype: dns.TypeA,
Ttl: ttl,
},
A: ip.AsSlice(),
}
}
return rr, rr != nil
}
// Addrs produces a sorted string array containing
// all the A/AAAA entries known for this zone.
func (zone *NSCacheZone) Addrs() []string {
var addrs []netip.Addr
zone.mu.Lock()
for _, s := range zone.glue {
addrs = append(addrs, s...)
}
zone.mu.Unlock()
sort.Slice(addrs, func(i, j int) bool {
return addrs[i].Compare(addrs[j]) < 0
})
out := make([]string, len(addrs))
for i, ip := range addrs {
out[i] = ip.String()
}
return out
}
// RandomAddrs produces a randomly shuffled strings array
// containing all the A/AAAA entries known for this zone
func (zone *NSCacheZone) RandomAddrs() []string {
zone.Index()
return zone.s.Servers()
}
// Servers produces a string array containing all the
// NS entries known for this zone.
func (zone *NSCacheZone) Servers() []string {
zone.mu.Lock()
defer zone.mu.Lock()
out := make([]string, len(zone.ns))
copy(out, zone.ns)
return out
}
// Server returns one address chosen randomly or
// and empty string if there is none.
func (zone *NSCacheZone) Server() string {
return zone.s.Server()
}
// AddNS adds the name of a NS to the zone, and returns true
// if it's new.
func (zone *NSCacheZone) AddNS(name string) bool {
if name == "" || name == "." {
// invalid
// TODO: validate further
return false
}
name = dns.Fqdn(name)
zone.mu.Lock()
defer zone.mu.Unlock()
if _, ok := zone.glue[name]; ok {
// known
return false
}
zone.ns = append(zone.ns, name)
zone.glue[name] = []netip.Addr{}
zone.s = nil
return true
}
// AddGlue adds an A/AAAA entry to the zone if the name is a
// registered NS. Returns true if it was added.
func (zone *NSCacheZone) AddGlue(name string, addrs ...netip.Addr) bool {
var added bool
zone.mu.Lock()
defer zone.mu.Unlock()
if s, ok := zone.glue[name]; ok {
// known NS
eq := func(a, b netip.Addr) bool {
return a.Compare(b) == 0
}
for _, addr := range addrs {
if !core.SliceContainsFn(s, addr, eq) {
zone.glue[name] = append(s, addr)
zone.s = nil
added = true
}
}
}
return added
}
// SetGlue set the A/AAAA entries for a NS of a zone
// if it's registered as such.
// Returns true if it was set.
func (zone *NSCacheZone) SetGlue(name string, addrs []netip.Addr) bool {
zone.mu.Lock()
defer zone.mu.Unlock()
if _, ok := zone.glue[name]; ok {
// known NS
zone.glue[name] = addrs
zone.s = nil
return true
}
return false
}
// AddGlueNS adds an A/AAAA entry to the zone and, if necessary,
// the name as NS. Returns true if it was added.
func (zone *NSCacheZone) AddGlueNS(name string, addrs ...netip.Addr) bool {
zone.AddNS(name)
return zone.AddGlue(name, addrs...)
}
// AddGlueRR adds an A/AAAA entry to the zone from a [dns.RR] record,
// if the name is a registered NS. Returns true
func (zone *NSCacheZone) AddGlueRR(rr dns.RR) bool {
switch v := rr.(type) {
case *dns.A:
ip, _ := netip.AddrFromSlice(v.A)
if ip.IsValid() {
return zone.AddGlue(v.Hdr.Name, ip)
}
case *dns.AAAA:
ip, _ := netip.AddrFromSlice(v.AAAA)
if ip.IsValid() {
return zone.AddGlue(v.Hdr.Name, ip)
}
}
return false
}
// HasGlue tells if this zone has any glue address.
func (zone *NSCacheZone) HasGlue() bool {
zone.mu.Lock()
defer zone.mu.Unlock()
if zone.s == nil {
zone.unsafeIndex()
}
return zone.s.Len() > 0
}
// ForEachNS calls the function for each registered NS, including any known
// glue addresses.
func (zone *NSCacheZone) ForEachNS(fn func(name string, addrs []netip.Addr)) {
if zone != nil && fn != nil {
zone.mu.Lock()
names := make([]string, len(zone.ns))
copy(names, zone.ns)
zone.mu.Unlock()
for _, name := range names {
fn(name, zone.glue[name])
}
}
}
// ForEachAddr calls a function for each address in random order.
// return true to terminate the loop.
func (zone *NSCacheZone) ForEachAddr(fn func(string) bool) {
if fn == nil {
return
}
zone.Index()
zone.s.ForEach(fn)
}
// Exchange performs a DNS request on a random NS server of the zone,
// retrying on errors if [NSCacheZone.SetResilience] has been used.
func (zone *NSCacheZone) Exchange(ctx context.Context, req *dns.Msg) (*dns.Msg, error) {
return zone.s.Exchange(ctx, req)
}
// ExchangeWithClient performs a DNS request on a random NS server of the zone,
// using the given [client.Client], and retrying on errors
// if [NSCacheZone.SetResilience] has been used.
func (zone *NSCacheZone) ExchangeWithClient(ctx context.Context, req *dns.Msg,
c client.Client) (*dns.Msg, error) {
return zone.s.ExchangeWithClient(ctx, req, c)
}
// NewNSCacheZone creates a blank [NSCacheZone].
func NewNSCacheZone(name string) *NSCacheZone {
if name != "" {
name = dns.Fqdn(name)
}
return &NSCacheZone{
name: name,
glue: make(map[string][]netip.Addr),
}
}
// NewNSCacheZoneFromDelegation creates a new [NSCacheZone] using the delegation information
// on a response.
func NewNSCacheZoneFromDelegation(resp *dns.Msg) (*NSCacheZone, error) {
if !exdns.HasNsType(resp, dns.TypeNS) {
// no delegation
return nil, core.ErrInvalid
}
resp2 := resp.Copy()
sanitizeDelegation(resp2, ".")
zone, ttl, ok := assembleNSCacheZoneFromDelegation(resp2)
if !ok {
return nil, errors.ErrBadResponse()
}
zone.SetTTL(ttl, ttl/2)
return zone, nil
}
// NewNSCacheZoneFromNS creates a new [NSCacheZone] using the
// the response to a NS query.
func NewNSCacheZoneFromNS(resp *dns.Msg) (*NSCacheZone, error) {
if !exdns.HasAnswerType(resp, dns.TypeNS) {
// no NS data
return nil, errors.ErrBadResponse()
}
zone, ttl, ok := assembleNSCacheZoneFromNS(resp)
if !ok {
return nil, errors.ErrBadResponse()
}
zone.SetTTL(ttl, ttl/2)
return zone, nil
}
// NewNSCacheZoneFromMap creates a new [NSCacheZone] using a map for the NS server
// addresses.
func NewNSCacheZoneFromMap(name string, ttl uint32, m map[string]string) *NSCacheZone {
if ttl < MinimumNSCacheTTL {
ttl = MinimumNSCacheTTL
}
zone := assembleNSCacheZoneFromMap(dns.Fqdn(name), m)
zone.SetTTL(ttl, ttl/2)
return zone
}
func sanitizeDelegation(resp *dns.Msg, authority string) {
if len(resp.Answer) == 0 {
// pure NS mode. one zone and its addresses.
sanitizePureDelegation(resp, authority)
} else {
// hybrid, only remove NS entries not
// controlled by the authority.
filterNs := func(_ []dns.RR, rr dns.RR) (dns.RR, bool) {
hdr := rr.Header()
if hdr.Class == dns.ClassINET && hdr.Rrtype == dns.TypeNS {
keep := dns.IsSubDomain(authority, hdr.Name)
return rr, keep
}
// keep
return rr, true
}
resp.Ns = core.SliceReplaceFn(resp.Ns, filterNs)
}
}
// revive:disable:cognitive-complexity
// revive:disable:cyclomatic
func sanitizePureDelegation(resp *dns.Msg, authority string) {
// revive:enable:cognitive-complexity
// revive:enable:cyclomatic
var domain string
var nsNames = make(map[string]bool, len(resp.Ns))
// NS for a single name.
filterNs := func(rr dns.RR) bool {
switch p := rr.(type) {
case *dns.NS:
// NS
switch {
case domain == "":
// first
if !dns.IsSubDomain(authority, p.Hdr.Name) {
// NS outside the authority's domain
return false
}
domain = p.Hdr.Name
fallthrough
case p.Hdr.Name == domain:
// same name
nsNames[p.Ns] = true
return true
default:
// wrong name
return false
}
default:
// let other types pass
// TODO: assess if further pruning is desired.
return true
}
}
resp.Ns = core.SliceReplaceFn(resp.Ns,
func(_ []dns.RR, rr dns.RR) (dns.RR, bool) {
var keep bool
// only INET
if rr.Header().Class == dns.ClassINET {
keep = filterNs(rr)
}
return rr, keep
})
// only A/AAAA referencing NS names on resp.Extra
// TODO: anything else to filter out? narrow further?
filterGlue := func(rr dns.RR) bool {
hdr := rr.Header()
switch hdr.Rrtype {
case dns.TypeA, dns.TypeAAAA:
if nsNames[hdr.Name] {
// NS address
return true
}
// remove other addresses
return false
default:
// let other types pass
return true
}
}
resp.Extra = core.SliceReplaceFn(resp.Extra,
func(_ []dns.RR, rr dns.RR) (dns.RR, bool) {
var keep bool
if rr.Header().Class == dns.ClassINET {
keep = filterGlue(rr)
}
return rr, keep
})
}
func assembleNSCacheZoneFromDelegation(resp *dns.Msg) (*NSCacheZone, uint32, bool) {
return assembleNSCacheZoneFromRR(resp.Ns, resp.Extra)
}
func assembleNSCacheZoneFromNS(resp *dns.Msg) (*NSCacheZone, uint32, bool) {
return assembleNSCacheZoneFromRR(resp.Answer, resp.Extra)
}
// revive:disable:cognitive-complexity
func assembleNSCacheZoneFromRR(ns, extra []dns.RR) (*NSCacheZone, uint32, bool) {
// revive:enable:cognitive-complexity
var ttl uint32
zone := NewNSCacheZone("")
// collect NS entries
exdns.ForEachRR(ns, func(rr *dns.NS) {
hdr := rr.Header()
if zone.name == "" {
// first
zone.name = dns.Fqdn(hdr.Name)
ttl = hdr.Ttl
}
if rr.Hdr.Ttl < ttl {
ttl = rr.Hdr.Ttl
}
zone.AddNS(rr.Ns)
})
// collect A/AAAA entries
exdns.ForEachRR(extra, func(rr dns.RR) {
if zone.AddGlueRR(rr) {
// accepted
if n := rr.Header().Ttl; n < ttl {
ttl = n
}
}
})
return zone, ttl, len(zone.ns) > 0
}
func assembleNSCacheZoneFromMap(qName string, m map[string]string) *NSCacheZone {
zone := NewNSCacheZone(qName)
for k, sAddr := range m {
k = dns.Fqdn(k)
addr, _ := netip.ParseAddr(sAddr)
if addr.IsValid() {
zone.AddGlueNS(k, addr)
}
}
return zone
}
func nsCacheSortAddr(addrs []netip.Addr) []netip.Addr {
sort.Slice(addrs, func(i, j int) bool {
a, b := addrs[i], addrs[j]
return a.Compare(b) < 0
})
return addrs
}
func nsCacheGlueMap(glue map[string][]netip.Addr) *Pool {
out, _ := NewPoolExchanger(nil)
for _, e := range glue {
for _, ip := range e {
addr, err := exdns.AsServerAddress(ip.String())
if err == nil {
_ = out.Add(addr)
}
}
}
return out
}