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/botfile_test.go b/pkg/exprhelpers/botfile_test.go index 0c51fdce4e6..3881af07a4f 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..27034d157e1 100644 --- a/pkg/exprhelpers/exprlib_test.go +++ b/pkg/exprhelpers/exprlib_test.go @@ -2,12 +2,14 @@ package exprhelpers import ( "errors" + "net" "net/url" "testing" "time" "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" @@ -2401,3 +2403,74 @@ func TestParseKvLax(t *testing.T) { }) } } + +func TestLookupHost(t *testing.T) { + tests := []struct { + name string + host string + want []string + wantLog string + }{ + { + 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{}, + 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) + + // 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 c2db20f7f24..e5399a83145 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,12 +858,18 @@ func GetActiveDecisionsTimeLeft(params ...any) (any, error) { func LookupHost(params ...any) (any, error) { value := params[0].(string) - addresses, err := net.LookupHost(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 { + addresses = append(addresses, ip.String()) + } + return addresses, nil }