Files
traefik-botfilter/botfilter.go
T

55 lines
1.2 KiB
Go

// Package traefik_botfilter is a Traefik middleware plugin that blocks known scans
// and applies a bounded, in-memory per-IP suspicion score.
package botfilter
import (
"bufio"
"context"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"strconv"
"time"
)
type botFilter struct {
next http.Handler
config *compiledConfig
cache *clientCache
logger filterLogger
}
// New constructs a Traefik middleware. Its signature is the interface used
// by Traefik's Go plugin runtime.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if next == nil {
return nil, fmt.Errorf("botfilter: next handler is nil")
}
compiled, err := compileConfig(config)
if err != nil {
return nil, err
}
return &botFilter{
next: next,
config: compiled,
cache: newClientCache(compiled),
logger: filterLogger{name: name, enabled: compiled.LogBlockedRequests},
}, nil
}
func (b *botFilter) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
now := time.Now()
addr := clientIP(r, b.config)
ip := addressString(addr)
if addressInPrefixes(addr, b.config.whitelist) {
b.next.ServeHTTP(rw, r)
return
}
if existing := b.cache.isBanned(ip, now); existing.banned {
b.reject(rw, ip, "temporary ban", existing)
return
}