-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathdns.go
More file actions
602 lines (513 loc) · 16.2 KB
/
dns.go
File metadata and controls
602 lines (513 loc) · 16.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
package home
import (
"context"
"crypto/tls"
"fmt"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/agh"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/querylog"
"github.com/AdguardTeam/AdGuardHome/internal/stats"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/netutil/urlutil"
"github.com/ameshkov/dnscrypt/v2"
yaml "go.yaml.in/yaml/v4"
)
// Default listening ports.
const (
defaultPortDNS uint16 = 53
defaultPortHTTP uint16 = 80
defaultPortHTTPS uint16 = 443
defaultPortQUIC uint16 = 853
defaultPortTLS uint16 = 853
)
// initDNS updates all the fields of the [globalContext] needed to initialize
// the DNS server and initializes it at last. It also must not be called unless
// [config] and [globalContext] are initialized. baseLogger, tlsMgr,
// confModifier, and httpReg must not be nil.
func initDNS(
ctx context.Context,
baseLogger *slog.Logger,
tlsMgr *tlsManager,
confModifier agh.ConfigModifier,
httpReg aghhttp.Registrar,
statsDir string,
querylogDir string,
) (err error) {
anonymizer := config.anonymizer()
statsConf := stats.Config{
Logger: baseLogger.With(slogutil.KeyPrefix, "stats"),
Filename: filepath.Join(statsDir, "stats.db"),
Limit: time.Duration(config.Stats.Interval),
ConfigModifier: confModifier,
HTTPReg: httpReg,
Enabled: config.Stats.Enabled,
ShouldCountClient: globalContext.clients.shouldCountClient,
}
engine, err := aghnet.NewIgnoreEngine(config.Stats.Ignored, config.Stats.IgnoredEnabled)
if err != nil {
return fmt.Errorf("statistics: ignored list: %w", err)
}
statsConf.Ignored = engine
globalContext.stats, err = stats.New(statsConf)
if err != nil {
return fmt.Errorf("init stats: %w", err)
}
conf := querylog.Config{
Logger: baseLogger.With(slogutil.KeyPrefix, "querylog"),
Anonymizer: anonymizer,
ConfigModifier: confModifier,
HTTPReg: httpReg,
FindClient: globalContext.clients.findMultiple,
BaseDir: querylogDir,
AnonymizeClientIP: config.DNS.AnonymizeClientIP,
RotationIvl: time.Duration(config.QueryLog.Interval),
MemSize: config.QueryLog.MemSize,
Enabled: config.QueryLog.Enabled,
FileEnabled: config.QueryLog.FileEnabled,
}
engine, err = aghnet.NewIgnoreEngine(config.QueryLog.Ignored, config.QueryLog.IgnoredEnabled)
if err != nil {
return fmt.Errorf("querylog: ignored list: %w", err)
}
conf.Ignored = engine
globalContext.queryLog, err = querylog.New(conf)
if err != nil {
return fmt.Errorf("init querylog: %w", err)
}
globalContext.filters, err = filtering.New(config.Filtering, nil)
if err != nil {
// Don't wrap the error, since it's informative enough as is.
return err
}
err = initDNSServer(
ctx,
globalContext.filters,
globalContext.stats,
globalContext.queryLog,
globalContext.dhcpServer,
anonymizer,
httpReg,
tlsMgr,
baseLogger,
confModifier,
)
if err != nil {
return fmt.Errorf("creating dns server: %w", err)
}
registerDoHHandlers(config.HTTPConfig.DoH.Routes)
return nil
}
// initDNSServer initializes the [context.dnsServer]. To only use the internal
// proxy, none of the arguments are required, but tlsMgr and l still must not be
// nil, in other cases all the arguments also must not be nil. It also must not
// be called unless [config] and [globalContext] are initialized.
//
// TODO(e.burkov): Use [dnsforward.DNSCreateParams] as a parameter.
func initDNSServer(
ctx context.Context,
filters *filtering.DNSFilter,
sts stats.Interface,
qlog querylog.QueryLog,
dhcpSrv dnsforward.DHCP,
anonymizer *aghnet.IPMut,
httpReg aghhttp.Registrar,
tlsMgr *tlsManager,
l *slog.Logger,
confModifier agh.ConfigModifier,
) (err error) {
globalContext.dnsServer, err = dnsforward.NewServer(dnsforward.DNSCreateParams{
Logger: l,
DNSFilter: filters,
Stats: sts,
QueryLog: qlog,
PrivateNets: parseSubnetSet(config.DNS.PrivateNets),
Anonymizer: anonymizer,
DHCPServer: dhcpSrv,
EtcHosts: globalContext.etcHosts,
LocalDomain: config.DHCP.LocalDomainName,
})
defer func() {
if err != nil {
closeDNSServer(ctx)
}
}()
if err != nil {
return fmt.Errorf("dnsforward.NewServer: %w", err)
}
globalContext.clients.clientChecker = globalContext.dnsServer
dnsConf, err := newServerConfig(
&config.DNS,
config.Clients.Sources,
tlsMgr.extendedTLSConfig(),
config.HTTPConfig.DoH,
tlsMgr,
httpReg,
globalContext.clients.storage,
confModifier,
)
if err != nil {
return fmt.Errorf("newServerConfig: %w", err)
}
// Try to prepare the server with disabled private RDNS resolution if it
// failed to prepare as is. See TODO on [dnsforward.PrivateRDNSError].
err = globalContext.dnsServer.Prepare(ctx, dnsConf)
if _, ok := errors.AsType[*dnsforward.PrivateRDNSError](err); ok {
l.WarnContext(ctx, "private rdns resolution failed; disabling", slogutil.KeyError, err)
dnsConf.UsePrivateRDNS = false
err = globalContext.dnsServer.Prepare(ctx, dnsConf)
}
if err != nil {
return fmt.Errorf("dnsServer.Prepare: %w", err)
}
return nil
}
// parseSubnetSet parses a slice of subnets. If the slice is empty, it returns
// a subnet set that matches all locally served networks, see
// [netutil.IsLocallyServed].
func parseSubnetSet(nets []netutil.Prefix) (s netutil.SubnetSet) {
switch len(nets) {
case 0:
// Use an optimized function-based matcher.
return netutil.SubnetSetFunc(netutil.IsLocallyServed)
case 1:
return nets[0].Prefix
default:
return netutil.SliceSubnetSet(netutil.UnembedPrefixes(nets))
}
}
// isRunning checks whether the DNS server is running.
func isRunning() (ok bool) {
return globalContext.dnsServer != nil && globalContext.dnsServer.IsRunning()
}
func ipsToTCPAddrs(ips []netip.Addr, port uint16) (tcpAddrs []*net.TCPAddr) {
if ips == nil {
return nil
}
tcpAddrs = make([]*net.TCPAddr, 0, len(ips))
for _, ip := range ips {
tcpAddrs = append(tcpAddrs, net.TCPAddrFromAddrPort(netip.AddrPortFrom(ip, port)))
}
return tcpAddrs
}
// ipsToAddrPorts converts a slice of [netip.Addr] into a slice of
// [netip.AddrPort] with the given port.
func ipsToAddrPorts(ips []netip.Addr, port uint16) (addrs []netip.AddrPort) {
if ips == nil {
return nil
}
addrs = make([]netip.AddrPort, 0, len(ips))
for _, ip := range ips {
addrs = append(addrs, netip.AddrPortFrom(ip, port))
}
return addrs
}
func ipsToUDPAddrs(ips []netip.Addr, port uint16) (udpAddrs []*net.UDPAddr) {
if ips == nil {
return nil
}
udpAddrs = make([]*net.UDPAddr, 0, len(ips))
for _, ip := range ips {
udpAddrs = append(udpAddrs, net.UDPAddrFromAddrPort(netip.AddrPortFrom(ip, port)))
}
return udpAddrs
}
// newServerConfig converts values from the configuration file into the internal
// DNS server configuration. All arguments must not be nil.
func newServerConfig(
dnsConf *dnsConfig,
clientSrcConf *clientSourcesConfig,
extTLSConf *tlsConfigSettings,
dohConf *doHConfig,
tlsMgr *tlsManager,
httpReg aghhttp.Registrar,
clientsContainer dnsforward.ClientsContainer,
confModifier agh.ConfigModifier,
) (newConf *dnsforward.ServerConfig, err error) {
hosts := aghalg.CoalesceSlice(dnsConf.BindHosts, []netip.Addr{netutil.IPv4Localhost()})
fwdConf := dnsConf.Config
fwdConf.ClientsContainer = clientsContainer
intTLSConf, err := newDNSTLSConfig(extTLSConf, hosts, dohConf.InsecureEnabled)
if err != nil {
return nil, fmt.Errorf("constructing tls config: %w", err)
}
newConf = &dnsforward.ServerConfig{
UDPListenAddrs: ipsToUDPAddrs(hosts, dnsConf.Port),
TCPListenAddrs: ipsToTCPAddrs(hosts, dnsConf.Port),
Config: fwdConf,
TLSConf: intTLSConf,
TLSAllowUnencryptedDoH: dohConf.InsecureEnabled,
UpstreamTimeout: time.Duration(dnsConf.UpstreamTimeout),
TLSv12Roots: tlsMgr.rootCerts,
ConfModifier: confModifier,
HTTPReg: httpReg,
LocalPTRResolvers: dnsConf.PrivateRDNSResolvers,
UseDNS64: dnsConf.UseDNS64,
DNS64Prefixes: dnsConf.DNS64Prefixes,
UsePrivateRDNS: dnsConf.UsePrivateRDNS,
ServeHTTP3: dnsConf.ServeHTTP3,
UseHTTP3Upstreams: dnsConf.UseHTTP3Upstreams,
ServePlainDNS: dnsConf.ServePlainDNS,
PendingRequestsEnabled: dnsConf.PendingRequests.Enabled,
}
var initialAddresses []netip.Addr
// Context.stats may be nil here if initDNSServer is called from
// [cmdlineUpdate].
if sts := globalContext.stats; sts != nil {
const initialClientsNum = 100
initialAddresses = globalContext.stats.TopClientsIP(initialClientsNum)
}
// Do not set DialContext, PrivateSubnets, and UsePrivateRDNS, because they
// are set by [dnsforward.Server.Prepare].
newConf.AddrProcConf = &client.DefaultAddrProcConfig{
Exchanger: globalContext.dnsServer,
AddressUpdater: &globalContext.clients,
InitialAddresses: initialAddresses,
CatchPanics: true,
UseRDNS: clientSrcConf.RDNS,
UseWHOIS: clientSrcConf.WHOIS,
}
return newConf, nil
}
// newDNSTLSConfig converts values from the configuration file into the internal
// TLS settings for the DNS server. extTLSConf must not be nil.
func newDNSTLSConfig(
extTLSConf *tlsConfigSettings,
addrs []netip.Addr,
allowUnencryptedDoH bool,
) (dnsConf *dnsforward.TLSConfig, err error) {
if !extTLSConf.Enabled {
return &dnsforward.TLSConfig{}, nil
}
// TODO(e.burkov): Add tracking for DNSCrypt configuration file changes to
// the [aghtls.Manager].
dnsCryptConf, err := newDNSCryptConfig(extTLSConf, addrs)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, err
}
dnsConf = &dnsforward.TLSConfig{
DNSCryptConf: dnsCryptConf,
ServerName: extTLSConf.ServerName,
StrictSNICheck: extTLSConf.StrictSNICheck,
}
if extTLSConf.PortHTTPS != 0 {
dnsConf.HTTPSListenAddrs = ipsToAddrPorts(addrs, extTLSConf.PortHTTPS)
}
if extTLSConf.PortDNSOverTLS != 0 {
dnsConf.TLSListenAddrs = ipsToTCPAddrs(addrs, extTLSConf.PortDNSOverTLS)
}
if extTLSConf.PortDNSOverQUIC != 0 {
dnsConf.QUICListenAddrs = ipsToUDPAddrs(addrs, extTLSConf.PortDNSOverQUIC)
}
cert, err := tls.X509KeyPair(extTLSConf.CertificateChainData, extTLSConf.PrivateKeyData)
if err != nil {
err = fmt.Errorf("parsing tls key pair: %w", err)
if allowUnencryptedDoH || dnsCryptConf != nil {
// TODO(s.chzhen): Use [slog.Logger].
log.Info("warning: %s", err)
return dnsConf, nil
}
// Don't wrap the error, because it's already annotated.
return nil, err
}
dnsConf.Cert = &cert
return dnsConf, nil
}
// newDNSCryptConfig converts values from the configuration file into the
// internal DNSCrypt settings for the DNS server. extTLSConf must not be nil.
func newDNSCryptConfig(
extTLSConf *tlsConfigSettings,
addrs []netip.Addr,
) (dnsCryptConf *dnsforward.DNSCryptConfig, err error) {
if extTLSConf.PortDNSCrypt == 0 {
return nil, nil
}
if extTLSConf.DNSCryptConfigFile == "" {
return nil, fmt.Errorf("dnscrypt_config_file: %w", errors.ErrEmptyValue)
}
f, err := os.Open(extTLSConf.DNSCryptConfigFile)
if err != nil {
return nil, fmt.Errorf("opening dnscrypt config: %w", err)
}
defer func() { err = errors.WithDeferred(err, f.Close()) }()
rc := &dnscrypt.ResolverConfig{}
err = yaml.NewDecoder(f).Decode(rc)
if err != nil {
return nil, fmt.Errorf("decoding dnscrypt config: %w", err)
}
cert, err := rc.CreateCert()
if err != nil {
return nil, fmt.Errorf("creating dnscrypt cert: %w", err)
}
return &dnsforward.DNSCryptConfig{
ResolverCert: cert,
UDPListenAddrs: ipsToUDPAddrs(addrs, extTLSConf.PortDNSCrypt),
TCPListenAddrs: ipsToTCPAddrs(addrs, extTLSConf.PortDNSCrypt),
ProviderName: rc.ProviderName,
}, nil
}
// dnsEncryption contains different types of TLS encryption addresses.
type dnsEncryption struct {
https string
tls string
quic string
}
// getDNSEncryption returns the TLS encryption addresses that AdGuard Home
// listens on. tlsMgr must not be nil.
func getDNSEncryption(tlsMgr *tlsManager) (de dnsEncryption) {
extTLSConf := tlsMgr.extendedTLSConfig()
if !extTLSConf.Enabled || extTLSConf.ServerName == "" {
return dnsEncryption{}
}
hostname := extTLSConf.ServerName
if extTLSConf.PortHTTPS != 0 {
addr := hostname
if p := extTLSConf.PortHTTPS; p != defaultPortHTTPS {
addr = netutil.JoinHostPort(addr, p)
}
de.https = (&url.URL{
Scheme: urlutil.SchemeHTTPS,
Host: addr,
Path: "/dns-query",
}).String()
}
if p := extTLSConf.PortDNSOverTLS; p != 0 {
de.tls = (&url.URL{
Scheme: "tls",
Host: netutil.JoinHostPort(hostname, p),
}).String()
}
if p := extTLSConf.PortDNSOverQUIC; p != 0 {
de.quic = (&url.URL{
Scheme: "quic",
Host: netutil.JoinHostPort(hostname, p),
}).String()
}
return de
}
// startDNSServer starts the DNS server, clients container, filters, stats and
// the query log.
func startDNSServer() (err error) {
config.RLock()
defer config.RUnlock()
if isRunning() {
return fmt.Errorf("unable to start forwarding DNS server: Already running")
}
globalContext.filters.EnableFilters(false)
// TODO(s.chzhen): Pass context.
ctx := context.TODO()
err = globalContext.clients.Start(ctx)
if err != nil {
return fmt.Errorf("starting clients container: %w", err)
}
err = globalContext.dnsServer.Start(ctx)
if err != nil {
return fmt.Errorf("starting dns server: %w", err)
}
globalContext.filters.Start()
globalContext.stats.Start()
err = globalContext.queryLog.Start(ctx)
if err != nil {
return fmt.Errorf("starting query log: %w", err)
}
return nil
}
func stopDNSServer(ctx context.Context) (err error) {
if !isRunning() {
return nil
}
err = globalContext.dnsServer.Stop(ctx)
if err != nil {
return fmt.Errorf("stopping forwarding dns server: %w", err)
}
err = globalContext.clients.close(ctx)
if err != nil {
return fmt.Errorf("closing clients container: %w", err)
}
closeDNSServer(ctx)
return nil
}
func closeDNSServer(ctx context.Context) {
// DNS forward module must be closed BEFORE stats or queryLog because it depends on them
if globalContext.dnsServer != nil {
globalContext.dnsServer.Close(ctx)
globalContext.dnsServer = nil
}
if globalContext.filters != nil {
globalContext.filters.Close()
}
if globalContext.stats != nil {
err := globalContext.stats.Close()
if err != nil {
log.Error("closing stats: %s", err)
}
}
if globalContext.queryLog != nil {
err := globalContext.queryLog.Shutdown(ctx)
if err != nil {
log.Error("closing query log: %s", err)
}
}
log.Debug("all dns modules are closed")
}
// checkStatsAndQuerylogDirs checks and returns directory paths to store
// statistics and query log.
func checkStatsAndQuerylogDirs(
conf *configuration,
workDir string,
) (statsDir, querylogDir string, err error) {
baseDir := filepath.Join(workDir, dataDir)
statsDir = conf.Stats.DirPath
if statsDir == "" {
statsDir = baseDir
} else {
err = checkDir(statsDir)
if err != nil {
return "", "", fmt.Errorf("statistics: custom directory: %w", err)
}
}
querylogDir = conf.QueryLog.DirPath
if querylogDir == "" {
querylogDir = baseDir
} else {
err = checkDir(querylogDir)
if err != nil {
return "", "", fmt.Errorf("querylog: custom directory: %w", err)
}
}
return statsDir, querylogDir, nil
}
// checkDir checks if the path is a directory. It's used to check for
// misconfiguration at startup.
func checkDir(path string) (err error) {
var fi os.FileInfo
if fi, err = os.Stat(path); err != nil {
// Don't wrap the error, since it's informative enough as is.
return err
}
if !fi.IsDir() {
return fmt.Errorf("%q is not a directory", path)
}
return nil
}
// registerDoHHandlers registers DoH handlers on the given routes.
func registerDoHHandlers(routes []string) {
for _, route := range routes {
globalContext.web.conf.mux.Handle(route, globalContext.dnsServer)
}
}