2018-11-28 15:40:56 +03:00
|
|
|
package dnsforward
|
|
|
|
|
|
|
|
import (
|
2019-02-12 17:23:38 +03:00
|
|
|
"crypto/tls"
|
2018-12-24 16:58:48 +03:00
|
|
|
"errors"
|
2018-11-28 15:40:56 +03:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2019-02-22 15:52:12 +03:00
|
|
|
"net/http"
|
2018-11-30 13:17:34 +03:00
|
|
|
"strings"
|
2018-11-28 15:40:56 +03:00
|
|
|
"sync"
|
2018-12-05 14:03:41 +03:00
|
|
|
"time"
|
2018-11-28 15:40:56 +03:00
|
|
|
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/dnsfilter"
|
2018-12-24 16:58:48 +03:00
|
|
|
"github.com/AdguardTeam/dnsproxy/proxy"
|
|
|
|
"github.com/AdguardTeam/dnsproxy/upstream"
|
2019-02-25 16:44:22 +03:00
|
|
|
"github.com/AdguardTeam/golibs/log"
|
2018-11-28 15:40:56 +03:00
|
|
|
"github.com/joomcode/errorx"
|
|
|
|
"github.com/miekg/dns"
|
2018-12-24 15:19:52 +03:00
|
|
|
)
|
|
|
|
|
2018-12-25 01:59:38 +03:00
|
|
|
// DefaultTimeout is the default upstream timeout
|
|
|
|
const DefaultTimeout = 10 * time.Second
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
const (
|
|
|
|
safeBrowsingBlockHost = "standard-block.dns.adguard.com"
|
|
|
|
parentalBlockHost = "family-block.dns.adguard.com"
|
2018-11-28 15:40:56 +03:00
|
|
|
)
|
|
|
|
|
2018-12-05 12:52:23 +03:00
|
|
|
// Server is the main way to start a DNS server.
|
|
|
|
//
|
2018-11-28 15:40:56 +03:00
|
|
|
// Example:
|
2018-12-05 12:52:23 +03: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 15:40:56 +03:00
|
|
|
//
|
|
|
|
// The zero Server is empty and ready for use.
|
|
|
|
type Server struct {
|
2019-02-10 20:47:43 +03:00
|
|
|
dnsProxy *proxy.Proxy // DNS proxy instance
|
2018-12-24 15:19:52 +03:00
|
|
|
dnsFilter *dnsfilter.Dnsfilter // DNS filter instance
|
2019-02-10 20:47:43 +03:00
|
|
|
queryLog *queryLog // Query log instance
|
|
|
|
stats *stats // General server statistics
|
2019-02-10 21:44:16 +03:00
|
|
|
once sync.Once
|
2018-12-05 18:47:03 +03:00
|
|
|
|
2018-11-28 15:40:56 +03:00
|
|
|
sync.RWMutex
|
2019-05-15 15:08:15 +03:00
|
|
|
conf ServerConfig
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2019-02-10 20:47:43 +03:00
|
|
|
// NewServer creates a new instance of the dnsforward.Server
|
|
|
|
// baseDir is the base directory for query logs
|
|
|
|
func NewServer(baseDir string) *Server {
|
|
|
|
return &Server{
|
|
|
|
queryLog: newQueryLog(baseDir),
|
|
|
|
stats: newStats(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// FilteringConfig represents the DNS filtering configuration of AdGuard Home
|
2019-02-12 17:23:38 +03:00
|
|
|
// The zero FilteringConfig is empty and ready for use.
|
2018-11-28 18:24:04 +03:00
|
|
|
type FilteringConfig struct {
|
2018-12-24 15:19:52 +03:00
|
|
|
ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of dnsfilter features
|
|
|
|
FilteringEnabled bool `yaml:"filtering_enabled"` // whether or not use filter lists
|
2019-05-04 23:51:14 +03:00
|
|
|
BlockingMode string `yaml:"blocking_mode"` // mode how to answer filtered requests
|
2018-12-05 18:47:03 +03:00
|
|
|
BlockedResponseTTL uint32 `yaml:"blocked_response_ttl"` // if 0, then default is used (3600)
|
2019-02-28 13:40:40 +03:00
|
|
|
QueryLogEnabled bool `yaml:"querylog_enabled"` // if true, query log is enabled
|
|
|
|
Ratelimit int `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
|
|
|
|
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 13:35:22 +03:00
|
|
|
|
|
|
|
dnsfilter.Config `yaml:",inline"`
|
2018-11-28 18:24:04 +03:00
|
|
|
}
|
|
|
|
|
2019-02-22 15:23:39 +03:00
|
|
|
// TLSConfig is the TLS configuration for HTTPS, DNS-over-HTTPS, and DNS-over-TLS
|
2019-02-12 17:23:38 +03:00
|
|
|
type TLSConfig struct {
|
|
|
|
TLSListenAddr *net.TCPAddr `yaml:"-" json:"-"`
|
2019-02-21 17:48:18 +03: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-02-12 17:23:38 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// ServerConfig represents server configuration.
|
2018-11-28 15:40:56 +03:00
|
|
|
// The zero ServerConfig is empty and ready for use.
|
|
|
|
type ServerConfig struct {
|
2019-03-20 14:24:33 +03: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
|
|
|
|
Filters []dnsfilter.Filter // A list of filters to use
|
2018-11-28 18:24:04 +03:00
|
|
|
|
|
|
|
FilteringConfig
|
2019-02-12 17:23:38 +03:00
|
|
|
TLSConfig
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-05 18:47:03 +03:00
|
|
|
// if any of ServerConfig values are zero, then default values from below are used
|
2018-11-28 15:40:56 +03:00
|
|
|
var defaultValues = ServerConfig{
|
2018-11-30 13:35:22 +03:00
|
|
|
UDPListenAddr: &net.UDPAddr{Port: 53},
|
2019-01-05 22:15:20 +03:00
|
|
|
TCPListenAddr: &net.TCPAddr{Port: 53},
|
2018-11-30 13:35:22 +03:00
|
|
|
FilteringConfig: FilteringConfig{BlockedResponseTTL: 3600},
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
func init() {
|
|
|
|
defaultDNS := []string{"8.8.8.8:53", "8.8.4.4:53"}
|
|
|
|
|
|
|
|
defaultUpstreams := make([]upstream.Upstream, 0)
|
|
|
|
for _, addr := range defaultDNS {
|
2019-02-22 18:16:47 +03:00
|
|
|
u, err := upstream.AddressToUpstream(addr, upstream.Options{Timeout: DefaultTimeout})
|
2018-12-24 15:19:52 +03:00
|
|
|
if err == nil {
|
|
|
|
defaultUpstreams = append(defaultUpstreams, u)
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
}
|
2018-12-24 15:19:52 +03:00
|
|
|
defaultValues.Upstreams = defaultUpstreams
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// Start starts the DNS server
|
2018-11-28 15:40:56 +03:00
|
|
|
func (s *Server) Start(config *ServerConfig) error {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2018-12-24 15:19:52 +03:00
|
|
|
return s.startInternal(config)
|
|
|
|
}
|
|
|
|
|
|
|
|
// startInternal starts without locking
|
|
|
|
func (s *Server) startInternal(config *ServerConfig) error {
|
2018-11-28 15:40:56 +03:00
|
|
|
if config != nil {
|
2019-05-15 15:08:15 +03:00
|
|
|
s.conf = *config
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:27:14 +03:00
|
|
|
if s.dnsFilter != nil || s.dnsProxy != nil {
|
|
|
|
return errors.New("DNS server is already started")
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2019-02-11 14:22:36 +03:00
|
|
|
if s.queryLog == nil {
|
|
|
|
s.queryLog = newQueryLog(".")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.stats == nil {
|
|
|
|
s.stats = newStats()
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:27:14 +03:00
|
|
|
err := s.initDNSFilter()
|
2018-12-05 14:03:41 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-02-07 18:24:12 +03:00
|
|
|
log.Tracef("Loading stats from querylog")
|
2019-02-10 20:47:43 +03:00
|
|
|
err = s.queryLog.fillStatsFromQueryLog(s.stats)
|
2018-12-24 15:27:14 +03:00
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "failed to load stats from querylog")
|
|
|
|
}
|
|
|
|
|
2019-02-10 21:44:16 +03:00
|
|
|
// TODO: Think about reworking this, the current approach won't work properly if AG Home is restarted periodically
|
|
|
|
s.once.Do(func() {
|
|
|
|
log.Printf("Start DNS server periodic jobs")
|
2019-02-10 20:47:43 +03:00
|
|
|
go s.queryLog.periodicQueryLogRotate()
|
|
|
|
go s.queryLog.runningTop.periodicHourlyTopRotate()
|
|
|
|
go s.stats.statsRotator()
|
2018-12-05 14:03:41 +03:00
|
|
|
})
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
proxyConfig := proxy.Config{
|
2019-05-15 15:08:15 +03:00
|
|
|
UDPListenAddr: s.conf.UDPListenAddr,
|
|
|
|
TCPListenAddr: s.conf.TCPListenAddr,
|
|
|
|
Ratelimit: s.conf.Ratelimit,
|
|
|
|
RatelimitWhitelist: s.conf.RatelimitWhitelist,
|
|
|
|
RefuseAny: s.conf.RefuseAny,
|
2019-03-20 14:24:33 +03:00
|
|
|
CacheEnabled: true,
|
2019-05-15 15:08:15 +03:00
|
|
|
Upstreams: s.conf.Upstreams,
|
|
|
|
DomainsReservedUpstreams: s.conf.DomainsReservedUpstreams,
|
2019-03-20 14:24:33 +03:00
|
|
|
Handler: s.handleDNSRequest,
|
2019-05-15 15:08:15 +03:00
|
|
|
AllServers: s.conf.AllServers,
|
2018-12-24 15:19:52 +03:00
|
|
|
}
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2019-05-15 15:08:15 +03:00
|
|
|
if s.conf.TLSListenAddr != nil && s.conf.CertificateChain != "" && s.conf.PrivateKey != "" {
|
|
|
|
proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
|
|
|
|
keypair, err := tls.X509KeyPair([]byte(s.conf.CertificateChain), []byte(s.conf.PrivateKey))
|
2019-02-12 17:23:38 +03:00
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "Failed to parse TLS keypair")
|
|
|
|
}
|
2019-04-17 12:02:56 +03:00
|
|
|
proxyConfig.TLSConfig = &tls.Config{
|
|
|
|
Certificates: []tls.Certificate{keypair},
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
}
|
2019-02-12 17:23:38 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
if proxyConfig.UDPListenAddr == nil {
|
|
|
|
proxyConfig.UDPListenAddr = defaultValues.UDPListenAddr
|
|
|
|
}
|
|
|
|
|
2019-01-05 22:15:20 +03:00
|
|
|
if proxyConfig.TCPListenAddr == nil {
|
|
|
|
proxyConfig.TCPListenAddr = defaultValues.TCPListenAddr
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
if len(proxyConfig.Upstreams) == 0 {
|
|
|
|
proxyConfig.Upstreams = defaultValues.Upstreams
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:27:14 +03:00
|
|
|
// Initialize and start the DNS proxy
|
2018-12-24 15:19:52 +03:00
|
|
|
s.dnsProxy = &proxy.Proxy{Config: proxyConfig}
|
2018-12-24 15:27:14 +03:00
|
|
|
return s.dnsProxy.Start()
|
|
|
|
}
|
2018-12-24 15:19:52 +03:00
|
|
|
|
2018-12-24 15:27:14 +03:00
|
|
|
// Initializes the DNS filter
|
|
|
|
func (s *Server) initDNSFilter() error {
|
2019-02-07 18:24:12 +03:00
|
|
|
log.Tracef("Creating dnsfilter")
|
2019-05-16 17:32:15 +03:00
|
|
|
|
|
|
|
var filters map[int]string
|
|
|
|
filters = nil
|
2019-05-15 15:08:15 +03:00
|
|
|
if s.conf.FilteringEnabled {
|
2019-05-16 17:32:15 +03:00
|
|
|
filters = make(map[int]string)
|
|
|
|
for _, f := range s.conf.Filters {
|
|
|
|
filters[int(f.ID)] = string(f.Data)
|
2018-12-24 15:27:14 +03:00
|
|
|
}
|
|
|
|
}
|
2019-05-16 17:32:15 +03:00
|
|
|
|
|
|
|
s.dnsFilter = dnsfilter.New(&s.conf.Config, filters)
|
|
|
|
if s.dnsFilter == nil {
|
|
|
|
return fmt.Errorf("could not initialize dnsfilter")
|
|
|
|
}
|
2018-12-24 15:27:14 +03:00
|
|
|
return nil
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// Stop stops the DNS server
|
2018-11-28 15:40:56 +03:00
|
|
|
func (s *Server) Stop() error {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2018-12-24 15:19:52 +03:00
|
|
|
return s.stopInternal()
|
|
|
|
}
|
|
|
|
|
|
|
|
// stopInternal stops without locking
|
|
|
|
func (s *Server) stopInternal() error {
|
|
|
|
if s.dnsProxy != nil {
|
|
|
|
err := s.dnsProxy.Stop()
|
|
|
|
s.dnsProxy = nil
|
2018-11-28 15:40:56 +03:00
|
|
|
if err != nil {
|
2018-12-24 15:19:52 +03:00
|
|
|
return errorx.Decorate(err, "could not stop the DNS server properly")
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
}
|
2018-12-05 14:21:48 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
if s.dnsFilter != nil {
|
|
|
|
s.dnsFilter.Destroy()
|
|
|
|
s.dnsFilter = nil
|
|
|
|
}
|
|
|
|
|
2018-12-05 14:21:48 +03:00
|
|
|
// flush remainder to file
|
2019-05-15 13:11:36 +03:00
|
|
|
return s.queryLog.flushLogBuffer(true)
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// IsRunning returns true if the DNS server is running
|
2018-11-28 16:43:50 +03:00
|
|
|
func (s *Server) IsRunning() bool {
|
|
|
|
s.RLock()
|
|
|
|
isRunning := true
|
2018-12-24 15:19:52 +03:00
|
|
|
if s.dnsProxy == nil {
|
2018-11-28 16:43:50 +03:00
|
|
|
isRunning = false
|
|
|
|
}
|
|
|
|
s.RUnlock()
|
|
|
|
return isRunning
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// Reconfigure applies the new configuration to the DNS server
|
|
|
|
func (s *Server) Reconfigure(config *ServerConfig) error {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2018-12-24 15:19:52 +03: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 15:40:56 +03:00
|
|
|
}
|
2018-12-24 15:19:52 +03:00
|
|
|
err = s.startInternal(config)
|
|
|
|
if err != nil {
|
|
|
|
return errorx.Decorate(err, "could not reconfigure the server")
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-02-22 15:52:12 +03: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()
|
|
|
|
s.dnsProxy.ServeHTTP(w, r)
|
|
|
|
s.RUnlock()
|
|
|
|
}
|
|
|
|
|
2019-02-10 20:47:43 +03:00
|
|
|
// GetQueryLog returns a map with the current query log ready to be converted to a JSON
|
|
|
|
func (s *Server) GetQueryLog() []map[string]interface{} {
|
2019-02-22 15:52:12 +03:00
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
2019-02-10 20:47:43 +03:00
|
|
|
return s.queryLog.getQueryLog()
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetStatsTop returns the current stop stats
|
|
|
|
func (s *Server) GetStatsTop() *StatsTop {
|
2019-02-22 15:52:12 +03:00
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
2019-02-10 20:47:43 +03:00
|
|
|
return s.queryLog.runningTop.getStatsTop()
|
|
|
|
}
|
|
|
|
|
2019-02-11 14:22:36 +03:00
|
|
|
// PurgeStats purges current server stats
|
|
|
|
func (s *Server) PurgeStats() {
|
2019-02-22 15:52:12 +03:00
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2019-02-10 20:47:43 +03:00
|
|
|
s.stats.purgeStats()
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAggregatedStats returns aggregated stats data for the 24 hours
|
|
|
|
func (s *Server) GetAggregatedStats() map[string]interface{} {
|
2019-02-22 15:52:12 +03:00
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
2019-02-10 20:47:43 +03:00
|
|
|
return s.stats.getAggregatedStats()
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetStatsHistory gets stats history aggregated by the specified time unit
|
|
|
|
// timeUnit is either time.Second, time.Minute, time.Hour, or 24*time.Hour
|
|
|
|
// start is start of the time range
|
|
|
|
// end is end of the time range
|
|
|
|
// returns nil if time unit is not supported
|
|
|
|
func (s *Server) GetStatsHistory(timeUnit time.Duration, startTime time.Time, endTime time.Time) (map[string]interface{}, error) {
|
2019-02-22 15:52:12 +03:00
|
|
|
s.RLock()
|
|
|
|
defer s.RUnlock()
|
2019-02-10 20:47:43 +03:00
|
|
|
return s.stats.getStatsHistory(timeUnit, startTime, endTime)
|
|
|
|
}
|
|
|
|
|
2018-12-24 18:47:33 +03:00
|
|
|
// handleDNSRequest filters the incoming DNS requests and writes them to the query log
|
|
|
|
func (s *Server) handleDNSRequest(p *proxy.Proxy, d *proxy.DNSContext) error {
|
2018-12-24 15:19:52 +03:00
|
|
|
start := time.Now()
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// use dnsfilter before cache -- changed settings or filters would require cache invalidation otherwise
|
|
|
|
res, err := s.filterDNSRequest(d)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
2018-11-30 13:51:15 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
if d.Res == nil {
|
|
|
|
// request was not filtered so let it be processed further
|
2018-12-24 18:47:33 +03:00
|
|
|
err = p.Resolve(d)
|
2018-12-24 15:19:52 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-11-30 13:51:15 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
shouldLog := true
|
|
|
|
msg := d.Req
|
2018-11-30 13:51:15 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// don't log ANY request if refuseAny is enabled
|
2019-05-15 15:08:15 +03:00
|
|
|
if len(msg.Question) >= 1 && msg.Question[0].Qtype == dns.TypeANY && s.conf.RefuseAny {
|
2018-12-24 15:19:52 +03:00
|
|
|
shouldLog = false
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2019-05-15 15:08:15 +03:00
|
|
|
if s.conf.QueryLogEnabled && shouldLog {
|
2018-12-24 15:19:52 +03:00
|
|
|
elapsed := time.Since(start)
|
|
|
|
upstreamAddr := ""
|
|
|
|
if d.Upstream != nil {
|
|
|
|
upstreamAddr = d.Upstream.Address()
|
|
|
|
}
|
2019-02-10 20:47:43 +03:00
|
|
|
entry := s.queryLog.logRequest(msg, d.Res, res, elapsed, d.Addr, upstreamAddr)
|
|
|
|
if entry != nil {
|
|
|
|
s.stats.incrementCounters(entry)
|
|
|
|
}
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
// filterDNSRequest applies the dnsFilter and sets d.Res if the request was filtered
|
|
|
|
func (s *Server) filterDNSRequest(d *proxy.DNSContext) (*dnsfilter.Result, error) {
|
|
|
|
msg := d.Req
|
|
|
|
host := strings.TrimSuffix(msg.Question[0].Name, ".")
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
s.RLock()
|
2019-05-15 15:08:15 +03:00
|
|
|
protectionEnabled := s.conf.ProtectionEnabled
|
2018-12-24 15:19:52 +03:00
|
|
|
dnsFilter := s.dnsFilter
|
|
|
|
s.RUnlock()
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
if !protectionEnabled {
|
|
|
|
return nil, nil
|
2018-12-05 18:47:03 +03:00
|
|
|
}
|
|
|
|
|
2018-12-11 14:20:14 +03:00
|
|
|
var res dnsfilter.Result
|
|
|
|
var err error
|
2018-11-28 15:40:56 +03:00
|
|
|
|
2019-05-28 14:14:12 +03:00
|
|
|
clientAddr := ""
|
|
|
|
if d.Addr != nil {
|
|
|
|
clientAddr, _, _ = net.SplitHostPort(d.Addr.String())
|
|
|
|
}
|
|
|
|
res, err = dnsFilter.CheckHost(host, d.Req.Question[0].Qtype, clientAddr)
|
2018-11-28 15:40:56 +03:00
|
|
|
if err != nil {
|
2018-12-24 15:19:52 +03:00
|
|
|
// Return immediately if there's an error
|
|
|
|
return nil, errorx.Decorate(err, "dnsfilter failed to check host '%s'", host)
|
|
|
|
} else if res.IsFiltered {
|
2018-12-29 17:23:42 +03:00
|
|
|
// log.Tracef("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule)
|
2018-12-24 15:19:52 +03:00
|
|
|
d.Res = s.genDNSFilterMessage(d, &res)
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
return &res, err
|
2018-12-05 14:03:41 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03: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 14:03:41 +03:00
|
|
|
|
2019-05-22 15:50:22 +03:00
|
|
|
if m.Question[0].Qtype != dns.TypeA && m.Question[0].Qtype != dns.TypeAAAA {
|
2018-12-24 15:19:52 +03:00
|
|
|
return s.genNXDomain(m)
|
2018-12-05 14:03:41 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
switch result.Reason {
|
|
|
|
case dnsfilter.FilteredSafeBrowsing:
|
2019-02-22 18:41:59 +03:00
|
|
|
return s.genBlockedHost(m, safeBrowsingBlockHost, d)
|
2018-12-24 15:19:52 +03:00
|
|
|
case dnsfilter.FilteredParental:
|
2019-02-22 18:41:59 +03:00
|
|
|
return s.genBlockedHost(m, parentalBlockHost, d)
|
2018-12-24 15:19:52 +03:00
|
|
|
default:
|
2019-01-24 20:11:01 +03:00
|
|
|
if result.IP != nil {
|
2019-05-22 15:50:22 +03:00
|
|
|
if m.Question[0].Qtype == dns.TypeA {
|
|
|
|
return s.genARecord(m, result.IP)
|
|
|
|
} else if m.Question[0].Qtype == dns.TypeAAAA {
|
|
|
|
return s.genAAAARecord(m, result.IP)
|
|
|
|
}
|
|
|
|
|
|
|
|
// empty response
|
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetReply(m)
|
|
|
|
return &resp
|
2018-12-05 18:47:03 +03:00
|
|
|
}
|
|
|
|
|
2019-05-15 15:08:15 +03:00
|
|
|
if s.conf.BlockingMode == "null_ip" {
|
2019-05-22 15:50:22 +03: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-05-04 23:51:14 +03:00
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
return s.genNXDomain(m)
|
2018-12-05 14:22:09 +03:00
|
|
|
}
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2018-12-05 14:03:41 +03:00
|
|
|
func (s *Server) genServerFailure(request *dns.Msg) *dns.Msg {
|
2018-11-28 15:40:56 +03:00
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetRcode(request, dns.RcodeServerFailure)
|
2018-12-05 18:47:03 +03:00
|
|
|
resp.RecursionAvailable = true
|
|
|
|
return &resp
|
|
|
|
}
|
|
|
|
|
2018-12-24 15:19:52 +03:00
|
|
|
func (s *Server) genARecord(request *dns.Msg, ip net.IP) *dns.Msg {
|
2018-12-05 18:47:03 +03:00
|
|
|
resp := dns.Msg{}
|
2018-12-24 15:19:52 +03:00
|
|
|
resp.SetReply(request)
|
2019-05-22 15:50:22 +03:00
|
|
|
resp.Answer = append(resp.Answer, s.genAAnswer(request, ip))
|
|
|
|
return &resp
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) genAAAARecord(request *dns.Msg, ip net.IP) *dns.Msg {
|
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetReply(request)
|
|
|
|
resp.Answer = append(resp.Answer, s.genAAAAAnswer(request, ip))
|
2018-12-05 14:03:41 +03:00
|
|
|
return &resp
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
|
2019-05-22 15:50:22 +03: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-02-22 18:41:59 +03:00
|
|
|
func (s *Server) genBlockedHost(request *dns.Msg, newAddr string, d *proxy.DNSContext) *dns.Msg {
|
2018-12-11 15:02:23 +03: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 18:41:59 +03:00
|
|
|
|
|
|
|
newContext := &proxy.DNSContext{
|
|
|
|
Proto: d.Proto,
|
|
|
|
Addr: d.Addr,
|
|
|
|
StartTime: time.Now(),
|
|
|
|
Req: &replReq,
|
|
|
|
}
|
|
|
|
|
|
|
|
err := s.dnsProxy.Resolve(newContext)
|
2018-12-11 15:02:23 +03:00
|
|
|
if err != nil {
|
2019-02-22 18:41:59 +03:00
|
|
|
log.Printf("Couldn't look up replacement host '%s': %s", newAddr, err)
|
2018-12-11 15:02:23 +03:00
|
|
|
return s.genServerFailure(request)
|
|
|
|
}
|
|
|
|
|
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetReply(request)
|
|
|
|
resp.Authoritative, resp.RecursionAvailable = true, true
|
2019-02-22 18:41:59 +03:00
|
|
|
if newContext.Res != nil {
|
|
|
|
for _, answer := range newContext.Res.Answer {
|
2018-12-11 15:02:23 +03:00
|
|
|
answer.Header().Name = request.Question[0].Name
|
|
|
|
resp.Answer = append(resp.Answer, answer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &resp
|
|
|
|
}
|
|
|
|
|
2018-12-05 14:03:41 +03:00
|
|
|
func (s *Server) genNXDomain(request *dns.Msg) *dns.Msg {
|
2018-11-28 15:40:56 +03:00
|
|
|
resp := dns.Msg{}
|
|
|
|
resp.SetRcode(request, dns.RcodeNameError)
|
2018-12-05 18:47:03 +03:00
|
|
|
resp.RecursionAvailable = true
|
2018-11-28 15:40:56 +03:00
|
|
|
resp.Ns = s.genSOA(request)
|
2018-12-05 14:03:41 +03:00
|
|
|
return &resp
|
2018-11-28 15:40:56 +03: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 15:08:15 +03:00
|
|
|
Ttl: s.conf.BlockedResponseTTL,
|
2018-11-28 15:40:56 +03: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 18:14:12 +03:00
|
|
|
soa.Hdr.Ttl = defaultValues.BlockedResponseTTL
|
2018-11-28 15:40:56 +03:00
|
|
|
}
|
|
|
|
if len(zone) > 0 && zone[0] != '.' {
|
|
|
|
soa.Mbox += zone
|
|
|
|
}
|
|
|
|
return []dns.RR{&soa}
|
|
|
|
}
|