mirror of
https://github.com/netbirdio/netbird.git
synced 2026-07-29 11:51:27 +02:00
Compare commits
4 Commits
reverse-pr
...
worktree-d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
473d61afc4 | ||
|
|
d918235afd | ||
|
|
f7af852851 | ||
|
|
4546908ceb |
@@ -273,8 +273,8 @@ dockers_v2:
|
||||
- netbirdio/netbird
|
||||
- ghcr.io/netbirdio/netbird
|
||||
tags:
|
||||
- "{{ .Version }}-rootless"
|
||||
- "{{ if eq .Env.SKIP_PUBLISH \"false\" }}rootless-latest{{ end }}"
|
||||
- "v{{ .Version }}-rootless"
|
||||
- "{{ if eq .Env.SKIP_PUBLISH \"false\" }}latest{{ end }}"
|
||||
dockerfile: client/Dockerfile-rootless
|
||||
extra_files:
|
||||
- client/netbird-entrypoint.sh
|
||||
|
||||
@@ -3,6 +3,7 @@ package dns
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"net"
|
||||
"slices"
|
||||
@@ -31,6 +32,26 @@ type SubdomainMatcher interface {
|
||||
MatchSubdomains() bool
|
||||
}
|
||||
|
||||
// responseMeta holds the annotations handlers attach to a request to explain the
|
||||
// response the chain ends up writing. It survives a deferral, so an answer that
|
||||
// did not come from the handler that owns the name still says who stepped aside
|
||||
// and why.
|
||||
type responseMeta map[resutil.MetaKey]string
|
||||
|
||||
// format renders the annotations for the response log line. The order is stable
|
||||
// so the same event reads the same way every time; a map's own order is not.
|
||||
func (m responseMeta) format() string {
|
||||
if len(m) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
for _, k := range slices.Sorted(maps.Keys(m)) {
|
||||
b.WriteString(" " + string(k) + "=" + m[k])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type HandlerEntry struct {
|
||||
Handler dns.Handler
|
||||
Priority int
|
||||
@@ -52,8 +73,19 @@ type ResponseWriterChain struct {
|
||||
origPattern string
|
||||
requestID string
|
||||
shouldContinue bool
|
||||
response *dns.Msg
|
||||
meta map[string]string
|
||||
// softNegative suppresses a poisoning negative verdict for this request. A
|
||||
// handler that owns the name but cannot answer this query type sets it
|
||||
// before deferring, and it stays set for every handler that runs after.
|
||||
softNegative bool
|
||||
// clientHasEdns records whether the original query advertised EDNS0, taken
|
||||
// before any handler ran: handlers add EDNS0 to the query they forward
|
||||
// upstream, so the message itself no longer answers the question later.
|
||||
clientHasEdns bool
|
||||
response *dns.Msg
|
||||
// meta is handed to the next handler when this one defers, so the same map
|
||||
// outlives the writer that created it. Handlers must only set metadata from
|
||||
// within ServeDNS, never from a goroutine that outlives the call.
|
||||
meta responseMeta
|
||||
}
|
||||
|
||||
// RequestID returns the request ID for tracing
|
||||
@@ -62,26 +94,64 @@ func (w *ResponseWriterChain) RequestID() string {
|
||||
}
|
||||
|
||||
// SetMeta sets a metadata key-value pair for logging
|
||||
func (w *ResponseWriterChain) SetMeta(key, value string) {
|
||||
func (w *ResponseWriterChain) SetMeta(key resutil.MetaKey, value string) {
|
||||
if w.meta == nil {
|
||||
w.meta = make(map[string]string)
|
||||
w.meta = make(responseMeta)
|
||||
}
|
||||
w.meta[key] = value
|
||||
}
|
||||
|
||||
// RequestSoftNegative marks the request so a downstream NXDOMAIN is turned into
|
||||
// NODATA before it reaches the client. Set by a handler that defers a query for
|
||||
// a name it owns but a type it cannot resolve.
|
||||
func (w *ResponseWriterChain) RequestSoftNegative() {
|
||||
w.softNegative = true
|
||||
}
|
||||
|
||||
func (w *ResponseWriterChain) WriteMsg(m *dns.Msg) error {
|
||||
// Check if this is a continue signal (NXDOMAIN with Zero bit set)
|
||||
if m.Rcode == dns.RcodeNameError && m.MsgHdr.Zero {
|
||||
w.shouldContinue = true
|
||||
return nil
|
||||
}
|
||||
if w.softNegative && m.Rcode == dns.RcodeNameError {
|
||||
m = softenNegative(m, w.clientHasEdns)
|
||||
w.SetMeta(resutil.MetaKeySoftened, "nxdomain->nodata")
|
||||
}
|
||||
w.response = m
|
||||
if m.MsgHdr.Truncated {
|
||||
w.SetMeta("truncated", "true")
|
||||
w.SetMeta(resutil.MetaKeyTruncated, "true")
|
||||
}
|
||||
return w.ResponseWriter.WriteMsg(m)
|
||||
}
|
||||
|
||||
// softenNegative downgrades an NXDOMAIN to NODATA for a request a handler that
|
||||
// owns the name deferred. NXDOMAIN is cached for the name and every type below
|
||||
// it, so a resolver that has never heard of a routed name would take out the
|
||||
// record types the route does serve; NODATA is cached for this name and type
|
||||
// only. The authority section goes with it: the negative TTL of a zone we just
|
||||
// overruled does not apply, and RFC 2308 keeps a negative answer that carries no
|
||||
// SOA out of caches altogether, so the rewrite cannot outlive the route.
|
||||
//
|
||||
// The rewrite is ours, not the answering resolver's, so an EDNS0 client is told
|
||||
// as much: the reply we hand back travels a path no capture on this host sees,
|
||||
// and an empty answer is otherwise indistinguishable from a real one. Returns a
|
||||
// copy so the answering handler keeps whatever it may hold on to.
|
||||
func softenNegative(m *dns.Msg, clientHasEdns bool) *dns.Msg {
|
||||
out := m.Copy()
|
||||
out.Rcode = dns.RcodeSuccess
|
||||
out.Ns = nil
|
||||
|
||||
if clientHasEdns {
|
||||
resutil.AttachEDE(out, resutil.EDENetbirdSoftenedNegative,
|
||||
"netbird: name is served locally, NXDOMAIN from the fallthrough resolver suppressed")
|
||||
} else {
|
||||
resutil.StripOPT(out)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func NewHandlerChain() *HandlerChain {
|
||||
return &HandlerChain{
|
||||
handlers: make([]HandlerEntry, 0),
|
||||
@@ -223,6 +293,19 @@ func (c *HandlerChain) dispatch(w dns.ResponseWriter, r *dns.Msg, maxPriority in
|
||||
handlers := slices.Clone(c.handlers)
|
||||
c.mu.RUnlock()
|
||||
|
||||
// Carried across deferrals: once a handler that owns the name defers, no
|
||||
// handler after it may answer with a verdict that poisons the name. The
|
||||
// metadata of a handler that stepped aside is carried too, so the response
|
||||
// log line explains an answer that did not come from the handler that owns
|
||||
// the name.
|
||||
var softNegative bool
|
||||
var carried responseMeta
|
||||
|
||||
// Taken before any handler runs: handlers advertise EDNS0 on the query they
|
||||
// forward upstream, so afterwards the message no longer tells us whether the
|
||||
// client did.
|
||||
clientHasEdns := r.IsEdns0() != nil
|
||||
|
||||
// Try handlers in priority order
|
||||
for _, entry := range handlers {
|
||||
if entry.Priority > maxPriority {
|
||||
@@ -245,11 +328,16 @@ func (c *HandlerChain) dispatch(w dns.ResponseWriter, r *dns.Msg, maxPriority in
|
||||
ResponseWriter: w,
|
||||
origPattern: entry.OrigPattern,
|
||||
requestID: requestID,
|
||||
softNegative: softNegative,
|
||||
clientHasEdns: clientHasEdns,
|
||||
meta: carried,
|
||||
}
|
||||
entry.Handler.ServeDNS(chainWriter, r)
|
||||
|
||||
// If handler wants to continue, try next handler
|
||||
if chainWriter.shouldContinue {
|
||||
softNegative = softNegative || chainWriter.softNegative
|
||||
carried = chainWriter.meta
|
||||
if entry.Priority != PriorityMgmtCache {
|
||||
logger.Tracef("handler requested continue for domain=%s", qname)
|
||||
}
|
||||
@@ -265,30 +353,59 @@ func (c *HandlerChain) dispatch(w dns.ResponseWriter, r *dns.Msg, maxPriority in
|
||||
qname, dns.TypeToString[question.Qtype], dns.ClassToString[question.Qclass])
|
||||
resp := &dns.Msg{}
|
||||
resp.SetRcode(r, dns.RcodeRefused)
|
||||
// A handler that owns the name deferred and nothing below it could answer
|
||||
// (a client with no primary nameserver group). The name exists as far as
|
||||
// this client is concerned, since the route serves its addresses, so REFUSED
|
||||
// would contradict the route: a stub that takes it as "not served here" and
|
||||
// retries another resolver can come back with an NXDOMAIN that takes the
|
||||
// whole name down. Answer "no records of this type" instead, without an SOA,
|
||||
// so RFC 2308 keeps it out of negative caches, and tell an EDNS0 client the
|
||||
// empty answer is ours rather than a resolver's.
|
||||
if softNegative {
|
||||
resp.Rcode = dns.RcodeSuccess
|
||||
if clientHasEdns {
|
||||
resutil.AttachEDE(resp, resutil.EDENetbirdSoftenedNegative,
|
||||
"netbird: name is served locally, no fallthrough resolver for this query type")
|
||||
}
|
||||
// logResponse never runs on this path, so the carried metadata is
|
||||
// appended here or the reason for the deferral is lost in exactly the
|
||||
// case that is hardest to diagnose.
|
||||
logger.Tracef("no handler below the deferring one for domain=%s type=%s, answering NODATA%s",
|
||||
qname, dns.TypeToString[question.Qtype], carried.format())
|
||||
}
|
||||
if err := w.WriteMsg(resp); err != nil {
|
||||
logger.Errorf("failed to write DNS response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandlerChain) logResponse(logger *log.Entry, cw *ResponseWriterChain, qname string, startTime time.Time) {
|
||||
// Runs for every query, and the arguments below are not free: Len() packs
|
||||
// the message to measure it, and formatting the answers and the metadata
|
||||
// allocates. None of it is worth doing when the line is discarded.
|
||||
if !log.IsLevelEnabled(log.TraceLevel) {
|
||||
return
|
||||
}
|
||||
|
||||
if cw.response == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var meta string
|
||||
for k, v := range cw.meta {
|
||||
meta += " " + k + "=" + v
|
||||
}
|
||||
|
||||
logger.Tracef("response: domain=%s rcode=%s answers=%s size=%dB%s took=%s",
|
||||
qname, dns.RcodeToString[cw.response.Rcode], resutil.FormatAnswers(cw.response.Answer),
|
||||
cw.response.Len(), meta, time.Since(startTime))
|
||||
cw.response.Len(), cw.meta.format(), time.Since(startTime))
|
||||
}
|
||||
|
||||
// ResolveInternal runs an in-process DNS query against the chain, skipping any
|
||||
// handler with priority > maxPriority. Used by internal callers (e.g. the mgmt
|
||||
// cache refresher) that must bypass themselves to avoid loops. Honors ctx
|
||||
// cancellation; on ctx.Done the dispatch goroutine is left to drain on its own
|
||||
// cache refresher) that must bypass themselves to avoid loops.
|
||||
//
|
||||
// "Nothing answered" is read off RcodeRefused, which a request soft-negatived by
|
||||
// a deferring handler never carries: it ends in an empty NOERROR instead, and
|
||||
// would look resolved. No caller can reach that today, since every handler that
|
||||
// defers sits above the maxPriority any caller passes. Lowering one below it
|
||||
// means this check needs the soft-negative case too.
|
||||
//
|
||||
// Honors ctx cancellation; on ctx.Done the dispatch goroutine is left to drain on its own
|
||||
// (bounded by the invoked handler's internal timeout).
|
||||
func (c *HandlerChain) ResolveInternal(ctx context.Context, r *dns.Msg, maxPriority int) (*dns.Msg, error) {
|
||||
if len(r.Question) == 0 {
|
||||
|
||||
@@ -3,15 +3,19 @@ package dns_test
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
log "github.com/sirupsen/logrus"
|
||||
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
nbdns "github.com/netbirdio/netbird/client/internal/dns"
|
||||
"github.com/netbirdio/netbird/client/internal/dns/resutil"
|
||||
"github.com/netbirdio/netbird/client/internal/dns/test"
|
||||
)
|
||||
|
||||
@@ -1238,6 +1242,276 @@ func TestHandlerChain_ResolveInternal_HonorsContextTimeout(t *testing.T) {
|
||||
assert.Less(t, elapsed, 500*time.Millisecond, "ResolveInternal must return shortly after ctx deadline")
|
||||
}
|
||||
|
||||
// requestSoftNegative asks the chain to soften a negative verdict produced by
|
||||
// the handlers that run after the caller defers, reporting whether the chain
|
||||
// supports the signal. Written as a type assertion so these tests compile
|
||||
// against a chain that does not support it yet.
|
||||
func requestSoftNegative(w dns.ResponseWriter) bool {
|
||||
sn, ok := w.(interface{ RequestSoftNegative() })
|
||||
if ok {
|
||||
sn.RequestSoftNegative()
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// deferringHandler defers to the next handler in the chain, optionally asking
|
||||
// for the negative verdict of whatever answers instead to be softened. This is
|
||||
// what a DNS route handler does for a record type its routing peer cannot
|
||||
// resolve.
|
||||
type deferringHandler struct {
|
||||
softNegative bool
|
||||
called bool
|
||||
supported bool
|
||||
}
|
||||
|
||||
func (h *deferringHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
h.called = true
|
||||
if h.softNegative {
|
||||
h.supported = requestSoftNegative(w)
|
||||
// The real handler records why it stepped aside, for the response log
|
||||
// line of whichever handler answers instead.
|
||||
resutil.SetMeta(w, resutil.MetaKeyDeferredBy, "test handler")
|
||||
}
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(r, dns.RcodeNameError)
|
||||
resp.MsgHdr.Zero = true
|
||||
_ = w.WriteMsg(resp)
|
||||
}
|
||||
|
||||
// nxdomainHandler answers an authoritative NXDOMAIN with an SOA in the
|
||||
// authority section, the way a public resolver answers for a name that only
|
||||
// exists inside the routed network.
|
||||
type nxdomainHandler struct{}
|
||||
|
||||
func (h *nxdomainHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(r, dns.RcodeNameError)
|
||||
resp.Ns = []dns.RR{&dns.SOA{
|
||||
Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 3600},
|
||||
Ns: "ns1.example.com.",
|
||||
Mbox: "hostmaster.example.com.",
|
||||
Minttl: 3600,
|
||||
Expire: 604800,
|
||||
Refresh: 7200,
|
||||
Retry: 3600,
|
||||
}}
|
||||
_ = w.WriteMsg(resp)
|
||||
}
|
||||
|
||||
// TestHandlerChain_SoftNegative_DowngradesDownstreamNXDOMAIN is the whole point
|
||||
// of the soft-negative signal: a route handler may only defer a query to the
|
||||
// public chain if the answer cannot poison the routed name. NXDOMAIN is cached
|
||||
// for the name and every type under it (RFC 2308, RFC 8020), so it has to be
|
||||
// rewritten to NODATA, which is cached per name and type only.
|
||||
func TestHandlerChain_SoftNegative_DowngradesDownstreamNXDOMAIN(t *testing.T) {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
|
||||
route := &deferringHandler{softNegative: true}
|
||||
chain.AddHandler("*.example.com.", route, nbdns.PriorityDNSRoute)
|
||||
chain.AddHandler(".", &nxdomainHandler{}, nbdns.PriorityDefault)
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
chain.ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must reach the client")
|
||||
assert.True(t, route.called, "the route handler must run first")
|
||||
require.True(t, route.supported, "the chain writer must accept a soft-negative request")
|
||||
assert.Equal(t, dns.RcodeSuccess, resp.Rcode, "NXDOMAIN must be softened to NODATA")
|
||||
assert.Empty(t, resp.Answer, "a softened negative carries no answer")
|
||||
assert.Empty(t, resp.Ns, "the downstream zone's SOA must not set the negative TTL for a name we overrode")
|
||||
}
|
||||
|
||||
// responseLineFor returns the chain's response log line for one query. Raising
|
||||
// the level to trace also unmutes whatever else is logging in this package, so
|
||||
// the line has to be picked by the name it was asked about rather than by being
|
||||
// the last one seen.
|
||||
func responseLineFor(hook *logtest.Hook, qname string) string {
|
||||
for _, e := range hook.AllEntries() {
|
||||
if strings.HasPrefix(e.Message, "response:") && strings.Contains(e.Message, qname) {
|
||||
return e.Message
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// TestHandlerChain_SoftNegative_IsVisibleToTheClient covers observability of the
|
||||
// rewrite. The reply we hand the application travels over loopback, which the
|
||||
// bundle capture does not see, so a softened verdict has to say so on the wire:
|
||||
// without it an empty answer is indistinguishable from a real "no such record"
|
||||
// in a dig output or a capture taken next to the application.
|
||||
func TestHandlerChain_SoftNegative_IsVisibleToTheClient(t *testing.T) {
|
||||
// One hook for the whole test: logtest installs it on the standard logger
|
||||
// and logrus has no way to take it off again, so a hook per subtest would
|
||||
// leave several behind buffering every later line in the package.
|
||||
hook := logtest.NewGlobal()
|
||||
t.Cleanup(hook.Reset)
|
||||
|
||||
newChain := func() *nbdns.HandlerChain {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
chain.AddHandler("*.example.com.", &deferringHandler{softNegative: true}, nbdns.PriorityDNSRoute)
|
||||
chain.AddHandler(".", &nxdomainHandler{}, nbdns.PriorityDefault)
|
||||
return chain
|
||||
}
|
||||
|
||||
t.Run("EDNS0 client gets an extended error", func(t *testing.T) {
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
r.SetEdns0(dns.DefaultMsgSize, false)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
newChain().ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp)
|
||||
require.Equal(t, dns.RcodeSuccess, resp.Rcode)
|
||||
|
||||
ede, ok := resutil.ExtractEDE(resp)
|
||||
require.True(t, ok, "a softened verdict must carry an extended DNS error")
|
||||
assert.Equal(t, resutil.EDENetbirdSoftenedNegative, ede.InfoCode)
|
||||
assert.Contains(t, ede.ExtraText, "netbird", "the text must name us as the source of the rewrite")
|
||||
})
|
||||
|
||||
t.Run("plain client gets no OPT", func(t *testing.T) {
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
newChain().ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp)
|
||||
assert.Nil(t, resp.IsEdns0(), "RFC 6891 forbids an OPT toward a client that did not advertise EDNS0")
|
||||
})
|
||||
|
||||
// The response line is what support reads out of a debug bundle, and it now
|
||||
// carries several annotations at once. Built from a map, their order would
|
||||
// differ on every query, so the same event never looks the same twice.
|
||||
t.Run("log fields keep a stable order", func(t *testing.T) {
|
||||
const qname = "_mongodb._tcp.stable.example.com."
|
||||
|
||||
prev := log.GetLevel()
|
||||
log.SetLevel(log.TraceLevel)
|
||||
t.Cleanup(func() { log.SetLevel(prev) })
|
||||
|
||||
lineFor := func() string {
|
||||
hook.Reset()
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion(qname, dns.TypeSRV)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
newChain().ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
line := responseLineFor(hook, qname)
|
||||
// The duration differs per query and is not what we compare.
|
||||
line, _, _ = strings.Cut(line, " took=")
|
||||
return line
|
||||
}
|
||||
|
||||
first := lineFor()
|
||||
require.NotEmpty(t, first, "the chain must log the response it wrote")
|
||||
require.Contains(t, first, "deferred_by=", "the line must carry more than one annotation to be worth ordering")
|
||||
require.Contains(t, first, "softened=")
|
||||
|
||||
for range 20 {
|
||||
assert.Equal(t, first, lineFor(), "the same event must produce the same line")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("logged with the reason it was deferred", func(t *testing.T) {
|
||||
const qname = "_mongodb._tcp.reason.example.com."
|
||||
|
||||
hook.Reset()
|
||||
|
||||
prev := log.GetLevel()
|
||||
log.SetLevel(log.TraceLevel)
|
||||
t.Cleanup(func() { log.SetLevel(prev) })
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion(qname, dns.TypeSRV)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
newChain().ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
response := responseLineFor(hook, qname)
|
||||
require.NotEmpty(t, response, "the chain must log the response it wrote")
|
||||
assert.Contains(t, response, "softened=", "the log must show the verdict was rewritten")
|
||||
assert.Contains(t, response, "deferred_by=", "the log must name the handler that deferred")
|
||||
})
|
||||
}
|
||||
|
||||
// TestHandlerChain_SoftNegative_NoHandlerBelow covers a client with no primary
|
||||
// nameserver group: the deferred query reaches the end of the chain unanswered.
|
||||
// REFUSED would say the name is not served here while the route serves its
|
||||
// addresses, and a stub that acts on that by asking elsewhere can bring back an
|
||||
// NXDOMAIN for the whole name. The answer must be an empty, uncacheable NODATA.
|
||||
func TestHandlerChain_SoftNegative_NoHandlerBelow(t *testing.T) {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
|
||||
route := &deferringHandler{softNegative: true}
|
||||
chain.AddHandler("*.example.com.", route, nbdns.PriorityDNSRoute)
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("db.example.com.", dns.TypeHTTPS)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
chain.ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must reach the client")
|
||||
assert.Equal(t, dns.RcodeSuccess, resp.Rcode, "an unanswered soft-negative query must be NODATA, not REFUSED")
|
||||
assert.Empty(t, resp.Answer)
|
||||
assert.Empty(t, resp.Ns,
|
||||
"no SOA, so RFC 2308 keeps the empty answer out of negative caches and it cannot outlive the route")
|
||||
}
|
||||
|
||||
// TestHandlerChain_SoftNegative_KeepsRealAnswers guards the other direction:
|
||||
// softening applies to negative verdicts only. A real answer from a downstream
|
||||
// handler must reach the client untouched.
|
||||
func TestHandlerChain_SoftNegative_KeepsRealAnswers(t *testing.T) {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
|
||||
route := &deferringHandler{softNegative: true}
|
||||
chain.AddHandler("*.example.com.", route, nbdns.PriorityDNSRoute)
|
||||
chain.AddHandler(".", &answeringHandler{name: "public", ip: "203.0.113.10"}, nbdns.PriorityDefault)
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("db.example.com.", dns.TypeA)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
chain.ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must reach the client")
|
||||
assert.Equal(t, dns.RcodeSuccess, resp.Rcode)
|
||||
require.Len(t, resp.Answer, 1, "the downstream answer must pass through")
|
||||
}
|
||||
|
||||
// TestHandlerChain_NXDOMAINPreservedWithoutSoftNegative makes sure the
|
||||
// softening is opt-in: an ordinary chain continuation still yields NXDOMAIN, so
|
||||
// genuine non-existence keeps being reported.
|
||||
func TestHandlerChain_NXDOMAINPreservedWithoutSoftNegative(t *testing.T) {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
|
||||
route := &deferringHandler{}
|
||||
chain.AddHandler("*.example.com.", route, nbdns.PriorityDNSRoute)
|
||||
chain.AddHandler(".", &nxdomainHandler{}, nbdns.PriorityDefault)
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("nope.example.com.", dns.TypeA)
|
||||
|
||||
mw := &test.MockResponseWriter{}
|
||||
chain.ServeDNS(&nbdns.ResponseWriterChain{ResponseWriter: mw}, r)
|
||||
|
||||
resp := mw.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must reach the client")
|
||||
assert.Equal(t, dns.RcodeNameError, resp.Rcode, "without the signal a real NXDOMAIN must survive")
|
||||
}
|
||||
|
||||
func TestHandlerChain_HasRootHandlerAtOrBelow(t *testing.T) {
|
||||
chain := nbdns.NewHandlerChain()
|
||||
h := &answeringHandler{name: "h", ip: "10.0.0.1"}
|
||||
|
||||
@@ -19,6 +19,34 @@ import (
|
||||
// uses when a resolved host has no addresses of the requested family.
|
||||
const errNoSuitableAddress = "no suitable address found"
|
||||
|
||||
// Extended DNS Error info codes NetBird emits so a client can see why an answer
|
||||
// looks the way it does without reading this peer's logs. They live in the RFC
|
||||
// 8914 Private Use range (49152-65535) and are registered here, in one place,
|
||||
// because nothing else guarantees two NetBird components pick distinct codes.
|
||||
const (
|
||||
// EDENetbirdUpstreamTimeout: a DNS forwarder's upstream did not answer.
|
||||
EDENetbirdUpstreamTimeout uint16 = 49152
|
||||
// EDENetbirdUpstreamFailure: a DNS forwarder's upstream failed.
|
||||
EDENetbirdUpstreamFailure uint16 = 49153
|
||||
// EDENetbirdSoftenedNegative: the empty answer is ours, not the answering
|
||||
// resolver's. A handler that owns the name deferred this query type, and the
|
||||
// negative verdict that came back was downgraded so it cannot poison the
|
||||
// name.
|
||||
EDENetbirdSoftenedNegative uint16 = 49154
|
||||
)
|
||||
|
||||
// AttachEDE adds an Extended DNS Error (RFC 8914) option to a message, creating
|
||||
// the OPT pseudo-record if it has none. Callers must only use it toward a client
|
||||
// that advertised EDNS0: per RFC 6891 an OPT must not appear otherwise.
|
||||
func AttachEDE(msg *dns.Msg, code uint16, text string) {
|
||||
opt := msg.IsEdns0()
|
||||
if opt == nil {
|
||||
msg.SetEdns0(dns.DefaultMsgSize, false)
|
||||
opt = msg.IsEdns0()
|
||||
}
|
||||
opt.Option = append(opt.Option, &dns.EDNS0_EDE{InfoCode: code, ExtraText: text})
|
||||
}
|
||||
|
||||
// GenerateRequestID creates a random 8-character hex string for request tracing.
|
||||
func GenerateRequestID() string {
|
||||
bytes := make([]byte, 4)
|
||||
@@ -78,10 +106,38 @@ type resolver interface {
|
||||
LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
|
||||
}
|
||||
|
||||
// MetaKey names an annotation a handler attaches to a request to explain the
|
||||
// response the chain ends up writing. The set is closed and rendered onto a
|
||||
// single log line, so an unrecognized key is a typo inventing a field rather
|
||||
// than a new fact.
|
||||
type MetaKey string
|
||||
|
||||
const (
|
||||
// MetaKeyProtocol: the transport a query arrived on.
|
||||
MetaKeyProtocol MetaKey = "protocol"
|
||||
// MetaKeyUpstream: the upstream that answered.
|
||||
MetaKeyUpstream MetaKey = "upstream"
|
||||
// MetaKeyUpstreamProtocol: the transport used toward that upstream.
|
||||
MetaKeyUpstreamProtocol MetaKey = "upstream_protocol"
|
||||
// MetaKeyPeer: the routing peer whose forwarder answered.
|
||||
MetaKeyPeer MetaKey = "peer"
|
||||
// MetaKeyEDE: an Extended DNS Error carried by the answer.
|
||||
MetaKeyEDE MetaKey = "ede"
|
||||
// MetaKeyTruncated: the answer did not fit and was truncated.
|
||||
MetaKeyTruncated MetaKey = "truncated"
|
||||
// MetaKeySoftened: a negative verdict was rewritten so it cannot poison a
|
||||
// name served locally.
|
||||
MetaKeySoftened MetaKey = "softened"
|
||||
// MetaKeyDeferredBy: the handler that owned the name and stepped aside.
|
||||
MetaKeyDeferredBy MetaKey = "deferred_by"
|
||||
// MetaKeyDeferredReason: why it stepped aside.
|
||||
MetaKeyDeferredReason MetaKey = "deferred_reason"
|
||||
)
|
||||
|
||||
// chainedWriter is implemented by ResponseWriters that carry request metadata
|
||||
type chainedWriter interface {
|
||||
RequestID() string
|
||||
SetMeta(key, value string)
|
||||
SetMeta(key MetaKey, value string)
|
||||
}
|
||||
|
||||
// GetRequestID extracts a request ID from the ResponseWriter if available,
|
||||
@@ -96,12 +152,30 @@ func GetRequestID(w dns.ResponseWriter) string {
|
||||
}
|
||||
|
||||
// SetMeta sets metadata on the ResponseWriter if it supports it.
|
||||
func SetMeta(w dns.ResponseWriter, key, value string) {
|
||||
func SetMeta(w dns.ResponseWriter, key MetaKey, value string) {
|
||||
if cw, ok := w.(chainedWriter); ok {
|
||||
cw.SetMeta(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// softNegativeRequester is implemented by chain writers that can soften the
|
||||
// negative verdict of the handlers a deferring handler falls through to.
|
||||
type softNegativeRequester interface {
|
||||
RequestSoftNegative()
|
||||
}
|
||||
|
||||
// RequestSoftNegative asks the handler chain to downgrade an NXDOMAIN from the
|
||||
// handlers that run after the caller defers. A handler that owns a name but
|
||||
// cannot answer one query type for it needs this: the resolvers it falls
|
||||
// through to cannot prove the name absent, and an NXDOMAIN from them is cached
|
||||
// for the name and every type under it (RFC 2308, RFC 8020), taking the
|
||||
// addresses the handler does serve down with it.
|
||||
func RequestSoftNegative(w dns.ResponseWriter) {
|
||||
if sn, ok := w.(softNegativeRequester); ok {
|
||||
sn.RequestSoftNegative()
|
||||
}
|
||||
}
|
||||
|
||||
// LookupResult contains the result of an external DNS lookup
|
||||
type LookupResult struct {
|
||||
IPs []netip.Addr
|
||||
@@ -199,11 +273,27 @@ type RecordResolver interface {
|
||||
LookupAddr(ctx context.Context, addr string) ([]string, error)
|
||||
}
|
||||
|
||||
// SupportedRecordQtype reports whether LookupRecords can resolve qtype. The
|
||||
// set is bounded by the net.Resolver API, which exposes no way to query an
|
||||
// arbitrary record type, and going around it with a raw exchange would mean
|
||||
// picking nameservers ourselves instead of resolving the way the host does.
|
||||
//
|
||||
// Both ends read this: a DNS forwarder answers these types for the domains it
|
||||
// routes, and a client uses it to tell which types are worth forwarding to a
|
||||
// peer at all.
|
||||
func SupportedRecordQtype(qtype uint16) bool {
|
||||
switch qtype {
|
||||
case dns.TypeMX, dns.TypeTXT, dns.TypeNS, dns.TypeSRV, dns.TypeCNAME, dns.TypePTR:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// LookupRecords resolves a non-address DNS record type through the host
|
||||
// resolver and returns the resource records and the DNS rcode. Types the host
|
||||
// resolver cannot answer (anything not covered by the net.Resolver Lookup*
|
||||
// methods) yield NODATA so that a routed name is never poisoned with NXDOMAIN
|
||||
// for an unsupported type.
|
||||
// resolver and returns the resource records and the DNS rcode. Types outside
|
||||
// SupportedRecordQtype yield NODATA so that a routed name is never poisoned
|
||||
// with NXDOMAIN for a type we cannot look up.
|
||||
func LookupRecords(ctx context.Context, r RecordResolver, name string, qtype uint16, ttl uint32) ([]dns.RR, int) {
|
||||
fqdn := dns.Fqdn(name)
|
||||
|
||||
|
||||
@@ -295,7 +295,7 @@ func (u *upstreamResolverBase) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
if addr := w.RemoteAddr(); addr != nil {
|
||||
network := addr.Network()
|
||||
ctx = contextWithDNSProtocol(ctx, network)
|
||||
resutil.SetMeta(w, "protocol", network)
|
||||
resutil.SetMeta(w, resutil.MetaKeyProtocol, network)
|
||||
}
|
||||
|
||||
ok, failures := u.tryUpstreamServers(ctx, w, r, logger)
|
||||
@@ -331,7 +331,7 @@ func (u *upstreamResolverBase) tryOnlyRace(ctx context.Context, w dns.ResponseWr
|
||||
return false, res.failures
|
||||
}
|
||||
if res.ede != "" {
|
||||
resutil.SetMeta(w, "ede", res.ede)
|
||||
resutil.SetMeta(w, resutil.MetaKeyEDE, res.ede)
|
||||
}
|
||||
u.writeSuccessResponse(w, res.msg, res.upstream, r.Question[0].Name, res.protocol, logger)
|
||||
return true, res.failures
|
||||
@@ -361,7 +361,7 @@ func (u *upstreamResolverBase) raceAll(ctx context.Context, w dns.ResponseWriter
|
||||
failures = append(failures, res.failures...)
|
||||
if res.msg != nil {
|
||||
if res.ede != "" {
|
||||
resutil.SetMeta(w, "ede", res.ede)
|
||||
resutil.SetMeta(w, resutil.MetaKeyEDE, res.ede)
|
||||
}
|
||||
u.writeSuccessResponse(w, res.msg, res.upstream, r.Question[0].Name, res.protocol, logger)
|
||||
return true, failures
|
||||
@@ -550,9 +550,9 @@ func (u *upstreamResolverBase) debugUpstreamTimeout(upstream netip.AddrPort) str
|
||||
}
|
||||
|
||||
func (u *upstreamResolverBase) writeSuccessResponse(w dns.ResponseWriter, rm *dns.Msg, upstream netip.AddrPort, domain string, proto string, logger *log.Entry) {
|
||||
resutil.SetMeta(w, "upstream", upstream.String())
|
||||
resutil.SetMeta(w, resutil.MetaKeyUpstream, upstream.String())
|
||||
if proto != "" {
|
||||
resutil.SetMeta(w, "upstream_protocol", proto)
|
||||
resutil.SetMeta(w, resutil.MetaKeyUpstreamProtocol, proto)
|
||||
}
|
||||
|
||||
// Clear Zero bit from external responses to prevent upstream servers from
|
||||
|
||||
@@ -26,15 +26,6 @@ import (
|
||||
const errResolveFailed = "failed to resolve query for domain=%s: %v"
|
||||
const upstreamTimeout = 15 * time.Second
|
||||
|
||||
// EDE info codes the forwarder emits on upstream failures so the querying
|
||||
// client can see the reason without inspecting this peer's logs. They live in
|
||||
// the RFC 8914 Private Use range (49152-65535); the Go resolver never exposes a
|
||||
// real upstream EDE here, so these cannot collide with a genuine code.
|
||||
const (
|
||||
edeNetbirdUpstreamTimeout uint16 = 49152
|
||||
edeNetbirdUpstreamFailure uint16 = 49153
|
||||
)
|
||||
|
||||
type resolver interface {
|
||||
LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
|
||||
LookupMX(ctx context.Context, name string) ([]*net.MX, error)
|
||||
@@ -216,6 +207,9 @@ func (f *DNSForwarder) handleDNSQuery(logger *log.Entry, w dns.ResponseWriter, q
|
||||
qname, dns.TypeToString[question.Qtype], dns.ClassToString[question.Qclass])
|
||||
|
||||
resp := query.SetReply(query)
|
||||
// Every answer here comes from a recursive lookup on this peer. SetReply
|
||||
// leaves RA unset, which reads to a client as a server that cannot recurse.
|
||||
resp.RecursionAvailable = true
|
||||
|
||||
mostSpecificResId, matchingEntries := f.getMatchingEntries(strings.TrimSuffix(qname, "."))
|
||||
if mostSpecificResId == "" {
|
||||
@@ -229,20 +223,22 @@ func (f *DNSForwarder) handleDNSQuery(logger *log.Entry, w dns.ResponseWriter, q
|
||||
|
||||
reqHasEdns := query.IsEdns0() != nil
|
||||
|
||||
switch question.Qtype {
|
||||
case dns.TypeA, dns.TypeAAAA:
|
||||
switch {
|
||||
case question.Qtype == dns.TypeA || question.Qtype == dns.TypeAAAA:
|
||||
f.handleAddressQuery(ctx, logger, w, resp, mostSpecificResId, matchingEntries, reqHasEdns, startTime)
|
||||
case dns.TypeMX, dns.TypeTXT, dns.TypeNS, dns.TypeSRV, dns.TypeCNAME, dns.TypePTR:
|
||||
case resutil.SupportedRecordQtype(question.Qtype):
|
||||
f.handleRecordQuery(ctx, logger, w, resp, startTime)
|
||||
default:
|
||||
// The domain is routed here, so any other type is answered NODATA
|
||||
// (NOERROR, empty answer) rather than falling back to a resolver that
|
||||
// would poison the name with NXDOMAIN. The Extended DNS Error lets a
|
||||
// client tell this capability-driven NODATA apart from an
|
||||
// authoritative one. The OPT pseudo-record must not appear unless the
|
||||
// query advertised EDNS0.
|
||||
// authoritative one; a current client knows the type is unsupported and
|
||||
// resolves it through its own handler chain instead of asking at all.
|
||||
// The OPT pseudo-record must not appear unless the query advertised
|
||||
// EDNS0.
|
||||
if reqHasEdns {
|
||||
attachEDE(resp, dns.ExtendedErrorCodeNotSupported, "netbird forwarder: unsupported query type")
|
||||
resutil.AttachEDE(resp, dns.ExtendedErrorCodeNotSupported, "netbird forwarder: unsupported query type")
|
||||
}
|
||||
f.writeResponse(logger, w, resp, qname, startTime)
|
||||
}
|
||||
@@ -441,7 +437,7 @@ func (f *DNSForwarder) handleDNSError(
|
||||
}
|
||||
|
||||
if reqHasEdns {
|
||||
attachEDE(resp, edeCodeFor(dnsErr), edeText(dnsErr))
|
||||
resutil.AttachEDE(resp, edeCodeFor(dnsErr), edeText(dnsErr))
|
||||
}
|
||||
|
||||
f.writeResponse(logger, w, resp, domain, startTime)
|
||||
@@ -488,9 +484,9 @@ func (f *DNSForwarder) getMatchingEntries(domain string) (route.ResID, []*Forwar
|
||||
// edeCodeFor maps an upstream lookup error to the NetBird EDE info code.
|
||||
func edeCodeFor(dnsErr *net.DNSError) uint16 {
|
||||
if dnsErr != nil && dnsErr.IsTimeout {
|
||||
return edeNetbirdUpstreamTimeout
|
||||
return resutil.EDENetbirdUpstreamTimeout
|
||||
}
|
||||
return edeNetbirdUpstreamFailure
|
||||
return resutil.EDENetbirdUpstreamFailure
|
||||
}
|
||||
|
||||
// edeText builds the EDE extra-text describing the class of upstream failure.
|
||||
@@ -503,14 +499,3 @@ func edeText(dnsErr *net.DNSError) string {
|
||||
}
|
||||
return "netbird forwarder: upstream failure"
|
||||
}
|
||||
|
||||
// attachEDE adds an Extended DNS Error (RFC 8914) option to the response,
|
||||
// creating the OPT pseudo-record if the response does not already carry one.
|
||||
func attachEDE(resp *dns.Msg, code uint16, text string) {
|
||||
opt := resp.IsEdns0()
|
||||
if opt == nil {
|
||||
resp.SetEdns0(dns.DefaultMsgSize, false)
|
||||
opt = resp.IsEdns0()
|
||||
}
|
||||
opt.Option = append(opt.Option, &dns.EDNS0_EDE{InfoCode: code, ExtraText: text})
|
||||
}
|
||||
|
||||
@@ -649,6 +649,39 @@ func TestDNSForwarder_ResponseCodes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDNSForwarder_RecursionAvailable covers the RA bit. Every answer this
|
||||
// forwarder produces comes from a recursive lookup on the routing peer, but
|
||||
// dns.Msg.SetReply leaves RA unset, so clients report "recursion not available"
|
||||
// and some stub resolvers treat the server as unable to serve the query.
|
||||
func TestDNSForwarder_RecursionAvailable(t *testing.T) {
|
||||
t.Run("record answer", func(t *testing.T) {
|
||||
mockResolver := &MockResolver{}
|
||||
forwarder := newRecordTestForwarder(t, mockResolver, "example.com")
|
||||
|
||||
mockResolver.On("LookupMX", mock.Anything, "example.com.").
|
||||
Return([]*net.MX{{Host: "mail.example.com.", Pref: 10}}, nil).Once()
|
||||
|
||||
resp := runRecordQuery(t, forwarder, "example.com", dns.TypeMX)
|
||||
assert.True(t, resp.RecursionAvailable, "the forwarder resolves recursively")
|
||||
})
|
||||
|
||||
t.Run("unsupported type NODATA", func(t *testing.T) {
|
||||
forwarder := newRecordTestForwarder(t, &MockResolver{}, "example.com")
|
||||
|
||||
resp := runRecordQuery(t, forwarder, "example.com", dns.TypeCAA)
|
||||
require.Equal(t, dns.RcodeSuccess, resp.Rcode)
|
||||
assert.True(t, resp.RecursionAvailable, "RA describes the server, not the query type")
|
||||
})
|
||||
|
||||
t.Run("unauthorized domain", func(t *testing.T) {
|
||||
forwarder := newRecordTestForwarder(t, &MockResolver{}, "example.com")
|
||||
|
||||
resp := runRecordQuery(t, forwarder, "other.com", dns.TypeMX)
|
||||
require.Equal(t, dns.RcodeRefused, resp.Rcode)
|
||||
assert.True(t, resp.RecursionAvailable, "RA describes the server, not the verdict")
|
||||
})
|
||||
}
|
||||
|
||||
func hasEDE(m *dns.Msg, code uint16) bool {
|
||||
opt := m.IsEdns0()
|
||||
if opt == nil {
|
||||
@@ -859,7 +892,7 @@ func TestDNSForwarder_UpstreamFailureEDE(t *testing.T) {
|
||||
lookupErr: &net.DNSError{Err: "i/o timeout", Server: "10.0.0.53:53", IsTimeout: true},
|
||||
reqEdns: true,
|
||||
wantEDE: true,
|
||||
wantCode: edeNetbirdUpstreamTimeout,
|
||||
wantCode: resutil.EDENetbirdUpstreamTimeout,
|
||||
wantTextHas: "netbird forwarder: upstream timeout",
|
||||
},
|
||||
{
|
||||
@@ -867,7 +900,7 @@ func TestDNSForwarder_UpstreamFailureEDE(t *testing.T) {
|
||||
lookupErr: &net.DNSError{Err: "server misbehaving", Server: "10.0.0.53:53"},
|
||||
reqEdns: true,
|
||||
wantEDE: true,
|
||||
wantCode: edeNetbirdUpstreamFailure,
|
||||
wantCode: resutil.EDENetbirdUpstreamFailure,
|
||||
wantTextHas: "netbird forwarder: upstream failure",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
nbdns "github.com/netbirdio/netbird/client/internal/dns"
|
||||
"github.com/netbirdio/netbird/client/internal/dns/resutil"
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
"github.com/netbirdio/netbird/client/internal/peerstore"
|
||||
"github.com/netbirdio/netbird/client/internal/routemanager/common"
|
||||
"github.com/netbirdio/netbird/client/internal/routemanager/fakeip"
|
||||
iface "github.com/netbirdio/netbird/client/internal/routemanager/iface"
|
||||
@@ -40,6 +39,61 @@ type internalDNATer interface {
|
||||
AddInternalDNATMapping(netip.Addr, netip.Addr) error
|
||||
}
|
||||
|
||||
// peerAllowedIPs reports the tunnel address a peer is reachable on.
|
||||
type peerAllowedIPs interface {
|
||||
AllowedIP(pubKey string) (netip.Addr, bool)
|
||||
}
|
||||
|
||||
// disposition says where a query for a given record type has to be answered.
|
||||
type disposition int
|
||||
|
||||
const (
|
||||
// dispositionPeer: the routing peer owns the answer. Address records are
|
||||
// what a DNS route exists for, and their answer programs the routes,
|
||||
// allowed IPs and firewall sets, so they are never resolved anywhere else.
|
||||
dispositionPeer disposition = iota
|
||||
// dispositionPeerFirst: the peer's forwarder resolves the type, and the
|
||||
// records may only exist inside the routed network, so it has to be asked.
|
||||
// A peer running a client that predates that support cannot answer, which
|
||||
// only its reply reveals.
|
||||
dispositionPeerFirst
|
||||
// dispositionChain: no forwarder resolves the type, so asking would cost a
|
||||
// tunnel round trip for a reply that says nothing. Public records for the
|
||||
// name are still better than none, so the query goes to the rest of the
|
||||
// chain.
|
||||
dispositionChain
|
||||
)
|
||||
|
||||
func dispositionFor(qtype uint16) disposition {
|
||||
switch {
|
||||
case qtype == dns.TypeA || qtype == dns.TypeAAAA:
|
||||
return dispositionPeer
|
||||
case resutil.SupportedRecordQtype(qtype):
|
||||
return dispositionPeerFirst
|
||||
default:
|
||||
return dispositionChain
|
||||
}
|
||||
}
|
||||
|
||||
// peerCannotAnswer reports whether a forwarder reply means the peer is unable to
|
||||
// resolve this query type, as opposed to having resolved it and found nothing.
|
||||
// A forwarder older than the one that learned to resolve non-address types
|
||||
// answers NOTIMP to all of them, before it even looks at the domain; FORMERR
|
||||
// covers one that cannot parse the EDNS0 we add to the query.
|
||||
//
|
||||
// REFUSED is deliberately not here. It says the peer does not hold the name,
|
||||
// which happens while the client and the peer disagree about the route set, and
|
||||
// falling through then would hand the name of an internal-only domain to a
|
||||
// public resolver. No forwarder version reports a missing record type that way.
|
||||
func peerCannotAnswer(rcode int) bool {
|
||||
switch rcode {
|
||||
case dns.RcodeNotImplemented, dns.RcodeFormatError:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type DnsInterceptor struct {
|
||||
mu sync.RWMutex
|
||||
route *route.Route
|
||||
@@ -50,7 +104,7 @@ type DnsInterceptor struct {
|
||||
currentPeerKey string
|
||||
interceptedDomains domainMap
|
||||
wgInterface iface.WGIface
|
||||
peerStore *peerstore.Store
|
||||
peerStore peerAllowedIPs
|
||||
firewall firewall.Manager
|
||||
fakeIPManager *fakeip.Manager
|
||||
forwarderPort *atomic.Uint32
|
||||
@@ -226,11 +280,14 @@ func (d *DnsInterceptor) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
return
|
||||
}
|
||||
|
||||
// All query types for an intercepted domain are forwarded to the peer's
|
||||
// DNS forwarder, which owns the name. Falling through to the system
|
||||
// resolver would let it answer NXDOMAIN for a name it isn't authoritative
|
||||
// for, poisoning the whole name (including the A/AAAA records the route
|
||||
// does serve). The forwarder answers NODATA for types it cannot resolve.
|
||||
qtype := r.Question[0].Qtype
|
||||
dispose := dispositionFor(qtype)
|
||||
|
||||
if dispose == dispositionChain {
|
||||
d.deferToChain(w, r, logger, "unsupported-qtype")
|
||||
return
|
||||
}
|
||||
|
||||
d.mu.RLock()
|
||||
peerKey := d.currentPeerKey
|
||||
d.mu.RUnlock()
|
||||
@@ -246,35 +303,33 @@ func (d *DnsInterceptor) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
return
|
||||
}
|
||||
|
||||
if r.Extra == nil {
|
||||
r.MsgHdr.AuthenticatedData = true
|
||||
}
|
||||
|
||||
// Advertise EDNS0 to the forwarder so it may return an Extended DNS Error
|
||||
// describing why a lookup failed. The OPT is stripped from the reply when
|
||||
// the original client did not request EDNS0.
|
||||
hadEdns := r.IsEdns0() != nil
|
||||
if !hadEdns {
|
||||
r.SetEdns0(dns.DefaultMsgSize, false)
|
||||
}
|
||||
query, hadEdns := peerQuery(r)
|
||||
|
||||
upstream := net.JoinHostPort(upstreamIP.String(), strconv.FormatUint(uint64(d.forwarderPort.Load()), 10))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), dnsTimeout)
|
||||
defer cancel()
|
||||
|
||||
reply := d.queryUpstreamDNS(ctx, w, r, upstream, upstreamIP, peerKey, logger)
|
||||
reply := d.queryUpstreamDNS(ctx, w, query, upstream, upstreamIP, peerKey, logger)
|
||||
if reply == nil {
|
||||
// queryUpstreamDNS already logged the failure and answered the client
|
||||
return
|
||||
}
|
||||
|
||||
// The peer owns the name but its forwarder cannot resolve this type. No
|
||||
// capability is announced anywhere, so the round trip above is the probe.
|
||||
if dispose == dispositionPeerFirst && peerCannotAnswer(reply.Rcode) {
|
||||
d.deferToChain(w, r, logger, "peer-rcode-"+dns.RcodeToString[reply.Rcode])
|
||||
return
|
||||
}
|
||||
|
||||
if ede, ok := resutil.ExtractEDE(reply); ok {
|
||||
resutil.SetMeta(w, "ede", fmt.Sprintf("%d %s", ede.InfoCode, ede.ExtraText))
|
||||
resutil.SetMeta(w, resutil.MetaKeyEDE, fmt.Sprintf("%d %s", ede.InfoCode, ede.ExtraText))
|
||||
}
|
||||
if !hadEdns {
|
||||
resutil.StripOPT(reply)
|
||||
}
|
||||
|
||||
resutil.SetMeta(w, "peer", peerKey)
|
||||
resutil.SetMeta(w, resutil.MetaKeyPeer, peerKey)
|
||||
|
||||
reply.Id = r.Id
|
||||
if err := d.writeMsg(w, reply, logger); err != nil {
|
||||
@@ -282,6 +337,30 @@ func (d *DnsInterceptor) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
}
|
||||
}
|
||||
|
||||
// deferToChain hands the query to the next handler in the chain and asks the
|
||||
// chain to soften the negative verdict of whatever answers instead. The
|
||||
// resolvers below cannot prove a name inside the routed network absent, so their
|
||||
// NXDOMAIN must not reach the client: it would be cached for the name and every
|
||||
// type under it, taking the addresses this route does serve with it.
|
||||
func (d *DnsInterceptor) deferToChain(w dns.ResponseWriter, r *dns.Msg, logger *log.Entry, reason string) {
|
||||
logger.Tracef("continuing to next handler for domain=%s type=%s reason=%s",
|
||||
r.Question[0].Name, dns.TypeToString[r.Question[0].Qtype], reason)
|
||||
|
||||
resutil.RequestSoftNegative(w)
|
||||
// Carried to the chain's response log line: without it the answer looks like
|
||||
// it came from the fallthrough resolver on its own.
|
||||
resutil.SetMeta(w, resutil.MetaKeyDeferredBy, "dns-route")
|
||||
resutil.SetMeta(w, resutil.MetaKeyDeferredReason, reason)
|
||||
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(r, dns.RcodeNameError)
|
||||
// Set Zero bit to signal handler chain to continue
|
||||
resp.MsgHdr.Zero = true
|
||||
if err := w.WriteMsg(resp); err != nil {
|
||||
logger.Errorf("failed writing DNS continue response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DnsInterceptor) writeDNSError(w dns.ResponseWriter, r *dns.Msg, logger *log.Entry, reason string) {
|
||||
logger.Warnf("failed to query upstream for domain=%s: %s", r.Question[0].Name, reason)
|
||||
|
||||
@@ -621,3 +700,26 @@ func (d *DnsInterceptor) debugPeerTimeout(peerIP netip.Addr, peerKey string) str
|
||||
|
||||
return fmt.Sprintf(" (peer %s)", nbdns.FormatPeerStatus(&peerState))
|
||||
}
|
||||
|
||||
// peerQuery builds the query sent to a peer's DNS forwarder and reports whether
|
||||
// the client itself advertised EDNS0. EDNS0 is added so the forwarder can return
|
||||
// an Extended DNS Error describing an upstream failure, and the OPT is stripped
|
||||
// from the reply again when the client did not ask for it. The client's message
|
||||
// is left untouched: it may still be handed to the next handler in the chain,
|
||||
// and neither the OPT nor the AD bit is ours to put on the wire on its behalf.
|
||||
func peerQuery(r *dns.Msg) (query *dns.Msg, hadEdns bool) {
|
||||
query = r.Copy()
|
||||
hadEdns = query.IsEdns0() != nil
|
||||
|
||||
// AD tells the forwarder we understand authenticated data. Only set when the
|
||||
// client sent no additional section of its own, so we never overrule what it
|
||||
// asked for.
|
||||
if len(query.Extra) == 0 {
|
||||
query.MsgHdr.AuthenticatedData = true
|
||||
}
|
||||
if !hadEdns {
|
||||
query.SetEdns0(dns.DefaultMsgSize, false)
|
||||
}
|
||||
|
||||
return query, hadEdns
|
||||
}
|
||||
|
||||
399
client/internal/routemanager/dnsinterceptor/handler_test.go
Normal file
399
client/internal/routemanager/dnsinterceptor/handler_test.go
Normal file
@@ -0,0 +1,399 @@
|
||||
package dnsinterceptor
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.zx2c4.com/wireguard/tun/netstack"
|
||||
|
||||
"github.com/netbirdio/netbird/client/iface/device"
|
||||
"github.com/netbirdio/netbird/client/iface/wgaddr"
|
||||
"github.com/netbirdio/netbird/client/internal/dns/resutil"
|
||||
"github.com/netbirdio/netbird/client/internal/dns/test"
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
"github.com/netbirdio/netbird/route"
|
||||
)
|
||||
|
||||
// softNegativeWriter records what the handler told the chain: whether to soften
|
||||
// a negative verdict from the handlers it defers to, and the metadata that ends
|
||||
// up on the chain's response log line.
|
||||
type softNegativeWriter struct {
|
||||
test.MockResponseWriter
|
||||
softNegative bool
|
||||
meta map[resutil.MetaKey]string
|
||||
}
|
||||
|
||||
func (w *softNegativeWriter) RequestSoftNegative() { w.softNegative = true }
|
||||
|
||||
func (w *softNegativeWriter) RequestID() string { return "test" }
|
||||
|
||||
func (w *softNegativeWriter) SetMeta(key resutil.MetaKey, value string) {
|
||||
if w.meta == nil {
|
||||
w.meta = make(map[resutil.MetaKey]string)
|
||||
}
|
||||
w.meta[key] = value
|
||||
}
|
||||
|
||||
// TestServeDNS_QtypeTheForwarderCannotResolve covers the record types no DNS
|
||||
// forwarder can answer, because the host resolver exposes no API for them.
|
||||
// Asking the peer only burns a tunnel round trip, so the query goes straight to
|
||||
// the rest of the chain. No peer key is configured, proving no round trip is
|
||||
// attempted.
|
||||
func TestServeDNS_QtypeTheForwarderCannotResolve(t *testing.T) {
|
||||
qtypes := []uint16{
|
||||
dns.TypeHTTPS,
|
||||
dns.TypeSVCB,
|
||||
dns.TypeCAA,
|
||||
dns.TypeNAPTR,
|
||||
dns.TypeTLSA,
|
||||
dns.TypeSOA,
|
||||
}
|
||||
|
||||
for _, qtype := range qtypes {
|
||||
t.Run(dns.TypeToString[qtype], func(t *testing.T) {
|
||||
d := &DnsInterceptor{}
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("db.example.com.", qtype)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
resp := w.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must be written")
|
||||
assert.Equal(t, dns.RcodeNameError, resp.Rcode, "chain continuation is signalled as NXDOMAIN")
|
||||
assert.True(t, resp.MsgHdr.Zero, "Zero bit must be set so the chain continues")
|
||||
assert.True(t, w.softNegative,
|
||||
"a downstream NXDOMAIN must be softened, or the fallthrough poisons the routed name")
|
||||
assert.Equal(t, "dns-route", w.meta[resutil.MetaKeyDeferredBy],
|
||||
"the chain's response log line must name us as the handler that stepped aside")
|
||||
assert.Equal(t, "unsupported-qtype", w.meta[resutil.MetaKeyDeferredReason],
|
||||
"the reason must survive to the log line, or the fallthrough is invisible")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestServeDNS_AddressQtypeNeverFallsThrough locks in the opposite case: A and
|
||||
// AAAA are what the route exists for, and the peer is authoritative for them.
|
||||
// A missing peer is an error the client must see, never a fallthrough to a
|
||||
// resolver that knows nothing about the routed name.
|
||||
func TestServeDNS_AddressQtypeNeverFallsThrough(t *testing.T) {
|
||||
for _, qtype := range []uint16{dns.TypeA, dns.TypeAAAA} {
|
||||
t.Run(dns.TypeToString[qtype], func(t *testing.T) {
|
||||
d := &DnsInterceptor{}
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("db.example.com.", qtype)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
resp := w.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must be written")
|
||||
assert.Equal(t, dns.RcodeServerFailure, resp.Rcode, "an unusable route must fail, not fall through")
|
||||
assert.False(t, resp.MsgHdr.Zero, "the chain must not continue for address queries")
|
||||
assert.False(t, w.softNegative, "no fallthrough means nothing to soften")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispositionFor pins the query-type policy, and ties the types we ask a
|
||||
// peer about to the types a forwarder can actually resolve, so the two ends
|
||||
// cannot drift apart.
|
||||
func TestDispositionFor(t *testing.T) {
|
||||
tests := []struct {
|
||||
qtype uint16
|
||||
want disposition
|
||||
}{
|
||||
{dns.TypeA, dispositionPeer},
|
||||
{dns.TypeAAAA, dispositionPeer},
|
||||
{dns.TypeMX, dispositionPeerFirst},
|
||||
{dns.TypeTXT, dispositionPeerFirst},
|
||||
{dns.TypeNS, dispositionPeerFirst},
|
||||
{dns.TypeSRV, dispositionPeerFirst},
|
||||
{dns.TypeCNAME, dispositionPeerFirst},
|
||||
{dns.TypePTR, dispositionPeerFirst},
|
||||
{dns.TypeHTTPS, dispositionChain},
|
||||
{dns.TypeSVCB, dispositionChain},
|
||||
{dns.TypeCAA, dispositionChain},
|
||||
{dns.TypeNAPTR, dispositionChain},
|
||||
{dns.TypeTLSA, dispositionChain},
|
||||
{dns.TypeDS, dispositionChain},
|
||||
{dns.TypeDNSKEY, dispositionChain},
|
||||
{dns.TypeSOA, dispositionChain},
|
||||
{dns.TypeANY, dispositionChain},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(dns.TypeToString[tt.qtype], func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, dispositionFor(tt.qtype), "disposition for %s", dns.TypeToString[tt.qtype])
|
||||
|
||||
// Address types are resolved by the forwarder's address path, not by
|
||||
// its record path, so they are deliberately outside
|
||||
// SupportedRecordQtype and their disposition does not depend on it.
|
||||
if tt.want == dispositionPeer {
|
||||
assert.False(t, resutil.SupportedRecordQtype(tt.qtype),
|
||||
"address types take the forwarder's address path")
|
||||
return
|
||||
}
|
||||
|
||||
assert.Equal(t, tt.want == dispositionPeerFirst, resutil.SupportedRecordQtype(tt.qtype),
|
||||
"only types a forwarder resolves may be sent to a peer")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerCannotAnswer separates a peer that cannot resolve a type from one that
|
||||
// resolved it and found nothing. Only the former may be retried elsewhere:
|
||||
// treating NODATA or NXDOMAIN as a capability failure would send the client to a
|
||||
// public resolver behind the peer's back and prefer a public record over the
|
||||
// private one the route exists to reach.
|
||||
func TestPeerCannotAnswer(t *testing.T) {
|
||||
cannot := []int{dns.RcodeNotImplemented, dns.RcodeFormatError}
|
||||
for _, rcode := range cannot {
|
||||
assert.True(t, peerCannotAnswer(rcode), "%s means the peer cannot answer", dns.RcodeToString[rcode])
|
||||
}
|
||||
|
||||
// REFUSED belongs here, not above: it says the peer does not hold the name,
|
||||
// so retrying elsewhere would leak the name of an internal-only domain to a
|
||||
// public resolver. No forwarder version reports a missing record type this
|
||||
// way, so nothing is lost by keeping it out.
|
||||
can := []int{
|
||||
dns.RcodeSuccess,
|
||||
dns.RcodeNameError,
|
||||
dns.RcodeServerFailure,
|
||||
dns.RcodeNotAuth,
|
||||
dns.RcodeRefused,
|
||||
}
|
||||
for _, rcode := range can {
|
||||
assert.False(t, peerCannotAnswer(rcode), "%s is the peer's answer, not a capability failure", dns.RcodeToString[rcode])
|
||||
}
|
||||
}
|
||||
|
||||
// fakeWGIface is the minimum an interceptor needs to reach a peer's DNS
|
||||
// forwarder over a plain socket. A nil netstack keeps the exchange on the host
|
||||
// stack so the test can point it at a loopback listener.
|
||||
type fakeWGIface struct{}
|
||||
|
||||
func (fakeWGIface) AddAllowedIP(string, netip.Prefix) error { return nil }
|
||||
func (fakeWGIface) RemoveAllowedIP(string, netip.Prefix) error { return nil }
|
||||
func (fakeWGIface) Name() string { return "wt0" }
|
||||
func (fakeWGIface) Address() wgaddr.Address { return wgaddr.Address{} }
|
||||
func (fakeWGIface) ToInterface() *net.Interface { return nil }
|
||||
func (fakeWGIface) IsUserspaceBind() bool { return false }
|
||||
func (fakeWGIface) GetFilter() device.PacketFilter { return nil }
|
||||
func (fakeWGIface) GetDevice() *device.FilteredDevice { return nil }
|
||||
func (fakeWGIface) GetNet() *netstack.Net { return nil }
|
||||
|
||||
// fakePeerIPs resolves every peer key to the loopback address the test's
|
||||
// forwarder stub listens on.
|
||||
type fakePeerIPs struct {
|
||||
addr netip.Addr
|
||||
}
|
||||
|
||||
func (p fakePeerIPs) AllowedIP(string) (netip.Addr, bool) { return p.addr, p.addr.IsValid() }
|
||||
|
||||
// forwarderStub stands in for the DNS forwarder of a routing peer, recording
|
||||
// what it was asked and answering with a canned reply.
|
||||
type forwarderStub struct {
|
||||
mu sync.Mutex
|
||||
queries []*dns.Msg
|
||||
reply func(q *dns.Msg) *dns.Msg
|
||||
port uint16
|
||||
shutdown func()
|
||||
}
|
||||
|
||||
func (s *forwarderStub) received() []*dns.Msg {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]*dns.Msg(nil), s.queries...)
|
||||
}
|
||||
|
||||
func newForwarderStub(t *testing.T, reply func(q *dns.Msg) *dns.Msg) *forwarderStub {
|
||||
t.Helper()
|
||||
|
||||
conn, err := net.ListenUDP("udp", net.UDPAddrFromAddrPort(netip.MustParseAddrPort("127.0.0.1:0")))
|
||||
require.NoError(t, err, "listen for the forwarder stub")
|
||||
|
||||
stub := &forwarderStub{reply: reply}
|
||||
stub.port = uint16(conn.LocalAddr().(*net.UDPAddr).Port)
|
||||
|
||||
mux := dns.NewServeMux()
|
||||
mux.HandleFunc(".", func(w dns.ResponseWriter, q *dns.Msg) {
|
||||
stub.mu.Lock()
|
||||
stub.queries = append(stub.queries, q.Copy())
|
||||
stub.mu.Unlock()
|
||||
_ = w.WriteMsg(stub.reply(q))
|
||||
})
|
||||
|
||||
srv := &dns.Server{PacketConn: conn, Handler: mux}
|
||||
started := make(chan struct{})
|
||||
srv.NotifyStartedFunc = func() { close(started) }
|
||||
go func() {
|
||||
_ = srv.ActivateAndServe()
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("forwarder stub did not start")
|
||||
}
|
||||
|
||||
stub.shutdown = func() { _ = srv.Shutdown() }
|
||||
t.Cleanup(stub.shutdown)
|
||||
|
||||
return stub
|
||||
}
|
||||
|
||||
func newTestInterceptor(t *testing.T, stub *forwarderStub) *DnsInterceptor {
|
||||
t.Helper()
|
||||
|
||||
port := new(atomic.Uint32)
|
||||
port.Store(uint32(stub.port))
|
||||
|
||||
return &DnsInterceptor{
|
||||
route: &route.Route{Domains: nil},
|
||||
statusRecorder: peer.NewRecorder("https://mgm"),
|
||||
currentPeerKey: "peer-key",
|
||||
interceptedDomains: make(domainMap),
|
||||
wgInterface: fakeWGIface{},
|
||||
peerStore: fakePeerIPs{addr: netip.MustParseAddr("127.0.0.1")},
|
||||
forwarderPort: port,
|
||||
}
|
||||
}
|
||||
|
||||
// TestServeDNS_PeerCannotResolveQtype is the reported regression: a routing peer
|
||||
// running a client older than the one that taught the forwarder about non-address
|
||||
// record types answers NOTIMP for every SRV query, and the interceptor used to
|
||||
// hand that straight to the application, breaking SRV-based service discovery.
|
||||
// The client cannot know the peer's capability up front, so it must try the peer
|
||||
// and fall back to the chain when the peer says it cannot answer.
|
||||
func TestServeDNS_PeerCannotResolveQtype(t *testing.T) {
|
||||
for _, rcode := range []int{dns.RcodeNotImplemented, dns.RcodeFormatError} {
|
||||
t.Run(dns.RcodeToString[rcode], func(t *testing.T) {
|
||||
stub := newForwarderStub(t, func(q *dns.Msg) *dns.Msg {
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(q, rcode)
|
||||
return resp
|
||||
})
|
||||
d := newTestInterceptor(t, stub)
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
require.Len(t, stub.received(), 1, "the peer must be asked before giving up on it")
|
||||
|
||||
resp := w.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must be written")
|
||||
assert.Equal(t, dns.RcodeNameError, resp.Rcode, "chain continuation is signalled as NXDOMAIN")
|
||||
assert.True(t, resp.MsgHdr.Zero, "Zero bit must be set so the chain continues")
|
||||
assert.True(t, w.softNegative, "the fallthrough must not be allowed to poison the routed name")
|
||||
assert.Equal(t, "dns-route", w.meta[resutil.MetaKeyDeferredBy])
|
||||
assert.Equal(t, "peer-rcode-"+dns.RcodeToString[rcode], w.meta[resutil.MetaKeyDeferredReason],
|
||||
"the peer's verdict must be visible in the log, it is the only trace of the probe")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestServeDNS_PeerVerdictPassesThrough covers the replies that are the peer's
|
||||
// answer rather than a statement about its capability. The peer is authoritative
|
||||
// for a name routed to it, so its verdict reaches the client as it is: retrying
|
||||
// these elsewhere would send the name of an internal-only domain to a public
|
||||
// resolver and prefer whatever that resolver says over the route.
|
||||
func TestServeDNS_PeerVerdictPassesThrough(t *testing.T) {
|
||||
// REFUSED means the peer does not consider the name routed to it, which
|
||||
// happens while the client and the peer disagree about the route set. It is
|
||||
// never how a peer reports a record type it cannot resolve: a forwarder too
|
||||
// old for non-address types answers NOTIMP before it looks at the domain.
|
||||
for _, rcode := range []int{dns.RcodeRefused, dns.RcodeNameError, dns.RcodeSuccess} {
|
||||
t.Run(dns.RcodeToString[rcode], func(t *testing.T) {
|
||||
stub := newForwarderStub(t, func(q *dns.Msg) *dns.Msg {
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(q, rcode)
|
||||
return resp
|
||||
})
|
||||
d := newTestInterceptor(t, stub)
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
require.Len(t, stub.received(), 1, "the peer must be asked exactly once")
|
||||
|
||||
resp := w.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must be written")
|
||||
assert.Equal(t, rcode, resp.Rcode, "the peer's verdict must reach the client unchanged")
|
||||
assert.False(t, resp.MsgHdr.Zero, "the chain must not continue past an answered query")
|
||||
assert.False(t, w.softNegative, "nothing was deferred, so nothing may be softened")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestServeDNS_PeerResolvesQtype guards the common case: a peer that can answer
|
||||
// the type stays authoritative, and its records reach the client unchanged.
|
||||
func TestServeDNS_PeerResolvesQtype(t *testing.T) {
|
||||
stub := newForwarderStub(t, func(q *dns.Msg) *dns.Msg {
|
||||
resp := new(dns.Msg)
|
||||
resp.SetReply(q)
|
||||
resp.Answer = []dns.RR{&dns.SRV{
|
||||
Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeSRV, Class: dns.ClassINET, Ttl: 60},
|
||||
Target: "shard-00.db.example.com.",
|
||||
Port: 27017,
|
||||
}}
|
||||
return resp
|
||||
})
|
||||
d := newTestInterceptor(t, stub)
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
resp := w.GetLastResponse()
|
||||
require.NotNil(t, resp, "a response must be written")
|
||||
assert.Equal(t, dns.RcodeSuccess, resp.Rcode)
|
||||
require.Len(t, resp.Answer, 1, "the peer's records must pass through")
|
||||
assert.False(t, resp.MsgHdr.Zero, "an answered query must not continue the chain")
|
||||
assert.False(t, w.softNegative)
|
||||
}
|
||||
|
||||
// TestServeDNS_DeferredQueryIsPristine covers what the fallthrough hands to the
|
||||
// next handler. The interceptor advertises EDNS0 to the peer so the forwarder can
|
||||
// return an Extended DNS Error, and sets AD, but neither belongs to the client's
|
||||
// query: on the deferred path they would travel to the public resolver and the
|
||||
// reply could come back carrying an OPT the client never advertised, which
|
||||
// RFC 6891 forbids us from passing on.
|
||||
func TestServeDNS_DeferredQueryIsPristine(t *testing.T) {
|
||||
stub := newForwarderStub(t, func(q *dns.Msg) *dns.Msg {
|
||||
resp := new(dns.Msg)
|
||||
resp.SetRcode(q, dns.RcodeNotImplemented)
|
||||
return resp
|
||||
})
|
||||
d := newTestInterceptor(t, stub)
|
||||
w := &softNegativeWriter{}
|
||||
|
||||
r := new(dns.Msg)
|
||||
r.SetQuestion("_mongodb._tcp.db.example.com.", dns.TypeSRV)
|
||||
|
||||
d.ServeDNS(w, r)
|
||||
|
||||
sent := stub.received()
|
||||
require.Len(t, sent, 1)
|
||||
assert.NotNil(t, sent[0].IsEdns0(), "the peer must be asked with EDNS0 so it can return an EDE")
|
||||
|
||||
assert.Nil(t, r.IsEdns0(), "the deferred query must not carry an OPT the client never sent")
|
||||
assert.False(t, r.AuthenticatedData, "the deferred query must not carry an AD bit the client never set")
|
||||
assert.Empty(t, r.Extra, "the deferred query must reach the next handler as the client sent it")
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build windows
|
||||
|
||||
package dnsinterceptor
|
||||
|
||||
// GetInterfaceGUIDString completes iface.WGIface on Windows, which requires the
|
||||
// interface GUID for DNS registration.
|
||||
func (fakeWGIface) GetInterfaceGUIDString() (string, error) { return "", nil }
|
||||
@@ -228,8 +228,6 @@ read_enable_crowdsec() {
|
||||
echo "CrowdSec checks client IPs against a community threat intelligence database" > /dev/stderr
|
||||
echo "and blocks known malicious sources before they reach your services." > /dev/stderr
|
||||
echo "A local CrowdSec LAPI container will be added to your deployment." > /dev/stderr
|
||||
echo "It also enables the AppSec (WAF) endpoint, so services can inspect HTTP" > /dev/stderr
|
||||
echo "requests for exploits. Both stay off per service until you enable them." > /dev/stderr
|
||||
echo -n "Enable CrowdSec? [y/N]: " > /dev/stderr
|
||||
read -r CHOICE < /dev/tty
|
||||
|
||||
@@ -499,8 +497,7 @@ generate_configuration_files() {
|
||||
# TCP ServersTransport for PROXY protocol v2 to the proxy backend
|
||||
render_traefik_dynamic > traefik-dynamic.yaml
|
||||
if [[ "$ENABLE_CROWDSEC" == "true" ]]; then
|
||||
mkdir -p crowdsec/acquis.d
|
||||
render_crowdsec_appsec_acquis > crowdsec/acquis.d/appsec.yaml
|
||||
mkdir -p crowdsec
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
@@ -534,23 +531,6 @@ generate_configuration_files() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# The AppSec (WAF) listener only exists if an appsec acquisition datasource is
|
||||
# configured. One datasource is one listener carrying one merged rule set: the
|
||||
# protocol has no rule-set selector, so per-service rule variation would need
|
||||
# either a second datasource on another port or pre_eval hooks filtering on
|
||||
# req.Host.
|
||||
render_crowdsec_appsec_acquis() {
|
||||
cat <<EOF
|
||||
source: appsec
|
||||
listen_addr: 0.0.0.0:7422
|
||||
appsec_configs:
|
||||
- crowdsecurity/appsec-default
|
||||
labels:
|
||||
type: appsec
|
||||
EOF
|
||||
return 0
|
||||
}
|
||||
|
||||
start_services_and_show_instructions() {
|
||||
# For built-in Traefik, start containers immediately
|
||||
# For NPM, start containers first (NPM needs services running to create proxy)
|
||||
@@ -762,11 +742,7 @@ render_docker_compose_traefik_builtin() {
|
||||
restart: unless-stopped
|
||||
networks: [netbird]
|
||||
environment:
|
||||
# appsec-generic-rules is required alongside appsec-virtual-patching:
|
||||
# the appsec-default config references crowdsecurity/generic-* and
|
||||
# crowdsecurity/experimental-*, which only that collection provides, and
|
||||
# the engine exits at startup if they are missing.
|
||||
COLLECTIONS: crowdsecurity/linux crowdsecurity/appsec-virtual-patching crowdsecurity/appsec-generic-rules
|
||||
COLLECTIONS: crowdsecurity/linux
|
||||
volumes:
|
||||
- ./crowdsec:/etc/crowdsec
|
||||
- crowdsec_db:/var/lib/crowdsec/data
|
||||
@@ -1031,11 +1007,6 @@ EOF
|
||||
cat <<EOF
|
||||
NB_PROXY_CROWDSEC_API_URL=http://crowdsec:8080
|
||||
NB_PROXY_CROWDSEC_API_KEY=$CROWDSEC_BOUNCER_KEY
|
||||
# AppSec (WAF) request inspection. Separate endpoint from the LAPI above and
|
||||
# validated with the same bouncer key. Setting it makes the proxy advertise the
|
||||
# AppSec capability, which is what lets a service select appsec_mode; nothing is
|
||||
# inspected until a service opts in.
|
||||
NB_PROXY_CROWDSEC_APPSEC_URL=http://crowdsec:7422/
|
||||
EOF
|
||||
fi
|
||||
|
||||
|
||||
@@ -23,9 +23,6 @@ type Domain struct {
|
||||
// SupportsCrowdSec is populated at query time from proxy cluster capabilities.
|
||||
// Not persisted.
|
||||
SupportsCrowdSec *bool `gorm:"-"`
|
||||
// SupportsAppSec is populated at query time from proxy cluster capabilities.
|
||||
// Not persisted.
|
||||
SupportsAppSec *bool `gorm:"-"`
|
||||
// SupportsPrivate is populated at query time from proxy cluster capabilities. Not persisted.
|
||||
SupportsPrivate *bool `gorm:"-"`
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ func domainToApi(d *domain.Domain) api.ReverseProxyDomain {
|
||||
SupportsCustomPorts: d.SupportsCustomPorts,
|
||||
RequireSubdomain: d.RequireSubdomain,
|
||||
SupportsCrowdsec: d.SupportsCrowdSec,
|
||||
SupportsAppsec: d.SupportsAppSec,
|
||||
SupportsPrivate: d.SupportsPrivate,
|
||||
}
|
||||
if d.TargetCluster != "" {
|
||||
|
||||
@@ -35,7 +35,6 @@ type proxyManager interface {
|
||||
ClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool
|
||||
}
|
||||
|
||||
@@ -95,7 +94,6 @@ func (m Manager) GetDomains(ctx context.Context, accountID, userID string) ([]*d
|
||||
d.SupportsCustomPorts = m.proxyManager.ClusterSupportsCustomPorts(ctx, cluster)
|
||||
d.RequireSubdomain = m.proxyManager.ClusterRequireSubdomain(ctx, cluster)
|
||||
d.SupportsCrowdSec = m.proxyManager.ClusterSupportsCrowdSec(ctx, cluster)
|
||||
d.SupportsAppSec = m.proxyManager.ClusterSupportsAppSec(ctx, cluster)
|
||||
d.SupportsPrivate = m.proxyManager.ClusterSupportsPrivate(ctx, cluster)
|
||||
ret = append(ret, d)
|
||||
}
|
||||
@@ -113,7 +111,6 @@ func (m Manager) GetDomains(ctx context.Context, accountID, userID string) ([]*d
|
||||
if d.TargetCluster != "" {
|
||||
cd.SupportsCustomPorts = m.proxyManager.ClusterSupportsCustomPorts(ctx, d.TargetCluster)
|
||||
cd.SupportsCrowdSec = m.proxyManager.ClusterSupportsCrowdSec(ctx, d.TargetCluster)
|
||||
cd.SupportsAppSec = m.proxyManager.ClusterSupportsAppSec(ctx, d.TargetCluster)
|
||||
cd.SupportsPrivate = m.proxyManager.ClusterSupportsPrivate(ctx, d.TargetCluster)
|
||||
}
|
||||
// Custom domains never require a subdomain by default since
|
||||
|
||||
@@ -40,10 +40,6 @@ func (m *mockProxyManager) ClusterSupportsCrowdSec(_ context.Context, _ string)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockProxyManager) ClusterSupportsAppSec(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockProxyManager) ClusterSupportsPrivate(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ type Manager interface {
|
||||
ClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool
|
||||
CleanupStale(ctx context.Context, inactivityDuration time.Duration) error
|
||||
GetAccountProxy(ctx context.Context, accountID string) (*Proxy, error)
|
||||
|
||||
@@ -21,7 +21,6 @@ type store interface {
|
||||
GetClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool
|
||||
CleanupStaleProxies(ctx context.Context, inactivityDuration time.Duration) error
|
||||
GetProxyByAccountID(ctx context.Context, accountID string) (*proxy.Proxy, error)
|
||||
@@ -139,13 +138,6 @@ func (m Manager) ClusterSupportsCrowdSec(ctx context.Context, clusterAddr string
|
||||
return m.store.GetClusterSupportsCrowdSec(ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsAppSec returns whether all active proxies in the cluster have
|
||||
// a CrowdSec AppSec endpoint configured (unanimous). Returns nil when no proxy
|
||||
// has reported capabilities.
|
||||
func (m Manager) ClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool {
|
||||
return m.store.GetClusterSupportsAppSec(ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsPrivate reports whether any active proxy claims the private capability (nil = unreported).
|
||||
func (m Manager) ClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool {
|
||||
return m.store.GetClusterSupportsPrivate(ctx, clusterAddr)
|
||||
|
||||
@@ -99,9 +99,6 @@ func (m *mockStore) GetClusterRequireSubdomain(_ context.Context, _ string) *boo
|
||||
func (m *mockStore) GetClusterSupportsCrowdSec(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
func (m *mockStore) GetClusterSupportsAppSec(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
func (m *mockStore) GetClusterSupportsPrivate(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -50,6 +50,20 @@ func (mr *MockManagerMockRecorder) CleanupStale(ctx, inactivityDuration interfac
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanupStale", reflect.TypeOf((*MockManager)(nil).CleanupStale), ctx, inactivityDuration)
|
||||
}
|
||||
|
||||
// ClusterSupportsCustomPorts mocks base method.
|
||||
func (m *MockManager) ClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ClusterSupportsCustomPorts", ctx, clusterAddr)
|
||||
ret0, _ := ret[0].(*bool)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// ClusterSupportsCustomPorts indicates an expected call of ClusterSupportsCustomPorts.
|
||||
func (mr *MockManagerMockRecorder) ClusterSupportsCustomPorts(ctx, clusterAddr interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterSupportsCustomPorts", reflect.TypeOf((*MockManager)(nil).ClusterSupportsCustomPorts), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterRequireSubdomain mocks base method.
|
||||
func (m *MockManager) ClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -64,20 +78,6 @@ func (mr *MockManagerMockRecorder) ClusterRequireSubdomain(ctx, clusterAddr inte
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterRequireSubdomain", reflect.TypeOf((*MockManager)(nil).ClusterRequireSubdomain), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsAppSec mocks base method.
|
||||
func (m *MockManager) ClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ClusterSupportsAppSec", ctx, clusterAddr)
|
||||
ret0, _ := ret[0].(*bool)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// ClusterSupportsAppSec indicates an expected call of ClusterSupportsAppSec.
|
||||
func (mr *MockManagerMockRecorder) ClusterSupportsAppSec(ctx, clusterAddr interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterSupportsAppSec", reflect.TypeOf((*MockManager)(nil).ClusterSupportsAppSec), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsCrowdSec mocks base method.
|
||||
func (m *MockManager) ClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -92,20 +92,6 @@ func (mr *MockManagerMockRecorder) ClusterSupportsCrowdSec(ctx, clusterAddr inte
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterSupportsCrowdSec", reflect.TypeOf((*MockManager)(nil).ClusterSupportsCrowdSec), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsCustomPorts mocks base method.
|
||||
func (m *MockManager) ClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ClusterSupportsCustomPorts", ctx, clusterAddr)
|
||||
ret0, _ := ret[0].(*bool)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// ClusterSupportsCustomPorts indicates an expected call of ClusterSupportsCustomPorts.
|
||||
func (mr *MockManagerMockRecorder) ClusterSupportsCustomPorts(ctx, clusterAddr interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterSupportsCustomPorts", reflect.TypeOf((*MockManager)(nil).ClusterSupportsCustomPorts), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// ClusterSupportsPrivate mocks base method.
|
||||
func (m *MockManager) ClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -135,35 +121,6 @@ func (mr *MockManagerMockRecorder) Connect(ctx, proxyID, sessionID, clusterAddre
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connect", reflect.TypeOf((*MockManager)(nil).Connect), ctx, proxyID, sessionID, clusterAddress, ipAddress, accountID, capabilities)
|
||||
}
|
||||
|
||||
// CountAccountProxies mocks base method.
|
||||
func (m *MockManager) CountAccountProxies(ctx context.Context, accountID string) (int64, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "CountAccountProxies", ctx, accountID)
|
||||
ret0, _ := ret[0].(int64)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// CountAccountProxies indicates an expected call of CountAccountProxies.
|
||||
func (mr *MockManagerMockRecorder) CountAccountProxies(ctx, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountAccountProxies", reflect.TypeOf((*MockManager)(nil).CountAccountProxies), ctx, accountID)
|
||||
}
|
||||
|
||||
// DeleteAccountCluster mocks base method.
|
||||
func (m *MockManager) DeleteAccountCluster(ctx context.Context, clusterAddress, accountID string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "DeleteAccountCluster", ctx, clusterAddress, accountID)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// DeleteAccountCluster indicates an expected call of DeleteAccountCluster.
|
||||
func (mr *MockManagerMockRecorder) DeleteAccountCluster(ctx, clusterAddress, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAccountCluster", reflect.TypeOf((*MockManager)(nil).DeleteAccountCluster), ctx, clusterAddress, accountID)
|
||||
}
|
||||
|
||||
// Disconnect mocks base method.
|
||||
func (m *MockManager) Disconnect(ctx context.Context, proxyID, sessionID string) error {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -178,21 +135,6 @@ func (mr *MockManagerMockRecorder) Disconnect(ctx, proxyID, sessionID interface{
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnect", reflect.TypeOf((*MockManager)(nil).Disconnect), ctx, proxyID, sessionID)
|
||||
}
|
||||
|
||||
// GetAccountProxy mocks base method.
|
||||
func (m *MockManager) GetAccountProxy(ctx context.Context, accountID string) (*Proxy, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetAccountProxy", ctx, accountID)
|
||||
ret0, _ := ret[0].(*Proxy)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetAccountProxy indicates an expected call of GetAccountProxy.
|
||||
func (mr *MockManagerMockRecorder) GetAccountProxy(ctx, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountProxy", reflect.TypeOf((*MockManager)(nil).GetAccountProxy), ctx, accountID)
|
||||
}
|
||||
|
||||
// GetActiveClusterAddresses mocks base method.
|
||||
func (m *MockManager) GetActiveClusterAddresses(ctx context.Context) ([]string, error) {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -208,7 +150,6 @@ func (mr *MockManagerMockRecorder) GetActiveClusterAddresses(ctx interface{}) *g
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetActiveClusterAddresses", reflect.TypeOf((*MockManager)(nil).GetActiveClusterAddresses), ctx)
|
||||
}
|
||||
|
||||
// GetActiveClusterAddressesForAccount mocks base method.
|
||||
func (m *MockManager) GetActiveClusterAddressesForAccount(ctx context.Context, accountID string) ([]string, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetActiveClusterAddressesForAccount", ctx, accountID)
|
||||
@@ -217,7 +158,6 @@ func (m *MockManager) GetActiveClusterAddressesForAccount(ctx context.Context, a
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetActiveClusterAddressesForAccount indicates an expected call of GetActiveClusterAddressesForAccount.
|
||||
func (mr *MockManagerMockRecorder) GetActiveClusterAddressesForAccount(ctx, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetActiveClusterAddressesForAccount", reflect.TypeOf((*MockManager)(nil).GetActiveClusterAddressesForAccount), ctx, accountID)
|
||||
@@ -237,6 +177,36 @@ func (mr *MockManagerMockRecorder) Heartbeat(ctx, p interface{}) *gomock.Call {
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Heartbeat", reflect.TypeOf((*MockManager)(nil).Heartbeat), ctx, p)
|
||||
}
|
||||
|
||||
// GetAccountProxy mocks base method.
|
||||
func (m *MockManager) GetAccountProxy(ctx context.Context, accountID string) (*Proxy, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetAccountProxy", ctx, accountID)
|
||||
ret0, _ := ret[0].(*Proxy)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetAccountProxy indicates an expected call of GetAccountProxy.
|
||||
func (mr *MockManagerMockRecorder) GetAccountProxy(ctx, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountProxy", reflect.TypeOf((*MockManager)(nil).GetAccountProxy), ctx, accountID)
|
||||
}
|
||||
|
||||
// CountAccountProxies mocks base method.
|
||||
func (m *MockManager) CountAccountProxies(ctx context.Context, accountID string) (int64, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "CountAccountProxies", ctx, accountID)
|
||||
ret0, _ := ret[0].(int64)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// CountAccountProxies indicates an expected call of CountAccountProxies.
|
||||
func (mr *MockManagerMockRecorder) CountAccountProxies(ctx, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountAccountProxies", reflect.TypeOf((*MockManager)(nil).CountAccountProxies), ctx, accountID)
|
||||
}
|
||||
|
||||
// IsClusterAddressAvailable mocks base method.
|
||||
func (m *MockManager) IsClusterAddressAvailable(ctx context.Context, clusterAddress, accountID string) (bool, error) {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -252,6 +222,20 @@ func (mr *MockManagerMockRecorder) IsClusterAddressAvailable(ctx, clusterAddress
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsClusterAddressAvailable", reflect.TypeOf((*MockManager)(nil).IsClusterAddressAvailable), ctx, clusterAddress, accountID)
|
||||
}
|
||||
|
||||
// DeleteAccountCluster mocks base method.
|
||||
func (m *MockManager) DeleteAccountCluster(ctx context.Context, clusterAddress, accountID string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "DeleteAccountCluster", ctx, clusterAddress, accountID)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// DeleteAccountCluster indicates an expected call of DeleteAccountCluster.
|
||||
func (mr *MockManagerMockRecorder) DeleteAccountCluster(ctx, clusterAddress, accountID interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAccountCluster", reflect.TypeOf((*MockManager)(nil).DeleteAccountCluster), ctx, clusterAddress, accountID)
|
||||
}
|
||||
|
||||
// MockController is a mock of Controller interface.
|
||||
type MockController struct {
|
||||
ctrl *gomock.Controller
|
||||
|
||||
@@ -20,9 +20,6 @@ type Capabilities struct {
|
||||
RequireSubdomain *bool
|
||||
// SupportsCrowdsec indicates whether this proxy has CrowdSec configured.
|
||||
SupportsCrowdsec *bool
|
||||
// SupportsAppsec indicates whether this proxy has a CrowdSec AppSec (WAF)
|
||||
// endpoint configured.
|
||||
SupportsAppsec *bool
|
||||
// Private indicates whether this proxy supports inbound access via Wireguard
|
||||
// tunnel and netbird-only authentication policies
|
||||
Private *bool
|
||||
@@ -77,6 +74,5 @@ type Cluster struct {
|
||||
SupportsCustomPorts *bool
|
||||
RequireSubdomain *bool
|
||||
SupportsCrowdSec *bool
|
||||
SupportsAppSec *bool
|
||||
Private *bool
|
||||
}
|
||||
|
||||
@@ -204,7 +204,6 @@ func (h *handler) getClusters(w http.ResponseWriter, r *http.Request) {
|
||||
SupportsCustomPorts: c.SupportsCustomPorts,
|
||||
RequireSubdomain: c.RequireSubdomain,
|
||||
SupportsCrowdsec: c.SupportsCrowdSec,
|
||||
SupportsAppsec: c.SupportsAppSec,
|
||||
Private: c.Private,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -82,7 +82,6 @@ type CapabilityProvider interface {
|
||||
ClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool
|
||||
ClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool
|
||||
}
|
||||
|
||||
@@ -138,7 +137,6 @@ func (m *Manager) GetClusters(ctx context.Context, accountID, userID string) ([]
|
||||
clusters[i].SupportsCustomPorts = m.capabilities.ClusterSupportsCustomPorts(ctx, clusters[i].Address)
|
||||
clusters[i].RequireSubdomain = m.capabilities.ClusterRequireSubdomain(ctx, clusters[i].Address)
|
||||
clusters[i].SupportsCrowdSec = m.capabilities.ClusterSupportsCrowdSec(ctx, clusters[i].Address)
|
||||
clusters[i].SupportsAppSec = m.capabilities.ClusterSupportsAppSec(ctx, clusters[i].Address)
|
||||
clusters[i].Private = m.capabilities.ClusterSupportsPrivate(ctx, clusters[i].Address)
|
||||
}
|
||||
|
||||
|
||||
@@ -165,18 +165,6 @@ type AccessRestrictions struct {
|
||||
AllowedCountries []string `json:"allowed_countries,omitempty" gorm:"serializer:json"`
|
||||
BlockedCountries []string `json:"blocked_countries,omitempty" gorm:"serializer:json"`
|
||||
CrowdSecMode string `json:"crowdsec_mode,omitempty" gorm:"serializer:json"`
|
||||
// AppSecMode is the CrowdSec AppSec (WAF) request inspection mode: "",
|
||||
// "off", "enforce", or "observe". HTTP services only.
|
||||
AppSecMode string `json:"appsec_mode,omitempty" gorm:"serializer:json"`
|
||||
}
|
||||
|
||||
// isEmpty reports whether no restriction is configured. Both conversions drop
|
||||
// the object entirely in that case, so a field missing from this check is
|
||||
// silently discarded on the way to the API and the proxy.
|
||||
func (r AccessRestrictions) isEmpty() bool {
|
||||
return len(r.AllowedCIDRs) == 0 && len(r.BlockedCIDRs) == 0 &&
|
||||
len(r.AllowedCountries) == 0 && len(r.BlockedCountries) == 0 &&
|
||||
r.CrowdSecMode == "" && r.AppSecMode == ""
|
||||
}
|
||||
|
||||
// Copy returns a deep copy of the AccessRestrictions.
|
||||
@@ -187,7 +175,6 @@ func (r AccessRestrictions) Copy() AccessRestrictions {
|
||||
AllowedCountries: slices.Clone(r.AllowedCountries),
|
||||
BlockedCountries: slices.Clone(r.BlockedCountries),
|
||||
CrowdSecMode: r.CrowdSecMode,
|
||||
AppSecMode: r.AppSecMode,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -821,17 +808,13 @@ func restrictionsFromAPI(r *api.AccessRestrictions) (AccessRestrictions, error)
|
||||
}
|
||||
res.CrowdSecMode = string(*r.CrowdsecMode)
|
||||
}
|
||||
if r.AppsecMode != nil {
|
||||
if !r.AppsecMode.Valid() {
|
||||
return AccessRestrictions{}, fmt.Errorf("invalid appsec_mode %q", *r.AppsecMode)
|
||||
}
|
||||
res.AppSecMode = string(*r.AppsecMode)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func restrictionsToAPI(r AccessRestrictions) *api.AccessRestrictions {
|
||||
if r.isEmpty() {
|
||||
if len(r.AllowedCIDRs) == 0 && len(r.BlockedCIDRs) == 0 &&
|
||||
len(r.AllowedCountries) == 0 && len(r.BlockedCountries) == 0 &&
|
||||
r.CrowdSecMode == "" {
|
||||
return nil
|
||||
}
|
||||
res := &api.AccessRestrictions{}
|
||||
@@ -851,15 +834,13 @@ func restrictionsToAPI(r AccessRestrictions) *api.AccessRestrictions {
|
||||
mode := api.AccessRestrictionsCrowdsecMode(r.CrowdSecMode)
|
||||
res.CrowdsecMode = &mode
|
||||
}
|
||||
if r.AppSecMode != "" {
|
||||
mode := api.AccessRestrictionsAppsecMode(r.AppSecMode)
|
||||
res.AppsecMode = &mode
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func restrictionsToProto(r AccessRestrictions) *proto.AccessRestrictions {
|
||||
if r.isEmpty() {
|
||||
if len(r.AllowedCIDRs) == 0 && len(r.BlockedCIDRs) == 0 &&
|
||||
len(r.AllowedCountries) == 0 && len(r.BlockedCountries) == 0 &&
|
||||
r.CrowdSecMode == "" {
|
||||
return nil
|
||||
}
|
||||
return &proto.AccessRestrictions{
|
||||
@@ -868,7 +849,6 @@ func restrictionsToProto(r AccessRestrictions) *proto.AccessRestrictions {
|
||||
AllowedCountries: r.AllowedCountries,
|
||||
BlockedCountries: r.BlockedCountries,
|
||||
CrowdsecMode: r.CrowdSecMode,
|
||||
AppsecMode: r.AppSecMode,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -894,11 +874,6 @@ func (s *Service) Validate() error {
|
||||
if err := validateAccessRestrictions(&s.Restrictions); err != nil {
|
||||
return err
|
||||
}
|
||||
// AppSec inspects HTTP requests, so it cannot apply to the L4 modes, which
|
||||
// forward opaque byte streams.
|
||||
if appSecEnabled(s.Restrictions.AppSecMode) && s.Mode != ModeHTTP {
|
||||
return fmt.Errorf("appsec_mode is only supported for HTTP services, got mode %q", s.Mode)
|
||||
}
|
||||
if err := s.validatePrivateRequirements(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1267,27 +1242,10 @@ func validateCrowdSecMode(mode string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func validateAppSecMode(mode string) error {
|
||||
switch mode {
|
||||
case "", "off", "enforce", "observe":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("appsec_mode %q is invalid", mode)
|
||||
}
|
||||
}
|
||||
|
||||
// appSecEnabled reports whether the mode asks for request inspection.
|
||||
func appSecEnabled(mode string) bool {
|
||||
return mode == "enforce" || mode == "observe"
|
||||
}
|
||||
|
||||
func validateAccessRestrictions(r *AccessRestrictions) error {
|
||||
if err := validateCrowdSecMode(r.CrowdSecMode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateAppSecMode(r.AppSecMode); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(r.AllowedCIDRs) > maxCIDREntries {
|
||||
return fmt.Errorf("allowed_cidrs: exceeds maximum of %d entries", maxCIDREntries)
|
||||
|
||||
@@ -26,17 +26,6 @@ func validProxy() *Service {
|
||||
}
|
||||
}
|
||||
|
||||
// validL4Proxy returns a service that passes validation in one of the L4 modes.
|
||||
func validL4Proxy(mode string) *Service {
|
||||
rp := validProxy()
|
||||
rp.Mode = mode
|
||||
rp.ListenPort = 9000
|
||||
rp.Targets = []*Target{
|
||||
{TargetId: "peer-1", TargetType: TargetTypePeer, Host: "10.0.0.1", Port: 5432, Protocol: mode, Enabled: true},
|
||||
}
|
||||
return rp
|
||||
}
|
||||
|
||||
func TestValidate_Valid(t *testing.T) {
|
||||
require.NoError(t, validProxy().Validate())
|
||||
}
|
||||
@@ -1326,68 +1315,3 @@ func TestValidate_Private_RejectsNonHTTPMode(t *testing.T) {
|
||||
}}
|
||||
assert.ErrorContains(t, rp.Validate(), "HTTP")
|
||||
}
|
||||
|
||||
func TestRestrictions_AppSecMode_RoundTrip(t *testing.T) {
|
||||
mode := api.AccessRestrictionsAppsecModeEnforce
|
||||
apiIn := &api.AccessRestrictions{AppsecMode: &mode}
|
||||
|
||||
model, err := restrictionsFromAPI(apiIn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "enforce", model.AppSecMode)
|
||||
|
||||
// appsec_mode alone must keep the restrictions object alive on both the API
|
||||
// and proto legs: it is meaningful without any CIDR or country entry.
|
||||
apiOut := restrictionsToAPI(model)
|
||||
require.NotNil(t, apiOut, "appsec_mode alone must not collapse the restrictions to nil")
|
||||
require.NotNil(t, apiOut.AppsecMode)
|
||||
assert.Equal(t, api.AccessRestrictionsAppsecModeEnforce, *apiOut.AppsecMode)
|
||||
|
||||
protoOut := restrictionsToProto(model)
|
||||
require.NotNil(t, protoOut, "appsec_mode alone must reach the proxy")
|
||||
assert.Equal(t, "enforce", protoOut.AppsecMode)
|
||||
}
|
||||
|
||||
func TestRestrictions_AppSecMode_EmptyIsOmitted(t *testing.T) {
|
||||
model, err := restrictionsFromAPI(&api.AccessRestrictions{
|
||||
AllowedCidrs: &[]string{"203.0.113.0/24"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, model.AppSecMode)
|
||||
|
||||
apiOut := restrictionsToAPI(model)
|
||||
require.NotNil(t, apiOut)
|
||||
assert.Nil(t, apiOut.AppsecMode, "empty appsec_mode is omitted from the API response")
|
||||
}
|
||||
|
||||
func TestRestrictions_AppSecMode_CopyIsDeep(t *testing.T) {
|
||||
original := AccessRestrictions{AppSecMode: "observe", CrowdSecMode: "enforce"}
|
||||
assert.Equal(t, original, original.Copy(), "Copy must carry every mode field")
|
||||
}
|
||||
|
||||
func TestValidate_RejectsInvalidAppSecMode(t *testing.T) {
|
||||
rp := validProxy()
|
||||
rp.Restrictions = AccessRestrictions{AppSecMode: "sometimes"}
|
||||
assert.ErrorContains(t, rp.Validate(), "appsec_mode")
|
||||
}
|
||||
|
||||
func TestValidate_RejectsAppSecOnL4Modes(t *testing.T) {
|
||||
// AppSec inspects HTTP requests, so the L4 modes cannot honor it. Accepting
|
||||
// the field there would report protection that never runs.
|
||||
for _, mode := range []string{ModeTCP, ModeUDP, ModeTLS} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
rp := validL4Proxy(mode)
|
||||
rp.Restrictions = AccessRestrictions{AppSecMode: "enforce"}
|
||||
assert.ErrorContains(t, rp.Validate(), "appsec_mode is only supported for HTTP services")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate_AllowsAppSecOffOnL4Modes(t *testing.T) {
|
||||
for _, mode := range []string{ModeTCP, ModeUDP, ModeTLS} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
rp := validL4Proxy(mode)
|
||||
rp.Restrictions = AccessRestrictions{AppSecMode: "off"}
|
||||
require.NoError(t, rp.Validate(), "an explicit off must not be rejected on L4 services")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/domain"
|
||||
|
||||
"github.com/netbirdio/netbird/management/internals/modules/agentnetwork"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/peers"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/accesslogs"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/proxy"
|
||||
@@ -37,6 +36,7 @@ import (
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/sessionkey"
|
||||
"github.com/netbirdio/netbird/management/server/idp"
|
||||
"github.com/netbirdio/netbird/management/server/peer"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/agentnetwork"
|
||||
"github.com/netbirdio/netbird/management/server/types"
|
||||
"github.com/netbirdio/netbird/management/server/users"
|
||||
proxyauth "github.com/netbirdio/netbird/proxy/auth"
|
||||
@@ -505,7 +505,6 @@ func (s *ProxyServiceServer) registerProxyConnection(ctx context.Context, params
|
||||
SupportsCustomPorts: c.SupportsCustomPorts,
|
||||
RequireSubdomain: c.RequireSubdomain,
|
||||
SupportsCrowdsec: c.SupportsCrowdsec,
|
||||
SupportsAppsec: c.SupportsAppsec,
|
||||
Private: c.Private,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2259,7 +2259,7 @@ func (s *SqlStore) getPostureChecks(ctx context.Context, accountID string) ([]*p
|
||||
}
|
||||
|
||||
func (s *SqlStore) getServices(ctx context.Context, accountID string) ([]*rpservice.Service, error) {
|
||||
const serviceQuery = `SELECT id, account_id, name, domain, enabled, auth, restrictions,
|
||||
const serviceQuery = `SELECT id, account_id, name, domain, enabled, auth,
|
||||
meta_created_at, meta_certificate_issued_at, meta_status, proxy_cluster,
|
||||
pass_host_header, rewrite_redirects, session_private_key, session_public_key,
|
||||
mode, listen_port, port_auto_assigned, source, source_peer, terminated,
|
||||
@@ -2278,7 +2278,6 @@ func (s *SqlStore) getServices(ctx context.Context, accountID string) ([]*rpserv
|
||||
services, err := pgx.CollectRows(serviceRows, func(row pgx.CollectableRow) (*rpservice.Service, error) {
|
||||
var s rpservice.Service
|
||||
var auth []byte
|
||||
var restrictions []byte
|
||||
var accessGroups []byte
|
||||
var createdAt, certIssuedAt sql.NullTime
|
||||
var status, proxyCluster, sessionPrivateKey, sessionPublicKey sql.NullString
|
||||
@@ -2292,7 +2291,6 @@ func (s *SqlStore) getServices(ctx context.Context, accountID string) ([]*rpserv
|
||||
&s.Domain,
|
||||
&s.Enabled,
|
||||
&auth,
|
||||
&restrictions,
|
||||
&createdAt,
|
||||
&certIssuedAt,
|
||||
&status,
|
||||
@@ -2320,12 +2318,6 @@ func (s *SqlStore) getServices(ctx context.Context, accountID string) ([]*rpserv
|
||||
}
|
||||
}
|
||||
|
||||
if len(restrictions) > 0 {
|
||||
if err := json.Unmarshal(restrictions, &s.Restrictions); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal restrictions: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(accessGroups) > 0 {
|
||||
if err := json.Unmarshal(accessGroups, &s.AccessGroups); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal access_groups: %w", err)
|
||||
@@ -6365,7 +6357,6 @@ var validCapabilityColumns = map[string]struct{}{
|
||||
"supports_custom_ports": {},
|
||||
"require_subdomain": {},
|
||||
"supports_crowdsec": {},
|
||||
"supports_appsec": {},
|
||||
"private": {},
|
||||
}
|
||||
|
||||
@@ -6396,14 +6387,6 @@ func (s *SqlStore) GetClusterSupportsCrowdSec(ctx context.Context, clusterAddr s
|
||||
return s.getClusterUnanimousCapability(ctx, clusterAddr, "supports_crowdsec")
|
||||
}
|
||||
|
||||
// GetClusterSupportsAppSec returns whether all active proxies in the cluster
|
||||
// have a CrowdSec AppSec endpoint configured. Returns nil when no proxy
|
||||
// reported the capability. Unanimous for the same reason as CrowdSec: a single
|
||||
// proxy without AppSec would let requests through uninspected.
|
||||
func (s *SqlStore) GetClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool {
|
||||
return s.getClusterUnanimousCapability(ctx, clusterAddr, "supports_appsec")
|
||||
}
|
||||
|
||||
// getClusterUnanimousCapability returns an aggregated boolean capability
|
||||
// requiring all active proxies in the cluster to report true.
|
||||
func (s *SqlStore) getClusterUnanimousCapability(ctx context.Context, clusterAddr, column string) *bool {
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/proxy"
|
||||
)
|
||||
|
||||
// Capabilities travel proxy → gRPC → embedded gorm columns → aggregation → API.
|
||||
// A field dropped at any of those hops reads as "capability absent", which is
|
||||
// indistinguishable from a proxy that never reported it: the dashboard simply
|
||||
// hides the feature and nothing fails. These assertions cover the persistence
|
||||
// and aggregation hops.
|
||||
func TestSqlStore_ClusterCapabilityAggregation(t *testing.T) {
|
||||
if os.Getenv("CI") == "true" && (runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
|
||||
t.Skip("skip CI tests on darwin and windows")
|
||||
}
|
||||
|
||||
yes, no := true, false
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
reported []*bool // one entry per connected proxy in the cluster
|
||||
wantAppSec *bool
|
||||
wantAssertion string
|
||||
}{
|
||||
{
|
||||
name: "unreported stays unknown",
|
||||
reported: []*bool{nil},
|
||||
wantAppSec: nil,
|
||||
wantAssertion: "an unreported capability must not read as false",
|
||||
},
|
||||
{
|
||||
name: "single proxy reporting true",
|
||||
reported: []*bool{&yes},
|
||||
wantAppSec: &yes,
|
||||
wantAssertion: "a reported capability must survive persistence",
|
||||
},
|
||||
{
|
||||
name: "one proxy without it disables the cluster",
|
||||
reported: []*bool{&yes, &no},
|
||||
wantAppSec: &no,
|
||||
wantAssertion: "capability must be unanimous, so a rolling upgrade cannot leave traffic uninspected",
|
||||
},
|
||||
{
|
||||
name: "one proxy yet to report disables the cluster",
|
||||
reported: []*bool{&yes, nil},
|
||||
wantAppSec: &no,
|
||||
wantAssertion: "a proxy that has not reported must not count as capable",
|
||||
},
|
||||
}
|
||||
|
||||
runTestForAllEngines(t, "", func(t *testing.T, store Store) {
|
||||
ctx := context.Background()
|
||||
for i, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cluster := fmt.Sprintf("cluster-%d.proxy.example", i)
|
||||
for j, reported := range tt.reported {
|
||||
require.NoError(t, store.SaveProxy(ctx, &proxy.Proxy{
|
||||
ID: fmt.Sprintf("proxy-%d-%d", i, j),
|
||||
ClusterAddress: cluster,
|
||||
Status: proxy.StatusConnected,
|
||||
LastSeen: time.Now(),
|
||||
Capabilities: proxy.Capabilities{SupportsAppsec: reported},
|
||||
}))
|
||||
}
|
||||
|
||||
got := store.GetClusterSupportsAppSec(ctx, cluster)
|
||||
if tt.wantAppSec == nil {
|
||||
assert.Nil(t, got, tt.wantAssertion)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, got, tt.wantAssertion)
|
||||
assert.Equal(t, *tt.wantAppSec, *got, tt.wantAssertion)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// AppSec and IP reputation are separate endpoints, so a cluster can have either
|
||||
// without the other. Gating one on the other would silently disable a feature
|
||||
// the operator configured.
|
||||
func TestSqlStore_ClusterCapabilitiesAreIndependent(t *testing.T) {
|
||||
if os.Getenv("CI") == "true" && (runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
|
||||
t.Skip("skip CI tests on darwin and windows")
|
||||
}
|
||||
|
||||
runTestForAllEngines(t, "", func(t *testing.T, store Store) {
|
||||
ctx := context.Background()
|
||||
const cluster = "independent.proxy.example"
|
||||
yes, no := true, false
|
||||
|
||||
require.NoError(t, store.SaveProxy(ctx, &proxy.Proxy{
|
||||
ID: "proxy-independent",
|
||||
ClusterAddress: cluster,
|
||||
Status: proxy.StatusConnected,
|
||||
LastSeen: time.Now(),
|
||||
Capabilities: proxy.Capabilities{
|
||||
SupportsAppsec: &yes,
|
||||
SupportsCrowdsec: &no,
|
||||
},
|
||||
}))
|
||||
|
||||
appsec := store.GetClusterSupportsAppSec(ctx, cluster)
|
||||
crowdsec := store.GetClusterSupportsCrowdSec(ctx, cluster)
|
||||
require.NotNil(t, appsec)
|
||||
require.NotNil(t, crowdsec)
|
||||
assert.True(t, *appsec, "AppSec must not be gated on CrowdSec")
|
||||
assert.False(t, *crowdsec, "CrowdSec must not be implied by AppSec")
|
||||
})
|
||||
}
|
||||
@@ -44,42 +44,3 @@ func TestSqlStore_GetAccount_PrivateServiceRoundtrip(t *testing.T) {
|
||||
assert.Equal(t, []string{"grp-admins", "grp-ops"}, got.AccessGroups)
|
||||
})
|
||||
}
|
||||
|
||||
// Restrictions are stored as a JSON blob, and the Postgres read path lists
|
||||
// columns by hand: a mode that is not read there is silently off on Postgres
|
||||
// while working in SQLite dev.
|
||||
func TestSqlStore_GetAccount_ServiceRestrictionsRoundtrip(t *testing.T) {
|
||||
if os.Getenv("CI") == "true" && (runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
|
||||
t.Skip("skip CI tests on darwin and windows")
|
||||
}
|
||||
|
||||
runTestForAllEngines(t, "", func(t *testing.T, store Store) {
|
||||
ctx := context.Background()
|
||||
account := newAccountWithId(ctx, "account_svc_restrictions", "testuser", "")
|
||||
require.NoError(t, store.SaveAccount(ctx, account))
|
||||
|
||||
svc := &rpservice.Service{
|
||||
ID: "svc-restrictions",
|
||||
AccountID: account.Id,
|
||||
Name: "restricted-svc",
|
||||
Domain: "restricted.example",
|
||||
Enabled: true,
|
||||
Mode: rpservice.ModeHTTP,
|
||||
Restrictions: rpservice.AccessRestrictions{
|
||||
AllowedCIDRs: []string{"203.0.113.0/24"},
|
||||
CrowdSecMode: "observe",
|
||||
AppSecMode: "enforce",
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.CreateService(ctx, svc))
|
||||
|
||||
loaded, err := store.GetAccount(ctx, account.Id)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, loaded.Services, 1)
|
||||
|
||||
got := loaded.Services[0].Restrictions
|
||||
assert.Equal(t, []string{"203.0.113.0/24"}, got.AllowedCIDRs)
|
||||
assert.Equal(t, "observe", got.CrowdSecMode)
|
||||
assert.Equal(t, "enforce", got.AppSecMode)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -321,7 +321,6 @@ type Store interface {
|
||||
GetClusterSupportsCustomPorts(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterRequireSubdomain(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool
|
||||
GetClusterSupportsPrivate(ctx context.Context, clusterAddr string) *bool
|
||||
CleanupStaleProxies(ctx context.Context, inactivityDuration time.Duration) error
|
||||
GetAllProxies(ctx context.Context) ([]*proxy.Proxy, error)
|
||||
|
||||
@@ -1835,20 +1835,6 @@ func (mr *MockStoreMockRecorder) GetClusterRequireSubdomain(ctx, clusterAddr int
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClusterRequireSubdomain", reflect.TypeOf((*MockStore)(nil).GetClusterRequireSubdomain), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// GetClusterSupportsAppSec mocks base method.
|
||||
func (m *MockStore) GetClusterSupportsAppSec(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetClusterSupportsAppSec", ctx, clusterAddr)
|
||||
ret0, _ := ret[0].(*bool)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// GetClusterSupportsAppSec indicates an expected call of GetClusterSupportsAppSec.
|
||||
func (mr *MockStoreMockRecorder) GetClusterSupportsAppSec(ctx, clusterAddr interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClusterSupportsAppSec", reflect.TypeOf((*MockStore)(nil).GetClusterSupportsAppSec), ctx, clusterAddr)
|
||||
}
|
||||
|
||||
// GetClusterSupportsCrowdSec mocks base method.
|
||||
func (m *MockStore) GetClusterSupportsCrowdSec(ctx context.Context, clusterAddr string) *bool {
|
||||
m.ctrl.T.Helper()
|
||||
|
||||
@@ -79,11 +79,6 @@ var (
|
||||
geoDataDir string
|
||||
crowdsecAPIURL string
|
||||
crowdsecAPIKey string
|
||||
appsecURL string
|
||||
appsecTimeout time.Duration
|
||||
appsecMaxBodyBytes int64
|
||||
captureBudgetBytes int64
|
||||
appsecMaxConcurrent int
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
@@ -130,11 +125,6 @@ func init() {
|
||||
rootCmd.Flags().StringVar(&geoDataDir, "geo-data-dir", envStringOrDefault("NB_PROXY_GEO_DATA_DIR", "/var/lib/netbird/geolocation"), "Directory for the GeoLite2 MMDB file (auto-downloaded if missing)")
|
||||
rootCmd.Flags().StringVar(&crowdsecAPIURL, "crowdsec-api-url", envStringOrDefault("NB_PROXY_CROWDSEC_API_URL", ""), "CrowdSec LAPI URL for IP reputation checks")
|
||||
rootCmd.Flags().StringVar(&crowdsecAPIKey, "crowdsec-api-key", envStringOrDefault("NB_PROXY_CROWDSEC_API_KEY", ""), "CrowdSec bouncer API key")
|
||||
rootCmd.Flags().StringVar(&appsecURL, "crowdsec-appsec-url", envStringOrDefault("NB_PROXY_CROWDSEC_APPSEC_URL", ""), "CrowdSec AppSec (WAF) endpoint for HTTP request inspection, e.g. http://127.0.0.1:7422/ (reuses the bouncer API key)")
|
||||
rootCmd.Flags().DurationVar(&appsecTimeout, "crowdsec-appsec-timeout", envDurationOrDefault("NB_PROXY_CROWDSEC_APPSEC_TIMEOUT", 0), "Timeout for a single AppSec inspection call (0 = 200ms)")
|
||||
rootCmd.Flags().IntVar(&appsecMaxConcurrent, "crowdsec-appsec-max-concurrent", int(envInt64OrDefault("NB_PROXY_CROWDSEC_APPSEC_MAX_CONCURRENT", 0)), "Cap on AppSec inspections in flight; further requests are denied in enforce mode rather than queued (0 = 256, negative = no cap)")
|
||||
rootCmd.Flags().Int64Var(&captureBudgetBytes, "capture-budget-bytes", envInt64OrDefault("NB_PROXY_CAPTURE_BUDGET_BYTES", 0), "Total in-flight request-body buffering across the proxy, shared by AppSec inspection and agent-network capture (0 = 256MiB)")
|
||||
rootCmd.Flags().Int64Var(&appsecMaxBodyBytes, "crowdsec-appsec-max-body-bytes", envInt64OrDefault("NB_PROXY_CROWDSEC_APPSEC_MAX_BODY_BYTES", 0), "Cap on the request body mirrored to AppSec (0 = 64KiB, negative = headers and URI only)")
|
||||
}
|
||||
|
||||
// Execute runs the root command.
|
||||
@@ -228,59 +218,47 @@ func runServer(cmd *cobra.Command, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
srv := proxy.New(ctx, serverConfig(logger, proxyToken, parsedTrustedProxies, perf))
|
||||
srv := proxy.New(ctx, proxy.Config{
|
||||
ListenAddr: addr,
|
||||
Logger: logger,
|
||||
Version: Version,
|
||||
ManagementAddress: mgmtAddr,
|
||||
ProxyURL: proxyDomain,
|
||||
ProxyToken: proxyToken,
|
||||
CertificateDirectory: certDir,
|
||||
CertificateFile: certFile,
|
||||
CertificateKeyFile: certKeyFile,
|
||||
GenerateACMECertificates: acmeCerts,
|
||||
ACMEChallengeAddress: acmeAddr,
|
||||
ACMEDirectory: acmeDir,
|
||||
ACMEEABKID: acmeEABKID,
|
||||
ACMEEABHMACKey: acmeEABHMACKey,
|
||||
ACMEChallengeType: acmeChallengeType,
|
||||
DebugEndpointEnabled: debugEndpoint,
|
||||
DebugEndpointAddress: debugEndpointAddr,
|
||||
HealthAddr: healthAddr,
|
||||
ForwardedProto: forwardedProto,
|
||||
TrustedProxies: parsedTrustedProxies,
|
||||
CertLockMethod: nbacme.CertLockMethod(certLockMethod),
|
||||
WildcardCertDir: wildcardCertDir,
|
||||
WireguardPort: wgPort,
|
||||
Performance: perf,
|
||||
ProxyProtocol: proxyProtocol,
|
||||
PreSharedKey: preSharedKey,
|
||||
SupportsCustomPorts: supportsCustomPorts,
|
||||
RequireSubdomain: requireSubdomain,
|
||||
Private: private,
|
||||
MaxDialTimeout: maxDialTimeout,
|
||||
MaxSessionIdleTimeout: maxSessionIdleTimeout,
|
||||
MappingBatchWatchdog: envDurationOrDefault("NB_PROXY_MAPPING_BATCH_WATCHDOG", 0),
|
||||
GeoDataDir: geoDataDir,
|
||||
CrowdSecAPIURL: crowdsecAPIURL,
|
||||
CrowdSecAPIKey: crowdsecAPIKey,
|
||||
})
|
||||
|
||||
return srv.ListenAndServe(ctx, addr)
|
||||
}
|
||||
|
||||
// serverConfig maps the parsed flags and environment onto the proxy config.
|
||||
// Kept separate from runServer so registering a new flag does not grow the
|
||||
// startup path.
|
||||
func serverConfig(logger *log.Logger, proxyToken string, trustedProxyList *trustedproxy.List, perf embed.Performance) proxy.Config {
|
||||
return proxy.Config{
|
||||
ListenAddr: addr,
|
||||
Logger: logger,
|
||||
Version: Version,
|
||||
ManagementAddress: mgmtAddr,
|
||||
ProxyURL: proxyDomain,
|
||||
ProxyToken: proxyToken,
|
||||
CertificateDirectory: certDir,
|
||||
CertificateFile: certFile,
|
||||
CertificateKeyFile: certKeyFile,
|
||||
GenerateACMECertificates: acmeCerts,
|
||||
ACMEChallengeAddress: acmeAddr,
|
||||
ACMEDirectory: acmeDir,
|
||||
ACMEEABKID: acmeEABKID,
|
||||
ACMEEABHMACKey: acmeEABHMACKey,
|
||||
ACMEChallengeType: acmeChallengeType,
|
||||
DebugEndpointEnabled: debugEndpoint,
|
||||
DebugEndpointAddress: debugEndpointAddr,
|
||||
HealthAddr: healthAddr,
|
||||
ForwardedProto: forwardedProto,
|
||||
TrustedProxies: trustedProxyList,
|
||||
CertLockMethod: nbacme.CertLockMethod(certLockMethod),
|
||||
WildcardCertDir: wildcardCertDir,
|
||||
WireguardPort: wgPort,
|
||||
Performance: perf,
|
||||
ProxyProtocol: proxyProtocol,
|
||||
PreSharedKey: preSharedKey,
|
||||
SupportsCustomPorts: supportsCustomPorts,
|
||||
RequireSubdomain: requireSubdomain,
|
||||
Private: private,
|
||||
MaxDialTimeout: maxDialTimeout,
|
||||
MaxSessionIdleTimeout: maxSessionIdleTimeout,
|
||||
MappingBatchWatchdog: envDurationOrDefault("NB_PROXY_MAPPING_BATCH_WATCHDOG", 0),
|
||||
GeoDataDir: geoDataDir,
|
||||
CrowdSecAPIURL: crowdsecAPIURL,
|
||||
CrowdSecAPIKey: crowdsecAPIKey,
|
||||
CrowdSecAppSecURL: appsecURL,
|
||||
CrowdSecAppSecTimeout: appsecTimeout,
|
||||
CrowdSecAppSecMaxBodyBytes: appsecMaxBodyBytes,
|
||||
CrowdSecAppSecMaxConcurrent: appsecMaxConcurrent,
|
||||
MiddlewareCaptureBudgetBytes: captureBudgetBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func envBoolOrDefault(key string, def bool) bool {
|
||||
v, exists := os.LookupEnv(key)
|
||||
if !exists {
|
||||
@@ -315,19 +293,6 @@ func envUint16OrDefault(key string, def uint16) uint16 {
|
||||
return uint16(parsed)
|
||||
}
|
||||
|
||||
func envInt64OrDefault(key string, def int64) int64 {
|
||||
v, exists := os.LookupEnv(key)
|
||||
if !exists {
|
||||
return def
|
||||
}
|
||||
parsed, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
log.Warnf("parse %s=%q: %v, using default %d", key, v, err, def)
|
||||
return def
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func envDurationOrDefault(key string, def time.Duration) time.Duration {
|
||||
v, exists := os.LookupEnv(key)
|
||||
if !exists {
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
package appsec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// bufferBody reads up to limit+1 bytes from r.Body and always restores r.Body so
|
||||
// the request stays forwardable. oversize reports that the body exceeded limit, in
|
||||
// which case the returned prefix must not be used for inspection: the bytes are
|
||||
// only read so they can be replayed to the backend.
|
||||
func bufferBody(r *http.Request, limit int64) (body []byte, oversize bool, err error) {
|
||||
original := r.Body
|
||||
buf, readErr := io.ReadAll(io.LimitReader(original, limit+1))
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
// Restore what was read so a downstream retry sees a consistent stream,
|
||||
// then surface the failure.
|
||||
r.Body = replay(buf, original)
|
||||
return nil, false, readErr
|
||||
}
|
||||
|
||||
if int64(len(buf)) > limit {
|
||||
r.Body = replay(buf, original)
|
||||
return nil, true, nil
|
||||
}
|
||||
|
||||
// The whole body is buffered, so the original is drained and can be closed.
|
||||
// A close error on a drained read-only body does not invalidate the bytes.
|
||||
_ = original.Close()
|
||||
r.Body = io.NopCloser(bytes.NewReader(buf))
|
||||
// Framing is deliberately left as the client sent it. Rewriting a chunked
|
||||
// request to a fixed Content-Length here would be invisible to the client
|
||||
// but not to the rest of the chain: a later body capture with a smaller cap
|
||||
// sees a known length over its cap and skips capture entirely, where an
|
||||
// unknown length would have given it a truncated prefix. Inspecting a
|
||||
// request must not change what any other layer gets to inspect.
|
||||
return buf, false, nil
|
||||
}
|
||||
|
||||
// replay returns a ReadCloser that yields the already-read prefix followed by
|
||||
// the remainder of the original stream, and closes the original.
|
||||
func replay(prefix []byte, rest io.ReadCloser) io.ReadCloser {
|
||||
return struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: io.MultiReader(bytes.NewReader(prefix), rest),
|
||||
Closer: rest,
|
||||
}
|
||||
}
|
||||
|
||||
// redactedPlaceholder replaces a credential value in the mirrored body. It is
|
||||
// inert for rule matching, and its fixed length leaks nothing about the secret.
|
||||
const redactedPlaceholder = "redacted"
|
||||
|
||||
// redactFormFields returns the body to mirror for a URL-encoded form, with the
|
||||
// values of the named fields replaced. The proxy's own password / PIN login
|
||||
// form posts to the service path itself, so without this the plaintext
|
||||
// credential would reach the Security Engine.
|
||||
//
|
||||
// Only the credential values are removed, never the whole body: dropping the
|
||||
// body outright would let a caller exempt any payload from inspection just by
|
||||
// appending a field named "password". Everything else in the form stays
|
||||
// inspectable, which is the point.
|
||||
//
|
||||
// Returns body unchanged when it is not a URL-encoded form or carries none of
|
||||
// the fields.
|
||||
//
|
||||
// Substitution happens on the raw bytes rather than by re-encoding parsed
|
||||
// values. Re-encoding would drop pairs that url.ParseQuery rejects, so a
|
||||
// payload hidden in a malformed pair alongside a credential-named field would
|
||||
// never be inspected while a tolerant backend parser still acted on it. Working
|
||||
// byte-wise also avoids reordering keys and normalizing escapes, so the engine
|
||||
// sees the same bytes the backend will.
|
||||
//
|
||||
// Field names match case-sensitively, on purpose: the caller passes the exact
|
||||
// names the login handler reads via r.FormValue, and that lookup is itself
|
||||
// case-sensitive. A "Password" field is therefore never a credential as far as
|
||||
// the proxy is concerned, and redacting it would only blind the WAF to a value
|
||||
// the proxy does not own.
|
||||
func redactFormFields(contentType string, body []byte, fields []string) []byte {
|
||||
if len(fields) == 0 || len(body) == 0 {
|
||||
return body
|
||||
}
|
||||
media, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || media != "application/x-www-form-urlencoded" {
|
||||
return body
|
||||
}
|
||||
return redactURLEncoded(body, fields)
|
||||
}
|
||||
|
||||
// redactURLEncoded replaces the values of the named keys in a URL-encoded
|
||||
// key/value sequence, the shared syntax of a query string and a form body.
|
||||
func redactURLEncoded(raw []byte, fields []string) []byte {
|
||||
// Split on "&" only, matching how Go's form parser delimits pairs.
|
||||
segments := bytes.Split(raw, []byte("&"))
|
||||
redacted := false
|
||||
for i, segment := range segments {
|
||||
rawKey, _, hasValue := bytes.Cut(segment, []byte("="))
|
||||
if !hasValue {
|
||||
continue
|
||||
}
|
||||
// Compare the decoded name, so an escaped spelling of the field
|
||||
// ("pass%77ord") is redacted too: the reader decodes before looking it
|
||||
// up. A key that fails to decode never reaches that reader either,
|
||||
// since the parser drops the pair.
|
||||
name, err := url.QueryUnescape(string(rawKey))
|
||||
if err != nil || !slices.Contains(fields, name) {
|
||||
continue
|
||||
}
|
||||
// Keep the key bytes as sent and replace only the value. Assigning a
|
||||
// fresh slice leaves raw untouched, which matters: the caller restored
|
||||
// the request body from the same buffer.
|
||||
segments[i] = []byte(string(rawKey) + "=" + redactedPlaceholder)
|
||||
redacted = true
|
||||
}
|
||||
if !redacted {
|
||||
return raw
|
||||
}
|
||||
return bytes.Join(segments, []byte("&"))
|
||||
}
|
||||
|
||||
// redactQuery replaces the values of the named query parameters in a raw query
|
||||
// string, leaving every other byte as sent.
|
||||
func redactQuery(rawQuery string, params []string) string {
|
||||
if len(params) == 0 || rawQuery == "" {
|
||||
return rawQuery
|
||||
}
|
||||
return string(redactURLEncoded([]byte(rawQuery), params))
|
||||
}
|
||||
|
||||
// redactCookieHeader replaces the values of the named cookies in a Cookie
|
||||
// header, keeping the others intact: cookies are a zone WAF rules match on, so
|
||||
// dropping the whole header would cost real coverage.
|
||||
func redactCookieHeader(value string, names []string) string {
|
||||
if len(names) == 0 || value == "" {
|
||||
return value
|
||||
}
|
||||
parts := strings.Split(value, ";")
|
||||
redacted := false
|
||||
for i, part := range parts {
|
||||
name, _, hasValue := strings.Cut(part, "=")
|
||||
if !hasValue {
|
||||
continue
|
||||
}
|
||||
// Cookie names are case-sensitive and are not percent-decoded.
|
||||
if !slices.Contains(names, strings.TrimSpace(name)) {
|
||||
continue
|
||||
}
|
||||
parts[i] = name + "=" + redactedPlaceholder
|
||||
redacted = true
|
||||
}
|
||||
if !redacted {
|
||||
return value
|
||||
}
|
||||
return strings.Join(parts, ";")
|
||||
}
|
||||
@@ -1,571 +0,0 @@
|
||||
// Package appsec implements the CrowdSec AppSec (WAF) side of the remediation
|
||||
// component protocol: each inspected HTTP request is mirrored to the Security
|
||||
// Engine's AppSec endpoint, which replies with an allow / ban / captcha verdict
|
||||
// for that request.
|
||||
//
|
||||
// This is a separate endpoint from the LAPI decision stream used by the
|
||||
// crowdsec package: LAPI answers "is this IP known bad", AppSec answers "is
|
||||
// this request an attack". The two are configured and enabled independently.
|
||||
package appsec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/netbirdio/netbird/proxy/internal/netutil"
|
||||
"github.com/netbirdio/netbird/proxy/internal/restrict"
|
||||
)
|
||||
|
||||
// Header names the AppSec component reads off the mirrored request. IP, URI and
|
||||
// Verb are mandatory: the engine answers 500 when any of them is missing.
|
||||
const (
|
||||
headerAPIKey = "X-Crowdsec-Appsec-Api-Key" //nolint:gosec // G101: a header name, not a credential
|
||||
headerIP = "X-Crowdsec-Appsec-Ip"
|
||||
headerURI = "X-Crowdsec-Appsec-Uri"
|
||||
headerVerb = "X-Crowdsec-Appsec-Verb"
|
||||
headerHost = "X-Crowdsec-Appsec-Host"
|
||||
headerUserAgent = "X-Crowdsec-Appsec-User-Agent"
|
||||
headerHTTPVersion = "X-Crowdsec-Appsec-Http-Version"
|
||||
headerTransactionID = "X-Crowdsec-Appsec-Transaction-Id"
|
||||
)
|
||||
|
||||
// headerPrefix covers every protocol header. Any client-supplied header in this
|
||||
// namespace is dropped before forwarding so a caller cannot influence the
|
||||
// engine's view of its own address, or replay an API key.
|
||||
const headerPrefix = "X-Crowdsec-Appsec-"
|
||||
|
||||
// Remediation actions the engine can return.
|
||||
const (
|
||||
actionAllow = "allow"
|
||||
actionBan = "ban"
|
||||
actionCaptcha = "captcha"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultTimeout matches the 200ms budget CrowdSec's remediation component
|
||||
// spec sets for the blocking AppSec call.
|
||||
DefaultTimeout = 200 * time.Millisecond
|
||||
// MinTimeout and MaxTimeout bound the configured inspection timeout.
|
||||
// Inspection is synchronous, so the upper bound is what keeps a
|
||||
// mis-set value from parking every request to an inspected service on a
|
||||
// slow engine; the lower bound keeps the call from timing out before the
|
||||
// engine can realistically answer. Mirrors the per-middleware bounds the
|
||||
// proxy already applies to in-path calls.
|
||||
MinTimeout = 10 * time.Millisecond
|
||||
MaxTimeout = 5 * time.Second
|
||||
// DefaultMaxBodyBytes caps the request body mirrored to the engine.
|
||||
// Requests with a larger body are inspected on headers and URI only.
|
||||
DefaultMaxBodyBytes int64 = 64 << 10
|
||||
// DefaultMaxConcurrent bounds inspections in flight toward the engine. The
|
||||
// point is to fail fast instead of parking a goroutine per request for the
|
||||
// whole timeout once the engine is saturated: a slow engine otherwise turns
|
||||
// a traffic burst into a pile of waiters that all time out anyway. Sized so
|
||||
// a healthy engine (single-digit milliseconds per call) never reaches it.
|
||||
DefaultMaxConcurrent = 256
|
||||
// MaxConcurrentLimit is the ceiling for that bound.
|
||||
MaxConcurrentLimit = 4096
|
||||
// MaxBodyBytesLimit is the ceiling for that cap. A single request can hold
|
||||
// this much in memory; the shared Budget is what bounds the total across
|
||||
// concurrent requests. Matches the proxy-wide body-capture ceiling.
|
||||
MaxBodyBytesLimit int64 = 8 << 20
|
||||
// maxResponseBytes bounds how much of a verdict response is read. The
|
||||
// engine answers with a two-field JSON object, so anything beyond this is
|
||||
// not a response we can act on.
|
||||
maxResponseBytes int64 = 4 << 10
|
||||
)
|
||||
|
||||
// Reasons the request body was not mirrored. Reported so an access-log reader
|
||||
// can distinguish "inspected and clean" from "never inspected", and so an
|
||||
// oversize opt-out is visible rather than silent.
|
||||
const (
|
||||
BypassOversize = "oversize"
|
||||
BypassUpgrade = "upgrade"
|
||||
BypassDisabled = "disabled"
|
||||
BypassBudget = "budget_exhausted"
|
||||
)
|
||||
|
||||
// ErrUnavailable reports that the engine could not produce a verdict: the call
|
||||
// failed, timed out, or the engine rejected it (401 bad key, 500 malformed).
|
||||
// Distinguished from a block verdict so the caller can apply the per-service
|
||||
// mode: enforce fails closed, observe allows.
|
||||
var ErrUnavailable = errors.New("appsec engine unavailable")
|
||||
|
||||
// Config configures a Client.
|
||||
type Config struct {
|
||||
// URL is the AppSec endpoint, e.g. http://127.0.0.1:7422/.
|
||||
URL string
|
||||
// APIKey is the CrowdSec bouncer API key. The AppSec component validates it
|
||||
// against LAPI, so the same key used for the decision stream works here.
|
||||
APIKey string
|
||||
// Timeout bounds a single inspection call. Zero means DefaultTimeout.
|
||||
Timeout time.Duration
|
||||
// MaxBodyBytes caps the mirrored request body. Zero means
|
||||
// DefaultMaxBodyBytes; negative disables body forwarding entirely.
|
||||
MaxBodyBytes int64
|
||||
// MaxConcurrent bounds inspections in flight toward the engine. Zero means
|
||||
// DefaultMaxConcurrent; negative disables the bound.
|
||||
MaxConcurrent int
|
||||
// Budget bounds the total body buffering in flight across all inspected
|
||||
// requests. Nil disables that ceiling, which leaves the worst case at
|
||||
// MaxBodyBytes times the concurrent request count; callers serving
|
||||
// untrusted traffic should share the proxy-wide capture budget here.
|
||||
Budget Budget
|
||||
Logger *log.Entry
|
||||
}
|
||||
|
||||
// Budget is the shared allowance for in-flight body buffering. Acquire reports
|
||||
// whether n bytes could be reserved; every successful Acquire is matched by a
|
||||
// Release of the same n. Satisfied by the proxy's capture budget, so AppSec and
|
||||
// the middleware body tap draw down one pool rather than two independent ones.
|
||||
type Budget interface {
|
||||
Acquire(n int64) bool
|
||||
Release(n int64)
|
||||
}
|
||||
|
||||
// Client mirrors HTTP requests to a CrowdSec AppSec endpoint. It holds no
|
||||
// per-service state and is safe for concurrent use.
|
||||
type Client struct {
|
||||
url string
|
||||
apiKey string
|
||||
maxBodyBytes int64
|
||||
// sem bounds in-flight inspections. Nil when the bound is disabled.
|
||||
sem chan struct{}
|
||||
budget Budget
|
||||
http *http.Client
|
||||
logger *log.Entry
|
||||
}
|
||||
|
||||
// New validates the config and returns a Client. The endpoint is not contacted
|
||||
// here: the engine may come up after the proxy.
|
||||
func New(cfg Config) (*Client, error) {
|
||||
if cfg.URL == "" {
|
||||
return nil, errors.New("appsec url is empty")
|
||||
}
|
||||
if cfg.APIKey == "" {
|
||||
return nil, errors.New("appsec api key is empty")
|
||||
}
|
||||
parsed, err := url.Parse(cfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse appsec url: %w", err)
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return nil, fmt.Errorf("appsec url scheme %q is not http(s)", parsed.Scheme)
|
||||
}
|
||||
if parsed.Host == "" {
|
||||
return nil, errors.New("appsec url has no host")
|
||||
}
|
||||
|
||||
logger := cfg.Logger
|
||||
if logger == nil {
|
||||
logger = log.NewEntry(log.StandardLogger())
|
||||
}
|
||||
|
||||
timeout := cfg.Timeout
|
||||
switch {
|
||||
case timeout <= 0:
|
||||
timeout = DefaultTimeout
|
||||
case timeout < MinTimeout:
|
||||
logger.Warnf("appsec timeout %s is below the minimum, using %s", timeout, MinTimeout)
|
||||
timeout = MinTimeout
|
||||
case timeout > MaxTimeout:
|
||||
logger.Warnf("appsec timeout %s exceeds the maximum, using %s", timeout, MaxTimeout)
|
||||
timeout = MaxTimeout
|
||||
}
|
||||
|
||||
// A negative cap is meaningful: forward no body at all.
|
||||
maxBody := cfg.MaxBodyBytes
|
||||
switch {
|
||||
case maxBody == 0:
|
||||
maxBody = DefaultMaxBodyBytes
|
||||
case maxBody > MaxBodyBytesLimit:
|
||||
logger.Warnf("appsec max body %d exceeds the maximum, using %d", maxBody, MaxBodyBytesLimit)
|
||||
maxBody = MaxBodyBytesLimit
|
||||
}
|
||||
|
||||
maxConcurrent := cfg.MaxConcurrent
|
||||
switch {
|
||||
case maxConcurrent == 0:
|
||||
maxConcurrent = DefaultMaxConcurrent
|
||||
case maxConcurrent > MaxConcurrentLimit:
|
||||
logger.Warnf("appsec max concurrent %d exceeds the maximum, using %d", maxConcurrent, MaxConcurrentLimit)
|
||||
maxConcurrent = MaxConcurrentLimit
|
||||
}
|
||||
var sem chan struct{}
|
||||
if maxConcurrent > 0 {
|
||||
sem = make(chan struct{}, maxConcurrent)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
url: cfg.URL,
|
||||
apiKey: cfg.APIKey,
|
||||
maxBodyBytes: maxBody,
|
||||
sem: sem,
|
||||
budget: cfg.Budget,
|
||||
logger: logger,
|
||||
http: &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Request is one inspection request.
|
||||
type Request struct {
|
||||
// HTTP is the in-flight client request. Inspect buffers and restores its
|
||||
// body, so the request stays forwardable afterwards.
|
||||
HTTP *http.Request
|
||||
// ClientIP is the resolved client address (after trusted-proxy handling).
|
||||
ClientIP netip.Addr
|
||||
// TransactionID correlates the engine's alert with the proxy's access log
|
||||
// entry. Empty lets the engine generate its own UUID.
|
||||
TransactionID string
|
||||
// RedactBodyFields lists form fields whose values are replaced before the
|
||||
// body is mirrored. Used to keep credentials submitted to the proxy's own
|
||||
// login form out of the engine while still inspecting the rest.
|
||||
RedactBodyFields []string
|
||||
// RedactHeaders, RedactCookies and RedactQueryParams name the credentials
|
||||
// the proxy already withholds from backends: the header-auth values, its
|
||||
// session cookie, and the OIDC session token. The engine logs and alerts on
|
||||
// what it inspects, so mirroring them there would reintroduce the leak the
|
||||
// upstream strippers exist to prevent. Only the values are replaced, so the
|
||||
// surrounding headers, cookies and query stay inspectable.
|
||||
RedactHeaders []string
|
||||
RedactCookies []string
|
||||
RedactQueryParams []string
|
||||
}
|
||||
|
||||
// Result is the outcome of an inspection.
|
||||
type Result struct {
|
||||
Verdict restrict.Verdict
|
||||
// BodyBypass names why the request body was not mirrored, empty when it
|
||||
// was (or when the request had none). The engine still saw the headers and
|
||||
// URI, so this is a coverage note, not a failure.
|
||||
BodyBypass string
|
||||
// Release returns the buffered body's budget reservation. Never nil, so it
|
||||
// is always safe to defer. It must run only once the request has been
|
||||
// served, not when Inspect returns: the buffer stays alive as r.Body for
|
||||
// the backend to read, so releasing earlier would let the budget admit
|
||||
// buffering that is still resident.
|
||||
Release func()
|
||||
}
|
||||
|
||||
// noopRelease is the Release for inspections that reserved no budget.
|
||||
func noopRelease() {}
|
||||
|
||||
// Inspect mirrors r to the AppSec engine and returns its verdict. A nil error
|
||||
// with restrict.Allow means the request passed. On failure it returns
|
||||
// DenyAppSecUnavailable wrapped with ErrUnavailable; the caller decides whether
|
||||
// that blocks, based on the per-service mode.
|
||||
func (c *Client) Inspect(ctx context.Context, req Request) (Result, error) {
|
||||
if c == nil {
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, Release: noopRelease}, ErrUnavailable
|
||||
}
|
||||
if req.HTTP == nil {
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, Release: noopRelease}, fmt.Errorf("%w: nil request", ErrUnavailable)
|
||||
}
|
||||
|
||||
// release is carried out to the caller rather than deferred here: the
|
||||
// buffered body outlives this call as r.Body.
|
||||
if !c.acquireSlot() {
|
||||
// Deny rather than wave through: a flood must not be a way to switch
|
||||
// inspection off. Enforce blocks, observe logs and allows, exactly as
|
||||
// for an unreachable engine.
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, Release: noopRelease},
|
||||
fmt.Errorf("%w: %d inspections already in flight", ErrUnavailable, cap(c.sem))
|
||||
}
|
||||
defer c.releaseSlot()
|
||||
|
||||
body, bypass, release, err := c.readBody(req)
|
||||
if err != nil {
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, Release: release}, fmt.Errorf("%w: read body: %w", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
outbound, err := c.buildRequest(ctx, req, body)
|
||||
if err != nil {
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, BodyBypass: bypass, Release: release}, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
resp, err := c.http.Do(outbound)
|
||||
if err != nil {
|
||||
return Result{Verdict: restrict.DenyAppSecUnavailable, BodyBypass: bypass, Release: release}, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
defer func() {
|
||||
// Drain before closing. net/http only returns a connection to the idle
|
||||
// pool once its body is read to EOF; closing with bytes outstanding
|
||||
// discards it. Every verdict carries a JSON body, so skipping this
|
||||
// would cost a fresh handshake per inspected request, inside the
|
||||
// timeout budget.
|
||||
if _, err := io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBytes)); err != nil {
|
||||
c.logger.Tracef("drain appsec response body: %v", err)
|
||||
}
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
c.logger.Tracef("close appsec response body: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
verdict, err := c.verdict(resp)
|
||||
return Result{Verdict: verdict, BodyBypass: bypass, Release: release}, err
|
||||
}
|
||||
|
||||
// acquireSlot takes an in-flight slot without blocking, reporting false when
|
||||
// the engine is already at capacity.
|
||||
func (c *Client) acquireSlot() bool {
|
||||
if c.sem == nil {
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case c.sem <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// releaseSlot returns the slot. Scoped to the engine call, not the request: the
|
||||
// buffered body outlives the call but the engine's attention does not.
|
||||
func (c *Client) releaseSlot() {
|
||||
if c.sem == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-c.sem:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// readBody buffers the body so it can be mirrored, always restoring it on the
|
||||
// original request. Returns nil when there is no body to forward: no body at
|
||||
// all, an upgrade request, or a body over the cap. A login form is forwarded
|
||||
// with its credential values redacted rather than suppressed.
|
||||
// release is never nil; the caller invokes it once the request has been served.
|
||||
func (c *Client) readBody(req Request) (body []byte, bypass string, release func(), err error) {
|
||||
r := req.HTTP
|
||||
if r.Body == nil || r.Body == http.NoBody {
|
||||
return nil, "", noopRelease, nil
|
||||
}
|
||||
if c.maxBodyBytes < 0 {
|
||||
return nil, BypassDisabled, noopRelease, nil
|
||||
}
|
||||
// A genuine upgrade request carries no body to inspect (net/http hands us
|
||||
// http.NoBody, caught above); the hijacked stream is reached through
|
||||
// Hijacker, never r.Body. The test has to be the forwarder's own, because a
|
||||
// looser one would skip inspection for requests the forwarder still
|
||||
// delivers to the backend with their body intact.
|
||||
if netutil.IsUpgradeRequest(r.Header) {
|
||||
return nil, BypassUpgrade, noopRelease, nil
|
||||
}
|
||||
// A Content-Length over the cap is known to be too large before reading.
|
||||
if r.ContentLength > c.maxBodyBytes {
|
||||
return nil, BypassOversize, noopRelease, nil
|
||||
}
|
||||
|
||||
// Reserve the whole cap rather than the eventual length: the reservation
|
||||
// has to be made before the body is read, and until then the only bound
|
||||
// known is the cap. Skipping inspection when the pool is drained keeps a
|
||||
// burst of large bodies from being an out-of-memory lever; the bypass is
|
||||
// recorded so the gap in coverage is visible.
|
||||
release = noopRelease
|
||||
if c.budget != nil {
|
||||
if !c.budget.Acquire(c.maxBodyBytes) {
|
||||
c.logger.Debugf("appsec buffer budget exhausted, inspecting headers and URI only")
|
||||
return nil, BypassBudget, noopRelease, nil
|
||||
}
|
||||
var once sync.Once
|
||||
release = func() { once.Do(func() { c.budget.Release(c.maxBodyBytes) }) }
|
||||
}
|
||||
|
||||
buffered, oversize, err := bufferBody(r, c.maxBodyBytes)
|
||||
if err != nil {
|
||||
// bufferBody restored r.Body from the bytes it did read, so the
|
||||
// reservation stays held until the caller releases it.
|
||||
return nil, "", release, err
|
||||
}
|
||||
// An oversize body was only partially read: a truncated prefix changes the
|
||||
// engine's verdict in both directions, so inspect headers and URI only.
|
||||
if oversize {
|
||||
return nil, BypassOversize, release, nil
|
||||
}
|
||||
return redactFormFields(r.Header.Get("Content-Type"), buffered, req.RedactBodyFields), "", release, nil
|
||||
}
|
||||
|
||||
// buildRequest assembles the mirrored request. Per the protocol it is a GET
|
||||
// when there is no body and a POST otherwise; bytes.Reader gives the outbound
|
||||
// request an accurate Content-Length, which the engine relies on to read the
|
||||
// body at all.
|
||||
func (c *Client) buildRequest(ctx context.Context, req Request, body []byte) (*http.Request, error) {
|
||||
method := http.MethodGet
|
||||
var payload io.Reader
|
||||
if len(body) > 0 {
|
||||
method = http.MethodPost
|
||||
payload = bytes.NewReader(body)
|
||||
}
|
||||
|
||||
outbound, err := http.NewRequestWithContext(ctx, method, c.url, payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build appsec request: %w", err)
|
||||
}
|
||||
|
||||
r := req.HTTP
|
||||
copyInspectableHeaders(outbound.Header, r.Header)
|
||||
redactSecrets(outbound.Header, req)
|
||||
|
||||
outbound.Header.Set(headerAPIKey, c.apiKey)
|
||||
outbound.Header.Set(headerIP, req.ClientIP.Unmap().String())
|
||||
outbound.Header.Set(headerURI, mirroredURI(r.URL, req.RedactQueryParams))
|
||||
outbound.Header.Set(headerVerb, r.Method)
|
||||
outbound.Header.Set(headerHost, r.Host)
|
||||
if ua := r.UserAgent(); ua != "" {
|
||||
outbound.Header.Set(headerUserAgent, ua)
|
||||
}
|
||||
outbound.Header.Set(headerHTTPVersion, httpVersion(r))
|
||||
if req.TransactionID != "" {
|
||||
outbound.Header.Set(headerTransactionID, req.TransactionID)
|
||||
}
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
// verdict maps the engine's response to a restrict.Verdict. 200 is a pass and
|
||||
// 401/500 are engine-side failures; every other status carries a remediation in
|
||||
// the body. The blocked status code is operator-configurable
|
||||
// (blocked_http_code), so the action field decides, not the status.
|
||||
func (c *Client) verdict(resp *http.Response) (restrict.Verdict, error) {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusUnauthorized:
|
||||
return restrict.DenyAppSecUnavailable, fmt.Errorf("%w: rejected api key", ErrUnavailable)
|
||||
case http.StatusInternalServerError:
|
||||
return restrict.DenyAppSecUnavailable, fmt.Errorf("%w: engine error", ErrUnavailable)
|
||||
}
|
||||
|
||||
// Every status, 200 included, has to carry a decodable remediation. Taking a
|
||||
// bare 200 as a pass would mean a URL pointing at anything that answers 200
|
||||
// (a health endpoint, a load balancer's default page) silently allows every
|
||||
// request while the service reports itself as enforcing.
|
||||
|
||||
var decoded struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxResponseBytes)).Decode(&decoded); err != nil {
|
||||
// Every remediation carries a decodable action, so a response without
|
||||
// one is not a verdict: most often the URL points at something that is
|
||||
// not the AppSec endpoint, which answers 404 with HTML. Reported as
|
||||
// unavailable rather than a ban so the access log names the real fault
|
||||
// instead of sending an operator hunting for a rule that never fired.
|
||||
// Enforce still blocks either way; only the recorded reason differs.
|
||||
return restrict.DenyAppSecUnavailable, fmt.Errorf("%w: undecodable response (status %d): %w", ErrUnavailable, resp.StatusCode, err)
|
||||
}
|
||||
|
||||
switch decoded.Action {
|
||||
case actionAllow:
|
||||
return restrict.Allow, nil
|
||||
case actionCaptcha:
|
||||
return restrict.DenyAppSecCaptcha, nil
|
||||
case actionBan:
|
||||
return restrict.DenyAppSecBan, nil
|
||||
case "":
|
||||
// Decodable JSON without a remediation is not a verdict either: the
|
||||
// endpoint answered, but not as the engine. Same reasoning as an
|
||||
// undecodable body, and the same reason to point at configuration.
|
||||
return restrict.DenyAppSecUnavailable,
|
||||
fmt.Errorf("%w: response carried no remediation (status %d)", ErrUnavailable, resp.StatusCode)
|
||||
default:
|
||||
// A remediation we do not implement still means the engine flagged the
|
||||
// request, so deny.
|
||||
c.logger.Debugf("unknown appsec action %q (status %d), treating as ban", decoded.Action, resp.StatusCode)
|
||||
return restrict.DenyAppSecBan, nil
|
||||
}
|
||||
}
|
||||
|
||||
// copyInspectableHeaders copies the client's headers, which are what the WAF
|
||||
// rules actually match on, dropping hop-by-hop headers that describe the
|
||||
// proxy-to-engine connection rather than the client request, and any header in
|
||||
// the AppSec protocol namespace.
|
||||
func copyInspectableHeaders(dst, src http.Header) {
|
||||
for name, values := range src {
|
||||
if hopByHopHeaders[http.CanonicalHeaderKey(name)] {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(http.CanonicalHeaderKey(name), headerPrefix) {
|
||||
continue
|
||||
}
|
||||
dst[http.CanonicalHeaderKey(name)] = append([]string(nil), values...)
|
||||
}
|
||||
// Content-Length describes the mirrored payload, not the client's: net/http
|
||||
// sets it from the body we actually attach. Content-Type is kept either way
|
||||
// so rules matching on it still fire when the body was not forwarded.
|
||||
dst.Del("Content-Length")
|
||||
}
|
||||
|
||||
// redactSecrets replaces the credential values the proxy withholds from
|
||||
// backends, so the mirrored copy does not carry them either.
|
||||
func redactSecrets(dst http.Header, req Request) {
|
||||
for _, name := range req.RedactHeaders {
|
||||
// Presence, not Get: a header whose first value is empty still carries
|
||||
// its later values to the engine, while the upstream strip deletes the
|
||||
// name outright. Set collapses every value into the placeholder.
|
||||
if len(dst.Values(name)) > 0 {
|
||||
dst.Set(name, redactedPlaceholder)
|
||||
}
|
||||
}
|
||||
// Every Cookie line, not just the first: a client may send several, and Get
|
||||
// would leave the session cookie in any later one mirrored in the clear.
|
||||
if cookies := dst.Values("Cookie"); len(cookies) > 0 {
|
||||
redacted := make([]string, len(cookies))
|
||||
for i, cookie := range cookies {
|
||||
redacted[i] = redactCookieHeader(cookie, req.RedactCookies)
|
||||
}
|
||||
dst["Cookie"] = redacted
|
||||
}
|
||||
}
|
||||
|
||||
// mirroredURI renders the request target for the URI header, with the named
|
||||
// query parameter values replaced.
|
||||
func mirroredURI(u *url.URL, redactParams []string) string {
|
||||
uri := u.RequestURI()
|
||||
if u.RawQuery == "" || len(redactParams) == 0 {
|
||||
return uri
|
||||
}
|
||||
redacted := redactQuery(u.RawQuery, redactParams)
|
||||
if redacted == u.RawQuery {
|
||||
return uri
|
||||
}
|
||||
// RequestURI is path + "?" + RawQuery; swap only the query part so the
|
||||
// path keeps its original encoding.
|
||||
return strings.TrimSuffix(uri, u.RawQuery) + redacted
|
||||
}
|
||||
|
||||
var hopByHopHeaders = map[string]bool{
|
||||
"Connection": true,
|
||||
"Keep-Alive": true,
|
||||
"Proxy-Authenticate": true,
|
||||
"Proxy-Authorization": true,
|
||||
"Proxy-Connection": true,
|
||||
"Te": true,
|
||||
"Trailer": true,
|
||||
"Transfer-Encoding": true,
|
||||
"Upgrade": true,
|
||||
}
|
||||
|
||||
// httpVersion renders the two-digit form the engine parses ("11", "20").
|
||||
func httpVersion(r *http.Request) string {
|
||||
major, minor := r.ProtoMajor, r.ProtoMinor
|
||||
if major < 0 || major > 9 || minor < 0 || minor > 9 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d%d", major, minor)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,306 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/proxy/internal/appsec"
|
||||
"github.com/netbirdio/netbird/proxy/internal/proxy"
|
||||
"github.com/netbirdio/netbird/proxy/internal/restrict"
|
||||
"github.com/netbirdio/netbird/proxy/internal/types"
|
||||
)
|
||||
|
||||
// appsecEngine is a stub AppSec component returning a fixed remediation.
|
||||
func appsecEngine(t *testing.T, status int, body string) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
if body != "" {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// serveWithAppSec runs a request through the middleware for a domain configured
|
||||
// with the given AppSec mode, returning the response and the captured metadata.
|
||||
func serveWithAppSec(t *testing.T, mode restrict.AppSecMode, client *appsec.Client, r *http.Request) (*httptest.ResponseRecorder, map[string]string, bool) {
|
||||
t.Helper()
|
||||
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
mw.SetAppSec(client)
|
||||
require.NoError(t, mw.AddDomain("svc.example.com", DomainSettings{
|
||||
AccountID: types.AccountID("acct-1"),
|
||||
ServiceID: types.ServiceID("svc-1"),
|
||||
AppSecMode: mode,
|
||||
}))
|
||||
|
||||
reached := false
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
reached = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
cd := proxy.NewCapturedData("req-1")
|
||||
r = r.WithContext(proxy.WithCapturedData(r.Context(), cd))
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
|
||||
return rec, cd.GetMetadata(), reached
|
||||
}
|
||||
|
||||
func appsecRequest() *http.Request {
|
||||
r := httptest.NewRequest(http.MethodGet, "http://svc.example.com/?x=/etc/passwd", nil)
|
||||
r.Host = "svc.example.com"
|
||||
r.RemoteAddr = "203.0.113.7:44444"
|
||||
return r
|
||||
}
|
||||
|
||||
func TestCheckAppSec_EnforceBlocksBannedRequest(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusForbidden, `{"action":"ban","http_status":403}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code)
|
||||
assert.False(t, reached, "a banned request must not reach the backend")
|
||||
assert.Equal(t, "appsec_ban", meta["appsec_verdict"])
|
||||
assert.NotContains(t, meta, "appsec_mode", "enforce is the default, only observe is annotated")
|
||||
}
|
||||
|
||||
func TestCheckAppSec_ObserveAllowsAndRecordsVerdict(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusForbidden, `{"action":"ban","http_status":403}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecObserve, client, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.True(t, reached, "observe mode must not block")
|
||||
assert.Equal(t, "appsec_ban", meta["appsec_verdict"])
|
||||
assert.Equal(t, "observe", meta["appsec_mode"])
|
||||
}
|
||||
|
||||
func TestCheckAppSec_AllowedRequestPasses(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusOK, `{"action":"allow","http_status":200}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.True(t, reached)
|
||||
assert.NotContains(t, meta, "appsec_verdict", "a clean request records no verdict")
|
||||
}
|
||||
|
||||
func TestCheckAppSec_OffSkipsInspection(t *testing.T) {
|
||||
// An engine that would ban everything; the mode must keep us away from it.
|
||||
srv := appsecEngine(t, http.StatusForbidden, `{"action":"ban"}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecOff, client, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.True(t, reached)
|
||||
assert.Empty(t, meta)
|
||||
}
|
||||
|
||||
func TestCheckAppSec_EnforceFailsClosedWithoutClient(t *testing.T) {
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, nil, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code,
|
||||
"enforce with no configured endpoint must deny rather than pass traffic uninspected")
|
||||
assert.False(t, reached)
|
||||
assert.Equal(t, "appsec_unavailable", meta["appsec_verdict"])
|
||||
}
|
||||
|
||||
func TestCheckAppSec_ObserveAllowsWithoutClient(t *testing.T) {
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecObserve, nil, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.True(t, reached)
|
||||
assert.Equal(t, "appsec_unavailable", meta["appsec_verdict"])
|
||||
assert.Equal(t, "observe", meta["appsec_mode"])
|
||||
}
|
||||
|
||||
func TestCheckAppSec_EnforceFailsClosedWhenEngineUnreachable(t *testing.T) {
|
||||
client, err := appsec.New(appsec.Config{URL: "http://127.0.0.1:1/", APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, appsecRequest())
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code)
|
||||
assert.False(t, reached)
|
||||
assert.Equal(t, "appsec_unavailable", meta["appsec_verdict"])
|
||||
}
|
||||
|
||||
func TestCheckAppSec_InspectsOverlayTraffic(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusForbidden, `{"action":"ban"}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Requests arriving over the WireGuard overlay skip the geo and IP-reputation
|
||||
// checks, but request content is just as inspectable.
|
||||
r := appsecRequest()
|
||||
r = r.WithContext(types.WithOverlayOrigin(r.Context()))
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, r)
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, "overlay traffic must still be inspected")
|
||||
assert.False(t, reached)
|
||||
assert.Equal(t, "appsec_ban", meta["appsec_verdict"])
|
||||
}
|
||||
|
||||
func TestCheckAppSec_UnresolvableClientIPFailsClosed(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusOK, `{"action":"allow"}`)
|
||||
client, err := appsec.New(appsec.Config{URL: srv.URL, APIKey: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
r := appsecRequest()
|
||||
r.RemoteAddr = "not-an-address"
|
||||
|
||||
rec, meta, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, r)
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code,
|
||||
"the engine requires a client address; a request we cannot attribute must not pass")
|
||||
assert.False(t, reached)
|
||||
assert.Equal(t, "appsec_unavailable", meta["appsec_verdict"])
|
||||
}
|
||||
|
||||
// The redaction sets are resolved from the domain's schemes at registration, so
|
||||
// what AppSec withholds cannot drift from what those schemes actually accept.
|
||||
func TestAddDomain_ResolvesRedactionSetsFromSchemes(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
require.NoError(t, mw.AddDomain("svc.example.com", DomainSettings{
|
||||
Schemes: []Scheme{
|
||||
NewPassword(nil, "svc-1", "acct-1"),
|
||||
NewHeader(nil, "svc-1", "acct-1", "X-Api-Key"),
|
||||
},
|
||||
SessionPublicKey: base64.StdEncoding.EncodeToString(make([]byte, ed25519.PublicKeySize)),
|
||||
SessionExpiration: time.Hour,
|
||||
AppSecMode: restrict.AppSecEnforce,
|
||||
}))
|
||||
|
||||
mw.domainsMux.RLock()
|
||||
config := mw.domains["svc.example.com"]
|
||||
mw.domainsMux.RUnlock()
|
||||
|
||||
assert.Equal(t, []string{"password"}, config.redactBodyFields)
|
||||
assert.Equal(t, []string{"X-Api-Key"}, config.redactHeaders)
|
||||
// r.FormValue merges the query into the form, so a credential passed there
|
||||
// authenticates and must be redacted alongside the OIDC session token.
|
||||
assert.Equal(t, []string{"session_token", "password"}, config.redactQueryParams)
|
||||
}
|
||||
|
||||
// countingBudget records reservations so a test can observe when the
|
||||
// middleware hands them back.
|
||||
type countingBudget struct {
|
||||
mu sync.Mutex
|
||||
total int64
|
||||
used int64
|
||||
maxAtOnce int64
|
||||
}
|
||||
|
||||
func (b *countingBudget) Acquire(n int64) bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.used+n > b.total {
|
||||
return false
|
||||
}
|
||||
b.used += n
|
||||
if b.used > b.maxAtOnce {
|
||||
b.maxAtOnce = b.used
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (b *countingBudget) Release(n int64) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.used -= n
|
||||
}
|
||||
|
||||
func (b *countingBudget) inUse() int64 {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.used
|
||||
}
|
||||
|
||||
// The buffered body stays alive as r.Body until the backend has read it, so
|
||||
// Protect must hold the reservation for the whole request and return it only
|
||||
// once the handler chain has unwound. Releasing inside Inspect would let the
|
||||
// budget admit buffering that is still resident.
|
||||
func TestProtect_AppSecBudgetHeldForRequestAndReleasedAfter(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusOK, `{"action":"allow"}`)
|
||||
budget := &countingBudget{total: 1 << 20}
|
||||
client, err := appsec.New(appsec.Config{
|
||||
URL: srv.URL,
|
||||
APIKey: "k",
|
||||
MaxBodyBytes: 4096,
|
||||
Budget: budget,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
mw.SetAppSec(client)
|
||||
require.NoError(t, mw.AddDomain("svc.example.com", DomainSettings{
|
||||
AccountID: types.AccountID("acct-1"),
|
||||
ServiceID: types.ServiceID("svc-1"),
|
||||
AppSecMode: restrict.AppSecEnforce,
|
||||
}))
|
||||
|
||||
var inHandler int64
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// The backend reads the buffered body here, so the reservation must
|
||||
// still be held at this point.
|
||||
inHandler = budget.inUse()
|
||||
_, _ = io.ReadAll(r.Body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "http://svc.example.com/", strings.NewReader("payload"))
|
||||
r.Host = "svc.example.com"
|
||||
cd := proxy.NewCapturedData("req-1")
|
||||
r = r.WithContext(proxy.WithCapturedData(r.Context(), cd))
|
||||
|
||||
handler.ServeHTTP(httptest.NewRecorder(), r)
|
||||
|
||||
assert.Equal(t, int64(4096), inHandler, "the reservation must be held while the backend reads the body")
|
||||
assert.Equal(t, int64(0), budget.inUse(), "Protect must release the reservation once the request is served")
|
||||
}
|
||||
|
||||
// A denied request never reaches the backend, but Protect still has to hand the
|
||||
// reservation back or the pool leaks one cap per blocked request.
|
||||
func TestProtect_AppSecBudgetReleasedOnDeny(t *testing.T) {
|
||||
srv := appsecEngine(t, http.StatusForbidden, `{"action":"ban"}`)
|
||||
budget := &countingBudget{total: 1 << 20}
|
||||
client, err := appsec.New(appsec.Config{
|
||||
URL: srv.URL,
|
||||
APIKey: "k",
|
||||
MaxBodyBytes: 4096,
|
||||
Budget: budget,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "http://svc.example.com/", strings.NewReader("payload"))
|
||||
r.Host = "svc.example.com"
|
||||
rec, _, reached := serveWithAppSec(t, restrict.AppSecEnforce, client, r)
|
||||
|
||||
assert.False(t, reached, "a banned request must not reach the backend")
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code)
|
||||
assert.Equal(t, int64(0), budget.inUse(), "a blocked request must not leak its reservation")
|
||||
}
|
||||
@@ -39,11 +39,6 @@ func (Header) Type() auth.Method {
|
||||
return auth.MethodHeader
|
||||
}
|
||||
|
||||
// HeaderName returns the request header this scheme reads its credential from.
|
||||
func (h Header) HeaderName() string {
|
||||
return h.headerName
|
||||
}
|
||||
|
||||
// Authenticate checks for the configured header in the request. If absent,
|
||||
// returns empty (unauthenticated). If present, validates via gRPC.
|
||||
func (h Header) Authenticate(r *http.Request) (string, string, error) {
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/netbirdio/netbird/proxy/auth"
|
||||
"github.com/netbirdio/netbird/proxy/internal/appsec"
|
||||
"github.com/netbirdio/netbird/proxy/internal/proxy"
|
||||
"github.com/netbirdio/netbird/proxy/internal/restrict"
|
||||
"github.com/netbirdio/netbird/proxy/internal/types"
|
||||
@@ -26,11 +25,6 @@ import (
|
||||
"github.com/netbirdio/netbird/shared/management/proto"
|
||||
)
|
||||
|
||||
// sessionCookieNames is the cookie set AppSec redacts before mirroring: the
|
||||
// proxy's session cookie is a bearer credential for the service, and the
|
||||
// reverse proxy already strips it before forwarding upstream.
|
||||
var sessionCookieNames = []string{auth.SessionCookieName}
|
||||
|
||||
// errValidationUnavailable indicates that session validation failed due to
|
||||
// an infrastructure error (e.g. gRPC unavailable), not an invalid token.
|
||||
var errValidationUnavailable = errors.New("session validation unavailable")
|
||||
@@ -65,14 +59,6 @@ type DomainConfig struct {
|
||||
IPRestrictions *restrict.Filter
|
||||
// Private routes the domain through ValidateTunnelPeer; failure → 403.
|
||||
Private bool
|
||||
// AppSecMode enables CrowdSec AppSec request inspection for this domain.
|
||||
AppSecMode restrict.AppSecMode
|
||||
// redact* name the credentials this domain's schemes accept, resolved once
|
||||
// at registration. AppSec replaces their values before mirroring a request,
|
||||
// matching what the reverse proxy strips before forwarding upstream.
|
||||
redactBodyFields []string
|
||||
redactHeaders []string
|
||||
redactQueryParams []string
|
||||
}
|
||||
|
||||
type validationResult struct {
|
||||
@@ -96,9 +82,6 @@ type Middleware struct {
|
||||
sessionValidator SessionValidator
|
||||
geo restrict.GeoResolver
|
||||
tunnelCache *tunnelValidationCache
|
||||
// appsec is the shared CrowdSec AppSec client, nil when the proxy has no
|
||||
// AppSec endpoint configured. Set once during startup, before serving.
|
||||
appsec *appsec.Client
|
||||
}
|
||||
|
||||
// NewMiddleware creates a new authentication middleware. The sessionValidator is
|
||||
@@ -116,12 +99,6 @@ func NewMiddleware(logger *log.Logger, sessionValidator SessionValidator, geo re
|
||||
}
|
||||
}
|
||||
|
||||
// SetAppSec installs the shared CrowdSec AppSec client. Must be called during
|
||||
// startup, before the middleware serves any request.
|
||||
func (mw *Middleware) SetAppSec(client *appsec.Client) {
|
||||
mw.appsec = client
|
||||
}
|
||||
|
||||
// Protect wraps next with per-domain authentication and IP restriction checks.
|
||||
// Requests whose Host is not registered pass through unchanged.
|
||||
func (mw *Middleware) Protect(next http.Handler) http.Handler {
|
||||
@@ -146,14 +123,6 @@ func (mw *Middleware) Protect(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// Deferred, not released here: the inspected body stays alive as r.Body
|
||||
// until the backend has read it, which happens inside next.ServeHTTP.
|
||||
appSecAllowed, releaseAppSec := mw.checkAppSec(w, r, config)
|
||||
defer releaseAppSec()
|
||||
if !appSecAllowed {
|
||||
return
|
||||
}
|
||||
|
||||
// Private services bypass operator schemes and gate on tunnel peer.
|
||||
if config.Private {
|
||||
if mw.forwardWithTunnelPeer(w, r, host, config, next) {
|
||||
@@ -293,134 +262,6 @@ func (mw *Middleware) checkIPRestrictions(w http.ResponseWriter, r *http.Request
|
||||
return false
|
||||
}
|
||||
|
||||
// checkAppSec mirrors the request to the CrowdSec AppSec engine when the domain
|
||||
// enables inspection. Returns false when the request was blocked and a response
|
||||
// has been written.
|
||||
//
|
||||
// The returned release frees the body-buffering budget the inspection reserved
|
||||
// and is never nil. It must run only after the request has been served, since
|
||||
// the buffered body stays alive as r.Body for the backend to read.
|
||||
//
|
||||
// Every non-allow remediation blocks with 403, captcha included: the proxy has
|
||||
// no challenge flow to serve. The distinct verdict is still recorded so the
|
||||
// access log shows which remediation the engine actually chose.
|
||||
//
|
||||
// Unlike the geo and IP-reputation checks, this runs for overlay traffic too:
|
||||
// AppSec inspects request content, which is just as meaningful when the caller
|
||||
// reached the proxy through the WireGuard tunnel.
|
||||
func (mw *Middleware) checkAppSec(w http.ResponseWriter, r *http.Request, config DomainConfig) (bool, func()) {
|
||||
if !config.AppSecMode.Enabled() {
|
||||
return true, func() {}
|
||||
}
|
||||
|
||||
verdict, release := mw.inspectAppSec(r, config)
|
||||
if verdict == restrict.Allow {
|
||||
return true, release
|
||||
}
|
||||
|
||||
observe := config.AppSecMode == restrict.AppSecObserve
|
||||
if cd := proxy.CapturedDataFromContext(r.Context()); cd != nil {
|
||||
cd.SetMetadata("appsec_verdict", verdict.String())
|
||||
if observe {
|
||||
cd.SetMetadata("appsec_mode", "observe")
|
||||
}
|
||||
}
|
||||
|
||||
if observe {
|
||||
mw.logger.Debugf("AppSec observe: would block %s for %s (%s)", r.RemoteAddr, r.Host, verdict)
|
||||
return true, release
|
||||
}
|
||||
|
||||
mw.markDenied(r, verdict.String())
|
||||
mw.logger.Debugf("AppSec: %s for %s %s", verdict, r.Host, r.RemoteAddr)
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return false, release
|
||||
}
|
||||
|
||||
// inspectAppSec runs the AppSec call and returns its verdict. Failures come
|
||||
// back as DenyAppSecUnavailable regardless of mode so observe mode still
|
||||
// records that inspection did not happen; the caller decides what blocks. The
|
||||
// returned release is never nil.
|
||||
func (mw *Middleware) inspectAppSec(r *http.Request, config DomainConfig) (restrict.Verdict, func()) {
|
||||
// Mode requested but the proxy has no AppSec endpoint configured. Management
|
||||
// gates this on the cluster capability; a stale mapping can still arrive.
|
||||
if mw.appsec == nil {
|
||||
mw.logger.Debugf("AppSec mode %q requested for %s but no AppSec endpoint is configured", config.AppSecMode, r.Host)
|
||||
return restrict.DenyAppSecUnavailable, func() {}
|
||||
}
|
||||
|
||||
clientIP := mw.resolveClientIP(r)
|
||||
if !clientIP.IsValid() {
|
||||
// The engine requires a client address, and a request whose source we
|
||||
// cannot establish is exactly the kind we must not wave through.
|
||||
mw.logger.Debugf("AppSec: cannot resolve client address for %q", r.RemoteAddr)
|
||||
return restrict.DenyAppSecUnavailable, func() {}
|
||||
}
|
||||
|
||||
req := appsec.Request{
|
||||
HTTP: r,
|
||||
ClientIP: clientIP,
|
||||
RedactBodyFields: config.redactBodyFields,
|
||||
RedactHeaders: config.redactHeaders,
|
||||
RedactCookies: sessionCookieNames,
|
||||
RedactQueryParams: config.redactQueryParams,
|
||||
}
|
||||
if cd := proxy.CapturedDataFromContext(r.Context()); cd != nil {
|
||||
req.TransactionID = cd.GetRequestID()
|
||||
}
|
||||
|
||||
result, err := mw.appsec.Inspect(r.Context(), req)
|
||||
if err != nil {
|
||||
mw.logger.Debugf("AppSec inspection failed for %s: %v", r.Host, err)
|
||||
}
|
||||
// Record when the body went uninspected: headers and URI were still
|
||||
// checked, but an operator reading the log should not read a clean verdict
|
||||
// as "the payload was examined". Oversize is reachable by padding, so its
|
||||
// absence from the log would hide a deliberate opt-out.
|
||||
if result.BodyBypass != "" {
|
||||
if cd := proxy.CapturedDataFromContext(r.Context()); cd != nil {
|
||||
cd.SetMetadata("appsec_body_bypass", result.BodyBypass)
|
||||
}
|
||||
}
|
||||
return result.Verdict, result.Release
|
||||
}
|
||||
|
||||
// credentialFormFields lists the login form fields whose values are redacted
|
||||
// from the mirrored body, so a password or PIN submitted to the proxy's own
|
||||
// login form never reaches the Security Engine.
|
||||
func credentialFormFields(schemes []Scheme) []string {
|
||||
var fields []string
|
||||
for _, s := range schemes {
|
||||
switch s.Type() {
|
||||
case auth.MethodPassword:
|
||||
fields = append(fields, passwordFormId)
|
||||
case auth.MethodPIN:
|
||||
fields = append(fields, pinFormId)
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// credentialHeaders lists the request headers whose values are redacted from
|
||||
// the mirrored request. A header-auth scheme carries a session token the proxy
|
||||
// validates and never forwards upstream, so the engine must not see it either.
|
||||
func credentialHeaders(schemes []Scheme) []string {
|
||||
var names []string
|
||||
for _, s := range schemes {
|
||||
// Structural, not a concrete Header assertion: if the scheme is ever
|
||||
// registered as a pointer, a type assertion would quietly stop matching
|
||||
// and the header would start reaching the engine again.
|
||||
named, ok := s.(interface{ HeaderName() string })
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if name := named.HeaderName(); name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// resolveClientIP extracts the real client IP from CapturedData, falling back to r.RemoteAddr.
|
||||
func (mw *Middleware) resolveClientIP(r *http.Request) netip.Addr {
|
||||
if cd := proxy.CapturedDataFromContext(r.Context()); cd != nil {
|
||||
@@ -440,18 +281,12 @@ func (mw *Middleware) resolveClientIP(r *http.Request) netip.Addr {
|
||||
return addr.Unmap()
|
||||
}
|
||||
|
||||
// markDenied records the deny reason on the captured data so the access log
|
||||
// attributes the response to the proxy rather than the backend.
|
||||
func (mw *Middleware) markDenied(r *http.Request, reason string) {
|
||||
// blockIPRestriction sets captured data fields for an IP-restriction block event.
|
||||
func (mw *Middleware) blockIPRestriction(r *http.Request, reason string) {
|
||||
if cd := proxy.CapturedDataFromContext(r.Context()); cd != nil {
|
||||
cd.SetOrigin(proxy.OriginAuth)
|
||||
cd.SetAuthMethod(reason)
|
||||
}
|
||||
}
|
||||
|
||||
// blockIPRestriction sets captured data fields for an IP-restriction block event.
|
||||
func (mw *Middleware) blockIPRestriction(r *http.Request, reason string) {
|
||||
mw.markDenied(r, reason)
|
||||
mw.logger.Debugf("IP restriction: %s for %s", reason, r.RemoteAddr)
|
||||
}
|
||||
|
||||
@@ -802,61 +637,45 @@ func wasCredentialSubmitted(r *http.Request, method auth.Method) bool {
|
||||
case auth.MethodPassword:
|
||||
return r.FormValue("password") != ""
|
||||
case auth.MethodOIDC:
|
||||
return r.URL.Query().Get(sessionTokenParam) != ""
|
||||
return r.URL.Query().Get("session_token") != ""
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DomainSettings is the per-domain configuration AddDomain applies.
|
||||
type DomainSettings struct {
|
||||
Schemes []Scheme
|
||||
// SessionPublicKey is the base64-encoded ed25519 key used to verify session
|
||||
// cookies. Required when Schemes is non-empty.
|
||||
SessionPublicKey string
|
||||
SessionExpiration time.Duration
|
||||
AccountID types.AccountID
|
||||
ServiceID types.ServiceID
|
||||
IPRestrictions *restrict.Filter
|
||||
// Private forces ValidateTunnelPeer enforcement (403 on failure) regardless
|
||||
// of the schemes list.
|
||||
Private bool
|
||||
AppSecMode restrict.AppSecMode
|
||||
}
|
||||
|
||||
// AddDomain registers authentication schemes for the given domain. With schemes
|
||||
// a valid session public key is required.
|
||||
func (mw *Middleware) AddDomain(domain string, settings DomainSettings) error {
|
||||
credentialFields := credentialFormFields(settings.Schemes)
|
||||
config := DomainConfig{
|
||||
AccountID: settings.AccountID,
|
||||
ServiceID: settings.ServiceID,
|
||||
IPRestrictions: settings.IPRestrictions,
|
||||
Private: settings.Private,
|
||||
AppSecMode: settings.AppSecMode,
|
||||
redactBodyFields: credentialFields,
|
||||
redactHeaders: credentialHeaders(settings.Schemes),
|
||||
// A credential can arrive in the query too: r.FormValue merges the URL
|
||||
// query into the form, so "?password=..." authenticates just as a form
|
||||
// post does and must not be mirrored in the clear either.
|
||||
redactQueryParams: append([]string{sessionTokenParam}, credentialFields...),
|
||||
// AddDomain registers authentication schemes for the given domain. With schemes a valid session public key is required.
|
||||
// private=true forces ValidateTunnelPeer enforcement (403 on failure) regardless of the schemes list.
|
||||
func (mw *Middleware) AddDomain(domain string, schemes []Scheme, publicKeyB64 string, expiration time.Duration, accountID types.AccountID, serviceID types.ServiceID, ipRestrictions *restrict.Filter, private bool) error {
|
||||
if len(schemes) == 0 {
|
||||
mw.domainsMux.Lock()
|
||||
defer mw.domainsMux.Unlock()
|
||||
mw.domains[domain] = DomainConfig{
|
||||
AccountID: accountID,
|
||||
ServiceID: serviceID,
|
||||
IPRestrictions: ipRestrictions,
|
||||
Private: private,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(settings.Schemes) > 0 {
|
||||
pubKeyBytes, err := base64.StdEncoding.DecodeString(settings.SessionPublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode session public key for domain %s: %w", domain, err)
|
||||
}
|
||||
if len(pubKeyBytes) != ed25519.PublicKeySize {
|
||||
return fmt.Errorf("invalid session public key size for domain %s: got %d, want %d", domain, len(pubKeyBytes), ed25519.PublicKeySize)
|
||||
}
|
||||
config.Schemes = settings.Schemes
|
||||
config.SessionPublicKey = pubKeyBytes
|
||||
config.SessionExpiration = settings.SessionExpiration
|
||||
pubKeyBytes, err := base64.StdEncoding.DecodeString(publicKeyB64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode session public key for domain %s: %w", domain, err)
|
||||
}
|
||||
if len(pubKeyBytes) != ed25519.PublicKeySize {
|
||||
return fmt.Errorf("invalid session public key size for domain %s: got %d, want %d", domain, len(pubKeyBytes), ed25519.PublicKeySize)
|
||||
}
|
||||
|
||||
mw.domainsMux.Lock()
|
||||
defer mw.domainsMux.Unlock()
|
||||
mw.domains[domain] = config
|
||||
mw.domains[domain] = DomainConfig{
|
||||
Schemes: schemes,
|
||||
SessionPublicKey: pubKeyBytes,
|
||||
SessionExpiration: expiration,
|
||||
AccountID: accountID,
|
||||
ServiceID: serviceID,
|
||||
IPRestrictions: ipRestrictions,
|
||||
Private: private,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -911,10 +730,10 @@ func (mw *Middleware) validateSessionToken(ctx context.Context, host, token stri
|
||||
// parameter removed so it doesn't linger in the browser's address bar or history.
|
||||
func stripSessionTokenParam(u *url.URL) string {
|
||||
q := u.Query()
|
||||
if !q.Has(sessionTokenParam) {
|
||||
if !q.Has("session_token") {
|
||||
return u.RequestURI()
|
||||
}
|
||||
q.Del(sessionTokenParam)
|
||||
q.Del("session_token")
|
||||
clean := *u
|
||||
clean.RawQuery = q.Encode()
|
||||
return clean.RequestURI()
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestAddDomain_ValidKey(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
err := mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
mw.domainsMux.RLock()
|
||||
@@ -81,7 +81,7 @@ func TestAddDomain_EmptyKey(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
err := mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", []Scheme{scheme}, "", time.Hour, "", "", nil, false)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid session public key size")
|
||||
|
||||
@@ -95,7 +95,7 @@ func TestAddDomain_InvalidBase64(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
err := mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: "not-valid-base64!!!", SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", []Scheme{scheme}, "not-valid-base64!!!", time.Hour, "", "", nil, false)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "decode session public key")
|
||||
|
||||
@@ -110,7 +110,7 @@ func TestAddDomain_WrongKeySize(t *testing.T) {
|
||||
|
||||
shortKey := base64.StdEncoding.EncodeToString([]byte("tooshort"))
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
err := mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: shortKey, SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", []Scheme{scheme}, shortKey, time.Hour, "", "", nil, false)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid session public key size")
|
||||
|
||||
@@ -123,7 +123,7 @@ func TestAddDomain_WrongKeySize(t *testing.T) {
|
||||
func TestAddDomain_NoSchemes_NoKeyRequired(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", nil, "", time.Hour, "", "", nil, false)
|
||||
require.NoError(t, err, "domains with no auth schemes should not require a key")
|
||||
|
||||
mw.domainsMux.RLock()
|
||||
@@ -139,8 +139,8 @@ func TestAddDomain_OverwritesPreviousConfig(t *testing.T) {
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp1.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp2.PublicKey, SessionExpiration: 2 * time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp1.PublicKey, time.Hour, "", "", nil, false))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp2.PublicKey, 2*time.Hour, "", "", nil, false))
|
||||
|
||||
mw.domainsMux.RLock()
|
||||
config := mw.domains["example.com"]
|
||||
@@ -156,7 +156,7 @@ func TestRemoveDomain(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
mw.RemoveDomain("example.com")
|
||||
|
||||
@@ -180,7 +180,7 @@ func TestProtect_UnknownDomainPassesThrough(t *testing.T) {
|
||||
|
||||
func TestProtect_DomainWithNoSchemesPassesThrough(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", nil, "", time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -197,7 +197,7 @@ func TestProtect_UnauthenticatedRequestIsBlocked(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -218,7 +218,7 @@ func TestProtect_HostWithPortIsMatched(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -239,7 +239,7 @@ func TestProtect_ValidSessionCookiePassesThrough(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
token, err := sessionkey.SignToken(kp.PrivateKey, "test-user", "", "example.com", auth.MethodPIN, nil, nil, time.Hour)
|
||||
require.NoError(t, err)
|
||||
@@ -272,7 +272,7 @@ func TestProtect_SessionCookieGroupsPropagate(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
groups := []string{"engineering", "sre"}
|
||||
token, err := sessionkey.SignToken(kp.PrivateKey, "test-user", "", "example.com", auth.MethodPIN, groups, nil, time.Hour)
|
||||
@@ -337,7 +337,7 @@ func TestProtect_PrivateService_TunnelPeerGroupsPropagate(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
// Private service: no operator schemes — auth gates solely on the tunnel peer.
|
||||
require.NoError(t, mw.AddDomain("agent.example.com", DomainSettings{SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acct-1", ServiceID: "svc-1", Private: true}))
|
||||
require.NoError(t, mw.AddDomain("agent.example.com", nil, kp.PublicKey, time.Hour, "acct-1", "svc-1", nil, true))
|
||||
|
||||
cd := proxy.NewCapturedData("")
|
||||
cd.SetClientIP(netip.MustParseAddr("100.90.1.14")) // CGNAT tunnel source
|
||||
@@ -377,7 +377,7 @@ func TestProtect_PrivateService_TunnelPeerDenied(t *testing.T) {
|
||||
}}
|
||||
mw := NewMiddleware(log.StandardLogger(), validator, nil)
|
||||
kp := generateTestKeyPair(t)
|
||||
require.NoError(t, mw.AddDomain("agent.example.com", DomainSettings{SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acct-1", ServiceID: "svc-1", Private: true}))
|
||||
require.NoError(t, mw.AddDomain("agent.example.com", nil, kp.PublicKey, time.Hour, "acct-1", "svc-1", nil, true))
|
||||
|
||||
cd := proxy.NewCapturedData("")
|
||||
cd.SetClientIP(netip.MustParseAddr("100.90.1.14"))
|
||||
@@ -405,7 +405,7 @@ func TestProtect_ExpiredSessionCookieIsRejected(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
// Sign a token that expired 1 second ago.
|
||||
token, err := sessionkey.SignToken(kp.PrivateKey, "test-user", "", "example.com", auth.MethodPIN, nil, nil, -time.Second)
|
||||
@@ -431,7 +431,7 @@ func TestProtect_WrongDomainCookieIsRejected(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
// Token signed for a different domain audience.
|
||||
token, err := sessionkey.SignToken(kp.PrivateKey, "test-user", "", "other.com", auth.MethodPIN, nil, nil, time.Hour)
|
||||
@@ -458,7 +458,7 @@ func TestProtect_WrongKeyCookieIsRejected(t *testing.T) {
|
||||
kp2 := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp1.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp1.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
// Token signed with a different private key.
|
||||
token, err := sessionkey.SignToken(kp2.PrivateKey, "test-user", "", "example.com", auth.MethodPIN, nil, nil, time.Hour)
|
||||
@@ -495,7 +495,7 @@ func TestProtect_SchemeAuthRedirectsWithCookie(t *testing.T) {
|
||||
return "", "pin", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -548,7 +548,7 @@ func TestProtect_FailedAuthDoesNotSetCookie(t *testing.T) {
|
||||
return "", "pin", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -584,7 +584,7 @@ func TestProtect_MultipleSchemes(t *testing.T) {
|
||||
return "", "password", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{pinScheme, passwordScheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{pinScheme, passwordScheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -614,7 +614,7 @@ func TestProtect_InvalidTokenFromSchemeReturns400(t *testing.T) {
|
||||
return "invalid-jwt-token", "", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -638,7 +638,7 @@ func TestAddDomain_RandomBytes32NotEd25519(t *testing.T) {
|
||||
key := base64.StdEncoding.EncodeToString(randomBytes)
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
|
||||
err = mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: key, SessionExpiration: time.Hour})
|
||||
err = mw.AddDomain("example.com", []Scheme{scheme}, key, time.Hour, "", "", nil, false)
|
||||
require.NoError(t, err, "any 32-byte key should be accepted at registration time")
|
||||
}
|
||||
|
||||
@@ -647,10 +647,10 @@ func TestAddDomain_InvalidKeyDoesNotCorruptExistingConfig(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
// Attempt to overwrite with an invalid key.
|
||||
err := mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: "bad", SessionExpiration: time.Hour})
|
||||
err := mw.AddDomain("example.com", []Scheme{scheme}, "bad", time.Hour, "", "", nil, false)
|
||||
require.Error(t, err)
|
||||
|
||||
// The original valid config should still be intact.
|
||||
@@ -674,7 +674,7 @@ func TestProtect_FailedPinAuthCapturesAuthMethod(t *testing.T) {
|
||||
return "", "pin", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
capturedData := proxy.NewCapturedData("")
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
@@ -701,7 +701,7 @@ func TestProtect_FailedPasswordAuthCapturesAuthMethod(t *testing.T) {
|
||||
return "", "password", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
capturedData := proxy.NewCapturedData("")
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
@@ -728,7 +728,7 @@ func TestProtect_NoCredentialsDoesNotCaptureAuthMethod(t *testing.T) {
|
||||
return "", "pin", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
capturedData := proxy.NewCapturedData("")
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
@@ -815,7 +815,8 @@ func TestWasCredentialSubmitted(t *testing.T) {
|
||||
func TestCheckIPRestrictions_UnparseableAddress(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{AccountID: "acc1", ServiceID: "svc1", IPRestrictions: restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"10.0.0.0/8"}})})
|
||||
err := mw.AddDomain("example.com", nil, "", 0, "acc1", "svc1",
|
||||
restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"10.0.0.0/8"}}), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -850,7 +851,8 @@ func TestCheckIPRestrictions_UsesCapturedDataClientIP(t *testing.T) {
|
||||
// trusted proxies), checkIPRestrictions should use that IP, not RemoteAddr.
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{AccountID: "acc1", ServiceID: "svc1", IPRestrictions: restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"203.0.113.0/24"}})})
|
||||
err := mw.AddDomain("example.com", nil, "", 0, "acc1", "svc1",
|
||||
restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"203.0.113.0/24"}}), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -890,7 +892,8 @@ func TestCheckIPRestrictions_NilGeoWithCountryRules(t *testing.T) {
|
||||
// Geo is nil, country restrictions are configured: must deny (fail-close).
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{AccountID: "acc1", ServiceID: "svc1", IPRestrictions: restrict.ParseFilter(restrict.FilterConfig{AllowedCountries: []string{"US"}})})
|
||||
err := mw.AddDomain("example.com", nil, "", 0, "acc1", "svc1",
|
||||
restrict.ParseFilter(restrict.FilterConfig{AllowedCountries: []string{"US"}}), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -913,10 +916,11 @@ func TestCheckIPRestrictions_NilGeoWithCountryRules(t *testing.T) {
|
||||
func TestCheckIPRestrictions_OverlayOriginSkipsCountryRules(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{AccountID: "acc1", ServiceID: "svc1", IPRestrictions: restrict.ParseFilter(restrict.FilterConfig{
|
||||
AllowedCIDRs: []string{"100.64.0.0/10"},
|
||||
AllowedCountries: []string{"US"},
|
||||
})})
|
||||
err := mw.AddDomain("example.com", nil, "", 0, "acc1", "svc1",
|
||||
restrict.ParseFilter(restrict.FilterConfig{
|
||||
AllowedCIDRs: []string{"100.64.0.0/10"},
|
||||
AllowedCountries: []string{"US"},
|
||||
}), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -949,7 +953,8 @@ func TestCheckIPRestrictions_OverlayOriginSkipsCountryRules(t *testing.T) {
|
||||
func TestCheckIPRestrictions_OverlayOriginRespectsCIDR(t *testing.T) {
|
||||
mw := NewMiddleware(log.StandardLogger(), nil, nil)
|
||||
|
||||
err := mw.AddDomain("example.com", DomainSettings{AccountID: "acc1", ServiceID: "svc1", IPRestrictions: restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"100.64.0.0/16"}})})
|
||||
err := mw.AddDomain("example.com", nil, "", 0, "acc1", "svc1",
|
||||
restrict.ParseFilter(restrict.FilterConfig{AllowedCIDRs: []string{"100.64.0.0/16"}}), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -977,7 +982,7 @@ func TestProtect_OIDCOnlyRedirectsDirectly(t *testing.T) {
|
||||
return "", oidcURL, nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1006,7 +1011,7 @@ func TestProtect_OIDCWithOtherMethodShowsLoginPage(t *testing.T) {
|
||||
return "", "pin", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{oidcScheme, pinScheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{oidcScheme, pinScheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1050,7 +1055,7 @@ func TestProtect_HeaderAuth_ForwardsOnSuccess(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
hdr := newHeaderSchemeWithToken(t, kp, "X-API-Key", "secret-key")
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
capturedData := proxy.NewCapturedData("")
|
||||
@@ -1093,7 +1098,7 @@ func TestProtect_HeaderAuth_MissingHeaderFallsThrough(t *testing.T) {
|
||||
hdr := newHeaderSchemeWithToken(t, kp, "X-API-Key", "secret-key")
|
||||
// Also add a PIN scheme so we can verify fallthrough behavior.
|
||||
pinScheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr, pinScheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr, pinScheme}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1113,7 +1118,7 @@ func TestProtect_HeaderAuth_WrongValueReturns401(t *testing.T) {
|
||||
return &proto.AuthenticateResponse{Success: false}, nil
|
||||
}}
|
||||
hdr := NewHeader(mock, "svc1", "acc1", "X-API-Key")
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
capturedData := proxy.NewCapturedData("")
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
@@ -1136,7 +1141,7 @@ func TestProtect_HeaderAuth_InfraErrorReturns502(t *testing.T) {
|
||||
return nil, errors.New("gRPC unavailable")
|
||||
}}
|
||||
hdr := NewHeader(mock, "svc1", "acc1", "X-API-Key")
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1153,7 +1158,7 @@ func TestProtect_HeaderAuth_SubsequentRequestUsesSessionCookie(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
hdr := newHeaderSchemeWithToken(t, kp, "X-API-Key", "secret-key")
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
@@ -1213,7 +1218,7 @@ func TestProtect_HeaderAuth_MultipleValuesSameHeader(t *testing.T) {
|
||||
|
||||
// Single Header scheme (as if one entry existed), but the mock checks both values.
|
||||
hdr := NewHeader(mock, "svc1", "acc1", "Authorization")
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{hdr}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour, AccountID: "acc1", ServiceID: "svc1"}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{hdr}, kp.PublicKey, time.Hour, "acc1", "svc1", nil, false))
|
||||
|
||||
var backendCalled bool
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -1271,7 +1276,7 @@ func TestProtect_OIDCOnPlainHTTP_BlockedWith400(t *testing.T) {
|
||||
return "", "https://idp.example.com/authorize", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1295,7 +1300,7 @@ func TestProtect_OIDCOverTLS_NotBlocked(t *testing.T) {
|
||||
return "", "https://idp.example.com/authorize", nil
|
||||
},
|
||||
}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1315,7 +1320,7 @@ func TestProtect_NonOIDCSchemes_PlainHTTP_NotBlocked(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1345,7 +1350,7 @@ func TestProtect_TunnelPeerFastPath_RequiresInboundMarker(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
@@ -1380,7 +1385,7 @@ func TestProtect_TunnelPeerFastPath_TakesPathWithInboundMarker(t *testing.T) {
|
||||
kp := generateTestKeyPair(t)
|
||||
|
||||
scheme := &stubScheme{method: auth.MethodPIN, promptID: "pin"}
|
||||
require.NoError(t, mw.AddDomain("example.com", DomainSettings{Schemes: []Scheme{scheme}, SessionPublicKey: kp.PublicKey, SessionExpiration: time.Hour}))
|
||||
require.NoError(t, mw.AddDomain("example.com", []Scheme{scheme}, kp.PublicKey, time.Hour, "", "", nil, false))
|
||||
|
||||
handler := mw.Protect(newPassthroughHandler())
|
||||
|
||||
|
||||
@@ -13,10 +13,6 @@ import (
|
||||
"github.com/netbirdio/netbird/shared/management/proto"
|
||||
)
|
||||
|
||||
// sessionTokenParam is the query parameter the management server uses to hand
|
||||
// the minted session token back to the proxy after an OIDC login.
|
||||
const sessionTokenParam = "session_token"
|
||||
|
||||
type urlGenerator interface {
|
||||
GetOIDCURL(context.Context, *proto.GetOIDCURLRequest, ...grpc.CallOption) (*proto.GetOIDCURLResponse, error)
|
||||
}
|
||||
@@ -47,7 +43,7 @@ func (o OIDC) Authenticate(r *http.Request) (string, string, error) {
|
||||
// Check for the session_token query param (from OIDC redirects).
|
||||
// The management server passes the token in the URL because it cannot set
|
||||
// cookies for the proxy's domain (cookies are domain-scoped per RFC 6265).
|
||||
if token := r.URL.Query().Get(sessionTokenParam); token != "" {
|
||||
if token := r.URL.Query().Get("session_token"); token != "" {
|
||||
return token, "", nil
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ func (s *stubSessionValidator) ValidateTunnelPeer(_ context.Context, in *proto.V
|
||||
func newTunnelMiddleware(t *testing.T, validator SessionValidator) *Middleware {
|
||||
t.Helper()
|
||||
mw := NewMiddleware(log.New(), validator, nil)
|
||||
require.NoError(t, mw.AddDomain("svc.example", DomainSettings{AccountID: "acct-1", ServiceID: "svc-1"}))
|
||||
require.NoError(t, mw.AddDomain("svc.example", nil, "", 0, "acct-1", "svc-1", nil, false))
|
||||
return mw
|
||||
}
|
||||
|
||||
@@ -235,8 +235,8 @@ func TestForwardWithTunnelPeer_RoutesAccountIDIntoCacheKey(t *testing.T) {
|
||||
}
|
||||
mw := NewMiddleware(log.New(), validator, nil)
|
||||
|
||||
require.NoError(t, mw.AddDomain("svc-a.example", DomainSettings{AccountID: "acct-a", ServiceID: "svc-a"}))
|
||||
require.NoError(t, mw.AddDomain("svc-b.example", DomainSettings{AccountID: "acct-b", ServiceID: "svc-b"}))
|
||||
require.NoError(t, mw.AddDomain("svc-a.example", nil, "", 0, "acct-a", "svc-a", nil, false))
|
||||
require.NoError(t, mw.AddDomain("svc-b.example", nil, "", 0, "acct-b", "svc-b", nil, false))
|
||||
|
||||
// The fast-path requires the inbound-listener marker on the context.
|
||||
// The peerstore lookup itself is account-agnostic at this level
|
||||
@@ -299,7 +299,7 @@ func TestForwardWithTunnelPeer_LocalLookupShortCircuitDoesNotPopulateCache(t *te
|
||||
|
||||
func TestPrivateService_FailsClosedOnTunnelPeerFailure(t *testing.T) {
|
||||
mw := NewMiddleware(log.New(), nil, nil)
|
||||
require.NoError(t, mw.AddDomain("private.svc", DomainSettings{AccountID: "acct-1", ServiceID: "svc-1", Private: true}))
|
||||
require.NoError(t, mw.AddDomain("private.svc", nil, "", 0, "acct-1", "svc-1", nil, true))
|
||||
|
||||
called := false
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -328,7 +328,7 @@ func TestPrivateService_ForwardsOnTunnelPeerSuccess(t *testing.T) {
|
||||
},
|
||||
}
|
||||
mw := NewMiddleware(log.New(), validator, nil)
|
||||
require.NoError(t, mw.AddDomain("private.svc", DomainSettings{AccountID: "acct-1", ServiceID: "svc-1", Private: true}))
|
||||
require.NoError(t, mw.AddDomain("private.svc", nil, "", 0, "acct-1", "svc-1", nil, true))
|
||||
|
||||
called := false
|
||||
handler := mw.Protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
|
||||
@@ -21,8 +21,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/netbirdio/netbird/proxy/internal/netutil"
|
||||
)
|
||||
|
||||
// MaxRoutingScanBytes bounds how far ScanRoutingFields will read into a
|
||||
@@ -36,6 +34,7 @@ const MaxRoutingScanBytes int64 = 32 << 20
|
||||
// metadata key by the chain when a request body is not surfaced.
|
||||
const (
|
||||
BypassUpgradeHeader = "upgrade_header"
|
||||
BypassConnectionUpgrd = "connection_upgrade"
|
||||
BypassContentType = "content_type_not_allowed"
|
||||
BypassBudget = "capture_budget_exhausted"
|
||||
BypassNoConfig = "no_capture_config"
|
||||
@@ -126,13 +125,12 @@ func CaptureRequest(r *http.Request, cfg *Config, b Budget) (body []byte, trunca
|
||||
if cfg.MaxRequestBytes <= 0 {
|
||||
return nil, false, 0, BypassCapZero, release, nil
|
||||
}
|
||||
// The predicate has to be the forwarder's own: a looser one (either header
|
||||
// on its own) skips capture for requests the forwarder still delivers to
|
||||
// the upstream with their body intact, which hides them from every
|
||||
// deny-capable middleware in the chain.
|
||||
if netutil.IsUpgradeRequest(r.Header) {
|
||||
if r.Header.Get("Upgrade") != "" {
|
||||
return nil, false, 0, BypassUpgradeHeader, release, nil
|
||||
}
|
||||
if strings.EqualFold(r.Header.Get("Connection"), "upgrade") {
|
||||
return nil, false, 0, BypassConnectionUpgrd, release, nil
|
||||
}
|
||||
if !contentTypeAllowed(r.Header.Get("Content-Type"), cfg.ContentTypes) {
|
||||
return nil, false, 0, BypassContentType, release, nil
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/net/http/httpguts"
|
||||
)
|
||||
|
||||
// IsUpgradeRequest reports whether r is a protocol-upgrade request, using the
|
||||
// same predicate httputil.ReverseProxy applies when it decides to hand the
|
||||
// connection over instead of proxying normally.
|
||||
//
|
||||
// Matching the forwarder exactly matters for anything that inspects a request
|
||||
// before it is proxied: a looser test (an Upgrade header on its own, say) marks
|
||||
// a request as an upgrade and skips inspection, while the forwarder still
|
||||
// delivers it to the backend as an ordinary request with its body intact. That
|
||||
// gap is a body-inspection bypass reachable by adding one header.
|
||||
func IsUpgradeRequest(h http.Header) bool {
|
||||
if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
|
||||
return false
|
||||
}
|
||||
return h.Get("Upgrade") != ""
|
||||
}
|
||||
@@ -50,37 +50,6 @@ const (
|
||||
CrowdSecObserve CrowdSecMode = "observe"
|
||||
)
|
||||
|
||||
// AppSecMode is the per-service CrowdSec AppSec (WAF) enforcement mode.
|
||||
type AppSecMode string
|
||||
|
||||
const (
|
||||
// AppSecOff disables request inspection.
|
||||
AppSecOff AppSecMode = ""
|
||||
// AppSecEnforce blocks requests the engine flags, and fails closed when the
|
||||
// engine is unreachable.
|
||||
AppSecEnforce AppSecMode = "enforce"
|
||||
// AppSecObserve records the verdict without blocking.
|
||||
AppSecObserve AppSecMode = "observe"
|
||||
)
|
||||
|
||||
// ParseAppSecMode maps a wire value to an AppSecMode. Unrecognized values map
|
||||
// to AppSecOff so a typo never turns inspection into an unintended block.
|
||||
func ParseAppSecMode(s string) AppSecMode {
|
||||
switch AppSecMode(s) {
|
||||
case AppSecEnforce:
|
||||
return AppSecEnforce
|
||||
case AppSecObserve:
|
||||
return AppSecObserve
|
||||
default:
|
||||
return AppSecOff
|
||||
}
|
||||
}
|
||||
|
||||
// Enabled reports whether the mode asks for request inspection.
|
||||
func (m AppSecMode) Enabled() bool {
|
||||
return m == AppSecEnforce || m == AppSecObserve
|
||||
}
|
||||
|
||||
// Filter evaluates IP restrictions. CIDR checks are performed first
|
||||
// (cheap), followed by country lookups (more expensive) only when needed.
|
||||
type Filter struct {
|
||||
@@ -177,13 +146,6 @@ const (
|
||||
// DenyCrowdSecUnavailable indicates enforce mode but the bouncer has not
|
||||
// completed its initial sync.
|
||||
DenyCrowdSecUnavailable
|
||||
// DenyAppSecBan indicates a CrowdSec AppSec "ban" remediation.
|
||||
DenyAppSecBan
|
||||
// DenyAppSecCaptcha indicates a CrowdSec AppSec "captcha" remediation.
|
||||
DenyAppSecCaptcha
|
||||
// DenyAppSecUnavailable indicates enforce mode but the AppSec engine could
|
||||
// not produce a verdict (unreachable, timed out, or it rejected the call).
|
||||
DenyAppSecUnavailable
|
||||
)
|
||||
|
||||
// String returns the deny reason string matching the HTTP auth mechanism names.
|
||||
@@ -205,12 +167,6 @@ func (v Verdict) String() string {
|
||||
return "crowdsec_throttle"
|
||||
case DenyCrowdSecUnavailable:
|
||||
return "crowdsec_unavailable"
|
||||
case DenyAppSecBan:
|
||||
return "appsec_ban"
|
||||
case DenyAppSecCaptcha:
|
||||
return "appsec_captcha"
|
||||
case DenyAppSecUnavailable:
|
||||
return "appsec_unavailable"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
@@ -226,16 +182,6 @@ func (v Verdict) IsCrowdSec() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// IsAppSec returns true when the verdict originates from an AppSec inspection.
|
||||
func (v Verdict) IsAppSec() bool {
|
||||
switch v {
|
||||
case DenyAppSecBan, DenyAppSecCaptcha, DenyAppSecUnavailable:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsObserveOnly returns true when v is a CrowdSec verdict and the filter is in
|
||||
// observe mode. Callers should log the verdict but not block the request.
|
||||
func (f *Filter) IsObserveOnly(v Verdict) bool {
|
||||
|
||||
@@ -126,23 +126,6 @@ type Config struct {
|
||||
// CrowdSecAPIKey is the CrowdSec bouncer API key. Empty disables
|
||||
// CrowdSec.
|
||||
CrowdSecAPIKey string
|
||||
// CrowdSecAppSecURL is the CrowdSec AppSec (WAF) endpoint. Empty disables
|
||||
// HTTP request inspection.
|
||||
CrowdSecAppSecURL string
|
||||
// CrowdSecAppSecTimeout bounds a single AppSec inspection call. Zero falls
|
||||
// back to the internal default.
|
||||
CrowdSecAppSecTimeout time.Duration
|
||||
// CrowdSecAppSecMaxBodyBytes caps the request body mirrored to AppSec.
|
||||
// Zero falls back to the internal default; negative forwards no body.
|
||||
CrowdSecAppSecMaxBodyBytes int64
|
||||
// CrowdSecAppSecMaxConcurrent bounds AppSec inspections in flight toward
|
||||
// the engine. Zero falls back to the internal default; negative removes
|
||||
// the bound.
|
||||
CrowdSecAppSecMaxConcurrent int
|
||||
// MiddlewareCaptureBudgetBytes bounds the total request-body buffering in
|
||||
// flight across the proxy, shared by AppSec inspection and the
|
||||
// agent-network capture. Zero falls back to the internal default.
|
||||
MiddlewareCaptureBudgetBytes int64
|
||||
}
|
||||
|
||||
// New builds a Server from cfg without performing any I/O. No goroutines
|
||||
@@ -152,47 +135,42 @@ type Config struct {
|
||||
// directly) byte-for-byte equivalent.
|
||||
func New(ctx context.Context, cfg Config) *Server {
|
||||
return &Server{
|
||||
ctx: ctx,
|
||||
ListenAddr: cfg.ListenAddr,
|
||||
ID: cfg.ID,
|
||||
Logger: cfg.Logger,
|
||||
Version: cfg.Version,
|
||||
ProxyURL: cfg.ProxyURL,
|
||||
ManagementAddress: cfg.ManagementAddress,
|
||||
ProxyToken: cfg.ProxyToken,
|
||||
CertificateDirectory: cfg.CertificateDirectory,
|
||||
CertificateFile: cfg.CertificateFile,
|
||||
CertificateKeyFile: cfg.CertificateKeyFile,
|
||||
GenerateACMECertificates: cfg.GenerateACMECertificates,
|
||||
ACMEChallengeAddress: cfg.ACMEChallengeAddress,
|
||||
ACMEDirectory: cfg.ACMEDirectory,
|
||||
ACMEEABKID: cfg.ACMEEABKID,
|
||||
ACMEEABHMACKey: cfg.ACMEEABHMACKey,
|
||||
ACMEChallengeType: cfg.ACMEChallengeType,
|
||||
CertLockMethod: cfg.CertLockMethod,
|
||||
WildcardCertDir: cfg.WildcardCertDir,
|
||||
DebugEndpointEnabled: cfg.DebugEndpointEnabled,
|
||||
DebugEndpointAddress: cfg.DebugEndpointAddress,
|
||||
HealthAddress: cfg.HealthAddr,
|
||||
ForwardedProto: cfg.ForwardedProto,
|
||||
TrustedProxies: cfg.TrustedProxies,
|
||||
WireguardPort: cfg.WireguardPort,
|
||||
ProxyProtocol: cfg.ProxyProtocol,
|
||||
PreSharedKey: cfg.PreSharedKey,
|
||||
Performance: cfg.Performance,
|
||||
SupportsCustomPorts: cfg.SupportsCustomPorts,
|
||||
RequireSubdomain: cfg.RequireSubdomain,
|
||||
Private: cfg.Private,
|
||||
MaxDialTimeout: cfg.MaxDialTimeout,
|
||||
MaxSessionIdleTimeout: cfg.MaxSessionIdleTimeout,
|
||||
MappingBatchWatchdog: cfg.MappingBatchWatchdog,
|
||||
GeoDataDir: cfg.GeoDataDir,
|
||||
CrowdSecAPIURL: cfg.CrowdSecAPIURL,
|
||||
CrowdSecAPIKey: cfg.CrowdSecAPIKey,
|
||||
CrowdSecAppSecURL: cfg.CrowdSecAppSecURL,
|
||||
CrowdSecAppSecTimeout: cfg.CrowdSecAppSecTimeout,
|
||||
CrowdSecAppSecMaxBodyBytes: cfg.CrowdSecAppSecMaxBodyBytes,
|
||||
CrowdSecAppSecMaxConcurrent: cfg.CrowdSecAppSecMaxConcurrent,
|
||||
MiddlewareCaptureBudgetBytes: cfg.MiddlewareCaptureBudgetBytes,
|
||||
ctx: ctx,
|
||||
ListenAddr: cfg.ListenAddr,
|
||||
ID: cfg.ID,
|
||||
Logger: cfg.Logger,
|
||||
Version: cfg.Version,
|
||||
ProxyURL: cfg.ProxyURL,
|
||||
ManagementAddress: cfg.ManagementAddress,
|
||||
ProxyToken: cfg.ProxyToken,
|
||||
CertificateDirectory: cfg.CertificateDirectory,
|
||||
CertificateFile: cfg.CertificateFile,
|
||||
CertificateKeyFile: cfg.CertificateKeyFile,
|
||||
GenerateACMECertificates: cfg.GenerateACMECertificates,
|
||||
ACMEChallengeAddress: cfg.ACMEChallengeAddress,
|
||||
ACMEDirectory: cfg.ACMEDirectory,
|
||||
ACMEEABKID: cfg.ACMEEABKID,
|
||||
ACMEEABHMACKey: cfg.ACMEEABHMACKey,
|
||||
ACMEChallengeType: cfg.ACMEChallengeType,
|
||||
CertLockMethod: cfg.CertLockMethod,
|
||||
WildcardCertDir: cfg.WildcardCertDir,
|
||||
DebugEndpointEnabled: cfg.DebugEndpointEnabled,
|
||||
DebugEndpointAddress: cfg.DebugEndpointAddress,
|
||||
HealthAddress: cfg.HealthAddr,
|
||||
ForwardedProto: cfg.ForwardedProto,
|
||||
TrustedProxies: cfg.TrustedProxies,
|
||||
WireguardPort: cfg.WireguardPort,
|
||||
ProxyProtocol: cfg.ProxyProtocol,
|
||||
PreSharedKey: cfg.PreSharedKey,
|
||||
Performance: cfg.Performance,
|
||||
SupportsCustomPorts: cfg.SupportsCustomPorts,
|
||||
RequireSubdomain: cfg.RequireSubdomain,
|
||||
Private: cfg.Private,
|
||||
MaxDialTimeout: cfg.MaxDialTimeout,
|
||||
MaxSessionIdleTimeout: cfg.MaxSessionIdleTimeout,
|
||||
MappingBatchWatchdog: cfg.MappingBatchWatchdog,
|
||||
GeoDataDir: cfg.GeoDataDir,
|
||||
CrowdSecAPIURL: cfg.CrowdSecAPIURL,
|
||||
CrowdSecAPIKey: cfg.CrowdSecAPIKey,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// New maps Config onto Server field by field, and a field left out of that
|
||||
// literal still compiles: the knob is simply parsed and then dropped, so an
|
||||
// operator setting it sees the default with no error anywhere. These assertions
|
||||
// are the only thing standing between a new setting and that silent no-op.
|
||||
func TestNew_ForwardsOperatorTuning(t *testing.T) {
|
||||
cfg := Config{
|
||||
ManagementAddress: "http://localhost:8080",
|
||||
ProxyToken: "token",
|
||||
CrowdSecAPIURL: "http://crowdsec:8080/",
|
||||
CrowdSecAPIKey: "key",
|
||||
CrowdSecAppSecURL: "http://crowdsec:7422/",
|
||||
CrowdSecAppSecTimeout: 321 * time.Millisecond,
|
||||
CrowdSecAppSecMaxBodyBytes: 4321,
|
||||
CrowdSecAppSecMaxConcurrent: 17,
|
||||
MiddlewareCaptureBudgetBytes: 5 << 20,
|
||||
MaxDialTimeout: 7 * time.Second,
|
||||
MaxSessionIdleTimeout: 11 * time.Second,
|
||||
GeoDataDir: "/var/lib/geo",
|
||||
}
|
||||
|
||||
srv := New(context.Background(), cfg)
|
||||
require.NotNil(t, srv)
|
||||
|
||||
assert.Equal(t, cfg.CrowdSecAPIURL, srv.CrowdSecAPIURL)
|
||||
assert.Equal(t, cfg.CrowdSecAPIKey, srv.CrowdSecAPIKey)
|
||||
assert.Equal(t, cfg.CrowdSecAppSecURL, srv.CrowdSecAppSecURL)
|
||||
assert.Equal(t, cfg.CrowdSecAppSecTimeout, srv.CrowdSecAppSecTimeout)
|
||||
assert.Equal(t, cfg.CrowdSecAppSecMaxBodyBytes, srv.CrowdSecAppSecMaxBodyBytes)
|
||||
assert.Equal(t, cfg.CrowdSecAppSecMaxConcurrent, srv.CrowdSecAppSecMaxConcurrent)
|
||||
assert.Equal(t, cfg.MiddlewareCaptureBudgetBytes, srv.MiddlewareCaptureBudgetBytes)
|
||||
assert.Equal(t, cfg.MaxDialTimeout, srv.MaxDialTimeout)
|
||||
assert.Equal(t, cfg.MaxSessionIdleTimeout, srv.MaxSessionIdleTimeout)
|
||||
assert.Equal(t, cfg.GeoDataDir, srv.GeoDataDir)
|
||||
}
|
||||
@@ -240,10 +240,6 @@ func (m *testProxyManager) ClusterSupportsCrowdSec(_ context.Context, _ string)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *testProxyManager) ClusterSupportsAppSec(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *testProxyManager) ClusterSupportsPrivate(_ context.Context, _ string) *bool {
|
||||
return nil
|
||||
}
|
||||
@@ -566,11 +562,16 @@ func TestIntegration_ProxyConnection_ReconnectDoesNotDuplicateState(t *testing.T
|
||||
addMappingCalls.Add(1)
|
||||
|
||||
// Apply to real auth middleware (idempotent)
|
||||
err := authMw.AddDomain(mapping.GetDomain(), auth.DomainSettings{
|
||||
AccountID: proxytypes.AccountID(mapping.GetAccountId()),
|
||||
ServiceID: proxytypes.ServiceID(mapping.GetId()),
|
||||
Private: mapping.GetPrivate(),
|
||||
})
|
||||
err := authMw.AddDomain(
|
||||
mapping.GetDomain(),
|
||||
nil,
|
||||
"",
|
||||
0,
|
||||
proxytypes.AccountID(mapping.GetAccountId()),
|
||||
proxytypes.ServiceID(mapping.GetId()),
|
||||
nil,
|
||||
mapping.GetPrivate(),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Apply to real proxy (idempotent)
|
||||
|
||||
102
proxy/server.go
102
proxy/server.go
@@ -45,7 +45,6 @@ import (
|
||||
"github.com/netbirdio/netbird/client/embed"
|
||||
"github.com/netbirdio/netbird/proxy/internal/accesslog"
|
||||
"github.com/netbirdio/netbird/proxy/internal/acme"
|
||||
"github.com/netbirdio/netbird/proxy/internal/appsec"
|
||||
"github.com/netbirdio/netbird/proxy/internal/auth"
|
||||
"github.com/netbirdio/netbird/proxy/internal/certwatch"
|
||||
"github.com/netbirdio/netbird/proxy/internal/conntrack"
|
||||
@@ -127,10 +126,6 @@ type Server struct {
|
||||
crowdsecMu sync.Mutex
|
||||
crowdsecServices map[types.ServiceID]bool
|
||||
|
||||
// appsecClient is the shared CrowdSec AppSec client, nil when no AppSec
|
||||
// endpoint is configured. Stateless, so it needs no per-service lifecycle.
|
||||
appsecClient *appsec.Client
|
||||
|
||||
// routerReady is closed once mainRouter is fully initialized.
|
||||
// The mapping worker waits on this before processing updates.
|
||||
routerReady chan struct{}
|
||||
@@ -243,20 +238,6 @@ type Server struct {
|
||||
CrowdSecAPIURL string
|
||||
// CrowdSecAPIKey is the CrowdSec bouncer API key. Empty disables CrowdSec.
|
||||
CrowdSecAPIKey string
|
||||
// CrowdSecAppSecURL is the CrowdSec AppSec (WAF) endpoint, e.g.
|
||||
// http://127.0.0.1:7422/. Empty disables request inspection. Requires
|
||||
// CrowdSecAPIKey, which the AppSec component validates against LAPI.
|
||||
CrowdSecAppSecURL string
|
||||
// CrowdSecAppSecTimeout bounds a single AppSec inspection call.
|
||||
// Zero means appsec.DefaultTimeout.
|
||||
CrowdSecAppSecTimeout time.Duration
|
||||
// CrowdSecAppSecMaxBodyBytes caps the request body mirrored to the AppSec
|
||||
// engine. Zero means appsec.DefaultMaxBodyBytes; negative disables body
|
||||
// forwarding, leaving header and URI inspection.
|
||||
CrowdSecAppSecMaxBodyBytes int64
|
||||
// CrowdSecAppSecMaxConcurrent bounds AppSec inspections in flight. Zero
|
||||
// means appsec.DefaultMaxConcurrent; negative removes the bound.
|
||||
CrowdSecAppSecMaxConcurrent int
|
||||
// MaxSessionIdleTimeout caps the per-service session idle timeout.
|
||||
// Zero means no cap (the proxy honors whatever management sends).
|
||||
// Set via NB_PROXY_MAX_SESSION_IDLE_TIMEOUT for shared deployments.
|
||||
@@ -403,13 +384,6 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
|
||||
s.crowdsecRegistry = crowdsec.NewRegistry(s.CrowdSecAPIURL, s.CrowdSecAPIKey, log.NewEntry(s.Logger))
|
||||
s.crowdsecServices = make(map[types.ServiceID]bool)
|
||||
// Must precede the mapping worker: the worker opens the management stream
|
||||
// and reports proxyCapabilities, which reads appsecClient. Building it
|
||||
// afterwards would both race the read and, when the worker won, advertise
|
||||
// the proxy as AppSec-incapable for the lifetime of that stream.
|
||||
if err := s.initAppSec(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go s.newManagementMappingWorker(runCtx, s.mgmtClient)
|
||||
|
||||
@@ -437,7 +411,6 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
}()
|
||||
|
||||
s.auth = auth.NewMiddleware(s.Logger, s.mgmtClient, s.geo)
|
||||
s.auth.SetAppSec(s.appsecClient)
|
||||
s.accessLog = accesslog.NewLogger(s.mgmtClient, s.Logger, s.TrustedProxies)
|
||||
|
||||
s.startDebugEndpoint()
|
||||
@@ -1301,7 +1274,6 @@ func (s *Server) newManagementMappingWorker(ctx context.Context, client proto.Pr
|
||||
|
||||
func (s *Server) proxyCapabilities() *proto.ProxyCapabilities {
|
||||
supportsCrowdSec := s.crowdsecRegistry.Available()
|
||||
supportsAppSec := s.appsecClient != nil
|
||||
privateCapability := s.Private
|
||||
// Always true: this build enforces ProxyMapping.private via the auth middleware.
|
||||
supportsPrivateService := true
|
||||
@@ -1309,7 +1281,6 @@ func (s *Server) proxyCapabilities() *proto.ProxyCapabilities {
|
||||
SupportsCustomPorts: &s.SupportsCustomPorts,
|
||||
RequireSubdomain: &s.RequireSubdomain,
|
||||
SupportsCrowdsec: &supportsCrowdSec,
|
||||
SupportsAppsec: &supportsAppSec,
|
||||
Private: &privateCapability,
|
||||
SupportsPrivateService: &supportsPrivateService,
|
||||
}
|
||||
@@ -1937,67 +1908,6 @@ func (s *Server) parseRestrictions(mapping *proto.ProxyMapping) *restrict.Filter
|
||||
})
|
||||
}
|
||||
|
||||
// initAppSec builds the shared AppSec client when an endpoint is configured.
|
||||
// A configured-but-invalid endpoint is a startup error rather than a silent
|
||||
// downgrade: services asking for enforce would otherwise fail closed on every
|
||||
// request with no indication why.
|
||||
//
|
||||
// Runs before the management stream opens so the reported capability is stable;
|
||||
// the auth middleware picks the client up separately once it exists.
|
||||
func (s *Server) initAppSec() error {
|
||||
if s.CrowdSecAppSecURL == "" {
|
||||
return nil
|
||||
}
|
||||
if s.CrowdSecAPIKey == "" {
|
||||
return errors.New("crowdsec appsec url is set but the crowdsec api key is empty")
|
||||
}
|
||||
|
||||
// Share the middleware capture budget rather than opening a second pool:
|
||||
// AppSec buffers before authentication, so its ceiling has to count against
|
||||
// the same proxy-wide allowance the body tap draws from.
|
||||
var budget appsec.Budget
|
||||
if s.middlewareManager != nil {
|
||||
budget = s.middlewareManager.Budget()
|
||||
}
|
||||
|
||||
client, err := appsec.New(appsec.Config{
|
||||
URL: s.CrowdSecAppSecURL,
|
||||
APIKey: s.CrowdSecAPIKey,
|
||||
Timeout: s.CrowdSecAppSecTimeout,
|
||||
MaxBodyBytes: s.CrowdSecAppSecMaxBodyBytes,
|
||||
MaxConcurrent: s.CrowdSecAppSecMaxConcurrent,
|
||||
Budget: budget,
|
||||
Logger: log.NewEntry(s.Logger),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("init crowdsec appsec: %w", err)
|
||||
}
|
||||
|
||||
s.appsecClient = client
|
||||
s.Logger.Infof("CrowdSec AppSec inspection available at %s", s.CrowdSecAppSecURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// appSecMode resolves the per-service AppSec mode. A service asking for
|
||||
// inspection on a proxy with no AppSec endpoint keeps its mode so the auth
|
||||
// middleware fails closed for enforce, mirroring the CrowdSec behavior.
|
||||
func (s *Server) appSecMode(mapping *proto.ProxyMapping) restrict.AppSecMode {
|
||||
raw := mapping.GetAccessRestrictions().GetAppsecMode()
|
||||
mode := restrict.ParseAppSecMode(raw)
|
||||
// An unrecognized value disables inspection, which is the safe default but a
|
||||
// silent one: with a newer management and an older proxy, a mode this build
|
||||
// does not know would look identical to "off" on a service the operator set
|
||||
// to enforce. Say so rather than leaving it to be discovered.
|
||||
if mode == restrict.AppSecOff && raw != "" && raw != "off" {
|
||||
s.Logger.Warnf("service %s requests unrecognized AppSec mode %q; this build supports %q and %q, so inspection is disabled",
|
||||
mapping.GetId(), raw, restrict.AppSecEnforce, restrict.AppSecObserve)
|
||||
}
|
||||
if mode.Enabled() && s.appsecClient == nil {
|
||||
s.Logger.Warnf("service %s requests AppSec mode %q but proxy has no AppSec endpoint configured", mapping.GetId(), mode)
|
||||
}
|
||||
return mode
|
||||
}
|
||||
|
||||
// releaseCrowdSec releases the CrowdSec bouncer reference for the given
|
||||
// service if it had one.
|
||||
func (s *Server) releaseCrowdSec(svcID types.ServiceID) {
|
||||
@@ -2164,17 +2074,7 @@ func (s *Server) updateMapping(ctx context.Context, mapping *proto.ProxyMapping)
|
||||
s.warnIfGeoUnavailable(mapping.GetDomain(), mapping.GetAccessRestrictions())
|
||||
|
||||
maxSessionAge := time.Duration(mapping.GetAuth().GetMaxSessionAgeSeconds()) * time.Second
|
||||
settings := auth.DomainSettings{
|
||||
Schemes: schemes,
|
||||
SessionPublicKey: mapping.GetAuth().GetSessionKey(),
|
||||
SessionExpiration: maxSessionAge,
|
||||
AccountID: accountID,
|
||||
ServiceID: svcID,
|
||||
IPRestrictions: ipRestrictions,
|
||||
Private: mapping.GetPrivate(),
|
||||
AppSecMode: s.appSecMode(mapping),
|
||||
}
|
||||
if err := s.auth.AddDomain(mapping.GetDomain(), settings); err != nil {
|
||||
if err := s.auth.AddDomain(mapping.GetDomain(), schemes, mapping.GetAuth().GetSessionKey(), maxSessionAge, accountID, svcID, ipRestrictions, mapping.GetPrivate()); err != nil {
|
||||
return fmt.Errorf("auth setup for domain %s: %w", mapping.GetDomain(), err)
|
||||
}
|
||||
m := s.protoToMapping(ctx, mapping)
|
||||
|
||||
@@ -3379,18 +3379,6 @@ components:
|
||||
- "observe"
|
||||
default: "off"
|
||||
description: CrowdSec IP reputation mode. Only available when the proxy cluster supports CrowdSec.
|
||||
appsec_mode:
|
||||
type: string
|
||||
enum:
|
||||
- "off"
|
||||
- "enforce"
|
||||
- "observe"
|
||||
default: "off"
|
||||
description: >-
|
||||
CrowdSec AppSec (WAF) request inspection mode. Only available when
|
||||
the proxy cluster supports AppSec, and only applied to HTTP
|
||||
services. "enforce" blocks requests the WAF flags; "observe" records
|
||||
the verdict in the access log without blocking.
|
||||
PasswordAuthConfig:
|
||||
type: object
|
||||
properties:
|
||||
@@ -3527,10 +3515,6 @@ components:
|
||||
type: boolean
|
||||
description: Whether all active proxies in the cluster have CrowdSec configured
|
||||
example: false
|
||||
supports_appsec:
|
||||
type: boolean
|
||||
description: Whether all active proxies in the cluster have a CrowdSec AppSec (WAF) endpoint configured
|
||||
example: false
|
||||
private:
|
||||
type: boolean
|
||||
description: True when at least one connected proxy in this cluster is running embedded in a netbird client (`netbird proxy`) and serving over a WireGuard tunnel. Lets the dashboard distinguish per-peer / private clusters from centralised ones.
|
||||
@@ -3590,10 +3574,6 @@ components:
|
||||
type: boolean
|
||||
description: Whether the proxy cluster has CrowdSec configured
|
||||
example: false
|
||||
supports_appsec:
|
||||
type: boolean
|
||||
description: Whether the proxy cluster has a CrowdSec AppSec (WAF) endpoint configured
|
||||
example: false
|
||||
supports_private:
|
||||
type: boolean
|
||||
description: Whether the proxy cluster supports private (NetBird-only) services. True when at least one connected proxy in the cluster runs embedded in a netbird client.
|
||||
|
||||
@@ -17,27 +17,6 @@ const (
|
||||
TokenAuthScopes tokenAuthContextKey = "TokenAuth.Scopes"
|
||||
)
|
||||
|
||||
// Defines values for AccessRestrictionsAppsecMode.
|
||||
const (
|
||||
AccessRestrictionsAppsecModeEnforce AccessRestrictionsAppsecMode = "enforce"
|
||||
AccessRestrictionsAppsecModeObserve AccessRestrictionsAppsecMode = "observe"
|
||||
AccessRestrictionsAppsecModeOff AccessRestrictionsAppsecMode = "off"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the AccessRestrictionsAppsecMode enum.
|
||||
func (e AccessRestrictionsAppsecMode) Valid() bool {
|
||||
switch e {
|
||||
case AccessRestrictionsAppsecModeEnforce:
|
||||
return true
|
||||
case AccessRestrictionsAppsecModeObserve:
|
||||
return true
|
||||
case AccessRestrictionsAppsecModeOff:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for AccessRestrictionsCrowdsecMode.
|
||||
const (
|
||||
AccessRestrictionsCrowdsecModeEnforce AccessRestrictionsCrowdsecMode = "enforce"
|
||||
@@ -1561,9 +1540,6 @@ type AccessRestrictions struct {
|
||||
// AllowedCountries ISO 3166-1 alpha-2 country codes to allow. If non-empty, only these countries are permitted.
|
||||
AllowedCountries *[]string `json:"allowed_countries,omitempty"`
|
||||
|
||||
// AppsecMode CrowdSec AppSec (WAF) request inspection mode. Only available when the proxy cluster supports AppSec, and only applied to HTTP services. "enforce" blocks requests the WAF flags; "observe" records the verdict in the access log without blocking.
|
||||
AppsecMode *AccessRestrictionsAppsecMode `json:"appsec_mode,omitempty"`
|
||||
|
||||
// BlockedCidrs CIDR blocklist. Connections from these CIDRs are rejected. Evaluated after allowed_cidrs.
|
||||
BlockedCidrs *[]string `json:"blocked_cidrs,omitempty"`
|
||||
|
||||
@@ -1574,9 +1550,6 @@ type AccessRestrictions struct {
|
||||
CrowdsecMode *AccessRestrictionsCrowdsecMode `json:"crowdsec_mode,omitempty"`
|
||||
}
|
||||
|
||||
// AccessRestrictionsAppsecMode CrowdSec AppSec (WAF) request inspection mode. Only available when the proxy cluster supports AppSec, and only applied to HTTP services. "enforce" blocks requests the WAF flags; "observe" records the verdict in the access log without blocking.
|
||||
type AccessRestrictionsAppsecMode string
|
||||
|
||||
// AccessRestrictionsCrowdsecMode CrowdSec IP reputation mode. Only available when the proxy cluster supports CrowdSec.
|
||||
type AccessRestrictionsCrowdsecMode string
|
||||
|
||||
@@ -4755,9 +4728,6 @@ type ProxyCluster struct {
|
||||
// RequireSubdomain Whether services on this cluster must include a subdomain label
|
||||
RequireSubdomain *bool `json:"require_subdomain,omitempty"`
|
||||
|
||||
// SupportsAppsec Whether all active proxies in the cluster have a CrowdSec AppSec (WAF) endpoint configured
|
||||
SupportsAppsec *bool `json:"supports_appsec,omitempty"`
|
||||
|
||||
// SupportsCrowdsec Whether all active proxies in the cluster have CrowdSec configured
|
||||
SupportsCrowdsec *bool `json:"supports_crowdsec,omitempty"`
|
||||
|
||||
@@ -4826,9 +4796,6 @@ type ReverseProxyDomain struct {
|
||||
// RequireSubdomain Whether a subdomain label is required in front of this domain. When true, the domain cannot be used bare.
|
||||
RequireSubdomain *bool `json:"require_subdomain,omitempty"`
|
||||
|
||||
// SupportsAppsec Whether the proxy cluster has a CrowdSec AppSec (WAF) endpoint configured
|
||||
SupportsAppsec *bool `json:"supports_appsec,omitempty"`
|
||||
|
||||
// SupportsCrowdsec Whether the proxy cluster has CrowdSec configured
|
||||
SupportsCrowdsec *bool `json:"supports_crowdsec,omitempty"`
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -73,10 +73,6 @@ message ProxyCapabilities {
|
||||
optional bool private = 4;
|
||||
// Whether the proxy enforces ProxyMapping.private (fails closed on ValidateTunnelPeer failure). Management MUST NOT stream private mappings to proxies that don't claim this.
|
||||
optional bool supports_private_service = 5;
|
||||
// Whether the proxy has a CrowdSec AppSec (WAF) endpoint configured and can
|
||||
// inspect HTTP requests. Independent of supports_crowdsec: AppSec is a
|
||||
// separate endpoint on the Security Engine and applies to HTTP services only.
|
||||
optional bool supports_appsec = 6;
|
||||
}
|
||||
|
||||
// GetMappingUpdateRequest is sent to initialise a mapping stream.
|
||||
@@ -207,10 +203,6 @@ message AccessRestrictions {
|
||||
repeated string blocked_countries = 4;
|
||||
// CrowdSec IP reputation mode: "", "off", "enforce", or "observe".
|
||||
string crowdsec_mode = 5;
|
||||
// CrowdSec AppSec (WAF) request inspection mode: "", "off", "enforce", or
|
||||
// "observe". HTTP services only: "enforce" and "observe" are rejected at
|
||||
// validation for TCP/UDP/TLS services, which carry no requests to inspect.
|
||||
string appsec_mode = 7;
|
||||
}
|
||||
|
||||
message ProxyMapping {
|
||||
|
||||
Reference in New Issue
Block a user