Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78b4ef1210 |
No files matched your search
@@ -13,7 +13,6 @@ require (
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/spf13/viper v1.21.0
|
||||
go.uber.org/fx v1.24.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/sys v0.48.0
|
||||
)
|
||||
|
||||
@@ -51,6 +50,7 @@ require (
|
||||
go.uber.org/zap v1.26.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
|
||||
@@ -19,8 +19,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
)
|
||||
|
||||
// off is the value that switches a timeout, a size limit or a rate limit
|
||||
@@ -42,7 +40,9 @@ var (
|
||||
errNotPositive = errors.New("must be more than zero, or off")
|
||||
errNotMilliseconds = errors.New(
|
||||
"is not a whole number of milliseconds above zero, such as 2000")
|
||||
errEmptyItem = errors.New("has an empty item in its list")
|
||||
errEmptyItem = errors.New("has an empty item in its list")
|
||||
errNotNetblock = errors.New(
|
||||
"is not a netblock such as 10.0.0.0/8, or an address")
|
||||
errNotListenAddr = errors.New(
|
||||
"is not an address to listen on, such as :8080")
|
||||
errNotCommand = errors.New("is not rproxy or waf")
|
||||
@@ -253,7 +253,7 @@ func parseNetblocks(value string) ([]netip.Prefix, error) {
|
||||
netblocks := make([]netip.Prefix, 0, len(items))
|
||||
|
||||
for _, item := range items {
|
||||
netblock, err := reputation.ParseNetblock(item)
|
||||
netblock, err := ParseNetblock(item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -264,6 +264,27 @@ func parseNetblocks(value string) ([]netip.Prefix, error) {
|
||||
return netblocks, nil
|
||||
}
|
||||
|
||||
// ParseNetblock reads a netblock in CIDR form, such as 10.0.0.0/8. A bare
|
||||
// address is a netblock of that address alone, a /32 or a /128. A
|
||||
// blocklist's lines are read with it too.
|
||||
func ParseNetblock(value string) (netip.Prefix, error) {
|
||||
if strings.Contains(value, "/") {
|
||||
netblock, err := netip.ParsePrefix(value)
|
||||
if err != nil {
|
||||
return netip.Prefix{}, fmt.Errorf("%q %w", value, errNotNetblock)
|
||||
}
|
||||
|
||||
return netblock.Masked(), nil
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(value)
|
||||
if err != nil || addr.Zone() != "" {
|
||||
return netip.Prefix{}, fmt.Errorf("%q %w", value, errNotNetblock)
|
||||
}
|
||||
|
||||
return netip.PrefixFrom(addr, addr.BitLen()), nil
|
||||
}
|
||||
|
||||
// parseListenAddr checks an address to listen on: an optional host and a
|
||||
// port number.
|
||||
func parseListenAddr(value string) (string, error) {
|
||||
|
||||
+121
-77
@@ -20,26 +20,11 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/net/http/httpguts"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/anomaly"
|
||||
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
|
||||
"sneak.berlin/go/smallwebwaf/internal/remotelog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
)
|
||||
|
||||
// The names of the settings that waf writes into log lines and ban notes,
|
||||
// as the setting that refused a request or lowered a client's limits.
|
||||
const (
|
||||
ExclusivelyAllowedCountriesSetting = "SWW_WAF_EXCLUSIVELY_ALLOWED_COUNTRIES"
|
||||
TagLimitPercentSetting = "SWW_WAF_TAG_LIMIT_PERCENT"
|
||||
ASNBytesLimitPercentSetting = "SWW_WAF_ASN_BYTES_LIMIT_PERCENT"
|
||||
CountryBytesLimitPercentSetting = "SWW_WAF_COUNTRY_BYTES_LIMIT_PERCENT"
|
||||
UnknownCountryLimitPercentSetting = "SWW_WAF_UNKNOWN_COUNTRY_LIMIT_PERCENT"
|
||||
ASNLimitPercentURLSetting = "SWW_WAF_ASN_LIMIT_PERCENT_URL"
|
||||
BlocklistActionSetting = "SWW_WAF_BLOCKLIST_ACTION"
|
||||
DNSBLAbuseIPDBActionSetting = "SWW_WAF_DNSBL_ABUSEIPDB_ACTION"
|
||||
)
|
||||
|
||||
// WAF is the settings of `sww waf`. A time or size limit of zero is off.
|
||||
@@ -115,7 +100,7 @@ type WAF struct {
|
||||
// with a tag that percentage of every rate limit and byte limit, from 1
|
||||
// to 99 (SWW_WAF_TAG_LIMIT_PERCENT). All hold tags as requests carry them: in
|
||||
// lower case, a country code in capitals.
|
||||
TagLists []reputation.TagList
|
||||
TagLists []TagList
|
||||
TagDeny []string
|
||||
TagLimitPercent map[string]int64
|
||||
// RouteWatchURL is where the routewatch instance is that adds the asn=
|
||||
@@ -512,8 +497,12 @@ var (
|
||||
"is not a whole number above zero, such as 60, or off",
|
||||
)
|
||||
errNotUTF8 = errors.New("is not valid UTF-8")
|
||||
errNotASN = errors.New("is not an AS number such as AS64496")
|
||||
errNotPercentItem = errors.New(
|
||||
"is not a code, : and a percentage, such as AS64496:50 or cn:25")
|
||||
errNotPercent = errors.New(
|
||||
"is not a percentage, a whole number from 0 to 100",
|
||||
)
|
||||
errNotAbuseIPDBThreshold = errors.New(
|
||||
"is not a whole number from 25 to 100, the scores AbuseIPDB's " +
|
||||
"blacklist can be cut at",
|
||||
@@ -629,24 +618,24 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
"800",
|
||||
),
|
||||
ExclusivelyAllowedCountries: env.countries(
|
||||
ExclusivelyAllowedCountriesSetting, ""),
|
||||
"SWW_WAF_EXCLUSIVELY_ALLOWED_COUNTRIES", ""),
|
||||
TagLists: env.tagLists("SWW_WAF_TAG_LISTS"),
|
||||
TagDeny: env.tags("SWW_WAF_TAG_DENY"),
|
||||
TagLimitPercent: env.tagPercents(TagLimitPercentSetting),
|
||||
TagLimitPercent: env.tagPercents("SWW_WAF_TAG_LIMIT_PERCENT"),
|
||||
RouteWatchURL: env.routeWatchURL("SWW_WAF_ROUTEWATCH_URL"),
|
||||
ASNBytesLimitPercent: env.percents(
|
||||
ASNBytesLimitPercentSetting,
|
||||
reputation.ParseASN,
|
||||
"SWW_WAF_ASN_BYTES_LIMIT_PERCENT",
|
||||
ParseASN,
|
||||
),
|
||||
CountryBytesLimitPercent: env.percents(
|
||||
CountryBytesLimitPercentSetting,
|
||||
"SWW_WAF_COUNTRY_BYTES_LIMIT_PERCENT",
|
||||
parseCountry,
|
||||
),
|
||||
UnknownCountryLimitPercent: env.percent(
|
||||
UnknownCountryLimitPercentSetting,
|
||||
"SWW_WAF_UNKNOWN_COUNTRY_LIMIT_PERCENT",
|
||||
"100",
|
||||
),
|
||||
ASNLimitPercentURL: env.listURL(ASNLimitPercentURLSetting),
|
||||
ASNLimitPercentURL: env.listURL("SWW_WAF_ASN_LIMIT_PERCENT_URL"),
|
||||
BlocklistURLs: env.listURLs("SWW_WAF_BLOCKLIST_URLS"),
|
||||
BlocklistRefresh: env.refresh("SWW_WAF_BLOCKLIST_REFRESH", "24h"),
|
||||
DNSBLZones: env.zones("SWW_WAF_DNSBL_ZONES"),
|
||||
@@ -820,9 +809,9 @@ func WAFFromEnvironment(v *viper.Viper) (*WAF, error) {
|
||||
cfg.AddLookupHeaders = env.boolean("SWW_WAF_ADD_LOOKUP_HEADERS",
|
||||
strconv.FormatBool(cfg.LookupSource != LookupSourceOff))
|
||||
cfg.BlocklistAction, cfg.BlocklistLimitPercent = env.action(
|
||||
BlocklistActionSetting, string(ReputationActionDeny))
|
||||
"SWW_WAF_BLOCKLIST_ACTION", string(ReputationActionDeny))
|
||||
cfg.DNSBLAbuseIPDBAction, cfg.DNSBLAbuseIPDBLimitPercent = env.action(
|
||||
DNSBLAbuseIPDBActionSetting, "limit:25")
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION", "limit:25")
|
||||
|
||||
env.checkInstanceNameForNtfy(cfg.InstanceName, cfg.AlertNtfyURL != nil)
|
||||
env.checkLookupDBPath(cfg)
|
||||
@@ -1022,7 +1011,7 @@ func (e *environment) percents(
|
||||
}
|
||||
|
||||
// tagLists reads SWW_WAF_TAG_LISTS, which is empty by default.
|
||||
func (e *environment) tagLists(name string) []reputation.TagList {
|
||||
func (e *environment) tagLists(name string) []TagList {
|
||||
lists, err := parseTagLists(e.value(name, ""))
|
||||
e.check(name, err)
|
||||
|
||||
@@ -1048,7 +1037,7 @@ func (e *environment) tagPercents(name string) map[string]int64 {
|
||||
|
||||
// percent reads a setting that is a percentage, from 0 to 100.
|
||||
func (e *environment) percent(name, defaultValue string) int64 {
|
||||
percent, err := reputation.ParsePercent(e.value(name, defaultValue))
|
||||
percent, err := ParsePercent(e.value(name, defaultValue))
|
||||
e.check(name, err)
|
||||
|
||||
return percent
|
||||
@@ -1133,7 +1122,7 @@ func (e *environment) action(
|
||||
string(value), string(ReputationActionLimit)+":",
|
||||
)
|
||||
|
||||
percent, err := reputation.ParsePercent(percentText)
|
||||
percent, err := ParsePercent(percentText)
|
||||
if !isLimit || err != nil {
|
||||
e.check(name, fmt.Errorf("%q %w", value, errNotAction))
|
||||
}
|
||||
@@ -1142,8 +1131,8 @@ func (e *environment) action(
|
||||
}
|
||||
|
||||
// zones reads the setting that is the list of DNSBL zones. It is empty by
|
||||
// default. The log shows each zone with its key masked, as
|
||||
// reputation.MaskZoneKey masks it.
|
||||
// default. The log shows each zone with its key masked, as MaskZoneKey
|
||||
// masks it.
|
||||
func (e *environment) zones(name string) []string {
|
||||
value, _ := e.lookup(name)
|
||||
zones, err := parseZones(value)
|
||||
@@ -1151,7 +1140,7 @@ func (e *environment) zones(name string) []string {
|
||||
|
||||
logged := make([]string, len(zones))
|
||||
for i, zone := range zones {
|
||||
logged[i] = reputation.MaskZoneKey(zone)
|
||||
logged[i] = MaskZoneKey(zone)
|
||||
}
|
||||
|
||||
e.settings = append(
|
||||
@@ -1231,7 +1220,7 @@ func (e *environment) checkLookupDBPath(cfg *WAF) {
|
||||
func (e *environment) checkCountriesAndLookups(cfg *WAF) {
|
||||
for _, country := range cfg.ExclusivelyAllowedCountries {
|
||||
if slices.Contains(cfg.TagDeny, CountryTagPrefix+country) {
|
||||
e.check(ExclusivelyAllowedCountriesSetting,
|
||||
e.check("SWW_WAF_EXCLUSIVELY_ALLOWED_COUNTRIES",
|
||||
fmt.Errorf("%q %w", country, errOnBothLists))
|
||||
}
|
||||
}
|
||||
@@ -1250,15 +1239,15 @@ func (e *environment) checkCountriesAndLookups(cfg *WAF) {
|
||||
name string
|
||||
set bool
|
||||
}{
|
||||
{ExclusivelyAllowedCountriesSetting, len(cfg.ExclusivelyAllowedCountries) > 0},
|
||||
{"SWW_WAF_EXCLUSIVELY_ALLOWED_COUNTRIES", len(cfg.ExclusivelyAllowedCountries) > 0},
|
||||
{"SWW_WAF_ADD_LOOKUP_HEADERS", cfg.AddLookupHeaders},
|
||||
{"SWW_WAF_TAG_DENY", slices.ContainsFunc(cfg.TagDeny, onlyLookupGives)},
|
||||
{TagLimitPercentSetting, slices.ContainsFunc(
|
||||
{"SWW_WAF_TAG_LIMIT_PERCENT", slices.ContainsFunc(
|
||||
slices.Collect(maps.Keys(cfg.TagLimitPercent)), onlyLookupGives)},
|
||||
{ASNBytesLimitPercentSetting, len(cfg.ASNBytesLimitPercent) > 0},
|
||||
{CountryBytesLimitPercentSetting, len(cfg.CountryBytesLimitPercent) > 0},
|
||||
{UnknownCountryLimitPercentSetting, cfg.UnknownCountryLimitPercent < 100},
|
||||
{ASNLimitPercentURLSetting, cfg.ASNLimitPercentURL != ""},
|
||||
{"SWW_WAF_ASN_BYTES_LIMIT_PERCENT", len(cfg.ASNBytesLimitPercent) > 0},
|
||||
{"SWW_WAF_COUNTRY_BYTES_LIMIT_PERCENT", len(cfg.CountryBytesLimitPercent) > 0},
|
||||
{"SWW_WAF_UNKNOWN_COUNTRY_LIMIT_PERCENT", cfg.UnknownCountryLimitPercent < 100},
|
||||
{"SWW_WAF_ASN_LIMIT_PERCENT_URL", cfg.ASNLimitPercentURL != ""},
|
||||
{"SWW_WAF_ANOMALY_ASN_REQUESTS_PER_MINUTE", cfg.AnomalyASN.RequestsPerMinute > 0},
|
||||
{"SWW_WAF_ANOMALY_ASN_REQUESTS_PER_HOUR", cfg.AnomalyASN.RequestsPerHour > 0},
|
||||
{"SWW_WAF_ANOMALY_ASN_BYTES_PER_MINUTE", cfg.AnomalyASN.BytesPerMinute > 0},
|
||||
@@ -1278,7 +1267,7 @@ func (e *environment) checkCountriesAndLookups(cfg *WAF) {
|
||||
// blocklist too: the file at a URL is fetched as one list or the other.
|
||||
func (e *environment) checkASNLimitPercentURL(cfg *WAF) {
|
||||
if slices.Contains(cfg.BlocklistURLs, cfg.ASNLimitPercentURL) {
|
||||
e.check(ASNLimitPercentURLSetting,
|
||||
e.check("SWW_WAF_ASN_LIMIT_PERCENT_URL",
|
||||
fmt.Errorf("%q %w", cfg.ASNLimitPercentURL, errInBlocklistURLs))
|
||||
}
|
||||
}
|
||||
@@ -1305,18 +1294,14 @@ func (e *environment) checkTags(cfg *WAF) {
|
||||
}
|
||||
|
||||
for tag := range cfg.TagLimitPercent {
|
||||
e.check(TagLimitPercentSetting, checkTag(cfg, tag))
|
||||
e.check("SWW_WAF_TAG_LIMIT_PERCENT", checkTag(cfg, tag))
|
||||
}
|
||||
}
|
||||
|
||||
// checkTag returns an error when tag would never apply, as checkTags says.
|
||||
func checkTag(cfg *WAF, tag string) error {
|
||||
if !requestCanGetTag(cfg, tag) {
|
||||
return fmt.Errorf(
|
||||
"%q %w",
|
||||
reputation.MaskZoneKey(tag),
|
||||
errNoRequestGetsTag,
|
||||
)
|
||||
return fmt.Errorf("%q %w", MaskZoneKey(tag), errNoRequestGetsTag)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1324,7 +1309,7 @@ func checkTag(cfg *WAF, tag string) error {
|
||||
|
||||
// requestCanGetTag reports whether anything cfg sets up can give a request tag.
|
||||
func requestCanGetTag(cfg *WAF, tag string) bool {
|
||||
isListName := func(list reputation.TagList) bool { return list.Name == tag }
|
||||
isListName := func(list TagList) bool { return list.Name == tag }
|
||||
if isLookupTag(tag) || slices.ContainsFunc(cfg.TagLists, isListName) {
|
||||
return true
|
||||
}
|
||||
@@ -1348,7 +1333,7 @@ func requestCanGetTag(cfg *WAF, tag string) bool {
|
||||
|
||||
return isZoneTag &&
|
||||
slices.ContainsFunc(cfg.DNSBLZones, func(each string) bool {
|
||||
return strings.ToLower(reputation.MaskZoneKey(each)) == zone
|
||||
return strings.ToLower(MaskZoneKey(each)) == zone
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1846,9 +1831,7 @@ func parseNamedNetblocks(value string) ([]anomaly.NamedNetblock, error) {
|
||||
return nil, fmt.Errorf("%q %w", item, errNotNamedNetblock)
|
||||
}
|
||||
|
||||
netblock, err := reputation.ParseNetblock(
|
||||
strings.TrimSpace(netblockText),
|
||||
)
|
||||
netblock, err := ParseNetblock(strings.TrimSpace(netblockText))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2054,6 +2037,21 @@ func parseCountry(value string) (string, error) {
|
||||
return country, nil
|
||||
}
|
||||
|
||||
// ParseASN reads an AS number such as AS64496, in either case, and
|
||||
// returns it as the lookup gives it: AS and the number, in capitals and
|
||||
// without leading zeros. The file SWW_WAF_ASN_LIMIT_PERCENT_URL names is
|
||||
// read with it too.
|
||||
func ParseASN(value string) (string, error) {
|
||||
digits, hasAS := strings.CutPrefix(strings.ToUpper(value), "AS")
|
||||
|
||||
number, err := strconv.ParseUint(digits, 10, 32)
|
||||
if !hasAS || err != nil {
|
||||
return "", fmt.Errorf("%q %w", value, errNotASN)
|
||||
}
|
||||
|
||||
return "AS" + strconv.FormatUint(number, 10), nil
|
||||
}
|
||||
|
||||
// The tags a request can get that the settings can name, as waf
|
||||
// writes them. The prefixes are followed by a value.
|
||||
const (
|
||||
@@ -2067,17 +2065,24 @@ const (
|
||||
ExploitSignatureTag = "exploitsignature"
|
||||
)
|
||||
|
||||
// TagList is an address list of SWW_WAF_TAG_LISTS: the tag it adds to the
|
||||
// requests of the clients it holds, and the URL it is fetched from.
|
||||
type TagList struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
// parseTagLists reads a comma-separated list of name=URL pairs, such as
|
||||
// torexit=https://example.com/tor.txt, and returns each list with its name
|
||||
// in lower case. A name can hold a =, as vpn=mullvad does, and ends at the
|
||||
// = before http. A name or a URL listed twice is an error.
|
||||
func parseTagLists(value string) ([]reputation.TagList, error) {
|
||||
func parseTagLists(value string) ([]TagList, error) {
|
||||
items, err := parseList(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lists := make([]reputation.TagList, 0, len(items))
|
||||
lists := make([]TagList, 0, len(items))
|
||||
|
||||
for _, item := range items {
|
||||
end := strings.Index(item, "=http")
|
||||
@@ -2085,12 +2090,9 @@ func parseTagLists(value string) ([]reputation.TagList, error) {
|
||||
return nil, fmt.Errorf("%q %w", item, errNotTagList)
|
||||
}
|
||||
|
||||
list := reputation.TagList{
|
||||
Name: strings.ToLower(item[:end]),
|
||||
URL: item[end+1:],
|
||||
}
|
||||
list := TagList{Name: strings.ToLower(item[:end]), URL: item[end+1:]}
|
||||
|
||||
if slices.ContainsFunc(lists, func(earlier reputation.TagList) bool {
|
||||
if slices.ContainsFunc(lists, func(earlier TagList) bool {
|
||||
return earlier.Name == list.Name || earlier.URL == list.URL
|
||||
}) {
|
||||
return nil, fmt.Errorf("%q %w", item, errListedTwice)
|
||||
@@ -2103,8 +2105,7 @@ func parseTagLists(value string) ([]reputation.TagList, error) {
|
||||
}
|
||||
|
||||
// parseTags reads a comma-separated list of tags, which parseTag reads. A
|
||||
// tag listed twice is an error, which shows the tag as
|
||||
// reputation.MaskZoneKey does.
|
||||
// tag listed twice is an error, which shows the tag as MaskZoneKey does.
|
||||
func parseTags(value string) ([]string, error) {
|
||||
items, err := parseList(value)
|
||||
if err != nil {
|
||||
@@ -2124,7 +2125,7 @@ func parseTags(value string) ([]string, error) {
|
||||
if slices.Contains(tags, tag) {
|
||||
return nil, fmt.Errorf(
|
||||
"%q %w",
|
||||
reputation.MaskZoneKey(item),
|
||||
MaskZoneKey(item),
|
||||
errListedTwice,
|
||||
)
|
||||
}
|
||||
@@ -2193,7 +2194,7 @@ func parseTagPercents(value string) (map[string]int64, error) {
|
||||
if colon <= 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"%q %w",
|
||||
reputation.MaskZoneKey(item),
|
||||
MaskZoneKey(item),
|
||||
errNotTagPercentItem,
|
||||
)
|
||||
}
|
||||
@@ -2207,7 +2208,7 @@ func parseTagPercents(value string) (map[string]int64, error) {
|
||||
if err != nil || percent < 1 || percent > 99 {
|
||||
return nil, fmt.Errorf(
|
||||
"%q %w",
|
||||
reputation.MaskZoneKey(item[colon+1:]),
|
||||
MaskZoneKey(item[colon+1:]),
|
||||
errNotTagPercent,
|
||||
)
|
||||
}
|
||||
@@ -2219,11 +2220,7 @@ func parseTagPercents(value string) (map[string]int64, error) {
|
||||
if _, listed := percents[tag]; listed {
|
||||
// tag, since item[:colon] may end in a space, which MaskZoneKey
|
||||
// would not mask.
|
||||
return nil, fmt.Errorf(
|
||||
"%q %w",
|
||||
reputation.MaskZoneKey(tag),
|
||||
errListedTwice,
|
||||
)
|
||||
return nil, fmt.Errorf("%q %w", MaskZoneKey(tag), errListedTwice)
|
||||
}
|
||||
|
||||
percents[tag] = percent
|
||||
@@ -2257,7 +2254,7 @@ func parsePercents(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
percent, err := reputation.ParsePercent(percentText)
|
||||
percent, err := ParsePercent(percentText)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2272,6 +2269,38 @@ func parsePercents(
|
||||
return percents, nil
|
||||
}
|
||||
|
||||
// ParsePercent reads a percentage, a whole number from 0 to 100. The file
|
||||
// SWW_WAF_ASN_LIMIT_PERCENT_URL names is read with it too.
|
||||
func ParsePercent(value string) (int64, error) {
|
||||
percent, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || percent < 0 || percent > 100 {
|
||||
return 0, fmt.Errorf("%q %w", value, errNotPercent)
|
||||
}
|
||||
|
||||
return percent, nil
|
||||
}
|
||||
|
||||
// headerNameChars are the characters RFC 9110 allows in a header name:
|
||||
// letters, digits and these marks.
|
||||
const headerNameChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
|
||||
"0123456789!#$%&'*+-.^_`|~"
|
||||
|
||||
// IsHeaderName reports whether name can be a header name: one or more of
|
||||
// the characters RFC 9110 allows in one.
|
||||
func IsHeaderName(name string) bool {
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, char := range name {
|
||||
if !strings.ContainsRune(headerNameChars, char) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// parseHeaderNames reads a comma-separated list of header names in either
|
||||
// case, and returns them in lower case. Host and Transfer-Encoding are
|
||||
// refused: Go's HTTP server takes them out of the request's headers.
|
||||
@@ -2284,7 +2313,7 @@ func parseHeaderNames(value string) ([]string, error) {
|
||||
headers := make([]string, 0, len(items))
|
||||
|
||||
for _, item := range items {
|
||||
if !httpguts.ValidHeaderFieldName(item) {
|
||||
if !IsHeaderName(item) {
|
||||
return nil, fmt.Errorf("%q %w", item, errNotHeaderName)
|
||||
}
|
||||
|
||||
@@ -2440,8 +2469,8 @@ const (
|
||||
// other name for one that does not exist, so that the zone would list no
|
||||
// client. A zone listed twice is an error, whatever the case of its
|
||||
// letters, which DNS names ignore, and whatever its key, since
|
||||
// reputation.MaskZoneKey shows two keys of one zone alike. An error shows a
|
||||
// zone as it does.
|
||||
// MaskZoneKey shows two keys of one zone alike. An error shows a zone as
|
||||
// MaskZoneKey does.
|
||||
func parseZones(value string) ([]string, error) {
|
||||
zones, err := parseList(value)
|
||||
if err != nil {
|
||||
@@ -2451,14 +2480,11 @@ func parseZones(value string) ([]string, error) {
|
||||
}
|
||||
|
||||
for i, zone := range zones {
|
||||
shown := reputation.MaskZoneKey(zone)
|
||||
shown := MaskZoneKey(zone)
|
||||
listedBefore := slices.ContainsFunc(
|
||||
zones[:i],
|
||||
func(earlier string) bool {
|
||||
return strings.EqualFold(
|
||||
reputation.MaskZoneKey(earlier),
|
||||
shown,
|
||||
)
|
||||
return strings.EqualFold(MaskZoneKey(earlier), shown)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -2475,6 +2501,24 @@ func parseZones(value string) ([]string, error) {
|
||||
return zones, nil
|
||||
}
|
||||
|
||||
// MaskZoneKey returns zone with ******** in place of its key, if it is a
|
||||
// zone of Spamhaus's keyed query service, a name under dq.spamhaus.net,
|
||||
// such as <key>.xbl.dq.spamhaus.net, whose first label is the key. Any
|
||||
// other zone it returns as it is. A zone is shown so wherever it leaves
|
||||
// the process: in the log, the alerts and the metrics.
|
||||
func MaskZoneKey(zone string) string {
|
||||
// DNS names ignore case, and a name may be written with a dot at its
|
||||
// end.
|
||||
name := strings.TrimSuffix(strings.ToLower(zone), ".")
|
||||
if !strings.HasSuffix(name, ".dq.spamhaus.net") {
|
||||
return zone
|
||||
}
|
||||
|
||||
_, rest, _ := strings.Cut(zone, ".")
|
||||
|
||||
return masked + "." + rest
|
||||
}
|
||||
|
||||
// isZone reports whether each label of zone is as parseZones takes it. It
|
||||
// also checks the hostnames of SWW_WAF_APPS, which are DNS names too.
|
||||
func isZone(zone string) bool {
|
||||
@@ -2530,7 +2574,7 @@ func parseWebhookHeaders(value string) (http.Header, string, error) {
|
||||
name, headerValue, found := strings.Cut(item, ":")
|
||||
name = strings.TrimSpace(name)
|
||||
|
||||
if !found || !httpguts.ValidHeaderFieldName(name) ||
|
||||
if !found || !IsHeaderName(name) ||
|
||||
strings.ContainsAny(headerValue, "\r\n\x00") {
|
||||
return nil, "", fmt.Errorf(
|
||||
"item %d %w",
|
||||
|
||||
+20
-29
@@ -18,12 +18,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/net/http/httpguts"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/anomaly"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config/configtest"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
)
|
||||
|
||||
// The settings, by name.
|
||||
@@ -866,32 +864,6 @@ func TestInstanceNameAndLoggedHeadersAsSet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// config and rules check header names with httpguts.ValidHeaderFieldName.
|
||||
// It takes a name of one or more of the characters RFC 9110 allows in one,
|
||||
// as the check it replaced did: letters, digits and these marks.
|
||||
func TestHeaderNameCheckTakesTheRFC9110Characters(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const marks = "!#$%&'*+-.^_`|~"
|
||||
|
||||
if httpguts.ValidHeaderFieldName("") {
|
||||
t.Error("the empty name is taken")
|
||||
}
|
||||
|
||||
for b := range 256 {
|
||||
char := byte(b)
|
||||
want := 'a' <= char && char <= 'z' || 'A' <= char && char <= 'Z' ||
|
||||
'0' <= char && char <= '9' || strings.IndexByte(marks, char) >= 0
|
||||
|
||||
// string(char) would be the UTF-8 of U+0080 to U+00FF, two bytes,
|
||||
// for a byte above 0x7f.
|
||||
name := string([]byte{char})
|
||||
if got := httpguts.ValidHeaderFieldName(name); got != want {
|
||||
t.Errorf("the name %q is taken: %t, want %t", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteLogSettingsDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1722,7 +1694,7 @@ func TestTagSettingsAsSet(t *testing.T) {
|
||||
tagLimitPercent: "vpn=mullvad :50, asn=014061:25, COUNTRY=cn:1, dnsbl=zen.example:99",
|
||||
})
|
||||
|
||||
wantLists := []reputation.TagList{
|
||||
wantLists := []config.TagList{
|
||||
{Name: torExitTag, URL: torURL},
|
||||
{Name: "vpn=mullvad", URL: "https://example.com/mullvad.txt"},
|
||||
}
|
||||
@@ -2316,6 +2288,25 @@ func TestInvalidDNSBLSettingStopsTheStartSayingWhatIsWrong(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaskZoneKeyMasksTheFirstLabelOfAZoneUnderDqSpamhausNet(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
for zone, want := range map[string]string{
|
||||
spamhaus: spamhausMasked,
|
||||
spamhaus + ".": spamhausMasked + ".",
|
||||
"KEY.ZEN.DQ.SPAMHAUS.NET": "********.ZEN.DQ.SPAMHAUS.NET",
|
||||
dronebl: dronebl,
|
||||
"dq.spamhaus.net": "dq.spamhaus.net",
|
||||
spamhaus + ".example": spamhaus + ".example",
|
||||
} {
|
||||
if got := config.MaskZoneKey(zone); got != want {
|
||||
t.Errorf("MaskZoneKey(%q) is %q, want %q", zone, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSBLZoneKeyIsLoggedMaskedAndNeverShown(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
+14
-47
@@ -99,13 +99,8 @@ type GeoJS struct {
|
||||
// waiting are the clients without an answer: those to ask GeoJS about,
|
||||
// and those it is being asked about.
|
||||
waiting map[netip.Prefix]*wait
|
||||
// asking is true while a request to GeoJS is under way, and endAsking
|
||||
// ends it. stopped is true once StopAsking has been called, and
|
||||
// askGoroutines waits for the goroutine that makes the requests.
|
||||
asking bool
|
||||
endAsking context.CancelFunc
|
||||
stopped bool
|
||||
askGoroutines sync.WaitGroup
|
||||
// asking is true while a request to GeoJS is under way.
|
||||
asking bool
|
||||
// retryDelay is how long GeoJS is left alone after its last failure,
|
||||
// zero after an answer; retryAt is when it may be asked again.
|
||||
retryDelay time.Duration
|
||||
@@ -215,23 +210,6 @@ func (g *GeoJS) LookUpWithoutWaiting(
|
||||
return answer
|
||||
}
|
||||
|
||||
// StopAsking ends the request to GeoJS under way, and returns once the
|
||||
// goroutine that made it has. A request it ends is no failure: Failed is not
|
||||
// called, and GeoJS is not left alone after it. After StopAsking, GeoJS is
|
||||
// asked nothing.
|
||||
func (g *GeoJS) StopAsking() {
|
||||
g.mu.Lock()
|
||||
|
||||
g.stopped = true
|
||||
if g.asking {
|
||||
g.endAsking()
|
||||
}
|
||||
|
||||
g.mu.Unlock()
|
||||
|
||||
g.askGoroutines.Wait()
|
||||
}
|
||||
|
||||
// Kept returns client's answer, if one is kept, without asking GeoJS.
|
||||
func (g *GeoJS) Kept(client netip.Prefix) (Answer, bool) {
|
||||
g.mu.Lock()
|
||||
@@ -316,8 +294,7 @@ func (g *GeoJS) answerOrWait(
|
||||
}
|
||||
|
||||
if !g.asking {
|
||||
// GeoJS is left alone after a failure, or asked nothing after
|
||||
// StopAsking, so no answer can come.
|
||||
// GeoJS is left alone after a failure, so no answer can come.
|
||||
w.late = true
|
||||
}
|
||||
|
||||
@@ -346,28 +323,22 @@ func (g *GeoJS) kept(client netip.Prefix) (Answer, bool) {
|
||||
}
|
||||
|
||||
// ask starts asking GeoJS about the waiting clients, unless a request to
|
||||
// it is under way, it is left alone after a failure, or StopAsking has
|
||||
// been called. The requests to GeoJS are for every client waiting, so they
|
||||
// go on when the caller whose ctx is given stops waiting, until StopAsking.
|
||||
// it is under way or it is left alone after a failure. The requests to
|
||||
// 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.stopped || g.now().Before(g.retryAt) {
|
||||
if g.asking || g.now().Before(g.retryAt) {
|
||||
return
|
||||
}
|
||||
|
||||
askCtx, end := context.WithCancel(context.WithoutCancel(ctx))
|
||||
g.asking, g.endAsking = true, end
|
||||
g.asking = true
|
||||
|
||||
g.askGoroutines.Go(func() {
|
||||
defer end()
|
||||
|
||||
g.askAboutWaiting(askCtx)
|
||||
})
|
||||
go g.askAboutWaiting(context.WithoutCancel(ctx))
|
||||
}
|
||||
|
||||
// askAboutWaiting asks GeoJS about the waiting clients, one request at a
|
||||
// time, until none is left, GeoJS fails, or StopAsking ends ctx. Each
|
||||
// answer kept is given to Answered, outside the lock, since Answered takes
|
||||
// locks of its own.
|
||||
// time, until none is left or GeoJS fails. Each answer kept is given to
|
||||
// Answered, outside the lock, since Answered takes locks of its own.
|
||||
func (g *GeoJS) askAboutWaiting(ctx context.Context) {
|
||||
for {
|
||||
clients := g.nextClients()
|
||||
@@ -376,10 +347,6 @@ func (g *GeoJS) askAboutWaiting(ctx context.Context) {
|
||||
}
|
||||
|
||||
given, err := g.request(ctx, clients)
|
||||
if err != nil && ctx.Err() != nil {
|
||||
continue // ended by StopAsking, which is no failure
|
||||
}
|
||||
|
||||
kept, answered := g.keep(clients, given, err)
|
||||
|
||||
if g.answered != nil {
|
||||
@@ -395,13 +362,13 @@ func (g *GeoJS) askAboutWaiting(ctx context.Context) {
|
||||
}
|
||||
|
||||
// nextClients returns up to maxPerRequest of the waiting clients. When
|
||||
// none is waiting, or StopAsking has been called, it returns none and
|
||||
// notes that no request to GeoJS is under way.
|
||||
// none is waiting, it returns none and notes that no request to GeoJS is
|
||||
// under way.
|
||||
func (g *GeoJS) nextClients() []netip.Prefix {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
|
||||
if len(g.waiting) == 0 || g.stopped {
|
||||
if len(g.waiting) == 0 {
|
||||
g.asking = false
|
||||
|
||||
return nil
|
||||
|
||||
@@ -318,44 +318,6 @@ func TestCallerWhoseContextEndsEarlyDoesNotStopTheRequest(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestStopAskingEndsTheRequestUnderWayAsNoFailureAndAsksNoMore(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
service, _, g, reports := startWithReports()
|
||||
clients := newClients()
|
||||
|
||||
service.set(hanging)
|
||||
g.LookUpWithoutWaiting(t.Context(), clients())
|
||||
waitForRequests(t, service, 1)
|
||||
|
||||
// The request is ended, not waited out, and is no failure.
|
||||
began := time.Now()
|
||||
|
||||
g.StopAsking()
|
||||
|
||||
if waited := time.Since(began); waited != 0 {
|
||||
t.Errorf("StopAsking returned after %s, want at once", waited)
|
||||
}
|
||||
|
||||
reports.wantFailures(t)
|
||||
|
||||
// A new client is then not asked about, and its lookup does not
|
||||
// wait.
|
||||
service.set(answering)
|
||||
wantCountry(t, g, clients(), "")
|
||||
|
||||
if waited := time.Since(began); waited != 0 {
|
||||
t.Errorf("the lookup returned after %s, want at once", waited)
|
||||
}
|
||||
|
||||
waitForRequests(t, service, 1)
|
||||
reports.wantFailures(t)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestOver10SecondsIsAFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||
"sneak.berlin/go/smallwebwaf/internal/remotelog"
|
||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||
@@ -300,7 +301,7 @@ const sourceLabel = "source"
|
||||
|
||||
// AddReputation adds the metrics of the lists fetched from URLs and of the
|
||||
// DNSBL zones, by source, each list's URL or each zone, its key masked as
|
||||
// reputation.MaskZoneKey masks it: the requests whose client a blocklist, a
|
||||
// config.MaskZoneKey masks it: the requests whose client a blocklist, a
|
||||
// zone's verdict or AbuseIPDB's score lists, which ReputationHit counts,
|
||||
// and, read from lists and dnsbl as the metrics are asked for, for a list,
|
||||
// the fetches that failed and when the copy in use was fetched, and for a
|
||||
@@ -319,9 +320,7 @@ func (m *Metrics) AddReputation(
|
||||
m.registry.MustRegister(m.reputationHits)
|
||||
|
||||
for _, zone := range dnsbl.Zones() {
|
||||
source := prometheus.Labels{
|
||||
sourceLabel: reputation.MaskZoneKey(zone),
|
||||
}
|
||||
source := prometheus.Labels{sourceLabel: config.MaskZoneKey(zone)}
|
||||
|
||||
m.addReputationQueries(
|
||||
source,
|
||||
|
||||
@@ -110,12 +110,8 @@ type AbuseIPDB struct {
|
||||
// scores are by client. Each is added as it is fetched and never moved
|
||||
// up, so that the one fetched longest ago is the first dropped.
|
||||
scores *simplelru.LRU[netip.Prefix, Score]
|
||||
// checking are the clients whose check is under way, each with the
|
||||
// function that ends it. stopped is true once StopChecking has been
|
||||
// called, and checkGoroutines waits for the goroutine of each check.
|
||||
checking map[netip.Prefix]context.CancelFunc
|
||||
stopped bool
|
||||
checkGoroutines sync.WaitGroup
|
||||
// checking are the clients whose check is under way.
|
||||
checking map[netip.Prefix]bool
|
||||
// day is the day, in UTC, of the checks spent counts.
|
||||
day civil.Date
|
||||
spent int
|
||||
@@ -138,7 +134,7 @@ func NewAbuseIPDB(params AbuseIPDBParams) *AbuseIPDB {
|
||||
params: params,
|
||||
httpClient: &http.Client{},
|
||||
scores: scores,
|
||||
checking: map[netip.Prefix]context.CancelFunc{},
|
||||
checking: map[netip.Prefix]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,11 +144,11 @@ func NewAbuseIPDB(params AbuseIPDBParams) *AbuseIPDB {
|
||||
// addresses its request comes from. A client without one is checked in
|
||||
// the background, by addr, the address its request came from, if
|
||||
// offender, if it has committed an offence, unless its check is under
|
||||
// way, a check failed less than failureDelay ago, the day's checks have
|
||||
// used up DailyBudget, or StopChecking has been called; Hit never waits
|
||||
// for a check. The check that uses the budget up is logged and raised as a
|
||||
// source_failure alert. ctx is the context of the client's request, and a
|
||||
// check goes on after the request ends, until StopChecking.
|
||||
// way, a check failed less than failureDelay ago, or the day's checks
|
||||
// have used up DailyBudget; Hit never waits for a check. The check that
|
||||
// uses the budget up is logged and raised as a source_failure alert. ctx
|
||||
// is the context of the client's request, and a check goes on after the
|
||||
// request ends.
|
||||
func (a *AbuseIPDB) Hit(
|
||||
ctx context.Context, client netip.Prefix, addr netip.Addr, offender bool,
|
||||
) (int64, bool) {
|
||||
@@ -171,21 +167,14 @@ func (a *AbuseIPDB) Hit(
|
||||
a.day, a.spent = today, 0
|
||||
}
|
||||
|
||||
_, checking := a.checking[client]
|
||||
|
||||
check := offender && !checking && !a.stopped &&
|
||||
!now.Before(a.retryAt) && a.spent < a.params.DailyBudget
|
||||
check := offender && !a.checking[client] && !now.Before(a.retryAt) &&
|
||||
a.spent < a.params.DailyBudget
|
||||
if check {
|
||||
checkCtx, end := context.WithCancel(context.WithoutCancel(ctx))
|
||||
a.checking[client] = end
|
||||
a.checking[client] = true
|
||||
a.checks++
|
||||
a.spent++
|
||||
|
||||
a.checkGoroutines.Go(func() {
|
||||
defer end()
|
||||
|
||||
a.check(checkCtx, client, addr)
|
||||
})
|
||||
go a.check(context.WithoutCancel(ctx), client, addr)
|
||||
}
|
||||
|
||||
usedUp := check && a.spent == a.params.DailyBudget
|
||||
@@ -200,24 +189,6 @@ func (a *AbuseIPDB) Hit(
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// StopChecking ends the checks under way, and returns once their goroutines
|
||||
// have. A check it ends gives no score and is no failure: it is neither
|
||||
// counted, logged nor raised as an alert, and checks are not left alone
|
||||
// after it. The ended check stays spent from the day's budget. After
|
||||
// StopChecking, Hit checks no client.
|
||||
func (a *AbuseIPDB) StopChecking() {
|
||||
a.mu.Lock()
|
||||
|
||||
a.stopped = true
|
||||
for _, end := range a.checking {
|
||||
end()
|
||||
}
|
||||
|
||||
a.mu.Unlock()
|
||||
|
||||
a.checkGoroutines.Wait()
|
||||
}
|
||||
|
||||
// Checked returns how many checks were made.
|
||||
func (a *AbuseIPDB) Checked() int {
|
||||
a.mu.Lock()
|
||||
@@ -344,8 +315,7 @@ func (a *AbuseIPDB) RunBlacklist(ctx context.Context) {
|
||||
// check checks client with AbuseIPDB by addr, one of its addresses, keeps
|
||||
// the score as client's, and notes the check as no longer under way. A
|
||||
// check that fails gives no score: it is counted, logged and raised as a
|
||||
// source_failure alert, and no client is checked for failureDelay. A check
|
||||
// ended as ctx ends, by StopChecking, is no failure.
|
||||
// source_failure alert, and no client is checked for failureDelay.
|
||||
func (a *AbuseIPDB) check(
|
||||
ctx context.Context,
|
||||
client netip.Prefix,
|
||||
@@ -353,26 +323,24 @@ func (a *AbuseIPDB) check(
|
||||
) {
|
||||
score, err := a.ask(ctx, addr)
|
||||
now := a.params.Now()
|
||||
isFailure := err != nil && ctx.Err() == nil
|
||||
|
||||
a.mu.Lock()
|
||||
|
||||
delete(a.checking, client)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if err == nil {
|
||||
a.scores.Add(
|
||||
client,
|
||||
Score{Client: client, Score: score, Fetched: now},
|
||||
)
|
||||
case isFailure:
|
||||
} else {
|
||||
a.failures++
|
||||
a.retryAt = now.Add(failureDelay)
|
||||
}
|
||||
|
||||
a.mu.Unlock()
|
||||
|
||||
if isFailure {
|
||||
if err != nil {
|
||||
a.alert("checking a client with AbuseIPDB failed", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,43 +394,6 @@ func TestCheckNotAnsweredWithinTheTimeoutFailsAndHitNeverWaits(
|
||||
})
|
||||
}
|
||||
|
||||
func TestStopCheckingEndsTheCheckUnderWayAsNoFailureAndChecksNoMore(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
queue := newQueue()
|
||||
p := abuseIPDBParams()
|
||||
p.Alerts = queue
|
||||
abuseIPDB := &abuseIPDBStandIn{hanging: true}
|
||||
checker := newAbuseIPDB(abuseIPDB, p)
|
||||
|
||||
wantScore(t, checker, suspect, true, 0, false)
|
||||
synctest.Wait()
|
||||
|
||||
// The check is ended, not waited out, and is no failure.
|
||||
began := time.Now()
|
||||
|
||||
checker.StopChecking()
|
||||
|
||||
if waited := time.Since(began); waited != 0 {
|
||||
t.Errorf("StopChecking returned after %s, want at once", waited)
|
||||
}
|
||||
|
||||
wantFailures(t, checker, 0)
|
||||
|
||||
if got := waiting(queue); len(got) != 0 {
|
||||
t.Errorf("alerts waiting %+v, want none", got)
|
||||
}
|
||||
|
||||
// An offender without a score is then not checked.
|
||||
wantScore(t, checker, other, true, 0, false)
|
||||
synctest.Wait()
|
||||
wantChecked(t, abuseIPDB, suspect)
|
||||
})
|
||||
}
|
||||
|
||||
func TestKeyIsSentInTheKeyHeaderAndNeverShown(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/hashicorp/golang-lru/v2/simplelru"
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -31,8 +32,6 @@ const (
|
||||
// it fails, and no client is checked with AbuseIPDB after a check
|
||||
// fails, so that a source refusing them is not asked on every request.
|
||||
failureDelay = time.Minute
|
||||
// maskedKey is what MaskZoneKey shows in place of a zone's key.
|
||||
maskedKey = "********"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -83,12 +82,8 @@ type DNSBL struct {
|
||||
// verdicts are by query. Each is added as it is fetched and never moved
|
||||
// up, so that the one fetched longest ago is the first dropped.
|
||||
verdicts *simplelru.LRU[query, Verdict]
|
||||
// asking are the queries under way, each with the function that ends
|
||||
// it. stopped is true once StopAsking has been called, and
|
||||
// queryGoroutines waits for the goroutine of each query.
|
||||
asking map[query]context.CancelFunc
|
||||
stopped bool
|
||||
queryGoroutines sync.WaitGroup
|
||||
// asking are the queries under way.
|
||||
asking map[query]bool
|
||||
// queries and failures count, by zone, the queries made and those that
|
||||
// failed, and retryAt is when a zone whose last query failed may be
|
||||
// asked again.
|
||||
@@ -125,31 +120,13 @@ func NewDNSBL(params DNSBLParams) *DNSBL {
|
||||
params: params,
|
||||
resolver: resolver,
|
||||
verdicts: verdicts,
|
||||
asking: map[query]context.CancelFunc{},
|
||||
asking: map[query]bool{},
|
||||
queries: map[string]int{},
|
||||
failures: map[string]int{},
|
||||
retryAt: map[string]time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
// MaskZoneKey returns zone with ******** in place of its key, if it is a
|
||||
// zone of Spamhaus's keyed query service, a name under dq.spamhaus.net,
|
||||
// such as <key>.xbl.dq.spamhaus.net, whose first label is the key. Any
|
||||
// other zone it returns as it is. A zone is shown so wherever it leaves
|
||||
// the process: in the log, the alerts and the metrics.
|
||||
func MaskZoneKey(zone string) string {
|
||||
// DNS names ignore case, and a name may be written with a dot at its
|
||||
// end.
|
||||
name := strings.TrimSuffix(strings.ToLower(zone), ".")
|
||||
if !strings.HasSuffix(name, ".dq.spamhaus.net") {
|
||||
return zone
|
||||
}
|
||||
|
||||
_, rest, _ := strings.Cut(zone, ".")
|
||||
|
||||
return maskedKey + "." + rest
|
||||
}
|
||||
|
||||
// Zones returns the zones, in the order SWW_WAF_DNSBL_ZONES names them.
|
||||
func (d *DNSBL) Zones() []string {
|
||||
return slices.Clone(d.params.Zones)
|
||||
@@ -157,14 +134,13 @@ func (d *DNSBL) Zones() []string {
|
||||
|
||||
// ListedBy returns the zones whose verdict on addr, a client's address,
|
||||
// lists it, in the order SWW_WAF_DNSBL_ZONES names them, each with its key
|
||||
// masked, as MaskZoneKey masks it, since they go to the request
|
||||
// masked, as config.MaskZoneKey masks it, since they go to the request
|
||||
// log, the alerts and the metrics. A verdict is used until CacheTTL has
|
||||
// passed since it was fetched. Each zone without one is asked about addr
|
||||
// in the background, unless a query about addr to it is under way, the
|
||||
// zone is left alone after a failure, maxQueries are under way, or
|
||||
// StopAsking has been called; ListedBy never waits for a query. ctx is the
|
||||
// context of the client's request, and a query goes on after the request
|
||||
// ends, until StopAsking.
|
||||
// zone is left alone after a failure, or maxQueries are under way;
|
||||
// ListedBy never waits for a query. ctx is the context of the client's
|
||||
// request, and a query goes on after the request ends.
|
||||
func (d *DNSBL) ListedBy(ctx context.Context, addr netip.Addr) []string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
@@ -177,47 +153,23 @@ func (d *DNSBL) ListedBy(ctx context.Context, addr netip.Addr) []string {
|
||||
q := query{zone: zone, client: addr}
|
||||
|
||||
kept, found := d.verdicts.Peek(q)
|
||||
_, asking := d.asking[q]
|
||||
|
||||
switch {
|
||||
case found && now.Sub(kept.Fetched) < d.params.CacheTTL:
|
||||
if kept.Listed {
|
||||
listedBy = append(listedBy, MaskZoneKey(zone))
|
||||
listedBy = append(listedBy, config.MaskZoneKey(zone))
|
||||
}
|
||||
case !asking && !d.stopped && !now.Before(d.retryAt[zone]) &&
|
||||
len(d.asking) < maxQueries:
|
||||
queryCtx, end := context.WithCancel(context.WithoutCancel(ctx))
|
||||
d.asking[q] = end
|
||||
case !d.asking[q] && !now.Before(d.retryAt[zone]) && len(d.asking) < maxQueries:
|
||||
d.asking[q] = true
|
||||
d.queries[zone]++
|
||||
|
||||
d.queryGoroutines.Go(func() {
|
||||
defer end()
|
||||
|
||||
d.ask(queryCtx, q)
|
||||
})
|
||||
go d.ask(context.WithoutCancel(ctx), q)
|
||||
}
|
||||
}
|
||||
|
||||
return listedBy
|
||||
}
|
||||
|
||||
// StopAsking ends the queries under way, and returns once their
|
||||
// goroutines have. A query it ends gives no verdict and is no failure: it
|
||||
// is neither counted, logged nor raised as an alert, and the zone is not
|
||||
// left alone after it. After StopAsking, ListedBy asks no zone.
|
||||
func (d *DNSBL) StopAsking() {
|
||||
d.mu.Lock()
|
||||
|
||||
d.stopped = true
|
||||
for _, end := range d.asking {
|
||||
end()
|
||||
}
|
||||
|
||||
d.mu.Unlock()
|
||||
|
||||
d.queryGoroutines.Wait()
|
||||
}
|
||||
|
||||
// Queries returns how many queries were made to zone.
|
||||
func (d *DNSBL) Queries(zone string) int {
|
||||
d.mu.Lock()
|
||||
@@ -286,32 +238,30 @@ func (d *DNSBL) Load(verdicts []Verdict) {
|
||||
// query as no longer under way. A query that fails gives no verdict: it
|
||||
// is counted, logged and raised as a source_failure alert, which show the
|
||||
// zone with its key masked, and the zone is not asked again for
|
||||
// failureDelay. A query ended as ctx ends, by StopAsking, is no failure.
|
||||
// failureDelay.
|
||||
func (d *DNSBL) ask(ctx context.Context, q query) {
|
||||
listed, err := d.lookUp(ctx, q)
|
||||
now := d.params.Now()
|
||||
isFailure := err != nil && ctx.Err() == nil
|
||||
|
||||
d.mu.Lock()
|
||||
|
||||
delete(d.asking, q)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if err == nil {
|
||||
d.verdicts.Add(q, Verdict{
|
||||
Zone: q.zone, Client: q.client, Listed: listed, Fetched: now,
|
||||
})
|
||||
case isFailure:
|
||||
} else {
|
||||
d.failures[q.zone]++
|
||||
d.retryAt[q.zone] = now.Add(failureDelay)
|
||||
}
|
||||
|
||||
d.mu.Unlock()
|
||||
|
||||
if isFailure {
|
||||
if err != nil {
|
||||
const failed = "asking a DNSBL zone failed"
|
||||
|
||||
shown := MaskZoneKey(q.zone)
|
||||
shown := config.MaskZoneKey(q.zone)
|
||||
|
||||
// Raised before it is logged, so that the alert is there once the
|
||||
// log line is.
|
||||
|
||||
@@ -210,45 +210,6 @@ func TestQueryNotAnsweredWithinTheTimeoutFails(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
//
|
||||
//nolint:paralleltest // one at a time, as the comment at the top of this file says
|
||||
func TestStopAskingEndsTheQueryUnderWayAsNoFailureAndAsksNoMore(
|
||||
t *testing.T,
|
||||
) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
queue := newQueue()
|
||||
p := dnsblParams(zone)
|
||||
p.Alerts = queue
|
||||
resolver := &resolverStandIn{hanging: true}
|
||||
dnsbl := newDNSBL(resolver, p)
|
||||
|
||||
wantZones(t, dnsbl, listed)
|
||||
synctest.Wait()
|
||||
|
||||
// The query is ended, not waited out, and is no failure.
|
||||
began := time.Now()
|
||||
|
||||
dnsbl.StopAsking()
|
||||
|
||||
if waited := time.Since(began); waited != 0 {
|
||||
t.Errorf("StopAsking returned after %s, want at once", waited)
|
||||
}
|
||||
|
||||
wantQueries(t, dnsbl, 1, 0)
|
||||
|
||||
if got := waiting(queue); len(got) != 0 {
|
||||
t.Errorf("alerts waiting %+v, want none", got)
|
||||
}
|
||||
|
||||
// A client without a verdict is then asked about in no zone.
|
||||
wantZones(t, dnsbl, unlisted)
|
||||
synctest.Wait()
|
||||
wantQueries(t, dnsbl, 1, 0)
|
||||
wantAsked(t, resolver, listedName)
|
||||
waitForTheResolver()
|
||||
})
|
||||
}
|
||||
|
||||
//
|
||||
//nolint:paralleltest // one at a time, as the comment at the top of this file says
|
||||
func TestZoneThatFailsOrRefusesGivesNoVerdictAndIsLeftAloneForAMinute(
|
||||
@@ -860,28 +821,3 @@ func wantAsked(t *testing.T, resolver *resolverStandIn, want ...string) {
|
||||
t.Errorf("asked about %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaskZoneKeyMasksTheFirstLabelOfAZoneUnderDqSpamhausNet(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
dronebl = "dnsbl.dronebl.org"
|
||||
spamhaus = "abcdefghijklmnopqrstuvwxyz.xbl.dq.spamhaus.net"
|
||||
spamhausMasked = "********.xbl.dq.spamhaus.net"
|
||||
)
|
||||
|
||||
for zone, want := range map[string]string{
|
||||
spamhaus: spamhausMasked,
|
||||
spamhaus + ".": spamhausMasked + ".",
|
||||
"KEY.ZEN.DQ.SPAMHAUS.NET": "********.ZEN.DQ.SPAMHAUS.NET",
|
||||
dronebl: dronebl,
|
||||
"dq.spamhaus.net": "dq.spamhaus.net",
|
||||
spamhaus + ".example": spamhaus + ".example",
|
||||
} {
|
||||
if got := reputation.MaskZoneKey(zone); got != want {
|
||||
t.Errorf("MaskZoneKey(%q) is %q, want %q", zone, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,8 @@
|
||||
// SWW_WAF_DNSBL_ZONES about clients, and keeps their verdicts, and checks
|
||||
// clients with AbuseIPDB, and keeps their scores and the checks spent
|
||||
// today. The state package writes all of these to files and reads them
|
||||
// from there, so that a restart keeps them too. It fetches AbuseIPDB's
|
||||
// blacklist, which it does not keep. Last, it reads the netblocks, AS
|
||||
// numbers and percentages that both the settings and the lists hold, and
|
||||
// masks the keys of DNSBL zones.
|
||||
// from there, so that a restart keeps them too. Last, it fetches
|
||||
// AbuseIPDB's blacklist, which it does not keep.
|
||||
package reputation
|
||||
|
||||
import (
|
||||
@@ -22,12 +20,12 @@ import (
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -42,28 +40,15 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
errStatus = errors.New("the server answered")
|
||||
errTooLong = errors.New("the list is longer than 16 MiB")
|
||||
errNotNetblockLine = errors.New(
|
||||
errStatus = errors.New("the server answered")
|
||||
errTooLong = errors.New("the list is longer than 16 MiB")
|
||||
errNotNetblock = errors.New(
|
||||
"is not an address or a netblock, such as 192.0.2.0/24",
|
||||
)
|
||||
errNotASNPercent = errors.New(
|
||||
"is not an AS number, : and a percentage, such as AS64496:50")
|
||||
errNotNetblock = errors.New(
|
||||
"is not a netblock such as 10.0.0.0/8, or an address")
|
||||
errNotASN = errors.New("is not an AS number such as AS64496")
|
||||
errNotPercent = errors.New(
|
||||
"is not a percentage, a whole number from 0 to 100",
|
||||
)
|
||||
)
|
||||
|
||||
// TagList is an address list of SWW_WAF_TAG_LISTS: the tag it adds to the
|
||||
// requests of the clients it holds, and the URL it is fetched from.
|
||||
type TagList struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
// List is a list as lists.json holds it: the URL it is fetched from,
|
||||
// when it was last tried, the fetch failed or not, and its last good copy:
|
||||
// when that was fetched, and its lines, as fetched, comment lines
|
||||
@@ -83,7 +68,7 @@ type Params struct {
|
||||
BlocklistURLs []string
|
||||
ASNLimitPercentURL string
|
||||
// TagLists are the address lists that add a tag (SWW_WAF_TAG_LISTS).
|
||||
TagLists []TagList
|
||||
TagLists []config.TagList
|
||||
// Refresh is how long after a list was last fetched or tried it is
|
||||
// fetched again (SWW_WAF_BLOCKLIST_REFRESH).
|
||||
Refresh time.Duration
|
||||
@@ -480,11 +465,7 @@ func parseNetblocks(lines []string) (entries, error) {
|
||||
|
||||
netblock, ok := parseNetblock(text)
|
||||
if !ok {
|
||||
return entries{}, fmt.Errorf(
|
||||
"line %d %w",
|
||||
i+1,
|
||||
errNotNetblockLine,
|
||||
)
|
||||
return entries{}, fmt.Errorf("line %d %w", i+1, errNotNetblock)
|
||||
}
|
||||
|
||||
found.netblocks[netblock] = true
|
||||
@@ -504,7 +485,7 @@ func parseNetblocks(lines []string) (entries, error) {
|
||||
// stands for, 192.0.2.0/24, and a mapped netblock shorter than /96, which
|
||||
// stands for none, is refused.
|
||||
func parseNetblock(text string) (netip.Prefix, bool) {
|
||||
netblock, err := ParseNetblock(text)
|
||||
netblock, err := config.ParseNetblock(text)
|
||||
if err != nil {
|
||||
return netip.Prefix{}, false
|
||||
}
|
||||
@@ -539,9 +520,9 @@ func parsePercents(lines []string) (entries, error) {
|
||||
}
|
||||
|
||||
asnText, percentText, _ := strings.Cut(text, ":")
|
||||
asn, asnErr := ParseASN(asnText)
|
||||
asn, asnErr := config.ParseASN(asnText)
|
||||
|
||||
percent, percentErr := ParsePercent(percentText)
|
||||
percent, percentErr := config.ParsePercent(percentText)
|
||||
if asnErr != nil || percentErr != nil {
|
||||
return entries{}, fmt.Errorf("line %d %w", i+1, errNotASNPercent)
|
||||
}
|
||||
@@ -555,53 +536,6 @@ func parsePercents(lines []string) (entries, error) {
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// ParseNetblock reads a netblock in CIDR form, such as 10.0.0.0/8. A bare
|
||||
// address is a netblock of that address alone, a /32 or a /128. A
|
||||
// blocklist's lines are read with it too.
|
||||
func ParseNetblock(value string) (netip.Prefix, error) {
|
||||
if strings.Contains(value, "/") {
|
||||
netblock, err := netip.ParsePrefix(value)
|
||||
if err != nil {
|
||||
return netip.Prefix{}, fmt.Errorf("%q %w", value, errNotNetblock)
|
||||
}
|
||||
|
||||
return netblock.Masked(), nil
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(value)
|
||||
if err != nil || addr.Zone() != "" {
|
||||
return netip.Prefix{}, fmt.Errorf("%q %w", value, errNotNetblock)
|
||||
}
|
||||
|
||||
return netip.PrefixFrom(addr, addr.BitLen()), nil
|
||||
}
|
||||
|
||||
// ParseASN reads an AS number such as AS64496, in either case, and
|
||||
// returns it as the lookup gives it: AS and the number, in capitals and
|
||||
// without leading zeros. The file SWW_WAF_ASN_LIMIT_PERCENT_URL names is
|
||||
// read with it too.
|
||||
func ParseASN(value string) (string, error) {
|
||||
digits, hasAS := strings.CutPrefix(strings.ToUpper(value), "AS")
|
||||
|
||||
number, err := strconv.ParseUint(digits, 10, 32)
|
||||
if !hasAS || err != nil {
|
||||
return "", fmt.Errorf("%q %w", value, errNotASN)
|
||||
}
|
||||
|
||||
return "AS" + strconv.FormatUint(number, 10), nil
|
||||
}
|
||||
|
||||
// ParsePercent reads a percentage, a whole number from 0 to 100. The file
|
||||
// SWW_WAF_ASN_LIMIT_PERCENT_URL names is read with it too.
|
||||
func ParsePercent(value string) (int64, error) {
|
||||
percent, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || percent < 0 || percent > 100 {
|
||||
return 0, fmt.Errorf("%q %w", value, errNotPercent)
|
||||
}
|
||||
|
||||
return percent, nil
|
||||
}
|
||||
|
||||
// withoutComment returns line without anything after a ; or a #, and
|
||||
// without the spaces around what is left.
|
||||
func withoutComment(line string) string {
|
||||
|
||||
@@ -99,12 +99,8 @@ type Client struct {
|
||||
// answers are by client. Each is added as it comes and never moved up,
|
||||
// so that the one that came longest ago is the first dropped.
|
||||
answers *simplelru.LRU[netip.Prefix, Answer]
|
||||
// asking are the clients whose query is under way, each with the
|
||||
// function that ends it. stopped is true once StopAsking has been
|
||||
// called, and queryGoroutines waits for the goroutine of each query.
|
||||
asking map[netip.Prefix]context.CancelFunc
|
||||
stopped bool
|
||||
queryGoroutines sync.WaitGroup
|
||||
// asking are the clients whose query is under way.
|
||||
asking map[netip.Prefix]bool
|
||||
// retryAt is when routewatch may be asked again after a query failed.
|
||||
retryAt time.Time
|
||||
}
|
||||
@@ -120,7 +116,7 @@ func New(params Params) *Client {
|
||||
params: params,
|
||||
httpClient: &http.Client{},
|
||||
answers: answers,
|
||||
asking: map[netip.Prefix]context.CancelFunc{},
|
||||
asking: map[netip.Prefix]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,9 +124,8 @@ func New(params Params) *Client {
|
||||
// IPv6 group, or why it has no route. It never waits for a query. A client
|
||||
// without an answer is asked about in the background, by addr, the address its
|
||||
// request came from, unless its query is under way, a query failed less than
|
||||
// failureKept ago, maxQueries are under way, or StopAsking has been called. ctx
|
||||
// is the context of the client's request, and a query goes on after the request
|
||||
// ends, until StopAsking.
|
||||
// failureKept ago, or maxQueries are under way. ctx is the context of the
|
||||
// client's request, and a query goes on after the request ends.
|
||||
func (c *Client) Route(
|
||||
ctx context.Context, client netip.Prefix, addr netip.Addr,
|
||||
) (Route, Missing) {
|
||||
@@ -152,38 +147,15 @@ func (c *Client) Route(
|
||||
return Route{}, RequestFailed
|
||||
}
|
||||
|
||||
_, asking := c.asking[client]
|
||||
if !asking && !c.stopped && len(c.asking) < maxQueries {
|
||||
queryCtx, end := context.WithCancel(context.WithoutCancel(ctx))
|
||||
c.asking[client] = end
|
||||
if !c.asking[client] && len(c.asking) < maxQueries {
|
||||
c.asking[client] = true
|
||||
|
||||
c.queryGoroutines.Go(func() {
|
||||
defer end()
|
||||
|
||||
c.ask(queryCtx, client, addr)
|
||||
})
|
||||
go c.ask(context.WithoutCancel(ctx), client, addr)
|
||||
}
|
||||
|
||||
return Route{}, NoAnswerYet
|
||||
}
|
||||
|
||||
// StopAsking ends the queries under way, and returns once their goroutines
|
||||
// have. A query it ends gives no answer and is no failure: it is not logged,
|
||||
// and routewatch is not left alone after it. After StopAsking, Route asks
|
||||
// routewatch nothing.
|
||||
func (c *Client) StopAsking() {
|
||||
c.mu.Lock()
|
||||
|
||||
c.stopped = true
|
||||
for _, end := range c.asking {
|
||||
end()
|
||||
}
|
||||
|
||||
c.mu.Unlock()
|
||||
|
||||
c.queryGoroutines.Wait()
|
||||
}
|
||||
|
||||
// Snapshot returns every answer still in use, sorted by client, as
|
||||
// routewatch.json lists them.
|
||||
func (c *Client) Snapshot() []Answer {
|
||||
@@ -233,8 +205,7 @@ func (c *Client) Load(answers []Answer) {
|
||||
// ask asks routewatch about addr, keeps the answer as client's, and notes the
|
||||
// query as no longer under way. A query that fails gives no answer, and
|
||||
// routewatch is not asked again for failureKept. Only the first failure of
|
||||
// those under way is logged. A query ended as ctx ends, by StopAsking, is no
|
||||
// failure.
|
||||
// those under way is logged.
|
||||
func (c *Client) ask(
|
||||
ctx context.Context,
|
||||
client netip.Prefix,
|
||||
@@ -242,20 +213,18 @@ func (c *Client) ask(
|
||||
) {
|
||||
route, err := c.query(ctx, addr)
|
||||
now := c.params.Now()
|
||||
isFailure := err != nil && ctx.Err() == nil
|
||||
|
||||
c.mu.Lock()
|
||||
|
||||
delete(c.asking, client)
|
||||
|
||||
firstFailure := isFailure && !now.Before(c.retryAt)
|
||||
firstFailure := err != nil && !now.Before(c.retryAt)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if err == nil {
|
||||
c.answers.Add(client, Answer{
|
||||
Client: client, Netblock: route.Netblock, ASN: route.ASN, Answered: now,
|
||||
})
|
||||
case isFailure:
|
||||
} else {
|
||||
c.retryAt = now.Add(failureKept)
|
||||
}
|
||||
|
||||
|
||||
@@ -361,54 +361,6 @@ func TestHangingRoutewatchNeverDelaysAndFailsTheQuery(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestStopAskingEndsTheQueryUnderWayAsNoFailureAndAsksNoMore(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
// In a synctest bubble, as TestHangingRoutewatchNeverDelaysAndFailsTheQuery
|
||||
// says.
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := &fixture{t: t, log: &syncBuffer{}}
|
||||
f.client = routewatch.New(routewatch.Params{
|
||||
URL: silentURL, Now: time.Now,
|
||||
ProcessLog: slog.New(slog.NewTextHandler(f.log, nil)),
|
||||
})
|
||||
|
||||
f.route()
|
||||
synctest.Wait()
|
||||
|
||||
// The query is ended, not waited out.
|
||||
began := time.Now()
|
||||
|
||||
f.client.StopAsking()
|
||||
|
||||
if waited := time.Since(began); waited != 0 {
|
||||
t.Errorf("StopAsking returned after %s, want at once", waited)
|
||||
}
|
||||
|
||||
// A query started now would fail within waitLimit. None is, and the
|
||||
// one ended is no failure: nothing is logged, and routewatch is not
|
||||
// left alone.
|
||||
for range 2 {
|
||||
if _, missing := f.route(); missing != routewatch.NoAnswerYet {
|
||||
t.Errorf(
|
||||
"Route gave %q, want %q",
|
||||
missing,
|
||||
routewatch.NoAnswerYet,
|
||||
)
|
||||
}
|
||||
|
||||
time.Sleep(waitLimit)
|
||||
synctest.Wait()
|
||||
}
|
||||
|
||||
if f.log.String() != "" {
|
||||
t.Errorf("process log %q, want nothing", f.log.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRepeatedRequestsMakeOneQueryAndTheAnswerExpires(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -21,9 +21,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"golang.org/x/net/http/httpguts"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
)
|
||||
|
||||
// The actions a rule takes when it matches.
|
||||
@@ -378,7 +378,7 @@ func parse(line string) (Rule, bool, error) {
|
||||
rule.Target,
|
||||
errNotTarget,
|
||||
)
|
||||
case isHeader && !httpguts.ValidHeaderFieldName(headerName):
|
||||
case isHeader && !config.IsHeaderName(headerName):
|
||||
return Rule{}, false, fmt.Errorf(
|
||||
"the target %q %w",
|
||||
rule.Target,
|
||||
|
||||
+12
-36
@@ -118,8 +118,7 @@ func RunWAF(ctx context.Context, params Params) int {
|
||||
"settings", cfg)
|
||||
|
||||
// The last write follows the stop of every hook, and so the end of every
|
||||
// loop that changes the state or raises an alert, and of every ask of
|
||||
// GeoJS, the DNSBL zones, AbuseIPDB and routewatch. A hook of the state
|
||||
// loop that changes the state or raises an alert. A hook of the state
|
||||
// files would stop before the loops of the parts built ahead of them.
|
||||
return run(ctx, app, failed, processLog, func() error {
|
||||
err := files.WriteAll()
|
||||
@@ -298,13 +297,11 @@ func newLists(
|
||||
return lists
|
||||
}
|
||||
|
||||
// newDNSBL returns what asks the DNSBL zones, none asked yet. At the stop it
|
||||
// ends the queries under way, as reputation.DNSBL.StopAsking says.
|
||||
// newDNSBL returns what asks the DNSBL zones, none asked yet.
|
||||
func newDNSBL(
|
||||
lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger,
|
||||
alertQueue *alerts.Queue,
|
||||
cfg *config.WAF, processLog *slog.Logger, alertQueue *alerts.Queue,
|
||||
) *reputation.DNSBL {
|
||||
dnsbl := reputation.NewDNSBL(reputation.DNSBLParams{
|
||||
return reputation.NewDNSBL(reputation.DNSBLParams{
|
||||
Zones: cfg.DNSBLZones,
|
||||
Resolver: cfg.DNSBLResolver,
|
||||
CacheTTL: cfg.IPReputationCacheTTL,
|
||||
@@ -313,17 +310,12 @@ func newDNSBL(
|
||||
ProcessLog: processLog,
|
||||
Alerts: alertQueue,
|
||||
})
|
||||
|
||||
lc.Append(fx.StopHook(dnsbl.StopAsking))
|
||||
|
||||
return dnsbl
|
||||
}
|
||||
|
||||
// newAbuseIPDB returns what checks clients with AbuseIPDB while
|
||||
// SWW_WAF_ABUSEIPDB_KEY is set, none checked yet. Until waf stops, it
|
||||
// fetches AbuseIPDB's blacklist as it is due, and bans the clients on it in
|
||||
// ledger, as waf.BanAbuseIPDBBlacklist says. At the stop it ends the checks
|
||||
// under way, as reputation.AbuseIPDB.StopChecking says.
|
||||
// ledger, as waf.BanAbuseIPDBBlacklist says.
|
||||
func newAbuseIPDB(
|
||||
lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger,
|
||||
alertQueue *alerts.Queue, ledger *bans.Ledger,
|
||||
@@ -349,30 +341,24 @@ func newAbuseIPDB(
|
||||
})
|
||||
|
||||
lc.Append(background(abuseIPDB.RunBlacklist))
|
||||
lc.Append(fx.StopHook(abuseIPDB.StopChecking))
|
||||
|
||||
return abuseIPDB
|
||||
}
|
||||
|
||||
// newRouteWatch returns what asks routewatch about clients, or nil while
|
||||
// SWW_WAF_ROUTEWATCH_URL is unset. At the stop it ends the queries under
|
||||
// way, as routewatch.Client.StopAsking says.
|
||||
// SWW_WAF_ROUTEWATCH_URL is unset.
|
||||
func newRouteWatch(
|
||||
lc fx.Lifecycle, cfg *config.WAF, processLog *slog.Logger,
|
||||
cfg *config.WAF, processLog *slog.Logger,
|
||||
) *routewatch.Client {
|
||||
if cfg.RouteWatchURL == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
routeWatch := routewatch.New(routewatch.Params{
|
||||
return routewatch.New(routewatch.Params{
|
||||
URL: cfg.RouteWatchURL,
|
||||
Now: utcNow,
|
||||
ProcessLog: processLog,
|
||||
})
|
||||
|
||||
lc.Append(fx.StopHook(routeWatch.StopAsking))
|
||||
|
||||
return routeWatch
|
||||
}
|
||||
|
||||
// newMetrics returns the metrics, with those read from the other parts as
|
||||
@@ -410,18 +396,12 @@ func newMetrics(
|
||||
|
||||
// newGeoJS returns what looks clients up at GeoJS, none looked up yet. Each
|
||||
// answer goes to the limiter and the ledger, as waf.AddLookup says, and each
|
||||
// failure is handled as waf.GeoJSFailed says. At the stop it ends the request
|
||||
// under way, as geojs.GeoJS.StopAsking says.
|
||||
// failure is handled as waf.GeoJSFailed says.
|
||||
func newGeoJS(
|
||||
lc fx.Lifecycle,
|
||||
cfg *config.WAF,
|
||||
m *metrics.Metrics,
|
||||
limiter *ratelimit.Limiter,
|
||||
ledger *bans.Ledger,
|
||||
alertQueue *alerts.Queue,
|
||||
processLog *slog.Logger,
|
||||
cfg *config.WAF, m *metrics.Metrics, limiter *ratelimit.Limiter,
|
||||
ledger *bans.Ledger, alertQueue *alerts.Queue, processLog *slog.Logger,
|
||||
) *geojs.GeoJS {
|
||||
geoJS := geojs.New(geojs.Params{
|
||||
return geojs.New(geojs.Params{
|
||||
URL: geojs.URL,
|
||||
Answered: func(answer geojs.Answer) {
|
||||
waf.AddLookup(cfg, limiter, ledger, answer)
|
||||
@@ -433,10 +413,6 @@ func newGeoJS(
|
||||
},
|
||||
WentWithoutAnswer: m.RequestsWithoutGeoJSAnswer.Inc,
|
||||
})
|
||||
|
||||
lc.Append(fx.StopHook(geoJS.StopAsking))
|
||||
|
||||
return geoJS
|
||||
}
|
||||
|
||||
// newWAFServer returns the server waf runs, with its parts and the time
|
||||
|
||||
@@ -548,6 +548,10 @@ func (s *sender) requestWithHeader(
|
||||
// body is sent as it is after the headers, header holding its
|
||||
// Content-Length or Transfer-Encoding. header may hold several lines,
|
||||
// separated by "\r\n". It returns the whole answer.
|
||||
//
|
||||
// It waits for the answer as long as it takes, since a busy host can slow
|
||||
// the Core Rule Set past any shorter wait. go test's -timeout ends a test
|
||||
// whose answer never comes.
|
||||
func (s *sender) requestWithBody(
|
||||
method, from, path, header, body string, status int, action string,
|
||||
) (logLine, answer) {
|
||||
@@ -566,11 +570,6 @@ func (s *sender) requestWithBody(
|
||||
send(s.t, conn, method+" "+path+" HTTP/1.1\r\nHost: "+appHost+"\r\n"+
|
||||
forwardedFor+": "+from+"\r\n"+header+"\r\n"+body)
|
||||
|
||||
err := conn.SetReadDeadline(time.Now().Add(waitLimit))
|
||||
if err != nil {
|
||||
s.t.Fatalf("set read deadline: %v", err)
|
||||
}
|
||||
|
||||
var got answer
|
||||
|
||||
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
|
||||
@@ -53,13 +53,13 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
if country == "" && !rq.skippedLookupWait {
|
||||
unknown = percentage{
|
||||
cfg.UnknownCountryLimitPercent,
|
||||
config.UnknownCountryLimitPercentSetting,
|
||||
"SWW_WAF_UNKNOWN_COUNTRY_LIMIT_PERCENT",
|
||||
}
|
||||
}
|
||||
|
||||
fetched := percentage{percent: whole}
|
||||
if percent, listed := rq.h.lists.ASNLimitPercent(asn); listed {
|
||||
fetched = percentage{percent, config.ASNLimitPercentURLSetting}
|
||||
fetched = percentage{percent, "SWW_WAF_ASN_LIMIT_PERCENT_URL"}
|
||||
}
|
||||
|
||||
blocklisted := percentage{percent: whole}
|
||||
@@ -67,7 +67,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
cfg.BlocklistAction == config.ReputationActionLimit {
|
||||
blocklisted = percentage{
|
||||
cfg.BlocklistLimitPercent,
|
||||
config.BlocklistActionSetting,
|
||||
"SWW_WAF_BLOCKLIST_ACTION",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,11 +76,11 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
cfg.DNSBLAbuseIPDBAction == config.ReputationActionLimit {
|
||||
dnsblAbuseIPDBListed = percentage{
|
||||
cfg.DNSBLAbuseIPDBLimitPercent,
|
||||
config.DNSBLAbuseIPDBActionSetting,
|
||||
"SWW_WAF_DNSBL_ABUSEIPDB_ACTION",
|
||||
}
|
||||
}
|
||||
|
||||
const tagSetting = config.TagLimitPercentSetting
|
||||
const tagSetting = "SWW_WAF_TAG_LIMIT_PERCENT"
|
||||
|
||||
asnRequests := lowest(
|
||||
given(cfg.TagLimitPercent, asnTag(asn), tagSetting),
|
||||
@@ -108,7 +108,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
asnBytes = given(
|
||||
cfg.ASNBytesLimitPercent,
|
||||
asn,
|
||||
config.ASNBytesLimitPercentSetting,
|
||||
"SWW_WAF_ASN_BYTES_LIMIT_PERCENT",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ func (rq *request) limitPercentages() (percentage, percentage) {
|
||||
countryBytes = given(
|
||||
cfg.CountryBytesLimitPercent,
|
||||
country,
|
||||
config.CountryBytesLimitPercentSetting,
|
||||
"SWW_WAF_COUNTRY_BYTES_LIMIT_PERCENT",
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"sneak.berlin/go/smallwebwaf/internal/config"
|
||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||
)
|
||||
|
||||
@@ -34,8 +33,7 @@ func (countries) check(
|
||||
return &verdict{
|
||||
action: requestlog.ActionCountryDenied,
|
||||
figures: map[string]any{
|
||||
"country": country,
|
||||
"setting": config.ExclusivelyAllowedCountriesSetting,
|
||||
"country": country, "setting": "SWW_WAF_EXCLUSIVELY_ALLOWED_COUNTRIES",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -193,11 +193,11 @@ func (o *output) requestLine(t *testing.T) logLine {
|
||||
// endedLines waits for count requests that went through rproxy, or to waf's
|
||||
// own endpoints, to have ended, and returns the last log line of each, in the
|
||||
// order waf took them. A question's last line is the one its report writes.
|
||||
// It waits as long as it takes, as requestWithBody does.
|
||||
func (o *output) endedLines(t *testing.T, count int) []logLine {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(waitLimit)
|
||||
for time.Now().Before(deadline) {
|
||||
for {
|
||||
found := o.lastLines(t)
|
||||
|
||||
ended := len(found) >= count
|
||||
@@ -213,10 +213,6 @@ func (o *output) endedLines(t *testing.T, count int) []logLine {
|
||||
|
||||
time.Sleep(pollInterval)
|
||||
}
|
||||
|
||||
t.Fatalf("fewer than %d requests have ended after %s", count, waitLimit)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// lastLines returns the last request log line written so far of each request,
|
||||
|
||||
Reference in new issue
Block a user