Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3761ac7d0 | ||
|
|
eb1c75d264 | ||
|
|
17bbea919a |
No files matched your search
@@ -74,9 +74,9 @@ never as a time.
|
||||
`go.uber.org/fx`. fx builds the parts of `waf` and `rproxy`, and starts
|
||||
and stops their background work.
|
||||
- `internal/config`: reads the settings, the one place they are read.
|
||||
- `internal/waf`: `waf`'s server. It runs the checks in `check`. Its
|
||||
`routes.go` lists `waf`'s own endpoints. It counts bytes, refusals and
|
||||
anomalies, and writes the log lines.
|
||||
- `internal/waf`: `waf`'s server. It runs the checks in `check`, and answers
|
||||
`waf`'s own endpoints in `answerOwnEndpoint`. It counts bytes, refusals
|
||||
and anomalies, and writes the log lines.
|
||||
- `internal/rproxy`: the reverse proxy in front of one app that asks `waf`
|
||||
about each request. It passes a request to the app with the standard
|
||||
library's `httputil.ReverseProxy`, within the time and size limits.
|
||||
@@ -128,7 +128,6 @@ never as a time.
|
||||
default `SWW_WAF_CORE_RULE_SET_DISABLED_RULES`, are built for that
|
||||
version. They are checked again before the version changes, since rule
|
||||
ids, and what each rule matches, change between versions;
|
||||
- `github.com/go-chi/chi/v5` to route the requests to `waf`'s own endpoints;
|
||||
- `github.com/hashicorp/golang-lru/v2` for the bounded tables;
|
||||
- `github.com/oschwald/maxminddb-golang/v2` to read the lookup database;
|
||||
- `github.com/fsnotify/fsnotify` to notice edited files;
|
||||
|
||||
@@ -7,7 +7,6 @@ require (
|
||||
github.com/corazawaf/coraza-coreruleset/v4 v4.25.0
|
||||
github.com/corazawaf/coraza/v3 v3.8.2-0.20261022102553-d028be399c68
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7
|
||||
github.com/maxmind/mmdbwriter v1.2.0
|
||||
github.com/oschwald/maxminddb-golang/v2 v2.7.0
|
||||
|
||||
@@ -21,8 +21,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
|
||||
+162
-30
@@ -12,6 +12,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -81,9 +82,17 @@ type request struct {
|
||||
// upgraded is the connection to the app once the app has switched protocols,
|
||||
// as for a WebSocket, and nil otherwise.
|
||||
upgraded *upgradedConn
|
||||
// limits are the request's SWW_RPROXY_MAX_REQUEST_TIME_MS and
|
||||
// SWW_RPROXY_MAX_RESPONSE_TIME_MS.
|
||||
limits *timeLimits
|
||||
|
||||
// mu guards what follows. The time limits run on goroutines of their own,
|
||||
// and the transport starts and stops them, and notes requestEnd, from its
|
||||
// own; once timersStopped is set, neither time limit acts any more.
|
||||
mu sync.Mutex
|
||||
timersStopped bool
|
||||
requestTimer *time.Timer
|
||||
responseTimer *time.Timer
|
||||
// requestEnd is when the app had been sent the whole request, or the answer
|
||||
// started, if that was sooner.
|
||||
requestEnd time.Time
|
||||
}
|
||||
|
||||
// newRequest starts handling r: it notes the time, works out the visitor from
|
||||
@@ -118,25 +127,12 @@ func (h *handler) newRequest(
|
||||
}
|
||||
}
|
||||
|
||||
rq.limits = &timeLimits{
|
||||
maxRequestTime: h.config.MaxRequestTime,
|
||||
maxResponseTime: h.config.MaxResponseTime,
|
||||
start: rq.start,
|
||||
refuse: rq.refuse,
|
||||
waitingForVisitor: func() bool {
|
||||
return rq.body != nil && rq.body.waiting.Load()
|
||||
},
|
||||
endVisitorRead: func() {
|
||||
_ = rq.rc.SetReadDeadline(time.Now())
|
||||
},
|
||||
}
|
||||
|
||||
return rq
|
||||
}
|
||||
|
||||
// answerHealth answers the health check.
|
||||
func (rq *request) answerHealth() {
|
||||
rq.prepareOwnAnswer(rq.limits.requestDeadline())
|
||||
rq.prepareOwnAnswer(rq.requestDeadline())
|
||||
rq.out.Header().Set("Content-Type", plainText)
|
||||
rq.send(http.StatusOK, []byte("ok\n"))
|
||||
}
|
||||
@@ -152,7 +148,7 @@ func (rq *request) readFirstPartOfBody() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
_ = rq.rc.SetReadDeadline(rq.limits.requestDeadline())
|
||||
_ = rq.rc.SetReadDeadline(rq.requestDeadline())
|
||||
held, err := io.ReadAll(
|
||||
io.LimitReader(rq.body, wafprotocol.QuestionBodyMaxBytes),
|
||||
)
|
||||
@@ -192,7 +188,7 @@ func (rq *request) forward(ctx context.Context) {
|
||||
|
||||
rq.cancel = cancel
|
||||
ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
|
||||
WroteRequest: rq.limits.wroteRequest,
|
||||
WroteRequest: rq.wroteRequest,
|
||||
})
|
||||
|
||||
out := rq.in.WithContext(ctx)
|
||||
@@ -209,7 +205,7 @@ func (rq *request) forward(ctx context.Context) {
|
||||
ErrorHandler: rq.answerError,
|
||||
}
|
||||
|
||||
rq.limits.startRequestTimer()
|
||||
rq.startRequestTimer()
|
||||
rq.upstreamStart = time.Now()
|
||||
reverseProxy.ServeHTTP(rq.out, out)
|
||||
}
|
||||
@@ -252,7 +248,7 @@ func (rq *request) modifyResponse(res *http.Response) error {
|
||||
// switch, as when the app's Upgrade is not the visitor's, so the status
|
||||
// is noted only once it has taken over the connection, by rq.out's
|
||||
// Hijack.
|
||||
rq.limits.stop()
|
||||
rq.stopTimers()
|
||||
|
||||
conn, ok := res.Body.(io.ReadWriteCloser)
|
||||
if ok {
|
||||
@@ -263,7 +259,7 @@ func (rq *request) modifyResponse(res *http.Response) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
requestEnd := rq.limits.endRequest()
|
||||
requestEnd := rq.endRequest()
|
||||
|
||||
// An answer that arrives once SWW_RPROXY_MAX_RESPONSE_TIME_MS has run out is not
|
||||
// passed on: the visitor is answered 504.
|
||||
@@ -293,12 +289,12 @@ func (rq *request) modifyResponse(res *http.Response) error {
|
||||
|
||||
// An answer that arrives before the app has been sent the whole request ends
|
||||
// the request, and SWW_RPROXY_MAX_RESPONSE_TIME_MS starts.
|
||||
rq.limits.startResponseTimer(requestEnd)
|
||||
rq.startResponseTimer(requestEnd)
|
||||
|
||||
res.Body = &responseBody{
|
||||
body: limitBody(res.Body, maxBytes),
|
||||
refuse: rq.refuse,
|
||||
responseReceived: rq.limits.stop,
|
||||
responseReceived: rq.responseReceived,
|
||||
ctx: rq.in.Context(),
|
||||
}
|
||||
rq.out.afterStatus = rq.setResponseDeadline
|
||||
@@ -351,7 +347,7 @@ func (rq *request) answer(status int) {
|
||||
// A visitor found too slow is read no more; any other may go on sending until
|
||||
// its time is up, so that the rest of the body is read and the request ends
|
||||
// cleanly: by Go's server, or by readRestOfBody.
|
||||
deadline := rq.limits.requestDeadline()
|
||||
deadline := rq.requestDeadline()
|
||||
if status == http.StatusRequestTimeout {
|
||||
deadline = time.Now()
|
||||
}
|
||||
@@ -397,7 +393,7 @@ func (rq *request) closeAfterAnswer() {
|
||||
// used that time up first, and at least minSendTime.
|
||||
func (rq *request) prepareOwnAnswer(deadline time.Time) {
|
||||
rq.stopReadingBody(deadline)
|
||||
rq.limits.endRequest()
|
||||
rq.endRequest()
|
||||
|
||||
limit := rq.h.config.MaxResponseTime
|
||||
if limit > 0 {
|
||||
@@ -418,7 +414,7 @@ func (rq *request) refuse(status int) {
|
||||
// finish ends the request's time limits, writes its log line and, if waf
|
||||
// answered the question, sends the report. ctx is the request's own context.
|
||||
func (rq *request) finish(ctx context.Context) {
|
||||
rq.limits.stop()
|
||||
rq.stopTimers()
|
||||
|
||||
// After a cut-off answer, the reading of a body that has not arrived whole
|
||||
// ends now. Go's server would otherwise keep the connection open while it
|
||||
@@ -436,10 +432,10 @@ func (rq *request) finish(ctx context.Context) {
|
||||
errors.Is(rq.rc.Flush(), os.ErrDeadlineExceeded):
|
||||
rq.stopPassingOnBody(time.Now())
|
||||
case rq.refused.Load() == 0:
|
||||
rq.stopPassingOnBody(rq.limits.requestDeadline())
|
||||
rq.stopPassingOnBody(rq.requestDeadline())
|
||||
}
|
||||
|
||||
requestEnd := rq.limits.endRequest()
|
||||
requestEnd := rq.endRequest()
|
||||
end := time.Now()
|
||||
requestBytes, responseBytes := rq.bytesEachWay()
|
||||
|
||||
@@ -513,6 +509,17 @@ func (rq *request) bytesEachWay() (int64, int64) {
|
||||
return requestBytes, responseBytes
|
||||
}
|
||||
|
||||
// requestDeadline is when the visitor must have sent its whole request, or zero
|
||||
// when SWW_RPROXY_MAX_REQUEST_TIME_MS is off.
|
||||
func (rq *request) requestDeadline() time.Time {
|
||||
limit := rq.h.config.MaxRequestTime
|
||||
if limit == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return rq.start.Add(limit)
|
||||
}
|
||||
|
||||
// stopReadingBody ends, at deadline, the reading of a visitor's body that has not
|
||||
// arrived whole: Go's server then reads no more of it, and closes the connection
|
||||
// after the answer.
|
||||
@@ -569,6 +576,100 @@ func (rq *request) stopPassingOnBody(deadline time.Time) {
|
||||
rq.stopReadingBody(deadline)
|
||||
}
|
||||
|
||||
// startRequestTimer starts SWW_RPROXY_MAX_REQUEST_TIME_MS, which runs from the
|
||||
// request's headers being read until the app has been sent the whole request.
|
||||
func (rq *request) startRequestTimer() {
|
||||
deadline := rq.requestDeadline()
|
||||
if deadline.IsZero() {
|
||||
return
|
||||
}
|
||||
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
rq.requestTimer = time.AfterFunc(
|
||||
time.Until(deadline),
|
||||
rq.requestTimedOut,
|
||||
)
|
||||
}
|
||||
|
||||
// requestTimedOut is called when SWW_RPROXY_MAX_REQUEST_TIME_MS runs out while the
|
||||
// request is still on its way to the app. The answer names the side rproxy was
|
||||
// waiting on at that moment: 408 when it was waiting for the visitor to send more
|
||||
// of its body, 504 when it was waiting for the app to be reached or to take what
|
||||
// it had.
|
||||
func (rq *request) requestTimedOut() {
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
if rq.timersStopped {
|
||||
return
|
||||
}
|
||||
|
||||
if rq.body == nil || !rq.body.waiting.Load() {
|
||||
rq.refuse(http.StatusGatewayTimeout)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq.refuse(http.StatusRequestTimeout)
|
||||
// The transport gives up on the app only once its Read of the visitor's body
|
||||
// returns, so that Read is ended now. The lock keeps this from reaching the
|
||||
// connection after the request is handled.
|
||||
_ = rq.rc.SetReadDeadline(time.Now())
|
||||
}
|
||||
|
||||
// wroteRequest is called once the app has been sent the whole request:
|
||||
// SWW_RPROXY_MAX_REQUEST_TIME_MS ends and SWW_RPROXY_MAX_RESPONSE_TIME_MS starts.
|
||||
func (rq *request) wroteRequest(info httptrace.WroteRequestInfo) {
|
||||
if info.Err != nil {
|
||||
return // the transport gives up, or tries again
|
||||
}
|
||||
|
||||
requestEnd := rq.endRequest()
|
||||
|
||||
rq.mu.Lock()
|
||||
stopTimer(rq.requestTimer)
|
||||
rq.mu.Unlock()
|
||||
|
||||
rq.startResponseTimer(requestEnd)
|
||||
}
|
||||
|
||||
// startResponseTimer starts SWW_RPROXY_MAX_RESPONSE_TIME_MS, which runs from
|
||||
// requestEnd, unless it has started already.
|
||||
func (rq *request) startResponseTimer(requestEnd time.Time) {
|
||||
limit := rq.h.config.MaxResponseTime
|
||||
if limit == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
if rq.timersStopped || rq.responseTimer != nil {
|
||||
return
|
||||
}
|
||||
|
||||
rq.responseTimer = time.AfterFunc(time.Until(requestEnd.Add(limit)),
|
||||
rq.responseTimedOut)
|
||||
}
|
||||
|
||||
// responseTimedOut is called when SWW_RPROXY_MAX_RESPONSE_TIME_MS runs out before the
|
||||
// app has sent its whole answer.
|
||||
func (rq *request) responseTimedOut() {
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
if !rq.timersStopped {
|
||||
rq.refuse(http.StatusGatewayTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// responseReceived is called once the app has sent its whole answer.
|
||||
func (rq *request) responseReceived() {
|
||||
rq.stopTimers()
|
||||
}
|
||||
|
||||
// setResponseDeadline sends the status and headers of the app's answer, with
|
||||
// at least minSendTime, before ReverseProxy reads the answer's body, and then
|
||||
// the rest has until SWW_RPROXY_MAX_RESPONSE_TIME_MS after the end of the request.
|
||||
@@ -578,7 +679,7 @@ func (rq *request) setResponseDeadline() {
|
||||
return
|
||||
}
|
||||
|
||||
deadline := rq.limits.endRequest().Add(limit)
|
||||
deadline := rq.endRequest().Add(limit)
|
||||
|
||||
_ = rq.rc.SetWriteDeadline(
|
||||
time.Now().Add(max(time.Until(deadline), minSendTime)),
|
||||
@@ -586,3 +687,34 @@ func (rq *request) setResponseDeadline() {
|
||||
_ = rq.rc.Flush()
|
||||
_ = rq.rc.SetWriteDeadline(deadline)
|
||||
}
|
||||
|
||||
// endRequest notes now as the end of the request, unless an end is noted, and
|
||||
// returns the end noted.
|
||||
func (rq *request) endRequest() time.Time {
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
if rq.requestEnd.IsZero() {
|
||||
rq.requestEnd = time.Now()
|
||||
}
|
||||
|
||||
return rq.requestEnd
|
||||
}
|
||||
|
||||
// stopTimers stops the request's time limits and keeps any from starting later:
|
||||
// the app's answer is complete, the connection upgraded, or the request handled.
|
||||
func (rq *request) stopTimers() {
|
||||
rq.mu.Lock()
|
||||
defer rq.mu.Unlock()
|
||||
|
||||
rq.timersStopped = true
|
||||
stopTimer(rq.requestTimer)
|
||||
stopTimer(rq.responseTimer)
|
||||
}
|
||||
|
||||
// stopTimer stops t, which is nil when its time limit is off.
|
||||
func stopTimer(t *time.Timer) {
|
||||
if t != nil {
|
||||
t.Stop()
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
package rproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// timeLimits are one request's two time limits: SWW_RPROXY_MAX_REQUEST_TIME_MS,
|
||||
// which runs from the request's headers being read until the app has been sent
|
||||
// the whole request, and SWW_RPROXY_MAX_RESPONSE_TIME_MS, which runs from then
|
||||
// until the app has sent its whole answer. A limit of zero is off. Each limit
|
||||
// runs on a goroutine of its own, and the transport starts and stops them from
|
||||
// its own.
|
||||
type timeLimits struct {
|
||||
maxRequestTime time.Duration
|
||||
maxResponseTime time.Duration
|
||||
// start is when the request's headers had been read.
|
||||
start time.Time
|
||||
// refuse refuses the request with 408 or 504 when a limit runs out.
|
||||
refuse func(status int)
|
||||
// waitingForVisitor reports whether a read of the visitor's body is waiting
|
||||
// for the visitor to send more.
|
||||
waitingForVisitor func() bool
|
||||
// endVisitorRead ends at once a read of the visitor's body that is waiting.
|
||||
endVisitorRead func()
|
||||
|
||||
// mu guards what follows. Once stopped is set, neither limit acts any more.
|
||||
mu sync.Mutex
|
||||
stopped bool
|
||||
requestTimer *time.Timer
|
||||
responseTimer *time.Timer
|
||||
// requestEnd is when the app had been sent the whole request, or the answer
|
||||
// started, if that was sooner.
|
||||
requestEnd time.Time
|
||||
}
|
||||
|
||||
// requestDeadline is when the visitor must have sent its whole request, or zero
|
||||
// when SWW_RPROXY_MAX_REQUEST_TIME_MS is off.
|
||||
func (l *timeLimits) requestDeadline() time.Time {
|
||||
if l.maxRequestTime == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return l.start.Add(l.maxRequestTime)
|
||||
}
|
||||
|
||||
// startRequestTimer starts SWW_RPROXY_MAX_REQUEST_TIME_MS.
|
||||
func (l *timeLimits) startRequestTimer() {
|
||||
deadline := l.requestDeadline()
|
||||
if deadline.IsZero() {
|
||||
return
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
l.requestTimer = time.AfterFunc(time.Until(deadline), l.requestTimedOut)
|
||||
}
|
||||
|
||||
// requestTimedOut is called when SWW_RPROXY_MAX_REQUEST_TIME_MS runs out while
|
||||
// the request is still on its way to the app. The answer names the side rproxy
|
||||
// was waiting on at that moment: 408 when it was waiting for the visitor to send
|
||||
// more of its body, 504 when it was waiting for the app to be reached or to take
|
||||
// what it had.
|
||||
func (l *timeLimits) requestTimedOut() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if l.stopped {
|
||||
return
|
||||
}
|
||||
|
||||
if !l.waitingForVisitor() {
|
||||
l.refuse(http.StatusGatewayTimeout)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
l.refuse(http.StatusRequestTimeout)
|
||||
// The transport gives up on the app only once its Read of the visitor's body
|
||||
// returns, so that Read is ended now. The lock keeps this from reaching the
|
||||
// connection after the request is handled.
|
||||
l.endVisitorRead()
|
||||
}
|
||||
|
||||
// wroteRequest is called once the app has been sent the whole request:
|
||||
// SWW_RPROXY_MAX_REQUEST_TIME_MS ends and SWW_RPROXY_MAX_RESPONSE_TIME_MS
|
||||
// starts.
|
||||
func (l *timeLimits) wroteRequest(info httptrace.WroteRequestInfo) {
|
||||
if info.Err != nil {
|
||||
return // the transport gives up, or tries again
|
||||
}
|
||||
|
||||
requestEnd := l.endRequest()
|
||||
|
||||
l.mu.Lock()
|
||||
stopTimer(l.requestTimer)
|
||||
l.mu.Unlock()
|
||||
|
||||
l.startResponseTimer(requestEnd)
|
||||
}
|
||||
|
||||
// startResponseTimer starts SWW_RPROXY_MAX_RESPONSE_TIME_MS, which runs from
|
||||
// requestEnd, unless it has started already.
|
||||
func (l *timeLimits) startResponseTimer(requestEnd time.Time) {
|
||||
if l.maxResponseTime == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if l.stopped || l.responseTimer != nil {
|
||||
return
|
||||
}
|
||||
|
||||
l.responseTimer = time.AfterFunc(
|
||||
time.Until(requestEnd.Add(l.maxResponseTime)),
|
||||
l.responseTimedOut,
|
||||
)
|
||||
}
|
||||
|
||||
// responseTimedOut is called when SWW_RPROXY_MAX_RESPONSE_TIME_MS runs out
|
||||
// before the app has sent its whole answer.
|
||||
func (l *timeLimits) responseTimedOut() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if !l.stopped {
|
||||
l.refuse(http.StatusGatewayTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// endRequest notes now as the end of the request, unless an end is noted, and
|
||||
// returns the end noted.
|
||||
func (l *timeLimits) endRequest() time.Time {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if l.requestEnd.IsZero() {
|
||||
l.requestEnd = time.Now()
|
||||
}
|
||||
|
||||
return l.requestEnd
|
||||
}
|
||||
|
||||
// stop stops both limits and keeps either from starting later: the app's
|
||||
// answer is complete, the connection upgraded, or the request handled.
|
||||
func (l *timeLimits) stop() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
l.stopped = true
|
||||
stopTimer(l.requestTimer)
|
||||
stopTimer(l.responseTimer)
|
||||
}
|
||||
|
||||
// stopTimer stops t, which is nil when its limit is off.
|
||||
func stopTimer(t *time.Timer) {
|
||||
if t != nil {
|
||||
t.Stop()
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package rproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The tests below run timeLimits in a synctest bubble, where time is a clock of
|
||||
// the test's own: time.Sleep moves it on at once, and synctest.Wait returns once
|
||||
// a limit that ran out has refused the request.
|
||||
|
||||
const (
|
||||
testRequestTime = 3 * time.Second
|
||||
testResponseTime = 5 * time.Second
|
||||
)
|
||||
|
||||
// limitsSeen is what a timeLimits under test did to its request.
|
||||
type limitsSeen struct {
|
||||
// refused is the status of the last refusal, or zero.
|
||||
refused atomic.Int64
|
||||
// readEnded is true once the read of the visitor's body was ended.
|
||||
readEnded atomic.Bool
|
||||
// waiting is what waitingForVisitor reports.
|
||||
waiting atomic.Bool
|
||||
}
|
||||
|
||||
// newTestLimits returns time limits that started now, with what they do noted
|
||||
// in seen.
|
||||
func newTestLimits(seen *limitsSeen) *timeLimits {
|
||||
return &timeLimits{
|
||||
maxRequestTime: testRequestTime,
|
||||
maxResponseTime: testResponseTime,
|
||||
start: time.Now(),
|
||||
refuse: func(status int) {
|
||||
seen.refused.Store(int64(status))
|
||||
},
|
||||
waitingForVisitor: seen.waiting.Load,
|
||||
endVisitorRead: func() {
|
||||
seen.readEnded.Store(true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// sleepThenWait moves the bubble's clock on by d and waits for what is then
|
||||
// due.
|
||||
func sleepThenWait(d time.Duration) {
|
||||
time.Sleep(d)
|
||||
synctest.Wait()
|
||||
}
|
||||
|
||||
func TestRequestTimeRunningOutWhileTheVisitorIsWaitedOnRefuses408(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
seen := &limitsSeen{}
|
||||
seen.waiting.Store(true)
|
||||
|
||||
limits := newTestLimits(seen)
|
||||
limits.startRequestTimer()
|
||||
|
||||
sleepThenWait(testRequestTime - time.Millisecond)
|
||||
|
||||
if got := seen.refused.Load(); got != 0 {
|
||||
t.Fatalf(
|
||||
"refused %d before the limit ran out, want nothing",
|
||||
got,
|
||||
)
|
||||
}
|
||||
|
||||
sleepThenWait(time.Millisecond)
|
||||
|
||||
if got := seen.refused.Load(); got != http.StatusRequestTimeout {
|
||||
t.Errorf("refused %d, want 408", got)
|
||||
}
|
||||
|
||||
if !seen.readEnded.Load() {
|
||||
t.Error("the read of the visitor's body goes on, want it ended")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestTimeRunningOutWhileTheAppIsWaitedOnRefuses504(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
seen := &limitsSeen{}
|
||||
|
||||
limits := newTestLimits(seen)
|
||||
limits.startRequestTimer()
|
||||
|
||||
sleepThenWait(testRequestTime)
|
||||
|
||||
if got := seen.refused.Load(); got != http.StatusGatewayTimeout {
|
||||
t.Errorf("refused %d, want 504", got)
|
||||
}
|
||||
|
||||
if seen.readEnded.Load() {
|
||||
t.Error("the read of the visitor's body was ended, want it not")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResponseTimeRunsFromTheEndOfTheRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
seen := &limitsSeen{}
|
||||
|
||||
limits := newTestLimits(seen)
|
||||
limits.startRequestTimer()
|
||||
|
||||
sleepThenWait(time.Second)
|
||||
|
||||
end := time.Now()
|
||||
|
||||
limits.wroteRequest(httptrace.WroteRequestInfo{})
|
||||
|
||||
if got := limits.endRequest(); !got.Equal(end) {
|
||||
t.Errorf("the request ended at %v, want %v", got, end)
|
||||
}
|
||||
|
||||
// Past SWW_RPROXY_MAX_REQUEST_TIME_MS, which the end of the request
|
||||
// stopped, and just short of SWW_RPROXY_MAX_RESPONSE_TIME_MS.
|
||||
sleepThenWait(testResponseTime - time.Millisecond)
|
||||
|
||||
if got := seen.refused.Load(); got != 0 {
|
||||
t.Fatalf(
|
||||
"refused %d before the limit ran out, want nothing",
|
||||
got,
|
||||
)
|
||||
}
|
||||
|
||||
sleepThenWait(time.Millisecond)
|
||||
|
||||
if got := seen.refused.Load(); got != http.StatusGatewayTimeout {
|
||||
t.Errorf("refused %d, want 504", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestStoppedLimitsRefuseNothing(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
seen := &limitsSeen{}
|
||||
seen.waiting.Store(true)
|
||||
|
||||
limits := newTestLimits(seen)
|
||||
limits.startRequestTimer()
|
||||
limits.stop()
|
||||
limits.startResponseTimer(limits.endRequest())
|
||||
|
||||
sleepThenWait(testRequestTime + testResponseTime)
|
||||
|
||||
if got := seen.refused.Load(); got != 0 {
|
||||
t.Errorf("refused %d, want nothing", got)
|
||||
}
|
||||
|
||||
if seen.readEnded.Load() {
|
||||
t.Error("the read of the visitor's body was ended, want it not")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -188,7 +188,7 @@ func canBeAsked(r *http.Request) bool {
|
||||
|
||||
// answerWith gives the visitor waf's answer, less its disposition.
|
||||
func (rq *request) answerWith(answer *wafAnswer) {
|
||||
rq.prepareOwnAnswer(rq.limits.requestDeadline())
|
||||
rq.prepareOwnAnswer(rq.requestDeadline())
|
||||
|
||||
header := rq.out.Header()
|
||||
maps.Copy(header, answer.header)
|
||||
|
||||
+147
-92
@@ -2,6 +2,7 @@ package waf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/state"
|
||||
)
|
||||
|
||||
@@ -39,23 +41,80 @@ var (
|
||||
errNotAddress = errors.New("is not an address, such as 203.0.113.9")
|
||||
)
|
||||
|
||||
// handleHealth answers GET wafprotocol.HealthPath.
|
||||
func handleHealth() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
// Set here rather than left to Go's server, which would set it only
|
||||
// after the log line has taken the response's headers.
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
_, _ = io.WriteString(w, "ok\n")
|
||||
// answerHealth answers a request for the health endpoint.
|
||||
func (rq *request) answerHealth() {
|
||||
rq.line.Action = requestlog.ActionOwnEndpoint
|
||||
// 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 one of waf's own endpoints. Each
|
||||
// needs a token, sent as Authorization: Bearer <token>: the metrics
|
||||
// SWW_WAF_METRICS_TOKEN, the others SWW_WAF_ADMIN_TOKEN. A request without it is
|
||||
// refused with 401. An endpoint whose token is unset answers 404, as any other
|
||||
// path does.
|
||||
func (rq *request) answerAdmin() {
|
||||
rq.line.Action = requestlog.ActionOwnEndpoint
|
||||
|
||||
token, answer := rq.endpoint()
|
||||
|
||||
switch {
|
||||
case token == "":
|
||||
http.Error(
|
||||
rq.out,
|
||||
http.StatusText(http.StatusNotFound),
|
||||
http.StatusNotFound,
|
||||
)
|
||||
case !hasToken(rq.in, token):
|
||||
rq.out.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(
|
||||
rq.out,
|
||||
http.StatusText(http.StatusUnauthorized),
|
||||
http.StatusUnauthorized,
|
||||
)
|
||||
default:
|
||||
answer()
|
||||
}
|
||||
}
|
||||
|
||||
// handleListBans answers GET BansPath with every ban held.
|
||||
func (h *handler) handleListBans() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
h.answerBans(w, h.ledger.Snapshot())
|
||||
// endpoint returns the token the request's endpoint needs, and what
|
||||
// answers the request there; "" when there is no such endpoint.
|
||||
func (rq *request) endpoint() (string, func()) {
|
||||
cfg := rq.h.config
|
||||
method, path := rq.in.Method, rq.in.URL.Path
|
||||
|
||||
switch {
|
||||
case method == http.MethodGet && path == MetricsPath:
|
||||
return cfg.MetricsToken, func() { rq.h.metrics.ServeHTTP(rq.out, rq.in) }
|
||||
case method == http.MethodGet && path == BansPath:
|
||||
return cfg.AdminToken, rq.listBans
|
||||
case method == http.MethodPost && path == BansPath:
|
||||
return cfg.AdminToken, rq.addBan
|
||||
case method == http.MethodDelete && strings.HasPrefix(path, BansPath+"/"):
|
||||
return cfg.AdminToken, rq.liftBans
|
||||
case method == http.MethodGet && strings.HasPrefix(path, ClientsPath):
|
||||
return cfg.AdminToken, rq.showClient
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
// hasToken reports whether r carries token, as Authorization: Bearer
|
||||
// <token>.
|
||||
func hasToken(r *http.Request, token string) bool {
|
||||
scheme, sent, _ := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
|
||||
return strings.EqualFold(scheme, "Bearer") &&
|
||||
subtle.ConstantTimeCompare([]byte(sent), []byte(token)) == 1
|
||||
}
|
||||
|
||||
// listBans answers GET BansPath with every ban held.
|
||||
func (rq *request) listBans() {
|
||||
rq.answerBans(rq.h.ledger.Snapshot())
|
||||
}
|
||||
|
||||
// banToAdd is the body of POST BansPath.
|
||||
type banToAdd struct {
|
||||
// Netblock is a netblock, or a client's address, which stands for the
|
||||
@@ -67,44 +126,44 @@ type banToAdd struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// handleAddBan answers POST BansPath: it bans the netblock the body names,
|
||||
// as an admin, from now for the duration the body gives, with its reason,
|
||||
// addBan answers POST BansPath: it bans the netblock the body names, as
|
||||
// an admin, from now for the duration the body gives, with its reason,
|
||||
// and answers with that ban.
|
||||
func (h *handler) handleAddBan() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
toAdd, err := readBanToAdd(r)
|
||||
func (rq *request) addBan() {
|
||||
toAdd, err := rq.readBanToAdd()
|
||||
|
||||
var (
|
||||
netblock netip.Prefix
|
||||
expires time.Time
|
||||
now = h.now()
|
||||
)
|
||||
var (
|
||||
netblock netip.Prefix
|
||||
expires time.Time
|
||||
now = rq.h.now()
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
netblock, err = h.parseBanNetblock(toAdd.Netblock)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
expires, err = expiry(toAdd.Duration, now)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ban := h.ledger.BanForAdmin(netblock, now, expires, toAdd.Reason)
|
||||
h.answerBans(w, []bans.Ban{ban})
|
||||
if err == nil {
|
||||
netblock, err = rq.h.parseBanNetblock(toAdd.Netblock)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
expires, err = expiry(toAdd.Duration, now)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
http.Error(rq.out, err.Error(), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ban := rq.h.ledger.BanForAdmin(netblock, now, expires, toAdd.Reason)
|
||||
rq.answerBans([]bans.Ban{ban})
|
||||
}
|
||||
|
||||
// readBanToAdd reads the body of POST BansPath: a JSON object with
|
||||
// nothing but whitespace after it, in at most banBodyMaxBytes.
|
||||
func readBanToAdd(r *http.Request) (banToAdd, error) {
|
||||
func (rq *request) readBanToAdd() (banToAdd, error) {
|
||||
data, err := io.ReadAll(
|
||||
http.MaxBytesReader(nil, r.Body, banBodyMaxBytes),
|
||||
http.MaxBytesReader(nil, rq.in.Body, banBodyMaxBytes),
|
||||
)
|
||||
rq.requestBytes = int64(len(data))
|
||||
|
||||
if err != nil {
|
||||
return banToAdd{}, fmt.Errorf("%w: %w", errNotBanToAdd, err)
|
||||
}
|
||||
@@ -191,31 +250,29 @@ func expiry(duration string, now time.Time) (time.Time, error) {
|
||||
return now.Add(length), nil
|
||||
}
|
||||
|
||||
// handleLiftBans answers DELETE BansPath/<client>: it lifts every ban
|
||||
// active on a netblock the client's address is in, and answers with those
|
||||
// bans, or with 404 when none is active.
|
||||
func (h *handler) handleLiftBans() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
client, err := pathAddress(r.URL.Path, BansPath+"/")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
// liftBans answers DELETE BansPath/<client>: it lifts every ban active on
|
||||
// a netblock the client's address is in, and answers with those bans, or
|
||||
// with 404 when none is active.
|
||||
func (rq *request) liftBans() {
|
||||
client, err := pathAddress(rq.in.URL.Path, BansPath+"/")
|
||||
if err != nil {
|
||||
http.Error(rq.out, err.Error(), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
lifted := h.ledger.Lift(client, h.now())
|
||||
if len(lifted) == 0 {
|
||||
http.Error(
|
||||
w,
|
||||
"no ban is active on "+client.String(),
|
||||
http.StatusNotFound,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
h.answerBans(w, lifted)
|
||||
return
|
||||
}
|
||||
|
||||
lifted := rq.h.ledger.Lift(client, rq.h.now())
|
||||
if len(lifted) == 0 {
|
||||
http.Error(
|
||||
rq.out,
|
||||
"no ban is active on "+client.String(),
|
||||
http.StatusNotFound,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq.answerBans(lifted)
|
||||
}
|
||||
|
||||
// clientAnswer is the answer to GET ClientsPath<ip>: the client the
|
||||
@@ -227,31 +284,29 @@ type clientAnswer struct {
|
||||
Bans []state.BanEntry `json:"bans"`
|
||||
}
|
||||
|
||||
// handleShowClient answers GET ClientsPath<ip> with what waf knows of the
|
||||
// client: its counters, its history, which holds its country as last looked
|
||||
// up and its offences, and its bans with their notes.
|
||||
func (h *handler) handleShowClient() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
addr, err := pathAddress(r.URL.Path, ClientsPath)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
// showClient answers GET ClientsPath<ip> with what waf knows of the client:
|
||||
// its counters, its history, which holds its country as last looked up and its
|
||||
// offences, and its bans with their notes.
|
||||
func (rq *request) showClient() {
|
||||
addr, err := pathAddress(rq.in.URL.Path, ClientsPath)
|
||||
if err != nil {
|
||||
http.Error(rq.out, err.Error(), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
answer := clientAnswer{
|
||||
Bans: state.BanEntries(h.ledger.Covering(addr)),
|
||||
}
|
||||
|
||||
client, seen := h.limiter.Client(
|
||||
clientGroup(h.config.IPv6GroupPrefix, addr),
|
||||
)
|
||||
if seen {
|
||||
answer.Client = &client
|
||||
}
|
||||
|
||||
h.answerJSON(w, answer)
|
||||
return
|
||||
}
|
||||
|
||||
answer := clientAnswer{
|
||||
Bans: state.BanEntries(rq.h.ledger.Covering(addr)),
|
||||
}
|
||||
|
||||
client, seen := rq.h.limiter.Client(
|
||||
clientGroup(rq.h.config.IPv6GroupPrefix, addr),
|
||||
)
|
||||
if seen {
|
||||
answer.Client = &client
|
||||
}
|
||||
|
||||
rq.answerJSON(answer)
|
||||
}
|
||||
|
||||
// pathAddress reads the client's address that follows prefix in path.
|
||||
@@ -267,27 +322,27 @@ func pathAddress(path, prefix string) (netip.Addr, error) {
|
||||
}
|
||||
|
||||
// answerBans answers with held under bans, as bans.json lists them.
|
||||
func (h *handler) answerBans(w http.ResponseWriter, held []bans.Ban) {
|
||||
h.answerJSON(w, struct {
|
||||
func (rq *request) answerBans(held []bans.Ban) {
|
||||
rq.answerJSON(struct {
|
||||
Bans []state.BanEntry `json:"bans"`
|
||||
}{state.BanEntries(held)})
|
||||
}
|
||||
|
||||
// answerJSON answers with value as indented JSON.
|
||||
func (h *handler) answerJSON(w http.ResponseWriter, value any) {
|
||||
func (rq *request) answerJSON(value any) {
|
||||
body, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
h.processLog.Error(
|
||||
rq.h.processLog.Error(
|
||||
"encoding an answer failed",
|
||||
"error",
|
||||
err.Error(),
|
||||
)
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError),
|
||||
http.Error(rq.out, http.StatusText(http.StatusInternalServerError),
|
||||
http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(append(body, '\n'))
|
||||
rq.out.Header().Set("Content-Type", "application/json")
|
||||
_, _ = rq.out.Write(append(body, '\n'))
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/state"
|
||||
"sneak.berlin/go/smallwebwaf/internal/waf"
|
||||
"sneak.berlin/go/smallwebwaf/internal/wafprotocol"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -334,39 +333,6 @@ func TestBanToAddThatCannotBeReadIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBanToAddIsLoggedWithTheBytesOfItsBody(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s, _, _ := startWithClock(
|
||||
t,
|
||||
"",
|
||||
map[string]string{adminToken: adminSecret},
|
||||
)
|
||||
|
||||
s.admin(http.MethodPost, waf.BansPath, banOtherClient, http.StatusOK)
|
||||
|
||||
line := s.out.endedLines(t, s.sent)[s.sent-1]
|
||||
if line.RequestBytes != int64(len(banOtherClient)) {
|
||||
t.Errorf(
|
||||
"the ban to add was logged with request_bytes %d, want %d",
|
||||
line.RequestBytes,
|
||||
len(banOtherClient),
|
||||
)
|
||||
}
|
||||
|
||||
// The health endpoint reads none of a body sent to it.
|
||||
s.ownEndpointRequest("", http.MethodGet, wafprotocol.HealthPath, "ok",
|
||||
http.StatusOK)
|
||||
|
||||
line = s.out.endedLines(t, s.sent)[s.sent-1]
|
||||
if line.RequestBytes != 0 {
|
||||
t.Errorf(
|
||||
"the health request was logged with request_bytes %d, want 0",
|
||||
line.RequestBytes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEndpointShowsTheClientAndItsBans(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -43,15 +43,6 @@ func (b blocklists) check(
|
||||
}
|
||||
}
|
||||
|
||||
// refusesWhateverTheLookupAnswers reports whether blocklists refuses rq, as
|
||||
// refusedByBlocklists says. The lookup's answer plays no part in it.
|
||||
func (b blocklists) refusesWhateverTheLookupAnswers(
|
||||
rq *request,
|
||||
_ time.Time,
|
||||
) bool {
|
||||
return b.refusedByBlocklists(b.lists.ListedBy(rq.client))
|
||||
}
|
||||
|
||||
// refusedByBlocklists reports whether the heuristic blocklists refuses a
|
||||
// client, given listedBy, the blocklists that list it: it does when one lists
|
||||
// it and SWW_WAF_BLOCKLIST_ACTION is deny.
|
||||
|
||||
@@ -58,14 +58,3 @@ func TestHealthEndpointCountsTowardNoLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthEndpointIsFoundAtItsPathPercentEncoded(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// %68 is h. An endpoint is found by the decoded path.
|
||||
s, _, _ := startWithClock(t, "", nil)
|
||||
|
||||
got := s.ownEndpointRequest("", http.MethodGet, "/_sww/%68ealthz", "",
|
||||
http.StatusOK)
|
||||
wantBody(t, got, "ok\n")
|
||||
}
|
||||
@@ -9,16 +9,6 @@ import (
|
||||
// and holds the settings and parts it reads. Add one line for it to one of the
|
||||
// lists that newHandler builds, which hands it those settings and parts. Its
|
||||
// settings go in config.WAF, and the comment at the top of its file names them.
|
||||
// A heuristic of afterLookup that can refuse a request whatever the lookup
|
||||
// answers also implements refusesWithoutLookup.
|
||||
//
|
||||
// Three places outside its file may change with it:
|
||||
// - waitForGeoJS in newHandler lists the settings that need the lookup's
|
||||
// answer;
|
||||
// - requestCanGetTag in internal/config/waf.go holds which setting can give a
|
||||
// request which tag;
|
||||
// - findBesideLookup does the work of each heuristic of besideLookup, by
|
||||
// name.
|
||||
|
||||
// heuristic is one of the checks that decide what waf does with a
|
||||
// request.
|
||||
@@ -30,15 +20,6 @@ type heuristic interface {
|
||||
check(ctx context.Context, rq *request, now time.Time) *verdict
|
||||
}
|
||||
|
||||
// refusesWithoutLookup is a heuristic of afterLookup that can tell, before the
|
||||
// lookup answers, that it will refuse a request whatever the answer.
|
||||
type refusesWithoutLookup interface {
|
||||
// refusesWhateverTheLookupAnswers reports whether the heuristic will refuse
|
||||
// rq at now, whatever the lookup answers about its client. It changes
|
||||
// nothing.
|
||||
refusesWhateverTheLookupAnswers(rq *request, now time.Time) bool
|
||||
}
|
||||
|
||||
// verdict is a heuristic refusing a request, or banning its client: the action
|
||||
// the log line names, one of requestlog's Action constants, and the figures the
|
||||
// heuristic acted on, by name, such as the count and the limit.
|
||||
|
||||
+31
-30
@@ -177,6 +177,30 @@ func newHandler(params Params) *handler {
|
||||
ipv6GroupPrefix: cfg.IPv6GroupPrefix,
|
||||
}
|
||||
|
||||
h.blocklists = blocklists{
|
||||
lists: params.Lists,
|
||||
action: cfg.BlocklistAction,
|
||||
hitNoter: hitNoter,
|
||||
}
|
||||
h.rateLimits = rateLimits{
|
||||
limiter: params.Limiter,
|
||||
exemptNets: cfg.RateLimitExemptNets,
|
||||
exemptPaths: cfg.RateLimitExemptPaths,
|
||||
banResponse: cfg.BanResponse,
|
||||
ipv6GroupPrefix: cfg.IPv6GroupPrefix,
|
||||
biasedThresholds: biasedThresholds{
|
||||
lists: params.Lists,
|
||||
tagLimitPercent: cfg.TagLimitPercent,
|
||||
asnBytesLimitPercent: cfg.ASNBytesLimitPercent,
|
||||
countryBytesLimitPercent: cfg.CountryBytesLimitPercent,
|
||||
unknownCountryLimitPercent: cfg.UnknownCountryLimitPercent,
|
||||
blocklistAction: cfg.BlocklistAction,
|
||||
blocklistLimitPercent: cfg.BlocklistLimitPercent,
|
||||
dnsblAbuseIPDBAction: cfg.DNSBLAbuseIPDBAction,
|
||||
dnsblAbuseIPDBLimitPercent: cfg.DNSBLAbuseIPDBLimitPercent,
|
||||
},
|
||||
banMaker: sharedBanMaker,
|
||||
}
|
||||
h.trapPaths = trapPaths{paths: cfg.TrapPaths, banMaker: sharedBanMaker}
|
||||
h.ruleFiles = ruleFiles{
|
||||
rules: params.Rules,
|
||||
@@ -206,11 +230,7 @@ func newHandler(params Params) *handler {
|
||||
}
|
||||
h.afterLookup = []heuristic{
|
||||
countries{allowed: cfg.ExclusivelyAllowedCountries},
|
||||
blocklists{
|
||||
lists: params.Lists,
|
||||
action: cfg.BlocklistAction,
|
||||
hitNoter: hitNoter,
|
||||
},
|
||||
h.blocklists,
|
||||
dnsbl{
|
||||
dnsbl: params.DNSBL,
|
||||
action: cfg.DNSBLAbuseIPDBAction,
|
||||
@@ -226,25 +246,7 @@ func newHandler(params Params) *handler {
|
||||
hitNoter: hitNoter,
|
||||
},
|
||||
tagDeny{tags: cfg.TagDeny},
|
||||
rateLimits{
|
||||
limiter: params.Limiter,
|
||||
exemptNets: cfg.RateLimitExemptNets,
|
||||
exemptPaths: cfg.RateLimitExemptPaths,
|
||||
banResponse: cfg.BanResponse,
|
||||
ipv6GroupPrefix: cfg.IPv6GroupPrefix,
|
||||
biasedThresholds: biasedThresholds{
|
||||
lists: params.Lists,
|
||||
tagLimitPercent: cfg.TagLimitPercent,
|
||||
asnBytesLimitPercent: cfg.ASNBytesLimitPercent,
|
||||
countryBytesLimitPercent: cfg.CountryBytesLimitPercent,
|
||||
unknownCountryLimitPercent: cfg.UnknownCountryLimitPercent,
|
||||
blocklistAction: cfg.BlocklistAction,
|
||||
blocklistLimitPercent: cfg.BlocklistLimitPercent,
|
||||
dnsblAbuseIPDBAction: cfg.DNSBLAbuseIPDBAction,
|
||||
dnsblAbuseIPDBLimitPercent: cfg.DNSBLAbuseIPDBLimitPercent,
|
||||
},
|
||||
banMaker: sharedBanMaker,
|
||||
},
|
||||
h.rateLimits,
|
||||
}
|
||||
h.besideLookup = []heuristic{h.trapPaths, h.ruleFiles, h.coreRuleSet}
|
||||
h.afterBesideLookup = []heuristic{tagDeny{tags: cfg.TagDeny}}
|
||||
@@ -266,8 +268,6 @@ func newHandler(params Params) *handler {
|
||||
},
|
||||
}
|
||||
|
||||
h.ownEndpoints = h.routes()
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -293,9 +293,6 @@ type handler struct {
|
||||
// awaitingReport holds the decision on each answered question by its id
|
||||
// until its report comes, and nil for a question still being handled.
|
||||
awaitingReport *lru.Cache[string, *decision]
|
||||
// ownEndpoints answers every request that is not a question, as routes
|
||||
// lists the endpoints.
|
||||
ownEndpoints http.Handler
|
||||
|
||||
// The lists of heuristics, each in the order its heuristics run. A client
|
||||
// in SWW_WAF_ALLOW_NETS skips them all.
|
||||
@@ -326,7 +323,11 @@ type handler struct {
|
||||
// afterAnswer, they only ban.
|
||||
onReport []heuristic
|
||||
|
||||
// The heuristics of besideLookup, whose work findBesideLookup does.
|
||||
// The heuristics of the lists that other steps of a request use too:
|
||||
// refusedWhateverTheAnswer asks blocklists and rateLimits, and
|
||||
// findBesideLookup does the work of trapPaths, ruleFiles and coreRuleSet.
|
||||
blocklists blocklists
|
||||
rateLimits rateLimits
|
||||
trapPaths trapPaths
|
||||
ruleFiles ruleFiles
|
||||
coreRuleSet coreRuleSet
|
||||
|
||||
@@ -67,14 +67,11 @@ func (r rateLimits) check(
|
||||
}
|
||||
}
|
||||
|
||||
// refusesWhateverTheLookupAnswers reports whether the heuristic rate_limits
|
||||
// will refuse rq at now, whatever its client's limit percentages, which the
|
||||
// lookup's answer can lower: the rate limits count it, and one more request
|
||||
// from its client takes it over a whole rate limit. It counts nothing.
|
||||
func (r rateLimits) refusesWhateverTheLookupAnswers(
|
||||
rq *request,
|
||||
now time.Time,
|
||||
) bool {
|
||||
// overAWholeRateLimit reports whether the heuristic rate_limits will refuse rq
|
||||
// at now, whatever its client's limit percentages: the rate limits count it,
|
||||
// and one more request from its client takes it over a whole rate limit. It
|
||||
// counts nothing.
|
||||
func (r rateLimits) overAWholeRateLimit(rq *request, now time.Time) bool {
|
||||
return r.countedByRateLimits(rq) &&
|
||||
r.limiter.OverARateLimit(
|
||||
clientGroup(r.ipv6GroupPrefix, rq.client),
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
package waf
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/wafprotocol"
|
||||
)
|
||||
|
||||
// routes returns the router of waf's own endpoints. A question never reaches
|
||||
// it, since ServeHTTP answers a question first. No check runs on a request
|
||||
// here: waf's address is on the private network, where the peers are rproxy
|
||||
// and the admin's tools, not visitors.
|
||||
func (h *handler) routes() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(matchDecodedPath)
|
||||
|
||||
// The report writes no log line of its own: it finishes the line of the
|
||||
// request it reports.
|
||||
r.Post(wafprotocol.ReportPath, h.handleReport())
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.logOwnEndpoint)
|
||||
// The answer to a path with no endpoint, and to a method the path has
|
||||
// no endpoint for, is set in this group, so that it is logged too.
|
||||
r.NotFound(answerNotFound)
|
||||
r.MethodNotAllowed(answerNotFound)
|
||||
|
||||
r.Get(wafprotocol.HealthPath, handleHealth())
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(requireToken(h.config.MetricsToken))
|
||||
r.Get(MetricsPath, h.metrics.ServeHTTP)
|
||||
})
|
||||
|
||||
// The handlers under BansPath/ and ClientsPath read the address from
|
||||
// the path themselves, so that one that is not an address gets 400
|
||||
// after the token check.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(requireToken(h.config.AdminToken))
|
||||
r.Get(BansPath, h.handleListBans())
|
||||
r.Post(BansPath, h.handleAddBan())
|
||||
r.Delete(BansPath+"/*", h.handleLiftBans())
|
||||
r.Get(ClientsPath+"*", h.handleShowClient())
|
||||
})
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// matchDecodedPath has the router match the decoded path, which the handlers
|
||||
// read. chi matches the path as sent when it is encoded in an unusual way,
|
||||
// which would make /_sww/%68ealthz a path with no endpoint.
|
||||
func matchDecodedPath(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
chi.RouteContext(r.Context()).RoutePath = r.URL.Path
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// logOwnEndpoint writes one log line for each request, with the action
|
||||
// own_endpoint. The line's request_bytes is how much of the body the handler
|
||||
// read.
|
||||
func (h *handler) logOwnEndpoint(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
peer := peerAddress(r)
|
||||
|
||||
rq := h.startRequest(w, r, peer, peer, false)
|
||||
defer rq.finish()
|
||||
|
||||
rq.line.Action = requestlog.ActionOwnEndpoint
|
||||
|
||||
counted := r.Clone(r.Context())
|
||||
counted.Body = &countedBody{
|
||||
ReadCloser: r.Body,
|
||||
read: &rq.requestBytes,
|
||||
}
|
||||
|
||||
next.ServeHTTP(rq.out, counted)
|
||||
})
|
||||
}
|
||||
|
||||
// countedBody is a request's body that adds the bytes read of it to read.
|
||||
type countedBody struct {
|
||||
io.ReadCloser
|
||||
|
||||
read *int64
|
||||
}
|
||||
|
||||
// Read reads part of the body.
|
||||
func (b *countedBody) Read(p []byte) (int, error) {
|
||||
n, err := b.ReadCloser.Read(p)
|
||||
*b.read += int64(n)
|
||||
|
||||
return n, err
|
||||
}
|
||||
|
||||
// requireToken returns middleware that lets a request through only when it
|
||||
// carries token, as Authorization: Bearer <token>. It answers 401 to a request
|
||||
// without it. While token is unset, it answers 404, as a path with no endpoint
|
||||
// does.
|
||||
func requireToken(token string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case token == "":
|
||||
answerNotFound(w, r)
|
||||
case !hasToken(r, token):
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(
|
||||
w,
|
||||
http.StatusText(http.StatusUnauthorized),
|
||||
http.StatusUnauthorized,
|
||||
)
|
||||
default:
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// hasToken reports whether r carries token, as Authorization: Bearer
|
||||
// <token>.
|
||||
func hasToken(r *http.Request, token string) bool {
|
||||
scheme, sent, _ := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
|
||||
return strings.EqualFold(scheme, "Bearer") &&
|
||||
subtle.ConstantTimeCompare([]byte(sent), []byte(token)) == 1
|
||||
}
|
||||
|
||||
// answerNotFound answers 404, for a path with no endpoint, and for a method
|
||||
// the path has no endpoint for.
|
||||
func answerNotFound(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
}
|
||||
+51
-34
@@ -58,8 +58,8 @@ func New(params Params) *Server {
|
||||
}
|
||||
|
||||
// ServeHTTP handles one request to waf: a request carrying
|
||||
// wafprotocol.ClientHeader is rproxy's question, and any other is for one of
|
||||
// waf's own endpoints.
|
||||
// wafprotocol.ClientHeader is rproxy's question, and any other is for waf
|
||||
// itself.
|
||||
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if len(r.Header.Values(wafprotocol.ClientHeader)) > 0 {
|
||||
h.answerQuestion(w, r)
|
||||
@@ -67,27 +67,23 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.ownEndpoints.ServeHTTP(w, r)
|
||||
h.answerOwnEndpoint(w, r)
|
||||
}
|
||||
|
||||
// refusedWhateverTheAnswer reports whether the request is one that does not wait
|
||||
// for GeoJS, since the checks will refuse it at now whatever GeoJS answers about
|
||||
// its client: a heuristic of afterLookup that implements refusesWithoutLookup
|
||||
// says it will refuse it. In observe mode, which refuses nothing, none is.
|
||||
// rproxy lets a request through when waf answers too late.
|
||||
// its client: the heuristic blocklists or rate_limits will refuse it, as a
|
||||
// function in that heuristic's file says. In observe mode, which refuses
|
||||
// nothing, none is. rproxy lets a request through when waf answers too late.
|
||||
func (rq *request) refusedWhateverTheAnswer(now time.Time) bool {
|
||||
if rq.h.config.Observe {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, each := range rq.h.afterLookup {
|
||||
knows, ok := each.(refusesWithoutLookup)
|
||||
if ok && knows.refusesWhateverTheLookupAnswers(rq, now) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
listedBy := rq.h.blocklists.lists.ListedBy(rq.client)
|
||||
|
||||
return false
|
||||
return rq.h.blocklists.refusedByBlocklists(listedBy) ||
|
||||
rq.h.rateLimits.overAWholeRateLimit(rq, now)
|
||||
}
|
||||
|
||||
// answerQuestion runs the checks on the visitor's request a question
|
||||
@@ -244,29 +240,50 @@ func (rq *request) deny(r refusal) {
|
||||
http.Error(rq.out, http.StatusText(r.status), r.status)
|
||||
}
|
||||
|
||||
// handleReport answers POST wafprotocol.ReportPath: it finishes the request
|
||||
// the report names, if it holds that request's decision, and ignores the
|
||||
// report otherwise.
|
||||
func (h *handler) handleReport() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
report, err := wafprotocol.ReadReport(w, r)
|
||||
if err != nil {
|
||||
h.processLog.Warn("a report is refused", "error", err.Error())
|
||||
http.Error(w, "the body is not a report", http.StatusBadRequest)
|
||||
// answerOwnEndpoint answers a request to waf'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.
|
||||
func (h *handler) answerOwnEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == wafprotocol.ReportPath {
|
||||
h.takeReport(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
held, found := h.awaitingReport.Peek(report.RequestID)
|
||||
// Remove reports true to one report only, of several that name the
|
||||
// id. A question still being handled is held as nil.
|
||||
if found && held != nil &&
|
||||
h.awaitingReport.Remove(report.RequestID) {
|
||||
h.finishWith(r.Context(), held, report)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
peer := peerAddress(r)
|
||||
|
||||
rq := h.startRequest(w, r, peer, peer, false)
|
||||
defer rq.finish()
|
||||
|
||||
if r.Method == http.MethodGet && r.URL.Path == wafprotocol.HealthPath {
|
||||
rq.answerHealth()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rq.answerAdmin()
|
||||
}
|
||||
|
||||
// takeReport answers POST wafprotocol.ReportPath: it finishes the request the
|
||||
// report names, if it holds that request's decision, and ignores the report
|
||||
// otherwise.
|
||||
func (h *handler) takeReport(w http.ResponseWriter, r *http.Request) {
|
||||
report, err := wafprotocol.ReadReport(w, r)
|
||||
if err != nil {
|
||||
h.processLog.Warn("a report is refused", "error", err.Error())
|
||||
http.Error(w, "the body is not a report", http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
held, found := h.awaitingReport.Peek(report.RequestID)
|
||||
// Remove reports true to one report only, of several that name the id. A
|
||||
// question still being handled is held as nil.
|
||||
if found && held != nil && h.awaitingReport.Remove(report.RequestID) {
|
||||
h.finishWith(r.Context(), held, report)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// finishWith finishes a request with what its report says, and writes the
|
||||
|
||||
Reference in new issue
Block a user