✨ skip the AppSec query for excluded locations (#413)

* ✨ skip the AppSec query for excluded locations

Refs #393.

crowdsecAppsecExcludedLocations lists paths (/healthz, any host) or
host/path entries (registry.example.com/v2/) whose requests are not sent
to AppSec. LAPI decisions still apply. An entry matches its exact path or
anything below it on a / boundary; the host is compared like Traefik's
Host matcher (case-insensitive, without port or trailing dot).

A request is only excluded when its path has a single reading: no
percent-encoding left, no dot or empty segment, no ; \ % * or non-ASCII.
Anything else is inspected as before, so ..;, %2F, double encoding and
similar tricks cannot reach another resource uninspected, whatever
sanitizePath is set to. /crowdsec-internal/challenge/ is always sent to
AppSec.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* 🍱 authorize just host and host:port

* 🍱 fix last bugz

* 🍱 fix comments

* 🍱 revert readme update

* 🍱 typo

* Update README.md

Co-authored-by: mathieuHa <mathieu@hanotaux.fr>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-07 13:37:54 +01:00
1 parent 0ceb2301f6
commit b642d2b211
8 files changed
+330 -6

No files matched your search

+2
View File
@@ -31,6 +31,7 @@ linters-settings:
- $gostd
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/logger
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/location
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/configuration
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/cache
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/captcha
@@ -44,6 +45,7 @@ linters-settings:
- github.com/maxlerebourg/simpleredis
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/logger
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/location
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/configuration
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/cache
- github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/captcha
+57 -1
View File
@@ -318,7 +318,7 @@ make run
>
> If you define different caches for different middlewares, only the first one to be instantiated will be bound to the crowdsec stream.
>
> Overall, this middleware is designed in such a way that **only one instance of the plugin is _possible_.** You can have multiple crowdsec middlewares in the same cluster, the key parameters must be aligned (MetricsUpdateIntervalSeconds, CrowdsecMode, CrowdsecAppsecEnabled, etc.)
> Overall, this middleware is designed in such a way that **only one instance of the plugin is _possible_.** You can have multiple crowdsec middlewares in the same cluster, the key parameters must be aligned (MetricsUpdateIntervalSeconds, CrowdsecMode, etc.). The `CrowdsecAppsec*` options are the exception: each middleware uses its own, so a router can use a middleware with `crowdsecAppsecEnabled: false` next to routers that use AppSec.
> [!WARNING]
> **Appsec maximum body limit is defaulted to 10MB** > _Be careful when you upgrade to >1.4.x_
@@ -390,6 +390,10 @@ make run
- bool
- default: true
- Behaviour when the request body cannot be buffered for inspection (HTTP/2 or HTTP/3 request without a `Content-Length`, typically a bidirectional gRPC stream). When `false` the request is forwarded to the Appsec Server with headers only (the body is left to stream through untouched). When `true` the request is blocked outright. Mirrors the reference bouncers' `APPSEC_DROP_UNREADABLE_BODY` option.
- CrowdsecAppsecExcludedLocations
- []string
- default: []
- Requests to these locations are not sent to the Appsec Server, while LAPI decisions still apply to them. An entry is a path such as `/healthz`, which applies to every host, or a host optionally followed by a path, such as `registry.example.com` for every path on that host, or `registry.example.com/v2/`. Read [AppSec excluded locations](#appsec-excluded-locations) before using it: every entry is a WAF bypass.
- CrowdsecAppsecKey
- string
- default: value of `CrowdsecLapiKey`
@@ -633,6 +637,9 @@ http:
crowdsecAppsecUnreachableBlock: true
crowdsecAppsecBodyLimit: 10485760
crowdsecAppsecUnreadableBodyBlock: false
crowdsecAppsecExcludedLocations:
- /healthz
- registry.example.com/v2/
crowdsecLapiKey: privateKey-foo
crowdsecLapiScheme: http
crowdsecLapiHost: crowdsec:8080
@@ -762,6 +769,55 @@ Set `crowdsecAppsecScheme` to `https`. Same three options as for the LAPI, prefi
Currently AppSec does not support mTLS authentication for the AppSec Component.
#### AppSec excluded locations
`crowdsecAppsecExcludedLocations` skips the AppSec query for some requests, for example
large uploads or machine-to-machine APIs where the rules mostly raise false positives:
the body is neither buffered nor sent to AppSec and `crowdsecAppsecUnreadableBodyBlock`
does not apply, while LAPI decisions (ban, captcha) still do. This differs from
`EXCLUDE_LOCATION` in the nginx and HAProxy Lua bouncers, which skips the whole bouncer,
and in `crowdsecMode: appsec` there is no LAPI check, so an excluded request is not
checked at all. For an entry with a path, a request is only excluded when its path can be
read one way only: no percent-encoding, no `.`, `..` or empty segment, no segment made only
of dots, and only ASCII letters, digits and `-._~!$&'()+,=:@/`. So `/healthz/..;/admin`,
`/healthz%2F..%2Fadmin` or `/healthz/%252e%252e/admin` are inspected, not excluded, with
`sanitizePath: false` too.
```yaml
crowdsecAppsecExcludedLocations:
- /healthz
- registry.example.com/v2/
```
- `/healthz` matches `/healthz` and everything below it, such as `/healthz/live`, but not
`/healthzfoo`. An entry ending with `/`, such as `/v2/`, only matches below it.
- An entry without a host applies to every host. An entry that is only a host, such as
`registry.example.com`, matches every path on that host. The host is compared
case-insensitively, without a trailing dot. An entry with a port, such as
`registry.example.com:8000`, only matches requests whose `Host` carries that port; an
entry without a port matches any port. There are no wildcards or regular expressions.
- The path is case-sensitive, and the query string is ignored.
- The path is the one the middleware receives. A middleware that runs before it, such as
`stripPrefix`, changes what is matched.
- `/crowdsec-internal/challenge/` is always sent to AppSec, so bot detection keeps working
on an excluded host.
> [!WARNING]
> Every entry is a WAF bypass for everything below it.
>
> - **The exclusion matches requests, not routers.** Any router that receives a matching
> host and path skips AppSec, including a catch-all router such as ``PathPrefix(`/`)``
> or a `HostRegexp` that also answers that host. Entries without a host apply to every
> router that uses the middleware, so `/v2/` would exclude the `/v2/` API of every
> application. Prefer the narrowest entries, bound to a host.
> - **AppSec never sees excluded requests**, so neither in-band nor out-of-band rules,
> nor the scenarios built on AppSec events, can react to them. Scenarios that read
> Traefik's access logs still see them.
> - Some backends take the path from a request header such as `X-Original-URL` or
> `X-Rewrite-URL`. Behind such a backend, a request to an excluded path can reach
> another resource uninspected. AppSec does not route on these headers either, so
> strip them in front of such a backend whether or not you exclude anything.
#### AppSec bot detection: route `/crowdsec-internal`
When AppSec bot detection is enabled, the challenge page it returns loads its fingerprint
+13 -1
View File
@@ -23,6 +23,7 @@ import (
captcha "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/captcha"
configuration "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/configuration"
ip "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip"
location "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/location"
logger "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/logger"
)
@@ -102,6 +103,7 @@ type Bouncer struct {
appsecUnreachableBlock bool
appsecUnreadableBodyBlock bool
appsecBodyLimit int64
appsecExcludedLocations *location.Matcher
crowdsecScheme string
crowdsecHost string
crowdsecPath string
@@ -162,6 +164,7 @@ func New(_ context.Context, next http.Handler, config *configuration.Config, nam
serverChecker, _ := ip.NewChecker(log, config.ForwardedHeadersTrustedIPs)
clientChecker, _ := ip.NewChecker(log, config.ClientTrustedIPs)
appsecExcludedLocations, _ := location.NewMatcher(config.CrowdsecAppsecExcludedLocations)
var tlsAppsecConfig *tls.Config
if config.CrowdsecAppsecEnabled {
@@ -233,6 +236,7 @@ func New(_ context.Context, next http.Handler, config *configuration.Config, nam
appsecUnreachableBlock: config.CrowdsecAppsecUnreachableBlock,
appsecUnreadableBodyBlock: config.CrowdsecAppsecUnreadableBodyBlock,
appsecBodyLimit: config.CrowdsecAppsecBodyLimit,
appsecExcludedLocations: appsecExcludedLocations,
crowdsecScheme: config.CrowdsecLapiScheme,
crowdsecHost: config.CrowdsecLapiHost,
crowdsecPath: config.CrowdsecLapiPath,
@@ -510,7 +514,7 @@ func (bouncer *Bouncer) handleRemediationServeHTTP(rw http.ResponseWriter, req *
}
func (bouncer *Bouncer) handleNextServeHTTP(rw http.ResponseWriter, req *http.Request, remoteIP string) {
if bouncer.appsecEnabled {
if bouncer.appsecEnabled && !bouncer.isAppsecExcluded(req, remoteIP) {
decision, err := appsecQuery(bouncer, remoteIP, req)
if err != nil {
bouncer.log.Debug(fmt.Sprintf("handleNextServeHTTP ip:%s isWaf:true %s", remoteIP, err.Error()))
@@ -528,6 +532,14 @@ func (bouncer *Bouncer) handleNextServeHTTP(rw http.ResponseWriter, req *http.Re
bouncer.next.ServeHTTP(rw, req)
}
func (bouncer *Bouncer) isAppsecExcluded(req *http.Request, remoteIP string) bool {
if strings.HasPrefix(req.URL.Path, appsecChallengePathPrefix) || !bouncer.appsecExcludedLocations.Contains(req) {
return false
}
bouncer.log.Debug(fmt.Sprintf("isAppsecExcluded ip:%s path:%s", remoteIP, req.URL.Path))
return true
}
func (bouncer *Bouncer) handleAppsecDecisionServeHTTP(rw http.ResponseWriter, req *http.Request, remoteIP string, decision *AppSecResponse) bool {
switch {
case decision == nil || decision.Action == appsecAllowAction:
+17 -4
View File
@@ -17,6 +17,7 @@ import (
"text/template"
ip "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip"
location "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/location"
)
// Enums for crowdsec mode.
@@ -64,6 +65,7 @@ type Config struct {
CrowdsecAppsecFailureBlock bool `json:"crowdsecAppsecFailureBlock,omitempty"`
CrowdsecAppsecUnreachableBlock bool `json:"crowdsecAppsecUnreachableBlock,omitempty"`
CrowdsecAppsecUnreadableBodyBlock bool `json:"crowdsecAppsecUnreadableBodyBlock,omitempty"`
CrowdsecAppsecExcludedLocations []string `json:"crowdsecAppsecExcludedLocations,omitempty"`
CrowdsecAppsecBodyLimit int64 `json:"crowdsecAppsecBodyLimit,omitempty"`
CrowdsecLapiScheme string `json:"crowdsecLapiScheme,omitempty"`
CrowdsecLapiHost string `json:"crowdsecLapiHost,omitempty"`
@@ -138,6 +140,7 @@ func New() *Config {
CrowdsecAppsecFailureBlock: true,
CrowdsecAppsecUnreachableBlock: true,
CrowdsecAppsecUnreadableBodyBlock: true,
CrowdsecAppsecExcludedLocations: []string{},
CrowdsecAppsecBodyLimit: 10485760,
CrowdsecAppsecScheme: "",
CrowdsecAppsecHost: "crowdsec:7422",
@@ -260,10 +263,7 @@ func ValidateParams(config *Config, log *slog.Logger) error {
return err
}
if err := validateParamsIPs(log, config.ForwardedHeadersTrustedIPs, "ForwardedHeadersTrustedIPs"); err != nil {
return err
}
if err := validateParamsIPs(log, config.ClientTrustedIPs, "ClientTrustedIPs"); err != nil {
if err := validateParamsLists(log, config); err != nil {
return err
}
@@ -402,6 +402,19 @@ func validateParamsTLS(config *Config) error {
return nil
}
func validateParamsLists(log *slog.Logger, config *Config) error {
if err := validateParamsIPs(log, config.ForwardedHeadersTrustedIPs, "ForwardedHeadersTrustedIPs"); err != nil {
return err
}
if err := validateParamsIPs(log, config.ClientTrustedIPs, "ClientTrustedIPs"); err != nil {
return err
}
if _, err := location.NewMatcher(config.CrowdsecAppsecExcludedLocations); err != nil {
return fmt.Errorf("CrowdsecAppsecExcludedLocations: %w", err)
}
return nil
}
func validateParamsIPs(log *slog.Logger, listIP []string, key string) error {
if len(listIP) > 0 {
if _, err := ip.NewChecker(log, listIP); err != nil {
+144
View File
@@ -0,0 +1,144 @@
// Package location matches requests against a list of host and path locations.
package location
import (
"errors"
"fmt"
"net"
"net/http"
"path"
"strconv"
"strings"
)
const (
hostChars = "abcdefghijklmnopqrstuvwxyz0123456789-._"
pathChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()+,=:@/"
)
type entry struct {
host string
port string
path string
prefix string
}
// Matcher holds the locations a request is compared to.
type Matcher struct {
entries []entry
}
// NewMatcher builds a Matcher from entries written as /path, host or host/path.
func NewMatcher(locations []string) (*Matcher, error) {
matcher := &Matcher{}
for _, raw := range locations {
loc := strings.TrimSpace(raw)
host, locationPath, port := "", loc, ""
if !strings.HasPrefix(loc, "/") {
slash := strings.IndexByte(loc, '/')
if slash < 0 {
slash = len(loc)
}
if slash == 0 {
return nil, fmt.Errorf("location %q must be a path starting with /, or a host optionally followed by a path", loc)
}
var err error
host, port, err = parseHost(loc[:slash])
if err != nil {
return nil, fmt.Errorf("location %q: %w", loc, err)
}
locationPath = "/"
if slash < len(loc) {
locationPath = loc[slash:]
}
}
if !isCanonicalPath(locationPath) {
return nil, fmt.Errorf("location %q: the path must be clean and use only letters, digits and -._~!$&'()+,=:@/", loc)
}
if host == "" && locationPath == "/" {
return nil, errors.New("location \"/\" matches every request, disable AppSec instead")
}
prefix := locationPath
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
matcher.entries = append(matcher.entries, entry{host: host, port: port, path: locationPath, prefix: prefix})
}
return matcher, nil
}
// Contains reports whether the request path, and host when the location has one, falls in a location.
func (m *Matcher) Contains(req *http.Request) bool {
if m == nil {
return false
}
reqHost, reqPort, reqPath := "", "", req.URL.Path
for _, e := range m.entries {
if reqPath != e.path && !strings.HasPrefix(reqPath, e.prefix) {
continue
}
if e.host != "" {
if reqHost == "" {
reqHost, reqPort = canonicalHost(req.Host)
}
if e.host != reqHost || (e.port != "" && e.port != reqPort) {
continue
}
}
if e.path == "/" || (reqPath == req.URL.EscapedPath() && isCanonicalPath(reqPath)) {
return true
}
}
return false
}
func parseHost(addr string) (string, string, error) {
host, port := addr, ""
if h, p, err := net.SplitHostPort(addr); err == nil {
number, err := strconv.ParseUint(p, 10, 16)
if err != nil || number == 0 {
return "", "", errors.New("the port must be a number between 1 and 65535")
}
host = h
port = strconv.FormatUint(number, 10)
}
host = strings.TrimSuffix(strings.ToLower(host), ".")
if !isHost(host) {
return "", "", errors.New("the host must be a domain name, without wildcard")
}
return host, port, nil
}
func canonicalHost(addr string) (string, string) {
host, port := addr, ""
if h, p, err := net.SplitHostPort(addr); err == nil {
host, port = h, p
}
if number, err := strconv.ParseUint(port, 10, 16); err == nil {
port = strconv.FormatUint(number, 10)
}
return strings.TrimSuffix(strings.ToLower(host), "."), port
}
func isHost(host string) bool {
return host != "" && !strings.HasPrefix(host, ".") && strings.Trim(host, hostChars) == ""
}
func isCanonicalPath(p string) bool {
if !strings.HasPrefix(p, "/") || strings.Trim(p, pathChars) != "" {
return false
}
cleaned := path.Clean(p)
if cleaned != "/" && strings.HasSuffix(p, "/") {
cleaned += "/"
}
if cleaned != p {
return false
}
for _, segment := range strings.Split(p, "/") {
if segment != "" && strings.Trim(segment, ".") == "" {
return false
}
}
return true
}
+89
View File
@@ -0,0 +1,89 @@
package location
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestMatcher_Contains(t *testing.T) {
matcher, err := NewMatcher([]string{
" /path ",
"every-port-host.com.",
"host-port-path.com:8000/v2/",
"host-port.com:8000",
})
if err != nil {
t.Fatal(err)
}
tests := []struct {
host string
target string
want bool
}{
{host: "other.com", target: "/"},
{host: "every-port-host.com", target: "/", want: true},
{host: "every-port-host.com.:1", target: "/", want: true},
{host: "evil.every-port-host.com", target: "/"},
{host: "every-port-host.com.evil", target: "/"},
{host: "host-port-path.com:8000", target: "/v2/x", want: true},
{host: "HOST-PORT-PATH.com:8000", target: "/v2/x", want: true},
{host: "host-port-path.com", target: "/v2/x"},
{host: "host-port-path.com:9000", target: "/v2/x"},
{host: "host-port-path.com:8000", target: "/v2"},
{host: "host-port-path.com:8000", target: "/v3/x"},
{host: "host-port-path.com:8000", target: "/path/Forbidden%20Char"},
{host: "app.com", target: "/path/Forbidden%20Char"},
{host: "app.com", target: "/path", want: true},
{host: "app.com", target: "/path/live?probe=1", want: true},
{host: "app.com", target: "/pathfoo"},
{host: "app.com", target: "/Path"},
{host: "app.com", target: "/admin?next=/path"},
{host: "app.com", target: "/v2/x"},
{host: "app.com", target: "//path"},
{host: "app.com", target: "/path/../admin"},
{host: "app.com", target: "/path/./live"},
{host: "app.com", target: "/path/.../admin"},
{host: "app.com", target: "/path/%2e%2e/admin"},
{host: "app.com", target: "/path%2F..%2Fadmin"},
{host: "app.com", target: "/path/%252e%252e/admin"},
{host: "app.com", target: "/path/..;/admin"},
{host: "app.com", target: "/path/..%3B/admin"},
{host: "app.com", target: "/path/..%5Cadmin"},
{host: "app.com", target: "/path/%00"},
{host: "app.com", target: "/path/%EF%BC%8E%EF%BC%8E%EF%BC%8Fadmin"},
{host: "app.com", target: "/path/%6Cive"},
}
for _, tt := range tests {
t.Run(tt.host+tt.target, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tt.target, nil)
req.Host = tt.host
if got := matcher.Contains(req); got != tt.want {
t.Errorf("Contains() = %v, want %v (path %q, escaped %q)", got, tt.want, req.URL.Path, req.URL.EscapedPath())
}
})
}
}
func TestNewMatcher_rejects(t *testing.T) {
for _, loc := range []string{
"",
"/",
"app.com:0",
"app.com:",
"app.com:abc",
"app.com:99999",
"app.com//",
"*.app.com/v2/",
"https://app.com/v2/",
"/path/../admin",
"//path",
"/v2/*",
"/a;b",
"/a%2Fb",
} {
if _, err := NewMatcher([]string{loc}); err == nil {
t.Errorf("NewMatcher(%q) must fail", loc)
}
}
}
@@ -28,5 +28,7 @@ http:
crowdsecAppsecUnreachableBlock: "false"
crowdsecAppsecScheme: http
crowdsecAppsecHost: "@@APPSEC_HOST@@"
crowdsecAppsecExcludedLocations:
- /foo/excluded
forwardedHeadersTrustedIps:
- "127.0.0.1/32"
+6
View File
@@ -39,6 +39,12 @@ body() {
echo "[$SCENARIO] request http2 that send unreadable body POST (AppSec 403)"
assert_status "http://127.0.0.1:${WEB_PORT}/foo" 403 -H "X-Forwarded-For: 1.2.3.4" --http2-prior-knowledge -H "Content-Length:" -X POST -d "test"
echo "[$SCENARIO] request to an excluded location must skip AppSec"
assert_status "http://127.0.0.1:${WEB_PORT}/foo/excluded/403" 200 -H "X-Forwarded-For: 1.2.3.4"
echo "[$SCENARIO] request that escapes an excluded location must still be inspected (AppSec 403)"
assert_status "http://127.0.0.1:${WEB_PORT}/foo/excluded/..;/403" 403 -H "X-Forwarded-For: 1.2.3.4" --path-as-is
}
run_scenario "$SCENARIO" "$HERE" body