Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a2d57dca2 | ||
|
|
fdabf4974b | ||
|
|
a9dc59546b | ||
|
|
2ac2b671f6 | ||
|
|
f408f42b28 | ||
|
|
acceecc7f8 |
@@ -8,8 +8,7 @@ scanners and other abusers before they reach the app.
|
|||||||
A web application firewall reads each request on its way to a web app and
|
A web application firewall reads each request on its way to a web app and
|
||||||
refuses the ones that look like abuse. `smallwebwaf` is also a reverse proxy: it
|
refuses the ones that look like abuse. `smallwebwaf` is also a reverse proxy: it
|
||||||
accepts requests on the app's behalf, passes them to the app, and passes the
|
accepts requests on the app's behalf, passes them to the app, and passes the
|
||||||
app's answers back. A request it does not refuse reaches the app as it came,
|
app's answers back.
|
||||||
apart from a few headers (see "Design" below).
|
|
||||||
|
|
||||||
It needs no setting. Every setting has a default chosen for a service on the
|
It needs no setting. Every setting has a default chosen for a service on the
|
||||||
open internet. [`SPEC.md`](SPEC.md) says how `smallwebwaf` behaves and why. The
|
open internet. [`SPEC.md`](SPEC.md) says how `smallwebwaf` behaves and why. The
|
||||||
@@ -18,10 +17,10 @@ reference documents under [`docs/`](docs/) are listed under "Documents" below.
|
|||||||
## What it protects against
|
## What it protects against
|
||||||
|
|
||||||
- Scrapers that fetch every page of a site, all day. Rate limiting gives each
|
- Scrapers that fetch every page of a site, all day. Rate limiting gives each
|
||||||
client 1000 requests a minute, 10,000 an hour and 50,000 a day. Byte limits
|
client 6000 requests a minute, 100,000 an hour and 1,000,000 a day. Byte
|
||||||
give it 10 GiB a minute, 20 GiB an hour and 50 GiB a day. A client over a
|
limits give it 4 GiB a minute, 20 GiB an hour and 200 GiB a day. A client over
|
||||||
limit is refused and banned. The first ban lasts an hour. Each repeat within a
|
a limit is refused and banned. The first ban lasts an hour. Each repeat within
|
||||||
day makes the next ban three times as long. A ban that would last more than
|
a day makes the next ban three times as long. A ban that would last more than
|
||||||
seven days is permanent.
|
seven days is permanent.
|
||||||
- Scanners that probe for secrets, such as `/.env` or `/.git/config`. The
|
- Scanners that probe for secrets, such as `/.env` or `/.git/config`. The
|
||||||
default rule file bans such a client for seven days at its first probe. Its
|
default rule file bans such a client for seven days at its first probe. Its
|
||||||
@@ -30,8 +29,8 @@ reference documents under [`docs/`](docs/) are listed under "Documents" below.
|
|||||||
of your own, or an entry in `SWWAF_TRAP_PATHS`, bans those the same way.
|
of your own, or an entry in `SWWAF_TRAP_PATHS`, bans those the same way.
|
||||||
- Attacks carried in a request's URL or headers, such as SQL injection and path
|
- Attacks carried in a request's URL or headers, such as SQL injection and path
|
||||||
traversal. The OWASP Core Rule Set is a published set of rules that recognise
|
traversal. The OWASP Core Rule Set is a published set of rules that recognise
|
||||||
common web attacks. Coraza, a Go engine, runs those rules (step 11 under "What
|
common web attacks. Coraza, a Go engine, runs those rules (see "Attack
|
||||||
happens to a request" below). A request the rules take for an attack is
|
detection" in [`SPEC.md`](SPEC.md)). A request the rules take for an attack is
|
||||||
refused.
|
refused.
|
||||||
- Abuse from networks and countries you do not want. You can:
|
- Abuse from networks and countries you do not want. You can:
|
||||||
- refuse whole netblocks and countries;
|
- refuse whole netblocks and countries;
|
||||||
@@ -142,89 +141,32 @@ while working on it, see "Entrypoints" below.
|
|||||||
|
|
||||||
## What happens to a request
|
## What happens to a request
|
||||||
|
|
||||||
Two terms recur below. A clear sign of attack is a request that matches a rule
|
`smallwebwaf` handles each request in fifteen steps, in this order. Once a step
|
||||||
whose action is `ban`, or asks for a trap path (steps 9 and 10). An offence is a
|
refuses a request, the steps after it are skipped, apart from step 15, and
|
||||||
request that counts against its client in its history. It is one of:
|
nothing of the request reaches the app. "What happens to a request" in
|
||||||
|
[`SPEC.md`](SPEC.md) gives each step in full, under the same numbers.
|
||||||
|
|
||||||
- a clear sign of attack;
|
1. The health check, `GET /_smallwebwaf/healthz`, is answered at once.
|
||||||
- a broken limit;
|
2. The client is identified.
|
||||||
- a refusal by a rule, by the Core Rule Set or for a missing or wrong token.
|
3. The static lists, `SWWAF_ALLOW_NETS` and `SWWAF_DENY_NETS`.
|
||||||
|
4. The bans.
|
||||||
|
5. The lookup of the client's AS number and country.
|
||||||
|
6. The country lists.
|
||||||
|
7. The reputation sources.
|
||||||
|
8. The client's limit percentage.
|
||||||
|
9. The rate limits.
|
||||||
|
10. The trap paths.
|
||||||
|
11. The rule files.
|
||||||
|
12. The Core Rule Set.
|
||||||
|
13. `smallwebwaf`'s own endpoints, under `/_smallwebwaf/`.
|
||||||
|
14. The request is passed to the app.
|
||||||
|
15. After the answer: the byte limits, the error burst and the client's history.
|
||||||
|
|
||||||
`smallwebwaf` handles each request in this order. A request one step refuses
|
A refused visitor is answered with `SWWAF_BAN_RESPONSE`, `403` by default (see
|
||||||
skips the steps after it, apart from step 13. Nothing of a refused request
|
"Ban lengths, response and scope" in [`SPEC.md`](SPEC.md)). A `block` rule or a
|
||||||
reaches the app. "What happens to a request" in [`SPEC.md`](SPEC.md) gives each
|
Core Rule Set match answers `403`. A missing or wrong token gets `401`. A
|
||||||
step in full.
|
request over a size or time limit gets the status for that limit, such as `413`
|
||||||
|
for a body too large (see "Size and time limits" in [`SPEC.md`](SPEC.md)).
|
||||||
1. `GET /_smallwebwaf/healthz` is answered `200` with `ok` at once, before any
|
|
||||||
check and without asking the app.
|
|
||||||
2. The client is worked out. A netblock is a range of addresses, written as an
|
|
||||||
address and a prefix length: `203.0.113.0/24`. `SWWAF_TRUSTED_PROXIES` lists
|
|
||||||
the netblocks traefik comes from, by default the private address ranges. For
|
|
||||||
a TCP peer inside them, `X-Forwarded-For` is read from the right, and the
|
|
||||||
first address outside those netblocks is the client. A peer outside them is
|
|
||||||
the client itself. An IPv6 client is its group: the whole netblock around its
|
|
||||||
address, a /64 by default; `SWWAF_IPV6_GROUP_PREFIX` sets its length.
|
|
||||||
3. A client in `SWWAF_ALLOW_NETS` skips steps 4 to 11, the byte limits and the
|
|
||||||
error burst, but still needs a token at step 12. A client in
|
|
||||||
`SWWAF_DENY_NETS` is refused.
|
|
||||||
4. A client under a ban is refused. If the ban was made for a clear sign of
|
|
||||||
attack, this request makes it permanent.
|
|
||||||
5. The client's AS number and country are looked up, unless
|
|
||||||
`SWWAF_LOOKUP_SOURCE` is `off`. An AS number names the network an address
|
|
||||||
belongs to, such as `AS64496`.
|
|
||||||
6. The country lists are checked. A client from a country in
|
|
||||||
`SWWAF_DENIED_COUNTRIES` is refused. When
|
|
||||||
`SWWAF_EXCLUSIVELY_ALLOWED_COUNTRIES` is set, a client from any other country
|
|
||||||
is refused, and so is a client without a country. Such a refusal is not an
|
|
||||||
offence.
|
|
||||||
7. The reputation sources are checked: the blocklists, the CrowdSec decision
|
|
||||||
list, the DNS blocklists and AbuseIPDB. A client on the CrowdSec decision
|
|
||||||
list is banned until the decision ends. Any other source refuses the client,
|
|
||||||
lowers its limits or only notes it, as `SWWAF_BLOCKLIST_ACTION` and
|
|
||||||
`SWWAF_REPUTATION_ACTION` say. No request waits for a query.
|
|
||||||
8. Rate limiting counts the request, unless the client or the path is exempt. A
|
|
||||||
request that takes the client over a limit is refused and bans the client.
|
|
||||||
9. A request for a path in `SWWAF_TRAP_PATHS` is refused and bans the client, as
|
|
||||||
a clear sign of attack.
|
|
||||||
10. The rule files are checked. A `log` rule notes the match. A `block` rule
|
|
||||||
refuses the request. A `ban` rule refuses it and bans the client, as a clear
|
|
||||||
sign of attack.
|
|
||||||
11. The Core Rule Set inspects the request's method, URL and headers, and, once
|
|
||||||
`SWWAF_WAF_BODY_LIMIT` is set, form, JSON and XML bodies. A request it takes
|
|
||||||
for an attack is refused while `SWWAF_WAF_MODE` is `block`, the default, and
|
|
||||||
let through while it is `detect`. It bans no one by itself.
|
|
||||||
12. A request under `/_smallwebwaf/` is answered here by `smallwebwaf`, after
|
|
||||||
its token is checked. Any other request is passed to the app. The app's
|
|
||||||
answer is streamed back within the size and time limits.
|
|
||||||
13. Once the answer has ended, a request passed to the app has its bytes counted
|
|
||||||
for the byte limits. If a rule, a trap path, the Core Rule Set or a token
|
|
||||||
check refused the request, the refusal is counted for the error burst. The
|
|
||||||
client's history and the anomaly counters are updated. More than
|
|
||||||
`SWWAF_ERROR_BURST_THRESHOLD` refusals of one client in a minute ban it.
|
|
||||||
|
|
||||||
In `observe` mode (`SWWAF_MODE=observe`), `smallwebwaf` makes no ban of its own.
|
|
||||||
It refuses a request only for a size or time limit, or for a missing or wrong
|
|
||||||
token. A request it would otherwise have refused is passed to the app, and its
|
|
||||||
log line says what `enforce` mode would have done. Observe mode is for trying a
|
|
||||||
configuration before enforcing it.
|
|
||||||
|
|
||||||
What a refused visitor sees:
|
|
||||||
|
|
||||||
- `SWWAF_BAN_RESPONSE`, by default `403` with the plain text `Forbidden`. It can
|
|
||||||
be `429` instead, or `close`, which closes the connection, so that traefik
|
|
||||||
answers `502`. It answers:
|
|
||||||
- a ban or a broken rate limit;
|
|
||||||
- a `ban` rule or a trap path;
|
|
||||||
- `SWWAF_DENY_NETS` and the country lists;
|
|
||||||
- a reputation source whose action is `deny`.
|
|
||||||
- `403` for a `block` rule and the Core Rule Set.
|
|
||||||
- For a size or time limit:
|
|
||||||
- `431` for headers over their limit;
|
|
||||||
- `413` for a body over its limit;
|
|
||||||
- `408` for a client too slow to send its body;
|
|
||||||
- `502` or `504` when the app passes a limit or cannot be reached.
|
|
||||||
- `401` from an endpoint of `smallwebwaf`'s own, for a request without its
|
|
||||||
token.
|
|
||||||
|
|
||||||
## Settings you are likely to touch
|
## Settings you are likely to touch
|
||||||
|
|
||||||
@@ -233,8 +175,11 @@ Each setting is an environment variable of the app's container, such as
|
|||||||
[`docs/settings.md`](docs/settings.md) lists every setting, its default and the
|
[`docs/settings.md`](docs/settings.md) lists every setting, its default and the
|
||||||
values it takes. The ones most deployments touch:
|
values it takes. The ones most deployments touch:
|
||||||
|
|
||||||
- `SWWAF_MODE=observe`: log what would have been refused, refuse almost nothing,
|
- `SWWAF_MODE=observe`: `smallwebwaf` makes no ban of its own, and refuses a
|
||||||
ban no one. For trying a configuration.
|
request only for a size or time limit or a missing or wrong token. A request
|
||||||
|
it would have refused is passed to the app, and its log line says what
|
||||||
|
`enforce` mode would have done. For trying a configuration before enforcing
|
||||||
|
it.
|
||||||
- `SWWAF_ALLOW_NETS`: netblocks you trust, such as your monitoring. Their
|
- `SWWAF_ALLOW_NETS`: netblocks you trust, such as your monitoring. Their
|
||||||
clients are refused only for a size or time limit or a missing or wrong token.
|
clients are refused only for a size or time limit or a missing or wrong token.
|
||||||
- `SWWAF_RATE_LIMIT_EXEMPT_NETS`: netblocks exempt from rate limiting and the
|
- `SWWAF_RATE_LIMIT_EXEMPT_NETS`: netblocks exempt from rate limiting and the
|
||||||
@@ -376,54 +321,41 @@ nixpkgs fixed at one release. An app's `Dockerfile` installs a package with
|
|||||||
[`docs/image.md`](docs/image.md) lists what the image holds and how each part is
|
[`docs/image.md`](docs/image.md) lists what the image holds and how each part is
|
||||||
pinned.
|
pinned.
|
||||||
|
|
||||||
- The container's first process is `runsvinit`, which starts runit, a service
|
- runit, a service supervisor, runs `smallwebwaf` and the app side by side, each
|
||||||
supervisor. runit runs the `run` script of each directory under
|
as its own user, and starts either again when it exits. The app cannot touch
|
||||||
`/etc/service`, and runs it again a second after its program exits.
|
the state files or the process of `smallwebwaf`.
|
||||||
`smallwebwaf` runs as the `smallwebwaf` user (uid 65532) and the app as a user
|
- `smallwebwaf` listens on port 8080 and passes requests to the app on
|
||||||
of its own. So the app cannot touch the state files or the process of
|
`127.0.0.1:8081`. The app listens on `127.0.0.1` only, so nothing reaches it
|
||||||
`smallwebwaf`.
|
except through `smallwebwaf`. `smallwebwaf`'s own endpoints are under
|
||||||
- `smallwebwaf` listens on port 8080, on every address. traefik sends the app's
|
`/_smallwebwaf/`, on the same port.
|
||||||
requests there. `smallwebwaf` passes them to the app on `127.0.0.1:8081`. The
|
- The app sees the headers traefik sent, with traefik's address added to
|
||||||
app listens on `127.0.0.1` only, so nothing reaches it except through
|
`X-Forwarded-For`, from a TCP peer on `127.0.0.1`. So the app must trust
|
||||||
`smallwebwaf`. The health check, the metrics and the ban management are on the
|
`127.0.0.1` and `::1` for forwarded headers, besides the private address
|
||||||
same port, under `/_smallwebwaf/`. A request for that prefix never reaches the
|
ranges.
|
||||||
app.
|
- Both processes start with the container's environment variables, so every
|
||||||
- The app sees what it would see from traefik directly: the same `Host`, the
|
setting of `smallwebwaf` starts with `SWWAF_`, and the app can read a token
|
||||||
same `X-Forwarded-Proto`, and `X-Forwarded-For` with traefik's address added
|
given as one. A token given as a file that only the `smallwebwaf` user can
|
||||||
at the end. The app's TCP peer is `smallwebwaf` on `127.0.0.1`. So the app
|
read is out of its reach (see "Settings given as files" in
|
||||||
must trust `127.0.0.1` and `::1` for forwarded headers, besides the private
|
|
||||||
address ranges. An app that keeps its usual trusted proxies sees every visitor
|
|
||||||
as `127.0.0.1`. Each request also carries its id in `X-Request-ID`. Any
|
|
||||||
`X-Client-ASN` or `X-Client-Country` header a client sent is removed.
|
|
||||||
- Both processes start with the container's environment variables. That is why
|
|
||||||
every setting of `smallwebwaf` starts with `SWWAF_`. A token given as an
|
|
||||||
environment variable is readable by the app. A token given as a file that only
|
|
||||||
the `smallwebwaf` user can read is not (see "Settings given as files" in
|
|
||||||
[`docs/settings.md`](docs/settings.md)).
|
[`docs/settings.md`](docs/settings.md)).
|
||||||
- The state files live in `/var/lib/smallwebwaf`. Without a volume there, they
|
- The state files live in `/var/lib/smallwebwaf`. A volume mounted there keeps
|
||||||
survive a restart of the container and are lost when a deploy replaces it. The
|
them across a deploy.
|
||||||
`run` script gives that directory and every file in it to the `smallwebwaf`
|
- `smallwebwaf servewaf` runs the same checks for the sites that ask it about
|
||||||
user at each start, so a host directory mounted there needs no change of
|
each request, and passes nothing to an app (see "`servewaf`" in
|
||||||
owner.
|
[`SPEC.md`](SPEC.md)).
|
||||||
- The image's health check passes while `smallwebwaf` answers
|
- `docker stop` stops both processes at once. `smallwebwaf` gives the requests
|
||||||
`GET /_smallwebwaf/healthz` and the app accepts connections. traefik sends a
|
in progress five seconds to finish, so the app must keep answering for five
|
||||||
container no requests until it is healthy.
|
|
||||||
- When `smallwebwaf` or the app exits, runit starts it again a second later. The
|
|
||||||
other process keeps running. While either is down, the client gets `502`. A
|
|
||||||
`smallwebwaf` that stops at start, as on an invalid setting, is started again
|
|
||||||
every second until the cause is fixed, and logs its message each time.
|
|
||||||
- `docker stop` has runit send `SIGTERM` to both processes at once.
|
|
||||||
`smallwebwaf` gives the requests in progress five seconds to finish and writes
|
|
||||||
its state files. To let them finish, the app must keep answering for five
|
|
||||||
seconds after `SIGTERM`.
|
seconds after `SIGTERM`.
|
||||||
|
|
||||||
"Deployment" in [`SPEC.md`](SPEC.md) has the rest: moving `smallwebwaf` to
|
"Deployment" in [`SPEC.md`](SPEC.md) has the rest: the health check, what
|
||||||
another port, the health check's timing, and the forwarded headers.
|
happens when a process stops, moving `smallwebwaf` to another port, and the
|
||||||
"Architecture" in [`SPEC.md`](SPEC.md) lists the packages and what each does.
|
forwarded headers. "Architecture" in [`SPEC.md`](SPEC.md) lists the packages and
|
||||||
|
what each does.
|
||||||
|
|
||||||
## TODO
|
## TODO
|
||||||
|
|
||||||
- Planned, as "Planned, not built" in [`SPEC.md`](SPEC.md) describes:
|
- Planned, as "Planned, not built" in [`SPEC.md`](SPEC.md) describes:
|
||||||
|
- `smallwebwaf rproxy`, the reverse proxy in front of each app that asks
|
||||||
|
`smallwebwaf servewaf` about each request;
|
||||||
- sharing bans between the instances of several apps;
|
- sharing bans between the instances of several apps;
|
||||||
- sending the log over RELP.
|
- sending the log over RELP.
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
The endpoints under `/_smallwebwaf/`, what each takes and what each answers.
|
The endpoints under `/_smallwebwaf/`, what each takes and what each answers.
|
||||||
"Admin endpoints" in [`SPEC.md`](../SPEC.md) says which checks they go through
|
"Admin endpoints" in [`SPEC.md`](../SPEC.md) says which checks they go through
|
||||||
and how their tokens work.
|
and how their tokens work. `smallwebwaf servewaf` answers them at its own
|
||||||
|
address, without those checks (see "`servewaf`" in [`SPEC.md`](../SPEC.md)).
|
||||||
|
|
||||||
- `GET /_smallwebwaf/healthz`: `200` and `ok`, to anyone.
|
- `GET /_smallwebwaf/healthz`: `200` and `ok`, to anyone.
|
||||||
- `GET /_smallwebwaf/metrics`: the metrics, for `SWWAF_METRICS_TOKEN` (see
|
- `GET /_smallwebwaf/metrics`: the metrics, for `SWWAF_METRICS_TOKEN` (see
|
||||||
|
|||||||
+15
-9
@@ -42,7 +42,7 @@ on one line:
|
|||||||
"asn": "",
|
"asn": "",
|
||||||
"as_name": "",
|
"as_name": "",
|
||||||
"country": "",
|
"country": "",
|
||||||
"reason": "requests per minute over the limit of 1000",
|
"reason": "requests per minute over the limit of 6000",
|
||||||
"detail": {
|
"detail": {
|
||||||
"ban_expires": "2026-10-06T13:00:00.123Z",
|
"ban_expires": "2026-10-06T13:00:00.123Z",
|
||||||
"cause": "limit",
|
"cause": "limit",
|
||||||
@@ -51,9 +51,9 @@ on one line:
|
|||||||
"as_name": "",
|
"as_name": "",
|
||||||
"country": "",
|
"country": "",
|
||||||
"kind": "requests",
|
"kind": "requests",
|
||||||
"limit": 1000,
|
"limit": 6000,
|
||||||
"window": "minute",
|
"window": "minute",
|
||||||
"count": 1001,
|
"count": 6001,
|
||||||
"request": {
|
"request": {
|
||||||
"time": "2026-10-06T12:00:00.123456789Z",
|
"time": "2026-10-06T12:00:00.123456789Z",
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
@@ -62,7 +62,7 @@ on one line:
|
|||||||
"status": 403,
|
"status": 403,
|
||||||
"user_agent": "scraper/1.0"
|
"user_agent": "scraper/1.0"
|
||||||
},
|
},
|
||||||
"requests": 5210,
|
"requests": 8210,
|
||||||
"refused": 0,
|
"refused": 0,
|
||||||
"earlier_bans": {
|
"earlier_bans": {
|
||||||
"limit": 0,
|
"limit": 0,
|
||||||
@@ -78,17 +78,21 @@ on one line:
|
|||||||
|
|
||||||
- `instance`: `SWWAF_INSTANCE_NAME`. `time`: when the alert was raised. `event`:
|
- `instance`: `SWWAF_INSTANCE_NAME`. `time`: when the alert was raised. `event`:
|
||||||
one of the events above.
|
one of the events above.
|
||||||
|
- `host`: the site of the request that raised the alert. Only `servewaf` sends
|
||||||
|
this field, since it serves many sites, and not for `source_failure`,
|
||||||
|
`file_error` and `summary`.
|
||||||
- `client`: the address whose request raised the alert. Empty for
|
- `client`: the address whose request raised the alert. Empty for
|
||||||
`source_failure` and `file_error`.
|
`source_failure`, `file_error` and `summary`.
|
||||||
- `netblock`: empty for `source_failure` and `file_error`; otherwise one of:
|
- `netblock`: empty for `source_failure`, `file_error` and `summary`; otherwise
|
||||||
|
one of:
|
||||||
- the ban's netblock;
|
- the ban's netblock;
|
||||||
- the netblock an anomaly counted;
|
- the netblock an anomaly counted, empty in the `asn` and `total` scopes;
|
||||||
- for the other events, the client as rate limiting counts it: an IPv4
|
- for the other events, the client as rate limiting counts it: an IPv4
|
||||||
address as a /32, or an IPv6 group.
|
address as a /32, or an IPv6 group.
|
||||||
- `asn`, `as_name` and `country`: the client's, as known when the alert was
|
- `asn`, `as_name` and `country`: the client's, as known when the alert was
|
||||||
raised. They are empty when GeoJS had not answered yet.
|
raised. They are empty when GeoJS had not answered yet.
|
||||||
- `reason`: a short sentence, such as
|
- `reason`: a short sentence, such as
|
||||||
`requests per minute over the limit of 1000` or `listed by a blocklist`.
|
`requests per minute over the limit of 6000` or `listed by a blocklist`.
|
||||||
- `detail`: what is particular to the event:
|
- `detail`: what is particular to the event:
|
||||||
- for a ban, its `cause`, `ban_expires` and `notes` (the notes are listed
|
- for a ban, its `cause`, `ban_expires` and `notes` (the notes are listed
|
||||||
under `bans.json` in [`state-files.md`](state-files.md));
|
under `bans.json` in [`state-files.md`](state-files.md));
|
||||||
@@ -97,6 +101,8 @@ on one line:
|
|||||||
- for a Core Rule Set match, the `rule_ids`, `score`, `method` and `path`;
|
- for a Core Rule Set match, the `rule_ids`, `score`, `method` and `path`;
|
||||||
- for a source failure, the `source` and `error`;
|
- for a source failure, the `source` and `error`;
|
||||||
- for a file error, the `file` and `error`;
|
- for a file error, the `file` and `error`;
|
||||||
|
- for a summary, the `hour` it covers, the `count` of alerts held back, and
|
||||||
|
that count by event in `events`;
|
||||||
- `mode`, when the request was not refused: `detect` or `observe`.
|
- `mode`, when the request was not refused: `detect` or `observe`.
|
||||||
- `suppressed_repeats`: how many repeats the cooldown held back before this
|
- `suppressed_repeats`: how many repeats the cooldown held back before this
|
||||||
alert.
|
alert.
|
||||||
@@ -107,7 +113,7 @@ Slack and ntfy get a message with a title and a text. The title is the instance
|
|||||||
and the event, such as `fsn1app1/gitea: ban`. The text is the `reason`, then one
|
and the event, such as `fsn1app1/gitea: ban`. The text is the `reason`, then one
|
||||||
line for each of these that the alert has:
|
line for each of these that the alert has:
|
||||||
|
|
||||||
- the client, the netblock and the country;
|
- the host, the client, the netblock and the country;
|
||||||
- the file, the source, the error and the mode from `detail`;
|
- the file, the source, the error and the mode from `detail`;
|
||||||
- the suppressed repeats, if any.
|
- the suppressed repeats, if any.
|
||||||
|
|
||||||
|
|||||||
+11
-8
@@ -11,8 +11,10 @@ checked again when gitea or the Core Rule Set changes version.
|
|||||||
|
|
||||||
- SSH access to gitea does not pass through `smallwebwaf` and is not protected
|
- SSH access to gitea does not pass through `smallwebwaf` and is not protected
|
||||||
by it.
|
by it.
|
||||||
- A clone is a response. It fits the defaults of 30 minutes and 5 GiB for all
|
- A clone is a response. It fits the defaults of 30 minutes and 1 GiB unless the
|
||||||
but the largest repositories and slowest links.
|
repository is large or the link slow. A repository whose clone is larger than
|
||||||
|
1 GiB needs `SWWAF_RESPONSE_MAX_BYTES` raised, and the byte limits with it
|
||||||
|
("Byte limits, per client" in `SPEC.md`).
|
||||||
- A push is a request, and so is every other upload:
|
- A push is a request, and so is every other upload:
|
||||||
- a git push;
|
- a git push;
|
||||||
- an LFS object;
|
- an LFS object;
|
||||||
@@ -30,12 +32,13 @@ checked again when gitea or the Core Rule Set changes version.
|
|||||||
request limits do most of the work there.
|
request limits do most of the work there.
|
||||||
- An Actions runner that reaches gitea through `smallwebwaf` sends requests all
|
- An Actions runner that reaches gitea through `smallwebwaf` sends requests all
|
||||||
day. One older than version 0.4 (April 2026) asks for work every 2 seconds,
|
day. One older than version 0.4 (April 2026) asks for work every 2 seconds,
|
||||||
43,200 requests a day, and reports a running job's log and state every second.
|
43,200 requests a day. While it runs a job, it reports the job's log and state
|
||||||
So it passes the day limit of 50,000 after about an hour and a quarter of
|
every second instead, two requests a second. So one runner busy all day sends
|
||||||
jobs. It is then banned, the job it is running fails, and each repeat within a
|
172,800 requests, under the request limits. Six such runners on one address,
|
||||||
day makes the ban longer. Newer runners ask less often, but a busy one, or
|
each busy all day, pass the day limit of 1,000,000 within two days; five stay
|
||||||
several on one address, can still pass it. Put the runners' addresses in
|
under it. Their address is then banned, their running jobs fail, and each
|
||||||
`SWWAF_RATE_LIMIT_EXEMPT_NETS`.
|
repeat within a day makes the ban longer. Newer runners ask for work less
|
||||||
|
often. Put the runners' addresses in `SWWAF_RATE_LIMIT_EXEMPT_NETS`.
|
||||||
|
|
||||||
## What the Core Rule Set lets through
|
## What the Core Rule Set lets through
|
||||||
|
|
||||||
|
|||||||
+12
-3
@@ -1,8 +1,17 @@
|
|||||||
# The metrics
|
# The metrics
|
||||||
|
|
||||||
The metrics `GET /_smallwebwaf/metrics` answers with, as "Metrics endpoint" in
|
What `GET /_smallwebwaf/metrics` answers with. "Metrics endpoint" in
|
||||||
[`SPEC.md`](../SPEC.md) describes it. Prometheus keeps the `instance` label as
|
[`SPEC.md`](../SPEC.md) describes the endpoint. Prometheus keeps the `instance`
|
||||||
`exported_instance` unless the scrape sets `honor_labels: true`.
|
label as `exported_instance` unless the scrape sets `honor_labels: true`.
|
||||||
|
|
||||||
|
`smallwebwaf servewaf` counts a denied request at its decision. It counts an
|
||||||
|
allowed request when its report comes, with the status, bytes and times the
|
||||||
|
report gives. These are not counted:
|
||||||
|
|
||||||
|
- a report itself;
|
||||||
|
- an allowed request whose report never comes;
|
||||||
|
- a question refused with `400`;
|
||||||
|
- a question whose body stopped arriving.
|
||||||
|
|
||||||
## Traffic
|
## Traffic
|
||||||
|
|
||||||
|
|||||||
@@ -117,3 +117,65 @@ All in milliseconds:
|
|||||||
connection;
|
connection;
|
||||||
- `duration_upstream_first_byte`: until the first byte of the answer;
|
- `duration_upstream_first_byte`: until the first byte of the answer;
|
||||||
- `duration_upstream_total`: until the end of the answer.
|
- `duration_upstream_total`: until the end of the answer.
|
||||||
|
|
||||||
|
## `servewaf`'s lines
|
||||||
|
|
||||||
|
`smallwebwaf servewaf` writes two lines for each question it answers, joined by
|
||||||
|
`request_id`. The field `servewaf_line` says which of the two a line is:
|
||||||
|
|
||||||
|
- `decision`: the line it writes once it has answered the question;
|
||||||
|
- `report`: the line it writes when `rproxy`'s report comes, with everything
|
||||||
|
known. The repetition is intended.
|
||||||
|
|
||||||
|
A request to its own endpoints writes one line, without `servewaf_line`. A
|
||||||
|
report writes no line but the `report` line of the request it names.
|
||||||
|
|
||||||
|
These questions write no line:
|
||||||
|
|
||||||
|
- a question refused with `400` (see "The question" under "`servewaf`" in
|
||||||
|
[`SPEC.md`](../SPEC.md));
|
||||||
|
- a question whose body stopped arriving, which gets no answer.
|
||||||
|
|
||||||
|
### The `decision` line
|
||||||
|
|
||||||
|
It has the fields above, with these meanings where they differ:
|
||||||
|
|
||||||
|
- `client_ip`: `X-Smallwebwaf-Client`.
|
||||||
|
- `peer_ip`: `X-Smallwebwaf-Peer`.
|
||||||
|
- `host`: the site the visitor asked for.
|
||||||
|
- `protocol`: the question's own, `HTTP/1.1`.
|
||||||
|
- `content_length`: `X-Smallwebwaf-Content-Length`.
|
||||||
|
- `request_id`: the question's `X-Request-ID`.
|
||||||
|
- `status`: what `servewaf` answered: `200` for `allow`, the status of `deny`,
|
||||||
|
or `0` for `close`, as the visitor is then sent nothing.
|
||||||
|
- `request_bytes`: how much of the question's body the Core Rule Set read.
|
||||||
|
- `response_bytes`: the body of `servewaf`'s answer.
|
||||||
|
- `action`: `forward` for `allow`, and `admin` for the `404` for a path under
|
||||||
|
`/_smallwebwaf/`.
|
||||||
|
- `aborted`: true when `rproxy` went away before the answer.
|
||||||
|
- `duration_total`: from the question's headers being read to the line.
|
||||||
|
|
||||||
|
The line leaves out `upstream_status`, `websocket` and the
|
||||||
|
`duration_upstream_...` fields, since `servewaf` passes nothing to the app.
|
||||||
|
|
||||||
|
The bytes of an allowed request are counted when its report comes. So `counts`
|
||||||
|
holds the client's bytes without this request's.
|
||||||
|
|
||||||
|
### The `report` line
|
||||||
|
|
||||||
|
It has every field of the `decision` line, and `time` stays when the request
|
||||||
|
arrived. These fields say what the report says:
|
||||||
|
|
||||||
|
- `status`: what the visitor got, `0` if nothing;
|
||||||
|
- `request_bytes` and `response_bytes`: the body bytes each way, with what a
|
||||||
|
WebSocket carried each way;
|
||||||
|
- `duration_total`: from the request's headers being read by `rproxy` to the end
|
||||||
|
of the answer;
|
||||||
|
- `duration_upstream_total`: from the hand-over to the app to the end of the
|
||||||
|
answer, for an allowed request.
|
||||||
|
|
||||||
|
For an allowed request, the report's counting also changes these fields:
|
||||||
|
|
||||||
|
- `counts`: the byte totals now include this request's;
|
||||||
|
- `limit_hit`, `offence` and `ban_expires`: set when the report's bytes broke a
|
||||||
|
byte limit.
|
||||||
|
|||||||
+37
-14
@@ -4,6 +4,23 @@ Every setting, its default and the values it takes, in the groups of "Settings"
|
|||||||
in [`SPEC.md`](../SPEC.md). That section gives the conventions, the settings
|
in [`SPEC.md`](../SPEC.md). That section gives the conventions, the settings
|
||||||
that take `off`, the `_FILE` form, and what each group does and why.
|
that take `off`, the `_FILE` form, and what each group does and why.
|
||||||
|
|
||||||
|
## `servewaf`
|
||||||
|
|
||||||
|
`smallwebwaf servewaf` uses every setting here but these, which it ignores:
|
||||||
|
|
||||||
|
- `SWWAF_UPSTREAM_URL` and `SWWAF_TRUSTED_PROXIES`;
|
||||||
|
- the five timeouts under "Size and time limits";
|
||||||
|
- `SWWAF_CLIENT_REQUEST_HEADER_MAX_BYTES`, `SWWAF_REQUEST_MAX_BYTES` and
|
||||||
|
`SWWAF_RESPONSE_MAX_BYTES`.
|
||||||
|
|
||||||
|
An invalid value of one of these still stops the start, and the line of settings
|
||||||
|
at start still shows them.
|
||||||
|
|
||||||
|
`SWWAF_ADD_LOOKUP_HEADERS` puts the headers on the answer to `rproxy`, not on a
|
||||||
|
request to an app. `SWWAF_WAF_BODY_LIMIT` has an effect up to 64 KiB less one
|
||||||
|
byte, whatever its value. A question carries no more of a body than 64 KiB (see
|
||||||
|
"`servewaf`" in [`SPEC.md`](../SPEC.md)).
|
||||||
|
|
||||||
## Forms of values
|
## Forms of values
|
||||||
|
|
||||||
- A duration is Go's syntax, with `d` for days: `90s`, `15m`, `24h`, `7d`. Zero
|
- A duration is Go's syntax, with `d` for days: `90s`, `15m`, `24h`, `7d`. Zero
|
||||||
@@ -91,24 +108,24 @@ that take `off`, the `_FILE` form, and what each group does and why.
|
|||||||
## Static lists
|
## Static lists
|
||||||
|
|
||||||
- `SWWAF_ALLOW_NETS` (default empty): netblocks you trust, such as your
|
- `SWWAF_ALLOW_NETS` (default empty): netblocks you trust, such as your
|
||||||
monitoring. Their clients are refused only for a size or time limit or a
|
monitoring (see step 3 in [`SPEC.md`](../SPEC.md)).
|
||||||
missing or wrong token.
|
|
||||||
- `SWWAF_RATE_LIMIT_EXEMPT_NETS` (default empty): netblocks whose clients are
|
- `SWWAF_RATE_LIMIT_EXEMPT_NETS` (default empty): netblocks whose clients are
|
||||||
exempt from rate limiting and the byte limits.
|
exempt from rate limiting and the byte limits.
|
||||||
- `SWWAF_DENY_NETS` (default empty): netblocks whose clients are always refused.
|
- `SWWAF_DENY_NETS` (default empty): netblocks whose clients are refused (see
|
||||||
|
step 3 in [`SPEC.md`](../SPEC.md)).
|
||||||
|
|
||||||
## Request rate limits, per client
|
## Request rate limits, per client
|
||||||
|
|
||||||
- `SWWAF_RATE_LIMIT_PER_MINUTE` (default `1000`), `SWWAF_RATE_LIMIT_PER_HOUR`
|
- `SWWAF_RATE_LIMIT_PER_MINUTE` (default `6000`), `SWWAF_RATE_LIMIT_PER_HOUR`
|
||||||
(default `10000`) and `SWWAF_RATE_LIMIT_PER_DAY` (default `50000`): the most
|
(default `100000`) and `SWWAF_RATE_LIMIT_PER_DAY` (default `1000000`): the
|
||||||
requests a client may make in each window. A count or `off`.
|
most requests a client may make in each window. A count or `off`.
|
||||||
- `SWWAF_RATE_LIMIT_EXEMPT_PATHS` (default empty): path prefixes exempt from
|
- `SWWAF_RATE_LIMIT_EXEMPT_PATHS` (default empty): path prefixes exempt from
|
||||||
rate limiting and the byte limits, such as `/assets/`.
|
rate limiting and the byte limits, such as `/assets/`.
|
||||||
|
|
||||||
## Byte limits, per client
|
## Byte limits, per client
|
||||||
|
|
||||||
- `SWWAF_BYTES_LIMIT_PER_MINUTE` (default `10G`), `SWWAF_BYTES_LIMIT_PER_HOUR`
|
- `SWWAF_BYTES_LIMIT_PER_MINUTE` (default `4G`), `SWWAF_BYTES_LIMIT_PER_HOUR`
|
||||||
(default `20G`) and `SWWAF_BYTES_LIMIT_PER_DAY` (default `50G`): the most
|
(default `20G`) and `SWWAF_BYTES_LIMIT_PER_DAY` (default `200G`): the most
|
||||||
bytes counted for a client in each window. A size or `off`.
|
bytes counted for a client in each window. A size or `off`.
|
||||||
- `SWWAF_BYTES_COUNT` (default `both`): which body bytes the byte limits count:
|
- `SWWAF_BYTES_COUNT` (default `both`): which body bytes the byte limits count:
|
||||||
`response`, `request` or `both`.
|
`response`, `request` or `both`.
|
||||||
@@ -131,12 +148,18 @@ that take `off`, the `_FILE` form, and what each group does and why.
|
|||||||
to send its whole answer. A duration or `off`.
|
to send its whole answer. A duration or `off`.
|
||||||
- `SWWAF_REQUEST_MAX_BYTES` (default `100M`): the largest request body. A size
|
- `SWWAF_REQUEST_MAX_BYTES` (default `100M`): the largest request body. A size
|
||||||
or `off`.
|
or `off`.
|
||||||
- `SWWAF_RESPONSE_MAX_BYTES` (default `5G`): the largest response body. A size
|
- `SWWAF_RESPONSE_MAX_BYTES` (default `1G`): the largest response body. A size
|
||||||
or `off`.
|
or `off`.
|
||||||
|
|
||||||
## Lookup of AS number and country
|
## Lookup of AS number and country
|
||||||
|
|
||||||
- `SWWAF_LOOKUP_SOURCE` (default `geojs`): `geojs`, `file` or `off`.
|
- `SWWAF_LOOKUP_SOURCE` (default `geojs`): `geojs`, `file` or `off`. `off` stops
|
||||||
|
the start while a setting that needs a lookup is set:
|
||||||
|
- the two country lists;
|
||||||
|
- `SWWAF_ADD_LOOKUP_HEADERS`;
|
||||||
|
- the four biased threshold lists and `SWWAF_ASN_LIMIT_PERCENT_URL`;
|
||||||
|
- `SWWAF_UNKNOWN_LIMIT_PERCENT` below `100`;
|
||||||
|
- an anomaly threshold per AS number.
|
||||||
- `SWWAF_LOOKUP_DB_PATH` (default empty): the IPinfo Lite database file, in its
|
- `SWWAF_LOOKUP_DB_PATH` (default empty): the IPinfo Lite database file, in its
|
||||||
`.mmdb` form, for `SWWAF_LOOKUP_SOURCE=file`.
|
`.mmdb` form, for `SWWAF_LOOKUP_SOURCE=file`.
|
||||||
- `SWWAF_LOOKUP_TIMEOUT` (default `1s`): how long a request waits for its
|
- `SWWAF_LOOKUP_TIMEOUT` (default `1s`): how long a request waits for its
|
||||||
@@ -190,8 +213,7 @@ that take `off`, the `_FILE` form, and what each group does and why.
|
|||||||
- `SWWAF_WAF_BODY_LIMIT` (default `off`): `off`, or how much of a request body
|
- `SWWAF_WAF_BODY_LIMIT` (default `off`): `off`, or how much of a request body
|
||||||
the Core Rule Set reads, a size of at most `1G`.
|
the Core Rule Set reads, a size of at most `1G`.
|
||||||
- `SWWAF_ERROR_BURST_THRESHOLD` (default `30`): the most refusals of one client
|
- `SWWAF_ERROR_BURST_THRESHOLD` (default `30`): the most refusals of one client
|
||||||
in a minute for a rule match, a trap path, a Core Rule Set match or a failed
|
in a minute (see "Attack detection" in `SPEC.md`). A count or `off`.
|
||||||
token check. A count or `off`.
|
|
||||||
|
|
||||||
## Ban lengths, response and scope
|
## Ban lengths, response and scope
|
||||||
|
|
||||||
@@ -286,7 +308,7 @@ as `REQUESTS_PER_MINUTE`:
|
|||||||
client;
|
client;
|
||||||
- `SWWAF_ANOMALY_NET_V6_PREFIX` (default `48`, from 0 to 128) for an IPv6
|
- `SWWAF_ANOMALY_NET_V6_PREFIX` (default `48`, from 0 to 128) for an IPv6
|
||||||
client.
|
client.
|
||||||
- `SWWAF_ANOMALY_ASN_...`: per AS number. Needs a lookup source.
|
- `SWWAF_ANOMALY_ASN_...`: per AS number.
|
||||||
- `SWWAF_ANOMALY_TOTAL_...`: the whole service.
|
- `SWWAF_ANOMALY_TOTAL_...`: the whole service.
|
||||||
- `SWWAF_WATCH_...`: each netblock in `SWWAF_WATCH_NETS`, as a whole.
|
- `SWWAF_WATCH_...`: each netblock in `SWWAF_WATCH_NETS`, as a whole.
|
||||||
`SWWAF_WATCH_NETS` (default empty) is a list of name, `=` and netblock, such
|
`SWWAF_WATCH_NETS` (default empty) is a list of name, `=` and netblock, such
|
||||||
@@ -322,4 +344,5 @@ A few limits are fixed rather than settings:
|
|||||||
- at most 100,000 DNS blocklist verdicts and 100,000 AbuseIPDB scores are kept;
|
- at most 100,000 DNS blocklist verdicts and 100,000 AbuseIPDB scores are kept;
|
||||||
- at most 1,000 DNS blocklist queries are under way at once;
|
- at most 1,000 DNS blocklist queries are under way at once;
|
||||||
- at most 20,000 anomaly counters are kept;
|
- at most 20,000 anomaly counters are kept;
|
||||||
- each alert destination's queue holds at most 1,000 alerts.
|
- each alert destination's queue holds at most 1,000 alerts;
|
||||||
|
- `servewaf` holds at most 10,000 answered requests awaiting their reports.
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// Package alerts sends alerts on bans, on traffic over an anomaly
|
// Package alerts sends alerts on bans, on traffic over an anomaly
|
||||||
// threshold, on a source that fails and on a file with an error to each
|
// threshold, on a source that fails and on a file with an error to each
|
||||||
// destination set: to the webhook
|
// destination set: to the webhook
|
||||||
// SWWAF_ALERT_WEBHOOK_URL names, each as one JSON object, as the "Alert
|
// SWWAF_ALERT_WEBHOOK_URL names, each as one JSON object, as "The JSON
|
||||||
// webhook schema" section of SPEC.md describes, to the Slack incoming
|
// object" in docs/alerts.md describes, to the Slack incoming
|
||||||
// webhook SWWAF_ALERT_SLACK_WEBHOOK_URL names, as a message, and to the
|
// webhook SWWAF_ALERT_SLACK_WEBHOOK_URL names, as a message, and to the
|
||||||
// ntfy topic SWWAF_ALERT_NTFY_URL names. A repeat within
|
// ntfy topic SWWAF_ALERT_NTFY_URL names. A repeat within
|
||||||
// SWWAF_ALERT_COOLDOWN is held back, and so is an alert past
|
// SWWAF_ALERT_COOLDOWN is held back, and so is an alert past
|
||||||
@@ -149,15 +149,17 @@ type Params struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Alert is one alert, as the webhook is sent it and alerts.json holds it,
|
// Alert is one alert, as the webhook is sent it and alerts.json holds it,
|
||||||
// with the fields of the "Alert webhook schema" section of SPEC.md. ASN,
|
// with the fields of "The JSON object" in docs/alerts.md. ASN, ASName and
|
||||||
// ASName and Country are, for a ban, the client's as the ban's notes give
|
// Country are, for a ban, the client's as the ban's notes give them. Host is
|
||||||
// them.
|
// the site of the request that raised the alert, while one servewaf serves
|
||||||
|
// many sites, and "" otherwise.
|
||||||
//
|
//
|
||||||
//nolint:tagliatelle // SPEC.md's alert webhook schema names its fields in snake_case
|
//nolint:tagliatelle // docs/alerts.md names the alert's fields in snake_case
|
||||||
type Alert struct {
|
type Alert struct {
|
||||||
Instance string `json:"instance"`
|
Instance string `json:"instance"`
|
||||||
Time time.Time `json:"time"`
|
Time time.Time `json:"time"`
|
||||||
Event string `json:"event"`
|
Event string `json:"event"`
|
||||||
|
Host string `json:"host,omitempty"`
|
||||||
Client netip.Addr `json:"client"`
|
Client netip.Addr `json:"client"`
|
||||||
Netblock netip.Prefix `json:"netblock"`
|
Netblock netip.Prefix `json:"netblock"`
|
||||||
ASN string `json:"asn"`
|
ASN string `json:"asn"`
|
||||||
@@ -900,12 +902,16 @@ func title(alert *Alert) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// text returns the text of alert in Slack and ntfy: its reason, then a
|
// text returns the text of alert in Slack and ntfy: its reason, then a
|
||||||
// line for each of its client, netblock and country, the file, source,
|
// line for each of its host, client, netblock and country, the file,
|
||||||
// error and mode its detail gives, and its suppressed repeats, that it
|
// source, error and mode its detail gives, and its suppressed repeats, that
|
||||||
// has.
|
// it has.
|
||||||
func text(alert *Alert) string {
|
func text(alert *Alert) string {
|
||||||
lines := []string{alert.Reason}
|
lines := []string{alert.Reason}
|
||||||
|
|
||||||
|
if alert.Host != "" {
|
||||||
|
lines = append(lines, "host: "+alert.Host)
|
||||||
|
}
|
||||||
|
|
||||||
if alert.Client.IsValid() {
|
if alert.Client.IsValid() {
|
||||||
lines = append(lines, "client: "+alert.Client.String())
|
lines = append(lines, "client: "+alert.Client.String())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1284,9 +1284,11 @@ func anAlertForEachEvent() []eventMessage {
|
|||||||
Event: alerts.EventWAFBlock, Client: netip.MustParseAddr("192.0.2.1"),
|
Event: alerts.EventWAFBlock, Client: netip.MustParseAddr("192.0.2.1"),
|
||||||
Netblock: netip.MustParsePrefix("192.0.2.1/32"),
|
Netblock: netip.MustParsePrefix("192.0.2.1/32"),
|
||||||
Reason: "refused by the Core Rule Set",
|
Reason: "refused by the Core Rule Set",
|
||||||
|
Host: "app.example",
|
||||||
},
|
},
|
||||||
"fsn1app1/gitea: waf_block", "default shield",
|
"fsn1app1/gitea: waf_block", "default shield",
|
||||||
"refused by the Core Rule Set\nclient: 192.0.2.1\nnetblock: 192.0.2.1/32",
|
"refused by the Core Rule Set\nhost: app.example\nclient: 192.0.2.1\n" +
|
||||||
|
"netblock: 192.0.2.1/32",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
alerts.Alert{
|
alerts.Alert{
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// Package anomaly counts requests and bytes over a minute and an hour, per
|
// Package anomaly counts requests and bytes over a minute and an hour, per
|
||||||
// client, per surrounding netblock, per AS number, for the whole service
|
// client, per surrounding netblock, per AS number, for the whole service
|
||||||
// and per named netblock, and raises an anomaly alert for a count over its
|
// and per named netblock, and raises an anomaly alert for a count over its
|
||||||
// threshold, as "Anomaly thresholds" under "Configuration surface" in
|
// threshold, as "Anomaly thresholds" under "Settings" in SPEC.md
|
||||||
// SPEC.md describes. It refuses and bans nothing. At most 20,000 counters
|
// describes. It refuses and bans nothing. At most 20,000 counters
|
||||||
// are kept, in memory, and written to alerts.json and read from it by the
|
// are kept, in memory, and written to alerts.json and read from it by the
|
||||||
// state package.
|
// state package.
|
||||||
package anomaly
|
package anomaly
|
||||||
@@ -103,6 +103,8 @@ type Counter struct {
|
|||||||
|
|
||||||
// Request is a request that has ended, as the counters count it.
|
// Request is a request that has ended, as the counters count it.
|
||||||
type Request struct {
|
type Request struct {
|
||||||
|
// Host is the site the alert names, "" for none.
|
||||||
|
Host string
|
||||||
// Client is the client's address, and ClientGroup the client it is
|
// Client is the client's address, and ClientGroup the client it is
|
||||||
// counted as: its IPv4 address, or the IPv6 netblock of
|
// counted as: its IPv4 address, or the IPv6 netblock of
|
||||||
// SWWAF_IPV6_GROUP_PREFIX its address is in.
|
// SWWAF_IPV6_GROUP_PREFIX its address is in.
|
||||||
@@ -396,6 +398,7 @@ func alertFor(r Request, k key, o overThreshold) alerts.Alert {
|
|||||||
|
|
||||||
return alerts.Alert{
|
return alerts.Alert{
|
||||||
Event: alerts.EventAnomaly,
|
Event: alerts.EventAnomaly,
|
||||||
|
Host: r.Host,
|
||||||
Client: r.Client,
|
Client: r.Client,
|
||||||
Netblock: k.netblock,
|
Netblock: k.netblock,
|
||||||
ASN: r.ASN,
|
ASN: r.ASN,
|
||||||
|
|||||||
@@ -502,17 +502,17 @@ func FromEnvironment(lookupEnv func(string) (string, bool)) (*Config, error) {
|
|||||||
UpstreamRequestTimeout: env.duration("SWWAF_UPSTREAM_REQUEST_TIMEOUT", "60s"),
|
UpstreamRequestTimeout: env.duration("SWWAF_UPSTREAM_REQUEST_TIMEOUT", "60s"),
|
||||||
UpstreamResponseTimeout: env.duration("SWWAF_UPSTREAM_RESPONSE_TIMEOUT", "30m"),
|
UpstreamResponseTimeout: env.duration("SWWAF_UPSTREAM_RESPONSE_TIMEOUT", "30m"),
|
||||||
RequestMaxBytes: env.size("SWWAF_REQUEST_MAX_BYTES", "100M"),
|
RequestMaxBytes: env.size("SWWAF_REQUEST_MAX_BYTES", "100M"),
|
||||||
ResponseMaxBytes: env.size("SWWAF_RESPONSE_MAX_BYTES", "5G"),
|
ResponseMaxBytes: env.size("SWWAF_RESPONSE_MAX_BYTES", "1G"),
|
||||||
AllowNets: env.netblocks("SWWAF_ALLOW_NETS", ""),
|
AllowNets: env.netblocks("SWWAF_ALLOW_NETS", ""),
|
||||||
RateLimitExemptNets: env.netblocks("SWWAF_RATE_LIMIT_EXEMPT_NETS", ""),
|
RateLimitExemptNets: env.netblocks("SWWAF_RATE_LIMIT_EXEMPT_NETS", ""),
|
||||||
DenyNets: env.netblocks("SWWAF_DENY_NETS", ""),
|
DenyNets: env.netblocks("SWWAF_DENY_NETS", ""),
|
||||||
RateLimitPerMinute: env.count("SWWAF_RATE_LIMIT_PER_MINUTE", "1000"),
|
RateLimitPerMinute: env.count("SWWAF_RATE_LIMIT_PER_MINUTE", "6000"),
|
||||||
RateLimitPerHour: env.count("SWWAF_RATE_LIMIT_PER_HOUR", "10000"),
|
RateLimitPerHour: env.count("SWWAF_RATE_LIMIT_PER_HOUR", "100000"),
|
||||||
RateLimitPerDay: env.count("SWWAF_RATE_LIMIT_PER_DAY", "50000"),
|
RateLimitPerDay: env.count("SWWAF_RATE_LIMIT_PER_DAY", "1000000"),
|
||||||
RateLimitExemptPaths: env.pathPrefixes("SWWAF_RATE_LIMIT_EXEMPT_PATHS", ""),
|
RateLimitExemptPaths: env.pathPrefixes("SWWAF_RATE_LIMIT_EXEMPT_PATHS", ""),
|
||||||
BytesLimitPerMinute: env.size("SWWAF_BYTES_LIMIT_PER_MINUTE", "10G"),
|
BytesLimitPerMinute: env.size("SWWAF_BYTES_LIMIT_PER_MINUTE", "4G"),
|
||||||
BytesLimitPerHour: env.size("SWWAF_BYTES_LIMIT_PER_HOUR", "20G"),
|
BytesLimitPerHour: env.size("SWWAF_BYTES_LIMIT_PER_HOUR", "20G"),
|
||||||
BytesLimitPerDay: env.size("SWWAF_BYTES_LIMIT_PER_DAY", "50G"),
|
BytesLimitPerDay: env.size("SWWAF_BYTES_LIMIT_PER_DAY", "200G"),
|
||||||
BytesCount: env.bytesCount("SWWAF_BYTES_COUNT", "both"),
|
BytesCount: env.bytesCount("SWWAF_BYTES_COUNT", "both"),
|
||||||
LookupSource: env.lookupSource("SWWAF_LOOKUP_SOURCE", "geojs"),
|
LookupSource: env.lookupSource("SWWAF_LOOKUP_SOURCE", "geojs"),
|
||||||
LookupDBPath: env.value("SWWAF_LOOKUP_DB_PATH", ""),
|
LookupDBPath: env.value("SWWAF_LOOKUP_DB_PATH", ""),
|
||||||
|
|||||||
@@ -261,10 +261,10 @@ func TestDefaults(t *testing.T) {
|
|||||||
UpstreamRequestTimeout: time.Minute,
|
UpstreamRequestTimeout: time.Minute,
|
||||||
UpstreamResponseTimeout: 30 * time.Minute,
|
UpstreamResponseTimeout: 30 * time.Minute,
|
||||||
RequestMaxBytes: 100 << 20,
|
RequestMaxBytes: 100 << 20,
|
||||||
ResponseMaxBytes: 5 << 30,
|
ResponseMaxBytes: 1 << 30,
|
||||||
RateLimitPerMinute: 1000,
|
RateLimitPerMinute: 6000,
|
||||||
RateLimitPerHour: 10000,
|
RateLimitPerHour: 100000,
|
||||||
RateLimitPerDay: 50000,
|
RateLimitPerDay: 1000000,
|
||||||
BanResponse: 403,
|
BanResponse: 403,
|
||||||
LimitBanDuration: time.Hour,
|
LimitBanDuration: time.Hour,
|
||||||
LimitBanRepeatWindow: 24 * time.Hour,
|
LimitBanRepeatWindow: 24 * time.Hour,
|
||||||
@@ -284,8 +284,8 @@ func TestDefaults(t *testing.T) {
|
|||||||
LookupSource: defaultLookupSource, LookupTimeout: time.Second,
|
LookupSource: defaultLookupSource, LookupTimeout: time.Second,
|
||||||
})
|
})
|
||||||
wantByteLimitSettings(t, cfg, config.Config{
|
wantByteLimitSettings(t, cfg, config.Config{
|
||||||
BytesLimitPerMinute: 10 << 30, BytesLimitPerHour: 20 << 30,
|
BytesLimitPerMinute: 4 << 30, BytesLimitPerHour: 20 << 30,
|
||||||
BytesLimitPerDay: 50 << 30, BytesCount: "both",
|
BytesLimitPerDay: 200 << 30, BytesCount: "both",
|
||||||
})
|
})
|
||||||
|
|
||||||
if cfg.UpstreamURL.String() != "http://127.0.0.1:8081" {
|
if cfg.UpstreamURL.String() != "http://127.0.0.1:8081" {
|
||||||
@@ -2371,17 +2371,17 @@ func TestLogsEachSettingWithItsValue(t *testing.T) {
|
|||||||
upstreamRequestTimeout: "60s",
|
upstreamRequestTimeout: "60s",
|
||||||
upstreamResponseTimeout: "30m",
|
upstreamResponseTimeout: "30m",
|
||||||
requestMaxBytes: "100M",
|
requestMaxBytes: "100M",
|
||||||
responseMaxBytes: "5G",
|
responseMaxBytes: "1G",
|
||||||
allowNets: "",
|
allowNets: "",
|
||||||
rateLimitExemptNets: "",
|
rateLimitExemptNets: "",
|
||||||
denyNets: "",
|
denyNets: "",
|
||||||
rateLimitPerMinute: "1000",
|
rateLimitPerMinute: "6000",
|
||||||
rateLimitPerHour: "10000",
|
rateLimitPerHour: "100000",
|
||||||
rateLimitPerDay: "50000",
|
rateLimitPerDay: "1000000",
|
||||||
rateLimitExemptPaths: "",
|
rateLimitExemptPaths: "",
|
||||||
bytesLimitPerMinute: "10G",
|
bytesLimitPerMinute: "4G",
|
||||||
bytesLimitPerHour: "20G",
|
bytesLimitPerHour: "20G",
|
||||||
bytesLimitPerDay: "50G",
|
bytesLimitPerDay: "200G",
|
||||||
bytesCount: "both",
|
bytesCount: "both",
|
||||||
lookupSource: defaultLookupSource,
|
lookupSource: defaultLookupSource,
|
||||||
lookupDBPath: "",
|
lookupDBPath: "",
|
||||||
|
|||||||
+44
-23
@@ -1,6 +1,7 @@
|
|||||||
// Package metrics keeps smallwebwaf's Prometheus metrics, as the "Metrics
|
// Package metrics keeps smallwebwaf's Prometheus metrics, as
|
||||||
// endpoint" section of SPEC.md lists them, and serves them in the
|
// docs/metrics.md lists them, and serves them in the Prometheus text
|
||||||
// Prometheus text format. No metric carries a client's address.
|
// format, as the "Metrics endpoint" section of SPEC.md requires. No
|
||||||
|
// metric carries a client's address.
|
||||||
package metrics
|
package metrics
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -402,28 +403,21 @@ func (m *Metrics) RequestEnded(
|
|||||||
line *requestlog.Line, limit string, duration, upstreamDuration time.Duration,
|
line *requestlog.Line, limit string, duration, upstreamDuration time.Duration,
|
||||||
) {
|
) {
|
||||||
m.inFlight.Dec()
|
m.inFlight.Dec()
|
||||||
|
m.count(line, limit, duration, upstreamDuration)
|
||||||
|
}
|
||||||
|
|
||||||
class := statusClass(line.Status)
|
// RequestAllowed counts a question of rproxy's, answered allow, as no longer
|
||||||
m.requests.WithLabelValues(class, line.Action).Inc()
|
// under way. RequestReported counts the request it was about.
|
||||||
m.requestBytes.WithLabelValues(class, line.Action).Add(float64(line.RequestBytes))
|
func (m *Metrics) RequestAllowed() {
|
||||||
m.responseBytes.WithLabelValues(class, line.Action).Add(float64(line.ResponseBytes))
|
m.inFlight.Dec()
|
||||||
m.requestDuration.Observe(duration.Seconds())
|
}
|
||||||
|
|
||||||
if upstreamDuration > 0 {
|
// RequestReported counts a request rproxy passed to the app, as RequestEnded
|
||||||
m.upstreamDuration.Observe(upstreamDuration.Seconds())
|
// does, from what its report says, which line holds.
|
||||||
}
|
func (m *Metrics) RequestReported(
|
||||||
|
line *requestlog.Line, duration, upstreamDuration time.Duration,
|
||||||
if limit != "" {
|
) {
|
||||||
m.sizeAndTimeLimitHits.WithLabelValues(limit).Inc()
|
m.count(line, "", duration, upstreamDuration)
|
||||||
}
|
|
||||||
|
|
||||||
if line.Country != "" {
|
|
||||||
m.countries.add(line.Country, line)
|
|
||||||
}
|
|
||||||
|
|
||||||
if line.ASN != "" {
|
|
||||||
m.asns.add(line.ASN, line)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LimitHit counts a request that broke a rate limit, a byte limit or the
|
// LimitHit counts a request that broke a rate limit, a byte limit or the
|
||||||
@@ -492,6 +486,33 @@ func (m *Metrics) StateFileEditSetAside(name string) {
|
|||||||
m.stateFileEditsSetAside.WithLabelValues(name).Inc()
|
m.stateFileEditsSetAside.WithLabelValues(name).Inc()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// count counts a request that has ended, as RequestEnded describes.
|
||||||
|
func (m *Metrics) count(
|
||||||
|
line *requestlog.Line, limit string, duration, upstreamDuration time.Duration,
|
||||||
|
) {
|
||||||
|
class := statusClass(line.Status)
|
||||||
|
m.requests.WithLabelValues(class, line.Action).Inc()
|
||||||
|
m.requestBytes.WithLabelValues(class, line.Action).Add(float64(line.RequestBytes))
|
||||||
|
m.responseBytes.WithLabelValues(class, line.Action).Add(float64(line.ResponseBytes))
|
||||||
|
m.requestDuration.Observe(duration.Seconds())
|
||||||
|
|
||||||
|
if upstreamDuration > 0 {
|
||||||
|
m.upstreamDuration.Observe(upstreamDuration.Seconds())
|
||||||
|
}
|
||||||
|
|
||||||
|
if limit != "" {
|
||||||
|
m.sizeAndTimeLimitHits.WithLabelValues(limit).Inc()
|
||||||
|
}
|
||||||
|
|
||||||
|
if line.Country != "" {
|
||||||
|
m.countries.add(line.Country, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
if line.ASN != "" {
|
||||||
|
m.asns.add(line.ASN, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// addReputationQueries adds the counter of the queries to source, a DNSBL
|
// addReputationQueries adds the counter of the queries to source, a DNSBL
|
||||||
// zone, or of the checks of clients with AbuseIPDB, which count tells.
|
// zone, or of the checks of clients with AbuseIPDB, which count tells.
|
||||||
func (m *Metrics) addReputationQueries(source prometheus.Labels, count func() int) {
|
func (m *Metrics) addReputationQueries(source prometheus.Labels, count func() int) {
|
||||||
|
|||||||
@@ -41,6 +41,15 @@ var (
|
|||||||
errNotAddress = errors.New("is not an address, such as 203.0.113.9")
|
errNotAddress = errors.New("is not an address, such as 203.0.113.9")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// answerHealth answers a request for the health endpoint.
|
||||||
|
func (rq *request) answerHealth() {
|
||||||
|
rq.line.Action = requestlog.ActionAdmin
|
||||||
|
// Set here rather than left to Go's server, which would set it only
|
||||||
|
// after the log line has taken the response's headers.
|
||||||
|
rq.out.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
_, _ = io.WriteString(rq.out, "ok\n")
|
||||||
|
}
|
||||||
|
|
||||||
// answerAdmin answers a request for smallwebwaf itself, under
|
// answerAdmin answers a request for smallwebwaf itself, under
|
||||||
// /_smallwebwaf/, once it has passed the checks. Each endpoint needs a
|
// /_smallwebwaf/, once it has passed the checks. Each endpoint needs a
|
||||||
// token, sent as Authorization: Bearer <token>: the metrics
|
// token, sent as Authorization: Bearer <token>: the metrics
|
||||||
|
|||||||
@@ -15,9 +15,11 @@ func TestWithEveryAnomalyThresholdOffARequestIsNotCounted(t *testing.T) {
|
|||||||
// anomaly counters, nor a clock, and the request no response: reading
|
// anomaly counters, nor a clock, and the request no response: reading
|
||||||
// any of them to count the request panics.
|
// any of them to count the request panics.
|
||||||
rq := &request{
|
rq := &request{
|
||||||
h: &handler{config: &config.Config{LookupSource: "geojs"}},
|
decision: decision{
|
||||||
client: netip.MustParseAddr("203.0.113.9"),
|
client: netip.MustParseAddr("203.0.113.9"),
|
||||||
lookedUp: true,
|
lookedUp: true,
|
||||||
|
},
|
||||||
|
h: &handler{config: &config.Config{LookupSource: "geojs"}},
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|||||||
@@ -323,6 +323,7 @@ func (rq *request) alertBan(ban bans.Ban) {
|
|||||||
|
|
||||||
rq.h.alerts.Raise(alerts.Alert{
|
rq.h.alerts.Raise(alerts.Alert{
|
||||||
Event: event,
|
Event: event,
|
||||||
|
Host: rq.site,
|
||||||
Client: rq.client,
|
Client: rq.client,
|
||||||
Netblock: ban.Netblock,
|
Netblock: ban.Netblock,
|
||||||
ASN: ban.Notes.ASN,
|
ASN: ban.Notes.ASN,
|
||||||
@@ -339,11 +340,11 @@ func (rq *request) alertBan(ban bans.Ban) {
|
|||||||
func (rq *request) noted(now time.Time, status int) bans.Request {
|
func (rq *request) noted(now time.Time, status int) bans.Request {
|
||||||
return bans.Request{
|
return bans.Request{
|
||||||
Time: now,
|
Time: now,
|
||||||
Method: rq.in.Method,
|
Method: rq.line.Method,
|
||||||
Host: rq.in.Host,
|
Host: rq.line.Host,
|
||||||
Path: rq.in.URL.RequestURI(),
|
Path: rq.requestURI,
|
||||||
Status: status,
|
Status: status,
|
||||||
UserAgent: rq.in.UserAgent(),
|
UserAgent: rq.line.UserAgent,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ const (
|
|||||||
userAgent = "ban-test/1.0"
|
userAgent = "ban-test/1.0"
|
||||||
// permanent is the log line's ban_expires for a permanent ban.
|
// permanent is the log line's ban_expires for a permanent ban.
|
||||||
permanent = "permanent"
|
permanent = "permanent"
|
||||||
|
// banResponseClose is the SWWAF_BAN_RESPONSE that closes the connection.
|
||||||
|
banResponseClose = "close"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBrokenLimitBansTheClient(t *testing.T) {
|
func TestBrokenLimitBansTheClient(t *testing.T) {
|
||||||
@@ -237,7 +239,7 @@ func TestBanResponseAnswersEveryRefusalButTheSizeLimits(t *testing.T) {
|
|||||||
{"", http.StatusForbidden},
|
{"", http.StatusForbidden},
|
||||||
{"403", http.StatusForbidden},
|
{"403", http.StatusForbidden},
|
||||||
{"429", http.StatusTooManyRequests},
|
{"429", http.StatusTooManyRequests},
|
||||||
{"close", 0},
|
{banResponseClose, 0},
|
||||||
} {
|
} {
|
||||||
t.Run(banResponse+"="+tc.setting, func(t *testing.T) {
|
t.Run(banResponse+"="+tc.setting, func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|||||||
@@ -113,6 +113,7 @@ func (rq *request) alertWAFBlock(result waf.Result) {
|
|||||||
|
|
||||||
rq.h.alerts.Raise(alerts.Alert{
|
rq.h.alerts.Raise(alerts.Alert{
|
||||||
Event: alerts.EventWAFBlock,
|
Event: alerts.EventWAFBlock,
|
||||||
|
Host: rq.site,
|
||||||
Client: rq.client,
|
Client: rq.client,
|
||||||
Netblock: rq.h.clientGroup(rq.client),
|
Netblock: rq.h.clientGroup(rq.client),
|
||||||
ASN: rq.line.ASN,
|
ASN: rq.line.ASN,
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ func TestMetricsCountLimitsAndBans(t *testing.T) {
|
|||||||
rateLimitPerMinute: "1",
|
rateLimitPerMinute: "1",
|
||||||
rateLimitExemptNets: scraper,
|
rateLimitExemptNets: scraper,
|
||||||
denyNets: denied,
|
denyNets: denied,
|
||||||
banResponse: "close",
|
banResponse: banResponseClose,
|
||||||
limitBanDuration: "1h",
|
limitBanDuration: "1h",
|
||||||
maxBanDuration: "2h",
|
maxBanDuration: "2h",
|
||||||
})
|
})
|
||||||
|
|||||||
+52
-33
@@ -1,6 +1,8 @@
|
|||||||
// Package proxy passes each request to the app and the app's answer back,
|
// Package proxy runs the checks on each request and writes its request log
|
||||||
// unchanged, within the size and time limits, and writes one request log
|
// line. New passes each request it lets through to the app and the app's
|
||||||
// line for each request.
|
// answer back, unchanged, within the size and time limits. NewServeWAF instead
|
||||||
|
// answers rproxy's question about each request, and takes rproxy's report once
|
||||||
|
// the visitor's answer has ended, which writes the request a second log line.
|
||||||
package proxy
|
package proxy
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -11,6 +13,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
lru "github.com/hashicorp/golang-lru/v2"
|
||||||
|
|
||||||
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
"sneak.berlin/go/smallwebwaf/internal/alerts"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/anomaly"
|
"sneak.berlin/go/smallwebwaf/internal/anomaly"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/bans"
|
"sneak.berlin/go/smallwebwaf/internal/bans"
|
||||||
@@ -19,7 +23,6 @@ import (
|
|||||||
"sneak.berlin/go/smallwebwaf/internal/metrics"
|
"sneak.berlin/go/smallwebwaf/internal/metrics"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
"sneak.berlin/go/smallwebwaf/internal/ratelimit"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
"sneak.berlin/go/smallwebwaf/internal/reputation"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
|
||||||
"sneak.berlin/go/smallwebwaf/internal/rules"
|
"sneak.berlin/go/smallwebwaf/internal/rules"
|
||||||
"sneak.berlin/go/smallwebwaf/internal/waf"
|
"sneak.berlin/go/smallwebwaf/internal/waf"
|
||||||
)
|
)
|
||||||
@@ -53,7 +56,8 @@ const ClientsPath = "/_smallwebwaf/clients/"
|
|||||||
// Params are what New needs.
|
// Params are what New needs.
|
||||||
type Params struct {
|
type Params struct {
|
||||||
Config *config.Config
|
Config *config.Config
|
||||||
// RequestLog receives one JSON line per request.
|
// RequestLog receives one JSON line per request, and from servewaf a second
|
||||||
|
// when the request's report comes.
|
||||||
RequestLog io.Writer
|
RequestLog io.Writer
|
||||||
// ProcessLog receives the process's own messages.
|
// ProcessLog receives the process's own messages.
|
||||||
ProcessLog *slog.Logger
|
ProcessLog *slog.Logger
|
||||||
@@ -109,6 +113,23 @@ type Server struct {
|
|||||||
// SWWAF_CLIENT_REQUEST_TIMEOUT while the headers arrive; the proxy
|
// SWWAF_CLIENT_REQUEST_TIMEOUT while the headers arrive; the proxy
|
||||||
// applies the timeouts and size limits from then on.
|
// applies the timeouts and size limits from then on.
|
||||||
func New(params Params) *Server {
|
func New(params Params) *Server {
|
||||||
|
h := newHandler(params)
|
||||||
|
|
||||||
|
return h.server(&http.Server{
|
||||||
|
Handler: h,
|
||||||
|
ReadHeaderTimeout: params.Config.ClientRequestTimeout,
|
||||||
|
// Off is an IdleTimeout of 0, which Go's server replaces with
|
||||||
|
// ReadTimeout: no limit, as long as ReadTimeout stays unset.
|
||||||
|
IdleTimeout: params.Config.ClientIdleTimeout,
|
||||||
|
// Go's server reads 4 KiB past MaxHeaderBytes before it
|
||||||
|
// refuses, so the limit a client meets is the setting.
|
||||||
|
MaxHeaderBytes: int(params.Config.ClientRequestHeaderMaxBytes - 4<<10),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// newHandler returns the handler with what every request shares, as the
|
||||||
|
// settings in params make it.
|
||||||
|
func newHandler(params Params) *handler {
|
||||||
errorLog := slog.NewLogLogger(params.ProcessLog.Handler(), slog.LevelWarn)
|
errorLog := slog.NewLogLogger(params.ProcessLog.Handler(), slog.LevelWarn)
|
||||||
m := metrics.New(params.Config.MetricsTopN, params.Config.InstanceName)
|
m := metrics.New(params.Config.MetricsTopN, params.Config.InstanceName)
|
||||||
lists, dnsbl, abuseIPDB := newReputation(params, m)
|
lists, dnsbl, abuseIPDB := newReputation(params, m)
|
||||||
@@ -171,29 +192,7 @@ func New(params Params) *Server {
|
|||||||
m.AddBansAndClients(h.ledger, h.limiter, params.Now)
|
m.AddBansAndClients(h.ledger, h.limiter, params.Now)
|
||||||
m.AddRules(params.Rules)
|
m.AddRules(params.Rules)
|
||||||
|
|
||||||
return &Server{
|
return h
|
||||||
Server: &http.Server{
|
|
||||||
Addr: params.Config.ListenAddr,
|
|
||||||
Handler: h,
|
|
||||||
ReadHeaderTimeout: params.Config.ClientRequestTimeout,
|
|
||||||
// Off is an IdleTimeout of 0, which Go's server replaces with
|
|
||||||
// ReadTimeout: no limit, as long as ReadTimeout stays unset.
|
|
||||||
IdleTimeout: params.Config.ClientIdleTimeout,
|
|
||||||
// Go's server reads 4 KiB past MaxHeaderBytes before it
|
|
||||||
// refuses, so the limit a client meets is the setting.
|
|
||||||
MaxHeaderBytes: int(params.Config.ClientRequestHeaderMaxBytes - 4<<10),
|
|
||||||
ErrorLog: errorLog,
|
|
||||||
},
|
|
||||||
Ledger: h.ledger,
|
|
||||||
Limiter: h.limiter,
|
|
||||||
GeoJS: h.geojs,
|
|
||||||
Anomalies: h.anomalies,
|
|
||||||
LookupFile: h.lookupFile,
|
|
||||||
Lists: h.lists,
|
|
||||||
DNSBL: h.dnsbl,
|
|
||||||
AbuseIPDB: h.abuseIPDB,
|
|
||||||
Metrics: m,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newReputation returns the lists fetched from URLs, the DNSBL zones'
|
// newReputation returns the lists fetched from URLs, the DNSBL zones'
|
||||||
@@ -274,6 +273,10 @@ type handler struct {
|
|||||||
rules *rules.Files
|
rules *rules.Files
|
||||||
coreRuleSet *waf.CoreRuleSet
|
coreRuleSet *waf.CoreRuleSet
|
||||||
alerts *alerts.Queue
|
alerts *alerts.Queue
|
||||||
|
// awaitingReport holds, in servewaf, the decision on each answered
|
||||||
|
// question by its id until its report comes, and nil for a question still
|
||||||
|
// being handled.
|
||||||
|
awaitingReport *lru.Cache[string, *decision]
|
||||||
}
|
}
|
||||||
|
|
||||||
// newTransport returns what carries requests to the app. It never goes
|
// newTransport returns what carries requests to the app. It never goes
|
||||||
@@ -299,11 +302,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
// The health endpoint is answered at once, before any check, so that
|
// The health endpoint is answered at once, before any check, so that
|
||||||
// a health checker is never refused. It does not ask the app.
|
// a health checker is never refused. It does not ask the app.
|
||||||
if r.Method == http.MethodGet && r.URL.Path == HealthPath {
|
if r.Method == http.MethodGet && r.URL.Path == HealthPath {
|
||||||
rq.line.Action = requestlog.ActionAdmin
|
rq.answerHealth()
|
||||||
// Set here rather than left to Go's server, which would set it only
|
|
||||||
// after the log line has taken the response's headers.
|
|
||||||
rq.out.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
||||||
_, _ = io.WriteString(rq.out, "ok\n")
|
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -339,3 +338,23 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
rq.forward(r.Context())
|
rq.forward(r.Context())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// server returns the Server of h, which listens at SWWAF_LISTEN_ADDR and
|
||||||
|
// logs through h, with what httpServer sets.
|
||||||
|
func (h *handler) server(httpServer *http.Server) *Server {
|
||||||
|
httpServer.Addr = h.config.ListenAddr
|
||||||
|
httpServer.ErrorLog = h.errorLog
|
||||||
|
|
||||||
|
return &Server{
|
||||||
|
Server: httpServer,
|
||||||
|
Ledger: h.ledger,
|
||||||
|
Limiter: h.limiter,
|
||||||
|
GeoJS: h.geojs,
|
||||||
|
Anomalies: h.anomalies,
|
||||||
|
LookupFile: h.lookupFile,
|
||||||
|
Lists: h.lists,
|
||||||
|
DNSBL: h.dnsbl,
|
||||||
|
AbuseIPDB: h.abuseIPDB,
|
||||||
|
Metrics: h.metrics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -284,6 +284,16 @@ func newProxy(
|
|||||||
) (*proxy.Server, *output, *alerts.Queue) {
|
) (*proxy.Server, *output, *alerts.Queue) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
|
return newServerWith(t, proxy.New, appURL, geojsURL, now, env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newServerWith is newProxy for the server build makes.
|
||||||
|
func newServerWith(
|
||||||
|
t *testing.T, build func(proxy.Params) *proxy.Server,
|
||||||
|
appURL, geojsURL string, now func() time.Time, env map[string]string,
|
||||||
|
) (*proxy.Server, *output, *alerts.Queue) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
settings := map[string]string{
|
settings := map[string]string{
|
||||||
"SWWAF_UPSTREAM_URL": appURL, rulesDir: t.TempDir(), instanceName: "app",
|
"SWWAF_UPSTREAM_URL": appURL, rulesDir: t.TempDir(), instanceName: "app",
|
||||||
wafMode: off,
|
wafMode: off,
|
||||||
@@ -334,7 +344,7 @@ func newProxy(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server := proxy.New(proxy.Params{
|
server := build(proxy.Params{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
RequestLog: out,
|
RequestLog: out,
|
||||||
ProcessLog: processLog,
|
ProcessLog: processLog,
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ func (rq *request) noteHit(hit bans.ReputationHit, reason string) {
|
|||||||
rq.h.metrics.ReputationHit(hit.Source)
|
rq.h.metrics.ReputationHit(hit.Source)
|
||||||
rq.h.alerts.Raise(alerts.Alert{
|
rq.h.alerts.Raise(alerts.Alert{
|
||||||
Event: alerts.EventReputationHit,
|
Event: alerts.EventReputationHit,
|
||||||
|
Host: rq.site,
|
||||||
Client: rq.client,
|
Client: rq.client,
|
||||||
Netblock: rq.h.clientGroup(rq.client),
|
Netblock: rq.h.clientGroup(rq.client),
|
||||||
ASN: rq.line.ASN,
|
ASN: rq.line.ASN,
|
||||||
|
|||||||
+97
-55
@@ -39,20 +39,20 @@ type refusal struct {
|
|||||||
limit string
|
limit string
|
||||||
}
|
}
|
||||||
|
|
||||||
// request is one request on its way through smallwebwaf, from the moment
|
// decision is what the checks note of a request: its log line, and what
|
||||||
// its headers have been read to its log line.
|
// counting the request needs once it has ended. servewaf keeps a copy of it
|
||||||
type request struct {
|
// until the request's report comes. It holds no credentials, since the log line
|
||||||
h *handler
|
// never does, and neither the request's objects nor their bodies.
|
||||||
in *http.Request
|
type decision struct {
|
||||||
// rc sets the deadlines of the connection to the client.
|
line requestlog.Line
|
||||||
rc *http.ResponseController
|
client netip.Addr
|
||||||
out *responseWriter
|
// requestURI is the path with the query, as a ban's notes keep it.
|
||||||
body *requestBody // nil for a request without a body
|
requestURI string
|
||||||
line requestlog.Line
|
// site is, in servewaf, the host the visitor asked for, which the
|
||||||
|
// alerts name, since one servewaf serves many sites. It is "" otherwise.
|
||||||
client netip.Addr
|
site string
|
||||||
peer netip.Addr
|
// allowed is true for a question answered with DispositionAllow.
|
||||||
peerTrusted bool
|
allowed bool
|
||||||
// lookedUp is true once the client's AS number and country have been
|
// lookedUp is true once the client's AS number and country have been
|
||||||
// looked up, whether or not an answer was there, and lookupAnswer is
|
// looked up, whether or not an answer was there, and lookupAnswer is
|
||||||
// what the lookup gave then, the zero Answer while GeoJS had given none.
|
// what the lookup gave then, the zero Answer while GeoJS had given none.
|
||||||
@@ -65,18 +65,37 @@ type request struct {
|
|||||||
counted bool
|
counted bool
|
||||||
limitPercent, bytesPercent percentage
|
limitPercent, bytesPercent percentage
|
||||||
// attack is true for a request that matched a ban rule or asked for a
|
// attack is true for a request that matched a ban rule or asked for a
|
||||||
// trap path, ruleBlocked for one a block rule refused, wafBlocked for
|
// trap path, ruleBlocked for one a block rule refused, and wafBlocked for
|
||||||
// one the Core Rule Set refused, and tokenRefused for one refused for a
|
// one the Core Rule Set refused, each an offence its client's history
|
||||||
// missing or wrong token, each an offence its client's history counts.
|
// counts.
|
||||||
attack, ruleBlocked, wafBlocked, tokenRefused bool
|
attack, ruleBlocked, wafBlocked bool
|
||||||
|
// reputation is the reputation sources that list the client, for the
|
||||||
|
// notes of a ban the request makes.
|
||||||
|
reputation []bans.ReputationHit
|
||||||
|
}
|
||||||
|
|
||||||
|
// request is one request on its way through smallwebwaf, from the moment
|
||||||
|
// its headers have been read to its log line.
|
||||||
|
type request struct {
|
||||||
|
decision
|
||||||
|
|
||||||
|
h *handler
|
||||||
|
in *http.Request
|
||||||
|
// rc sets the deadlines of the connection to the client.
|
||||||
|
rc *http.ResponseController
|
||||||
|
out *responseWriter
|
||||||
|
body *requestBody // nil for a request without a body
|
||||||
|
|
||||||
|
peer netip.Addr
|
||||||
|
peerTrusted bool
|
||||||
|
// tokenRefused is true for a request refused for a missing or wrong
|
||||||
|
// token, an offence its client's history counts.
|
||||||
|
tokenRefused bool
|
||||||
// blocklisted is true once a blocklist is found to list the client,
|
// blocklisted is true once a blocklist is found to list the client,
|
||||||
// dnsblListed once a DNSBL zone's verdict is, and abuseIPDBHit once
|
// dnsblListed once a DNSBL zone's verdict is, and abuseIPDBHit once
|
||||||
// AbuseIPDB's score of it is a hit.
|
// AbuseIPDB's score of it is a hit.
|
||||||
blocklisted, dnsblListed, abuseIPDBHit bool
|
blocklisted, dnsblListed, abuseIPDBHit bool
|
||||||
// reputation is the reputation sources that list the client, for the
|
start time.Time
|
||||||
// notes of a ban the request makes.
|
|
||||||
reputation []bans.ReputationHit
|
|
||||||
start time.Time
|
|
||||||
// checked is when the checks were done, and upstreamStart when the
|
// checked is when the checks were done, and upstreamStart when the
|
||||||
// request was handed to the app.
|
// request was handed to the app.
|
||||||
checked time.Time
|
checked time.Time
|
||||||
@@ -108,50 +127,62 @@ type request struct {
|
|||||||
answerStarted time.Time
|
answerStarted time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// newRequest starts handling r: it notes the time, counts the request as
|
// newRequest starts handling r: it works out the client from the TCP peer
|
||||||
// under way, works out the client, and starts the log line with what is
|
// and X-Forwarded-For, and goes on as startRequest does.
|
||||||
// known of the request.
|
|
||||||
func (h *handler) newRequest(w http.ResponseWriter, r *http.Request) *request {
|
func (h *handler) newRequest(w http.ResponseWriter, r *http.Request) *request {
|
||||||
|
peer := peerAddress(r)
|
||||||
|
trusted := h.config.TrustedProxies
|
||||||
|
client := clientAddress(peer, r.Header.Values("X-Forwarded-For"), trusted)
|
||||||
|
|
||||||
|
return h.startRequest(w, r, client, peer, isInside(peer, trusted))
|
||||||
|
}
|
||||||
|
|
||||||
|
// startRequest starts handling r from client, which came through peer: it
|
||||||
|
// notes the time, counts the request as under way, and starts the log line
|
||||||
|
// with what is known of the request. peerTrusted says whether to believe
|
||||||
|
// the request's id and scheme, which r's headers give.
|
||||||
|
func (h *handler) startRequest(
|
||||||
|
w http.ResponseWriter, r *http.Request, client, peer netip.Addr, peerTrusted bool,
|
||||||
|
) *request {
|
||||||
h.metrics.RequestStarted()
|
h.metrics.RequestStarted()
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
peer := peerAddress(r)
|
|
||||||
trusted := h.config.TrustedProxies
|
|
||||||
peerTrusted := isInside(peer, trusted)
|
|
||||||
forwardedFor := r.Header.Values("X-Forwarded-For")
|
forwardedFor := r.Header.Values("X-Forwarded-For")
|
||||||
client := clientAddress(peer, forwardedFor, trusted)
|
|
||||||
|
|
||||||
rq := &request{
|
rq := &request{
|
||||||
|
decision: decision{
|
||||||
|
client: client,
|
||||||
|
requestURI: r.URL.RequestURI(),
|
||||||
|
line: requestlog.Line{
|
||||||
|
Time: requestlog.FormatTime(start),
|
||||||
|
Instance: h.config.InstanceName,
|
||||||
|
ClientIP: client.String(),
|
||||||
|
Method: r.Method,
|
||||||
|
Scheme: scheme(r, peerTrusted),
|
||||||
|
Host: r.Host,
|
||||||
|
Path: rules.Path(r),
|
||||||
|
Query: r.URL.RawQuery,
|
||||||
|
Protocol: r.Proto,
|
||||||
|
Referer: r.Referer(),
|
||||||
|
UserAgent: r.UserAgent(),
|
||||||
|
RequestID: requestID(r, peerTrusted),
|
||||||
|
PeerIP: peer.String(),
|
||||||
|
ForwardedFor: strings.Join(forwardedFor, ", "),
|
||||||
|
ClientGroup: h.clientGroup(client).String(),
|
||||||
|
ContentType: r.Header.Get("Content-Type"),
|
||||||
|
RequestHeaders: requestHeaders(r, h.config.LogRequestHeaders),
|
||||||
|
HasAuthorization: len(r.Header.Values("Authorization")) > 0,
|
||||||
|
HasCookie: len(r.Header.Values("Cookie")) > 0,
|
||||||
|
Action: requestlog.ActionForward,
|
||||||
|
},
|
||||||
|
},
|
||||||
h: h,
|
h: h,
|
||||||
in: r,
|
in: r,
|
||||||
rc: http.NewResponseController(w),
|
rc: http.NewResponseController(w),
|
||||||
out: &responseWriter{ResponseWriter: w},
|
out: &responseWriter{ResponseWriter: w},
|
||||||
client: client,
|
|
||||||
peer: peer,
|
peer: peer,
|
||||||
peerTrusted: peerTrusted,
|
peerTrusted: peerTrusted,
|
||||||
start: start,
|
start: start,
|
||||||
line: requestlog.Line{
|
|
||||||
Time: requestlog.FormatTime(start),
|
|
||||||
Instance: h.config.InstanceName,
|
|
||||||
ClientIP: client.String(),
|
|
||||||
Method: r.Method,
|
|
||||||
Scheme: scheme(r, peerTrusted),
|
|
||||||
Host: r.Host,
|
|
||||||
Path: rules.Path(r),
|
|
||||||
Query: r.URL.RawQuery,
|
|
||||||
Protocol: r.Proto,
|
|
||||||
Referer: r.Referer(),
|
|
||||||
UserAgent: r.UserAgent(),
|
|
||||||
RequestID: requestID(r, peerTrusted),
|
|
||||||
PeerIP: peer.String(),
|
|
||||||
ForwardedFor: strings.Join(forwardedFor, ", "),
|
|
||||||
ClientGroup: h.clientGroup(client).String(),
|
|
||||||
ContentType: r.Header.Get("Content-Type"),
|
|
||||||
RequestHeaders: requestHeaders(r, h.config.LogRequestHeaders),
|
|
||||||
HasAuthorization: len(r.Header.Values("Authorization")) > 0,
|
|
||||||
HasCookie: len(r.Header.Values("Cookie")) > 0,
|
|
||||||
Action: requestlog.ActionForward,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A length of -1 is a body whose length was not announced.
|
// A length of -1 is a body whose length was not announced.
|
||||||
@@ -569,10 +600,20 @@ func (rq *request) finish() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Counted before the log line is written, so that the metrics count
|
// Counted before the log line is written, so that the metrics count
|
||||||
// every request whose line is out.
|
// every request whose line is out. An allowed request is the exception:
|
||||||
rq.h.metrics.RequestEnded(line, limit, duration, upstreamDuration)
|
// its report gives the status, bytes and times the metrics count.
|
||||||
|
if rq.allowed {
|
||||||
|
rq.h.metrics.RequestAllowed()
|
||||||
|
} else {
|
||||||
|
rq.h.metrics.RequestEnded(line, limit, duration, upstreamDuration)
|
||||||
|
}
|
||||||
|
|
||||||
err := requestlog.Write(rq.h.requestLog, line)
|
rq.writeLine()
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeLine writes the request's log line.
|
||||||
|
func (rq *request) writeLine() {
|
||||||
|
err := requestlog.Write(rq.h.requestLog, &rq.line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
rq.h.processLog.Error("writing the request log failed", "error", err.Error())
|
rq.h.processLog.Error("writing the request log failed", "error", err.Error())
|
||||||
}
|
}
|
||||||
@@ -634,6 +675,7 @@ func (rq *request) countAnomalies() {
|
|||||||
answer, _ := rq.answerAtTheEnd()
|
answer, _ := rq.answerAtTheEnd()
|
||||||
|
|
||||||
rq.h.anomalies.Count(rq.h.now(), anomaly.Request{
|
rq.h.anomalies.Count(rq.h.now(), anomaly.Request{
|
||||||
|
Host: rq.site,
|
||||||
Client: rq.client,
|
Client: rq.client,
|
||||||
ClientGroup: rq.h.clientGroup(rq.client),
|
ClientGroup: rq.h.clientGroup(rq.client),
|
||||||
ASN: answer.ASN,
|
ASN: answer.ASN,
|
||||||
|
|||||||
@@ -0,0 +1,464 @@
|
|||||||
|
package proxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
lru "github.com/hashicorp/golang-lru/v2"
|
||||||
|
|
||||||
|
"sneak.berlin/go/smallwebwaf/internal/requestlog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The headers of rproxy's question and of servewaf's answer, as
|
||||||
|
// "servewaf" in SPEC.md gives them.
|
||||||
|
const (
|
||||||
|
// ClientHeader marks a request as rproxy's question, and gives the
|
||||||
|
// visitor's address.
|
||||||
|
ClientHeader = "X-Smallwebwaf-Client"
|
||||||
|
// PeerHeader gives the address of rproxy's own TCP peer.
|
||||||
|
PeerHeader = "X-Smallwebwaf-Peer"
|
||||||
|
// ContentLengthHeader gives the body length the visitor announced.
|
||||||
|
ContentLengthHeader = "X-Smallwebwaf-Content-Length"
|
||||||
|
// DispositionHeader gives servewaf's answer.
|
||||||
|
DispositionHeader = "X-Smallwebwaf-Disposition"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The values of DispositionHeader.
|
||||||
|
const (
|
||||||
|
// DispositionAllow tells rproxy to pass the request to the app.
|
||||||
|
DispositionAllow = "allow"
|
||||||
|
// DispositionDeny tells rproxy to give the visitor the answer's status,
|
||||||
|
// headers and body.
|
||||||
|
DispositionDeny = "deny"
|
||||||
|
// DispositionClose tells rproxy to close the visitor's connection
|
||||||
|
// without an answer, which SWWAF_BAN_RESPONSE asks for when it is close.
|
||||||
|
// servewaf closing the question's connection instead would read as
|
||||||
|
// servewaf being down, and rproxy would then let the request through.
|
||||||
|
DispositionClose = "close"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReportPath is where rproxy sends the report of each request servewaf
|
||||||
|
// answered.
|
||||||
|
const ReportPath = "/_smallwebwaf/report"
|
||||||
|
|
||||||
|
// QuestionBodyMaxBytes is the most of a visitor's body a question carries.
|
||||||
|
const QuestionBodyMaxBytes = 64 << 10
|
||||||
|
|
||||||
|
const (
|
||||||
|
// maxAwaitingReport is the most answered requests held until their
|
||||||
|
// reports come. Past it, the request answered longest ago is dropped.
|
||||||
|
maxAwaitingReport = 10000
|
||||||
|
// maxRequestIDBytes is the longest id a question may give.
|
||||||
|
maxRequestIDBytes = 128
|
||||||
|
// reportBodyMaxBytes is the most of a report's body that is read. It is
|
||||||
|
// far above any report's.
|
||||||
|
reportBodyMaxBytes = 1 << 20
|
||||||
|
// maxHTTPStatus is the highest status a report may give.
|
||||||
|
maxHTTPStatus = 599
|
||||||
|
// maxReportedBytes is the most bytes a report may give for each way, 1
|
||||||
|
// PiB, so that adding them up cannot overflow.
|
||||||
|
maxReportedBytes = 1 << 50
|
||||||
|
// maxReportedMilliseconds is the longest duration a report may give,
|
||||||
|
// about 31 years, so that it fits a time.Duration.
|
||||||
|
maxReportedMilliseconds = 1e12
|
||||||
|
// serveWAFTimeout bounds how long a request to servewaf takes to arrive,
|
||||||
|
// and its answer to leave, and serveWAFIdleTimeout how long a kept-open
|
||||||
|
// connection waits for its next request.
|
||||||
|
serveWAFTimeout = 60 * time.Second
|
||||||
|
serveWAFIdleTimeout = 120 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errReportFieldMissing = errors.New("a field is missing")
|
||||||
|
errReportValue = errors.New("a value is out of range")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Report is the JSON object rproxy posts to ReportPath once the visitor's
|
||||||
|
// answer has ended, its fields named as the request log's of the same
|
||||||
|
// meaning. RequestID is the question's id. Status is what the visitor got, 0
|
||||||
|
// if nothing. The durations are in milliseconds.
|
||||||
|
//
|
||||||
|
//nolint:tagliatelle // docs/request-log.md names the fields in snake_case
|
||||||
|
type Report struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
RequestBytes int64 `json:"request_bytes"`
|
||||||
|
ResponseBytes int64 `json:"response_bytes"`
|
||||||
|
DurationTotal float64 `json:"duration_total"`
|
||||||
|
DurationUpstreamTotal float64 `json:"duration_upstream_total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewServeWAF returns the server `smallwebwaf servewaf` runs. It answers
|
||||||
|
// rproxy's questions with the checks New runs, takes rproxy's reports and
|
||||||
|
// answers its own endpoints. It passes nothing to an app. rproxy applies
|
||||||
|
// the size and time limits to the visitor, so their settings do not apply
|
||||||
|
// here. Go's default limit on a request's line and headers, 1 MiB, stays:
|
||||||
|
// it is far above rproxy's, and a question refused for its size would have
|
||||||
|
// rproxy let the request through.
|
||||||
|
func NewServeWAF(params Params) *Server {
|
||||||
|
cfg := *params.Config
|
||||||
|
cfg.RequestMaxBytes = 0
|
||||||
|
cfg.ClientRequestTimeout = serveWAFTimeout
|
||||||
|
// The server's WriteTimeout does this. It sets a new deadline for each
|
||||||
|
// request, where a deadline a handler sets stays on a kept-open
|
||||||
|
// connection, and would run out under a later request's answer.
|
||||||
|
cfg.ClientResponseTimeout = 0
|
||||||
|
// A question's body of QuestionBodyMaxBytes may be cut short, and the
|
||||||
|
// Core Rule Set does not read a JSON or XML body over its limit.
|
||||||
|
cfg.WAFBodyLimit = min(cfg.WAFBodyLimit, QuestionBodyMaxBytes-1)
|
||||||
|
params.Config = &cfg
|
||||||
|
|
||||||
|
h := newHandler(params)
|
||||||
|
|
||||||
|
awaitingReport, err := lru.New[string, *decision](maxAwaitingReport)
|
||||||
|
if err != nil {
|
||||||
|
panic(err) // New fails only for a size below one
|
||||||
|
}
|
||||||
|
|
||||||
|
h.awaitingReport = awaitingReport
|
||||||
|
|
||||||
|
return h.server(&http.Server{
|
||||||
|
Handler: http.HandlerFunc(h.serveWAF),
|
||||||
|
ReadTimeout: serveWAFTimeout,
|
||||||
|
WriteTimeout: serveWAFTimeout,
|
||||||
|
IdleTimeout: serveWAFIdleTimeout,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// serveWAF handles one request to servewaf: a request carrying
|
||||||
|
// ClientHeader is rproxy's question, and any other is for servewaf itself.
|
||||||
|
func (h *handler) serveWAF(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if len(r.Header.Values(ClientHeader)) > 0 {
|
||||||
|
h.answerQuestion(w, r)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.answerOwnEndpoint(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerQuestion runs the checks on the visitor's request a question
|
||||||
|
// carries, and answers rproxy what to do with it. A denied request's counting
|
||||||
|
// is finished here, and an allowed one's by its report.
|
||||||
|
func (h *handler) answerQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
client, body, ok := h.readQuestion(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// One that cannot be read leaves the log line's peer_ip invalid.
|
||||||
|
peer, _ := netip.ParseAddr(r.Header.Get(PeerHeader))
|
||||||
|
|
||||||
|
rq := h.startRequest(w, asTheVisitorSentIt(r, body), client.Unmap(), peer.Unmap(),
|
||||||
|
true)
|
||||||
|
// The last deferred runs first, so that what is held has the finished log
|
||||||
|
// line. Go's server sends the answer only once this function has
|
||||||
|
// returned, so the report cannot come before it is held.
|
||||||
|
defer rq.holdForReport()
|
||||||
|
defer rq.finish()
|
||||||
|
|
||||||
|
rq.site = r.Host
|
||||||
|
rq.line.ServeWAFLine = requestlog.ServeWAFLineDecision
|
||||||
|
refused := rq.check(r.Context())
|
||||||
|
rq.checked = time.Now()
|
||||||
|
underOwnPrefix := strings.HasPrefix(r.URL.Path, adminPrefix)
|
||||||
|
|
||||||
|
if refused == nil && !underOwnPrefix {
|
||||||
|
// In observe mode, what enforce mode would have refused counts here.
|
||||||
|
defer rq.countRefusal()
|
||||||
|
|
||||||
|
rq.allow()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// The last deferred runs first, as in ServeHTTP.
|
||||||
|
defer rq.addToHistory()
|
||||||
|
defer rq.countAnomalies()
|
||||||
|
defer rq.countRefusal()
|
||||||
|
|
||||||
|
if refused != nil {
|
||||||
|
rq.deny(*refused)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// The app never sees this prefix. servewaf's own endpoints are at its
|
||||||
|
// own address, so this answers as a path with no endpoint does.
|
||||||
|
rq.line.Action = requestlog.ActionAdmin
|
||||||
|
rq.out.Header().Set(DispositionHeader, DispositionDeny)
|
||||||
|
http.Error(rq.out, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readQuestion returns the visitor's address and the body a question carries,
|
||||||
|
// and whether servewaf takes the question. It answers a question it does not
|
||||||
|
// take with 400 and no disposition, which rproxy treats as it treats no
|
||||||
|
// answer. The id of a question it takes is held from here on, without a
|
||||||
|
// decision yet, so that another question with that id is refused while this
|
||||||
|
// one is being handled.
|
||||||
|
//
|
||||||
|
// The body is read before any check, since Go's server does not send an answer
|
||||||
|
// until it has read the body. A question whose body stops arriving gets no
|
||||||
|
// answer, and is not looked at.
|
||||||
|
func (h *handler) readQuestion(
|
||||||
|
w http.ResponseWriter, r *http.Request,
|
||||||
|
) (netip.Addr, []byte, bool) {
|
||||||
|
client, err := netip.ParseAddr(r.Header.Get(ClientHeader))
|
||||||
|
if err != nil || client.Zone() != "" {
|
||||||
|
h.refuseQuestion(w, ClientHeader+" is not an address without a zone")
|
||||||
|
|
||||||
|
return netip.Addr{}, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
id := r.Header.Get(requestIDHeader)
|
||||||
|
if id == "" || len(id) > maxRequestIDBytes || !utf8.ValidString(id) {
|
||||||
|
h.refuseQuestion(w, requestIDHeader+" is not a valid id")
|
||||||
|
|
||||||
|
return netip.Addr{}, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, QuestionBodyMaxBytes))
|
||||||
|
|
||||||
|
if _, tooLarge := errors.AsType[*http.MaxBytesError](err); tooLarge {
|
||||||
|
h.refuseQuestion(w, "the body is over 64 KiB")
|
||||||
|
|
||||||
|
return netip.Addr{}, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
h.processLog.Warn("a question's body stopped arriving", "error", err.Error())
|
||||||
|
// This panic has Go's server close the connection without an answer,
|
||||||
|
// and log nothing.
|
||||||
|
panic(http.ErrAbortHandler)
|
||||||
|
}
|
||||||
|
|
||||||
|
held, _ := h.awaitingReport.ContainsOrAdd(id, nil)
|
||||||
|
if held {
|
||||||
|
h.refuseQuestion(w, requestIDHeader+" is the id of a request servewaf holds")
|
||||||
|
|
||||||
|
return netip.Addr{}, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return client, body, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// refuseQuestion answers a question servewaf does not take, for reason.
|
||||||
|
func (h *handler) refuseQuestion(w http.ResponseWriter, reason string) {
|
||||||
|
h.processLog.Warn("a question is refused", "reason", reason)
|
||||||
|
http.Error(w, reason, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// asTheVisitorSentIt returns a copy of r, a question, as the checks and the
|
||||||
|
// log line are to see it: without the headers rproxy adds for servewaf, with
|
||||||
|
// body, which has been read of r, and with the length the visitor announced,
|
||||||
|
// as -1 when it announced none. The question's own length covers only the part
|
||||||
|
// of the body it carries.
|
||||||
|
func asTheVisitorSentIt(r *http.Request, body []byte) *http.Request {
|
||||||
|
sent := r.Clone(r.Context())
|
||||||
|
announced := sent.Header.Get(ContentLengthHeader)
|
||||||
|
|
||||||
|
sent.Header.Del(ClientHeader)
|
||||||
|
sent.Header.Del(PeerHeader)
|
||||||
|
sent.Header.Del(ContentLengthHeader)
|
||||||
|
sent.Header.Del("Content-Length")
|
||||||
|
|
||||||
|
sent.ContentLength = -1
|
||||||
|
|
||||||
|
length, err := strconv.ParseInt(announced, 10, 64)
|
||||||
|
if err == nil && length >= 0 {
|
||||||
|
sent.ContentLength = length
|
||||||
|
sent.Header.Set("Content-Length", announced)
|
||||||
|
}
|
||||||
|
|
||||||
|
sent.Body = http.NoBody
|
||||||
|
if len(body) > 0 {
|
||||||
|
sent.Body = io.NopCloser(bytes.NewReader(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
return sent
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow answers a question with DispositionAllow and, while
|
||||||
|
// SWWAF_ADD_LOOKUP_HEADERS is set, the client's AS number and country.
|
||||||
|
func (rq *request) allow() {
|
||||||
|
rq.allowed = true
|
||||||
|
|
||||||
|
header := rq.out.Header()
|
||||||
|
header.Set(DispositionHeader, DispositionAllow)
|
||||||
|
|
||||||
|
if rq.h.config.AddLookupHeaders {
|
||||||
|
setLookupHeaders(header, rq.line.ASN, rq.line.Country)
|
||||||
|
}
|
||||||
|
|
||||||
|
rq.out.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
// holdForReport holds a copy of what the report's steps need, by the request's
|
||||||
|
// id. A report only ever reaches that copy, never the request being handled.
|
||||||
|
func (rq *request) holdForReport() {
|
||||||
|
held := rq.decision
|
||||||
|
rq.h.awaitingReport.Add(rq.line.RequestID, &held)
|
||||||
|
}
|
||||||
|
|
||||||
|
// deny answers a question with what the visitor is to get for r.
|
||||||
|
func (rq *request) deny(r refusal) {
|
||||||
|
if r.status == 0 {
|
||||||
|
// SWWAF_BAN_RESPONSE is close. Written past rq.out, since the log line's
|
||||||
|
// status stays 0: the visitor is sent nothing.
|
||||||
|
rq.refused.CompareAndSwap(nil, &r)
|
||||||
|
rq.out.Header().Set(DispositionHeader, DispositionClose)
|
||||||
|
rq.out.ResponseWriter.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rq.out.Header().Set(DispositionHeader, DispositionDeny)
|
||||||
|
rq.answer(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerOwnEndpoint answers a request to servewaf's own address. No check
|
||||||
|
// runs on it: the address is on the private network, where the peers are
|
||||||
|
// rproxy and the admin's tools, not visitors.
|
||||||
|
func (h *handler) answerOwnEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == http.MethodPost && r.URL.Path == ReportPath {
|
||||||
|
h.takeReport(w, r)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
peer := peerAddress(r)
|
||||||
|
|
||||||
|
rq := h.startRequest(w, r, peer, peer, false)
|
||||||
|
defer rq.finish()
|
||||||
|
|
||||||
|
if r.Method == http.MethodGet && r.URL.Path == HealthPath {
|
||||||
|
rq.answerHealth()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rq.answerAdmin()
|
||||||
|
}
|
||||||
|
|
||||||
|
// takeReport answers POST ReportPath: it finishes the request the report
|
||||||
|
// names, if it holds that request's decision, and ignores the report
|
||||||
|
// otherwise.
|
||||||
|
func (h *handler) takeReport(w http.ResponseWriter, r *http.Request) {
|
||||||
|
report, err := readReport(w, r)
|
||||||
|
if err != nil {
|
||||||
|
h.processLog.Warn("a report is refused", "error", err.Error())
|
||||||
|
http.Error(w, "the body is not a report", http.StatusBadRequest)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
held, found := h.awaitingReport.Peek(report.RequestID)
|
||||||
|
// Remove reports true to one report only, of several that name the id.
|
||||||
|
if found && held != nil && h.awaitingReport.Remove(report.RequestID) {
|
||||||
|
h.finishWith(held, report)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readReport reads a report from r's body, which must be one JSON object with
|
||||||
|
// all of Report's fields, in the ranges SPEC.md gives.
|
||||||
|
func readReport(w http.ResponseWriter, r *http.Request) (Report, error) {
|
||||||
|
var report Report
|
||||||
|
|
||||||
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, reportBodyMaxBytes))
|
||||||
|
if err != nil {
|
||||||
|
return report, fmt.Errorf("read the body: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var fields map[string]json.RawMessage
|
||||||
|
|
||||||
|
err = json.Unmarshal(body, &fields)
|
||||||
|
if err != nil {
|
||||||
|
return report, fmt.Errorf("decode the body: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range []string{
|
||||||
|
"request_id", "status", "request_bytes", "response_bytes",
|
||||||
|
"duration_total", "duration_upstream_total",
|
||||||
|
} {
|
||||||
|
value, there := fields[name]
|
||||||
|
if !there || string(value) == "null" {
|
||||||
|
return report, fmt.Errorf("%w: %s", errReportFieldMissing, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(body, &report)
|
||||||
|
if err != nil {
|
||||||
|
return report, fmt.Errorf("decode the body: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return report, report.checkRanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkRanges returns an error for a value of the report that cannot be true.
|
||||||
|
func (report *Report) checkRanges() error {
|
||||||
|
switch {
|
||||||
|
case report.Status != 0 &&
|
||||||
|
(report.Status < http.StatusContinue || report.Status > maxHTTPStatus):
|
||||||
|
return fmt.Errorf("%w: status", errReportValue)
|
||||||
|
case report.RequestBytes < 0 || report.RequestBytes > maxReportedBytes:
|
||||||
|
return fmt.Errorf("%w: request_bytes", errReportValue)
|
||||||
|
case report.ResponseBytes < 0 || report.ResponseBytes > maxReportedBytes:
|
||||||
|
return fmt.Errorf("%w: response_bytes", errReportValue)
|
||||||
|
case report.DurationTotal < 0 || report.DurationTotal > maxReportedMilliseconds:
|
||||||
|
return fmt.Errorf("%w: duration_total", errReportValue)
|
||||||
|
case report.DurationUpstreamTotal < 0 ||
|
||||||
|
report.DurationUpstreamTotal > maxReportedMilliseconds:
|
||||||
|
return fmt.Errorf("%w: duration_upstream_total", errReportValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// finishWith finishes a request with what its report says, and writes the
|
||||||
|
// request's last log line, which holds its decision's fields and the report's.
|
||||||
|
// For an allowed request it first takes the steps ServeHTTP takes once a
|
||||||
|
// request passed to the app has ended, with the status and bytes of the report
|
||||||
|
// in place of those it would have seen. A denied request's counting was
|
||||||
|
// finished at its decision.
|
||||||
|
func (h *handler) finishWith(held *decision, report Report) {
|
||||||
|
rq := &request{
|
||||||
|
decision: *held,
|
||||||
|
h: h,
|
||||||
|
out: &responseWriter{status: report.Status, bytes: report.ResponseBytes},
|
||||||
|
body: &requestBody{},
|
||||||
|
}
|
||||||
|
rq.body.bytes.Store(report.RequestBytes)
|
||||||
|
|
||||||
|
rq.line.ServeWAFLine = requestlog.ServeWAFLineReport
|
||||||
|
rq.line.Status = report.Status
|
||||||
|
rq.line.RequestBytes = report.RequestBytes
|
||||||
|
rq.line.ResponseBytes = report.ResponseBytes
|
||||||
|
rq.line.DurationTotal = report.DurationTotal
|
||||||
|
|
||||||
|
if rq.allowed {
|
||||||
|
rq.line.DurationUpstreamTotal = &report.DurationUpstreamTotal
|
||||||
|
// addToHistory goes by this for whether the request reached the app.
|
||||||
|
rq.upstreamStart = time.Now()
|
||||||
|
|
||||||
|
rq.countBytes()
|
||||||
|
rq.countAnomalies()
|
||||||
|
rq.addToHistory()
|
||||||
|
|
||||||
|
rq.h.metrics.RequestReported(&rq.line,
|
||||||
|
time.Duration(report.DurationTotal*float64(time.Millisecond)),
|
||||||
|
time.Duration(report.DurationUpstreamTotal*float64(time.Millisecond)))
|
||||||
|
}
|
||||||
|
|
||||||
|
rq.writeLine()
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -206,7 +206,7 @@ type Hit struct {
|
|||||||
// Counts are a client's requests and bytes in the minute, the hour and
|
// Counts are a client's requests and bytes in the minute, the hour and
|
||||||
// the day that end at a request, that request's included.
|
// the day that end at a request, that request's included.
|
||||||
//
|
//
|
||||||
//nolint:tagliatelle // SPEC.md's request log names its fields in snake_case
|
//nolint:tagliatelle // docs/request-log.md names the fields in snake_case
|
||||||
type Counts struct {
|
type Counts struct {
|
||||||
Minute float64 `json:"minute"`
|
Minute float64 `json:"minute"`
|
||||||
Hour float64 `json:"hour"`
|
Hour float64 `json:"hour"`
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Package requestlog writes the lines smallwebwaf prints on stdout: one
|
// Package requestlog writes the lines smallwebwaf prints on stdout: one
|
||||||
// JSON object per request, marked "type":"request", and the process's own
|
// JSON object per request, or two from servewaf, marked "type":"request", and
|
||||||
// messages as JSON lines marked "type":"process".
|
// the process's own messages as JSON lines marked "type":"process".
|
||||||
package requestlog
|
package requestlog
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -60,17 +60,29 @@ const OffenceLimit = "limit"
|
|||||||
// that broke the error burst.
|
// that broke the error burst.
|
||||||
const LimitHitErrorBurst = "error_burst"
|
const LimitHitErrorBurst = "error_burst"
|
||||||
|
|
||||||
|
// The servewaf_line a request line names, which says which of servewaf's two
|
||||||
|
// lines about a question it is.
|
||||||
|
const (
|
||||||
|
// ServeWAFLineDecision is servewaf's line at its decision.
|
||||||
|
ServeWAFLineDecision = "decision"
|
||||||
|
// ServeWAFLineReport is servewaf's line when rproxy's report comes, with
|
||||||
|
// the decision's fields and the report's together.
|
||||||
|
ServeWAFLineReport = "report"
|
||||||
|
)
|
||||||
|
|
||||||
// timeLayout is RFC 3339 with milliseconds.
|
// timeLayout is RFC 3339 with milliseconds.
|
||||||
const timeLayout = "2006-01-02T15:04:05.000Z07:00"
|
const timeLayout = "2006-01-02T15:04:05.000Z07:00"
|
||||||
|
|
||||||
// Line is one request's line in the request log. The field names, and
|
// Line is one request's line in the request log. The field names, and
|
||||||
// their order, are those of the "Request log" section of SPEC.md. A field
|
// their order, are those of docs/request-log.md. A field that may not
|
||||||
// that may not apply to a request is left out of its line when it does
|
// apply to a request is left out of its line when it does not.
|
||||||
// not.
|
|
||||||
//
|
//
|
||||||
//nolint:tagliatelle // SPEC.md's request log names its fields in snake_case
|
//nolint:tagliatelle // docs/request-log.md names the fields in snake_case
|
||||||
type Line struct {
|
type Line struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
// ServeWAFLine is ServeWAFLineDecision or ServeWAFLineReport on servewaf's
|
||||||
|
// two lines about a question.
|
||||||
|
ServeWAFLine string `json:"servewaf_line,omitempty"`
|
||||||
|
|
||||||
// The standard web log fields. Scheme is how the client reached
|
// The standard web log fields. Scheme is how the client reached
|
||||||
// smallwebwaf, or the trusted proxy in front of it.
|
// smallwebwaf, or the trusted proxy in front of it.
|
||||||
|
|||||||
@@ -60,8 +60,19 @@ func TestHealthCheck(t *testing.T) {
|
|||||||
}, 0, "")
|
}, 0, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
app.Close()
|
// Another test can take a closed server's port at once, so the app's
|
||||||
wantHealthCheck(t, env, 1, "unhealthy: connect to the app: ")
|
// address here is a multicast address, to which TCP cannot connect.
|
||||||
|
wantHealthCheck(t, map[string]string{
|
||||||
|
listenAddr: ":" + port,
|
||||||
|
upstreamURL: "http://224.0.0.1",
|
||||||
|
}, 1, "unhealthy: connect to the app: ")
|
||||||
|
|
||||||
|
// Listening on port 0 takes any free port, so nothing listens on port 0
|
||||||
|
// itself.
|
||||||
|
wantHealthCheck(t, map[string]string{listenAddr: ":0"}, 1,
|
||||||
|
"unhealthy: ask smallwebwaf: ")
|
||||||
|
wantHealthCheck(t, map[string]string{listenAddr: "8080"}, 1,
|
||||||
|
"unhealthy: invalid setting: SWWAF_LISTEN_ADDR: ")
|
||||||
|
|
||||||
stop()
|
stop()
|
||||||
|
|
||||||
@@ -70,10 +81,6 @@ func TestHealthCheck(t *testing.T) {
|
|||||||
case <-time.After(waitLimit):
|
case <-time.After(waitLimit):
|
||||||
t.Fatal("still running after being told to stop")
|
t.Fatal("still running after being told to stop")
|
||||||
}
|
}
|
||||||
|
|
||||||
wantHealthCheck(t, env, 1, "unhealthy: ask smallwebwaf: ")
|
|
||||||
wantHealthCheck(t, map[string]string{listenAddr: "8080"}, 1,
|
|
||||||
"unhealthy: invalid setting: SWWAF_LISTEN_ADDR: ")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHealthCheckRefusesAnArgument(t *testing.T) {
|
func TestHealthCheckRefusesAnArgument(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
package smallwebwaf_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"sneak.berlin/go/smallwebwaf/internal/proxy"
|
||||||
|
"sneak.berlin/go/smallwebwaf/internal/smallwebwaf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// commandForMain, while set in the environment, has this test binary run Main
|
||||||
|
// with the command it gives, in place of the tests, so that a test can run
|
||||||
|
// Main in a process of its own.
|
||||||
|
const commandForMain = "SMALLWEBWAF_TEST_COMMAND"
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
command, set := os.LookupEnv(commandForMain)
|
||||||
|
if !set {
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
|
|
||||||
|
os.Args = strings.Fields("smallwebwaf " + command)
|
||||||
|
|
||||||
|
os.Exit(smallwebwaf.Main(testVersion))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMainAnswersQuestionsOnlyAsServeWAF(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
command, disposition string
|
||||||
|
}{
|
||||||
|
{"servewaf", proxy.DispositionAllow},
|
||||||
|
{"", ""},
|
||||||
|
} {
|
||||||
|
t.Run("command "+tc.command, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
binary, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("find the test binary: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(t.Context(), 3*waitLimit)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
out := &output{}
|
||||||
|
cmd := exec.CommandContext(ctx, binary) //nolint:gosec // this test binary
|
||||||
|
cmd.Stdout = out
|
||||||
|
|
||||||
|
cmd.Env = append(os.Environ(),
|
||||||
|
commandForMain+"="+tc.command,
|
||||||
|
listenAddr+"="+localhost+":0",
|
||||||
|
upstreamURL+"="+startApp(t),
|
||||||
|
stateDir+"="+t.TempDir(),
|
||||||
|
rulesDir+"="+t.TempDir(),
|
||||||
|
lookupSource+"=off")
|
||||||
|
|
||||||
|
err = cmd.Start()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("start: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = cmd.Process.Kill()
|
||||||
|
_ = cmd.Wait()
|
||||||
|
})
|
||||||
|
|
||||||
|
addr, _ := out.line(t, "msg", "starting")["address"].(string)
|
||||||
|
ask(t, addr, "/", http.StatusOK, tc.disposition)
|
||||||
|
|
||||||
|
err = cmd.Process.Signal(syscall.SIGTERM)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("signal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cmd.Wait()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("exit: %v; output:\n%s", err, out.text())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ask sends servewaf at addr rproxy's question about a request for path from
|
||||||
|
// placed, checks the answer's status and disposition, and closes it.
|
||||||
|
func ask(t *testing.T, addr, path string, status int, disposition string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||||
|
"http://"+addr+path, http.NoBody)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("new request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set(proxy.ClientHeader, placed)
|
||||||
|
req.Header.Set("X-Request-ID", rand.Text())
|
||||||
|
|
||||||
|
transport := &http.Transport{}
|
||||||
|
defer transport.CloseIdleConnections()
|
||||||
|
|
||||||
|
res, err := (&http.Client{Transport: transport}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("question: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = io.Copy(io.Discard, res.Body)
|
||||||
|
_ = res.Body.Close()
|
||||||
|
|
||||||
|
if res.StatusCode != status ||
|
||||||
|
res.Header.Get(proxy.DispositionHeader) != disposition {
|
||||||
|
t.Errorf("answered %d with disposition %q, want %d with %q", res.StatusCode,
|
||||||
|
res.Header.Get(proxy.DispositionHeader), status, disposition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runServeWAF runs `smallwebwaf servewaf` with the settings in env, has use
|
||||||
|
// send it requests at the address it listens on, stops it as SIGTERM does, and
|
||||||
|
// checks that it stopped in order.
|
||||||
|
func runServeWAF(t *testing.T, env map[string]string, use func(addr string)) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
ctx, stop := context.WithCancel(t.Context())
|
||||||
|
out := &output{}
|
||||||
|
exited := make(chan int, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
exited <- runAs(ctx, true, env, out)
|
||||||
|
}()
|
||||||
|
|
||||||
|
addr, _ := out.line(t, "msg", "starting")["address"].(string)
|
||||||
|
use(addr)
|
||||||
|
stop()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case status := <-exited:
|
||||||
|
if status != 0 {
|
||||||
|
t.Fatalf("exit status %d, want 0; output:\n%s", status, out.text())
|
||||||
|
}
|
||||||
|
case <-time.After(waitLimit):
|
||||||
|
t.Fatal("still running after being told to stop")
|
||||||
|
}
|
||||||
|
|
||||||
|
out.line(t, "msg", "stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeWAFKeepsItsBansAcrossARestartAndNeedsNoApp(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
env := map[string]string{
|
||||||
|
listenAddr: localhost + ":0",
|
||||||
|
stateDir: t.TempDir(),
|
||||||
|
rulesDir: filepath.Join("..", "..", "share", "rules.d"),
|
||||||
|
}
|
||||||
|
|
||||||
|
runServeWAF(t, env, func(addr string) {
|
||||||
|
ask(t, addr, "/", http.StatusOK, proxy.DispositionAllow)
|
||||||
|
// The default rule file bans a probe for this.
|
||||||
|
ask(t, addr, "/.env", http.StatusForbidden, proxy.DispositionDeny)
|
||||||
|
})
|
||||||
|
|
||||||
|
runServeWAF(t, env, func(addr string) {
|
||||||
|
ask(t, addr, "/", http.StatusForbidden, proxy.DispositionDeny)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithoutACommandTheClientHeaderIsNoQuestion(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
runUntilStopped(t, map[string]string{
|
||||||
|
listenAddr: localhost + ":0",
|
||||||
|
upstreamURL: startApp(t),
|
||||||
|
stateDir: t.TempDir(),
|
||||||
|
rulesDir: t.TempDir(),
|
||||||
|
}, func(url string) {
|
||||||
|
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, url,
|
||||||
|
http.NoBody)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("new request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set(proxy.ClientHeader, placed)
|
||||||
|
|
||||||
|
transport := &http.Transport{}
|
||||||
|
defer transport.CloseIdleConnections()
|
||||||
|
|
||||||
|
res, err := (&http.Client{Transport: transport}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(res.Body)
|
||||||
|
_ = res.Body.Close()
|
||||||
|
|
||||||
|
if err != nil || string(body) != greeting ||
|
||||||
|
res.Header.Get(proxy.DispositionHeader) != "" {
|
||||||
|
t.Errorf("answered %q (%v) with disposition %q, want the app's greeting",
|
||||||
|
body, err, res.Header.Get(proxy.DispositionHeader))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
// Package smallwebwaf runs the smallwebwaf process: it reads the settings,
|
// Package smallwebwaf runs the smallwebwaf process: it reads the settings,
|
||||||
// the rule files, the lookup database and the state files, serves requests
|
// the rule files, the lookup database and the state files, serves requests
|
||||||
// until it is told to stop, and then stops in an orderly way, writing the
|
// until it is told to stop, and then stops in an orderly way, writing the
|
||||||
// state files.
|
// state files. It serves them in front of an app, or, as `smallwebwaf
|
||||||
|
// servewaf`, by answering rproxy's questions about them.
|
||||||
package smallwebwaf
|
package smallwebwaf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -45,11 +46,15 @@ type Params struct {
|
|||||||
LookupEnv func(string) (string, bool)
|
LookupEnv func(string) (string, bool)
|
||||||
// Stdout receives the request log and the process's own messages.
|
// Stdout receives the request log and the process's own messages.
|
||||||
Stdout io.Writer
|
Stdout io.Writer
|
||||||
|
// ServeWAF makes it `smallwebwaf servewaf`, which answers rproxy's
|
||||||
|
// questions, rather than the proxy in front of an app.
|
||||||
|
ServeWAF bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main runs smallwebwaf until SIGTERM or SIGINT, and returns the
|
// Main runs smallwebwaf until SIGTERM or SIGINT, and returns the
|
||||||
// process's exit status. Run as `smallwebwaf healthcheck`, it is the
|
// process's exit status. Run as `smallwebwaf servewaf`, it answers
|
||||||
// container's health check instead.
|
// rproxy's questions rather than pass requests to an app. Run as
|
||||||
|
// `smallwebwaf healthcheck`, it is the container's health check instead.
|
||||||
func Main(version string) int {
|
func Main(version string) int {
|
||||||
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
||||||
return HealthCheck(context.Background(), os.Args[2:], os.LookupEnv, os.Stderr)
|
return HealthCheck(context.Background(), os.Args[2:], os.LookupEnv, os.Stderr)
|
||||||
@@ -63,6 +68,7 @@ func Main(version string) int {
|
|||||||
Version: version,
|
Version: version,
|
||||||
LookupEnv: os.LookupEnv,
|
LookupEnv: os.LookupEnv,
|
||||||
Stdout: os.Stdout,
|
Stdout: os.Stdout,
|
||||||
|
ServeWAF: len(os.Args) > 1 && os.Args[1] == "servewaf",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +123,12 @@ func Run(ctx context.Context, params Params) int {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
server, err := newServer(cfg, stdout, processLog, now, ruleFiles, alertQueue)
|
newProxy := proxy.New
|
||||||
|
if params.ServeWAF {
|
||||||
|
newProxy = proxy.NewServeWAF
|
||||||
|
}
|
||||||
|
|
||||||
|
server, err := newServer(newProxy, cfg, stdout, processLog, now, ruleFiles, alertQueue)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
processLog.Error("cannot use the lookup database", "error", err.Error())
|
processLog.Error("cannot use the lookup database", "error", err.Error())
|
||||||
|
|
||||||
@@ -151,10 +162,12 @@ func Run(ctx context.Context, params Params) int {
|
|||||||
return serve(ctx, server, listener, files, ruleFiles, alertQueue, processLog)
|
return serve(ctx, server, listener, files, ruleFiles, alertQueue, processLog)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newServer returns the server smallwebwaf runs, with the metrics of the
|
// newServer returns the server smallwebwaf runs, which newProxy makes, with
|
||||||
// alerts, after reading the lookup database while SWWAF_LOOKUP_SOURCE is
|
// the metrics of the alerts, after reading the lookup database while
|
||||||
// file. A lookup database that cannot be read is an error.
|
// SWWAF_LOOKUP_SOURCE is file. A lookup database that cannot be read is an
|
||||||
|
// error.
|
||||||
func newServer(
|
func newServer(
|
||||||
|
newProxy func(proxy.Params) *proxy.Server,
|
||||||
cfg *config.Config, stdout io.Writer, processLog *slog.Logger,
|
cfg *config.Config, stdout io.Writer, processLog *slog.Logger,
|
||||||
now func() time.Time, ruleFiles *rules.Files, alertQueue *alerts.Queue,
|
now func() time.Time, ruleFiles *rules.Files, alertQueue *alerts.Queue,
|
||||||
) (*proxy.Server, error) {
|
) (*proxy.Server, error) {
|
||||||
@@ -174,7 +187,7 @@ func newServer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server := proxy.New(proxy.Params{
|
server := newProxy(proxy.Params{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
RequestLog: stdout,
|
RequestLog: stdout,
|
||||||
ProcessLog: processLog,
|
ProcessLog: processLog,
|
||||||
|
|||||||
@@ -113,6 +113,13 @@ func (o *output) text() string {
|
|||||||
// returns its exit status. SWWAF_LOOKUP_SOURCE is off unless env sets it,
|
// returns its exit status. SWWAF_LOOKUP_SOURCE is off unless env sets it,
|
||||||
// so that no test sends GeoJS its clients' addresses.
|
// so that no test sends GeoJS its clients' addresses.
|
||||||
func run(ctx context.Context, env map[string]string, out *output) int {
|
func run(ctx context.Context, env map[string]string, out *output) int {
|
||||||
|
return runAs(ctx, false, env, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// runAs is run as `smallwebwaf servewaf` while serveWAF is true.
|
||||||
|
func runAs(
|
||||||
|
ctx context.Context, serveWAF bool, env map[string]string, out *output,
|
||||||
|
) int {
|
||||||
return smallwebwaf.Run(ctx, smallwebwaf.Params{
|
return smallwebwaf.Run(ctx, smallwebwaf.Params{
|
||||||
Version: testVersion,
|
Version: testVersion,
|
||||||
LookupEnv: func(name string) (string, bool) {
|
LookupEnv: func(name string) (string, bool) {
|
||||||
@@ -123,7 +130,8 @@ func run(ctx context.Context, env map[string]string, out *output) int {
|
|||||||
|
|
||||||
return value, ok
|
return value, ok
|
||||||
},
|
},
|
||||||
Stdout: out,
|
Stdout: out,
|
||||||
|
ServeWAF: serveWAF,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1240,13 +1248,13 @@ func wantStartingLine(t *testing.T, line map[string]any, appURL, dir string) {
|
|||||||
"SWWAF_UPSTREAM_REQUEST_TIMEOUT": "60s",
|
"SWWAF_UPSTREAM_REQUEST_TIMEOUT": "60s",
|
||||||
"SWWAF_UPSTREAM_RESPONSE_TIMEOUT": "30m",
|
"SWWAF_UPSTREAM_RESPONSE_TIMEOUT": "30m",
|
||||||
"SWWAF_REQUEST_MAX_BYTES": "100M",
|
"SWWAF_REQUEST_MAX_BYTES": "100M",
|
||||||
"SWWAF_RESPONSE_MAX_BYTES": "5G",
|
"SWWAF_RESPONSE_MAX_BYTES": "1G",
|
||||||
"SWWAF_ALLOW_NETS": "",
|
"SWWAF_ALLOW_NETS": "",
|
||||||
rateLimitExemptNets: "",
|
rateLimitExemptNets: "",
|
||||||
"SWWAF_DENY_NETS": "",
|
"SWWAF_DENY_NETS": "",
|
||||||
"SWWAF_RATE_LIMIT_PER_MINUTE": "1000",
|
"SWWAF_RATE_LIMIT_PER_MINUTE": "6000",
|
||||||
"SWWAF_RATE_LIMIT_PER_HOUR": "10000",
|
"SWWAF_RATE_LIMIT_PER_HOUR": "100000",
|
||||||
rateLimitPerDay: "50000",
|
rateLimitPerDay: "1000000",
|
||||||
"SWWAF_RATE_LIMIT_EXEMPT_PATHS": "",
|
"SWWAF_RATE_LIMIT_EXEMPT_PATHS": "",
|
||||||
"SWWAF_DENIED_COUNTRIES": "",
|
"SWWAF_DENIED_COUNTRIES": "",
|
||||||
"SWWAF_EXCLUSIVELY_ALLOWED_COUNTRIES": "",
|
"SWWAF_EXCLUSIVELY_ALLOWED_COUNTRIES": "",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
// Package state keeps smallwebwaf's state in JSON files in
|
// Package state keeps smallwebwaf's state in JSON files in
|
||||||
// SWWAF_STATE_DIR, as the "Persistent state" section of SPEC.md describes:
|
// SWWAF_STATE_DIR, as the "Persistent state" section of SPEC.md requires
|
||||||
|
// and docs/state-files.md lists them:
|
||||||
// bans.json holds the bans, clients.json each client's counters and
|
// bans.json holds the bans, clients.json each client's counters and
|
||||||
// history, lookups.json GeoJS's answers, reputation.json the last try and
|
// history, lookups.json GeoJS's answers, reputation.json the last try and
|
||||||
// last good copy of each list fetched from a URL, the DNSBL zones'
|
// last good copy of each list fetched from a URL, the DNSBL zones'
|
||||||
|
|||||||
@@ -1019,8 +1019,8 @@ func TestEditJustBeforeAScheduledWriteSurvivesIt(t *testing.T) {
|
|||||||
edit(t, dir, bansJSON, permanentBansJSON)
|
edit(t, dir, bansJSON, permanentBansJSON)
|
||||||
|
|
||||||
// The write takes the edit in first, and writes it back. The second
|
// The write takes the edit in first, and writes it back. The second
|
||||||
// ban, made after the admin opened the file, is lost, as "Edits
|
// ban, made after the admin opened the file, is lost, as the
|
||||||
// while running" in SPEC.md says.
|
// "Persistent state" section of SPEC.md says.
|
||||||
time.Sleep(time.Nanosecond)
|
time.Sleep(time.Nanosecond)
|
||||||
synctest.Wait()
|
synctest.Wait()
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
// Package waf runs the OWASP Core Rule Set 4.25.0, through Coraza, on the
|
// Package waf 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 SWWAF_WAF_BODY_LIMIT is set, with the six changes smallwebwaf
|
// body while SWWAF_WAF_BODY_LIMIT is set, with the six changes smallwebwaf
|
||||||
// makes to it, as "Attack detection" under "Configuration surface" in
|
// makes to it, as "Attack detection" under "Settings" in SPEC.md describes
|
||||||
// SPEC.md describes them. It reads no response.
|
// them. It reads no response.
|
||||||
//
|
//
|
||||||
// smallwebwaf writes only to its state directory, so Coraza is built with
|
// smallwebwaf 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
|
||||||
|
|||||||
@@ -2,11 +2,12 @@
|
|||||||
# script/gitea-requests: build the image and run gitea 1.27.3 behind it,
|
# script/gitea-requests: build the image and run gitea 1.27.3 behind it,
|
||||||
# with every setting of smallwebwaf at its default but SWWAF_UPSTREAM_URL,
|
# with every setting of smallwebwaf at its default but SWWAF_UPSTREAM_URL,
|
||||||
# which names gitea's container. Then send through it the gitea requests
|
# which names gitea's container. Then send through it the gitea requests
|
||||||
# that reading gitea's source found the Core Rule Set refuses, and a short
|
# that reading gitea's source found the Core Rule Set refuses, which
|
||||||
# sample of gitea's ordinary use: signing in, pages of files and commits,
|
# docs/gitea.md records, and a short sample of gitea's ordinary use:
|
||||||
# a diff, the API, a push, clone and fetch over HTTP, and two container
|
# signing in, pages of files and commits, a diff, the API, a push, clone
|
||||||
# image pushes. Last, print each request smallwebwaf logged, with what it
|
# and fetch over HTTP, and two container image pushes. Last, print each
|
||||||
# did with it and the ids of the Core Rule Set's rules that matched it.
|
# request smallwebwaf logged, with what it did with it and the ids of the
|
||||||
|
# Core Rule Set's rules that matched it.
|
||||||
# Every request comes from one client, docker's gateway, so more than
|
# Every request comes from one client, docker's gateway, so more than
|
||||||
# SWWAF_ERROR_BURST_THRESHOLD, 30, refusals in a minute would ban it, and
|
# SWWAF_ERROR_BURST_THRESHOLD, 30, refusals in a minute would ban it, and
|
||||||
# the requests after would show as banned. The containers, the network,
|
# the requests after would show as banned. The containers, the network,
|
||||||
|
|||||||
Reference in New Issue
Block a user