2018-11-28 12:40:56 +00:00
|
|
|
package dnsforward
|
|
|
|
|
|
|
|
import (
|
2019-02-12 14:23:38 +00:00
|
|
|
"crypto/tls"
|
2020-01-22 15:40:43 +00:00
|
|
|
"crypto/x509"
|
2019-10-30 08:52:58 +00:00
|
|
|
"fmt"
|
2018-11-28 12:40:56 +00:00
|
|
|
"net"
|
2019-02-22 12:52:12 +00:00
|
|
|
"net/http"
|
2019-10-21 12:58:14 +00:00
|
|
|
"runtime"
|
2020-01-22 15:40:43 +00:00
|
|
|
"sort"
|
2018-11-30 10:17:34 +00:00
|
|
|
"strings"
|
2018-11-28 12:40:56 +00:00
|
|
|
"sync"
|
2018-12-05 11:03:41 +00:00
|
|
|
"time"
|
2018-11-28 12:40:56 +00:00
|
|
|
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/dnsfilter"
|
2019-08-26 08:54:38 +00:00
|
|
|
"github.com/AdguardTeam/AdGuardHome/querylog"
|
2019-08-22 13:34:58 +00:00
|
|
|
"github.com/AdguardTeam/AdGuardHome/stats"
|
2018-12-24 13:58:48 +00:00
|
|
|
"github.com/AdguardTeam/dnsproxy/proxy"
|
|
|
|
"github.com/AdguardTeam/dnsproxy/upstream"
|
2019-02-25 13:44:22 +00:00
|
|
|
"github.com/AdguardTeam/golibs/log"
|
2020-01-22 15:40:43 +00:00
|
|
|
"github.com/AdguardTeam/golibs/utils"
|
2018-11-28 12:40:56 +00:00
|
|
|
"github.com/joomcode/errorx"
|
|
|
|
"github.com/miekg/dns"
|
2018-12-24 12:19:52 +00:00
|
|
|
)
|
|
|
|
|
2018-12-24 22:59:38 +00:00
|
|
|
// DefaultTimeout is the default upstream timeout
|
|
|
|
const DefaultTimeout = 10 * time.Second
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
const (
|
|
|
|
safeBrowsingBlockHost = "standard-block.dns.adguard.com"
|
|
|
|
parentalBlockHost = "family-block.dns.adguard.com"
|
2018-11-28 12:40:56 +00:00
|
|
|
)
|
|
|
|
|
2019-10-31 09:32:14 +00:00
|
|
|
var defaultDNS = []string{
|
2019-10-31 09:43:33 +00:00
|
|
|
"https://dns.quad9.net/dns-query",
|
2019-10-31 09:32:14 +00:00
|
|
|
}
|
2019-10-31 09:43:33 +00:00
|
|
|
var defaultBootstrap = []string{"9.9.9.9", "149.112.112.112"}
|
2019-10-31 09:32:14 +00:00
|
|
|
|
2020-01-16 11:25:40 +00:00
|
|
|
var webRegistered bool
|
|
|
|
|
2018-12-05 09:52:23 +00:00
|
|
|
// Server is the main way to start a DNS server.
|
|
|
|
//
|
2018-11-28 12:40:56 +00:00
|
|
|
// Example:
|
2018-12-05 09:52:23 +00:00
|
|
|
// s := dnsforward.Server{}
|
|
|
|
// err := s.Start(nil) // will start a DNS server listening on default port 53, in a goroutine
|
|
|
|
// err := s.Reconfigure(ServerConfig{UDPListenAddr: &net.UDPAddr{Port: 53535}}) // will reconfigure running DNS server to listen on UDP port 53535
|
|
|
|
// err := s.Stop() // will stop listening on port 53535 and cancel all goroutines
|
|
|
|
// err := s.Start(nil) // will start listening again, on port 53535, in a goroutine
|
2018-11-28 12:40:56 +00:00
|
|
|
//
|
|
|
|
// The zero Server is empty and ready for use.
|
|
|
|
type Server struct {
|
2019-02-10 17:47:43 +00:00
|
|
|
dnsProxy *proxy.Proxy // DNS proxy instance
|
2018-12-24 12:19:52 +00:00
|
|
|
dnsFilter *dnsfilter.Dnsfilter // DNS filter instance
|
2019-08-26 08:54:38 +00:00
|
|
|
queryLog querylog.QueryLog // Query log instance
|
2019-08-22 13:34:58 +00:00
|
|
|
stats stats.Stats
|
2019-10-30 12:11:16 +00:00
|
|
|
access *accessCtx
|
2019-05-24 11:49:26 +00:00
|
|
|
|
2019-12-11 09:38:58 +00:00
|
|
|
// DNS proxy instance for internal usage
|
|
|
|
// We don't Start() it and so no listen port is required.
|
|
|
|
internalProxy *proxy.Proxy
|
|
|
|
|
2020-01-16 11:25:40 +00:00
|
|
|
isRunning bool
|
2019-10-30 08:52:58 +00:00
|
|
|
|
2018-11-28 12:40:56 +00:00
|
|
|
sync.RWMutex
|
2019-05-15 12:08:15 +00:00
|
|
|
conf ServerConfig
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2019-02-10 17:47:43 +00:00
|
|
|
// NewServer creates a new instance of the dnsforward.Server
|
2019-07-10 08:56:54 +00:00
|
|
|
// Note: this function must be called only once
|
2019-10-09 16:51:26 +00:00
|
|
|
func NewServer(dnsFilter *dnsfilter.Dnsfilter, stats stats.Stats, queryLog querylog.QueryLog) *Server {
|
2019-08-26 08:54:38 +00:00
|
|
|
s := &Server{}
|
2019-10-09 16:51:26 +00:00
|
|
|
s.dnsFilter = dnsFilter
|
2019-08-22 13:34:58 +00:00
|
|
|
s.stats = stats
|
2019-08-26 08:54:38 +00:00
|
|
|
s.queryLog = queryLog
|
2019-10-31 09:32:14 +00:00
|
|
|
|
|
|
|
if runtime.GOARCH == "mips" || runtime.GOARCH == "mipsle" {
|
|
|
|
// Use plain DNS on MIPS, encryption is too slow
|
2019-10-31 09:43:33 +00:00
|
|
|
defaultDNS = defaultBootstrap
|
2019-10-31 09:32:14 +00:00
|
|
|
}
|
2019-07-10 08:56:54 +00:00
|
|
|
return s
|
2019-02-10 17:47:43 +00:00
|
|
|
}
|
|
|
|
|
2019-10-30 08:52:58 +00:00
|
|
|
// Close - close object
|
2019-09-16 12:54:41 +00:00
|
|
|
func (s *Server) Close() {
|
|
|
|
s.Lock()
|
2019-10-09 16:51:26 +00:00
|
|
|
s.dnsFilter = nil
|
2019-09-16 12:54:41 +00:00
|
|
|
s.stats = nil
|
|
|
|
s.queryLog = nil
|
2019-12-11 09:38:58 +00:00
|
|
|
s.dnsProxy = nil
|
2019-09-16 12:54:41 +00:00
|
|
|
s.Unlock()
|
|
|
|
}
|
|
|
|
|
2019-12-12 12:04:29 +00:00
|
|
|
func stringArrayDup(a []string) []string {
|
|
|
|
a2 := make([]string, len(a))
|
|
|
|
copy(a2, a)
|
|
|
|
return a2
|
|
|
|
}
|
|
|
|
|
2019-10-30 08:52:58 +00:00
|
|
|
// WriteDiskConfig - write configuration
|
|
|
|
func (s *Server) WriteDiskConfig(c *FilteringConfig) {
|
2019-12-17 10:09:03 +00:00
|
|
|
s.RLock()
|
2019-12-12 12:04:29 +00:00
|
|
|
sc := s.conf.FilteringConfig
|
|
|
|
*c = sc
|
|
|
|
c.RatelimitWhitelist = stringArrayDup(sc.RatelimitWhitelist)
|
|
|
|
c.BootstrapDNS = stringArrayDup(sc.BootstrapDNS)
|
|
|
|
c.AllowedClients = stringArrayDup(sc.AllowedClients)
|
|
|
|
c.DisallowedClients = stringArrayDup(sc.DisallowedClients)
|
|
|
|
c.BlockedHosts = stringArrayDup(sc.BlockedHosts)
|
|
|
|
c.UpstreamDNS = stringArrayDup(sc.UpstreamDNS)
|
2019-12-17 10:09:03 +00:00
|
|
|
s.RUnlock()
|
2019-10-30 08:52:58 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// FilteringConfig represents the DNS filtering configuration of AdGuard Home
|
2019-02-12 14:23:38 +00:00
|
|
|
// The zero FilteringConfig is empty and ready for use.
|
2018-11-28 15:24:04 +00:00
|
|
|
type FilteringConfig struct {
|
2019-10-09 16:51:26 +00:00
|
|
|
// Filtering callback function
|
|
|
|
FilterHandler func(clientAddr string, settings *dnsfilter.RequestFilteringSettings) `yaml:"-"`
|
2019-09-20 10:48:22 +00:00
|
|
|
|
2019-11-06 14:24:15 +00:00
|
|
|
// This callback function returns the list of upstream servers for a client specified by IP address
|
2019-12-23 16:31:27 +00:00
|
|
|
GetUpstreamsByClient func(clientAddr string) []upstream.Upstream `yaml:"-"`
|
2019-11-06 14:24:15 +00:00
|
|
|
|
2019-10-30 08:52:58 +00:00
|
|
|
ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of dnsfilter features
|
2019-09-04 11:12:00 +00:00
|
|
|
|
2019-11-08 13:19:56 +00:00
|
|
|
BlockingMode string `yaml:"blocking_mode"` // mode how to answer filtered requests
|
|
|
|
BlockingIPv4 string `yaml:"blocking_ipv4"` // IP address to be returned for a blocked A request
|
|
|
|
BlockingIPv6 string `yaml:"blocking_ipv6"` // IP address to be returned for a blocked AAAA request
|
|
|
|
BlockingIPAddrv4 net.IP `yaml:"-"`
|
|
|
|
BlockingIPAddrv6 net.IP `yaml:"-"`
|
|
|
|
|
2018-12-05 15:47:03 +00:00
|
|
|
BlockedResponseTTL uint32 `yaml:"blocked_response_ttl"` // if 0, then default is used (3600)
|
2019-11-08 11:59:12 +00:00
|
|
|
Ratelimit uint32 `yaml:"ratelimit"` // max number of requests per second from a given IP (0 to disable)
|
2019-02-28 10:40:40 +00:00
|
|
|
RatelimitWhitelist []string `yaml:"ratelimit_whitelist"` // a list of whitelisted client IP addresses
|
|
|
|
RefuseAny bool `yaml:"refuse_any"` // if true, refuse ANY requests
|
|
|
|
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
|
2018-11-30 10:35:22 +00:00
|
|
|
|
2019-11-12 16:45:55 +00:00
|
|
|
EnableEDNSClientSubnet bool `yaml:"edns_client_subnet"` // Enable EDNS Client Subnet option
|
|
|
|
|
2019-11-11 16:34:47 +00:00
|
|
|
// Respond with an empty answer to all AAAA requests
|
|
|
|
AAAADisabled bool `yaml:"aaaa_disabled"`
|
|
|
|
|
2019-05-24 11:49:26 +00:00
|
|
|
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
|
|
|
|
|
2019-07-22 09:16:30 +00:00
|
|
|
// 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"`
|
|
|
|
|
2019-10-30 08:52:58 +00:00
|
|
|
CacheSize uint `yaml:"cache_size"` // DNS cache size (in bytes)
|
|
|
|
UpstreamDNS []string `yaml:"upstream_dns"`
|
2018-11-28 15:24:04 +00:00
|
|
|
}
|
|
|
|
|
2019-02-22 12:23:39 +00:00
|
|
|
// TLSConfig is the TLS configuration for HTTPS, DNS-over-HTTPS, and DNS-over-TLS
|
2019-02-12 14:23:38 +00:00
|
|
|
type TLSConfig struct {
|
|
|
|
TLSListenAddr *net.TCPAddr `yaml:"-" json:"-"`
|
2020-01-22 15:40:43 +00:00
|
|
|
StrictSNICheck bool `yaml:"strict_sni_check" json:"-"` // Reject connection if the client uses server name (in SNI) that doesn't match the certificate
|
2019-02-21 14:48:18 +00:00
|
|
|
CertificateChain string `yaml:"certificate_chain" json:"certificate_chain"` // PEM-encoded certificates chain
|
|
|
|
PrivateKey string `yaml:"private_key" json:"private_key"` // PEM-encoded private key
|
2019-08-13 09:32:52 +00:00
|
|
|
|
|
|
|
CertificatePath string `yaml:"certificate_path" json:"certificate_path"` // certificate file name
|
|
|
|
PrivateKeyPath string `yaml:"private_key_path" json:"private_key_path"` // private key file name
|
|
|
|
|
2019-12-13 14:38:17 +00:00
|
|
|
CertificateChainData []byte `yaml:"-" json:"-"`
|
|
|
|
PrivateKeyData []byte `yaml:"-" json:"-"`
|
2020-01-22 15:40:43 +00:00
|
|
|
|
|
|
|
cert tls.Certificate // nolint(structcheck) - linter thinks that this field is unused, while TLSConfig is directly included into ServerConfig
|
|
|
|
dnsNames []string // nolint(structcheck) // DNS names from certificate (SAN) or CN value from Subject
|
2019-02-12 14:23:38 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// ServerConfig represents server configuration.
|
2018-11-28 12:40:56 +00:00
|
|
|
// The zero ServerConfig is empty and ready for use.
|
|
|
|
type ServerConfig struct {
|
2019-03-20 11:24:33 +00:00
|
|
|
UDPListenAddr *net.UDPAddr // UDP listen address
|
|
|
|
TCPListenAddr *net.TCPAddr // TCP listen address
|
|
|
|
Upstreams []upstream.Upstream // Configured upstreams
|
|
|
|
DomainsReservedUpstreams map[string][]upstream.Upstream // Map of domains and lists of configured upstreams
|
2019-05-21 11:53:13 +00:00
|
|
|
OnDNSRequest func(d *proxy.DNSContext)
|
2018-11-28 15:24:04 +00:00
|
|
|
|
|
|
|
FilteringConfig
|
2019-02-12 14:23:38 +00:00
|
|
|
TLSConfig
|
2019-10-30 08:52:58 +00:00
|
|
|
|
|
|
|
// Called when the configuration is changed by HTTP request
|
|
|
|
ConfigModified func()
|
|
|
|
|
|
|
|
// Register an HTTP handler
|
|
|
|
HTTPRegister func(string, string, func(http.ResponseWriter, *http.Request))
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2018-12-05 15:47:03 +00:00
|
|
|
// if any of ServerConfig values are zero, then default values from below are used
|
2018-11-28 12:40:56 +00:00
|
|
|
var defaultValues = ServerConfig{
|
2018-11-30 10:35:22 +00:00
|
|
|
UDPListenAddr: &net.UDPAddr{Port: 53},
|
2019-01-05 19:15:20 +00:00
|
|
|
TCPListenAddr: &net.TCPAddr{Port: 53},
|
2018-11-30 10:35:22 +00:00
|
|
|
FilteringConfig: FilteringConfig{BlockedResponseTTL: 3600},
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2019-12-11 09:38:58 +00:00
|
|
|
// Resolve - get IP addresses by host name from an upstream server.
|
|
|
|
// No request/response filtering is performed.
|
|
|
|
// Query log and Stats are not updated.
|
|
|
|
// This method may be called before Start().
|
|
|
|
func (s *Server) Resolve(host string) ([]net.IPAddr, error) {
|
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
|
|
|
return s.internalProxy.LookupIPAddr(host)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Exchange - send DNS request to an upstream server and receive response
|
|
|
|
// No request/response filtering is performed.
|
|
|
|
// Query log and Stats are not updated.
|
|
|
|
// This method may be called before Start().
|
|
|
|
func (s *Server) Exchange(req *dns.Msg) (*dns.Msg, error) {
|
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
|
|
|
|
|
|
|
ctx := &proxy.DNSContext{
|
|
|
|
Proto: "udp",
|
|
|
|
Req: req,
|
|
|
|
StartTime: time.Now(),
|
|
|
|
}
|
|
|
|
err := s.internalProxy.Resolve(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return ctx.Res, nil
|
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// Start starts the DNS server
|
2019-12-11 09:38:58 +00:00
|
|
|
func (s *Server) Start() error {
|
2018-11-28 12:40:56 +00:00
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2019-12-11 09:38:58 +00:00
|
|
|
return s.startInternal()
|
2018-12-24 12:19:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// startInternal starts without locking
|
2019-12-11 09:38:58 +00:00
|
|
|
func (s *Server) startInternal() error {
|
|
|
|
err := s.dnsProxy.Start()
|
|
|
|
if err == nil {
|
|
|
|
s.isRunning = true
|
2019-11-21 13:13:19 +00:00
|
|
|
}
|
2019-12-11 09:38:58 +00:00
|
|
|
return err
|
2019-11-21 13:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare the object
|
2020-01-22 15:40:43 +00:00
|
|
|
// nolint(gocyclo)
|
2019-12-11 09:38:58 +00:00
|
|
|
func (s *Server) Prepare(config *ServerConfig) error {
|
2019-10-09 16:51:26 +00:00
|
|
|
if config != nil {
|
|
|
|
s.conf = *config
|
2019-12-16 14:04:30 +00:00
|
|
|
if s.conf.BlockingMode == "custom_ip" {
|
|
|
|
s.conf.BlockingIPAddrv4 = net.ParseIP(s.conf.BlockingIPv4)
|
|
|
|
s.conf.BlockingIPAddrv6 = net.ParseIP(s.conf.BlockingIPv6)
|
|
|
|
if s.conf.BlockingIPAddrv4 == nil || s.conf.BlockingIPAddrv6 == nil {
|
|
|
|
return fmt.Errorf("DNS: invalid custom blocking IP address specified")
|
|
|
|
}
|
|
|
|
}
|
2019-10-31 09:32:14 +00:00
|
|
|
}
|
2019-10-30 08:52:58 +00:00
|
|
|
|
2019-10-31 09:32:14 +00:00
|
|
|
if len(s.conf.UpstreamDNS) == 0 {
|
|
|
|
s.conf.UpstreamDNS = defaultDNS
|
2019-10-09 16:51:26 +00:00
|
|
|
}
|
2019-10-31 09:32:14 +00:00
|
|
|
if len(s.conf.BootstrapDNS) == 0 {
|
|
|
|
s.conf.BootstrapDNS = defaultBootstrap
|
|
|
|
}
|
|
|
|
|
|
|
|
upstreamConfig, err := proxy.ParseUpstreamsConfig(s.conf.UpstreamDNS, s.conf.BootstrapDNS, DefaultTimeout)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("DNS: proxy.ParseUpstreamsConfig: %s", err)
|
|
|
|
}
|
|
|
|
s.conf.Upstreams = upstreamConfig.Upstreams
|
|
|
|
s.conf.DomainsReservedUpstreams = upstreamConfig.DomainReservedUpstreams
|
|
|
|
|
2019-10-09 16:51:26 +00:00
|
|
|
if len(s.conf.ParentalBlockHost) == 0 {
|
|
|
|
s.conf.ParentalBlockHost = parentalBlockHost
|
|
|
|
}
|
|
|
|
if len(s.conf.SafeBrowsingBlockHost) == 0 {
|
|
|
|
s.conf.SafeBrowsingBlockHost = safeBrowsingBlockHost
|
2018-12-05 11:03:41 +00:00
|
|
|
}
|
2019-10-31 09:32:14 +00:00
|
|
|
if s.conf.UDPListenAddr == nil {
|
|
|
|
s.conf.UDPListenAddr = defaultValues.UDPListenAddr
|
|
|
|
}
|
|
|
|
if s.conf.TCPListenAddr == nil {
|
|
|
|
s.conf.TCPListenAddr = defaultValues.TCPListenAddr
|
|
|
|
}
|
2018-12-05 11:03:41 +00:00
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
proxyConfig := proxy.Config{
|
2019-05-15 12:08:15 +00:00
|
|
|
UDPListenAddr: s.conf.UDPListenAddr,
|
|
|
|
TCPListenAddr: s.conf.TCPListenAddr,
|
2019-11-08 11:59:12 +00:00
|
|
|
Ratelimit: int(s.conf.Ratelimit),
|
2019-05-15 12:08:15 +00:00
|
|
|
RatelimitWhitelist: s.conf.RatelimitWhitelist,
|
|
|
|
RefuseAny: s.conf.RefuseAny,
|
2019-03-20 11:24:33 +00:00
|
|
|
CacheEnabled: true,
|
2019-08-22 12:09:43 +00:00
|
|
|
CacheSizeBytes: int(s.conf.CacheSize),
|
2019-05-15 12:08:15 +00:00
|
|
|
Upstreams: s.conf.Upstreams,
|
|
|
|
DomainsReservedUpstreams: s.conf.DomainsReservedUpstreams,
|
2019-05-24 11:49:26 +00:00
|
|
|
BeforeRequestHandler: s.beforeRequestHandler,
|
|
|
|
RequestHandler: s.handleDNSRequest,
|
2019-05-15 12:08:15 +00:00
|
|
|
AllServers: s.conf.AllServers,
|
2019-11-12 16:45:55 +00:00
|
|
|
EnableEDNSClientSubnet: s.conf.EnableEDNSClientSubnet,
|
2018-12-24 12:19:52 +00:00
|
|
|
}
|
2018-11-28 12:40:56 +00:00
|
|
|
|
2019-12-11 09:38:58 +00:00
|
|
|
intlProxyConfig := proxy.Config{
|
|
|
|
CacheEnabled: true,
|
|
|
|
CacheSizeBytes: 4096,
|
|
|
|
Upstreams: s.conf.Upstreams,
|
|
|
|
DomainsReservedUpstreams: s.conf.DomainsReservedUpstreams,
|
|
|
|
}
|
|
|
|
s.internalProxy = &proxy.Proxy{Config: intlProxyConfig}
|
|
|
|
|
2019-10-30 12:11:16 +00:00
|
|
|
s.access = &accessCtx{}
|
2019-10-31 09:32:14 +00:00
|
|
|
err = s.access.Init(s.conf.AllowedClients, s.conf.DisallowedClients, s.conf.BlockedHosts)
|
2019-05-24 11:49:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-13 09:32:52 +00:00
|
|
|
if s.conf.TLSListenAddr != nil && len(s.conf.CertificateChainData) != 0 && len(s.conf.PrivateKeyData) != 0 {
|
2019-05-15 12:08:15 +00:00
|
|
|
proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
|
2020-01-22 15:40:43 +00:00
|
|
|
s.conf.cert, err = tls.X509KeyPair(s.conf.CertificateChainData, s.conf.PrivateKeyData)
|
2019-02-12 14:23:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "Failed to parse TLS keypair")
|
|
|
|
}
|
2020-01-22 15:40:43 +00:00
|
|
|
|
|
|
|
if s.conf.StrictSNICheck {
|
|
|
|
x, err := x509.ParseCertificate(s.conf.cert.Certificate[0])
|
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "x509.ParseCertificate(): %s", 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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-17 09:02:56 +00:00
|
|
|
proxyConfig.TLSConfig = &tls.Config{
|
2020-01-22 15:40:43 +00:00
|
|
|
GetCertificate: s.onGetCertificate,
|
|
|
|
MinVersion: tls.VersionTLS12,
|
2019-04-17 09:02:56 +00:00
|
|
|
}
|
2019-02-12 14:23:38 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
if len(proxyConfig.Upstreams) == 0 {
|
2019-10-31 09:32:14 +00:00
|
|
|
log.Fatal("len(proxyConfig.Upstreams) == 0")
|
2018-12-24 12:19:52 +00:00
|
|
|
}
|
|
|
|
|
2020-01-16 11:25:40 +00:00
|
|
|
if !webRegistered && s.conf.HTTPRegister != nil {
|
|
|
|
webRegistered = true
|
2019-10-30 08:52:58 +00:00
|
|
|
s.registerHandlers()
|
|
|
|
}
|
|
|
|
|
2018-12-24 12:27:14 +00:00
|
|
|
// Initialize and start the DNS proxy
|
2018-12-24 12:19:52 +00:00
|
|
|
s.dnsProxy = &proxy.Proxy{Config: proxyConfig}
|
2019-11-21 13:13:19 +00:00
|
|
|
return nil
|
2018-12-24 12:27:14 +00:00
|
|
|
}
|
2018-12-24 12:19:52 +00:00
|
|
|
|
2020-01-22 15:40:43 +00:00
|
|
|
// Find value in a sorted array
|
|
|
|
func findSorted(ar []string, val string) int {
|
|
|
|
i := sort.SearchStrings(ar, val)
|
|
|
|
if i == len(ar) || ar[i] != val {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return i
|
|
|
|
}
|
|
|
|
|
|
|
|
func isWildcard(host string) bool {
|
|
|
|
return len(host) >= 2 &&
|
|
|
|
host[0] == '*' && host[1] == '.'
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return TRUE if host name matches a wildcard pattern
|
|
|
|
func matchDomainWildcard(host, wildcard string) bool {
|
|
|
|
return isWildcard(wildcard) &&
|
|
|
|
strings.HasSuffix(host, wildcard[1:])
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return TRUE if client's SNI value matches DNS names from certificate
|
|
|
|
func matchDNSName(dnsNames []string, sni string) bool {
|
|
|
|
if utils.IsValidHostname(sni) != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if findSorted(dnsNames, sni) != -1 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, dn := range dnsNames {
|
|
|
|
if matchDomainWildcard(sni, dn) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// Stop stops the DNS server
|
2018-11-28 12:40:56 +00:00
|
|
|
func (s *Server) Stop() error {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2018-12-24 12:19:52 +00:00
|
|
|
return s.stopInternal()
|
|
|
|
}
|
|
|
|
|
|
|
|
// stopInternal stops without locking
|
|
|
|
func (s *Server) stopInternal() error {
|
|
|
|
if s.dnsProxy != nil {
|
|
|
|
err := s.dnsProxy.Stop()
|
2018-11-28 12:40:56 +00:00
|
|
|
if err != nil {
|
2018-12-24 12:19:52 +00:00
|
|
|
return errorx.Decorate(err, "could not stop the DNS server properly")
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
}
|
2018-12-05 11:21:48 +00:00
|
|
|
|
2019-12-11 09:38:58 +00:00
|
|
|
s.isRunning = false
|
2019-08-26 08:54:38 +00:00
|
|
|
return nil
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// IsRunning returns true if the DNS server is running
|
2018-11-28 13:43:50 +00:00
|
|
|
func (s *Server) IsRunning() bool {
|
|
|
|
s.RLock()
|
2019-12-11 09:38:58 +00:00
|
|
|
defer s.RUnlock()
|
|
|
|
return s.isRunning
|
2018-11-28 13:43:50 +00:00
|
|
|
}
|
|
|
|
|
2019-10-31 09:32:14 +00:00
|
|
|
// Reconfigure applies the new configuration to the DNS server
|
2018-12-24 12:19:52 +00:00
|
|
|
func (s *Server) Reconfigure(config *ServerConfig) error {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2018-11-28 12:40:56 +00:00
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
log.Print("Start reconfiguring the server")
|
|
|
|
err := s.stopInternal()
|
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "could not reconfigure the server")
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
2019-10-21 12:58:14 +00:00
|
|
|
|
2019-12-11 14:54:34 +00:00
|
|
|
// It seems that net.Listener.Close() doesn't close file descriptors right away.
|
|
|
|
// We wait for some time and hope that this fd will be closed.
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
2019-10-21 12:58:14 +00:00
|
|
|
|
2019-12-11 09:38:58 +00:00
|
|
|
err = s.Prepare(config)
|
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "could not reconfigure the server")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = s.startInternal()
|
2018-12-24 12:19:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "could not reconfigure the server")
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-02-22 12:52:12 +00:00
|
|
|
// ServeHTTP is a HTTP handler method we use to provide DNS-over-HTTPS
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
s.RLock()
|
2019-12-12 12:00:10 +00:00
|
|
|
p := s.dnsProxy
|
2019-02-22 12:52:12 +00:00
|
|
|
s.RUnlock()
|
2019-12-12 12:00:10 +00:00
|
|
|
if p != nil { // an attempt to protect against race in case we're here after Close() was called
|
|
|
|
p.ServeHTTP(w, r)
|
|
|
|
}
|
2019-02-22 12:52:12 +00:00
|
|
|
}
|
|
|
|
|
2019-12-16 09:36:52 +00:00
|
|
|
// Get IP address from net.Addr object
|
|
|
|
// Note: we can't use net.SplitHostPort(a.String()) because of IPv6 zone:
|
|
|
|
// https://github.com/AdguardTeam/AdGuardHome/issues/1261
|
|
|
|
func ipFromAddr(a net.Addr) string {
|
|
|
|
switch addr := a.(type) {
|
|
|
|
case *net.UDPAddr:
|
|
|
|
return addr.IP.String()
|
|
|
|
case *net.TCPAddr:
|
|
|
|
return addr.IP.String()
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2019-05-24 11:49:26 +00:00
|
|
|
func (s *Server) beforeRequestHandler(p *proxy.Proxy, d *proxy.DNSContext) (bool, error) {
|
2019-12-16 09:36:52 +00:00
|
|
|
ip := ipFromAddr(d.Addr)
|
2019-10-30 12:11:16 +00:00
|
|
|
if s.access.IsBlockedIP(ip) {
|
2019-05-24 11:49:26 +00:00
|
|
|
log.Tracef("Client IP %s is blocked by settings", ip)
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(d.Req.Question) == 1 {
|
|
|
|
host := strings.TrimSuffix(d.Req.Question[0].Name, ".")
|
2019-10-30 12:11:16 +00:00
|
|
|
if s.access.IsBlockedDomain(host) {
|
2019-05-24 11:49:26 +00:00
|
|
|
log.Tracef("Domain %s is blocked by settings", host)
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
// To transfer information between modules
|
|
|
|
type dnsContext struct {
|
|
|
|
srv *Server
|
|
|
|
proxyCtx *proxy.DNSContext
|
|
|
|
setts *dnsfilter.RequestFilteringSettings // filtering settings for this client
|
|
|
|
startTime time.Time
|
|
|
|
result *dnsfilter.Result
|
|
|
|
origResp *dns.Msg // response received from upstream servers. Set when response is modified by filtering
|
|
|
|
origQuestion dns.Question // question received from client. Set when Rewrites are used.
|
|
|
|
err error // error returned from the module
|
|
|
|
protectionEnabled bool // filtering is enabled, dnsfilter object is ready
|
|
|
|
responseFromUpstream bool // response is received from upstream servers
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
resultDone = iota // module has completed its job, continue
|
|
|
|
resultFinish // module has completed its job, exit normally
|
|
|
|
resultError // an error occurred, exit with an error
|
|
|
|
)
|
2018-11-28 12:40:56 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
// Perform initial checks; process WHOIS & rDNS
|
|
|
|
func processInitial(ctx *dnsContext) int {
|
|
|
|
s := ctx.srv
|
|
|
|
d := ctx.proxyCtx
|
2019-11-11 16:34:47 +00:00
|
|
|
if s.conf.AAAADisabled && d.Req.Question[0].Qtype == dns.TypeAAAA {
|
|
|
|
_ = proxy.CheckDisabledAAAARequest(d, true)
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultFinish
|
2019-11-11 16:34:47 +00:00
|
|
|
}
|
|
|
|
|
2019-05-21 11:53:13 +00:00
|
|
|
if s.conf.OnDNSRequest != nil {
|
|
|
|
s.conf.OnDNSRequest(d)
|
|
|
|
}
|
|
|
|
|
2019-09-12 15:23:33 +00:00
|
|
|
// disable Mozilla DoH
|
|
|
|
if (d.Req.Question[0].Qtype == dns.TypeA || d.Req.Question[0].Qtype == dns.TypeAAAA) &&
|
|
|
|
d.Req.Question[0].Name == "use-application-dns.net." {
|
|
|
|
d.Res = s.genNXDomain(d.Req)
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultFinish
|
2019-09-12 15:23:33 +00:00
|
|
|
}
|
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultDone
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply filtering logic
|
|
|
|
func processFilteringBeforeRequest(ctx *dnsContext) int {
|
|
|
|
s := ctx.srv
|
|
|
|
d := ctx.proxyCtx
|
|
|
|
|
2019-08-20 11:46:09 +00:00
|
|
|
s.RLock()
|
|
|
|
// Synchronize access to s.dnsFilter so it won't be suddenly uninitialized while in use.
|
|
|
|
// This could happen after proxy server has been stopped, but its workers are not yet exited.
|
|
|
|
//
|
|
|
|
// A better approach is for proxy.Stop() to wait until all its workers exit,
|
|
|
|
// but this would require the Upstream interface to have Close() function
|
|
|
|
// (to prevent from hanging while waiting for unresponsive DNS server to respond).
|
2020-01-09 16:52:06 +00:00
|
|
|
|
|
|
|
var err error
|
2020-01-21 10:49:34 +00:00
|
|
|
ctx.protectionEnabled = s.conf.ProtectionEnabled && s.dnsFilter != nil
|
|
|
|
if ctx.protectionEnabled {
|
|
|
|
ctx.setts = s.getClientRequestFilteringSettings(d)
|
|
|
|
ctx.result, err = s.filterDNSRequest(ctx)
|
2020-01-09 16:52:06 +00:00
|
|
|
}
|
2019-08-20 11:46:09 +00:00
|
|
|
s.RUnlock()
|
2020-01-21 10:49:34 +00:00
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
if err != nil {
|
2020-01-21 10:49:34 +00:00
|
|
|
ctx.err = err
|
|
|
|
return resultError
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultDone
|
|
|
|
}
|
2018-11-30 10:51:15 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
// Pass request to upstream servers; process the response
|
|
|
|
func processUpstream(ctx *dnsContext) int {
|
|
|
|
s := ctx.srv
|
|
|
|
d := ctx.proxyCtx
|
|
|
|
if d.Res != nil {
|
|
|
|
return resultDone // response is already set - nothing to do
|
|
|
|
}
|
2019-07-29 08:37:16 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
if d.Addr != nil && s.conf.GetUpstreamsByClient != nil {
|
|
|
|
clientIP := ipFromAddr(d.Addr)
|
|
|
|
upstreams := s.conf.GetUpstreamsByClient(clientIP)
|
|
|
|
if len(upstreams) > 0 {
|
|
|
|
log.Debug("Using custom upstreams for %s", clientIP)
|
|
|
|
d.Upstreams = upstreams
|
2019-07-29 08:37:16 +00:00
|
|
|
}
|
2020-01-21 10:49:34 +00:00
|
|
|
}
|
2019-07-29 08:37:16 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
// request was not filtered so let it be processed further
|
|
|
|
err := s.dnsProxy.Resolve(d)
|
|
|
|
if err != nil {
|
|
|
|
ctx.err = err
|
|
|
|
return resultError
|
|
|
|
}
|
2019-11-06 14:24:15 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
ctx.responseFromUpstream = true
|
|
|
|
return resultDone
|
|
|
|
}
|
2019-07-29 08:37:16 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
// Apply filtering logic after we have received response from upstream servers
|
|
|
|
func processFilteringAfterResponse(ctx *dnsContext) int {
|
|
|
|
s := ctx.srv
|
|
|
|
d := ctx.proxyCtx
|
|
|
|
res := ctx.result
|
|
|
|
var err error
|
2019-07-29 08:37:16 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
if !ctx.responseFromUpstream {
|
|
|
|
return resultDone // don't process response if it's not from upstream servers
|
|
|
|
}
|
2019-11-21 13:13:19 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
if res.Reason == dnsfilter.ReasonRewrite && len(res.CanonName) != 0 {
|
|
|
|
d.Req.Question[0] = ctx.origQuestion
|
|
|
|
d.Res.Question[0] = ctx.origQuestion
|
|
|
|
|
|
|
|
if len(d.Res.Answer) != 0 {
|
|
|
|
answer := []dns.RR{}
|
|
|
|
answer = append(answer, s.genCNAMEAnswer(d.Req, res.CanonName))
|
|
|
|
answer = append(answer, d.Res.Answer...) // host -> IP
|
|
|
|
d.Res.Answer = answer
|
2019-07-29 08:37:16 +00:00
|
|
|
}
|
2018-11-30 10:51:15 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
} else if res.Reason != dnsfilter.NotFilteredWhiteList && ctx.protectionEnabled {
|
|
|
|
origResp2 := d.Res
|
|
|
|
ctx.result, err = s.filterDNSResponse(ctx)
|
|
|
|
if err != nil {
|
|
|
|
ctx.err = err
|
|
|
|
return resultError
|
|
|
|
}
|
|
|
|
if ctx.result != nil {
|
|
|
|
ctx.origResp = origResp2 // matched by response
|
|
|
|
} else {
|
|
|
|
ctx.result = &dnsfilter.Result{}
|
|
|
|
}
|
2019-10-23 16:31:34 +00:00
|
|
|
}
|
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultDone
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write Stats data and logs
|
|
|
|
func processQueryLogsAndStats(ctx *dnsContext) int {
|
|
|
|
elapsed := time.Since(ctx.startTime)
|
|
|
|
s := ctx.srv
|
|
|
|
d := ctx.proxyCtx
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
shouldLog := true
|
|
|
|
msg := d.Req
|
2018-11-30 10:51:15 +00:00
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// don't log ANY request if refuseAny is enabled
|
2019-05-15 12:08:15 +00:00
|
|
|
if len(msg.Question) >= 1 && msg.Question[0].Qtype == dns.TypeANY && s.conf.RefuseAny {
|
2018-12-24 12:19:52 +00:00
|
|
|
shouldLog = false
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2019-09-16 12:54:41 +00:00
|
|
|
s.RLock()
|
|
|
|
// Synchronize access to s.queryLog and s.stats so they won't be suddenly uninitialized while in use.
|
|
|
|
// This can happen after proxy server has been stopped, but its workers haven't yet exited.
|
2019-09-27 15:58:57 +00:00
|
|
|
if shouldLog && s.queryLog != nil {
|
2019-11-21 13:13:19 +00:00
|
|
|
p := querylog.AddParams{
|
|
|
|
Question: msg,
|
|
|
|
Answer: d.Res,
|
2020-01-21 10:49:34 +00:00
|
|
|
OrigAnswer: ctx.origResp,
|
|
|
|
Result: ctx.result,
|
2019-11-21 13:13:19 +00:00
|
|
|
Elapsed: elapsed,
|
|
|
|
ClientIP: getIP(d.Addr),
|
|
|
|
}
|
2018-12-24 12:19:52 +00:00
|
|
|
if d.Upstream != nil {
|
2019-11-21 13:13:19 +00:00
|
|
|
p.Upstream = d.Upstream.Address()
|
2018-12-24 12:19:52 +00:00
|
|
|
}
|
2019-11-21 13:13:19 +00:00
|
|
|
s.queryLog.Add(p)
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
s.updateStats(d, elapsed, *ctx.result)
|
2019-09-16 12:54:41 +00:00
|
|
|
s.RUnlock()
|
2019-08-22 13:34:58 +00:00
|
|
|
|
2020-01-21 10:49:34 +00:00
|
|
|
return resultDone
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleDNSRequest filters the incoming DNS requests and writes them to the query log
|
|
|
|
// nolint (gocyclo)
|
|
|
|
func (s *Server) handleDNSRequest(p *proxy.Proxy, d *proxy.DNSContext) error {
|
|
|
|
ctx := &dnsContext{srv: s, proxyCtx: d}
|
|
|
|
ctx.result = &dnsfilter.Result{}
|
|
|
|
ctx.startTime = time.Now()
|
|
|
|
|
|
|
|
type modProcessFunc func(ctx *dnsContext) int
|
|
|
|
mods := []modProcessFunc{
|
|
|
|
processInitial,
|
|
|
|
processFilteringBeforeRequest,
|
|
|
|
processUpstream,
|
|
|
|
processFilteringAfterResponse,
|
2020-01-30 07:25:02 +00:00
|
|
|
processQueryLogsAndStats,
|
2020-01-21 10:49:34 +00:00
|
|
|
}
|
|
|
|
for _, process := range mods {
|
|
|
|
r := process(ctx)
|
|
|
|
switch r {
|
|
|
|
case resultFinish:
|
|
|
|
return nil
|
|
|
|
case resultError:
|
|
|
|
return ctx.err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if d.Res != nil {
|
|
|
|
d.Res.Compress = true // some devices require DNS message compression
|
|
|
|
}
|
2018-11-28 12:40:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-19 11:09:10 +00:00
|
|
|
// Get IP address from net.Addr
|
|
|
|
func getIP(addr net.Addr) net.IP {
|
|
|
|
switch addr := addr.(type) {
|
|
|
|
case *net.UDPAddr:
|
|
|
|
return addr.IP
|
|
|
|
case *net.TCPAddr:
|
|
|
|
return addr.IP
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-08-22 13:34:58 +00:00
|
|
|
func (s *Server) updateStats(d *proxy.DNSContext, elapsed time.Duration, res dnsfilter.Result) {
|
|
|
|
if s.stats == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
e := stats.Entry{}
|
|
|
|
e.Domain = strings.ToLower(d.Req.Question[0].Name)
|
|
|
|
e.Domain = e.Domain[:len(e.Domain)-1] // remove last "."
|
|
|
|
switch addr := d.Addr.(type) {
|
|
|
|
case *net.UDPAddr:
|
|
|
|
e.Client = addr.IP
|
|
|
|
case *net.TCPAddr:
|
|
|
|
e.Client = addr.IP
|
|
|
|
}
|
2019-09-10 14:59:10 +00:00
|
|
|
e.Time = uint32(elapsed / 1000)
|
2019-08-22 13:34:58 +00:00
|
|
|
switch res.Reason {
|
|
|
|
|
|
|
|
case dnsfilter.NotFilteredNotFound:
|
|
|
|
fallthrough
|
|
|
|
case dnsfilter.NotFilteredWhiteList:
|
|
|
|
fallthrough
|
|
|
|
case dnsfilter.NotFilteredError:
|
|
|
|
e.Result = stats.RNotFiltered
|
|
|
|
|
|
|
|
case dnsfilter.FilteredSafeBrowsing:
|
|
|
|
e.Result = stats.RSafeBrowsing
|
|
|
|
case dnsfilter.FilteredParental:
|
|
|
|
e.Result = stats.RParental
|
|
|
|
case dnsfilter.FilteredSafeSearch:
|
|
|
|
e.Result = stats.RSafeSearch
|
|
|
|
|
|
|
|
case dnsfilter.FilteredBlackList:
|
|
|
|
fallthrough
|
|
|
|
case dnsfilter.FilteredInvalid:
|
|
|
|
fallthrough
|
|
|
|
case dnsfilter.FilteredBlockedService:
|
|
|
|
e.Result = stats.RFiltered
|
|
|
|
}
|
|
|
|
s.stats.Update(e)
|
|
|
|
}
|
|
|
|
|
2019-12-23 10:36:59 +00:00
|
|
|
// getClientRequestFilteringSettings lookups client filtering settings
|
|
|
|
// using the client's IP address from the DNSContext
|
|
|
|
func (s *Server) getClientRequestFilteringSettings(d *proxy.DNSContext) *dnsfilter.RequestFilteringSettings {
|
2019-10-09 16:51:26 +00:00
|
|
|
setts := s.dnsFilter.GetConfig()
|
2019-07-25 13:37:06 +00:00
|
|
|
setts.FilteringEnabled = true
|
|
|
|
if s.conf.FilterHandler != nil {
|
2019-12-16 09:36:52 +00:00
|
|
|
clientAddr := ipFromAddr(d.Addr)
|
2019-07-25 13:37:06 +00:00
|
|
|
s.conf.FilterHandler(clientAddr, &setts)
|
|
|
|
}
|
2019-12-23 10:36:59 +00:00
|
|
|
return &setts
|
|
|
|
}
|
|
|
|
|
|
|
|
// filterDNSRequest applies the dnsFilter and sets d.Res if the request was filtered
|
2020-01-21 10:49:34 +00:00
|
|
|
func (s *Server) filterDNSRequest(ctx *dnsContext) (*dnsfilter.Result, error) {
|
|
|
|
d := ctx.proxyCtx
|
2019-10-09 16:51:26 +00:00
|
|
|
req := d.Req
|
|
|
|
host := strings.TrimSuffix(req.Question[0].Name, ".")
|
2020-01-21 10:49:34 +00:00
|
|
|
res, err := s.dnsFilter.CheckHost(host, d.Req.Question[0].Qtype, ctx.setts)
|
2018-11-28 12:40:56 +00:00
|
|
|
if err != nil {
|
2018-12-24 12:19:52 +00:00
|
|
|
// Return immediately if there's an error
|
|
|
|
return nil, errorx.Decorate(err, "dnsfilter failed to check host '%s'", host)
|
2019-07-29 08:37:16 +00:00
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
} else if res.IsFiltered {
|
2018-12-29 14:23:42 +00:00
|
|
|
// log.Tracef("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule)
|
2018-12-24 12:19:52 +00:00
|
|
|
d.Res = s.genDNSFilterMessage(d, &res)
|
2019-07-29 08:37:16 +00:00
|
|
|
|
|
|
|
} else if res.Reason == dnsfilter.ReasonRewrite && len(res.IPList) != 0 {
|
2019-12-19 08:52:21 +00:00
|
|
|
resp := s.makeResponse(req)
|
2019-07-29 08:37:16 +00:00
|
|
|
|
|
|
|
name := host
|
|
|
|
if len(res.CanonName) != 0 {
|
|
|
|
resp.Answer = append(resp.Answer, s.genCNAMEAnswer(req, res.CanonName))
|
|
|
|
name = res.CanonName
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ip := range res.IPList {
|
|
|
|
if req.Question[0].Qtype == dns.TypeA {
|
|
|
|
a := s.genAAnswer(req, ip)
|
|
|
|
a.Hdr.Name = dns.Fqdn(name)
|
|
|
|
resp.Answer = append(resp.Answer, a)
|
|
|
|
} else if req.Question[0].Qtype == dns.TypeAAAA {
|
2019-09-16 13:28:00 +00:00
|
|
|
a := s.genAAAAAnswer(req, ip)
|
2019-07-29 08:37:16 +00:00
|
|
|
a.Hdr.Name = dns.Fqdn(name)
|
|
|
|
resp.Answer = append(resp.Answer, a)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-19 08:52:21 +00:00
|
|
|
d.Res = resp
|
2020-01-21 10:49:34 +00:00
|
|
|
|
|
|
|
} else if res.Reason == dnsfilter.ReasonRewrite && len(res.CanonName) != 0 {
|
|
|
|
ctx.origQuestion = d.Req.Question[0]
|
|
|
|
// resolve canonical name, not the original host name
|
|
|
|
d.Req.Question[0].Name = dns.Fqdn(res.CanonName)
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
return &res, err
|
2018-12-05 11:03:41 +00:00
|
|
|
}
|
|
|
|
|
2019-11-21 13:13:19 +00:00
|
|
|
// If response contains CNAME, A or AAAA records, we apply filtering to each canonical host name or IP address.
|
|
|
|
// If this is a match, we set a new response in d.Res and return.
|
2020-01-21 10:49:34 +00:00
|
|
|
func (s *Server) filterDNSResponse(ctx *dnsContext) (*dnsfilter.Result, error) {
|
|
|
|
d := ctx.proxyCtx
|
2019-11-21 13:13:19 +00:00
|
|
|
for _, a := range d.Res.Answer {
|
|
|
|
host := ""
|
|
|
|
|
|
|
|
switch v := a.(type) {
|
|
|
|
case *dns.CNAME:
|
|
|
|
log.Debug("DNSFwd: Checking CNAME %s for %s", v.Target, v.Hdr.Name)
|
|
|
|
host = strings.TrimSuffix(v.Target, ".")
|
|
|
|
|
|
|
|
case *dns.A:
|
|
|
|
host = v.A.String()
|
|
|
|
log.Debug("DNSFwd: Checking record A (%s) for %s", host, v.Hdr.Name)
|
|
|
|
|
|
|
|
case *dns.AAAA:
|
|
|
|
host = v.AAAA.String()
|
|
|
|
log.Debug("DNSFwd: Checking record AAAA (%s) for %s", host, v.Hdr.Name)
|
|
|
|
|
|
|
|
default:
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
s.RLock()
|
|
|
|
// Synchronize access to s.dnsFilter so it won't be suddenly uninitialized while in use.
|
|
|
|
// This could happen after proxy server has been stopped, but its workers are not yet exited.
|
|
|
|
if !s.conf.ProtectionEnabled || s.dnsFilter == nil {
|
|
|
|
s.RUnlock()
|
|
|
|
continue
|
|
|
|
}
|
2020-01-21 10:49:34 +00:00
|
|
|
res, err := s.dnsFilter.CheckHostRules(host, d.Req.Question[0].Qtype, ctx.setts)
|
2019-11-21 13:13:19 +00:00
|
|
|
s.RUnlock()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
|
|
|
|
} else if res.IsFiltered {
|
|
|
|
d.Res = s.genDNSFilterMessage(d, &res)
|
|
|
|
log.Debug("DNSFwd: Matched %s by response: %s", d.Req.Question[0].Name, host)
|
|
|
|
return &res, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2019-12-19 08:52:21 +00:00
|
|
|
// Create a DNS response by DNS request and set necessary flags
|
|
|
|
func (s *Server) makeResponse(req *dns.Msg) *dns.Msg {
|
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetReply(req)
|
|
|
|
resp.RecursionAvailable = true
|
|
|
|
resp.Compress = true
|
|
|
|
return &resp
|
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
// genDNSFilterMessage generates a DNS message corresponding to the filtering result
|
|
|
|
func (s *Server) genDNSFilterMessage(d *proxy.DNSContext, result *dnsfilter.Result) *dns.Msg {
|
|
|
|
m := d.Req
|
2018-12-05 11:03:41 +00:00
|
|
|
|
2019-05-22 12:50:22 +00:00
|
|
|
if m.Question[0].Qtype != dns.TypeA && m.Question[0].Qtype != dns.TypeAAAA {
|
2018-12-24 12:19:52 +00:00
|
|
|
return s.genNXDomain(m)
|
2018-12-05 11:03:41 +00:00
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
switch result.Reason {
|
|
|
|
case dnsfilter.FilteredSafeBrowsing:
|
2019-07-22 09:16:30 +00:00
|
|
|
return s.genBlockedHost(m, s.conf.SafeBrowsingBlockHost, d)
|
2018-12-24 12:19:52 +00:00
|
|
|
case dnsfilter.FilteredParental:
|
2019-07-22 09:16:30 +00:00
|
|
|
return s.genBlockedHost(m, s.conf.ParentalBlockHost, d)
|
2018-12-24 12:19:52 +00:00
|
|
|
default:
|
2020-02-05 11:30:43 +00:00
|
|
|
// If the query was filtered by "Safe search", dnsfilter also must return
|
|
|
|
// the IP address that must be used in response.
|
|
|
|
// In this case regardless of the filtering method, we should return it
|
|
|
|
if result.Reason == dnsfilter.FilteredSafeSearch && result.IP != nil {
|
|
|
|
return s.genResponseWithIP(m, result.IP)
|
|
|
|
}
|
|
|
|
|
2019-05-15 12:08:15 +00:00
|
|
|
if s.conf.BlockingMode == "null_ip" {
|
2020-02-05 11:30:43 +00:00
|
|
|
// it means that we should return 0.0.0.0 or :: for any blocked request
|
|
|
|
|
2019-05-22 12:50:22 +00:00
|
|
|
switch m.Question[0].Qtype {
|
|
|
|
case dns.TypeA:
|
|
|
|
return s.genARecord(m, []byte{0, 0, 0, 0})
|
|
|
|
case dns.TypeAAAA:
|
|
|
|
return s.genAAAARecord(m, net.IPv6zero)
|
|
|
|
}
|
2019-11-08 13:19:56 +00:00
|
|
|
|
|
|
|
} else if s.conf.BlockingMode == "custom_ip" {
|
2020-02-05 11:30:43 +00:00
|
|
|
// means that we should return custom IP for any blocked request
|
|
|
|
|
2019-11-08 13:19:56 +00:00
|
|
|
switch m.Question[0].Qtype {
|
|
|
|
case dns.TypeA:
|
|
|
|
return s.genARecord(m, s.conf.BlockingIPAddrv4)
|
|
|
|
case dns.TypeAAAA:
|
|
|
|
return s.genAAAARecord(m, s.conf.BlockingIPAddrv6)
|
|
|
|
}
|
2019-12-30 15:41:51 +00:00
|
|
|
|
|
|
|
} else if s.conf.BlockingMode == "nxdomain" {
|
2020-02-05 11:30:43 +00:00
|
|
|
// means that we should return NXDOMAIN for any blocked request
|
|
|
|
|
2019-12-30 15:41:51 +00:00
|
|
|
return s.genNXDomain(m)
|
2019-05-04 20:51:14 +00:00
|
|
|
}
|
|
|
|
|
2020-02-05 11:30:43 +00:00
|
|
|
// Default blocking mode
|
|
|
|
// If there's an IP specified in the rule, return it
|
|
|
|
// If there is no IP, return NXDOMAIN
|
2019-12-30 15:41:51 +00:00
|
|
|
if result.IP != nil {
|
|
|
|
return s.genResponseWithIP(m, result.IP)
|
|
|
|
}
|
2018-12-24 12:19:52 +00:00
|
|
|
return s.genNXDomain(m)
|
2018-12-05 11:22:09 +00:00
|
|
|
}
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2018-12-05 11:03:41 +00:00
|
|
|
func (s *Server) genServerFailure(request *dns.Msg) *dns.Msg {
|
2018-11-28 12:40:56 +00:00
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetRcode(request, dns.RcodeServerFailure)
|
2018-12-05 15:47:03 +00:00
|
|
|
resp.RecursionAvailable = true
|
|
|
|
return &resp
|
|
|
|
}
|
|
|
|
|
2018-12-24 12:19:52 +00:00
|
|
|
func (s *Server) genARecord(request *dns.Msg, ip net.IP) *dns.Msg {
|
2019-12-19 08:52:21 +00:00
|
|
|
resp := s.makeResponse(request)
|
2019-05-22 12:50:22 +00:00
|
|
|
resp.Answer = append(resp.Answer, s.genAAnswer(request, ip))
|
2019-12-19 08:52:21 +00:00
|
|
|
return resp
|
2019-05-22 12:50:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) genAAAARecord(request *dns.Msg, ip net.IP) *dns.Msg {
|
2019-12-19 08:52:21 +00:00
|
|
|
resp := s.makeResponse(request)
|
2019-05-22 12:50:22 +00:00
|
|
|
resp.Answer = append(resp.Answer, s.genAAAAAnswer(request, ip))
|
2019-12-19 08:52:21 +00:00
|
|
|
return resp
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
2019-05-22 12:50:22 +00:00
|
|
|
func (s *Server) genAAnswer(req *dns.Msg, ip net.IP) *dns.A {
|
|
|
|
answer := new(dns.A)
|
|
|
|
answer.Hdr = dns.RR_Header{
|
|
|
|
Name: req.Question[0].Name,
|
|
|
|
Rrtype: dns.TypeA,
|
|
|
|
Ttl: s.conf.BlockedResponseTTL,
|
|
|
|
Class: dns.ClassINET,
|
|
|
|
}
|
|
|
|
answer.A = ip
|
|
|
|
return answer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) genAAAAAnswer(req *dns.Msg, ip net.IP) *dns.AAAA {
|
|
|
|
answer := new(dns.AAAA)
|
|
|
|
answer.Hdr = dns.RR_Header{
|
|
|
|
Name: req.Question[0].Name,
|
|
|
|
Rrtype: dns.TypeAAAA,
|
|
|
|
Ttl: s.conf.BlockedResponseTTL,
|
|
|
|
Class: dns.ClassINET,
|
|
|
|
}
|
|
|
|
answer.AAAA = ip
|
|
|
|
return answer
|
|
|
|
}
|
|
|
|
|
2019-07-22 09:33:45 +00:00
|
|
|
// generate DNS response message with an IP address
|
|
|
|
func (s *Server) genResponseWithIP(req *dns.Msg, ip net.IP) *dns.Msg {
|
|
|
|
if req.Question[0].Qtype == dns.TypeA && ip.To4() != nil {
|
|
|
|
return s.genARecord(req, ip.To4())
|
2020-01-09 16:31:14 +00:00
|
|
|
} else if req.Question[0].Qtype == dns.TypeAAAA &&
|
|
|
|
len(ip) == net.IPv6len && ip.To4() == nil {
|
2019-07-22 09:33:45 +00:00
|
|
|
return s.genAAAARecord(req, ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// empty response
|
2019-12-19 08:52:21 +00:00
|
|
|
resp := s.makeResponse(req)
|
|
|
|
return resp
|
2019-07-22 09:33:45 +00:00
|
|
|
}
|
|
|
|
|
2019-02-22 15:41:59 +00:00
|
|
|
func (s *Server) genBlockedHost(request *dns.Msg, newAddr string, d *proxy.DNSContext) *dns.Msg {
|
2019-07-22 09:33:45 +00:00
|
|
|
|
|
|
|
ip := net.ParseIP(newAddr)
|
|
|
|
if ip != nil {
|
|
|
|
return s.genResponseWithIP(request, ip)
|
|
|
|
}
|
|
|
|
|
2018-12-11 12:02:23 +00:00
|
|
|
// look up the hostname, TODO: cache
|
|
|
|
replReq := dns.Msg{}
|
|
|
|
replReq.SetQuestion(dns.Fqdn(newAddr), request.Question[0].Qtype)
|
|
|
|
replReq.RecursionDesired = true
|
2019-02-22 15:41:59 +00:00
|
|
|
|
|
|
|
newContext := &proxy.DNSContext{
|
|
|
|
Proto: d.Proto,
|
|
|
|
Addr: d.Addr,
|
|
|
|
StartTime: time.Now(),
|
|
|
|
Req: &replReq,
|
|
|
|
}
|
|
|
|
|
|
|
|
err := s.dnsProxy.Resolve(newContext)
|
2018-12-11 12:02:23 +00:00
|
|
|
if err != nil {
|
2019-02-22 15:41:59 +00:00
|
|
|
log.Printf("Couldn't look up replacement host '%s': %s", newAddr, err)
|
2018-12-11 12:02:23 +00:00
|
|
|
return s.genServerFailure(request)
|
|
|
|
}
|
|
|
|
|
2019-12-19 08:52:21 +00:00
|
|
|
resp := s.makeResponse(request)
|
2019-02-22 15:41:59 +00:00
|
|
|
if newContext.Res != nil {
|
|
|
|
for _, answer := range newContext.Res.Answer {
|
2018-12-11 12:02:23 +00:00
|
|
|
answer.Header().Name = request.Question[0].Name
|
|
|
|
resp.Answer = append(resp.Answer, answer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-19 08:52:21 +00:00
|
|
|
return resp
|
2018-12-11 12:02:23 +00:00
|
|
|
}
|
|
|
|
|
2019-07-29 08:37:16 +00:00
|
|
|
// Make a CNAME response
|
|
|
|
func (s *Server) genCNAMEAnswer(req *dns.Msg, cname string) *dns.CNAME {
|
|
|
|
answer := new(dns.CNAME)
|
|
|
|
answer.Hdr = dns.RR_Header{
|
|
|
|
Name: req.Question[0].Name,
|
|
|
|
Rrtype: dns.TypeCNAME,
|
|
|
|
Ttl: s.conf.BlockedResponseTTL,
|
|
|
|
Class: dns.ClassINET,
|
|
|
|
}
|
|
|
|
answer.Target = dns.Fqdn(cname)
|
|
|
|
return answer
|
|
|
|
}
|
|
|
|
|
2018-12-05 11:03:41 +00:00
|
|
|
func (s *Server) genNXDomain(request *dns.Msg) *dns.Msg {
|
2018-11-28 12:40:56 +00:00
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetRcode(request, dns.RcodeNameError)
|
2018-12-05 15:47:03 +00:00
|
|
|
resp.RecursionAvailable = true
|
2018-11-28 12:40:56 +00:00
|
|
|
resp.Ns = s.genSOA(request)
|
2018-12-05 11:03:41 +00:00
|
|
|
return &resp
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) genSOA(request *dns.Msg) []dns.RR {
|
|
|
|
zone := ""
|
|
|
|
if len(request.Question) > 0 {
|
|
|
|
zone = request.Question[0].Name
|
|
|
|
}
|
|
|
|
|
|
|
|
soa := dns.SOA{
|
|
|
|
// values copied from verisign's nonexistent .com domain
|
|
|
|
// their exact values are not important in our use case because they are used for domain transfers between primary/secondary DNS servers
|
|
|
|
Refresh: 1800,
|
|
|
|
Retry: 900,
|
|
|
|
Expire: 604800,
|
|
|
|
Minttl: 86400,
|
|
|
|
// copied from AdGuard DNS
|
|
|
|
Ns: "fake-for-negative-caching.adguard.com.",
|
|
|
|
Serial: 100500,
|
|
|
|
// rest is request-specific
|
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: zone,
|
|
|
|
Rrtype: dns.TypeSOA,
|
2019-05-15 12:08:15 +00:00
|
|
|
Ttl: s.conf.BlockedResponseTTL,
|
2018-11-28 12:40:56 +00:00
|
|
|
Class: dns.ClassINET,
|
|
|
|
},
|
|
|
|
Mbox: "hostmaster.", // zone will be appended later if it's not empty or "."
|
|
|
|
}
|
|
|
|
if soa.Hdr.Ttl == 0 {
|
2018-11-28 15:14:12 +00:00
|
|
|
soa.Hdr.Ttl = defaultValues.BlockedResponseTTL
|
2018-11-28 12:40:56 +00:00
|
|
|
}
|
|
|
|
if len(zone) > 0 && zone[0] != '.' {
|
|
|
|
soa.Mbox += zone
|
|
|
|
}
|
|
|
|
return []dns.RR{&soa}
|
|
|
|
}
|