Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions pkg/dnscache/dnscache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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{}
Expand All @@ -168,5 +185,5 @@ func lookupForward(host string) []netip.Addr {
}
}

return addrs
return forwardResult{ips: addrs}
}
24 changes: 24 additions & 0 deletions pkg/dnscache/dnscache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions pkg/exprhelpers/botfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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}
Expand Down
73 changes: 73 additions & 0 deletions pkg/exprhelpers/exprlib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -2401,3 +2403,74 @@ func TestParseKvLax(t *testing.T) {
})
}
}

func TestLookupHost(t *testing.T) {
tests := []struct {
Comment thread
twiesing marked this conversation as resolved.
Resolved
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())
})
}
}
9 changes: 8 additions & 1 deletion pkg/exprhelpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

Expand Down
Loading