fc9ddcf941
Merge in DNS/adguard-home from 1383-client-id to master Updates #1383. Squashed commit of the following: commit ebe2678bfa9bf651a2cb1e64499b38edcf19a7ad Author: Ildar Kamalov <ik@adguard.com> Date: Wed Jan 27 17:51:59 2021 +0300 - client: check if IP is valid commit 0c330585a170ea149ee75e43dfa65211e057299c Author: Ildar Kamalov <ik@adguard.com> Date: Wed Jan 27 17:07:50 2021 +0300 - client: find clients by client_id commit 71c9593ee35d996846f061e114b7867c3aa3c978 Merge: 9104f1613e9edd9e
Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Wed Jan 27 16:09:45 2021 +0300 Merge branch 'master' into 1383-client-id commit 9104f1615d2d462606c52017df25a422df872cea Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Wed Jan 27 13:28:50 2021 +0300 dnsforward: imp tests commit ed47f26e611ade625a2cc2c2f71a291b796bbf8f Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Wed Jan 27 12:39:52 2021 +0300 dnsforward: fix address commit 98b222ba69a5d265f620c180c960d01c84a1fb3b Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 19:50:31 2021 +0300 home: imp code commit 4f3966548a2d8437d0b68207dd108dd1a6cb7d20 Merge: 199fdc05c215b820
Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 19:45:13 2021 +0300 Merge branch 'master' into 1383-client-id commit 199fdc056f8a8be5500584f3aaee32865188aedc Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 19:20:37 2021 +0300 all: imp tests, logging, etc commit 35ff14f4d534251aecb2ea60baba225f3eed8a3e Author: Ildar Kamalov <ik@adguard.com> Date: Tue Jan 26 18:55:19 2021 +0300 + client: remove block button from clients with client_id commit 32991a0b4c56583a02fb5e00bba95d96000bce20 Author: Ildar Kamalov <ik@adguard.com> Date: Tue Jan 26 18:54:25 2021 +0300 + client: add requests count for client_id commit 2d68df4d2eac4a296d7469923e601dad4575c1a1 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 15:49:50 2021 +0300 stats: handle client ids commit 4e14ab3590328f93a8cd6e9cbe1665baf74f220b Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 13:45:25 2021 +0300 openapi: fix example commit ca9cf3f744fe197cace2c28ddc5bc68f71dad1f3 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 13:37:10 2021 +0300 openapi: improve clients find api docs commit f79876e550c424558b704bc316a4cd04f25db011 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Jan 26 13:18:52 2021 +0300 home: accept ids in clients find commit 5b72595122aa0bd64debadfd753ed8a0e0840629 Merge: 607e241fabf8f65f
Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Mon Jan 25 18:34:56 2021 +0300 Merge branch 'master' into 1383-client-id commit 607e241f1c339dd6397218f70b8301e3de6a1ee0 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Mon Jan 25 18:30:39 2021 +0300 dnsforward: fix quic commit f046352fef93e46234c2bbe8ae316d21034260e5 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Mon Jan 25 16:53:09 2021 +0300 all: remove wildcard requirement commit 3b679489bae82c54177372be453fe184d8f0bab6 Author: Andrey Meshkov <am@adguard.com> Date: Mon Jan 25 16:02:28 2021 +0300 workDir now supports symlinks commit 0647ab4f113de2223f6949df001f42ecab05c995 Author: Ildar Kamalov <ik@adguard.com> Date: Mon Jan 25 14:59:46 2021 +0300 - client: remove wildcard from domain validation commit b1aec04a4ecadc9d65648ed6d284188fecce01c3 Author: Ildar Kamalov <ik@adguard.com> Date: Mon Jan 25 14:55:39 2021 +0300 + client: add form to download mobileconfig ... and 12 more commits
364 lines
13 KiB
Go
364 lines
13 KiB
Go
package dnsforward
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"errors"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net"
|
|
"net/http"
|
|
"sort"
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
|
|
"github.com/AdguardTeam/AdGuardHome/internal/util"
|
|
"github.com/AdguardTeam/dnsproxy/proxy"
|
|
"github.com/AdguardTeam/dnsproxy/upstream"
|
|
"github.com/AdguardTeam/golibs/log"
|
|
"github.com/ameshkov/dnscrypt/v2"
|
|
)
|
|
|
|
// FilteringConfig represents the DNS filtering configuration of AdGuard Home
|
|
// The zero FilteringConfig is empty and ready for use.
|
|
type FilteringConfig struct {
|
|
// Callbacks for other modules
|
|
// --
|
|
|
|
// FilterHandler is an optional additional filtering callback.
|
|
FilterHandler func(clientAddr net.IP, clientID string, settings *dnsfilter.RequestFilteringSettings) `yaml:"-"`
|
|
|
|
// GetCustomUpstreamByClient - a callback function that returns upstreams configuration
|
|
// based on the client IP address. Returns nil if there are no custom upstreams for the client
|
|
//
|
|
// TODO(e.burkov): Replace argument type with net.IP.
|
|
GetCustomUpstreamByClient func(clientAddr string) *proxy.UpstreamConfig `yaml:"-"`
|
|
|
|
// Protection configuration
|
|
// --
|
|
|
|
ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of dnsfilter features
|
|
BlockingMode string `yaml:"blocking_mode"` // mode how to answer filtered requests
|
|
BlockingIPv4 net.IP `yaml:"blocking_ipv4"` // IP address to be returned for a blocked A request
|
|
BlockingIPv6 net.IP `yaml:"blocking_ipv6"` // IP address to be returned for a blocked AAAA request
|
|
BlockedResponseTTL uint32 `yaml:"blocked_response_ttl"` // if 0, then default is used (3600)
|
|
|
|
// IP (or domain name) which is used to respond to DNS requests blocked by parental control or safe-browsing
|
|
ParentalBlockHost string `yaml:"parental_block_host"`
|
|
SafeBrowsingBlockHost string `yaml:"safebrowsing_block_host"`
|
|
|
|
// Anti-DNS amplification
|
|
// --
|
|
|
|
Ratelimit uint32 `yaml:"ratelimit"` // max number of requests per second from a given IP (0 to disable)
|
|
RatelimitWhitelist []string `yaml:"ratelimit_whitelist"` // a list of whitelisted client IP addresses
|
|
RefuseAny bool `yaml:"refuse_any"` // if true, refuse ANY requests
|
|
|
|
// Upstream DNS servers configuration
|
|
// --
|
|
|
|
UpstreamDNS []string `yaml:"upstream_dns"`
|
|
UpstreamDNSFileName string `yaml:"upstream_dns_file"`
|
|
BootstrapDNS []string `yaml:"bootstrap_dns"` // a list of bootstrap DNS for DoH and DoT (plain DNS only)
|
|
AllServers bool `yaml:"all_servers"` // if true, parallel queries to all configured upstream servers are enabled
|
|
FastestAddr bool `yaml:"fastest_addr"` // use Fastest Address algorithm
|
|
|
|
// Access settings
|
|
// --
|
|
|
|
AllowedClients []string `yaml:"allowed_clients"` // IP addresses of whitelist clients
|
|
DisallowedClients []string `yaml:"disallowed_clients"` // IP addresses of clients that should be blocked
|
|
BlockedHosts []string `yaml:"blocked_hosts"` // hosts that should be blocked
|
|
|
|
// DNS cache settings
|
|
// --
|
|
|
|
CacheSize uint32 `yaml:"cache_size"` // DNS cache size (in bytes)
|
|
CacheMinTTL uint32 `yaml:"cache_ttl_min"` // override TTL value (minimum) received from upstream server
|
|
CacheMaxTTL uint32 `yaml:"cache_ttl_max"` // override TTL value (maximum) received from upstream server
|
|
|
|
// Other settings
|
|
// --
|
|
|
|
BogusNXDomain []string `yaml:"bogus_nxdomain"` // transform responses with these IP addresses to NXDOMAIN
|
|
AAAADisabled bool `yaml:"aaaa_disabled"` // Respond with an empty answer to all AAAA requests
|
|
EnableDNSSEC bool `yaml:"enable_dnssec"` // Set DNSSEC flag in outcoming DNS request
|
|
EnableEDNSClientSubnet bool `yaml:"edns_client_subnet"` // Enable EDNS Client Subnet option
|
|
MaxGoroutines uint32 `yaml:"max_goroutines"` // Max. number of parallel goroutines for processing incoming requests
|
|
|
|
// IPSET configuration - add IP addresses of the specified domain names to an ipset list
|
|
// Syntax:
|
|
// "DOMAIN[,DOMAIN].../IPSET_NAME"
|
|
IPSETList []string `yaml:"ipset"`
|
|
}
|
|
|
|
// TLSConfig is the TLS configuration for HTTPS, DNS-over-HTTPS, and DNS-over-TLS
|
|
type TLSConfig struct {
|
|
TLSListenAddr *net.TCPAddr `yaml:"-" json:"-"`
|
|
QUICListenAddr *net.UDPAddr `yaml:"-" json:"-"`
|
|
|
|
// Reject connection if the client uses server name (in SNI) that doesn't match the certificate
|
|
StrictSNICheck bool `yaml:"strict_sni_check" json:"-"`
|
|
|
|
// PEM-encoded certificates chain
|
|
CertificateChain string `yaml:"certificate_chain" json:"certificate_chain"`
|
|
// PEM-encoded private key
|
|
PrivateKey string `yaml:"private_key" json:"private_key"`
|
|
|
|
CertificatePath string `yaml:"certificate_path" json:"certificate_path"`
|
|
PrivateKeyPath string `yaml:"private_key_path" json:"private_key_path"`
|
|
|
|
CertificateChainData []byte `yaml:"-" json:"-"`
|
|
PrivateKeyData []byte `yaml:"-" json:"-"`
|
|
|
|
// ServerName is the hostname of the server. Currently, it is only
|
|
// being used for client ID checking.
|
|
ServerName string `yaml:"-" json:"-"`
|
|
|
|
cert tls.Certificate
|
|
// DNS names from certificate (SAN) or CN value from Subject
|
|
dnsNames []string
|
|
}
|
|
|
|
// DNSCryptConfig is the DNSCrypt server configuration struct.
|
|
type DNSCryptConfig struct {
|
|
UDPListenAddr *net.UDPAddr
|
|
TCPListenAddr *net.TCPAddr
|
|
ProviderName string
|
|
ResolverCert *dnscrypt.Cert
|
|
Enabled bool
|
|
}
|
|
|
|
// ServerConfig represents server configuration.
|
|
// The zero ServerConfig is empty and ready for use.
|
|
type ServerConfig struct {
|
|
UDPListenAddr *net.UDPAddr // UDP listen address
|
|
TCPListenAddr *net.TCPAddr // TCP listen address
|
|
UpstreamConfig *proxy.UpstreamConfig // Upstream DNS servers config
|
|
OnDNSRequest func(d *proxy.DNSContext)
|
|
|
|
FilteringConfig
|
|
TLSConfig
|
|
DNSCryptConfig
|
|
TLSAllowUnencryptedDOH bool
|
|
|
|
TLSv12Roots *x509.CertPool // list of root CAs for TLSv1.2
|
|
TLSCiphers []uint16 // list of TLS ciphers to use
|
|
|
|
// Called when the configuration is changed by HTTP request
|
|
ConfigModified func()
|
|
|
|
// Register an HTTP handler
|
|
HTTPRegister func(string, string, func(http.ResponseWriter, *http.Request))
|
|
}
|
|
|
|
// if any of ServerConfig values are zero, then default values from below are used
|
|
var defaultValues = ServerConfig{
|
|
UDPListenAddr: &net.UDPAddr{Port: 53},
|
|
TCPListenAddr: &net.TCPAddr{Port: 53},
|
|
FilteringConfig: FilteringConfig{BlockedResponseTTL: 3600},
|
|
}
|
|
|
|
// createProxyConfig creates and validates configuration for the main proxy
|
|
func (s *Server) createProxyConfig() (proxy.Config, error) {
|
|
proxyConfig := proxy.Config{
|
|
UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
|
|
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr},
|
|
Ratelimit: int(s.conf.Ratelimit),
|
|
RatelimitWhitelist: s.conf.RatelimitWhitelist,
|
|
RefuseAny: s.conf.RefuseAny,
|
|
CacheMinTTL: s.conf.CacheMinTTL,
|
|
CacheMaxTTL: s.conf.CacheMaxTTL,
|
|
UpstreamConfig: s.conf.UpstreamConfig,
|
|
BeforeRequestHandler: s.beforeRequestHandler,
|
|
RequestHandler: s.handleDNSRequest,
|
|
EnableEDNSClientSubnet: s.conf.EnableEDNSClientSubnet,
|
|
MaxGoroutines: int(s.conf.MaxGoroutines),
|
|
}
|
|
|
|
if s.conf.CacheSize != 0 {
|
|
proxyConfig.CacheEnabled = true
|
|
proxyConfig.CacheSizeBytes = int(s.conf.CacheSize)
|
|
}
|
|
|
|
proxyConfig.UpstreamMode = proxy.UModeLoadBalance
|
|
if s.conf.AllServers {
|
|
proxyConfig.UpstreamMode = proxy.UModeParallel
|
|
} else if s.conf.FastestAddr {
|
|
proxyConfig.UpstreamMode = proxy.UModeFastestAddr
|
|
}
|
|
|
|
if len(s.conf.BogusNXDomain) > 0 {
|
|
for _, s := range s.conf.BogusNXDomain {
|
|
ip := net.ParseIP(s)
|
|
if ip == nil {
|
|
log.Error("Invalid bogus IP: %s", s)
|
|
} else {
|
|
proxyConfig.BogusNXDomain = append(proxyConfig.BogusNXDomain, ip)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TLS settings
|
|
err := s.prepareTLS(&proxyConfig)
|
|
if err != nil {
|
|
return proxyConfig, err
|
|
}
|
|
|
|
if s.conf.DNSCryptConfig.Enabled {
|
|
proxyConfig.DNSCryptUDPListenAddr = []*net.UDPAddr{s.conf.DNSCryptConfig.UDPListenAddr}
|
|
proxyConfig.DNSCryptTCPListenAddr = []*net.TCPAddr{s.conf.DNSCryptConfig.TCPListenAddr}
|
|
proxyConfig.DNSCryptProviderName = s.conf.DNSCryptConfig.ProviderName
|
|
proxyConfig.DNSCryptResolverCert = s.conf.DNSCryptConfig.ResolverCert
|
|
}
|
|
|
|
// Validate proxy config
|
|
if proxyConfig.UpstreamConfig == nil || len(proxyConfig.UpstreamConfig.Upstreams) == 0 {
|
|
return proxyConfig, errors.New("no default upstream servers configured")
|
|
}
|
|
|
|
return proxyConfig, 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 len(s.conf.ParentalBlockHost) == 0 {
|
|
s.conf.ParentalBlockHost = parentalBlockHost
|
|
}
|
|
if len(s.conf.SafeBrowsingBlockHost) == 0 {
|
|
s.conf.SafeBrowsingBlockHost = safeBrowsingBlockHost
|
|
}
|
|
if s.conf.UDPListenAddr == nil {
|
|
s.conf.UDPListenAddr = defaultValues.UDPListenAddr
|
|
}
|
|
if s.conf.TCPListenAddr == nil {
|
|
s.conf.TCPListenAddr = defaultValues.TCPListenAddr
|
|
}
|
|
if len(s.conf.BlockedHosts) == 0 {
|
|
s.conf.BlockedHosts = defaultBlockedHosts
|
|
}
|
|
}
|
|
|
|
// prepareUpstreamSettings - prepares upstream DNS server settings
|
|
func (s *Server) prepareUpstreamSettings() error {
|
|
// We're setting a customized set of RootCAs
|
|
// The reason is that Go default mechanism of loading TLS roots
|
|
// does not always work properly on some routers so we're
|
|
// loading roots manually and pass it here.
|
|
// See "util.LoadSystemRootCAs"
|
|
upstream.RootCAs = s.conf.TLSv12Roots
|
|
|
|
// See util.InitTLSCiphers -- removed unsafe ciphers
|
|
if len(s.conf.TLSCiphers) > 0 {
|
|
upstream.CipherSuites = s.conf.TLSCiphers
|
|
}
|
|
|
|
// Load upstreams either from the file, or from the settings
|
|
var upstreams []string
|
|
if s.conf.UpstreamDNSFileName != "" {
|
|
data, err := ioutil.ReadFile(s.conf.UpstreamDNSFileName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d := string(data)
|
|
for len(d) != 0 {
|
|
s := util.SplitNext(&d, '\n')
|
|
upstreams = append(upstreams, s)
|
|
}
|
|
log.Debug("DNS: using %d upstream servers from file %s", len(upstreams), s.conf.UpstreamDNSFileName)
|
|
} else {
|
|
upstreams = s.conf.UpstreamDNS
|
|
}
|
|
upstreams = filterOutComments(upstreams)
|
|
upstreamConfig, err := proxy.ParseUpstreamsConfig(upstreams, s.conf.BootstrapDNS, DefaultTimeout)
|
|
if err != nil {
|
|
return fmt.Errorf("dns: proxy.ParseUpstreamsConfig: %w", err)
|
|
}
|
|
|
|
if len(upstreamConfig.Upstreams) == 0 {
|
|
log.Info("Warning: no default upstream servers specified, using %v", defaultDNS)
|
|
uc, err := proxy.ParseUpstreamsConfig(defaultDNS, s.conf.BootstrapDNS, DefaultTimeout)
|
|
if err != nil {
|
|
return fmt.Errorf("dns: failed to parse default upstreams: %v", err)
|
|
}
|
|
upstreamConfig.Upstreams = uc.Upstreams
|
|
}
|
|
|
|
s.conf.UpstreamConfig = &upstreamConfig
|
|
return nil
|
|
}
|
|
|
|
// prepareIntlProxy - initializes DNS proxy that we use for internal DNS queries
|
|
func (s *Server) prepareIntlProxy() {
|
|
intlProxyConfig := proxy.Config{
|
|
CacheEnabled: true,
|
|
CacheSizeBytes: 4096,
|
|
UpstreamConfig: s.conf.UpstreamConfig,
|
|
}
|
|
s.internalProxy = &proxy.Proxy{Config: intlProxyConfig}
|
|
}
|
|
|
|
// prepareTLS - prepares TLS configuration for the DNS proxy
|
|
func (s *Server) prepareTLS(proxyConfig *proxy.Config) error {
|
|
if len(s.conf.CertificateChainData) == 0 || len(s.conf.PrivateKeyData) == 0 {
|
|
return nil
|
|
}
|
|
|
|
if s.conf.TLSListenAddr == nil &&
|
|
s.conf.QUICListenAddr == nil {
|
|
return nil
|
|
}
|
|
|
|
if s.conf.TLSListenAddr != nil {
|
|
proxyConfig.TLSListenAddr = []*net.TCPAddr{s.conf.TLSListenAddr}
|
|
}
|
|
|
|
if s.conf.QUICListenAddr != nil {
|
|
proxyConfig.QUICListenAddr = []*net.UDPAddr{s.conf.QUICListenAddr}
|
|
}
|
|
|
|
var err error
|
|
s.conf.cert, err = tls.X509KeyPair(s.conf.CertificateChainData, s.conf.PrivateKeyData)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to parse TLS keypair: %w", err)
|
|
}
|
|
|
|
if s.conf.StrictSNICheck {
|
|
x, err := x509.ParseCertificate(s.conf.cert.Certificate[0])
|
|
if err != nil {
|
|
return fmt.Errorf("x509.ParseCertificate(): %w", err)
|
|
}
|
|
if len(x.DNSNames) != 0 {
|
|
s.conf.dnsNames = x.DNSNames
|
|
log.Debug("DNS: using DNS names from certificate's SAN: %v", x.DNSNames)
|
|
sort.Strings(s.conf.dnsNames)
|
|
} else {
|
|
s.conf.dnsNames = append(s.conf.dnsNames, x.Subject.CommonName)
|
|
log.Debug("DNS: using DNS name from certificate's CN: %s", x.Subject.CommonName)
|
|
}
|
|
}
|
|
|
|
proxyConfig.TLSConfig = &tls.Config{
|
|
GetCertificate: s.onGetCertificate,
|
|
MinVersion: tls.VersionTLS12,
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// 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.StrictSNICheck && !matchDNSName(s.conf.dnsNames, ch.ServerName) {
|
|
log.Info("DNS: TLS: unknown SNI in Client Hello: %s", ch.ServerName)
|
|
return nil, fmt.Errorf("invalid SNI")
|
|
}
|
|
return &s.conf.cert, nil
|
|
}
|