servewaf answers rproxy's question about each request and takes its report (closes #170)
check / check (push) Successful in 4m27s
check / check (push) Successful in 4m27s
`smallwebwaf servewaf` runs today's checks on the visitor's request a question carries and answers allow, deny or close, instead of passing it to an app. rproxy's report then counts the bytes toward the byte limits and adds the request to the client's history. SPEC.md gives the exact question, answer and report, which rproxy follows. `smallwebwaf` with no command is unchanged. Judgement call: a third disposition, close, since closing the question's connection would read as servewaf down and let the request through. Judgement call: allow can answer a new request id, since a visitor behind a trusted proxy can choose its own. Model: opus-5-5
This commit is contained in:
@@ -41,6 +41,15 @@ var (
|
||||
errNotAddress = errors.New("is not an address, such as 203.0.113.9")
|
||||
)
|
||||
|
||||
// answerHealth answers a request for the health endpoint.
|
||||
func (rq *request) answerHealth() {
|
||||
rq.line.Action = requestlog.ActionAdmin
|
||||
// Set here rather than left to Go's server, which would set it only
|
||||
// after the log line has taken the response's headers.
|
||||
rq.out.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
_, _ = io.WriteString(rq.out, "ok\n")
|
||||
}
|
||||
|
||||
// answerAdmin answers a request for smallwebwaf itself, under
|
||||
// /_smallwebwaf/, once it has passed the checks. Each endpoint needs a
|
||||
// token, sent as Authorization: Bearer <token>: the metrics
|
||||
|
||||
@@ -323,6 +323,7 @@ func (rq *request) alertBan(ban bans.Ban) {
|
||||
|
||||
rq.h.alerts.Raise(alerts.Alert{
|
||||
Event: event,
|
||||
Host: rq.site,
|
||||
Client: rq.client,
|
||||
Netblock: ban.Netblock,
|
||||
ASN: ban.Notes.ASN,
|
||||
|
||||
@@ -25,6 +25,8 @@ const (
|
||||
userAgent = "ban-test/1.0"
|
||||
// permanent is the log line's ban_expires for a permanent ban.
|
||||
permanent = "permanent"
|
||||
// banResponseClose is the SWWAF_BAN_RESPONSE that closes the connection.
|
||||
banResponseClose = "close"
|
||||
)
|
||||
|
||||
func TestBrokenLimitBansTheClient(t *testing.T) {
|
||||
@@ -237,7 +239,7 @@ func TestBanResponseAnswersEveryRefusalButTheSizeLimits(t *testing.T) {
|
||||
{"", http.StatusForbidden},
|
||||
{"403", http.StatusForbidden},
|
||||
{"429", http.StatusTooManyRequests},
|
||||
{"close", 0},
|
||||
{banResponseClose, 0},
|
||||
} {
|
||||
t.Run(banResponse+"="+tc.setting, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -113,6 +113,7 @@ func (rq *request) alertWAFBlock(result waf.Result) {
|
||||
|
||||
rq.h.alerts.Raise(alerts.Alert{
|
||||
Event: alerts.EventWAFBlock,
|
||||
Host: rq.site,
|
||||
Client: rq.client,
|
||||
Netblock: rq.h.clientGroup(rq.client),
|
||||
ASN: rq.line.ASN,
|
||||
|
||||
@@ -207,7 +207,7 @@ func TestMetricsCountLimitsAndBans(t *testing.T) {
|
||||
rateLimitPerMinute: "1",
|
||||
rateLimitExemptNets: scraper,
|
||||
denyNets: denied,
|
||||
banResponse: "close",
|
||||
banResponse: banResponseClose,
|
||||
limitBanDuration: "1h",
|
||||
maxBanDuration: "2h",
|
||||
})
|
||||
|
||||
+49
-32
@@ -1,6 +1,8 @@
|
||||
// Package proxy passes each request to the app and the app's answer back,
|
||||
// unchanged, within the size and time limits, and writes one request log
|
||||
// line for each request.
|
||||
// Package proxy runs the checks on each request and writes one request log
|
||||
// line for it. New passes each request it lets through to the app and the
|
||||
// app's answer back, unchanged, within the size and time limits. NewServeWAF
|
||||
// instead answers rproxy's question about each request, and takes rproxy's
|
||||
// report once the visitor's answer has ended.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
@@ -11,6 +13,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/anomaly"
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
@@ -19,7 +23,6 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/metrics"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/rules"
|
||||
"sneak.berlin/go/smallwebwaf/internal/waf"
|
||||
)
|
||||
@@ -109,6 +112,23 @@ type Server struct {
|
||||
// SWWAF_CLIENT_REQUEST_TIMEOUT while the headers arrive; the proxy
|
||||
// applies the timeouts and size limits from then on.
|
||||
func New(params Params) *Server {
|
||||
h := newHandler(params)
|
||||
|
||||
return h.server(&http.Server{
|
||||
Handler: h,
|
||||
ReadHeaderTimeout: params.Config.ClientRequestTimeout,
|
||||
// Off is an IdleTimeout of 0, which Go's server replaces with
|
||||
// ReadTimeout: no limit, as long as ReadTimeout stays unset.
|
||||
IdleTimeout: params.Config.ClientIdleTimeout,
|
||||
// Go's server reads 4 KiB past MaxHeaderBytes before it
|
||||
// refuses, so the limit a client meets is the setting.
|
||||
MaxHeaderBytes: int(params.Config.ClientRequestHeaderMaxBytes - 4<<10),
|
||||
})
|
||||
}
|
||||
|
||||
// newHandler returns the handler with what every request shares, as the
|
||||
// settings in params make it.
|
||||
func newHandler(params Params) *handler {
|
||||
errorLog := slog.NewLogLogger(params.ProcessLog.Handler(), slog.LevelWarn)
|
||||
m := metrics.New(params.Config.MetricsTopN, params.Config.InstanceName)
|
||||
lists, dnsbl, abuseIPDB := newReputation(params, m)
|
||||
@@ -171,29 +191,7 @@ func New(params Params) *Server {
|
||||
m.AddBansAndClients(h.ledger, h.limiter, params.Now)
|
||||
m.AddRules(params.Rules)
|
||||
|
||||
return &Server{
|
||||
Server: &http.Server{
|
||||
Addr: params.Config.ListenAddr,
|
||||
Handler: h,
|
||||
ReadHeaderTimeout: params.Config.ClientRequestTimeout,
|
||||
// Off is an IdleTimeout of 0, which Go's server replaces with
|
||||
// ReadTimeout: no limit, as long as ReadTimeout stays unset.
|
||||
IdleTimeout: params.Config.ClientIdleTimeout,
|
||||
// Go's server reads 4 KiB past MaxHeaderBytes before it
|
||||
// refuses, so the limit a client meets is the setting.
|
||||
MaxHeaderBytes: int(params.Config.ClientRequestHeaderMaxBytes - 4<<10),
|
||||
ErrorLog: errorLog,
|
||||
},
|
||||
Ledger: h.ledger,
|
||||
Limiter: h.limiter,
|
||||
GeoJS: h.geojs,
|
||||
Anomalies: h.anomalies,
|
||||
LookupFile: h.lookupFile,
|
||||
Lists: h.lists,
|
||||
DNSBL: h.dnsbl,
|
||||
AbuseIPDB: h.abuseIPDB,
|
||||
Metrics: m,
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// newReputation returns the lists fetched from URLs, the DNSBL zones'
|
||||
@@ -274,6 +272,9 @@ type handler struct {
|
||||
rules *rules.Files
|
||||
coreRuleSet *waf.CoreRuleSet
|
||||
alerts *alerts.Queue
|
||||
// awaitingReport holds, in servewaf, each allowed request by its id
|
||||
// until its report comes.
|
||||
awaitingReport *lru.Cache[string, *request]
|
||||
}
|
||||
|
||||
// newTransport returns what carries requests to the app. It never goes
|
||||
@@ -299,11 +300,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// The health endpoint is answered at once, before any check, so that
|
||||
// a health checker is never refused. It does not ask the app.
|
||||
if r.Method == http.MethodGet && r.URL.Path == HealthPath {
|
||||
rq.line.Action = requestlog.ActionAdmin
|
||||
// Set here rather than left to Go's server, which would set it only
|
||||
// after the log line has taken the response's headers.
|
||||
rq.out.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
_, _ = io.WriteString(rq.out, "ok\n")
|
||||
rq.answerHealth()
|
||||
|
||||
return
|
||||
}
|
||||
@@ -339,3 +336,23 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
rq.forward(r.Context())
|
||||
}
|
||||
|
||||
// server returns the Server of h, which listens at SWWAF_LISTEN_ADDR and
|
||||
// logs through h, with what httpServer sets.
|
||||
func (h *handler) server(httpServer *http.Server) *Server {
|
||||
httpServer.Addr = h.config.ListenAddr
|
||||
httpServer.ErrorLog = h.errorLog
|
||||
|
||||
return &Server{
|
||||
Server: httpServer,
|
||||
Ledger: h.ledger,
|
||||
Limiter: h.limiter,
|
||||
GeoJS: h.geojs,
|
||||
Anomalies: h.anomalies,
|
||||
LookupFile: h.lookupFile,
|
||||
Lists: h.lists,
|
||||
DNSBL: h.dnsbl,
|
||||
AbuseIPDB: h.abuseIPDB,
|
||||
Metrics: h.metrics,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,6 +284,16 @@ func newProxy(
|
||||
) (*proxy.Server, *output, *alerts.Queue) {
|
||||
t.Helper()
|
||||
|
||||
return newServerWith(t, proxy.New, appURL, geojsURL, now, env)
|
||||
}
|
||||
|
||||
// newServerWith is newProxy for the server build makes.
|
||||
func newServerWith(
|
||||
t *testing.T, build func(proxy.Params) *proxy.Server,
|
||||
appURL, geojsURL string, now func() time.Time, env map[string]string,
|
||||
) (*proxy.Server, *output, *alerts.Queue) {
|
||||
t.Helper()
|
||||
|
||||
settings := map[string]string{
|
||||
"SWWAF_UPSTREAM_URL": appURL, rulesDir: t.TempDir(), instanceName: "app",
|
||||
wafMode: off,
|
||||
@@ -334,7 +344,7 @@ func newProxy(
|
||||
}
|
||||
}
|
||||
|
||||
server := proxy.New(proxy.Params{
|
||||
server := build(proxy.Params{
|
||||
Config: cfg,
|
||||
RequestLog: out,
|
||||
ProcessLog: processLog,
|
||||
|
||||
@@ -110,6 +110,7 @@ func (rq *request) noteHit(hit bans.ReputationHit, reason string) {
|
||||
rq.h.metrics.ReputationHit(hit.Source)
|
||||
rq.h.alerts.Raise(alerts.Alert{
|
||||
Event: alerts.EventReputationHit,
|
||||
Host: rq.site,
|
||||
Client: rq.client,
|
||||
Netblock: rq.h.clientGroup(rq.client),
|
||||
ASN: rq.line.ASN,
|
||||
|
||||
@@ -53,6 +53,11 @@ type request struct {
|
||||
client netip.Addr
|
||||
peer netip.Addr
|
||||
peerTrusted bool
|
||||
// site is, in servewaf, the host the visitor asked for, which the
|
||||
// alerts name, since one servewaf serves many sites. It is "" otherwise.
|
||||
site string
|
||||
// allowed is true for a question answered with DispositionAllow.
|
||||
allowed bool
|
||||
// lookedUp is true once the client's AS number and country have been
|
||||
// looked up, whether or not an answer was there, and lookupAnswer is
|
||||
// what the lookup gave then, the zero Answer while GeoJS had given none.
|
||||
@@ -108,18 +113,27 @@ type request struct {
|
||||
answerStarted time.Time
|
||||
}
|
||||
|
||||
// newRequest starts handling r: it notes the time, counts the request as
|
||||
// under way, works out the client, and starts the log line with what is
|
||||
// known of the request.
|
||||
// newRequest starts handling r: it works out the client from the TCP peer
|
||||
// and X-Forwarded-For, and goes on as startRequest does.
|
||||
func (h *handler) newRequest(w http.ResponseWriter, r *http.Request) *request {
|
||||
peer := peerAddress(r)
|
||||
trusted := h.config.TrustedProxies
|
||||
client := clientAddress(peer, r.Header.Values("X-Forwarded-For"), trusted)
|
||||
|
||||
return h.startRequest(w, r, client, peer, isInside(peer, trusted))
|
||||
}
|
||||
|
||||
// startRequest starts handling r from client, which came through peer: it
|
||||
// notes the time, counts the request as under way, and starts the log line
|
||||
// with what is known of the request. peerTrusted says whether to believe
|
||||
// the request's id and scheme, which r's headers give.
|
||||
func (h *handler) startRequest(
|
||||
w http.ResponseWriter, r *http.Request, client, peer netip.Addr, peerTrusted bool,
|
||||
) *request {
|
||||
h.metrics.RequestStarted()
|
||||
|
||||
start := time.Now()
|
||||
peer := peerAddress(r)
|
||||
trusted := h.config.TrustedProxies
|
||||
peerTrusted := isInside(peer, trusted)
|
||||
forwardedFor := r.Header.Values("X-Forwarded-For")
|
||||
client := clientAddress(peer, forwardedFor, trusted)
|
||||
|
||||
rq := &request{
|
||||
h: h,
|
||||
@@ -569,8 +583,13 @@ func (rq *request) finish() {
|
||||
}
|
||||
|
||||
// Counted before the log line is written, so that the metrics count
|
||||
// every request whose line is out.
|
||||
rq.h.metrics.RequestEnded(line, limit, duration, upstreamDuration)
|
||||
// every request whose line is out. An allowed request is the exception:
|
||||
// its report gives the status, bytes and times the metrics count.
|
||||
if rq.allowed {
|
||||
rq.h.metrics.RequestAllowed()
|
||||
} else {
|
||||
rq.h.metrics.RequestEnded(line, limit, duration, upstreamDuration)
|
||||
}
|
||||
|
||||
err := requestlog.Write(rq.h.requestLog, line)
|
||||
if err != nil {
|
||||
@@ -634,6 +653,7 @@ func (rq *request) countAnomalies() {
|
||||
answer, _ := rq.answerAtTheEnd()
|
||||
|
||||
rq.h.anomalies.Count(rq.h.now(), anomaly.Request{
|
||||
Host: rq.site,
|
||||
Client: rq.client,
|
||||
ClientGroup: rq.h.clientGroup(rq.client),
|
||||
ASN: answer.ASN,
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
// The headers of rproxy's question and of servewaf's answer, as
|
||||
// "servewaf" in SPEC.md gives them.
|
||||
const (
|
||||
// ClientHeader marks a request as rproxy's question, and gives the
|
||||
// visitor's address.
|
||||
ClientHeader = "X-Smallwebwaf-Client"
|
||||
// PeerHeader gives the address of rproxy's own TCP peer.
|
||||
PeerHeader = "X-Smallwebwaf-Peer"
|
||||
// ContentLengthHeader gives the body length the visitor announced.
|
||||
ContentLengthHeader = "X-Smallwebwaf-Content-Length"
|
||||
// DispositionHeader gives servewaf's answer.
|
||||
DispositionHeader = "X-Smallwebwaf-Disposition"
|
||||
)
|
||||
|
||||
// The values of DispositionHeader.
|
||||
const (
|
||||
// DispositionAllow tells rproxy to pass the request to the app.
|
||||
DispositionAllow = "allow"
|
||||
// DispositionDeny tells rproxy to give the visitor the answer's status,
|
||||
// headers and body.
|
||||
DispositionDeny = "deny"
|
||||
// DispositionClose tells rproxy to close the visitor's connection
|
||||
// without an answer, which SWWAF_BAN_RESPONSE asks for when it is close.
|
||||
// servewaf closing the question's connection instead would read as
|
||||
// servewaf being down, and rproxy would then let the request through.
|
||||
DispositionClose = "close"
|
||||
)
|
||||
|
||||
// ReportPath is where rproxy sends the report of each request it passed to
|
||||
// the app.
|
||||
const ReportPath = "/_smallwebwaf/report"
|
||||
|
||||
// QuestionBodyMaxBytes is the most of a visitor's body a question carries.
|
||||
const QuestionBodyMaxBytes = 64 << 10
|
||||
|
||||
const (
|
||||
// maxAwaitingReport is the most allowed requests held until their
|
||||
// reports come. Past it, the request asked about longest ago is dropped.
|
||||
maxAwaitingReport = 10000
|
||||
// reportBodyMaxBytes is the most of a report's body that is read. It is
|
||||
// far above any report's, since the longest thing in one is the request
|
||||
// id, which comes from a header.
|
||||
reportBodyMaxBytes = 1 << 20
|
||||
// serveWAFTimeout bounds how long a request to servewaf takes to arrive,
|
||||
// and its answer to leave, and serveWAFIdleTimeout how long a kept-open
|
||||
// connection waits for its next request.
|
||||
serveWAFTimeout = 60 * time.Second
|
||||
serveWAFIdleTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
// Report is the JSON object rproxy posts to ReportPath once the visitor's
|
||||
// answer has ended, its fields named as the request log's of the same
|
||||
// meaning. RequestID is the id servewaf's allow gave. Status is what the
|
||||
// visitor got, 0 if nothing. The durations are in milliseconds.
|
||||
//
|
||||
//nolint:tagliatelle // docs/request-log.md names the fields in snake_case
|
||||
type Report struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Status int `json:"status"`
|
||||
RequestBytes int64 `json:"request_bytes"`
|
||||
ResponseBytes int64 `json:"response_bytes"`
|
||||
DurationTotal float64 `json:"duration_total"`
|
||||
DurationUpstreamTotal float64 `json:"duration_upstream_total"`
|
||||
}
|
||||
|
||||
// NewServeWAF returns the server `smallwebwaf servewaf` runs. It answers
|
||||
// rproxy's questions with the checks New runs, takes rproxy's reports and
|
||||
// answers its own endpoints. It passes nothing to an app. rproxy applies
|
||||
// the size and time limits to the visitor, so their settings do not apply
|
||||
// here. Go's default limit on a request's line and headers, 1 MiB, stays:
|
||||
// it is far above rproxy's, and a question refused for its size would have
|
||||
// rproxy let the request through.
|
||||
func NewServeWAF(params Params) *Server {
|
||||
cfg := *params.Config
|
||||
cfg.RequestMaxBytes = 0
|
||||
cfg.ClientRequestTimeout = serveWAFTimeout
|
||||
// The server's WriteTimeout does this. It sets a new deadline for each
|
||||
// request, where a deadline a handler sets stays on a kept-open
|
||||
// connection, and would run out under a later request's answer.
|
||||
cfg.ClientResponseTimeout = 0
|
||||
// A question's body of QuestionBodyMaxBytes may be cut short, and the
|
||||
// Core Rule Set does not read a JSON or XML body over its limit.
|
||||
cfg.WAFBodyLimit = min(cfg.WAFBodyLimit, QuestionBodyMaxBytes-1)
|
||||
params.Config = &cfg
|
||||
|
||||
h := newHandler(params)
|
||||
|
||||
awaitingReport, err := lru.New[string, *request](maxAwaitingReport)
|
||||
if err != nil {
|
||||
panic(err) // New fails only for a size below one
|
||||
}
|
||||
|
||||
h.awaitingReport = awaitingReport
|
||||
|
||||
return h.server(&http.Server{
|
||||
Handler: http.HandlerFunc(h.serveWAF),
|
||||
ReadTimeout: serveWAFTimeout,
|
||||
WriteTimeout: serveWAFTimeout,
|
||||
IdleTimeout: serveWAFIdleTimeout,
|
||||
})
|
||||
}
|
||||
|
||||
// serveWAF handles one request to servewaf: a request carrying
|
||||
// ClientHeader is rproxy's question, and any other is for servewaf itself.
|
||||
func (h *handler) serveWAF(w http.ResponseWriter, r *http.Request) {
|
||||
if len(r.Header.Values(ClientHeader)) > 0 {
|
||||
h.answerQuestion(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.answerOwnEndpoint(w, r)
|
||||
}
|
||||
|
||||
// answerQuestion runs the checks on the visitor's request a question
|
||||
// carries, and answers rproxy what to do with it. A denied request is
|
||||
// finished here. An allowed one is finished by its report. A question
|
||||
// without a visitor's address gets no disposition, so that rproxy treats
|
||||
// it as it treats no answer.
|
||||
func (h *handler) answerQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
client, err := netip.ParseAddr(r.Header.Get(ClientHeader))
|
||||
if err != nil {
|
||||
h.processLog.Warn("a question gives no visitor's address", "error", err.Error())
|
||||
http.Error(w, "X-Smallwebwaf-Client is not an address", http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// One that cannot be read leaves the log line's peer_ip invalid.
|
||||
peer, _ := netip.ParseAddr(r.Header.Get(PeerHeader))
|
||||
|
||||
rq := h.startRequest(w, asTheVisitorSentIt(r), client.Unmap(), peer.Unmap(), true)
|
||||
defer rq.finish()
|
||||
|
||||
rq.site = r.Host
|
||||
refused := rq.check(r.Context())
|
||||
rq.checked = time.Now()
|
||||
underOwnPrefix := strings.HasPrefix(r.URL.Path, adminPrefix)
|
||||
|
||||
if refused == nil && !underOwnPrefix {
|
||||
// In observe mode, what enforce mode would have refused counts here.
|
||||
defer rq.countRefusal()
|
||||
|
||||
rq.allow()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// The last deferred runs first, as in ServeHTTP.
|
||||
defer rq.addToHistory()
|
||||
defer rq.countAnomalies()
|
||||
defer rq.countRefusal()
|
||||
|
||||
if refused != nil {
|
||||
rq.deny(*refused)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// The app never sees this prefix. servewaf's own endpoints are at its
|
||||
// own address, so this answers as a path with no endpoint does.
|
||||
rq.line.Action = requestlog.ActionAdmin
|
||||
rq.out.Header().Set(DispositionHeader, DispositionDeny)
|
||||
http.Error(rq.out, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
}
|
||||
|
||||
// asTheVisitorSentIt returns a copy of r, a question, as the checks and the
|
||||
// log line are to see it: without the headers rproxy adds for servewaf, and
|
||||
// with the length the visitor announced, as -1 when it announced none. The
|
||||
// question's own length covers only the part of the body it carries.
|
||||
func asTheVisitorSentIt(r *http.Request) *http.Request {
|
||||
sent := r.Clone(r.Context())
|
||||
announced := sent.Header.Get(ContentLengthHeader)
|
||||
|
||||
sent.Header.Del(ClientHeader)
|
||||
sent.Header.Del(PeerHeader)
|
||||
sent.Header.Del(ContentLengthHeader)
|
||||
sent.Header.Del("Content-Length")
|
||||
|
||||
sent.ContentLength = -1
|
||||
|
||||
length, err := strconv.ParseInt(announced, 10, 64)
|
||||
if err == nil && length >= 0 {
|
||||
sent.ContentLength = length
|
||||
sent.Header.Set("Content-Length", announced)
|
||||
}
|
||||
|
||||
return sent
|
||||
}
|
||||
|
||||
// allow answers a question with DispositionAllow, the request's id and,
|
||||
// while SWWAF_ADD_LOOKUP_HEADERS is set, the client's AS number and country,
|
||||
// and holds the request until its report comes.
|
||||
func (rq *request) allow() {
|
||||
rq.allowed = true
|
||||
|
||||
// servewaf sends no app this part of the body, and the table of requests
|
||||
// awaiting their reports must not hold it.
|
||||
if rq.body != nil {
|
||||
rq.body.readByCoreRuleSet = nil
|
||||
}
|
||||
|
||||
rq.awaitReport()
|
||||
|
||||
header := rq.out.Header()
|
||||
header.Set(DispositionHeader, DispositionAllow)
|
||||
header.Set(requestIDHeader, rq.line.RequestID)
|
||||
|
||||
if rq.h.config.AddLookupHeaders {
|
||||
setLookupHeaders(header, rq.line.ASN, rq.line.Country)
|
||||
}
|
||||
|
||||
// Go's server sends this only once the handler has returned, so a report
|
||||
// that answers it cannot come while the handler still uses rq.
|
||||
rq.out.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
// awaitReport holds the request by its id, which its report is to name. A
|
||||
// visitor behind a trusted proxy can choose its id, which must not let it
|
||||
// have its report taken for another request's, or lost, and its bytes not
|
||||
// counted. So the request gets a new id when another held request has the
|
||||
// question's, or when that is not valid UTF-8, which a JSON report cannot
|
||||
// carry unchanged.
|
||||
func (rq *request) awaitReport() {
|
||||
id := rq.line.RequestID
|
||||
if !utf8.ValidString(id) {
|
||||
id = rand.Text()
|
||||
}
|
||||
|
||||
held, _ := rq.h.awaitingReport.ContainsOrAdd(id, rq)
|
||||
if held {
|
||||
id = rand.Text()
|
||||
rq.h.awaitingReport.Add(id, rq)
|
||||
}
|
||||
|
||||
rq.line.RequestID = id
|
||||
}
|
||||
|
||||
// deny answers a question with what the visitor is to get for r.
|
||||
func (rq *request) deny(r refusal) {
|
||||
if r.status == 0 {
|
||||
// SWWAF_BAN_RESPONSE is close. Written past rq.out, since the log line's
|
||||
// status stays 0: the visitor is sent nothing.
|
||||
rq.refused.CompareAndSwap(nil, &r)
|
||||
rq.out.Header().Set(DispositionHeader, DispositionClose)
|
||||
rq.out.ResponseWriter.WriteHeader(http.StatusOK)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq.out.Header().Set(DispositionHeader, DispositionDeny)
|
||||
rq.answer(r)
|
||||
}
|
||||
|
||||
// answerOwnEndpoint answers a request to servewaf's own address. No check
|
||||
// runs on it: the address is on the private network, where the peers are
|
||||
// rproxy and the admin's tools, not visitors. A report writes no log line.
|
||||
func (h *handler) answerOwnEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == ReportPath {
|
||||
h.takeReport(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
peer := peerAddress(r)
|
||||
|
||||
rq := h.startRequest(w, r, peer, peer, false)
|
||||
defer rq.finish()
|
||||
|
||||
if r.Method == http.MethodGet && r.URL.Path == HealthPath {
|
||||
rq.answerHealth()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq.answerAdmin()
|
||||
}
|
||||
|
||||
// takeReport answers POST ReportPath: it finishes the request the report
|
||||
// names, if it holds that request, and ignores the report otherwise.
|
||||
func (h *handler) takeReport(w http.ResponseWriter, r *http.Request) {
|
||||
var report Report
|
||||
|
||||
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, reportBodyMaxBytes)).
|
||||
Decode(&report)
|
||||
if err != nil || report.RequestBytes < 0 || report.ResponseBytes < 0 {
|
||||
http.Error(w, "the body is not a report", http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq, held := h.awaitingReport.Peek(report.RequestID)
|
||||
// Remove reports true to one report only, of several that name the id.
|
||||
if held && h.awaitingReport.Remove(report.RequestID) {
|
||||
rq.finishWith(report)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// finishWith finishes an allowed request with what its report says: the
|
||||
// steps ServeHTTP takes once a request passed to the app has ended, with
|
||||
// the status and bytes of the report in place of those it would have seen.
|
||||
func (rq *request) finishWith(report Report) {
|
||||
// A limit the question broke has been logged.
|
||||
rq.line.LimitHit = ""
|
||||
// addToHistory goes by this for whether the request reached the app.
|
||||
rq.upstreamStart = time.Now()
|
||||
rq.out = &responseWriter{status: report.Status, bytes: report.ResponseBytes}
|
||||
rq.body = &requestBody{}
|
||||
rq.body.bytes.Store(report.RequestBytes)
|
||||
|
||||
rq.countBytes()
|
||||
rq.countAnomalies()
|
||||
rq.addToHistory()
|
||||
|
||||
rq.line.Status = report.Status
|
||||
rq.line.RequestBytes = report.RequestBytes
|
||||
rq.line.ResponseBytes = report.ResponseBytes
|
||||
rq.h.metrics.RequestReported(&rq.line,
|
||||
time.Duration(report.DurationTotal*float64(time.Millisecond)),
|
||||
time.Duration(report.DurationUpstreamTotal*float64(time.Millisecond)))
|
||||
|
||||
// The request's log line went out with the answer to its question.
|
||||
if rq.line.LimitHit != "" {
|
||||
rq.h.processLog.Warn("a report's bytes broke a byte limit",
|
||||
"request_id", rq.line.RequestID,
|
||||
"client_ip", rq.line.ClientIP,
|
||||
"host", rq.line.Host,
|
||||
"limit_hit", rq.line.LimitHit,
|
||||
"ban_expires", rq.line.BanExpires)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
package proxy_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
"sneak.berlin/go/smallwebwaf/internal/proxy"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
const (
|
||||
// siteA and siteB are two sites behind one servewaf.
|
||||
siteA = "a.example"
|
||||
siteB = "b.example"
|
||||
// rproxyPeer is what the tests' questions give as rproxy's TCP peer.
|
||||
rproxyPeer = "172.18.0.2"
|
||||
)
|
||||
|
||||
// serveWAF is a servewaf running for one test, on a clock set to midnight.
|
||||
type serveWAF struct {
|
||||
t *testing.T
|
||||
addr string
|
||||
out *output
|
||||
server *proxy.Server
|
||||
clock *clock
|
||||
queue *alerts.Queue
|
||||
}
|
||||
|
||||
// startServeWAF starts servewaf with the settings in env, clients' AS numbers
|
||||
// and countries looked up at geojsURL.
|
||||
func startServeWAF(t *testing.T, geojsURL string, env map[string]string) *serveWAF {
|
||||
t.Helper()
|
||||
|
||||
clk := &clock{now: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC)}
|
||||
settings := map[string]string{
|
||||
alertWebhookURL: "https://alerts.example/servewaf",
|
||||
instanceName: alertInstance,
|
||||
}
|
||||
maps.Copy(settings, env)
|
||||
|
||||
server, out, queue := newServerWith(t, proxy.NewServeWAF,
|
||||
"http://127.0.0.1:8081", geojsURL, clk.Now, settings)
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", localhost+":0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
_ = server.Serve(listener)
|
||||
}()
|
||||
|
||||
t.Cleanup(func() {
|
||||
_ = server.Close()
|
||||
})
|
||||
|
||||
return &serveWAF{
|
||||
t: t, addr: listener.Addr().String(), out: out, server: server,
|
||||
clock: clk, queue: queue,
|
||||
}
|
||||
}
|
||||
|
||||
// question makes rproxy's question about a request for path on host, from the
|
||||
// visitor at from.
|
||||
func (s *serveWAF) question(host, from, path string) *http.Request {
|
||||
s.t.Helper()
|
||||
|
||||
req := newRequest(s.t, http.MethodGet, s.addr, path, http.NoBody)
|
||||
req.Host = host
|
||||
req.Header.Set(proxy.ClientHeader, from)
|
||||
req.Header.Set(proxy.PeerHeader, rproxyPeer)
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
// ask sends the question about a request for path on siteA from the visitor at
|
||||
// from, and returns the answer.
|
||||
func (s *serveWAF) ask(from, path string) answer {
|
||||
s.t.Helper()
|
||||
|
||||
return do(s.t, s.question(siteA, from, path))
|
||||
}
|
||||
|
||||
// allowed asks about a request for / on siteA, checks that the answer is allow,
|
||||
// and returns the id the answer gives for the report.
|
||||
func (s *serveWAF) allowed(from string) string {
|
||||
s.t.Helper()
|
||||
|
||||
got := s.ask(from, "/")
|
||||
wantDisposition(s.t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
return got.header.Get(requestIDHeader)
|
||||
}
|
||||
|
||||
// report sends rproxy's report and returns the answer.
|
||||
func (s *serveWAF) report(report proxy.Report) answer {
|
||||
s.t.Helper()
|
||||
|
||||
body, err := json.Marshal(report)
|
||||
if err != nil {
|
||||
s.t.Fatalf("encode the report: %v", err)
|
||||
}
|
||||
|
||||
return do(s.t, newRequest(s.t, http.MethodPost, s.addr, proxy.ReportPath,
|
||||
bytes.NewReader(body)))
|
||||
}
|
||||
|
||||
// passedOn asks about a request from the visitor at from on siteA, and reports
|
||||
// it as answered 200 with bodyBytes and answerBytes.
|
||||
func (s *serveWAF) passedOn(from string) {
|
||||
s.t.Helper()
|
||||
|
||||
got := s.report(proxy.Report{
|
||||
RequestID: s.allowed(from),
|
||||
Status: http.StatusOK,
|
||||
RequestBytes: bodyBytes,
|
||||
ResponseBytes: answerBytes,
|
||||
})
|
||||
wantStatus(s.t, got, http.StatusNoContent)
|
||||
}
|
||||
|
||||
// history returns what the table of clients holds of client's history.
|
||||
func (s *serveWAF) history() ratelimit.History {
|
||||
held, _ := s.server.Limiter.Client(netip.MustParsePrefix(client + "/32"))
|
||||
|
||||
return held.History
|
||||
}
|
||||
|
||||
// metrics returns what the metrics endpoint answers, for a server started with
|
||||
// the token as SWWAF_METRICS_TOKEN.
|
||||
func (s *serveWAF) metrics() string {
|
||||
s.t.Helper()
|
||||
|
||||
req := newRequest(s.t, http.MethodGet, s.addr, proxy.MetricsPath, http.NoBody)
|
||||
req.Header.Set("Authorization", bearer)
|
||||
|
||||
got := do(s.t, req)
|
||||
wantStatus(s.t, got, http.StatusOK)
|
||||
|
||||
return string(got.body)
|
||||
}
|
||||
|
||||
// wantDisposition checks an answer's status and disposition.
|
||||
func wantDisposition(t *testing.T, got answer, status int, disposition string) {
|
||||
t.Helper()
|
||||
wantStatus(t, got, status)
|
||||
|
||||
if answered := got.header.Get(proxy.DispositionHeader); answered != disposition {
|
||||
t.Errorf("answered with disposition %q, want %q", answered, disposition)
|
||||
}
|
||||
}
|
||||
|
||||
// wantBody checks an answer's body.
|
||||
func wantBody(t *testing.T, got answer, want string) {
|
||||
t.Helper()
|
||||
|
||||
if string(got.body) != want {
|
||||
t.Errorf("answered with the body %q, want %q", got.body, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuestionAllowedIsAnsweredAndLogged(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", nil)
|
||||
|
||||
req := s.question(siteA, client, "/page?q=1")
|
||||
req.Header.Set(requestIDHeader, "the-id")
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
req.Header.Set(proxy.ContentLengthHeader, "1234")
|
||||
|
||||
got := do(t, req)
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
wantBody(t, got, "")
|
||||
|
||||
if id := got.header.Get(requestIDHeader); id != "the-id" {
|
||||
t.Errorf("answered with the id %q, want the-id", id)
|
||||
}
|
||||
|
||||
line := s.out.requestLine(t)
|
||||
wantLine(t, line, http.StatusOK, requestlog.ActionForward)
|
||||
|
||||
if line.ClientIP != client || line.PeerIP != rproxyPeer || line.Host != siteA ||
|
||||
line.Path != "/page" || line.Query != "q=1" || line.RequestID != "the-id" ||
|
||||
line.Scheme != "https" || line.ContentLength != 1234 {
|
||||
t.Errorf("log line is %+v", line.Line)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPv6VisitorIsCountedInItsGroup(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{rateLimitPerMinute: "1"})
|
||||
|
||||
s.allowed("2001:db8::1")
|
||||
|
||||
got := s.ask("2001:db8::2", "/")
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
}
|
||||
|
||||
func TestQuestionWithoutAnAddressGetsNoDisposition(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", nil)
|
||||
|
||||
got := s.ask("not an address", "/")
|
||||
wantDisposition(t, got, http.StatusBadRequest, "")
|
||||
}
|
||||
|
||||
func TestQuestionDeniedGetsTheBanResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, status := range []int{http.StatusForbidden, http.StatusTooManyRequests} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
denyNets: client, banResponse: strconv.Itoa(status),
|
||||
})
|
||||
|
||||
got := s.ask(client, "/")
|
||||
wantDisposition(t, got, status, proxy.DispositionDeny)
|
||||
wantBody(t, got, http.StatusText(status)+"\n")
|
||||
wantLine(t, s.out.requestLine(t), status, requestlog.ActionDenied)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBanResponseCloseIsAnAnswerOfItsOwn(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
denyNets: client, banResponse: banResponseClose, metricsToken: token,
|
||||
})
|
||||
|
||||
got := s.ask(client, "/")
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionClose)
|
||||
wantBody(t, got, "")
|
||||
// The visitor is sent nothing.
|
||||
wantLine(t, s.out.requestLine(t), 0, requestlog.ActionDenied)
|
||||
wantMetric(t, s.metrics(), `smallwebwaf_requests_total{action="denied",instance="`+
|
||||
alertInstance+`",status_class="none"}`, 1)
|
||||
}
|
||||
|
||||
func TestBlockRuleIsDeniedWith403AndABanRuleWithTheBanResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
rulesDir: writeRules(t, testRules),
|
||||
banResponse: "429",
|
||||
})
|
||||
|
||||
got := s.ask(client, "/blocked")
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
wantLine(t, s.out.requestLine(t), http.StatusForbidden,
|
||||
requestlog.ActionRuleBlocked)
|
||||
|
||||
got = s.ask(client, "/.env")
|
||||
wantDisposition(t, got, http.StatusTooManyRequests, proxy.DispositionDeny)
|
||||
wantLine(t, s.out.requestLines(t, 2)[1], http.StatusTooManyRequests,
|
||||
requestlog.ActionBanned)
|
||||
}
|
||||
|
||||
func TestQuestionUnderTheOwnPrefixIsDeniedWith404AfterTheChecks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
metricsToken: token, denyNets: otherClient,
|
||||
})
|
||||
|
||||
for _, path := range []string{proxy.HealthPath, proxy.MetricsPath, proxy.ReportPath} {
|
||||
got := s.ask(client, path)
|
||||
wantDisposition(t, got, http.StatusNotFound, proxy.DispositionDeny)
|
||||
}
|
||||
|
||||
wantLine(t, s.out.requestLine(t), http.StatusNotFound, requestlog.ActionAdmin)
|
||||
|
||||
got := s.ask(otherClient, proxy.MetricsPath)
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
}
|
||||
|
||||
func TestObserveModeAllowsAndLogsWhatEnforceModeWouldHaveDone(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{mode: observe, denyNets: client})
|
||||
|
||||
got := s.ask(client, "/")
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
line := s.out.requestLine(t)
|
||||
wantLine(t, line, http.StatusOK, requestlog.ActionForward)
|
||||
wantWouldAction(t, line, requestlog.ActionDenied)
|
||||
}
|
||||
|
||||
func TestAllowCarriesTheLookupHeadersWhileTheSettingIsSet(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, tc := range []struct {
|
||||
setting string
|
||||
wantASN, wantCountry string
|
||||
}{
|
||||
{"true", "AS64496", "DE"},
|
||||
{"false", "", ""},
|
||||
} {
|
||||
t.Run(tc.setting, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
geojsURL, _ := startGeoJS(t)
|
||||
s := startServeWAF(t, geojsURL, map[string]string{
|
||||
addLookupHeaders: tc.setting, lookupTimeout: "1h", deniedCountries: "kp",
|
||||
})
|
||||
|
||||
got := s.ask(fromDE, "/")
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
asn, country := got.header.Get("X-Client-Asn"), got.header.Get("X-Client-Country")
|
||||
if asn != tc.wantASN || country != tc.wantCountry {
|
||||
t.Errorf("answered with the AS number %q and the country %q, want %q and %q",
|
||||
asn, country, tc.wantASN, tc.wantCountry)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportCountsTowardAByteLimitWhichThenBans(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{bytesLimitPerMinute: byteLimit})
|
||||
|
||||
// The request's own question counts no bytes: it is the report that does.
|
||||
id := s.allowed(client)
|
||||
s.allowed(client)
|
||||
|
||||
if held := s.server.Ledger.Snapshot(); len(held) != 0 {
|
||||
t.Fatalf("banned before any report: %v", held)
|
||||
}
|
||||
|
||||
// 100 bytes are over the limit of 99.
|
||||
got := s.report(proxy.Report{
|
||||
RequestID: id, Status: http.StatusBadGateway,
|
||||
RequestBytes: bodyBytes, ResponseBytes: answerBytes,
|
||||
})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
held := s.server.Ledger.Snapshot()
|
||||
if len(held) != 1 || held[0].Cause != bans.CauseLimit ||
|
||||
held[0].Notes.Kind != ratelimit.KindBytes ||
|
||||
held[0].Notes.Request.Status != http.StatusBadGateway ||
|
||||
held[0].Notes.Request.Host != siteA {
|
||||
t.Errorf("bans held are %+v", held)
|
||||
}
|
||||
|
||||
got = s.ask(client, "/")
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
|
||||
if !strings.Contains(s.out.text(), `"msg":"a report's bytes broke a byte limit"`) {
|
||||
t.Error("no message says that a report's bytes broke a byte limit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportCountsAtThePercentageItsQuestionWasGiven(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
geojsURL, _ := startGeoJS(t)
|
||||
// 100 bytes pass half of a limit of 99 and are within a limit of 199.
|
||||
s := startServeWAF(t, geojsURL, map[string]string{
|
||||
bytesLimitPerMinute: "199", countryBytesPercent: countryDEHalf,
|
||||
lookupTimeout: "1h",
|
||||
})
|
||||
|
||||
s.passedOn(fromKP)
|
||||
wantDisposition(t, s.ask(fromKP, "/"), http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
s.passedOn(fromDE)
|
||||
wantDisposition(t, s.ask(fromDE, "/"), http.StatusForbidden, proxy.DispositionDeny)
|
||||
}
|
||||
|
||||
func TestReportAddsTheRequestToItsClientsHistoryAndTheAnomalyCounters(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
"SWWAF_ANOMALY_CLIENT_REQUESTS_PER_MINUTE": "1000",
|
||||
})
|
||||
|
||||
id := s.allowed(client)
|
||||
|
||||
if requests := s.history().Requests; requests != 0 {
|
||||
t.Errorf("history holds %d requests before the report, want none", requests)
|
||||
}
|
||||
|
||||
if counters := s.server.Anomalies.Snapshot(); len(counters) != 0 {
|
||||
t.Errorf("anomaly counters %v before the report, want none", counters)
|
||||
}
|
||||
|
||||
got := s.report(proxy.Report{
|
||||
RequestID: id, Status: http.StatusBadGateway,
|
||||
RequestBytes: bodyBytes, ResponseBytes: answerBytes,
|
||||
})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
history := s.history()
|
||||
if history.Requests != 1 || history.Forwarded != 1 ||
|
||||
history.RequestBytes != bodyBytes || history.ResponseBytes != answerBytes ||
|
||||
history.Responses.Status5xx != 1 {
|
||||
t.Errorf("history is %+v", history)
|
||||
}
|
||||
|
||||
if counters := s.server.Anomalies.Snapshot(); len(counters) != 1 {
|
||||
t.Errorf("anomaly counters %v, want the client's", counters)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeniedRequestIsFinishedAtItsDecision(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{rateLimitPerMinute: "1"})
|
||||
|
||||
s.allowed(client)
|
||||
wantDisposition(t, s.ask(client, "/"), http.StatusForbidden, proxy.DispositionDeny)
|
||||
|
||||
history := s.history()
|
||||
if history.Requests != 1 || history.Refused != 1 {
|
||||
t.Errorf("history is %+v, want the refused request alone", history)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsCountAnAllowedRequestFromItsReport(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{metricsToken: token})
|
||||
|
||||
id := s.allowed(client)
|
||||
|
||||
const series = `{action="forward",instance="` + alertInstance + `",status_class="5xx"}`
|
||||
|
||||
metrics := s.metrics()
|
||||
wantNoSeries(t, metrics, "smallwebwaf_requests_total"+series)
|
||||
wantMetric(t, metrics, `smallwebwaf_requests_in_flight{instance="`+alertInstance+`"}`,
|
||||
1) // the scrape itself
|
||||
|
||||
got := s.report(proxy.Report{
|
||||
RequestID: id, Status: http.StatusBadGateway,
|
||||
RequestBytes: bodyBytes, ResponseBytes: answerBytes,
|
||||
DurationTotal: 5, DurationUpstreamTotal: 4,
|
||||
})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
metrics = s.metrics()
|
||||
wantMetric(t, metrics, "smallwebwaf_requests_total"+series, 1)
|
||||
wantMetric(t, metrics, "smallwebwaf_request_bytes_total"+series, bodyBytes)
|
||||
wantMetric(t, metrics, "smallwebwaf_response_bytes_total"+series, answerBytes)
|
||||
wantMetric(t, metrics, `smallwebwaf_upstream_duration_seconds_sum{instance="`+
|
||||
alertInstance+`"}`, 0.004)
|
||||
}
|
||||
|
||||
func TestReportForARequestNotHeldIsIgnored(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{bytesLimitPerMinute: byteLimit})
|
||||
|
||||
got := s.report(proxy.Report{RequestID: "no-such-request", ResponseBytes: 1000})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
if clients := s.server.Limiter.Snapshot(); len(clients) != 0 {
|
||||
t.Errorf("the table of clients holds %v", clients)
|
||||
}
|
||||
|
||||
if held := s.server.Ledger.Snapshot(); len(held) != 0 {
|
||||
t.Errorf("bans held are %v", held)
|
||||
}
|
||||
|
||||
// A second report of the same request does not count it twice.
|
||||
id := s.allowed(client)
|
||||
for range 2 {
|
||||
got = s.report(proxy.Report{RequestID: id, ResponseBytes: answerBytes})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
}
|
||||
|
||||
if counted := s.history().ResponseBytes; counted != answerBytes {
|
||||
t.Errorf("history holds %d response bytes, want %d", counted, answerBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportThatCannotBeReadIsRefusedAndTheRequestStaysHeld(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", nil)
|
||||
|
||||
id := s.allowed(client)
|
||||
|
||||
for _, body := range []string{
|
||||
"not JSON",
|
||||
`{"request_id":"` + id + `","request_bytes":-1}`,
|
||||
`{"request_id":"` + id + `","response_bytes":-1}`,
|
||||
} {
|
||||
got := do(t, newRequest(t, http.MethodPost, s.addr, proxy.ReportPath,
|
||||
strings.NewReader(body)))
|
||||
wantStatus(t, got, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
got := s.report(proxy.Report{RequestID: id, ResponseBytes: answerBytes})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
if counted := s.history().ResponseBytes; counted != answerBytes {
|
||||
t.Errorf("history holds %d response bytes, want %d", counted, answerBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisitorCannotHaveItsReportTakenForAnothersByChoosingItsID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
chosen = "chosen-by-a-visitor"
|
||||
exempt = "/static/x"
|
||||
)
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
bytesLimitPerMinute: byteLimit, rateLimitExemptPaths: "/static/",
|
||||
})
|
||||
|
||||
// The request whose bytes are not counted takes the id first.
|
||||
first := s.question(siteA, client, exempt)
|
||||
first.Header.Set(requestIDHeader, chosen)
|
||||
gotFirst := do(t, first)
|
||||
wantDisposition(t, gotFirst, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
second := s.question(siteA, client, "/download")
|
||||
second.Header.Set(requestIDHeader, chosen)
|
||||
gotSecond := do(t, second)
|
||||
wantDisposition(t, gotSecond, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
id := gotSecond.header.Get(requestIDHeader)
|
||||
if gotFirst.header.Get(requestIDHeader) != chosen || id == chosen || id == "" {
|
||||
t.Errorf("answered with the ids %q and %q, want %q and a new one",
|
||||
gotFirst.header.Get(requestIDHeader), id, chosen)
|
||||
}
|
||||
|
||||
if line := s.out.requestLines(t, 2)[1]; line.RequestID != id {
|
||||
t.Errorf("log line has request_id %q, want %q", line.RequestID, id)
|
||||
}
|
||||
|
||||
got := s.report(proxy.Report{RequestID: id, ResponseBytes: 1000})
|
||||
wantStatus(t, got, http.StatusNoContent)
|
||||
|
||||
if held := s.server.Ledger.Snapshot(); len(held) != 1 {
|
||||
t.Errorf("bans held are %v, want the one the download's bytes make", held)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIDAJSONReportCannotCarryIsReplaced(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{bytesLimitPerMinute: byteLimit})
|
||||
|
||||
req := s.question(siteA, client, "/")
|
||||
req.Header.Set(requestIDHeader, "not-utf-8-\xff")
|
||||
|
||||
got := do(t, req)
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
report := s.report(proxy.Report{
|
||||
RequestID: got.header.Get(requestIDHeader), ResponseBytes: 1000,
|
||||
})
|
||||
wantStatus(t, report, http.StatusNoContent)
|
||||
|
||||
if held := s.server.Ledger.Snapshot(); len(held) != 1 {
|
||||
t.Errorf("bans held are %v, want the one the report's bytes make", held)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBanMadeThroughOneHostRefusesTheClientOnAnother(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{rulesDir: writeRules(t, testRules)})
|
||||
|
||||
got := do(t, s.question(siteA, client, "/.env"))
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
|
||||
got = do(t, s.question(siteB, client, "/"))
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
|
||||
lines := s.out.requestLines(t, 2)
|
||||
if lines[0].Host != siteA || lines[1].Host != siteB {
|
||||
t.Errorf("log lines have the hosts %q and %q", lines[0].Host, lines[1].Host)
|
||||
}
|
||||
|
||||
held := s.server.Ledger.Snapshot()
|
||||
if len(held) != 1 || held[0].Notes.Request.Host != siteA {
|
||||
t.Errorf("bans held are %+v, want one whose notes name %s", held, siteA)
|
||||
}
|
||||
|
||||
waiting := s.queue.Snapshot().Waiting[alerts.DestinationWebhook]
|
||||
if len(waiting) == 0 || waiting[0].Host != siteA {
|
||||
t.Errorf("alerts waiting are %+v, want the ban's, naming %s", waiting, siteA)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestsOnEverySiteCountTowardOneSetOfLimits(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{rateLimitPerMinute: "1"})
|
||||
|
||||
s.allowed(client)
|
||||
|
||||
got := do(t, s.question(siteB, client, "/"))
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
}
|
||||
|
||||
func TestOwnEndpointsAnswerOnlyWithoutTheClientHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Were a check run on its requests, localhost's would be refused.
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
metricsToken: token, adminToken: adminSecret, denyNets: localhost,
|
||||
})
|
||||
|
||||
for _, tc := range []struct {
|
||||
path, authorization string
|
||||
want int
|
||||
}{
|
||||
{proxy.HealthPath, "", http.StatusOK},
|
||||
{proxy.MetricsPath, bearer, http.StatusOK},
|
||||
{proxy.MetricsPath, "", http.StatusUnauthorized},
|
||||
{proxy.BansPath, adminBearer, http.StatusOK},
|
||||
{proxy.BansPath, "", http.StatusUnauthorized},
|
||||
{proxy.ClientsPath + client, adminBearer, http.StatusOK},
|
||||
{proxy.ReportPath, "", http.StatusNotFound},
|
||||
{"/_smallwebwaf/other", "", http.StatusNotFound},
|
||||
{"/", "", http.StatusNotFound},
|
||||
} {
|
||||
req := newRequest(t, http.MethodGet, s.addr, tc.path, http.NoBody)
|
||||
req.Header.Set("Authorization", tc.authorization)
|
||||
wantDisposition(t, do(t, req), tc.want, "")
|
||||
|
||||
// The same request carrying the header is a question about it.
|
||||
req = newRequest(t, http.MethodGet, s.addr, tc.path, http.NoBody)
|
||||
req.Header.Set("Authorization", tc.authorization)
|
||||
req.Header.Set(proxy.ClientHeader, client)
|
||||
|
||||
if strings.HasPrefix(tc.path, "/_smallwebwaf/") {
|
||||
wantDisposition(t, do(t, req), http.StatusNotFound, proxy.DispositionDeny)
|
||||
} else {
|
||||
wantDisposition(t, do(t, req), http.StatusOK, proxy.DispositionAllow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportWritesNoLogLine(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", nil)
|
||||
|
||||
s.passedOn(client)
|
||||
// The health check's line comes after the question's.
|
||||
wantStatus(t, get(t, s.addr, proxy.HealthPath), http.StatusOK)
|
||||
|
||||
lines := s.out.requestLines(t, 2)
|
||||
if len(lines) != 2 || lines[1].Path != proxy.HealthPath {
|
||||
t.Errorf("request log lines are %+v, want the question's and the health check's",
|
||||
lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsOfTheLimitsAndTheProxiesAreIgnored(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
requestMaxBytes: "1",
|
||||
clientHeaderMaxBytes: "5K",
|
||||
clientRequestTimeout: off,
|
||||
clientResponseTimeout: off,
|
||||
trustedProxies: localhost,
|
||||
})
|
||||
|
||||
req := newRequest(t, http.MethodPost, s.addr, "/", strings.NewReader("a body"))
|
||||
req.Host = siteA
|
||||
req.Header.Set(proxy.ClientHeader, client)
|
||||
req.Header.Set(proxy.ContentLengthHeader, "1073741824")
|
||||
req.Header.Set(forwardedFor, otherClient)
|
||||
req.Header.Set("X-Long", strings.Repeat("x", 40<<10))
|
||||
|
||||
got := do(t, req)
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
|
||||
line := s.out.requestLine(t)
|
||||
if line.ClientIP != client || line.ContentLength != 1<<30 {
|
||||
t.Errorf("log line has client_ip %q and content_length %d",
|
||||
line.ClientIP, line.ContentLength)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChecksSeeTheHeadersTheVisitorSent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
rulesDir: writeRules(t, `
|
||||
own-header header:X-Smallwebwaf-Client block .
|
||||
announced header:Content-Length block ^70000$
|
||||
carried header:Content-Length block ^6$
|
||||
`),
|
||||
})
|
||||
|
||||
// What the question's own Content-Length says, 6, is not what the visitor
|
||||
// announced.
|
||||
for _, tc := range []struct {
|
||||
announced string
|
||||
want int
|
||||
}{
|
||||
{"70000", http.StatusForbidden},
|
||||
{"", http.StatusOK},
|
||||
{"6000", http.StatusOK},
|
||||
} {
|
||||
req := newRequest(t, http.MethodPost, s.addr, "/", strings.NewReader("a body"))
|
||||
req.Header.Set(proxy.ClientHeader, client)
|
||||
|
||||
if tc.announced != "" {
|
||||
req.Header.Set(proxy.ContentLengthHeader, tc.announced)
|
||||
}
|
||||
|
||||
wantStatus(t, do(t, req), tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoreRuleSetReadsTheBodyAQuestionCarries(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
wafMode: block, wafBodyLimit: "1M",
|
||||
})
|
||||
|
||||
ask := func(contentType, body string) answer {
|
||||
req := newRequest(t, http.MethodPost, s.addr, "/", strings.NewReader(body))
|
||||
req.Header.Set(proxy.ClientHeader, client)
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
req.Header.Set(proxy.ContentLengthHeader, "100000")
|
||||
|
||||
return do(t, req)
|
||||
}
|
||||
|
||||
got := ask(formData, "id=1'%20OR%20'1'='1")
|
||||
wantDisposition(t, got, http.StatusForbidden, proxy.DispositionDeny)
|
||||
|
||||
// The first 64 KiB of a longer JSON body cannot be parsed, which is no
|
||||
// attack, so the Core Rule Set does not read it.
|
||||
cut := `{"text":"` + strings.Repeat("x", proxy.QuestionBodyMaxBytes)
|
||||
got = ask("application/json", cut[:proxy.QuestionBodyMaxBytes])
|
||||
wantDisposition(t, got, http.StatusOK, proxy.DispositionAllow)
|
||||
}
|
||||
|
||||
func TestAnomalyAlertNamesTheSite(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := startServeWAF(t, "", map[string]string{
|
||||
"SWWAF_ANOMALY_CLIENT_REQUESTS_PER_MINUTE": "1",
|
||||
})
|
||||
|
||||
for range 2 {
|
||||
s.passedOn(client)
|
||||
}
|
||||
|
||||
waiting := s.queue.Snapshot().Waiting[alerts.DestinationWebhook]
|
||||
if len(waiting) != 1 || waiting[0].Event != alerts.EventAnomaly ||
|
||||
waiting[0].Host != siteA {
|
||||
t.Errorf("alerts waiting are %+v, want an anomaly naming %s", waiting, siteA)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user