Files
smallwebwaf/internal/waf/lookup.go
clawbot 8c9f20d346
check / check (push) Failing after 1m51s
waf: run the trap paths, rule files and Core Rule Set during the GeoJS wait (closes #405)
While the lookup waits for GeoJS, the trap paths, the rule files and the
Core Rule Set run at the same time as the checks after the lookup. The
first side to refuse answers the request; what the other side finds leaves
no trace. Those three checks have 500 ms together: past it, the request is
refused with 503 as checks_timed_out, with no ban and no offence.

Tests hold GeoJS and the Core Rule Set with stand-ins under synctest. The
test helper lifts the 500 ms limit for tests that run the real Core Rule
Set, which the race detector slows past it.

Model: opus-5-5
2026-11-17 06:11:52 +01:00

175 lines
5.2 KiB
Go

package waf
import (
"context"
"net/http"
"net/netip"
"strings"
"time"
"sneak.berlin/go/smallwebwaf/internal/alerts"
"sneak.berlin/go/smallwebwaf/internal/config"
"sneak.berlin/go/smallwebwaf/internal/geojs"
)
// The headers in which an answer of allow gives rproxy the client's AS number
// and country, for the app, while SWW_WAF_ADD_LOOKUP_HEADERS is true. Go writes
// every header name in this form, as it sends it and as it receives it, so
// X-Client-ASN arrives as X-Client-Asn; header names are not case-sensitive.
const (
asnHeader = "X-Client-Asn"
countryHeader = "X-Client-Country"
)
// lookupResult is what the lookup gave for a request: whether its client was
// looked up, the answer, and whether the request skipped the wait for GeoJS.
type lookupResult struct {
lookedUp, skippedWait bool
answer geojs.Answer
}
// startLookUp starts looking up the client's AS number and country, in the
// lookup database or through GeoJS, unless SWW_WAF_LOOKUP_SOURCE is off or the
// client is on a private, loopback or link-local address, which no lookup can
// place. It returns the channel the result comes on. A result that needs no
// wait is on it when startLookUp returns: the lookup database's, an answer
// GeoJS gave earlier, or none. With GeoJS, while a setting needs the answer,
// such as a country list or a biased threshold, a new client's request waits
// for it up to SWW_WAF_ASN_AND_COUNTRY_LOOKUP_TIMEOUT_MS, unless
// refusedWhateverTheAnswer reports true. The wait goes on to its end even once
// the request has been answered, so that it ends as it would have for a
// request that waited. startLookUp changes nothing of the request. ctx is the
// request's own context.
func (rq *request) startLookUp(
ctx context.Context, now time.Time,
) <-chan lookupResult {
result := make(chan lookupResult, 1)
if rq.h.config.LookupSource == "off" || !canBePlaced(rq.client) {
result <- lookupResult{}
return result
}
client := rq.h.clientGroup(rq.client)
if rq.h.config.LookupSource == "file" {
result <- lookupResult{
lookedUp: true, answer: rq.h.lookupFile.LookUp(client),
}
return result
}
answer := rq.h.geojs.LookUpWithoutWaiting(ctx, client)
refused := rq.refusedWhateverTheAnswer(now)
if !answer.Answered.IsZero() || refused || !rq.h.waitForGeoJS {
result <- lookupResult{
lookedUp: true,
skippedWait: refused && answer.Answered.IsZero(),
answer: answer,
}
return result
}
go func() {
result <- lookupResult{
lookedUp: true,
answer: rq.h.geojs.LookUp(context.WithoutCancel(ctx), client,
rq.h.config.ASNAndCountryLookupTimeout),
}
}()
return result
}
// noteLookup notes result for the log line and as the request's asn= and
// country= tags.
func (rq *request) noteLookup(result lookupResult) {
if !result.lookedUp {
return
}
rq.lookedUp = true
rq.lookupAnswer = result.answer
rq.skippedLookupWait = result.skippedWait
rq.line.ASN = rq.lookupAnswer.ASN
rq.line.ASName = rq.lookupAnswer.ASName
rq.line.Country = rq.lookupAnswer.Country
if tag := asnTag(rq.line.ASN); tag != "" {
rq.addTag(tag)
}
if tag := countryTag(rq.line.Country); tag != "" {
rq.addTag(tag)
}
}
// asnTag returns the tag of asn, an AS number as the lookup gives it, such as
// asn=64496 for AS64496, or "" for no AS number.
func asnTag(asn string) string {
if asn == "" {
return ""
}
return config.ASNTagPrefix + strings.TrimPrefix(asn, "AS")
}
// countryTag returns the tag of country, a code as the lookup gives it, such
// as country=DE for DE, or "" for no country.
func countryTag(country string) string {
if country == "" {
return ""
}
return config.CountryTagPrefix + country
}
// addLookup adds answer, an answer about a client from the lookup
// database or GeoJS, to the client's history, and to the notes of the bans
// on its netblock that have no AS number, AS name or country yet.
func (h *handler) addLookup(answer geojs.Answer) {
h.limiter.AddLookup(answer.Client, answer.Answered,
answer.ASN, answer.ASName, answer.Country)
h.ledger.AddLookup(h.netblock(answer.Client.Addr()),
answer.ASN, answer.ASName, answer.Country)
}
// geojsFailed logs a failure of GeoJS, raises a source_failure alert for it
// and counts it. askingAgainIn is how long GeoJS is left alone after it.
func (h *handler) geojsFailed(err error, askingAgainIn time.Duration) {
h.processLog.Warn("asking GeoJS failed",
"error", err.Error(), "asking_again_in", askingAgainIn.String())
h.alerts.Raise(alerts.Alert{
Event: alerts.EventSourceFailure,
Reason: "asking GeoJS failed",
Detail: map[string]any{
"source": "geojs", "error": err.Error(),
"asking_again_in": askingAgainIn.String(),
},
})
h.metrics.GeoJSFailures.Inc()
}
// setLookupHeaders sets the headers that give the client's AS number and
// country, leaving out one that is unknown.
func setLookupHeaders(header http.Header, asn, country string) {
if asn != "" {
header.Set(asnHeader, asn)
}
if country != "" {
header.Set(countryHeader, country)
}
}
// canBePlaced reports whether a lookup can place addr: private, loopback
// and link-local addresses have no AS number or country.
func canBePlaced(addr netip.Addr) bool {
return !addr.IsPrivate() && !addr.IsLoopback() &&
!addr.IsLinkLocalUnicast()
}