-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathconfig.go
More file actions
896 lines (718 loc) · 27.2 KB
/
config.go
File metadata and controls
896 lines (718 loc) · 27.2 KB
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
package dnsforward
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log/slog"
"net"
"net/netip"
"os"
"slices"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/agh"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/aghslog"
"github.com/AdguardTeam/AdGuardHome/internal/aghtls"
"github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/dnsproxy/ratelimit"
"github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/stringutil"
"github.com/AdguardTeam/golibs/timeutil"
"github.com/AdguardTeam/golibs/validate"
"github.com/ameshkov/dnscrypt/v2"
)
// Config represents the DNS filtering configuration of AdGuard Home. The zero
// Config is empty and ready for use.
type Config struct {
// Callbacks for other modules
// ClientsContainer stores the information about special handling of some
// DNS clients.
ClientsContainer ClientsContainer `yaml:"-"`
// Anti-DNS amplification
// Ratelimit is the maximum number of requests per second from a given IP
// (0 to disable).
Ratelimit uint32 `yaml:"ratelimit"`
// RatelimitSubnetLenIPv4 is a subnet length for IPv4 addresses used for
// rate limiting requests.
RatelimitSubnetLenIPv4 uint `yaml:"ratelimit_subnet_len_ipv4"`
// RatelimitSubnetLenIPv6 is a subnet length for IPv6 addresses used for
// rate limiting requests.
RatelimitSubnetLenIPv6 uint `yaml:"ratelimit_subnet_len_ipv6"`
// RatelimitWhitelist is the list of whitelisted client IP addresses.
RatelimitWhitelist []netip.Addr `yaml:"ratelimit_whitelist"`
// RefuseAny, if true, refuse ANY requests.
RefuseAny bool `yaml:"refuse_any"`
// Upstream DNS servers configuration
// UpstreamDNS is the list of upstream DNS servers.
UpstreamDNS []string `yaml:"upstream_dns"`
// UpstreamDNSFileName, if set, points to the file which contains upstream
// DNS servers.
UpstreamDNSFileName string `yaml:"upstream_dns_file"`
// BootstrapDNS is the list of bootstrap DNS servers for DoH and DoT
// resolvers (plain DNS only).
BootstrapDNS []string `yaml:"bootstrap_dns"`
// FallbackDNS is the list of fallback DNS servers used when upstream DNS
// servers are not responding.
FallbackDNS []string `yaml:"fallback_dns"`
// UpstreamMode determines the logic through which upstreams will be used.
UpstreamMode UpstreamMode `yaml:"upstream_mode"`
// FastestTimeout replaces the default timeout for dialing IP addresses
// when FastestAddr is true.
FastestTimeout timeutil.Duration `yaml:"fastest_timeout"`
// Access settings
// AllowedClients is the slice of IP addresses, CIDR networks, and
// ClientIDs of allowed clients. If not empty, only these clients are
// allowed, and [Config.DisallowedClients] are ignored.
AllowedClients []string `yaml:"allowed_clients"`
// DisallowedClients is the slice of IP addresses, CIDR networks, and
// ClientIDs of disallowed clients.
DisallowedClients []string `yaml:"disallowed_clients"`
// BlockedHosts is the list of hosts that should be blocked.
BlockedHosts []string `yaml:"blocked_hosts"`
// TrustedProxies is the list of CIDR networks with proxy servers addresses
// from which the DoH requests should be handled. The value of nil or an
// empty slice for this field makes Proxy not trust any address.
TrustedProxies []netutil.Prefix `yaml:"trusted_proxies"`
// DNS cache settings
// CacheEnabled defines if the DNS cache should be used.
CacheEnabled bool `yaml:"cache_enabled"`
// CacheSize is the DNS cache size (in bytes).
CacheSize uint32 `yaml:"cache_size"`
// CacheMinTTL is the override TTL value (minimum) received from upstream
// server.
CacheMinTTL uint32 `yaml:"cache_ttl_min"`
// CacheMaxTTL is the override TTL value (maximum) received from upstream
// server.
CacheMaxTTL uint32 `yaml:"cache_ttl_max"`
// CacheOptimistic defines if optimistic cache mechanism should be used.
CacheOptimistic bool `yaml:"cache_optimistic"`
// CacheOptimisticAnswerTTL is the default TTL for expired cached responses.
CacheOptimisticAnswerTTL timeutil.Duration `yaml:"cache_optimistic_answer_ttl"`
// CacheOptimisticMaxAge is the maximum time entries remain in the cache
// when cache is optimistic.
CacheOptimisticMaxAge timeutil.Duration `yaml:"cache_optimistic_max_age"`
// Other settings
// BogusNXDomain is the list of IP addresses, responses with them will be
// transformed to NXDOMAIN.
BogusNXDomain []string `yaml:"bogus_nxdomain"`
// AAAADisabled, if true, respond with an empty answer to all AAAA
// requests.
AAAADisabled bool `yaml:"aaaa_disabled"`
// EnableDNSSEC defines whether the proxy should set the AD/DO bits in the
// upstream requests.
EnableDNSSEC bool `yaml:"enable_dnssec"`
// EDNSClientSubnet is the settings list for EDNS Client Subnet.
EDNSClientSubnet *EDNSClientSubnet `yaml:"edns_client_subnet"`
// MaxGoroutines is the max number of parallel goroutines for processing
// incoming requests.
MaxGoroutines uint `yaml:"max_goroutines"`
// HandleDDR, if true, handle DDR requests
HandleDDR bool `yaml:"handle_ddr"`
// IpsetList is the ipset configuration that allows AdGuard Home to add IP
// addresses of the specified domain names to an ipset list. Syntax:
//
// DOMAIN[,DOMAIN].../IPSET_NAME[,IPSET_NAME]...
//
// This field is ignored if [IpsetListFileName] is set.
IpsetList []string `yaml:"ipset"`
// IpsetListFileName, if set, points to the file with ipset configuration.
// The format is the same as in [IpsetList].
IpsetListFileName string `yaml:"ipset_file"`
// BootstrapPreferIPv6, if true, instructs the bootstrapper to prefer IPv6
// addresses to IPv4 ones for DoH, DoQ, and DoT.
BootstrapPreferIPv6 bool `yaml:"bootstrap_prefer_ipv6"`
}
// EDNSClientSubnet is the settings list for EDNS Client Subnet.
type EDNSClientSubnet struct {
// CustomIP for EDNS Client Subnet.
CustomIP netip.Addr `yaml:"custom_ip"`
// Enabled defines if EDNS Client Subnet is enabled.
Enabled bool `yaml:"enabled"`
// UseCustom defines if CustomIP should be used.
UseCustom bool `yaml:"use_custom"`
}
// TLSConfig contains the TLS configuration settings for DNSCrypt,
// DNS-over-HTTPS (DoH), DNS-over-TLS (DoT), DNS-over-QUIC (DoQ), and Discovery
// of Designated Resolvers (DDR).
type TLSConfig struct {
// DNSCryptConf contains the configuration settings for a DNSCrypt server.
// It is nil if the DNSCrypt server is disabled.
DNSCryptConf *DNSCryptConfig
// Cert is the TLS certificate used for TLS connections. It is nil if
// encryption is disabled.
Cert *tls.Certificate
// TLSListenAddrs are the addresses to listen on for DoT connections. Each
// item in the list must be non-nil if Cert is not nil.
TLSListenAddrs []*net.TCPAddr
// QUICListenAddrs are the addresses to listen on for DoQ connections. Each
// item in the list must be non-nil if Cert is not nil.
QUICListenAddrs []*net.UDPAddr
// HTTPSListenAddrs should be the addresses AdGuard Home is listening on for
// DoH connections. These addresses are announced with DDR. Each item in
// the list must be non-nil.
HTTPSListenAddrs []netip.AddrPort
// ServerName is the hostname of the server. Currently, it is only being
// used for ClientID checking and Discovery of Designated Resolvers (DDR).
ServerName string
// StrictSNICheck controls if the connections with SNI mismatching the
// certificate's ones should be rejected.
StrictSNICheck bool
}
// DNSCryptConfig contains the configuration settings for a DNSCrypt server.
type DNSCryptConfig struct {
// ResolverCert is the certificate used for DNSCrypt connections. It is not
// nil if there is at least one UDP or TCP address present.
ResolverCert *dnscrypt.Cert
// UDPListenAddrs are the addresses to listen on for DNSCrypt UDP
// connections.
UDPListenAddrs []*net.UDPAddr
// TCPListenAddrs are the addresses to listen on for DNSCrypt TCP
// connections.
TCPListenAddrs []*net.TCPAddr
// ProviderName is the name of the DNSCrypt provider. It is not empty if
// there is at least one UDP or TCP address present.
ProviderName string
}
// ServerConfig represents server configuration.
// The zero ServerConfig is empty and ready for use.
type ServerConfig struct {
// UDPListenAddrs is the list of addresses to listen for DNS-over-UDP.
UDPListenAddrs []*net.UDPAddr
// TCPListenAddrs is the list of addresses to listen for DNS-over-TCP.
TCPListenAddrs []*net.TCPAddr
// UpstreamConfig is the general configuration of upstream DNS servers.
UpstreamConfig *proxy.UpstreamConfig
// PrivateRDNSUpstreamConfig is the configuration of upstream DNS servers
// for private reverse DNS.
PrivateRDNSUpstreamConfig *proxy.UpstreamConfig
// AddrProcConf defines the configuration for the client IP processor.
// If nil, [client.EmptyAddrProc] is used.
//
// TODO(a.garipov): The use of [client.EmptyAddrProc] is a crutch for tests.
// Remove that.
AddrProcConf *client.DefaultAddrProcConfig
// TLSConf is the TLS configuration for DNS-over-TLS, DNS-over-QUIC, and
// HTTPS. It must not be nil.
TLSConf *TLSConfig
Config
// TLSAllowUnencryptedDoH defines if unencrypted DoH connections are
// allowed.
TLSAllowUnencryptedDoH bool
// UpstreamTimeout is the timeout for querying upstream servers.
UpstreamTimeout time.Duration
TLSv12Roots *x509.CertPool // list of root CAs for TLSv1.2
// TLSCiphers are the IDs of TLS cipher suites to use.
TLSCiphers []uint16
// ConfModifier is used to update the global configuration. It must not be
// nil.
ConfModifier agh.ConfigModifier
// Register an HTTP handler
HTTPReg aghhttp.Registrar
// LocalPTRResolvers is a slice of addresses to be used as upstreams for
// resolving PTR queries for local addresses.
LocalPTRResolvers []string
// DNS64Prefixes is a slice of NAT64 prefixes to be used for DNS64.
DNS64Prefixes []netip.Prefix
// UsePrivateRDNS defines if the PTR requests for unknown addresses from
// locally-served networks should be resolved via private PTR resolvers.
UsePrivateRDNS bool
// UseDNS64 defines if DNS64 is enabled for incoming requests.
UseDNS64 bool
// ServeHTTP3 defines if HTTP/3 is be allowed for incoming requests.
ServeHTTP3 bool
// UseHTTP3Upstreams defines if HTTP/3 is be allowed for DNS-over-HTTPS
// upstreams.
UseHTTP3Upstreams bool
// ServePlainDNS defines if plain DNS is allowed for incoming requests.
ServePlainDNS bool
// PendingRequestsEnabled defines if duplicate requests should be forwarded
// to upstreams along with the original one.
PendingRequestsEnabled bool
}
// UpstreamMode is a enumeration of upstream mode representations. See
// [proxy.UpstreamModeType].
//
// TODO(d.kolyshev): Consider using [proxy.UpstreamMode].
type UpstreamMode string
const (
UpstreamModeLoadBalance UpstreamMode = "load_balance"
UpstreamModeParallel UpstreamMode = "parallel"
UpstreamModeFastestAddr UpstreamMode = "fastest_addr"
)
// newProxyConfig creates and validates configuration for the main proxy.
//
// TODO(d.kolyshev): Improve maintainability.
func (s *Server) newProxyConfig(ctx context.Context) (conf *proxy.Config, err error) {
srvConf := s.conf
trustedPrefixes := netutil.UnembedPrefixes(srvConf.TrustedProxies)
ratelimitMw, err := newRatelimitMw(s.baseLogger, srvConf)
if err != nil {
return nil, fmt.Errorf("ratelimit middleware: %w", err)
}
logMw := newLogMiddleware(s.baseLogger, slogutil.LevelTrace)
httpConf := &proxy.HTTPConfig{
ServerHeader: aghhttp.UserAgent(),
InsecureEnabled: s.conf.TLSAllowUnencryptedDoH,
}
conf = &proxy.Config{
Logger: s.baseLogger.With(slogutil.KeyPrefix, aghslog.PrefixDNSProxy),
RefuseAny: srvConf.RefuseAny,
TrustedProxies: netutil.SliceSubnetSet(trustedPrefixes),
CacheMinTTL: srvConf.CacheMinTTL,
CacheMaxTTL: srvConf.CacheMaxTTL,
CacheOptimistic: srvConf.CacheOptimistic,
CacheOptimisticAnswerTTL: time.Duration(srvConf.CacheOptimisticAnswerTTL),
CacheOptimisticMaxAge: time.Duration(srvConf.CacheOptimisticMaxAge),
UpstreamConfig: srvConf.UpstreamConfig,
PrivateRDNSUpstreamConfig: srvConf.PrivateRDNSUpstreamConfig,
RequestHandler: ratelimitMw.Wrap(logMw.Wrap(s.Wrap(s))),
EnableEDNSClientSubnet: srvConf.EDNSClientSubnet.Enabled,
MaxGoroutines: srvConf.MaxGoroutines,
UseDNS64: srvConf.UseDNS64,
DNS64Prefs: srvConf.DNS64Prefixes,
UsePrivateRDNS: srvConf.UsePrivateRDNS,
PrivateSubnets: s.privateNets,
MessageConstructor: s,
PendingRequests: &proxy.PendingRequestsConfig{
Enabled: srvConf.PendingRequestsEnabled,
},
HTTPConfig: httpConf,
DNSSECEnabled: srvConf.EnableDNSSEC,
}
if srvConf.EDNSClientSubnet.UseCustom {
// TODO(s.chzhen): Use netip.Addr instead of net.IP inside dnsproxy.
conf.EDNSAddr = net.IP(srvConf.EDNSClientSubnet.CustomIP.AsSlice())
}
err = setProxyUpstreamMode(conf, srvConf.UpstreamMode, time.Duration(srvConf.FastestTimeout))
if err != nil {
return nil, fmt.Errorf("upstream mode: %w", err)
}
conf.BogusNXDomain, err = parseBogusNXDOMAIN(srvConf.BogusNXDomain)
if err != nil {
return nil, fmt.Errorf("bogus_nxdomain: %w", err)
}
err = s.prepareTLS(ctx, conf)
if err != nil {
return nil, fmt.Errorf("validating tls: %w", err)
}
err = s.preparePlain(ctx, conf)
if err != nil {
return nil, fmt.Errorf("validating plain: %w", err)
}
conf, err = prepareCacheConfig(conf,
srvConf.CacheEnabled,
srvConf.CacheSize,
srvConf.CacheMinTTL,
srvConf.CacheMaxTTL,
)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
return conf, nil
}
// newRatelimitMw returns the ratelimit middleware. In case of invalid
// ratelimit configuration returns an error. l must not be nil.
func newRatelimitMw(
l *slog.Logger,
conf ServerConfig,
) (mw proxy.Middleware, err error) {
if conf.Ratelimit == 0 {
return proxy.MiddlewareFunc(proxy.PassThrough), nil
}
rlConf := &ratelimit.Config{
Logger: l.With(slogutil.KeyPrefix, "ratelimit"),
Ratelimit: uint(conf.Ratelimit),
SubnetLenIPv4: conf.RatelimitSubnetLenIPv4,
SubnetLenIPv6: conf.RatelimitSubnetLenIPv6,
}
if err = rlConf.Validate(); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
return ratelimit.NewMiddleware(rlConf), nil
}
// prepareCacheConfig prepares the cache configuration and returns an error if
// there is one.
func prepareCacheConfig(
conf *proxy.Config,
isEnabled bool,
size uint32,
minTTL uint32,
maxTTL uint32,
) (prepared *proxy.Config, err error) {
if isEnabled {
cacheSize := int(size)
err = validate.Positive("cache_size", cacheSize)
if err != nil {
return nil, fmt.Errorf("cache_enabled is true: %w", err)
}
conf.CacheEnabled = true
conf.CacheSizeBytes = cacheSize
}
err = validateCacheTTL(minTTL, maxTTL)
if err != nil {
return nil, fmt.Errorf("validating cache ttl: %w", err)
}
return conf, nil
}
// parseBogusNXDOMAIN parses the bogus NXDOMAIN strings into valid subnets.
func parseBogusNXDOMAIN(confBogusNXDOMAIN []string) (subnets []netip.Prefix, err error) {
for i, s := range confBogusNXDOMAIN {
var subnet netip.Prefix
subnet, err = aghnet.ParseSubnet(s)
if err != nil {
return nil, fmt.Errorf("subnet at index %d: %w", i, err)
}
subnets = append(subnets, subnet)
}
return subnets, nil
}
// initDefaultSettings initializes default settings if nothing
// is configured
func (s *Server) initDefaultSettings() {
if len(s.conf.UpstreamDNS) == 0 {
s.conf.UpstreamDNS = defaultDNS
}
if len(s.conf.BootstrapDNS) == 0 {
s.conf.BootstrapDNS = defaultBootstrap
}
if s.conf.UDPListenAddrs == nil {
s.conf.UDPListenAddrs = defaultUDPListenAddrs
}
if s.conf.TCPListenAddrs == nil {
s.conf.TCPListenAddrs = defaultTCPListenAddrs
}
if len(s.conf.BlockedHosts) == 0 {
s.conf.BlockedHosts = defaultBlockedHosts
}
if s.conf.UpstreamTimeout == 0 {
s.conf.UpstreamTimeout = DefaultTimeout
}
}
// prepareIpsetListSettings reads and prepares the ipset configuration either
// from a file or from the data in the configuration file.
func (s *Server) prepareIpsetListSettings(ctx context.Context) (ipsets []string, err error) {
fn := s.conf.IpsetListFileName
if fn == "" {
return s.conf.IpsetList, nil
}
// #nosec G304 -- Trust the path explicitly given by the user.
data, err := os.ReadFile(fn)
if err != nil {
return nil, err
}
ipsets = stringutil.SplitTrimmed(string(data), "\n")
ipsets = slices.DeleteFunc(ipsets, aghnet.IsCommentOrEmpty)
s.logger.DebugContext(ctx, "using ipset rules from file", "num", len(ipsets), "file", fn)
return ipsets, nil
}
// loadUpstreams parses upstream DNS servers from the configured file or from
// the configuration itself. l must not be nil.
func (conf *ServerConfig) loadUpstreams(
ctx context.Context,
l *slog.Logger,
) (upstreams []string, err error) {
if conf.UpstreamDNSFileName == "" {
return stringutil.FilterOut(conf.UpstreamDNS, aghnet.IsCommentOrEmpty), nil
}
var data []byte
// #nosec G703 -- Trust the path explicitly given by the user.
data, err = os.ReadFile(conf.UpstreamDNSFileName)
if err != nil {
return nil, fmt.Errorf("reading upstream from file: %w", err)
}
upstreams = stringutil.SplitTrimmed(string(data), "\n")
l.DebugContext(
ctx,
"got upstreams",
"number", len(upstreams),
"filename", conf.UpstreamDNSFileName,
)
return stringutil.FilterOut(upstreams, aghnet.IsCommentOrEmpty), nil
}
// collectListenAddr adds addrPort to addrs. It also adds its port to
// unspecPorts if its address is unspecified.
func collectListenAddr(
addrPort netip.AddrPort,
addrs *container.MapSet[netip.AddrPort],
unspecPorts *container.MapSet[uint16],
) {
if addrPort == (netip.AddrPort{}) {
return
}
addrs.Add(addrPort)
if addrPort.Addr().IsUnspecified() {
unspecPorts.Add(addrPort.Port())
}
}
// collectDNSAddrs returns configured set of listening addresses. It also
// returns a set of ports of each unspecified listening address.
func (conf *ServerConfig) collectDNSAddrs() (
addrs *container.MapSet[netip.AddrPort],
unspecPorts *container.MapSet[uint16],
) {
addrs = container.NewMapSet[netip.AddrPort]()
unspecPorts = container.NewMapSet[uint16]()
for _, laddr := range conf.TCPListenAddrs {
collectListenAddr(laddr.AddrPort(), addrs, unspecPorts)
}
for _, laddr := range conf.UDPListenAddrs {
collectListenAddr(laddr.AddrPort(), addrs, unspecPorts)
}
return addrs, unspecPorts
}
// defaultPlainDNSPort is the default port for plain DNS.
const defaultPlainDNSPort uint16 = 53
// addrPortSet is a set of [netip.AddrPort] values.
type addrPortSet interface {
// Has returns true if addrPort is in the set.
Has(addrPort netip.AddrPort) (ok bool)
}
// type check
var _ addrPortSet = emptyAddrPortSet{}
// emptyAddrPortSet is the [addrPortSet] containing no values.
type emptyAddrPortSet struct{}
// Has implements the [addrPortSet] interface for [emptyAddrPortSet].
func (emptyAddrPortSet) Has(_ netip.AddrPort) (ok bool) { return false }
// combinedAddrPortSet is the [addrPortSet] defined by some IP addresses along
// with ports, any combination of which is considered being in the set.
type combinedAddrPortSet struct {
// TODO(e.burkov): Use container.SliceSet when available.
ports *container.MapSet[uint16]
addrs *container.MapSet[netip.Addr]
}
// type check
var _ addrPortSet = (*combinedAddrPortSet)(nil)
// Has implements the [addrPortSet] interface for [*combinedAddrPortSet].
func (m *combinedAddrPortSet) Has(addrPort netip.AddrPort) (ok bool) {
return m.ports.Has(addrPort.Port()) && m.addrs.Has(addrPort.Addr())
}
// filterOutAddrs filters out all the upstreams that match um. It returns all
// the closing errors joined.
func filterOutAddrs(upsConf *proxy.UpstreamConfig, set addrPortSet) (err error) {
var errs []error
delFunc := func(u upstream.Upstream) (ok bool) {
// TODO(e.burkov): We should probably consider the protocol of u to
// only filter out the listening addresses of the same protocol.
addr, parseErr := aghnet.ParseAddrPort(u.Address(), defaultPlainDNSPort)
if parseErr != nil || !set.Has(addr) {
// Don't filter out the upstream if it either cannot be parsed, or
// does not match m.
return false
}
errs = append(errs, u.Close())
return true
}
upsConf.Upstreams = slices.DeleteFunc(upsConf.Upstreams, delFunc)
for d, ups := range upsConf.DomainReservedUpstreams {
upsConf.DomainReservedUpstreams[d] = slices.DeleteFunc(ups, delFunc)
}
for d, ups := range upsConf.SpecifiedDomainUpstreams {
upsConf.SpecifiedDomainUpstreams[d] = slices.DeleteFunc(ups, delFunc)
}
return errors.Join(errs...)
}
// ourAddrsSet returns an addrPortSet that contains all the configured listening
// addresses. l must not be nil.
func (conf *ServerConfig) ourAddrsSet(
ctx context.Context,
l *slog.Logger,
) (m addrPortSet, err error) {
addrs, unspecPorts := conf.collectDNSAddrs()
switch {
case addrs.Len() == 0:
l.DebugContext(ctx, "no listen addresses")
return emptyAddrPortSet{}, nil
case unspecPorts.Len() == 0:
l.DebugContext(ctx, "filtering out addresses", "addresses", addrs)
return addrs, nil
default:
var ifaceAddrs []netip.Addr
ifaceAddrs, err = aghnet.CollectAllIfacesAddrs()
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
l.DebugContext(
ctx,
"filtering out addresses",
"addresses", ifaceAddrs,
"ports", unspecPorts,
)
return &combinedAddrPortSet{
ports: unspecPorts,
addrs: container.NewMapSet(ifaceAddrs...),
}, nil
}
}
// prepareDNSCrypt sets up the DNSCrypt configuration for the DNS proxy.
func (s *Server) prepareDNSCrypt(proxyConf *proxy.Config) {
dnsCryptConf := s.conf.TLSConf.DNSCryptConf
if dnsCryptConf == nil {
return
}
proxyConf.DNSCryptUDPListenAddr = dnsCryptConf.UDPListenAddrs
proxyConf.DNSCryptTCPListenAddr = dnsCryptConf.TCPListenAddrs
proxyConf.DNSCryptProviderName = dnsCryptConf.ProviderName
proxyConf.DNSCryptResolverCert = dnsCryptConf.ResolverCert
}
// prepareTLS sets up the TLS configuration for the DNS proxy.
func (s *Server) prepareTLS(ctx context.Context, proxyConf *proxy.Config) (err error) {
s.prepareDNSCrypt(proxyConf)
if s.conf.TLSConf.Cert == nil {
return nil
}
if s.conf.TLSConf.TLSListenAddrs == nil && s.conf.TLSConf.QUICListenAddrs == nil {
return nil
}
proxyConf.TLSListenAddr = s.conf.TLSConf.TLSListenAddrs
proxyConf.QUICListenAddr = s.conf.TLSConf.QUICListenAddrs
cert, err := x509.ParseCertificate(s.conf.TLSConf.Cert.Certificate[0])
if err != nil {
return fmt.Errorf("x509.ParseCertificate(): %w", err)
}
s.hasIPAddrs = aghtls.CertificateHasIP(cert)
if s.conf.TLSConf.StrictSNICheck {
if len(cert.DNSNames) != 0 {
s.dnsNames = cert.DNSNames
s.logger.DebugContext(
ctx,
"using certificate's SAN as DNS names",
"dns_names", cert.DNSNames,
)
slices.Sort(s.dnsNames)
} else {
s.dnsNames = []string{cert.Subject.CommonName}
s.logger.DebugContext(
ctx,
"using certificate's CN as DNS name",
"common_name",
cert.Subject.CommonName,
)
}
}
proxyConf.TLSConfig = &tls.Config{
GetCertificate: s.onGetCertificate,
CipherSuites: s.conf.TLSCiphers,
MinVersion: tls.VersionTLS12,
}
return nil
}
// isWildcard returns true if host is a wildcard hostname.
func isWildcard(host string) (ok bool) {
return strings.HasPrefix(host, "*.")
}
// matchesDomainWildcard returns true if host matches the domain wildcard
// pattern pat.
func matchesDomainWildcard(host, pat string) (ok bool) {
return isWildcard(pat) && strings.HasSuffix(host, pat[1:])
}
// anyNameMatches returns true if sni, the client's SNI value, matches any of
// the DNS names and patterns from certificate. dnsNames must be sorted.
func anyNameMatches(dnsNames []string, sni string) (ok bool) {
// Check sni is either a valid hostname or a valid IP address.
if !netutil.IsValidHostname(sni) && !netutil.IsValidIPString(sni) {
return false
}
if _, ok = slices.BinarySearch(dnsNames, sni); ok {
return true
}
for _, dn := range dnsNames {
if matchesDomainWildcard(sni, dn) {
return true
}
}
return false
}
// onGetCertificate is called by [tls] package when Client Hello is received. If
// the server name (from SNI) supplied by client is incorrect - we terminate the
// ongoing TLS handshake.
func (s *Server) onGetCertificate(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
if s.conf.TLSConf.StrictSNICheck && !anyNameMatches(s.dnsNames, ch.ServerName) {
// TODO(s.chzhen): Pass context.
s.logger.WarnContext(
context.TODO(),
"unknown SNI in Client Hello",
"server_name", ch.ServerName,
)
return nil, fmt.Errorf("invalid SNI")
}
return s.conf.TLSConf.Cert, nil
}
// preparePlain prepares the plain-DNS configuration for the DNS proxy. The
// method assumes that prepareTLS has already been called.
func (s *Server) preparePlain(ctx context.Context, proxyConf *proxy.Config) (err error) {
if s.conf.ServePlainDNS {
proxyConf.UDPListenAddr = s.conf.UDPListenAddrs
proxyConf.TCPListenAddr = s.conf.TCPListenAddrs
return nil
}
lenEncrypted := len(proxyConf.DNSCryptTCPListenAddr) +
len(proxyConf.DNSCryptUDPListenAddr) +
len(proxyConf.HTTPConfig.ListenAddresses) +
len(proxyConf.QUICListenAddr) +
len(proxyConf.TLSListenAddr)
if lenEncrypted == 0 {
// TODO(a.garipov): Support full disabling of all DNS.
return errors.Error("disabling plain dns requires at least one encrypted protocol")
}
s.logger.WarnContext(ctx, "plain dns is disabled")
return nil
}
// UpdatedProtectionStatus updates protection state, if the protection was
// disabled temporarily. Returns the updated state of protection.
func (s *Server) UpdatedProtectionStatus(
ctx context.Context,
) (enabled bool, disabledUntil *time.Time) {
s.serverLock.RLock()
defer s.serverLock.RUnlock()
enabled, disabledUntil = s.dnsFilter.ProtectionStatus()
if disabledUntil == nil {
return enabled, nil
}
if time.Now().Before(*disabledUntil) {
return false, disabledUntil
}
// Update the values in a separate goroutine, unless an update is already in
// progress. Since this method is called very often, and this update is a
// relatively rare situation, do not lock s.serverLock for writing, as that
// can lead to freezes.
//
// See https://github.com/AdguardTeam/AdGuardHome/issues/5661.
if s.protectionUpdateInProgress.CompareAndSwap(false, true) {
go s.enableProtectionAfterPause(ctx)
}
return true, nil
}
// enableProtectionAfterPause sets the protection configuration to enabled
// values. It is intended to be used as a goroutine.
func (s *Server) enableProtectionAfterPause(ctx context.Context) {
defer slogutil.RecoverAndLog(ctx, s.logger)
defer s.protectionUpdateInProgress.Store(false)
defer s.conf.ConfModifier.Apply(ctx)
s.serverLock.Lock()
defer s.serverLock.Unlock()
s.dnsFilter.SetProtectionStatus(true, nil)
s.logger.InfoContext(ctx, "protection is restarted after pause")
}
// validateCacheTTL returns an error if the configuration of the cache TTL
// invalid.
//
// TODO(s.chzhen): Move to dnsproxy.
func validateCacheTTL(minTTL, maxTTL uint32) (err error) {
if minTTL == 0 && maxTTL == 0 {
return nil
}
if maxTTL > 0 && minTTL > maxTTL {
return errors.Error("cache_ttl_min must be less than or equal to cache_ttl_max")
}
return nil
}