Pull request 2087: AG-27616-upd-proxy-ratelimit-whitelist

Squashed commit of the following:

commit 099a2eb11609a07a1cb72d9e15da3e668042de1d
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue Dec 5 17:25:49 2023 +0300

    all: upd proxy

commit db07130df80ed06b867f6ce6878908b1eb93a934
Merge: 9e6e8e7cf 75cb9d412
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue Dec 5 14:44:44 2023 +0300

    Merge branch 'master' into AG-27616-upd-proxy-ratelimit-whitelist

commit 9e6e8e7cfc80507cff81761dd3964cf7777ac58b
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Wed Nov 29 19:46:17 2023 +0300

    all: imp tests

commit e753bb53880c2a0791d97079a12960e0b1d667ed
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Wed Nov 29 13:35:21 2023 +0300

    all: upd proxy ratelimit whitelist
This commit is contained in:
Stanislav Chzhen 2023-12-05 17:43:50 +03:00
parent 75cb9d412a
commit 99af7f46de
13 changed files with 82 additions and 135 deletions

6
go.mod
View File

@ -3,8 +3,8 @@ module github.com/AdguardTeam/AdGuardHome
go 1.20 go 1.20
require ( require (
github.com/AdguardTeam/dnsproxy v0.59.2-0.20231129093901-b1d6bad15937 github.com/AdguardTeam/dnsproxy v0.60.0
github.com/AdguardTeam/golibs v0.17.2 github.com/AdguardTeam/golibs v0.18.0
github.com/AdguardTeam/urlfilter v0.17.3 github.com/AdguardTeam/urlfilter v0.17.3
github.com/NYTimes/gziphandler v1.1.1 github.com/NYTimes/gziphandler v1.1.1
github.com/ameshkov/dnscrypt/v2 v2.2.7 github.com/ameshkov/dnscrypt/v2 v2.2.7
@ -64,5 +64,3 @@ require (
golang.org/x/text v0.14.0 // indirect golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.15.0 // indirect golang.org/x/tools v0.15.0 // indirect
) )
require github.com/jessevdk/go-flags v1.5.0 // indirect

14
go.sum
View File

@ -1,9 +1,7 @@
github.com/AdguardTeam/dnsproxy v0.59.1 h1:G/6T32EuPF0rhRkACkLFwD0pajI9351a1LACpuA2UcE= github.com/AdguardTeam/dnsproxy v0.60.0 h1:0gLYoFyWRhQ1MP6g6AqqZXL5/h2QM4FE1aybUZ5HGuE=
github.com/AdguardTeam/dnsproxy v0.59.1/go.mod h1:ZvkbM71HwpilgkCnTubDiR4Ba6x5Qvnhy2iasMWaTDM= github.com/AdguardTeam/dnsproxy v0.60.0/go.mod h1:B7FvvTFQZBfey1cJXQo732EyCLX6xj4JqrciCawATzg=
github.com/AdguardTeam/dnsproxy v0.59.2-0.20231129093901-b1d6bad15937 h1:ZGOsX3UYLtrPJbBoKL9Zv6PLnO1duE8RgOsoxFmXGjQ= github.com/AdguardTeam/golibs v0.18.0 h1:ckS2YK7t2Ub6UkXl0fnreVaM15Zb07Hh1gmFqttjpWg=
github.com/AdguardTeam/dnsproxy v0.59.2-0.20231129093901-b1d6bad15937/go.mod h1:ZvkbM71HwpilgkCnTubDiR4Ba6x5Qvnhy2iasMWaTDM= github.com/AdguardTeam/golibs v0.18.0/go.mod h1:DKhCIXHcUYtBhU8ibTLKh1paUL96n5zhQBlx763sj+U=
github.com/AdguardTeam/golibs v0.17.2 h1:vg6wHMjUKscnyPGRvxS5kAt7Uw4YxcJiITZliZ476W8=
github.com/AdguardTeam/golibs v0.17.2/go.mod h1:DKhCIXHcUYtBhU8ibTLKh1paUL96n5zhQBlx763sj+U=
github.com/AdguardTeam/urlfilter v0.17.3 h1:fg/ObbnO0Cv6aw0tW6N/ETDMhhNvmcUUOZ7HlmKC3rw= github.com/AdguardTeam/urlfilter v0.17.3 h1:fg/ObbnO0Cv6aw0tW6N/ETDMhhNvmcUUOZ7HlmKC3rw=
github.com/AdguardTeam/urlfilter v0.17.3/go.mod h1:Jru7jFfeH2CoDf150uDs+rRYcZBzHHBz05r9REyDKyE= github.com/AdguardTeam/urlfilter v0.17.3/go.mod h1:Jru7jFfeH2CoDf150uDs+rRYcZBzHHBz05r9REyDKyE=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
@ -54,8 +52,6 @@ github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714 h1:/jC7qQFrv8
github.com/insomniacslk/dhcp v0.0.0-20231016090811-6a2c8fbdcc1c h1:PgxFEySCI41sH0mB7/2XswdXbUykQsRUGod8Rn+NubM= github.com/insomniacslk/dhcp v0.0.0-20231016090811-6a2c8fbdcc1c h1:PgxFEySCI41sH0mB7/2XswdXbUykQsRUGod8Rn+NubM=
github.com/insomniacslk/dhcp v0.0.0-20231016090811-6a2c8fbdcc1c/go.mod h1:3A9PQ1cunSDF/1rbTq99Ts4pVnycWg+vlPkfeD2NLFI= github.com/insomniacslk/dhcp v0.0.0-20231016090811-6a2c8fbdcc1c/go.mod h1:3A9PQ1cunSDF/1rbTq99Ts4pVnycWg+vlPkfeD2NLFI=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.1.1-0.20230202152459-5c7d0dd6ab86 h1:elKwZS1OcdQ0WwEDBeqxKwb7WB62QX8bvZ/FJnVXIfk= github.com/josharian/native v1.1.1-0.20230202152459-5c7d0dd6ab86 h1:elKwZS1OcdQ0WwEDBeqxKwb7WB62QX8bvZ/FJnVXIfk=
@ -104,7 +100,6 @@ github.com/shirou/gopsutil/v3 v3.23.7 h1:C+fHO8hfIppoJ1WdsVm1RoI0RwXoNdfTK7yWXV0
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
@ -150,7 +145,6 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View File

@ -67,7 +67,7 @@ type Config struct {
RatelimitSubnetLenIPv6 int `yaml:"ratelimit_subnet_len_ipv6"` RatelimitSubnetLenIPv6 int `yaml:"ratelimit_subnet_len_ipv6"`
// RatelimitWhitelist is the list of whitelisted client IP addresses. // RatelimitWhitelist is the list of whitelisted client IP addresses.
RatelimitWhitelist []string `yaml:"ratelimit_whitelist"` RatelimitWhitelist []netip.Addr `yaml:"ratelimit_whitelist"`
// RefuseAny, if true, refuse ANY requests. // RefuseAny, if true, refuse ANY requests.
RefuseAny bool `yaml:"refuse_any"` RefuseAny bool `yaml:"refuse_any"`
@ -300,8 +300,8 @@ func (s *Server) newProxyConfig() (conf *proxy.Config, err error) {
conf = &proxy.Config{ conf = &proxy.Config{
HTTP3: srvConf.ServeHTTP3, HTTP3: srvConf.ServeHTTP3,
Ratelimit: int(srvConf.Ratelimit), Ratelimit: int(srvConf.Ratelimit),
RatelimitSubnetMaskIPv4: net.CIDRMask(srvConf.RatelimitSubnetLenIPv4, netutil.IPv4BitLen), RatelimitSubnetLenIPv4: srvConf.RatelimitSubnetLenIPv4,
RatelimitSubnetMaskIPv6: net.CIDRMask(srvConf.RatelimitSubnetLenIPv6, netutil.IPv6BitLen), RatelimitSubnetLenIPv6: srvConf.RatelimitSubnetLenIPv6,
RatelimitWhitelist: srvConf.RatelimitWhitelist, RatelimitWhitelist: srvConf.RatelimitWhitelist,
RefuseAny: srvConf.RefuseAny, RefuseAny: srvConf.RefuseAny,
TrustedProxies: srvConf.TrustedProxies, TrustedProxies: srvConf.TrustedProxies,

View File

@ -299,7 +299,7 @@ func (s *Server) WriteDiskConfig(c *Config) {
sc := s.conf.Config sc := s.conf.Config
*c = sc *c = sc
c.RatelimitWhitelist = stringutil.CloneSlice(sc.RatelimitWhitelist) c.RatelimitWhitelist = slices.Clone(sc.RatelimitWhitelist)
c.BootstrapDNS = stringutil.CloneSlice(sc.BootstrapDNS) c.BootstrapDNS = stringutil.CloneSlice(sc.BootstrapDNS)
c.FallbackDNS = stringutil.CloneSlice(sc.FallbackDNS) c.FallbackDNS = stringutil.CloneSlice(sc.FallbackDNS)
c.AllowedClients = stringutil.CloneSlice(sc.AllowedClients) c.AllowedClients = stringutil.CloneSlice(sc.AllowedClients)

View File

@ -54,13 +54,10 @@ const (
testMessagesCount = 10 testMessagesCount = 10
) )
// testClientAddr is the common net.Addr for tests. // testClientAddrPort is the common net.Addr for tests.
// //
// TODO(a.garipov): Use more. // TODO(a.garipov): Use more.
var testClientAddr net.Addr = &net.TCPAddr{ var testClientAddrPort = netip.MustParseAddrPort("1.2.3.4:12345")
IP: net.IP{1, 2, 3, 4},
Port: 12345,
}
func startDeferStop(t *testing.T, s *Server) { func startDeferStop(t *testing.T, s *Server) {
t.Helper() t.Helper()

View File

@ -10,7 +10,6 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/urlfilter/rules" "github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns" "github.com/miekg/dns"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
@ -28,8 +27,7 @@ func (s *Server) beforeRequestHandler(
return false, fmt.Errorf("getting clientid: %w", err) return false, fmt.Errorf("getting clientid: %w", err)
} }
addrPort := netutil.NetAddrToAddrPort(pctx.Addr) blocked, _ := s.IsBlockedClient(pctx.Addr.Addr(), clientID)
blocked, _ := s.IsBlockedClient(addrPort.Addr(), clientID)
if blocked { if blocked {
return s.preBlockedResponse(pctx) return s.preBlockedResponse(pctx)
} }
@ -60,8 +58,7 @@ func (s *Server) clientRequestFilteringSettings(dctx *dnsContext) (setts *filter
setts = s.dnsFilter.Settings() setts = s.dnsFilter.Settings()
setts.ProtectionEnabled = dctx.protectionEnabled setts.ProtectionEnabled = dctx.protectionEnabled
if s.conf.FilterHandler != nil { if s.conf.FilterHandler != nil {
addrPort := netutil.NetAddrToAddrPort(dctx.proxyCtx.Addr) s.conf.FilterHandler(dctx.proxyCtx.Addr.Addr(), dctx.clientID, setts)
s.conf.FilterHandler(addrPort.Addr(), dctx.clientID, setts)
} }
return setts return setts

View File

@ -187,7 +187,7 @@ func TestHandleDNSRequest_handleDNSRequest(t *testing.T) {
dctx := &proxy.DNSContext{ dctx := &proxy.DNSContext{
Proto: proxy.ProtoUDP, Proto: proxy.ProtoUDP,
Req: tc.req, Req: tc.req,
Addr: &net.UDPAddr{IP: net.IP{127, 0, 0, 1}, Port: 1}, Addr: testClientAddrPort,
} }
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
@ -326,7 +326,7 @@ func TestHandleDNSRequest_filterDNSResponse(t *testing.T) {
Proto: proxy.ProtoUDP, Proto: proxy.ProtoUDP,
Req: tc.req, Req: tc.req,
Res: resp, Res: resp,
Addr: &net.UDPAddr{IP: net.IP{127, 0, 0, 1}, Port: 1}, Addr: testClientAddrPort,
} }
dctx := &dnsContext{ dctx := &dnsContext{

View File

@ -52,7 +52,7 @@ type jsonDNSConfig struct {
RatelimitSubnetLenIPv6 *int `json:"ratelimit_subnet_len_ipv6"` RatelimitSubnetLenIPv6 *int `json:"ratelimit_subnet_len_ipv6"`
// RatelimitWhitelist is a list of IP addresses excluded from rate limiting. // RatelimitWhitelist is a list of IP addresses excluded from rate limiting.
RatelimitWhitelist *[]string `json:"ratelimit_whitelist"` RatelimitWhitelist *[]netip.Addr `json:"ratelimit_whitelist"`
// BlockingMode defines the way blocked responses are constructed. // BlockingMode defines the way blocked responses are constructed.
BlockingMode *filtering.BlockingMode `json:"blocking_mode"` BlockingMode *filtering.BlockingMode `json:"blocking_mode"`
@ -129,7 +129,7 @@ func (s *Server) getDNSConfig() (c *jsonDNSConfig) {
ratelimit := s.conf.Ratelimit ratelimit := s.conf.Ratelimit
ratelimitSubnetLenIPv4 := s.conf.RatelimitSubnetLenIPv4 ratelimitSubnetLenIPv4 := s.conf.RatelimitSubnetLenIPv4
ratelimitSubnetLenIPv6 := s.conf.RatelimitSubnetLenIPv6 ratelimitSubnetLenIPv6 := s.conf.RatelimitSubnetLenIPv6
ratelimitWhitelist := stringutil.CloneSliceOrEmpty(s.conf.RatelimitWhitelist) ratelimitWhitelist := append([]netip.Addr{}, s.conf.RatelimitWhitelist...)
customIP := s.conf.EDNSClientSubnet.CustomIP customIP := s.conf.EDNSClientSubnet.CustomIP
enableEDNSClientSubnet := s.conf.EDNSClientSubnet.Enabled enableEDNSClientSubnet := s.conf.EDNSClientSubnet.Enabled
@ -291,12 +291,6 @@ func (req *jsonDNSConfig) validate(privateNets netutil.SubnetSet) (err error) {
return err return err
} }
err = req.checkRatelimitWhitelist()
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
err = req.checkBlockingMode() err = req.checkBlockingMode()
if err != nil { if err != nil {
// Don't wrap the error since it's informative enough as is. // Don't wrap the error since it's informative enough as is.
@ -405,21 +399,6 @@ func checkInclusion(ptr *int, minN, maxN int) (err error) {
return nil return nil
} }
// checkRatelimitWhitelist returns an error if any of IP addresses is invalid.
func (req *jsonDNSConfig) checkRatelimitWhitelist() (err error) {
if req.RatelimitWhitelist == nil {
return nil
}
for i, ipStr := range *req.RatelimitWhitelist {
if _, err = netip.ParseAddr(ipStr); err != nil {
return fmt.Errorf("ratelimit whitelist: at index %d: %w", i, err)
}
}
return nil
}
// handleSetConfig handles requests to the POST /control/dns_config endpoint. // handleSetConfig handles requests to the POST /control/dns_config endpoint.
func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) { func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
req := &jsonDNSConfig{} req := &jsonDNSConfig{}

View File

@ -196,8 +196,7 @@ func TestDNSForwardHTTP_handleSetConfig(t *testing.T) {
wantSet: "", wantSet: "",
}, { }, {
name: "ratelimit_whitelist_not_ip", name: "ratelimit_whitelist_not_ip",
wantSet: `validating dns config: ratelimit whitelist: at index 1: ParseAddr("not.ip"): ` + wantSet: `decoding request: ParseAddr("not.ip"): unexpected character (at "not.ip")`,
`unexpected character (at "not.ip")`,
}, { }, {
name: "edns_cs_enabled", name: "edns_cs_enabled",
wantSet: "", wantSet: "",

View File

@ -191,7 +191,7 @@ func (s *Server) processInitial(dctx *dnsContext) (rc resultCode) {
defer log.Debug("dnsforward: finished processing initial") defer log.Debug("dnsforward: finished processing initial")
pctx := dctx.proxyCtx pctx := dctx.proxyCtx
s.processClientIP(pctx.Addr) s.processClientIP(pctx.Addr.Addr())
q := pctx.Req.Question[0] q := pctx.Req.Question[0]
qt := q.Qtype qt := q.Qtype
@ -228,9 +228,8 @@ func (s *Server) processInitial(dctx *dnsContext) (rc resultCode) {
} }
// processClientIP sends the client IP address to s.addrProc, if needed. // processClientIP sends the client IP address to s.addrProc, if needed.
func (s *Server) processClientIP(addr net.Addr) { func (s *Server) processClientIP(addr netip.Addr) {
clientIP := netutil.NetAddrToAddrPort(addr).Addr() if !addr.IsValid() {
if clientIP == (netip.Addr{}) {
log.Info("dnsforward: warning: bad client addr %q", addr) log.Info("dnsforward: warning: bad client addr %q", addr)
return return
@ -241,7 +240,7 @@ func (s *Server) processClientIP(addr net.Addr) {
s.serverLock.RLock() s.serverLock.RLock()
defer s.serverLock.RUnlock() defer s.serverLock.RUnlock()
s.addrProc.Process(clientIP) s.addrProc.Process(addr)
} }
// processDDRQuery responds to Discovery of Designated Resolvers (DDR) SVCB // processDDRQuery responds to Discovery of Designated Resolvers (DDR) SVCB
@ -351,12 +350,7 @@ func (s *Server) processDetermineLocal(dctx *dnsContext) (rc resultCode) {
rc = resultCodeSuccess rc = resultCodeSuccess
var ip net.IP dctx.isLocalClient = s.privateNets.Contains(dctx.proxyCtx.Addr.Addr().AsSlice())
if ip, _ = netutil.IPAndPortFromAddr(dctx.proxyCtx.Addr); ip == nil {
return rc
}
dctx.isLocalClient = s.privateNets.Contains(ip)
return rc return rc
} }
@ -831,12 +825,12 @@ func (s *Server) dhcpHostFromRequest(q *dns.Question) (reqHost string) {
// setCustomUpstream sets custom upstream settings in pctx, if necessary. // setCustomUpstream sets custom upstream settings in pctx, if necessary.
func (s *Server) setCustomUpstream(pctx *proxy.DNSContext, clientID string) { func (s *Server) setCustomUpstream(pctx *proxy.DNSContext, clientID string) {
if pctx.Addr == nil || s.conf.ClientsContainer == nil { if !pctx.Addr.IsValid() || s.conf.ClientsContainer == nil {
return return
} }
// Use the ClientID first, since it has a higher priority. // Use the ClientID first, since it has a higher priority.
id := stringutil.Coalesce(clientID, ipStringFromAddr(pctx.Addr)) id := stringutil.Coalesce(clientID, pctx.Addr.Addr().String())
upsConf, err := s.conf.ClientsContainer.UpstreamConfigByID(id, s.bootstrap) upsConf, err := s.conf.ClientsContainer.UpstreamConfigByID(id, s.bootstrap)
if err != nil { if err != nil {
log.Error("dnsforward: getting custom upstreams for client %s: %s", id, err) log.Error("dnsforward: getting custom upstreams for client %s: %s", id, err)

View File

@ -97,14 +97,14 @@ func TestServer_ProcessInitial(t *testing.T) {
dctx := &dnsContext{ dctx := &dnsContext{
proxyCtx: &proxy.DNSContext{ proxyCtx: &proxy.DNSContext{
Req: createTestMessageWithType(tc.target, tc.qType), Req: createTestMessageWithType(tc.target, tc.qType),
Addr: testClientAddr, Addr: testClientAddrPort,
RequestID: 1234, RequestID: 1234,
}, },
} }
gotRC := s.processInitial(dctx) gotRC := s.processInitial(dctx)
assert.Equal(t, tc.wantRC, gotRC) assert.Equal(t, tc.wantRC, gotRC)
assert.Equal(t, netutil.NetAddrToAddrPort(testClientAddr).Addr(), gotAddr) assert.Equal(t, testClientAddrPort.Addr(), gotAddr)
if tc.wantRCode > 0 { if tc.wantRCode > 0 {
gotResp := dctx.proxyCtx.Res gotResp := dctx.proxyCtx.Res
@ -201,7 +201,7 @@ func TestServer_ProcessFilteringAfterResponse(t *testing.T) {
Proto: proxy.ProtoUDP, Proto: proxy.ProtoUDP,
Req: tc.req, Req: tc.req,
Res: resp, Res: resp,
Addr: testClientAddr, Addr: testClientAddrPort,
}, },
} }
@ -399,31 +399,25 @@ func TestServer_ProcessDetermineLocal(t *testing.T) {
testCases := []struct { testCases := []struct {
want assert.BoolAssertionFunc want assert.BoolAssertionFunc
name string name string
cliIP net.IP cliAddr netip.AddrPort
}{{ }{{
want: assert.True, want: assert.True,
name: "local", name: "local",
cliIP: net.IP{192, 168, 0, 1}, cliAddr: netip.MustParseAddrPort("192.168.0.1:1"),
}, { }, {
want: assert.False, want: assert.False,
name: "external", name: "external",
cliIP: net.IP{250, 249, 0, 1}, cliAddr: netip.MustParseAddrPort("250.249.0.1:1"),
}, { }, {
want: assert.False, want: assert.False,
name: "invalid", name: "invalid",
cliIP: net.IP{1, 2, 3, 4, 5}, cliAddr: netip.AddrPort{},
}, {
want: assert.False,
name: "nil",
cliIP: nil,
}} }}
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
proxyCtx := &proxy.DNSContext{ proxyCtx := &proxy.DNSContext{
Addr: &net.TCPAddr{ Addr: tc.cliAddr,
IP: tc.cliIP,
},
} }
dctx := &dnsContext{ dctx := &dnsContext{
proxyCtx: proxyCtx, proxyCtx: proxyCtx,
@ -711,31 +705,31 @@ func TestServer_ProcessRestrictLocal(t *testing.T) {
name string name string
want string want string
question net.IP question net.IP
cliIP net.IP cliAddr netip.AddrPort
wantLen int wantLen int
}{{ }{{
name: "from_local_to_external", name: "from_local_to_external",
want: "host1.example.net.", want: "host1.example.net.",
question: net.IP{254, 253, 252, 251}, question: net.IP{254, 253, 252, 251},
cliIP: net.IP{192, 168, 10, 10}, cliAddr: netip.MustParseAddrPort("192.168.10.10:1"),
wantLen: 1, wantLen: 1,
}, { }, {
name: "from_external_for_local", name: "from_external_for_local",
want: "", want: "",
question: net.IP{192, 168, 1, 1}, question: net.IP{192, 168, 1, 1},
cliIP: net.IP{254, 253, 252, 251}, cliAddr: netip.MustParseAddrPort("254.253.252.251:1"),
wantLen: 0, wantLen: 0,
}, { }, {
name: "from_local_for_local", name: "from_local_for_local",
want: "some.local-client.", want: "some.local-client.",
question: net.IP{192, 168, 1, 1}, question: net.IP{192, 168, 1, 1},
cliIP: net.IP{192, 168, 1, 2}, cliAddr: netip.MustParseAddrPort("192.168.1.2:1"),
wantLen: 1, wantLen: 1,
}, { }, {
name: "from_external_for_external", name: "from_external_for_external",
want: "host1.example.net.", want: "host1.example.net.",
question: net.IP{254, 253, 252, 251}, question: net.IP{254, 253, 252, 251},
cliIP: net.IP{254, 253, 252, 255}, cliAddr: netip.MustParseAddrPort("254.253.252.255:1"),
wantLen: 1, wantLen: 1,
}} }}
@ -747,9 +741,7 @@ func TestServer_ProcessRestrictLocal(t *testing.T) {
pctx := &proxy.DNSContext{ pctx := &proxy.DNSContext{
Proto: proxy.ProtoTCP, Proto: proxy.ProtoTCP,
Req: req, Req: req,
Addr: &net.TCPAddr{ Addr: tc.cliAddr,
IP: tc.cliIP,
},
} }
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
@ -794,7 +786,7 @@ func TestServer_ProcessLocalPTR_usingResolvers(t *testing.T) {
var dnsCtx *dnsContext var dnsCtx *dnsContext
setup := func(use bool) { setup := func(use bool) {
proxyCtx = &proxy.DNSContext{ proxyCtx = &proxy.DNSContext{
Addr: testClientAddr, Addr: testClientAddrPort,
Req: createTestMessageWithType(reqAddr, dns.TypePTR), Req: createTestMessageWithType(reqAddr, dns.TypePTR),
} }
dnsCtx = &dnsContext{ dnsCtx = &dnsContext{

View File

@ -10,9 +10,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/stats" "github.com/AdguardTeam/AdGuardHome/internal/stats"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/miekg/dns" "github.com/miekg/dns"
"golang.org/x/exp/slices"
) )
// Write Stats data and logs // Write Stats data and logs
@ -25,13 +23,12 @@ func (s *Server) processQueryLogsAndStats(dctx *dnsContext) (rc resultCode) {
host := aghnet.NormalizeDomain(q.Name) host := aghnet.NormalizeDomain(q.Name)
processingTime := time.Since(dctx.startTime) processingTime := time.Since(dctx.startTime)
ip, _ := netutil.IPAndPortFromAddr(pctx.Addr) ip := pctx.Addr.Addr().AsSlice()
ip = slices.Clone(ip)
s.anonymizer.Load()(ip) s.anonymizer.Load()(ip)
log.Debug("dnsforward: client ip for stats and querylog: %s", ip) log.Debug("dnsforward: client ip for stats and querylog: %s", ip)
ipStr := ip.String() ipStr := pctx.Addr.Addr().String()
ids := []string{ipStr, dctx.clientID} ids := []string{ipStr, dctx.clientID}
qt, cl := q.Qtype, q.Qclass qt, cl := q.Qtype, q.Qclass

View File

@ -1,7 +1,7 @@
package dnsforward package dnsforward
import ( import (
"net" "net/netip"
"testing" "testing"
"time" "time"
@ -65,7 +65,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name string name string
domain string domain string
proto proxy.Proto proto proxy.Proto
addr net.Addr addr netip.AddrPort
clientID string clientID string
wantLogProto querylog.ClientProto wantLogProto querylog.ClientProto
wantStatClient string wantStatClient string
@ -76,7 +76,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp", name: "success_udp",
domain: domain, domain: domain,
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -87,7 +87,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_tls_clientid", name: "success_tls_clientid",
domain: domain, domain: domain,
proto: proxy.ProtoTLS, proto: proxy.ProtoTLS,
addr: &net.TCPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "cli42", clientID: "cli42",
wantLogProto: querylog.ClientProtoDoT, wantLogProto: querylog.ClientProtoDoT,
wantStatClient: "cli42", wantStatClient: "cli42",
@ -98,7 +98,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_tls", name: "success_tls",
domain: domain, domain: domain,
proto: proxy.ProtoTLS, proto: proxy.ProtoTLS,
addr: &net.TCPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: querylog.ClientProtoDoT, wantLogProto: querylog.ClientProtoDoT,
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -109,7 +109,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_quic", name: "success_quic",
domain: domain, domain: domain,
proto: proxy.ProtoQUIC, proto: proxy.ProtoQUIC,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: querylog.ClientProtoDoQ, wantLogProto: querylog.ClientProtoDoQ,
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -120,7 +120,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_https", name: "success_https",
domain: domain, domain: domain,
proto: proxy.ProtoHTTPS, proto: proxy.ProtoHTTPS,
addr: &net.TCPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: querylog.ClientProtoDoH, wantLogProto: querylog.ClientProtoDoH,
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -131,7 +131,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_dnscrypt", name: "success_dnscrypt",
domain: domain, domain: domain,
proto: proxy.ProtoDNSCrypt, proto: proxy.ProtoDNSCrypt,
addr: &net.TCPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: querylog.ClientProtoDNSCrypt, wantLogProto: querylog.ClientProtoDNSCrypt,
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -142,7 +142,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp_filtered", name: "success_udp_filtered",
domain: domain, domain: domain,
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -153,7 +153,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp_sb", name: "success_udp_sb",
domain: domain, domain: domain,
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -164,7 +164,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp_ss", name: "success_udp_ss",
domain: domain, domain: domain,
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -175,7 +175,7 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp_pc", name: "success_udp_pc",
domain: domain, domain: domain,
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 1234}, addr: testClientAddrPort,
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.4", wantStatClient: "1.2.3.4",
@ -186,10 +186,10 @@ func TestServer_ProcessQueryLogsAndStats(t *testing.T) {
name: "success_udp_pc_empty_fqdn", name: "success_udp_pc_empty_fqdn",
domain: ".", domain: ".",
proto: proxy.ProtoUDP, proto: proxy.ProtoUDP,
addr: &net.UDPAddr{IP: net.IP{1, 2, 3, 5}, Port: 1234}, addr: netip.MustParseAddrPort("4.3.2.1:1234"),
clientID: "", clientID: "",
wantLogProto: "", wantLogProto: "",
wantStatClient: "1.2.3.5", wantStatClient: "4.3.2.1",
wantCode: resultCodeSuccess, wantCode: resultCodeSuccess,
reason: filtering.FilteredParental, reason: filtering.FilteredParental,
wantStatResult: stats.RParental, wantStatResult: stats.RParental,