Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bc631315d | ||
|
|
1002433c35 | ||
|
|
805c64a256 | ||
|
|
967ccdf75e |
No files matched your search
@@ -906,9 +906,11 @@ stops the running process (see [`docs/state-files.md`](docs/state-files.md)).
|
||||
`internal/coreruleset`, `internal/geojs`, `internal/lookup`,
|
||||
`internal/reputation`, `internal/routewatch`, `internal/anomaly` and
|
||||
`internal/alerts`: one check or source each.
|
||||
- `internal/state`, `internal/requestlog`, `internal/remotelog` and
|
||||
`internal/metrics`: the state and cache files, the log lines, the syslog
|
||||
sender and the metrics.
|
||||
- `internal/state`: the state and cache files.
|
||||
- `internal/requestlog`: the request log.
|
||||
- `internal/processlog`: the process's own messages.
|
||||
- `internal/remotelog`: the syslog sender.
|
||||
- `internal/metrics`: the metrics.
|
||||
|
||||
## Rationale
|
||||
|
||||
|
||||
@@ -104,8 +104,10 @@ never as a time.
|
||||
its own.
|
||||
- `internal/state`: reads the state and cache files at start, takes in edits
|
||||
while running, and writes the files when due and at the stop.
|
||||
- `internal/requestlog` and `internal/remotelog`: the lines on stdout, and
|
||||
sending them to the syslog server.
|
||||
- `internal/requestlog`: the request log, as JSON lines on stdout.
|
||||
- `internal/processlog`: the process lines on stdout, which hold the
|
||||
process's own messages.
|
||||
- `internal/remotelog`: sends the lines on stdout to the syslog server.
|
||||
- `internal/metrics`: the metrics, in the Prometheus text format.
|
||||
- `Dockerfile`: the lint and test phases, then the image.
|
||||
`deploy/example-app` is an app built on the image, with `rproxy` in its
|
||||
|
||||
+93
-32
@@ -75,7 +75,7 @@ type WAF struct {
|
||||
BytesLimitPerMinute int64
|
||||
BytesLimitPerHour int64
|
||||
BytesLimitPerDay int64
|
||||
BytesCounted string
|
||||
BytesCounted BytesCounted
|
||||
// LookupSource is where each client's AS number and country are looked
|
||||
// up (SWW_WAF_LOOKUP_SOURCE): geojs, file, or off for nowhere.
|
||||
// LookupDBPath is the lookup database, the IPinfo Lite file looked up in
|
||||
@@ -86,7 +86,7 @@ type WAF struct {
|
||||
// AddLookupHeaders is true when the app is passed the client's AS number
|
||||
// and country in headers (SWW_WAF_ADD_LOOKUP_HEADERS), by default unless
|
||||
// LookupSource is off.
|
||||
LookupSource string
|
||||
LookupSource LookupSource
|
||||
LookupDBPath string
|
||||
ASNAndCountryLookupTimeout time.Duration
|
||||
AddLookupHeaders bool
|
||||
@@ -131,7 +131,7 @@ type WAF struct {
|
||||
// BlocklistLimitPercent is the percentage of every limit it gets.
|
||||
BlocklistURLs []string
|
||||
BlocklistRefresh time.Duration
|
||||
BlocklistAction string
|
||||
BlocklistAction ReputationAction
|
||||
BlocklistLimitPercent int64
|
||||
// DNSBLZones are the DNSBL zones clients are asked about
|
||||
// (SWW_WAF_DNSBL_ZONES), through DNSBLResolver (SWW_WAF_DNSBL_RESOLVER), or
|
||||
@@ -154,7 +154,7 @@ type WAF struct {
|
||||
AbuseIPDBKey string
|
||||
AbuseIPDBMinScore int64
|
||||
AbuseIPDBDailyBudget int
|
||||
DNSBLAbuseIPDBAction string
|
||||
DNSBLAbuseIPDBAction ReputationAction
|
||||
DNSBLAbuseIPDBLimitPercent int64
|
||||
IPReputationCacheTTL time.Duration
|
||||
DNSBLAbuseIPDBTimeout time.Duration
|
||||
@@ -237,7 +237,7 @@ type WAF struct {
|
||||
// reads none.
|
||||
// CoreRuleSetExclusionsFile is the path of the file of its exclusions
|
||||
// (SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE), "" while there is none.
|
||||
CoreRuleSetMode string
|
||||
CoreRuleSetMode CoreRuleSetMode
|
||||
CoreRuleSetParanoiaLevel int
|
||||
CoreRuleSetScoreThreshold int
|
||||
CoreRuleSetDisabledRules []int
|
||||
@@ -316,20 +316,66 @@ type WAF struct {
|
||||
settings []slog.Attr
|
||||
}
|
||||
|
||||
// BytesCounted is which body bytes count toward the byte limits and the
|
||||
// byte anomaly thresholds, a value of SWW_WAF_BYTES_COUNTED.
|
||||
type BytesCounted string
|
||||
|
||||
// The values of SWW_WAF_BYTES_COUNTED.
|
||||
const (
|
||||
// BytesCountedResponse counts the response's body bytes.
|
||||
BytesCountedResponse BytesCounted = "response"
|
||||
// BytesCountedRequest counts the request's body bytes.
|
||||
BytesCountedRequest BytesCounted = "request"
|
||||
// BytesCountedBoth counts the body bytes of both.
|
||||
BytesCountedBoth BytesCounted = "both"
|
||||
)
|
||||
|
||||
// LookupSource is where each client's AS number and country are looked up,
|
||||
// a value of SWW_WAF_LOOKUP_SOURCE.
|
||||
type LookupSource string
|
||||
|
||||
// The values of SWW_WAF_LOOKUP_SOURCE.
|
||||
const (
|
||||
// LookupSourceGeoJS asks GeoJS.
|
||||
LookupSourceGeoJS LookupSource = "geojs"
|
||||
// LookupSourceFile looks clients up in the lookup database, the file
|
||||
// SWW_WAF_LOOKUP_DB_PATH names.
|
||||
LookupSourceFile LookupSource = "file"
|
||||
// LookupSourceOff looks no client up.
|
||||
LookupSourceOff LookupSource = "off"
|
||||
)
|
||||
|
||||
// ReputationAction is what is done with a client a reputation source
|
||||
// lists, a value of SWW_WAF_BLOCKLIST_ACTION and of
|
||||
// SWW_WAF_DNSBL_ABUSEIPDB_ACTION.
|
||||
type ReputationAction string
|
||||
|
||||
// The values of SWW_WAF_BLOCKLIST_ACTION and SWW_WAF_DNSBL_ABUSEIPDB_ACTION.
|
||||
const (
|
||||
// ReputationActionDeny refuses the client's requests.
|
||||
ReputationActionDeny ReputationAction = "deny"
|
||||
// ReputationActionLimit gives the client a percentage of every limit,
|
||||
// written limit:<percent> in the setting.
|
||||
ReputationActionLimit ReputationAction = "limit"
|
||||
// ReputationActionLog only notes the hit in the log line and raises an
|
||||
// alert.
|
||||
ReputationActionLog ReputationAction = "log"
|
||||
)
|
||||
|
||||
// CoreRuleSetMode is what the Core Rule Set does, a value of
|
||||
// SWW_WAF_CORE_RULE_SET_MODE.
|
||||
type CoreRuleSetMode string
|
||||
|
||||
// The values of SWW_WAF_CORE_RULE_SET_MODE.
|
||||
const (
|
||||
// CoreRuleSetModeOff runs no request through the Core Rule Set.
|
||||
CoreRuleSetModeOff = off
|
||||
CoreRuleSetModeOff CoreRuleSetMode = "off"
|
||||
// CoreRuleSetModeDetect logs and alerts a match, and refuses nothing.
|
||||
CoreRuleSetModeDetect = "detect"
|
||||
CoreRuleSetModeDetect CoreRuleSetMode = "detect"
|
||||
// CoreRuleSetModeBlock refuses a match with 403.
|
||||
CoreRuleSetModeBlock = "block"
|
||||
CoreRuleSetModeBlock CoreRuleSetMode = "block"
|
||||
)
|
||||
|
||||
// fileSource is the SWW_WAF_LOOKUP_SOURCE that looks clients up in the
|
||||
// lookup database, the file SWW_WAF_LOOKUP_DB_PATH names.
|
||||
const fileSource = "file"
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
ipv4Bits = 32
|
||||
@@ -558,10 +604,13 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
),
|
||||
BytesLimitPerHour: env.size("SWW_WAF_BYTES_LIMIT_PER_HOUR", "50G"),
|
||||
BytesLimitPerDay: env.size("SWW_WAF_BYTES_LIMIT_PER_DAY", "100G"),
|
||||
BytesCounted: env.bytesCounted("SWW_WAF_BYTES_COUNTED", "both"),
|
||||
BytesCounted: env.bytesCounted(
|
||||
"SWW_WAF_BYTES_COUNTED",
|
||||
BytesCountedBoth,
|
||||
),
|
||||
LookupSource: env.lookupSource(
|
||||
"SWW_WAF_LOOKUP_SOURCE",
|
||||
"geojs",
|
||||
LookupSourceGeoJS,
|
||||
),
|
||||
LookupDBPath: env.value("SWW_WAF_LOOKUP_DB_PATH", ""),
|
||||
ASNAndCountryLookupTimeout: env.milliseconds(
|
||||
@@ -758,9 +807,9 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
cfg.InstanceName, cfg.LogRemoteURL != nil)
|
||||
// The app gets the headers by default, unless no client is looked up.
|
||||
cfg.AddLookupHeaders = env.boolean("SWW_WAF_ADD_LOOKUP_HEADERS",
|
||||
strconv.FormatBool(cfg.LookupSource != off))
|
||||
strconv.FormatBool(cfg.LookupSource != LookupSourceOff))
|
||||
cfg.BlocklistAction, cfg.BlocklistLimitPercent = env.action(
|
||||
"SWW_WAF_BLOCKLIST_ACTION", "deny")
|
||||
"SWW_WAF_BLOCKLIST_ACTION", string(ReputationActionDeny))
|
||||
cfg.DNSBLAbuseIPDBAction, cfg.DNSBLAbuseIPDBLimitPercent = env.action(
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION", "limit:25")
|
||||
|
||||
@@ -858,9 +907,12 @@ func (e *environment) count(name, defaultValue string) int64 {
|
||||
|
||||
// bytesCounted reads the setting that is which body bytes count toward the
|
||||
// byte limits and the byte anomaly thresholds: response, request or both.
|
||||
func (e *environment) bytesCounted(name, defaultValue string) string {
|
||||
value := e.value(name, defaultValue)
|
||||
if value != "response" && value != "request" && value != "both" {
|
||||
func (e *environment) bytesCounted(
|
||||
name string, defaultValue BytesCounted,
|
||||
) BytesCounted {
|
||||
value := BytesCounted(e.value(name, string(defaultValue)))
|
||||
if value != BytesCountedResponse && value != BytesCountedRequest &&
|
||||
value != BytesCountedBoth {
|
||||
e.check(name, fmt.Errorf("%q %w", value, errNotBytesCounted))
|
||||
}
|
||||
|
||||
@@ -905,8 +957,10 @@ func (e *environment) trapPaths(name string) []string {
|
||||
|
||||
// coreRuleSetMode reads the setting that is what the Core Rule Set does: off,
|
||||
// detect or block.
|
||||
func (e *environment) coreRuleSetMode(name, defaultValue string) string {
|
||||
mode := e.value(name, defaultValue)
|
||||
func (e *environment) coreRuleSetMode(
|
||||
name string, defaultValue CoreRuleSetMode,
|
||||
) CoreRuleSetMode {
|
||||
mode := CoreRuleSetMode(e.value(name, string(defaultValue)))
|
||||
if mode != CoreRuleSetModeOff && mode != CoreRuleSetModeDetect &&
|
||||
mode != CoreRuleSetModeBlock {
|
||||
e.check(name, fmt.Errorf("%q %w", mode, errNotCoreRuleSetMode))
|
||||
@@ -1056,20 +1110,24 @@ func (e *environment) refresh(name, defaultValue string) time.Duration {
|
||||
// action reads a setting that is what is done with a client a blocklist
|
||||
// or a DNSBL zone lists: deny, log, or limit:<percent>, which it returns
|
||||
// as limit and the percentage.
|
||||
func (e *environment) action(name, defaultValue string) (string, int64) {
|
||||
value := e.value(name, defaultValue)
|
||||
if value == "deny" || value == "log" {
|
||||
func (e *environment) action(
|
||||
name, defaultValue string,
|
||||
) (ReputationAction, int64) {
|
||||
value := ReputationAction(e.value(name, defaultValue))
|
||||
if value == ReputationActionDeny || value == ReputationActionLog {
|
||||
return value, 0
|
||||
}
|
||||
|
||||
percentText, isLimit := strings.CutPrefix(value, "limit:")
|
||||
percentText, isLimit := strings.CutPrefix(
|
||||
string(value), string(ReputationActionLimit)+":",
|
||||
)
|
||||
|
||||
percent, err := ParsePercent(percentText)
|
||||
if !isLimit || err != nil {
|
||||
e.check(name, fmt.Errorf("%q %w", value, errNotAction))
|
||||
}
|
||||
|
||||
return "limit", percent
|
||||
return ReputationActionLimit, percent
|
||||
}
|
||||
|
||||
// zones reads the setting that is the list of DNSBL zones. It is empty by
|
||||
@@ -1120,9 +1178,12 @@ func (e *environment) routeWatchURL(name string) string {
|
||||
|
||||
// lookupSource reads the setting that is where clients are looked up:
|
||||
// geojs, file, or off.
|
||||
func (e *environment) lookupSource(name, defaultValue string) string {
|
||||
source := e.value(name, defaultValue)
|
||||
if source != "geojs" && source != fileSource && source != off {
|
||||
func (e *environment) lookupSource(
|
||||
name string, defaultValue LookupSource,
|
||||
) LookupSource {
|
||||
source := LookupSource(e.value(name, string(defaultValue)))
|
||||
if source != LookupSourceGeoJS && source != LookupSourceFile &&
|
||||
source != LookupSourceOff {
|
||||
e.check(name, fmt.Errorf("%q %w", source, errNotLookupSource))
|
||||
}
|
||||
|
||||
@@ -1134,12 +1195,12 @@ func (e *environment) lookupSource(name, defaultValue string) string {
|
||||
// one source at a time.
|
||||
func (e *environment) checkLookupDBPath(cfg *WAF) {
|
||||
switch {
|
||||
case cfg.LookupSource == fileSource && cfg.LookupDBPath == "":
|
||||
case cfg.LookupSource == LookupSourceFile && cfg.LookupDBPath == "":
|
||||
e.check("SWW_WAF_LOOKUP_SOURCE", fmt.Errorf(
|
||||
"is file while SWW_WAF_LOOKUP_DB_PATH is unset; %w",
|
||||
errNeedsDBPath,
|
||||
))
|
||||
case cfg.LookupSource != fileSource && cfg.LookupDBPath != "":
|
||||
case cfg.LookupSource != LookupSourceFile && cfg.LookupDBPath != "":
|
||||
e.check("SWW_WAF_LOOKUP_DB_PATH", fmt.Errorf(
|
||||
"is set while SWW_WAF_LOOKUP_SOURCE is %s; %w",
|
||||
cfg.LookupSource,
|
||||
@@ -1164,7 +1225,7 @@ func (e *environment) checkCountriesAndLookups(cfg *WAF) {
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.LookupSource != off {
|
||||
if cfg.LookupSource != LookupSourceOff {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -614,7 +614,7 @@ func TestCoreRuleSetSettings(t *testing.T) {
|
||||
},
|
||||
{
|
||||
environment{
|
||||
coreRuleSetMode: config.CoreRuleSetModeDetect,
|
||||
coreRuleSetMode: string(config.CoreRuleSetModeDetect),
|
||||
coreRuleSetParanoiaLevel: "4",
|
||||
coreRuleSetScoreThreshold: "10",
|
||||
coreRuleSetDisabledRules: "942100, 920350",
|
||||
@@ -2033,8 +2033,9 @@ func TestReputationSettingsAsSet(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
value, action string
|
||||
percent int64
|
||||
value string
|
||||
action config.ReputationAction
|
||||
percent int64
|
||||
}{
|
||||
{actionDeny, actionDeny, 0},
|
||||
{actionLog, actionLog, 0},
|
||||
@@ -2167,7 +2168,7 @@ func TestDNSBLSettingsAsSet(t *testing.T) {
|
||||
// want are the zones, resolver, action and percent config.WAF gives.
|
||||
want []string
|
||||
wantResolver string
|
||||
wantAction string
|
||||
wantAction config.ReputationAction
|
||||
wantPercent int64
|
||||
}{
|
||||
{
|
||||
@@ -3049,7 +3050,7 @@ func TestLogsEachSettingWithItsValue(t *testing.T) {
|
||||
logLevel: "info",
|
||||
ruleFilesDir: "/etc/sww/rules.d",
|
||||
ruleFilesEnabled: "true",
|
||||
coreRuleSetMode: config.CoreRuleSetModeBlock,
|
||||
coreRuleSetMode: string(config.CoreRuleSetModeBlock),
|
||||
coreRuleSetParanoiaLevel: "1",
|
||||
coreRuleSetScoreThreshold: "5",
|
||||
coreRuleSetDisabledRules: defaultCoreRuleSetDisabledRules,
|
||||
|
||||
+14
-24
@@ -84,12 +84,7 @@ type Params struct {
|
||||
// one request to GeoJS is under way at a time, and it asks about every
|
||||
// client waiting, up to maxPerRequest. It is safe for concurrent use.
|
||||
type GeoJS struct {
|
||||
url string
|
||||
answered func(Answer)
|
||||
now func() time.Time
|
||||
asked func()
|
||||
failed func(err error, askingAgainIn time.Duration)
|
||||
wentWithoutAnswer func()
|
||||
params Params
|
||||
// httpClient follows no redirect, so that visitors' addresses go to
|
||||
// GeoJS alone: a redirect is a failure.
|
||||
httpClient *http.Client
|
||||
@@ -140,12 +135,7 @@ func New(params Params) *GeoJS {
|
||||
}
|
||||
|
||||
return &GeoJS{
|
||||
url: params.URL,
|
||||
answered: params.Answered,
|
||||
now: params.Now,
|
||||
asked: params.Asked,
|
||||
failed: params.Failed,
|
||||
wentWithoutAnswer: params.WentWithoutAnswer,
|
||||
params: params,
|
||||
httpClient: &http.Client{
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
@@ -188,7 +178,7 @@ func (g *GeoJS) LookUp(
|
||||
|
||||
answer, found := g.kept(client)
|
||||
if !found {
|
||||
g.wentWithoutAnswer()
|
||||
g.params.WentWithoutAnswer()
|
||||
}
|
||||
|
||||
w, waiting := g.waiting[client]
|
||||
@@ -251,7 +241,7 @@ func (g *GeoJS) Load(answers []Answer) {
|
||||
|
||||
g.answers.Purge()
|
||||
|
||||
now := g.now()
|
||||
now := g.params.Now()
|
||||
|
||||
for _, answer := range answers {
|
||||
if now.Sub(answer.Answered) < keepFor {
|
||||
@@ -288,7 +278,7 @@ func (g *GeoJS) answerOrWait(
|
||||
}
|
||||
|
||||
if w == nil {
|
||||
g.wentWithoutAnswer()
|
||||
g.params.WentWithoutAnswer()
|
||||
|
||||
return Answer{}, nil // too many clients wait already
|
||||
}
|
||||
@@ -299,7 +289,7 @@ func (g *GeoJS) answerOrWait(
|
||||
}
|
||||
|
||||
if w.late {
|
||||
g.wentWithoutAnswer()
|
||||
g.params.WentWithoutAnswer()
|
||||
|
||||
return Answer{}, nil
|
||||
}
|
||||
@@ -310,7 +300,7 @@ func (g *GeoJS) answerOrWait(
|
||||
// kept returns client's answer, if GeoJS gave it less than keepFor ago,
|
||||
// and notes that it was used.
|
||||
func (g *GeoJS) kept(client netip.Prefix) (Answer, bool) {
|
||||
now := g.now()
|
||||
now := g.params.Now()
|
||||
|
||||
kept, found := g.answers.Get(client)
|
||||
if !found || now.Sub(kept.Answered) >= keepFor {
|
||||
@@ -327,7 +317,7 @@ func (g *GeoJS) kept(client netip.Prefix) (Answer, bool) {
|
||||
// GeoJS are for every client waiting, so they go on when the caller whose
|
||||
// ctx is given stops waiting.
|
||||
func (g *GeoJS) ask(ctx context.Context) {
|
||||
if g.asking || g.now().Before(g.retryAt) {
|
||||
if g.asking || g.params.Now().Before(g.retryAt) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -349,9 +339,9 @@ func (g *GeoJS) askAboutWaiting(ctx context.Context) {
|
||||
given, err := g.request(ctx, clients)
|
||||
kept, answered := g.keep(clients, given, err)
|
||||
|
||||
if g.answered != nil {
|
||||
if g.params.Answered != nil {
|
||||
for _, answer := range kept {
|
||||
g.answered(answer)
|
||||
g.params.Answered(answer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,7 +390,7 @@ func (g *GeoJS) keep(
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
|
||||
now := g.now()
|
||||
now := g.params.Now()
|
||||
kept := make([]Answer, 0, len(clients))
|
||||
leftOut := 0
|
||||
|
||||
@@ -444,7 +434,7 @@ func (g *GeoJS) keep(
|
||||
w.late = true
|
||||
}
|
||||
|
||||
g.failed(err, g.retryDelay)
|
||||
g.params.Failed(err, g.retryDelay)
|
||||
|
||||
return kept, false
|
||||
}
|
||||
@@ -474,7 +464,7 @@ func (g *GeoJS) request(
|
||||
req, err := http.NewRequestWithContext(
|
||||
ctx,
|
||||
http.MethodGet,
|
||||
g.url,
|
||||
g.params.URL,
|
||||
http.NoBody,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -483,7 +473,7 @@ func (g *GeoJS) request(
|
||||
|
||||
req.URL.RawQuery = "ip=" + strings.Join(addrs, ",")
|
||||
|
||||
g.asked()
|
||||
g.params.Asked()
|
||||
|
||||
res, err := g.httpClient.Do(req)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package processlog builds the logger for the process's own messages,
|
||||
// which it writes as JSON lines marked "type":"process". The request log
|
||||
// is package requestlog's.
|
||||
package processlog
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
// Params are what New needs.
|
||||
type Params struct {
|
||||
// Output is where the lines are written.
|
||||
Output io.Writer
|
||||
// InstanceName, SWW_WAF_INSTANCE_NAME, is each line's instance.
|
||||
InstanceName string
|
||||
// Level, SWW_WAF_LOG_LEVEL, is the least severe level written.
|
||||
Level slog.Level
|
||||
}
|
||||
|
||||
// New returns the logger for the process's own messages: JSON lines on
|
||||
// params.Output, marked "type":"process", with the time in the same form
|
||||
// as a request line's. It writes only the messages at params.Level or more
|
||||
// severe; the request lines requestlog.Write writes are never held back.
|
||||
func New(params Params) *slog.Logger {
|
||||
handler := slog.NewJSONHandler(params.Output, &slog.HandlerOptions{
|
||||
Level: params.Level,
|
||||
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
|
||||
if attr.Key == slog.TimeKey && len(groups) == 0 {
|
||||
return slog.String(
|
||||
slog.TimeKey,
|
||||
requestlog.FormatTime(attr.Value.Time()),
|
||||
)
|
||||
}
|
||||
|
||||
return attr
|
||||
},
|
||||
})
|
||||
|
||||
return slog.New(handler).
|
||||
With("type", "process", "instance", params.InstanceName)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package processlog_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
)
|
||||
|
||||
// instanceName is the instance the tests' loggers are built with.
|
||||
const instanceName = "host1/blog"
|
||||
|
||||
func TestProcessLinesAreMarkedProcessAndGiveTheInstance(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
processlog.New(processlog.Params{
|
||||
Output: &out,
|
||||
InstanceName: instanceName,
|
||||
Level: slog.LevelInfo,
|
||||
}).
|
||||
Info("starting",
|
||||
"version", "v1")
|
||||
|
||||
var fields map[string]any
|
||||
|
||||
err := json.Unmarshal(out.Bytes(), &fields)
|
||||
if err != nil {
|
||||
t.Fatalf("decode %q: %v", out.String(), err)
|
||||
}
|
||||
|
||||
if fields["type"] != "process" ||
|
||||
fields["instance"] != "host1/blog" ||
|
||||
fields["msg"] != "starting" ||
|
||||
fields["level"] != "INFO" ||
|
||||
fields["version"] != "v1" {
|
||||
t.Errorf("process line %v", fields)
|
||||
}
|
||||
|
||||
timeText, _ := fields["time"].(string)
|
||||
|
||||
logged, err := time.Parse(time.RFC3339, timeText)
|
||||
if err != nil || !strings.HasSuffix(timeText, "Z") ||
|
||||
len(timeText) != len("2006-01-02T15:04:05.000Z") ||
|
||||
time.Since(logged) > time.Minute {
|
||||
t.Errorf(
|
||||
"process line time %q, want now in UTC with milliseconds",
|
||||
timeText,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessLoggerWritesTheMessagesAtItsLevelOrMoreSevere(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
levels := []slog.Level{
|
||||
slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError,
|
||||
}
|
||||
|
||||
for i, level := range levels {
|
||||
t.Run(level.String(), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
processLog := processlog.New(processlog.Params{
|
||||
Output: &out,
|
||||
InstanceName: instanceName,
|
||||
Level: level,
|
||||
})
|
||||
for _, at := range levels {
|
||||
processLog.Log(t.Context(), at, "message")
|
||||
}
|
||||
|
||||
var got, want []string
|
||||
|
||||
for line := range strings.Lines(out.String()) {
|
||||
var fields struct {
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal([]byte(line), &fields)
|
||||
if err != nil {
|
||||
t.Fatalf("decode %q: %v", line, err)
|
||||
}
|
||||
|
||||
got = append(got, fields.Level)
|
||||
}
|
||||
|
||||
for _, written := range levels[i:] {
|
||||
want = append(want, written.String())
|
||||
}
|
||||
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("lines at %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
func TestHistoryKeepsEveryRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestHistoryKeepsEveryRequest(t *testing.T) {
|
||||
func TestLookupReachesTheHistoryOfAClientInTheTable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
other := netip.MustParsePrefix("198.51.100.7/32")
|
||||
start := midnight()
|
||||
@@ -100,7 +100,10 @@ func TestLookupReachesTheHistoryOfAClientInTheTable(t *testing.T) {
|
||||
func TestResetKeepsTheHistory(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{PerMinute: limit}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -123,7 +126,7 @@ func TestResetKeepsTheHistory(t *testing.T) {
|
||||
func TestRequestsAddsUpTheClientsInsideTheNetblock(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
|
||||
for client, requests := range map[string]int{
|
||||
"198.51.100.9/32": 2,
|
||||
|
||||
@@ -156,16 +156,28 @@ type Request struct {
|
||||
BlockedByCoreRuleSet bool
|
||||
}
|
||||
|
||||
// New returns a Limiter for limits, with no client counted yet, whose
|
||||
// table holds at most maxClients clients (SWW_WAF_MAX_TRACKED_CLIENTS). Past
|
||||
// it, the least recently seen client is dropped, with its history, and
|
||||
// starts afresh if it comes back.
|
||||
func New(limits Limits, maxClients int) *Limiter {
|
||||
clients, err := simplelru.NewLRU[netip.Prefix, *Client](maxClients, nil)
|
||||
// Params are what New needs.
|
||||
type Params struct {
|
||||
// Limits are what each client's requests and bytes are counted against.
|
||||
Limits Limits
|
||||
// MaxClients is the most clients the table holds,
|
||||
// SWW_WAF_MAX_TRACKED_CLIENTS. Past it, the least recently seen client
|
||||
// is dropped, with its history, and starts afresh if it comes back.
|
||||
MaxClients int
|
||||
}
|
||||
|
||||
// New returns a Limiter with no client counted yet.
|
||||
func New(params Params) *Limiter {
|
||||
clients, err := simplelru.NewLRU[netip.Prefix, *Client](
|
||||
params.MaxClients,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
panic(err) // NewLRU fails only for a size below one
|
||||
}
|
||||
|
||||
limits := params.Limits
|
||||
|
||||
return &Limiter{
|
||||
windows: [3]window{
|
||||
{
|
||||
|
||||
@@ -33,10 +33,10 @@ func TestOverARateLimitSaysWhatTheNextRequestWouldDoAndCountsNothing(
|
||||
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
now := midnight()
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: limit, PerDay: limit + 1},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit, PerDay: limit + 1},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
|
||||
if limiter.OverARateLimit(client, now) {
|
||||
t.Error("a client never seen is over a rate limit")
|
||||
@@ -72,7 +72,7 @@ func TestOverARateLimitSaysWhatTheNextRequestWouldDoAndCountsNothing(
|
||||
wantCount(t, limiter, client, now, minute)
|
||||
|
||||
// A limit that is off is never gone over.
|
||||
off := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
off := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
off.Count(client, now, whole)
|
||||
|
||||
if off.OverARateLimit(client, now) {
|
||||
@@ -95,7 +95,10 @@ func TestEachWindowRefusesAtItsLimitAndLetsTheClientBack(t *testing.T) {
|
||||
t.Run(tc.window, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(tc.limits, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: tc.limits,
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
quarter := tc.length / 4
|
||||
@@ -126,10 +129,10 @@ func TestEachWindowRefusesAtItsLimitAndLetsTheClientBack(t *testing.T) {
|
||||
func TestHitGivesTheLimitAndTheRequestsCounted(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: limit, PerHour: limit},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit, PerHour: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -159,10 +162,13 @@ func TestHitGivesTheLimitAndTheRequestsCounted(t *testing.T) {
|
||||
func TestClientGetsItsPercentageOfEachLimitRoundedDown(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: 5, BytesPerDay: math.MaxInt64},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{
|
||||
PerMinute: 5,
|
||||
BytesPerDay: math.MaxInt64,
|
||||
},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -203,10 +209,10 @@ func TestZeroPercentIsAZeroAllowanceAndALimitOffStaysOff(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Only the hour has limits: the minute's and the day's are off.
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerHour: limit, BytesPerHour: 1000},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerHour: limit, BytesPerHour: 1000},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -253,7 +259,10 @@ func TestEachByteLimitIsBrokenByTheBytesCounted(t *testing.T) {
|
||||
t.Run(tc.window, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(tc.limits, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: tc.limits,
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
|
||||
// 600 bytes are within the limit, 600 more over it.
|
||||
@@ -287,10 +296,10 @@ func TestEachByteLimitIsBrokenByTheBytesCounted(t *testing.T) {
|
||||
func TestALimitIsBrokenOnlyByWhatIsAddedToIt(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: 2, BytesPerMinute: 1000},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: 2, BytesPerMinute: 1000},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
other := netip.MustParsePrefix("203.0.113.10/32")
|
||||
start := midnight()
|
||||
@@ -314,7 +323,7 @@ func TestALimitIsBrokenOnlyByWhatIsAddedToIt(t *testing.T) {
|
||||
func TestCountGivesTheBytesInEachWindow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -340,7 +349,10 @@ func TestCountGivesTheBytesInEachWindow(t *testing.T) {
|
||||
func TestResetSetsTheBytesBackToZero(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{BytesPerDay: 1000}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{BytesPerDay: 1000},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -356,7 +368,7 @@ func TestRefusalsOverTheLimitInAMinuteBreakTheRefusalLimit(
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -411,7 +423,7 @@ func TestRefusalsOverTheLimitInAMinuteBreakTheRefusalLimit(
|
||||
func TestCountGivesTheRequestsInEachWindow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -438,10 +450,10 @@ func TestCountGivesTheRequestsInEachWindow(t *testing.T) {
|
||||
func TestResetSetsTheCountsBackToZero(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: limit, PerDay: limit},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit, PerDay: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -463,7 +475,10 @@ func TestResetSetsTheCountsBackToZero(t *testing.T) {
|
||||
func TestClientBackAfterAWholeBucketIsWithinTheLimitAtOnce(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{PerHour: limit}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerHour: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -482,10 +497,10 @@ func TestClientBackAfterAWholeBucketIsWithinTheLimitAtOnce(t *testing.T) {
|
||||
func TestRefusedRequestsCount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(
|
||||
ratelimit.Limits{PerMinute: limit, PerHour: 2 * limit},
|
||||
tableSize,
|
||||
)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit, PerHour: 2 * limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
refused := netip.MustParsePrefix("203.0.113.9/32")
|
||||
within := netip.MustParsePrefix("203.0.113.10/32")
|
||||
start := midnight()
|
||||
@@ -518,7 +533,10 @@ func TestRefusedRequestsCount(t *testing.T) {
|
||||
func TestRequestCountedLateGoesInTheBucketUnderWay(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{PerMinute: limit}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -534,7 +552,10 @@ func TestRequestCountedLateGoesInTheBucketUnderWay(t *testing.T) {
|
||||
func TestClockSetBackStartsTheBucketsAfresh(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{PerHour: limit}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerHour: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
@@ -562,7 +583,10 @@ func TestKeepsAtMostMaxClientsDroppingTheLeastRecentlySeen(t *testing.T) {
|
||||
|
||||
const maxClients = 3
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{PerMinute: 1}, maxClients)
|
||||
limiter := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerMinute: 1},
|
||||
MaxClients: maxClients,
|
||||
})
|
||||
now := midnight()
|
||||
|
||||
clients := make([]netip.Prefix, maxClients+1)
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestSnapshotListsTheClientsByAddress(t *testing.T) {
|
||||
"2001:db8::/64",
|
||||
}
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
for _, i := range []int{2, 3, 0, 1} {
|
||||
limiter.Count(netip.MustParsePrefix(want[i]), midnight(), whole)
|
||||
}
|
||||
@@ -52,7 +52,10 @@ func TestLoadedCountsCarryOn(t *testing.T) {
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
before := ratelimit.New(ratelimit.Limits{PerHour: limit}, tableSize)
|
||||
before := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerHour: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
for range limit {
|
||||
wantCount(t, before, client, start, "")
|
||||
}
|
||||
@@ -60,7 +63,10 @@ func TestLoadedCountsCarryOn(t *testing.T) {
|
||||
// Loaded into a new limiter, as across a restart, the client has no
|
||||
// fresh allowance.
|
||||
later := start.Add(time.Minute)
|
||||
after := ratelimit.New(ratelimit.Limits{PerHour: limit}, tableSize)
|
||||
after := ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{PerHour: limit},
|
||||
MaxClients: tableSize,
|
||||
})
|
||||
after.Load(before.Snapshot(), later)
|
||||
wantCount(t, after, client, later, hour)
|
||||
}
|
||||
@@ -71,7 +77,7 @@ func TestLoadEmptiesBucketsWhoseTimeHasPassed(t *testing.T) {
|
||||
client := netip.MustParsePrefix("203.0.113.9/32")
|
||||
start := midnight()
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
limiter.Count(client, start, whole)
|
||||
limiter.CountBytes(client, start, 5, whole)
|
||||
limiter.CountRefusal(client, start, limit)
|
||||
@@ -80,7 +86,7 @@ func TestLoadEmptiesBucketsWhoseTimeHasPassed(t *testing.T) {
|
||||
loaded := func(now time.Time) ratelimit.Client {
|
||||
t.Helper()
|
||||
|
||||
after := ratelimit.New(ratelimit.Limits{}, tableSize)
|
||||
after := ratelimit.New(ratelimit.Params{MaxClients: tableSize})
|
||||
after.Load(limiter.Snapshot(), now)
|
||||
|
||||
return after.Snapshot()[0]
|
||||
@@ -142,7 +148,7 @@ func TestLoadDropsTheLeastRecentlySeenFirst(t *testing.T) {
|
||||
addr = addr.Next()
|
||||
}
|
||||
|
||||
limiter := ratelimit.New(ratelimit.Limits{}, maxClients)
|
||||
limiter := ratelimit.New(ratelimit.Params{MaxClients: maxClients})
|
||||
limiter.Load(clients, midnight())
|
||||
|
||||
got := limiter.Snapshot()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package requestlog writes the lines sww prints on stdout: one
|
||||
// Package requestlog writes the request log sww prints on stdout: one
|
||||
// JSON object per request, two from waf and a short one from rproxy,
|
||||
// marked "type":"request", and the process's own messages as JSON lines marked
|
||||
// "type":"process".
|
||||
// marked "type":"request". Package processlog writes the process's own
|
||||
// messages.
|
||||
package requestlog
|
||||
|
||||
import (
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
@@ -300,31 +299,3 @@ func Milliseconds(d time.Duration) float64 {
|
||||
time.Millisecond/time.Microsecond,
|
||||
)
|
||||
}
|
||||
|
||||
// NewProcessLogger returns the logger for the process's own messages:
|
||||
// JSON lines on w, marked "type":"process", with the time in the same form
|
||||
// as a request line's, and instanceName, SWW_WAF_INSTANCE_NAME, as instance.
|
||||
// It writes only the messages at level, SWW_WAF_LOG_LEVEL, or more severe;
|
||||
// the request lines Write writes are never held back.
|
||||
func NewProcessLogger(
|
||||
w io.Writer,
|
||||
instanceName string,
|
||||
level slog.Level,
|
||||
) *slog.Logger {
|
||||
handler := slog.NewJSONHandler(w, &slog.HandlerOptions{
|
||||
Level: level,
|
||||
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
|
||||
if attr.Key == slog.TimeKey && len(groups) == 0 {
|
||||
return slog.String(
|
||||
slog.TimeKey,
|
||||
FormatTime(attr.Value.Time()),
|
||||
)
|
||||
}
|
||||
|
||||
return attr
|
||||
},
|
||||
})
|
||||
|
||||
return slog.New(handler).
|
||||
With("type", "process", "instance", instanceName)
|
||||
}
|
||||
@@ -3,8 +3,6 @@ package requestlog_test
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -134,88 +132,3 @@ func TestWriteRProxyLineWritesOneJSONLineWithOnlyItsFields(t *testing.T) {
|
||||
t.Errorf("wrote %s, want %s", out.String(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessLinesAreMarkedProcessAndGiveTheInstance(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
requestlog.NewProcessLogger(&out, "host1/blog", slog.LevelInfo).
|
||||
Info("starting",
|
||||
"version", "v1")
|
||||
|
||||
var fields map[string]any
|
||||
|
||||
err := json.Unmarshal(out.Bytes(), &fields)
|
||||
if err != nil {
|
||||
t.Fatalf("decode %q: %v", out.String(), err)
|
||||
}
|
||||
|
||||
if fields["type"] != "process" ||
|
||||
fields["instance"] != "host1/blog" ||
|
||||
fields["msg"] != "starting" ||
|
||||
fields["level"] != "INFO" ||
|
||||
fields["version"] != "v1" {
|
||||
t.Errorf("process line %v", fields)
|
||||
}
|
||||
|
||||
timeText, _ := fields["time"].(string)
|
||||
|
||||
logged, err := time.Parse(time.RFC3339, timeText)
|
||||
if err != nil || !strings.HasSuffix(timeText, "Z") ||
|
||||
len(timeText) != len("2006-01-02T15:04:05.000Z") ||
|
||||
time.Since(logged) > time.Minute {
|
||||
t.Errorf(
|
||||
"process line time %q, want now in UTC with milliseconds",
|
||||
timeText,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessLoggerWritesTheMessagesAtItsLevelOrMoreSevere(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
levels := []slog.Level{
|
||||
slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError,
|
||||
}
|
||||
|
||||
for i, level := range levels {
|
||||
t.Run(level.String(), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
processLog := requestlog.NewProcessLogger(
|
||||
&out,
|
||||
"host1/blog",
|
||||
level,
|
||||
)
|
||||
for _, at := range levels {
|
||||
processLog.Log(t.Context(), at, "message")
|
||||
}
|
||||
|
||||
var got, want []string
|
||||
|
||||
for line := range strings.Lines(out.String()) {
|
||||
var fields struct {
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal([]byte(line), &fields)
|
||||
if err != nil {
|
||||
t.Fatalf("decode %q: %v", line, err)
|
||||
}
|
||||
|
||||
got = append(got, fields.Level)
|
||||
}
|
||||
|
||||
for _, written := range levels[i:] {
|
||||
want = append(want, written.String())
|
||||
}
|
||||
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("lines at %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package rproxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
@@ -23,9 +22,7 @@ type requestBody struct {
|
||||
// body is the visitor's body, ending in an *http.MaxBytesError past
|
||||
// SWW_RPROXY_MAX_REQUEST_SIZE.
|
||||
body io.ReadCloser
|
||||
// refuse refuses the request with a status, as the request's own refuse
|
||||
// does.
|
||||
refuse func(status int)
|
||||
rq *request
|
||||
// held is the part read before the request goes to the app, which Read gives
|
||||
// first.
|
||||
held []byte
|
||||
@@ -71,7 +68,7 @@ func (b *requestBody) Read(p []byte) (int, error) {
|
||||
case errors.Is(err, io.EOF):
|
||||
b.received.Store(true)
|
||||
case errors.As(err, &tooLarge):
|
||||
b.refuse(http.StatusRequestEntityTooLarge)
|
||||
b.rq.refuse(http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
|
||||
return n, err
|
||||
@@ -89,13 +86,7 @@ type responseBody struct {
|
||||
// body is the app's body, ending in an *http.MaxBytesError past
|
||||
// SWW_RPROXY_MAX_RESPONSE_SIZE.
|
||||
body io.ReadCloser
|
||||
// refuse refuses the request with a status, as the request's own refuse
|
||||
// does.
|
||||
refuse func(status int)
|
||||
// responseReceived is called once the app's whole answer has arrived.
|
||||
responseReceived func()
|
||||
// ctx is the visitor's request's context.
|
||||
ctx context.Context //nolint:containedctx // the body ends with the request
|
||||
rq *request
|
||||
}
|
||||
|
||||
// Read reads from the app's body.
|
||||
@@ -109,15 +100,15 @@ func (b *responseBody) Read(p []byte) (int, error) {
|
||||
|
||||
switch {
|
||||
case errors.Is(err, io.EOF):
|
||||
b.responseReceived()
|
||||
b.rq.responseReceived()
|
||||
case errors.As(err, &tooLarge):
|
||||
b.refuse(http.StatusBadGateway)
|
||||
b.rq.refuse(http.StatusBadGateway)
|
||||
|
||||
return n, errResponseTooLarge
|
||||
case b.ctx.Err() == nil:
|
||||
case b.rq.in.Context().Err() == nil:
|
||||
// The answer broke off, not because the visitor went away. If a time
|
||||
// limit cut it, that refusal came first and is the one kept.
|
||||
b.refuse(http.StatusBadGateway)
|
||||
b.rq.refuse(http.StatusBadGateway)
|
||||
}
|
||||
|
||||
return n, err
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config/configtest"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/rproxy"
|
||||
"sneak.berlin/go/smallwebwaf/internal/waf"
|
||||
)
|
||||
@@ -51,11 +51,11 @@ func TestServerHasTheFixedLimits(t *testing.T) {
|
||||
server := rproxy.New(rproxy.Params{
|
||||
Config: cfg,
|
||||
RequestLog: io.Discard,
|
||||
ProcessLog: requestlog.NewProcessLogger(
|
||||
io.Discard,
|
||||
"test",
|
||||
slog.LevelInfo,
|
||||
),
|
||||
ProcessLog: processlog.New(processlog.Params{
|
||||
Output: io.Discard,
|
||||
InstanceName: "test",
|
||||
Level: slog.LevelInfo,
|
||||
}),
|
||||
})
|
||||
|
||||
if server.Addr != ":8080" || server.MaxHeaderBytes != 28<<10 ||
|
||||
|
||||
@@ -126,8 +126,8 @@ func (h *handler) newRequest(
|
||||
|
||||
if r.Body != http.NoBody {
|
||||
rq.body = &requestBody{
|
||||
body: limitBody(r.Body, h.config.MaxRequestSize),
|
||||
refuse: rq.refuse,
|
||||
body: limitBody(r.Body, h.config.MaxRequestSize),
|
||||
rq: rq,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,12 +294,7 @@ func (rq *request) modifyResponse(res *http.Response) error {
|
||||
// the request, and SWW_RPROXY_MAX_RESPONSE_TIME_MS starts.
|
||||
rq.startResponseTimer(requestEnd)
|
||||
|
||||
res.Body = &responseBody{
|
||||
body: limitBody(res.Body, maxBytes),
|
||||
refuse: rq.refuse,
|
||||
responseReceived: rq.responseReceived,
|
||||
ctx: rq.in.Context(),
|
||||
}
|
||||
res.Body = &responseBody{body: limitBody(res.Body, maxBytes), rq: rq}
|
||||
rq.out.afterStatus = rq.setResponseDeadline
|
||||
|
||||
return nil
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config/configtest"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/rproxy"
|
||||
"sneak.berlin/go/smallwebwaf/internal/waf"
|
||||
)
|
||||
@@ -370,11 +370,11 @@ func startServerLogging(
|
||||
server := rproxy.New(rproxy.Params{
|
||||
Config: cfg,
|
||||
RequestLog: requestLog,
|
||||
ProcessLog: requestlog.NewProcessLogger(
|
||||
processLog,
|
||||
"test",
|
||||
slog.LevelInfo,
|
||||
),
|
||||
ProcessLog: processlog.New(processlog.Params{
|
||||
Output: processLog,
|
||||
InstanceName: "test",
|
||||
Level: slog.LevelInfo,
|
||||
}),
|
||||
})
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(
|
||||
|
||||
@@ -2448,7 +2448,7 @@ func newParams(dir string) state.Params {
|
||||
AttackBanDuration: 7 * 24 * time.Hour,
|
||||
MaxBans: 5000,
|
||||
}),
|
||||
Limiter: ratelimit.New(ratelimit.Limits{}, 20000),
|
||||
Limiter: ratelimit.New(ratelimit.Params{MaxClients: 20000}),
|
||||
GeoJS: geojs.New(geojs.Params{Now: midnight}),
|
||||
Lists: reputation.New(reputation.Params{
|
||||
BlocklistURLs: []string{
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"go.uber.org/fx"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/rproxy"
|
||||
)
|
||||
|
||||
@@ -23,11 +23,11 @@ import (
|
||||
// setting for either.
|
||||
func RunRProxy(ctx context.Context, params Params) int {
|
||||
hostname, _ := os.Hostname() // "" when the host has no name to give
|
||||
processLog := requestlog.NewProcessLogger(
|
||||
params.Stdout,
|
||||
hostname,
|
||||
slog.LevelInfo,
|
||||
)
|
||||
processLog := processlog.New(processlog.Params{
|
||||
Output: params.Stdout,
|
||||
InstanceName: hostname,
|
||||
Level: slog.LevelInfo,
|
||||
})
|
||||
|
||||
cfg, err := config.RProxyFromEnvironment(params.Viper)
|
||||
if err != nil {
|
||||
|
||||
@@ -660,7 +660,9 @@ func TestCoreRuleSetExclusionsFileThatCannotBeUsedStopsTheStartWhileTheCoreRuleS
|
||||
|
||||
status := run(t.Context(), map[string]string{
|
||||
listenAddr: localhost + ":0", stateDir: t.TempDir(), ruleFilesDir: t.TempDir(),
|
||||
"SWW_WAF_CORE_RULE_SET_MODE": config.CoreRuleSetModeOff,
|
||||
"SWW_WAF_CORE_RULE_SET_MODE": string(
|
||||
config.CoreRuleSetModeOff,
|
||||
),
|
||||
"SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE": path,
|
||||
}, out)
|
||||
if status != 1 {
|
||||
|
||||
+51
-20
@@ -2,6 +2,7 @@ package sww
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
@@ -18,10 +19,10 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/geojs"
|
||||
"sneak.berlin/go/smallwebwaf/internal/lookup"
|
||||
"sneak.berlin/go/smallwebwaf/internal/metrics"
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/remotelog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/routewatch"
|
||||
"sneak.berlin/go/smallwebwaf/internal/rules"
|
||||
"sneak.berlin/go/smallwebwaf/internal/state"
|
||||
@@ -42,8 +43,11 @@ const remoteLogStopTimeout = 2 * time.Second
|
||||
func RunWAF(ctx context.Context, params Params) int {
|
||||
// Until the settings are read, the one message is an invalid setting's
|
||||
// error, which every SWW_WAF_LOG_LEVEL lets through.
|
||||
processLog := requestlog.NewProcessLogger(params.Stdout,
|
||||
config.InstanceName(params.Viper), slog.LevelError)
|
||||
processLog := processlog.New(processlog.Params{
|
||||
Output: params.Stdout,
|
||||
InstanceName: config.InstanceName(params.Viper),
|
||||
Level: slog.LevelError,
|
||||
})
|
||||
|
||||
cfg, err := config.WAFFromEnvironment(params.Viper)
|
||||
if err != nil {
|
||||
@@ -62,11 +66,11 @@ func RunWAF(ctx context.Context, params Params) int {
|
||||
stdout = io.MultiWriter(params.Stdout, remote)
|
||||
}
|
||||
|
||||
processLog = requestlog.NewProcessLogger(
|
||||
stdout,
|
||||
cfg.InstanceName,
|
||||
cfg.LogLevel,
|
||||
)
|
||||
processLog = processlog.New(processlog.Params{
|
||||
Output: stdout,
|
||||
InstanceName: cfg.InstanceName,
|
||||
Level: cfg.LogLevel,
|
||||
})
|
||||
|
||||
if remote != nil {
|
||||
stopSending := startSending(ctx, remote, processLog)
|
||||
@@ -175,11 +179,35 @@ func newRuleFiles(
|
||||
return ruleFiles, nil
|
||||
}
|
||||
|
||||
// newCoreRuleSet returns the Core Rule Set, as waf.NewCoreRuleSet does.
|
||||
// newCoreRuleSet returns the Core Rule Set at SWW_WAF_CORE_RULE_SET_PARANOIA_LEVEL,
|
||||
// without the rules SWW_WAF_CORE_RULE_SET_DISABLED_RULES switches off, reading bodies
|
||||
// up to SWW_WAF_CORE_RULE_SET_BODY_INSPECTION_SIZE, with the exclusions in
|
||||
// SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE and the fixes of the apps in SWW_WAF_APPS,
|
||||
// or nil while SWW_WAF_CORE_RULE_SET_MODE is off. An exclusions file that
|
||||
// coreruleset.New refuses is an error in every mode. While the mode is off, a
|
||||
// set file is loaded with the Core Rule Set only to check it.
|
||||
func newCoreRuleSet(cfg *config.WAF) (*coreruleset.CoreRuleSet, error) {
|
||||
crs, err := waf.NewCoreRuleSet(cfg)
|
||||
if cfg.CoreRuleSetMode == config.CoreRuleSetModeOff &&
|
||||
cfg.CoreRuleSetExclusionsFile == "" {
|
||||
return nil, nil //nolint:nilnil // off is no Core Rule Set, and no error
|
||||
}
|
||||
|
||||
crs, err := coreruleset.New(coreruleset.Params{
|
||||
ParanoiaLevel: cfg.CoreRuleSetParanoiaLevel,
|
||||
DisabledRules: cfg.CoreRuleSetDisabledRules,
|
||||
BodyInspectionSize: cfg.CoreRuleSetBodyInspectionSize,
|
||||
ExclusionsFile: cfg.CoreRuleSetExclusionsFile,
|
||||
Apps: cfg.Apps,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, startError{"cannot use the Core Rule Set", err}
|
||||
return nil, startError{
|
||||
"cannot use the Core Rule Set",
|
||||
fmt.Errorf("SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE: %w", err),
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.CoreRuleSetMode == config.CoreRuleSetModeOff {
|
||||
return nil, nil //nolint:nilnil // off is no Core Rule Set, and no error
|
||||
}
|
||||
|
||||
return crs, nil
|
||||
@@ -192,7 +220,7 @@ func newLookupFile(
|
||||
lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger,
|
||||
alertQueue *alerts.Queue,
|
||||
) (*lookup.File, error) {
|
||||
if cfg.LookupSource != "file" {
|
||||
if cfg.LookupSource != config.LookupSourceFile {
|
||||
return nil, nil //nolint:nilnil // no lookup database, and no error
|
||||
}
|
||||
|
||||
@@ -213,14 +241,17 @@ func newLookupFile(
|
||||
|
||||
// newLimiter returns the table of clients, with the rate and byte limits.
|
||||
func newLimiter(cfg *config.WAF) *ratelimit.Limiter {
|
||||
return ratelimit.New(ratelimit.Limits{
|
||||
PerMinute: cfg.RateLimitPerMinute,
|
||||
PerHour: cfg.RateLimitPerHour,
|
||||
PerDay: cfg.RateLimitPerDay,
|
||||
BytesPerMinute: cfg.BytesLimitPerMinute,
|
||||
BytesPerHour: cfg.BytesLimitPerHour,
|
||||
BytesPerDay: cfg.BytesLimitPerDay,
|
||||
}, cfg.MaxTrackedClients)
|
||||
return ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{
|
||||
PerMinute: cfg.RateLimitPerMinute,
|
||||
PerHour: cfg.RateLimitPerHour,
|
||||
PerDay: cfg.RateLimitPerDay,
|
||||
BytesPerMinute: cfg.BytesLimitPerMinute,
|
||||
BytesPerHour: cfg.BytesLimitPerHour,
|
||||
BytesPerDay: cfg.BytesLimitPerDay,
|
||||
},
|
||||
MaxClients: cfg.MaxTrackedClients,
|
||||
})
|
||||
}
|
||||
|
||||
// newLedger returns the ledger of the bans, with the settings for them.
|
||||
|
||||
@@ -54,7 +54,7 @@ func (abuseIPDB) check(
|
||||
"scored by AbuseIPDB at or over SWW_WAF_ABUSEIPDB_MIN_SCORE",
|
||||
)
|
||||
|
||||
if rq.h.config.DNSBLAbuseIPDBAction != deny {
|
||||
if rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -86,13 +86,14 @@ func (rq *request) countedBytes() int64 {
|
||||
response, request := rq.out.bytes, rq.requestBytes
|
||||
|
||||
switch rq.h.config.BytesCounted {
|
||||
case "response":
|
||||
case config.BytesCountedResponse:
|
||||
return response
|
||||
case "request":
|
||||
case config.BytesCountedRequest:
|
||||
return request
|
||||
default: // both
|
||||
return response + request
|
||||
case config.BytesCountedBoth:
|
||||
}
|
||||
|
||||
return response + request
|
||||
}
|
||||
|
||||
// banForLimit bans the client's netblock at now for a broken limit, the
|
||||
|
||||
@@ -63,7 +63,8 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
}
|
||||
|
||||
blocklisted := percentage{percent: whole}
|
||||
if rq.blocklisted && cfg.BlocklistAction == "limit" {
|
||||
if rq.blocklisted &&
|
||||
cfg.BlocklistAction == config.ReputationActionLimit {
|
||||
blocklisted = percentage{
|
||||
cfg.BlocklistLimitPercent,
|
||||
"SWW_WAF_BLOCKLIST_ACTION",
|
||||
@@ -72,7 +73,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
|
||||
dnsblAbuseIPDBListed := percentage{percent: whole}
|
||||
if (rq.dnsblListed || rq.abuseIPDBHit) &&
|
||||
cfg.DNSBLAbuseIPDBAction == "limit" {
|
||||
cfg.DNSBLAbuseIPDBAction == config.ReputationActionLimit {
|
||||
dnsblAbuseIPDBListed = percentage{
|
||||
cfg.DNSBLAbuseIPDBLimitPercent,
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION",
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
@@ -41,5 +42,6 @@ func (blocklists) check(
|
||||
// client, given listedBy, the blocklists that list it: it does when one lists
|
||||
// it and SWW_WAF_BLOCKLIST_ACTION is deny.
|
||||
func (rq *request) refusedByBlocklists(listedBy []string) bool {
|
||||
return len(listedBy) > 0 && rq.h.config.BlocklistAction == deny
|
||||
return len(listedBy) > 0 && rq.h.config.BlocklistAction ==
|
||||
config.ReputationActionDeny
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func (coreRuleSet) check(
|
||||
rq.line.CoreRuleSetScore = &result.Score
|
||||
|
||||
for _, id := range result.RuleIDs {
|
||||
rq.h.metrics.CoreRuleSetMatched(cfg.CoreRuleSetMode, id)
|
||||
rq.h.metrics.CoreRuleSetMatched(string(cfg.CoreRuleSetMode), id)
|
||||
}
|
||||
|
||||
threshold := cfg.CoreRuleSetScoreThreshold
|
||||
@@ -99,7 +99,7 @@ func (rq *request) alertCoreRuleSetMatch(result coreruleset.Result) {
|
||||
|
||||
switch {
|
||||
case rq.h.config.CoreRuleSetMode == config.CoreRuleSetModeDetect:
|
||||
detail["mode"] = config.CoreRuleSetModeDetect
|
||||
detail["mode"] = string(config.CoreRuleSetModeDetect)
|
||||
case rq.h.config.Observe:
|
||||
detail["mode"] = "observe"
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ func (dnsbl) check(ctx context.Context, rq *request, _ time.Time) *verdict {
|
||||
rq.addTag(config.DNSBLTagPrefix + strings.ToLower(zone))
|
||||
}
|
||||
|
||||
if !rq.dnsblListed || rq.h.config.DNSBLAbuseIPDBAction != deny {
|
||||
if !rq.dnsblListed ||
|
||||
rq.h.config.DNSBLAbuseIPDBAction != config.ReputationActionDeny {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,8 @@ func (rq *request) startLookUp(
|
||||
) <-chan lookupResult {
|
||||
result := make(chan lookupResult, 1)
|
||||
|
||||
if rq.h.config.LookupSource == "off" || !canBePlaced(rq.client) {
|
||||
if rq.h.config.LookupSource == config.LookupSourceOff ||
|
||||
!canBePlaced(rq.client) {
|
||||
result <- lookupResult{}
|
||||
|
||||
return result
|
||||
@@ -57,7 +58,7 @@ func (rq *request) startLookUp(
|
||||
|
||||
client := clientGroup(rq.h.config, rq.client)
|
||||
|
||||
if rq.h.config.LookupSource == "file" {
|
||||
if rq.h.config.LookupSource == config.LookupSourceFile {
|
||||
result <- lookupResult{
|
||||
lookedUp: true, answer: rq.h.lookupFile.LookUp(client),
|
||||
}
|
||||
|
||||
+2
-37
@@ -6,7 +6,6 @@ package waf
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -83,8 +82,8 @@ type Params struct {
|
||||
// LookupFile is the lookup database they are looked up in while
|
||||
// SWW_WAF_LOOKUP_SOURCE is file, and nil otherwise.
|
||||
LookupFile *lookup.File
|
||||
// CoreRuleSet is what NewCoreRuleSet returns: what inspects requests
|
||||
// while SWW_WAF_CORE_RULE_SET_MODE is not off, and nil while it is.
|
||||
// CoreRuleSet is what inspects requests while
|
||||
// SWW_WAF_CORE_RULE_SET_MODE is not off, and nil while it is.
|
||||
CoreRuleSet CoreRuleSetInspector
|
||||
// Now tells the time by which requests are counted for the rate
|
||||
// limits, bans are made and run out, and GeoJS's answers are kept,
|
||||
@@ -174,40 +173,6 @@ func newHandler(params Params) *handler {
|
||||
}
|
||||
}
|
||||
|
||||
// NewCoreRuleSet returns the Core Rule Set at SWW_WAF_CORE_RULE_SET_PARANOIA_LEVEL,
|
||||
// without the rules SWW_WAF_CORE_RULE_SET_DISABLED_RULES switches off, reading bodies
|
||||
// up to SWW_WAF_CORE_RULE_SET_BODY_INSPECTION_SIZE, with the exclusions in
|
||||
// SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE and the fixes of the apps in SWW_WAF_APPS,
|
||||
// or nil while SWW_WAF_CORE_RULE_SET_MODE is off. An exclusions file that
|
||||
// coreruleset.New refuses is an error in every mode. While the mode is off, a
|
||||
// set file is loaded with the Core Rule Set only to check it.
|
||||
func NewCoreRuleSet(cfg *config.WAF) (*coreruleset.CoreRuleSet, error) {
|
||||
if cfg.CoreRuleSetMode == config.CoreRuleSetModeOff &&
|
||||
cfg.CoreRuleSetExclusionsFile == "" {
|
||||
return nil, nil //nolint:nilnil // off is no Core Rule Set, and no error
|
||||
}
|
||||
|
||||
coreRuleSet, err := coreruleset.New(coreruleset.Params{
|
||||
ParanoiaLevel: cfg.CoreRuleSetParanoiaLevel,
|
||||
DisabledRules: cfg.CoreRuleSetDisabledRules,
|
||||
BodyInspectionSize: cfg.CoreRuleSetBodyInspectionSize,
|
||||
ExclusionsFile: cfg.CoreRuleSetExclusionsFile,
|
||||
Apps: cfg.Apps,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"SWW_WAF_CORE_RULE_SET_EXCLUSIONS_FILE: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if cfg.CoreRuleSetMode == config.CoreRuleSetModeOff {
|
||||
return nil, nil //nolint:nilnil // off is no Core Rule Set, and no error
|
||||
}
|
||||
|
||||
return coreRuleSet, nil
|
||||
}
|
||||
|
||||
// handler is waf's handler. It holds what every request shares; what
|
||||
// belongs to one request is in a request.
|
||||
type handler struct {
|
||||
|
||||
+56
-31
@@ -20,9 +20,11 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config/configtest"
|
||||
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
|
||||
"sneak.berlin/go/smallwebwaf/internal/geojs"
|
||||
"sneak.berlin/go/smallwebwaf/internal/lookup"
|
||||
"sneak.berlin/go/smallwebwaf/internal/metrics"
|
||||
"sneak.berlin/go/smallwebwaf/internal/processlog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
@@ -397,11 +399,11 @@ func startRProxy(
|
||||
server := rproxy.New(rproxy.Params{
|
||||
Config: cfg,
|
||||
RequestLog: io.Discard,
|
||||
ProcessLog: requestlog.NewProcessLogger(
|
||||
io.Discard,
|
||||
"rproxy",
|
||||
slog.LevelInfo,
|
||||
),
|
||||
ProcessLog: processlog.New(processlog.Params{
|
||||
Output: io.Discard,
|
||||
InstanceName: "rproxy",
|
||||
Level: slog.LevelInfo,
|
||||
}),
|
||||
})
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(
|
||||
@@ -470,11 +472,11 @@ func newWAFWith(
|
||||
}
|
||||
|
||||
out := &output{}
|
||||
processLog := requestlog.NewProcessLogger(
|
||||
out,
|
||||
cfg.InstanceName,
|
||||
cfg.LogLevel,
|
||||
)
|
||||
processLog := processlog.New(processlog.Params{
|
||||
Output: out,
|
||||
InstanceName: cfg.InstanceName,
|
||||
Level: cfg.LogLevel,
|
||||
})
|
||||
|
||||
ruleFiles, err := rules.Load(rules.Params{
|
||||
Dir: cfg.RuleFilesDir, Enabled: cfg.RuleFilesEnabled, ProcessLog: processLog,
|
||||
@@ -504,24 +506,20 @@ func newWAFWith(
|
||||
}
|
||||
}
|
||||
|
||||
coreRuleSet, err := waf.NewCoreRuleSet(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("Core Rule Set: %v", err)
|
||||
}
|
||||
|
||||
params := waf.Params{
|
||||
Config: cfg,
|
||||
RequestLog: out,
|
||||
ProcessLog: processLog,
|
||||
LookupFile: lookupFile,
|
||||
CoreRuleSet: coreRuleSet,
|
||||
Now: now,
|
||||
Rules: ruleFiles,
|
||||
Alerts: alertQueue,
|
||||
Config: cfg,
|
||||
RequestLog: out,
|
||||
ProcessLog: processLog,
|
||||
LookupFile: lookupFile,
|
||||
Now: now,
|
||||
Rules: ruleFiles,
|
||||
Alerts: alertQueue,
|
||||
// The tests of the limit set it back, and hold the Core Rule Set
|
||||
// with a stand-in.
|
||||
BesideLookupTimeLimit: time.Hour,
|
||||
}
|
||||
|
||||
addCoreRuleSet(t, ¶ms)
|
||||
addCounters(¶ms)
|
||||
addOutsideSources(¶ms, geojsURL, abuseIPDBCheckURL)
|
||||
|
||||
@@ -530,6 +528,30 @@ func newWAFWith(
|
||||
return server, out, alertQueue
|
||||
}
|
||||
|
||||
// addCoreRuleSet adds to params the Core Rule Set, with the settings for it,
|
||||
// while SWW_WAF_CORE_RULE_SET_MODE is not off.
|
||||
func addCoreRuleSet(t *testing.T, params *waf.Params) {
|
||||
t.Helper()
|
||||
|
||||
cfg := params.Config
|
||||
if cfg.CoreRuleSetMode == config.CoreRuleSetModeOff {
|
||||
return
|
||||
}
|
||||
|
||||
coreRuleSet, err := coreruleset.New(coreruleset.Params{
|
||||
ParanoiaLevel: cfg.CoreRuleSetParanoiaLevel,
|
||||
DisabledRules: cfg.CoreRuleSetDisabledRules,
|
||||
BodyInspectionSize: cfg.CoreRuleSetBodyInspectionSize,
|
||||
ExclusionsFile: cfg.CoreRuleSetExclusionsFile,
|
||||
Apps: cfg.Apps,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Core Rule Set: %v", err)
|
||||
}
|
||||
|
||||
params.CoreRuleSet = coreRuleSet
|
||||
}
|
||||
|
||||
// addCounters adds to params the metrics, the table of clients, the ledger
|
||||
// and the anomaly counters, as sww builds them from params' settings. The
|
||||
// metrics read the ledger, the table of clients and the rules.
|
||||
@@ -540,14 +562,17 @@ func addCounters(params *waf.Params) {
|
||||
cfg.MetricsBusiestCountriesAndASNs,
|
||||
cfg.InstanceName,
|
||||
)
|
||||
params.Limiter = ratelimit.New(ratelimit.Limits{
|
||||
PerMinute: cfg.RateLimitPerMinute,
|
||||
PerHour: cfg.RateLimitPerHour,
|
||||
PerDay: cfg.RateLimitPerDay,
|
||||
BytesPerMinute: cfg.BytesLimitPerMinute,
|
||||
BytesPerHour: cfg.BytesLimitPerHour,
|
||||
BytesPerDay: cfg.BytesLimitPerDay,
|
||||
}, cfg.MaxTrackedClients)
|
||||
params.Limiter = ratelimit.New(ratelimit.Params{
|
||||
Limits: ratelimit.Limits{
|
||||
PerMinute: cfg.RateLimitPerMinute,
|
||||
PerHour: cfg.RateLimitPerHour,
|
||||
PerDay: cfg.RateLimitPerDay,
|
||||
BytesPerMinute: cfg.BytesLimitPerMinute,
|
||||
BytesPerHour: cfg.BytesLimitPerHour,
|
||||
BytesPerDay: cfg.BytesLimitPerDay,
|
||||
},
|
||||
MaxClients: cfg.MaxTrackedClients,
|
||||
})
|
||||
params.Ledger = bans.New(bans.Params{
|
||||
LimitBanDuration: cfg.LimitBanDuration,
|
||||
LimitBanRepeatWindow: cfg.LimitBanRepeatWindow,
|
||||
|
||||
@@ -7,10 +7,6 @@ import (
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
)
|
||||
|
||||
// deny is the SWW_WAF_BLOCKLIST_ACTION and the SWW_WAF_DNSBL_ABUSEIPDB_ACTION that
|
||||
// refuses the requests of a client a source lists.
|
||||
const deny = "deny"
|
||||
|
||||
// noteListed notes each of sources, the URLs of the blocklists or the
|
||||
// DNSBL zones, their keys masked, that list the client, as noteHit does,
|
||||
// with reason.
|
||||
|
||||
@@ -421,7 +421,7 @@ func (rq *request) answerAtTheEnd() (geojs.Answer, bool) {
|
||||
return geojs.Answer{}, false
|
||||
}
|
||||
|
||||
if rq.h.config.LookupSource == "file" {
|
||||
if rq.h.config.LookupSource == config.LookupSourceFile {
|
||||
return rq.lookupAnswer, true
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user