From 491db0075090e2d658f687a7a7ca64d3ad398a1d Mon Sep 17 00:00:00 2001 From: Tobias Wiesing Date: Tue, 6 Oct 2026 13:15:08 +0200 Subject: [PATCH 1/2] exprhelpers: LookupHost goes through the DNS cache LookupHost called net.LookupHost on every evaluation. In a parser whitelist that is one DNS query per log line and name. It now uses dnscache.ForwardIPs, as MatchKnownBot does. --- pkg/exprhelpers/botfile_test.go | 8 +++-- pkg/exprhelpers/exprlib_test.go | 59 +++++++++++++++++++++++++++++++++ pkg/exprhelpers/helpers.go | 11 +++--- 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/pkg/exprhelpers/botfile_test.go b/pkg/exprhelpers/botfile_test.go index 1724edd8233..8e5fd4eae45 100644 --- a/pkg/exprhelpers/botfile_test.go +++ b/pkg/exprhelpers/botfile_test.go @@ -15,13 +15,15 @@ import ( ) // fakeResolver implements dnscache.Resolver from in-memory maps so no test -// ever hits real DNS. ptrCalls lets tests assert how many lookups ran. +// ever hits real DNS. ptrCalls and fwdCalls let tests assert how many +// lookups ran. // (The cache/singleflight internals are tested in pkg/dnscache; here the -// fake only backs the end-to-end MatchKnownBot checks.) +// fake only backs the end-to-end MatchKnownBot and LookupHost checks.) type fakeResolver struct { ptr map[string][]string // ip → PTR names fwd map[string][]net.IPAddr // hostname → addresses ptrCalls atomic.Int32 + fwdCalls atomic.Int32 } func (f *fakeResolver) LookupAddr(_ context.Context, addr string) ([]string, error) { @@ -36,6 +38,8 @@ func (f *fakeResolver) LookupAddr(_ context.Context, addr string) ([]string, err } func (f *fakeResolver) LookupIPAddr(_ context.Context, host string) ([]net.IPAddr, error) { + f.fwdCalls.Add(1) + ips, ok := f.fwd[host] if !ok { return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} diff --git a/pkg/exprhelpers/exprlib_test.go b/pkg/exprhelpers/exprlib_test.go index 1d285c3e34a..df3fa80be0d 100644 --- a/pkg/exprhelpers/exprlib_test.go +++ b/pkg/exprhelpers/exprlib_test.go @@ -2,6 +2,7 @@ package exprhelpers import ( "errors" + "net" "net/url" "testing" "time" @@ -2401,3 +2402,61 @@ func TestParseKvLax(t *testing.T) { }) } } + +func TestLookupHost(t *testing.T) { + resolver := &fakeResolver{ + fwd: map[string][]net.IPAddr{ + "home.example.com": { + {IP: net.ParseIP("192.0.2.10")}, + {IP: net.ParseIP("2001:db8::10")}, + }, + }, + } + setupBotTest(t, resolver) + + tests := []struct { + name string + host string + want []string + wantCalls int32 + }{ + { + name: "known host", + host: "home.example.com", + want: []string{"192.0.2.10", "2001:db8::10"}, + wantCalls: 1, + }, + { + name: "known host again is served from the cache", + host: "home.example.com", + want: []string{"192.0.2.10", "2001:db8::10"}, + wantCalls: 1, + }, + { + name: "unknown host", + host: "nope.example.com", + want: []string{}, + wantCalls: 2, + }, + { + name: "unknown host again is served from the cache", + host: "nope.example.com", + want: []string{}, + wantCalls: 2, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + env := map[string]any{"host": tc.host} + + vm, err := expr.Compile("LookupHost(host)", GetExprOptions(env)...) + require.NoError(t, err) + + got, err := expr.Run(vm, env) + require.NoError(t, err) + require.Equal(t, tc.want, got) + require.Equal(t, tc.wantCalls, resolver.fwdCalls.Load()) + }) + } +} diff --git a/pkg/exprhelpers/helpers.go b/pkg/exprhelpers/helpers.go index c2db20f7f24..ec6cfaef1fc 100644 --- a/pkg/exprhelpers/helpers.go +++ b/pkg/exprhelpers/helpers.go @@ -36,6 +36,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/cache" "github.com/crowdsecurity/crowdsec/pkg/database" + "github.com/crowdsecurity/crowdsec/pkg/dnscache" "github.com/crowdsecurity/crowdsec/pkg/enrichment" "github.com/crowdsecurity/crowdsec/pkg/fflag" "github.com/crowdsecurity/crowdsec/pkg/metrics" @@ -857,10 +858,12 @@ func GetActiveDecisionsTimeLeft(params ...any) (any, error) { func LookupHost(params ...any) (any, error) { value := params[0].(string) - addresses, err := net.LookupHost(value) - if err != nil { - log.Errorf("Failed to lookup host '%s' : %s", value, err) - return []string{}, nil + // cached: this runs for every event of a whitelist that names a host + ips := dnscache.ForwardIPs(value) + addresses := make([]string, 0, len(ips)) + + for _, ip := range ips { + addresses = append(addresses, ip.String()) } return addresses, nil From 6914a75e9fc65babbea1b4f90cc73d19b31975fb Mon Sep 17 00:00:00 2001 From: Tobias Wiesing Date: Tue, 6 Oct 2026 17:38:32 +0200 Subject: [PATCH 2/2] exprhelpers: LookupHost logs a failed lookup again dnscache keeps the error of a failed forward lookup with its empty result, and ForwardLookup returns both. LookupHost logs it at error level, as it did before it used the cache. ForwardIPs is unchanged. The subtests of TestLookupHost each have a resolver and a cache of their own. --- pkg/dnscache/dnscache.go | 29 ++++++++--- pkg/dnscache/dnscache_test.go | 24 +++++++++ pkg/exprhelpers/exprlib_test.go | 90 +++++++++++++++++++-------------- pkg/exprhelpers/helpers.go | 8 ++- 4 files changed, 105 insertions(+), 46 deletions(-) diff --git a/pkg/dnscache/dnscache.go b/pkg/dnscache/dnscache.go index da17049ccd3..fc7285295f0 100644 --- a/pkg/dnscache/dnscache.go +++ b/pkg/dnscache/dnscache.go @@ -5,7 +5,7 @@ // singleflight, so a given DNS fact costs at most one query per TTL. // // Consumers: the parser's reverse_dns enricher (PTR only) and the -// MatchKnownBot expr helper (FCrDNS). +// MatchKnownBot (FCrDNS) and LookupHost (forward) expr helpers. package dnscache import ( @@ -113,12 +113,29 @@ func PTRRecords(addr netip.Addr) []string { }, func(names []string) bool { return len(names) == 0 }) } +// forwardResult is what the cache keeps for a name: a failed lookup with +// its error, so that a caller that reports it can do so from the cache too. +type forwardResult struct { + ips []netip.Addr + err error +} + func ForwardIPs(host string) []netip.Addr { + ips, _ := ForwardLookup(host) + + return ips +} + +// ForwardLookup is ForwardIPs with the error of a failed lookup, which is +// cached with the empty result for the negative TTL. +func ForwardLookup(host string) ([]netip.Addr, error) { host = strings.TrimSuffix(strings.ToLower(host), ".") - return cachedLookup("fwd:"+host, func() []netip.Addr { + res := cachedLookup("fwd:"+host, func() forwardResult { return lookupForward(host) - }, func(ips []netip.Addr) bool { return len(ips) == 0 }) + }, func(res forwardResult) bool { return len(res.ips) == 0 }) + + return res.ips, res.err } func ForwardConfirmedNames(addr netip.Addr) []string { @@ -150,14 +167,14 @@ func lookupPTR(addr netip.Addr) []string { return names } -func lookupForward(host string) []netip.Addr { +func lookupForward(host string) forwardResult { ctx, cancel := context.WithTimeout(context.Background(), lookupTimeout) defer cancel() ips, err := resolver.LookupIPAddr(ctx, host) if err != nil { log.Debugf("dnscache: forward lookup failed for %s: %s", host, err) - return []netip.Addr{} + return forwardResult{ips: []netip.Addr{}, err: err} } addrs := []netip.Addr{} @@ -168,5 +185,5 @@ func lookupForward(host string) []netip.Addr { } } - return addrs + return forwardResult{ips: addrs} } diff --git a/pkg/dnscache/dnscache_test.go b/pkg/dnscache/dnscache_test.go index e31e013cc6d..1a925462e46 100644 --- a/pkg/dnscache/dnscache_test.go +++ b/pkg/dnscache/dnscache_test.go @@ -89,6 +89,30 @@ func TestForwardIPsKeyNormalization(t *testing.T) { assert.Equal(t, int32(1), resolver.fwdCalls.Load(), "normalized variants must share one cache entry") } +func TestForwardLookupCachesTheError(t *testing.T) { + resolver := &fakeResolver{ + fwd: map[string][]net.IPAddr{"host.example.com": {{IP: net.ParseIP("192.0.2.1")}}}, + } + setupDNSTest(t, resolver) + + ips, err := ForwardLookup("host.example.com") + require.NoError(t, err) + assert.Equal(t, []netip.Addr{netip.MustParseAddr("192.0.2.1")}, ips) + + // the error of a failed lookup comes back from the cache as well + for range 2 { + ips, err = ForwardLookup("nope.example.com") + + var dnsErr *net.DNSError + + require.ErrorAs(t, err, &dnsErr) + assert.True(t, dnsErr.IsNotFound) + assert.Empty(t, ips) + } + + assert.Equal(t, int32(2), resolver.fwdCalls.Load(), "failed lookup must be cached as negative") +} + func TestForwardConfirmedNames(t *testing.T) { tests := []struct { name string diff --git a/pkg/exprhelpers/exprlib_test.go b/pkg/exprhelpers/exprlib_test.go index df3fa80be0d..27034d157e1 100644 --- a/pkg/exprhelpers/exprlib_test.go +++ b/pkg/exprhelpers/exprlib_test.go @@ -9,6 +9,7 @@ import ( "github.com/expr-lang/expr" log "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -2404,59 +2405,72 @@ func TestParseKvLax(t *testing.T) { } func TestLookupHost(t *testing.T) { - resolver := &fakeResolver{ - fwd: map[string][]net.IPAddr{ - "home.example.com": { - {IP: net.ParseIP("192.0.2.10")}, - {IP: net.ParseIP("2001:db8::10")}, - }, - }, - } - setupBotTest(t, resolver) - tests := []struct { - name string - host string - want []string - wantCalls int32 + name string + host string + want []string + wantLog string }{ { - name: "known host", - host: "home.example.com", - want: []string{"192.0.2.10", "2001:db8::10"}, - wantCalls: 1, - }, - { - name: "known host again is served from the cache", - host: "home.example.com", - want: []string{"192.0.2.10", "2001:db8::10"}, - wantCalls: 1, + name: "known host", + host: "home.example.com", + want: []string{"192.0.2.10", "2001:db8::10"}, }, { - name: "unknown host", - host: "nope.example.com", - want: []string{}, - wantCalls: 2, - }, - { - name: "unknown host again is served from the cache", - host: "nope.example.com", - want: []string{}, - wantCalls: 2, + name: "unknown host", + host: "nope.example.com", + want: []string{}, + wantLog: "Failed to lookup host 'nope.example.com' : lookup nope.example.com: no such host", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { + resolver := &fakeResolver{ + fwd: map[string][]net.IPAddr{ + "home.example.com": { + {IP: net.ParseIP("192.0.2.10")}, + {IP: net.ParseIP("2001:db8::10")}, + }, + }, + } + setupBotTest(t, resolver) + + logger := log.StandardLogger() + hooks := logger.ReplaceHooks(make(log.LevelHooks)) + hook := logtest.NewLocal(logger) + + t.Cleanup(func() { logger.ReplaceHooks(hooks) }) + env := map[string]any{"host": tc.host} vm, err := expr.Compile("LookupHost(host)", GetExprOptions(env)...) require.NoError(t, err) - got, err := expr.Run(vm, env) - require.NoError(t, err) - require.Equal(t, tc.want, got) - require.Equal(t, tc.wantCalls, resolver.fwdCalls.Load()) + // the second call is served from the cache, a failure with its error + for range 2 { + hook.Reset() + + got, err := expr.Run(vm, env) + require.NoError(t, err) + require.Equal(t, tc.want, got) + + logged := []string{} + + for _, entry := range hook.AllEntries() { + if entry.Level == log.ErrorLevel { + logged = append(logged, entry.Message) + } + } + + if tc.wantLog == "" { + require.Empty(t, logged) + } else { + require.Equal(t, []string{tc.wantLog}, logged) + } + } + + require.Equal(t, int32(1), resolver.fwdCalls.Load()) }) } } diff --git a/pkg/exprhelpers/helpers.go b/pkg/exprhelpers/helpers.go index ec6cfaef1fc..e5399a83145 100644 --- a/pkg/exprhelpers/helpers.go +++ b/pkg/exprhelpers/helpers.go @@ -858,8 +858,12 @@ func GetActiveDecisionsTimeLeft(params ...any) (any, error) { func LookupHost(params ...any) (any, error) { value := params[0].(string) - // cached: this runs for every event of a whitelist that names a host - ips := dnscache.ForwardIPs(value) + ips, err := dnscache.ForwardLookup(value) + if err != nil { + log.Errorf("Failed to lookup host '%s' : %s", value, err) + return []string{}, nil + } + addresses := make([]string, 0, len(ips)) for _, ip := range ips {