diff --git a/README.md b/README.md index 1084f4c..5e7cd52 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ runtime through `PUT /admin-api/policy`, which persists to `policy_settings`. | `Rate` | `Off` | the volume budget: `Off` / `Observe` / `Enforce` (OPEN-56) | | `RateLimitPerWindow` | `100` | requests one source may make per window | | `RateWindowSeconds` | `60` | how long that budget lasts | +| `NetblockCandidateBans` | `5` | how many live engine bans inside one block make the edge offer that block to the operator; `0` is the watch off (OPEN-67) | +| `NetblockPrefixV4` / `NetblockPrefixV6` | `24` / `48` | the block a candidate is written as | A `PUT` whose value is outside its range is a **400 that names the key and the range**, not a 200 that quietly keeps the old value. Both halves of that matter, @@ -238,6 +240,9 @@ addresses were refused on their first request. | `engineBlockStatus` | 400–599 | a block must answer with a status that means blocked | | `operatorBlockStatus` | 301 or 400–599 | 301 is the redirect; any other 3xx is a redirect with no Location | | `refusalRange` / `serverErrorRange` | `low-high` inside 100–599 | a range matching nothing is a pillar switched off by a typo | +| `netblockCandidateBans` | 0–1000 | 0 is off and says so; past 1000 the watch is off by arithmetic while the surface still answers | +| `netblockPrefixV4` | 8–31 | below /8 a "block" is most of the internet — the same reason the block form refuses `0.0.0.0/0`; /32 is an address, and the list already has a row for that | +| `netblockPrefixV6` | 29–127 | /29 is about the smallest allocation a registry hands out; /127 is one address again | | `rateMode` | `off` / `observe` / `enforce` | off is the default: a limit nobody wrote is a defence nobody asked for, and a false positive here locks out a whole office behind one address | | `rateLimitPerWindow` | 1–100000 | 0 is not "no limit" — that is `rateMode: Off`; past 100000 the pillar is switched off by arithmetic while still reading Enforce | | `rateWindowSeconds` | 1–3600 | below a second the counter is stale before it is read (the snapshot TTL is 30 s); past an hour it is a quota, and the lever for a longer sentence is `banDurationMinutes` | @@ -397,7 +402,10 @@ GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8, GET /admin-api/observations per-source streaks, durable — the maximum ever seen GET /admin-api/streaks the streak standing right now, in this process, with the threshold GET /admin-api/alerts server_error_streak | candidate_ban | rule_match | rate_breach + | netblock_candidate GET /admin-api/rate what the volume counter holds right now, biggest first +GET /admin-api/netblocks the blocks the edge's own bans point at, with the threshold + they were measured against — an offer, never a ban GET /admin-api/rules path patterns, in the order they are enforced POST {"pattern","action":"observe|block","note","expiresInMinutes"} DELETE /admin-api/rules/{id} @@ -1024,6 +1032,59 @@ What the record deliberately does **not** do: `/admin-api/state` — because "the config changed and the record of it did not land" has to be a sentence an operator can read. +### The edge notices the netblock behind its bans + +OPEN-66 made a range enforceable. This is the half that decides an operator +should write one. A scanner farm inside one /24 is twenty engine bans and twenty +operator decisions: the streak rule works per source, so the edge bans each +address it sees and nothing connects them. `GET /admin-api/netblocks` groups the +edge's **live engine bans** by the block they sit under and returns the blocks +with at least `netblockCandidateBans` of them (default 5, `0` is off), each with +its ban count, its oldest and newest ban, three of the keys inside it, and +whether a range the operator already wrote covers it. + +The rulings: + +* **The evidence is the edge's own bans.** An operator's row is a decision + already taken, and an expired ban is a row the edge stopped honouring — neither + is evidence about a netblock. Nothing new is observed and nothing new is + stored. +* **An offer is not a ban.** A candidate changes nothing on the wire: the + operator's call — `POST /admin-api/blocks` with the CIDR — is what enforces + it, and the console button is that same call. Twenty honest visitors of one + provider and one farm inside one rented block produce the same number, and + only a human can tell them apart. +* **The grouping is one allocation up from the key.** v4 groups to /24, the unit + most providers hand out; v6 groups to /48, because the streak key is already a + /64 and grouping at /64 would only repeat the key. Both are keys, because a + host that hands out /22s should be shown the block it can actually act on. +* **A ban keyed on a wider block is not evidence about one netblock.** With + `ipv4KeyPrefixLength` below the netblock prefix, one row already claims more + than a /24, and counting it as one ban inside a /24 would invent a candidate. +* **Reading the list is not news.** The scan that answers the surface raises no + alert, so refreshing a page cannot manufacture alert rows. The timer's scan + raises `netblock_candidate` — through the same durable alert table and push + queue as every other kind — at most once per block per six hours, and not at + all for a block the operator has already banned. +* **A failed scan retires the offers.** The last answer is dropped rather than + repeated, and `/admin-api/state` says which of the three situations this is: + `netblockCandidateBans` (0 is off), `netblockCandidates`, `netblockLastScanAt`, + `netblockScanError`. + +```bash +curl -s -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/netblocks' +# {"threshold":5,"prefixV4":24,"prefixV6":48,"scannedAt":"…","scanError":null, +# "scope":"this-edge","note":"candidates only: nothing here is banned …", +# "netblocks":[{"match":"203.0.113.0/24","prefix":24,"bans":11, +# "firstBanAt":"…","lastBanAt":"…", +# "sample":["203.0.113.10","203.0.113.11","203.0.113.12"], +# "alreadyBanned":false}]} +``` + +What it costs: one scan every five minutes over a table the edge already keeps, +off the request path. Nothing on the request path changed — a candidate is read +by a surface, not by a guard. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1082,6 +1143,15 @@ nobody is told about never fires at 3am either. With an endpoint configured the page says `pushed to `, with how many landed, how many failed and how many are still owed; without one it says `not pushed anywhere: each row waits for someone to open this page`, so "no alerts" and "alerts go nowhere" stay two different sentences. +It shows the netblocks the edge noticed (OPEN-67) — the blocks its own live +engine bans point at, each with the count inside it, the span of those bans and a +few of the keys, with one button that writes the range through the same block +call the form above uses. A block the operator has already banned says +`already banned` instead of offering again, the note under the table says plainly +that a candidate is an offer and not a ban, and the summary carries +`netblock offers N` apart from `ranges N` — what the edge is suggesting and what +this edge is enforcing are two numbers, and mixing them would make a suggestion +look like a decision. It shows what changed on this edge — the record of every deliberate config change (OPEN-64) as a table of when, section, action, target, the note somebody typed and the surface it came through, with the log's two bounds (`pruned after @@ -1218,9 +1288,9 @@ On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable alert-push queue, the config transfer, the second token, the startup refusals, the change -log and that log on the console, and the operator's ranges: build 0 warnings / -0 errors, unit **334/334**, integration **312/312 in 31 s**, -console **105 assertions, 0 failed**, smoke **passed 137, failed 0**, and compose **285 passed, +log and that log on the console, the operator's ranges and the netblock watch: +build 0 warnings / 0 errors, unit **353/353**, integration **326/326 in 31 s**, +console **114 assertions, 0 failed**, smoke **passed 149, failed 0**, and compose **293 passed, 0 failed** against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the diff --git a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs index 9bdf69c..eb703bb 100644 --- a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs +++ b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs @@ -94,6 +94,26 @@ public sealed record EdgePolicy /// readable. public int ChangeLogMaxRows { get; init; } = 5000; + /// How many live engine bans inside one block make that block worth + /// showing the operator as a range they could ban instead (OPEN-67). 0 turns + /// the watch off, and 0 is the honest way to say off: a threshold no edge + /// will ever reach is the same switch thrown with arithmetic while the + /// surface still answers. Nothing is banned by this number — it decides only + /// what is offered, and the operator decides the rest. + public int NetblockCandidateBans { get; init; } = 5; + + /// The block a v4 ban is grouped into while looking for a + /// candidate. /24 is the allocation unit most providers hand out, so it is + /// the block an operator can act on with one row; a deployment whose host + /// hands out a /22 writes a smaller number and sees the bigger block. + public int NetblockPrefixV4 { get; init; } = 24; + + /// The same for v6. The streak key is already a /64, so a candidate + /// at /64 would only ever repeat the key the ban is stored under; /48 is the + /// allocation one size up, which is where a rotating v6 farm first looks + /// like one thing rather than sixty-four rows. + public int NetblockPrefixV6 { get; init; } = 48; + public GeoMode Geo { get; init; } = GeoMode.Off; /// Whether X-Forwarded-For / CF-Connecting-IP may define the diff --git a/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs b/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs index aea5c69..019eddd 100644 --- a/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs +++ b/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs @@ -77,6 +77,25 @@ public static class PolicyBounds /// The one non-4xx the operator block may answer, because 301 is /// the reference behaviour: a redirect to a honey-pot target. Any other /// 3xx would be a redirect with no Location, which is not a redirect. + /// How many live engine bans inside one block make it a candidate + /// the operator is shown (OPEN-67). 0 is off, and it is a value rather than + /// a mistake: the watch only ever suggests, so an operator who does not want + /// suggestions can say so. The ceiling is the streak threshold's argument — + /// a number no edge will reach is the watch switched off by arithmetic, with + /// the surface still answering as if it were on. + public const int NetblockCandidateBansMin = 0, NetblockCandidateBansMax = 1000; + + /// The block a candidate is written as. The v4 floor is /8 because + /// below that a "block" is most of the address space, and banning that is a + /// shutdown dressed as a range — the same reason the block form itself + /// refuses 0.0.0.0/0. The ceiling is /31 because a single address is an + /// address, and the block list already has a row shape for that. + public const int NetblockPrefixV4Min = 8, NetblockPrefixV4Max = 31; + + /// v6 keeps the same shape: /29 is about the smallest allocation a + /// registry hands out, and /127 is one address again. + public const int NetblockPrefixV6Min = 29, NetblockPrefixV6Max = 127; + public const int OperatorRedirectStatus = 301; /// A status the HTTP/1.1 wire format can carry. Kestrel accepts @@ -98,6 +117,9 @@ public static class PolicyBounds public static bool Ipv6KeyPrefixLengthOk(int v) => v is >= Ipv6KeyPrefixLengthMin and <= Ipv6KeyPrefixLengthMax; public static bool RateLimitPerWindowOk(int v) => v is >= RateLimitPerWindowMin and <= RateLimitPerWindowMax; public static bool RateWindowSecondsOk(double v) => v is >= RateWindowSecondsMin and <= RateWindowSecondsMax; + public static bool NetblockCandidateBansOk(int v) => v is >= NetblockCandidateBansMin and <= NetblockCandidateBansMax; + public static bool NetblockPrefixV4Ok(int v) => v is >= NetblockPrefixV4Min and <= NetblockPrefixV4Max; + public static bool NetblockPrefixV6Ok(int v) => v is >= NetblockPrefixV6Min and <= NetblockPrefixV6Max; public static bool EngineBlockStatusOk(int v) => v is >= BlockStatusMin and <= BlockStatusMax; public static bool OperatorBlockStatusOk(int v) => @@ -116,6 +138,9 @@ public static class PolicyBounds "engineBlockStatus" => $"{BlockStatusMin}..{BlockStatusMax}", "rateLimitPerWindow" => $"{RateLimitPerWindowMin}..{RateLimitPerWindowMax}", "rateWindowSeconds" => $"{RateWindowSecondsMin}..{RateWindowSecondsMax}", + "netblockCandidateBans" => $"{NetblockCandidateBansMin}..{NetblockCandidateBansMax}", + "netblockPrefixV4" => $"{NetblockPrefixV4Min}..{NetblockPrefixV4Max}", + "netblockPrefixV6" => $"{NetblockPrefixV6Min}..{NetblockPrefixV6Max}", "operatorBlockStatus" => $"{OperatorRedirectStatus} or {BlockStatusMin}..{BlockStatusMax}", "refusalRange" or "serverErrorRange" => @@ -136,6 +161,9 @@ public static class PolicyBounds "engineBlockStatus" => int.TryParse(value, out var v) && EngineBlockStatusOk(v), "rateLimitPerWindow" => int.TryParse(value, out var v) && RateLimitPerWindowOk(v), "rateWindowSeconds" => double.TryParse(value, out var v) && RateWindowSecondsOk(v), + "netblockCandidateBans" => int.TryParse(value, out var v) && NetblockCandidateBansOk(v), + "netblockPrefixV4" => int.TryParse(value, out var v) && NetblockPrefixV4Ok(v), + "netblockPrefixV6" => int.TryParse(value, out var v) && NetblockPrefixV6Ok(v), "operatorBlockStatus" => int.TryParse(value, out var v) && OperatorBlockStatusOk(v), "refusalRange" or "serverErrorRange" => StatusRange.TryParse(value, out var r) diff --git a/dotnet/OpenWaf.Domain/Security/NetblockCandidate.cs b/dotnet/OpenWaf.Domain/Security/NetblockCandidate.cs new file mode 100644 index 0000000..899f17e --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/NetblockCandidate.cs @@ -0,0 +1,147 @@ +using System.Net; +using System.Net.Sockets; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Domain.Security; + +/// +/// A netblock the edge's own bans point at (OPEN-67). This is not a decision +/// and nothing here enforces anything: it says "these N live engine bans all +/// sit inside this one block", which is a fact about the edge's list, not a +/// claim that the block is one farm. Twenty honest visitors of one provider and +/// one scanner rotating through one rented /24 produce the same number, and +/// only the operator can tell them apart — which is why the candidate ends as a +/// suggestion on a surface and never as a row in the block list. +/// +/// The block in the one CIDR spelling OPEN-66 stores and +/// enforces, so the string on the surface is the string the block form takes. +/// How many live engine bans sit inside it. +/// A few of those keys, so the operator can check the +/// claim against the rows rather than trust the count. +/// Whether a live operator range already covers this +/// block — the offer has been taken, and the row in the block list is the answer. +public sealed record NetblockCandidate( + string Match, + int Prefix, + int Bans, + DateTimeOffset FirstBanAt, + DateTimeOffset LastBanAt, + IReadOnlyList Sample, + bool AlreadyBanned); + +/// The grouping rules, as pure functions: the arithmetic a reader has +/// to check sits in one place and is testable without a database. +public static class Netblocks +{ + /// How many of a candidate's addresses the surface shows. + public const int SampleSize = 3; + + /// The prefix a ban key itself names: 32 for a bare v4 address, 64 + /// for a v6 key written "a:b:c:d::/64", -1 when the key names no address at + /// all (the "*" a /0 source key becomes). + public static int KeyPrefix(string? banKey) + { + if (!TryKeyAddress(banKey, out var ip)) return -1; + var full = ip.AddressFamily == AddressFamily.InterNetwork ? 32 : 128; + var slash = banKey!.Trim().IndexOf('/'); + if (slash < 0) return full; + return int.TryParse(banKey.Trim()[(slash + 1)..], out var prefix) ? prefix : -1; + } + + /// The address a ban key names, whether the key was written as one + /// address or as a block. The v6 key the engine stores is a block — + /// "2001:db8:1:2::/64" — so a parser that only accepts bare addresses cannot + /// see the bans it is supposed to group. + private static bool TryKeyAddress(string? banKey, out IPAddress address) + { + address = IPAddress.None; + if (string.IsNullOrWhiteSpace(banKey)) return false; + var text = banKey.Trim(); + var slash = text.IndexOf('/'); + if (slash >= 0) text = text[..slash]; + return SourceKey.TryParse(text, out _, out address); + } + + /// The block this ban key sits under, or null when the key is not + /// evidence about one block. + public static string? Covering(string? banKey, EdgePolicy policy) + { + if (!TryKeyAddress(banKey, out var ip)) return null; + var prefix = NetblockPrefix(ip.AddressFamily, policy); + return $"{SourceKey.Mask(ip, prefix)}/{prefix}"; + } + + public static int NetblockPrefix(AddressFamily family, EdgePolicy policy) + => family == AddressFamily.InterNetwork ? policy.NetblockPrefixV4 : policy.NetblockPrefixV6; + + /// Group live engine bans into the blocks they point at and keep + /// the blocks with enough of them to be worth showing. + public static IReadOnlyList Candidates( + IEnumerable<(string Key, DateTimeOffset CreatedAt)> liveEngineBans, + EdgePolicy policy, + NetworkBanIndex operatorRanges, + DateTimeOffset now) + { + if (policy.NetblockCandidateBans <= 0) return []; + + var groups = new Dictionary(StringComparer.Ordinal); + foreach (var (key, createdAt) in liveEngineBans) + { + if (!TryKeyAddress(key, out var ip)) continue; + var ownPrefix = KeyPrefix(key); + + // A key that names no address at all (the "*" a /0 source key + // becomes) is inside no block, and a ban whose own key is a block + // wider than the netblock prefix is not evidence about one netblock: + // counting the /8 the operator keyed on as "one ban inside + // 198.51.100.0/24" would invent a candidate out of a row that + // already claims more than that. + if (ownPrefix < 0 || ownPrefix < NetblockPrefix(ip.AddressFamily, policy)) continue; + var prefix = NetblockPrefix(ip.AddressFamily, policy); + + var match = $"{SourceKey.Mask(ip, prefix)}/{prefix}"; + if (!groups.TryGetValue(match, out var group)) groups[match] = group = new Group(); + group.Add(key, createdAt); + } + + var candidates = new List(); + foreach (var (match, group) in groups) + { + if (group.Count < policy.NetblockCandidateBans) continue; + var slash = match.IndexOf('/'); + // The block's own address answers the question "is this block + // already inside a range the operator wrote?" — a range equal to it + // or broader covers that address, and a narrower one does not. + var covered = operatorRanges.Covers(match[..slash], now); + candidates.Add(new NetblockCandidate( + match, NetworkBans.PrefixOf(match), group.Count, group.First, group.Last, + group.Sample(), covered)); + } + + candidates.Sort((a, b) => + { + var byBans = b.Bans.CompareTo(a.Bans); + return byBans != 0 ? byBans : string.CompareOrdinal(a.Match, b.Match); + }); + return candidates; + } + + private sealed class Group + { + private readonly List _sample = []; + public int Count { get; private set; } + public DateTimeOffset First { get; private set; } + public DateTimeOffset Last { get; private set; } + + public void Add(string key, DateTimeOffset createdAt) + { + Count++; + if (Count == 1 || createdAt < First) First = createdAt; + if (Count == 1 || createdAt > Last) Last = createdAt; + if (_sample.Count < SampleSize && !_sample.Contains(key, StringComparer.Ordinal)) _sample.Add(key); + } + + public IReadOnlyList Sample() => _sample; + } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 6962681..e2e802c 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -120,6 +120,10 @@ internal static class AdminConsole
sourceprovenancereasonlive untillast
+

Netblocks the edge noticed

+
+
blockbans insideoldest bannewest bansome of those bans
+

Allow entries

matchnoteexpires
@@ -257,7 +261,7 @@ function row(cells) { async function load() { if (!token) { note('no token', true); return; } try { - const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, alertsRes, geoRes, changesRes] = await Promise.all([ + const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, alertsRes, geoRes, changesRes, netblocksRes] = await Promise.all([ apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'), apiRaw(withSrc('/admin-api/observations?limit=25')), apiRaw(withSrc('/admin-api/streaks')), @@ -266,7 +270,8 @@ async function load() { apiRaw('/admin-api/rules?live=false&limit=500'), apiRaw('/admin-api/rate?limit=25'), apiRaw('/admin-api/alerts?limit=25'), apiRaw('/admin-api/geo'), - apiRaw('/admin-api/changes?limit=25') + apiRaw('/admin-api/changes?limit=25'), + apiRaw('/admin-api/netblocks') ]); // The core read decides whether there is anything to draw. When the admin // surface is switched off the edge says so in the body — "admin api @@ -282,7 +287,7 @@ async function load() { const alerts = alertsRes.body; const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body, allow = allowRes.body, pathRules = pathRulesRes.body, rate = rateRes.body, geo = geoRes.body, - changes = changesRes.body; + changes = changesRes.body, netblocks = netblocksRes.body; // The listing is capped server-side. Saying so is the difference between a // console and a misleading one: the delete beside this table is not capped. el('blocknote').textContent = blocksRes.truncated @@ -369,6 +374,11 @@ async function load() { // thousand addresses, so a single number mixing the two answers neither // "how many decisions did I write" nor "how wide are they". 'ranges ' + esc(state.operatorRanges) + ' ' + + // What the watch is offering (OPEN-67), counted apart from what is in + // force: an offer bans nobody, and a number that mixed the two would make + // "the edge noticed a /24" look like "the edge banned a /24". + 'netblock offers ' + + esc(((netblocks && netblocks.netblocks) || []).length) + ' ' + // Live exemptions, not rows: the pill used to count rows, which is how a // page could say "allow entries 1" about an exemption the edge had // already stopped honouring. @@ -398,6 +408,28 @@ async function load() { { v: (b.lastStatusCode || '') + ' ' + (b.lastPath || ''), n: true }, { h: '' } ])).join('') || row([{ v: 'none' }]); + // The watch (OPEN-67): the edge's own live engine bans, grouped into the + // block they all sit under. Nothing in this table is in force - it is an + // offer, and the button is the same call the block form makes, so the + // decision to ban a netblock stays a decision. + el('netblocks').tBodies[0].innerHTML = ((netblocks && netblocks.netblocks) || []).map((n) => row([ + { v: n.match }, + { v: n.bans, n: true }, + { v: (n.firstBanAt || '').slice(0, 16).replace('T', ' ') }, + { v: (n.lastBanAt || '').slice(0, 16).replace('T', ' ') }, + { v: (n.sample || []).join(', ') }, + n.alreadyBanned + ? { h: 'already banned' } + : { h: '' } + ])).join('') || row([{ v: 'none' }]); + el('netblocknote').textContent = netblocks && netblocks.scanError + ? 'the last scan failed: ' + netblocks.scanError + ' - nothing is offered, and the last answer was dropped rather than repeated' + : Number(netblocks.threshold) <= 0 + ? 'the watch is off (netblockCandidateBans = 0): the edge groups nothing and offers nothing' + : (((netblocks && netblocks.netblocks) || []).length === 0 + ? 'no block holds ' + netblocks.threshold + ' live engine bans yet - a candidate is an offer, not a ban' + : ((netblocks.netblocks || []).length) + ' block(s) hold ' + netblocks.threshold + + '+ live engine bans - banning one replaces those rows with one range, and nothing here is in force until you do'); // The row is not the answer. An allow entry with an expiry stops being // obeyed the moment it ages — measured on the shipped image: the exempted // address went 502 (through) at 03:58:20 and back to 301 (blocked) at @@ -708,6 +740,16 @@ document.addEventListener('click', async (e) => { if (b.dataset.act === 'delblock') { const r = await apiRaw('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); if (!failed(r)) done('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)'); + } else if (b.dataset.act === 'banrange') { + // The same POST the block form sends. The console does not get a second, + // softer way to write a range, because then it would have a second set of + // rules about what a range means. + // postJson, not a bare POST: the edge refuses a body it cannot name a + // content type for, and the console gate caught this on the first run — + // the button wrote nothing and the page looked idle rather than wrong. + if (await postJson('/admin-api/blocks', { + ip: b.dataset.k, reason: 'netblock the edge noticed: ' + (b.dataset.n || 'several') + ' live engine bans inside it' })) + done('banned the range ' + b.dataset.k); } else if (b.dataset.act === 'delallow') { const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); if (!failed(r)) done('allow entry removed'); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index 694ea51..ae649d0 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -85,7 +85,10 @@ internal sealed record PolicyDto( int BanRetentionDays, string RateMode, int RateLimitPerWindow, - double RateWindowSeconds); + double RateWindowSeconds, + int NetblockCandidateBans, + int NetblockPrefixV4, + int NetblockPrefixV6); /// Every field is optional and null means "leave it alone" — a /// partial update is the only sane shape for a live policy knob. @@ -106,7 +109,23 @@ internal sealed record PolicyUpdateRequest( string[]? DefaultRedirectTargets, string? RateMode, int? RateLimitPerWindow, - double? RateWindowSeconds); + double? RateWindowSeconds, + int? NetblockCandidateBans, + int? NetblockPrefixV4, + int? NetblockPrefixV6); + +/// A block the edge's own bans point at (OPEN-67), as the surface +/// shows it. Nothing here is a decision: the row says how many live engine bans +/// sit inside the block and whether the operator already banned it. +internal sealed record NetblockDto( + /// The block, in the CIDR spelling the block form takes. + string Match, + int Prefix, + int Bans, + DateTimeOffset FirstBanAt, + DateTimeOffset LastBanAt, + IReadOnlyList Sample, + bool AlreadyBanned); /// One source's live volume window, as the limiter is counting it /// right now (OPEN-56). diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs index 0ba3be5..7c0c12b 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs @@ -114,7 +114,8 @@ internal static partial class AdminEndpoints p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders, p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus, p.OperatorBlockStatus, p.DefaultRedirectTargets.ToArray(), p.Rate.ToString(), - p.RateLimitPerWindow, p.RateWindow.TotalSeconds), + p.RateLimitPerWindow, p.RateWindow.TotalSeconds, + p.NetblockCandidateBans, p.NetblockPrefixV4, p.NetblockPrefixV6), blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt)) .Concat(rangeRows.Select(b => new ExportedBlock(b.Match, b.Reason, b.RedirectTo, b.ExpiresAt))), allow = allowRows.Select(a => new ExportedAllow(a.Match, a.Note, a.ExpiresAt)), @@ -459,6 +460,12 @@ internal static partial class AdminEndpoints if (before.Rate != after.Rate) moved.Add($"rate {before.Rate}->{after.Rate}"); if (before.RateLimitPerWindow != after.RateLimitPerWindow) moved.Add($"rateLimitPerWindow {before.RateLimitPerWindow}->{after.RateLimitPerWindow}"); + if (before.NetblockCandidateBans != after.NetblockCandidateBans) + moved.Add($"netblockCandidateBans {before.NetblockCandidateBans}->{after.NetblockCandidateBans}"); + if (before.NetblockPrefixV4 != after.NetblockPrefixV4) + moved.Add($"netblockPrefixV4 {before.NetblockPrefixV4}->{after.NetblockPrefixV4}"); + if (before.NetblockPrefixV6 != after.NetblockPrefixV6) + moved.Add($"netblockPrefixV6 {before.NetblockPrefixV6}->{after.NetblockPrefixV6}"); if (!before.DefaultRedirectTargets.SequenceEqual(after.DefaultRedirectTargets)) moved.Add("redirectTargets changed"); return moved.Count == 0 ? "no field changed" : string.Join(", ", moved); @@ -527,6 +534,9 @@ internal static partial class AdminEndpoints if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets); if (req.RateLimitPerWindow is { } rateLimit) overrides["rateLimitPerWindow"] = rateLimit.ToString(); if (req.RateWindowSeconds is { } rateWindow) overrides["rateWindowSeconds"] = rateWindow.ToString(); + if (req.NetblockCandidateBans is { } netblockBans) overrides["netblockCandidateBans"] = netblockBans.ToString(); + if (req.NetblockPrefixV4 is { } netblockV4) overrides["netblockPrefixV4"] = netblockV4.ToString(); + if (req.NetblockPrefixV6 is { } netblockV6) overrides["netblockPrefixV6"] = netblockV6.ToString(); return true; } } diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index c2f8a8a..07631f8 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -394,6 +394,38 @@ internal static partial class AdminEndpoints }); }); + group.MapGet("/netblocks", async (NetblockWatcher watcher, EdgePolicyProvider policyProvider, + HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + var policy = policyProvider.Current; + // A surface read is not news: the scan runs without raising alerts, + // so refreshing this page cannot manufacture alert rows. + var candidates = await watcher.ScanAsync(false, ct); + return Results.Ok(new + { + // The rules the numbers below were produced with, in the same + // answer. A candidate count without its threshold is a number an + // operator cannot read, and 0 means the watch is off rather than + // that this edge has no netblocks. + threshold = policy.NetblockCandidateBans, + prefixV4 = policy.NetblockPrefixV4, + prefixV6 = policy.NetblockPrefixV6, + scannedAt = watcher.LastScanAt, + scanError = watcher.LastError, + // Counted on this edge, from this edge's bans. Two edges behind a + // load balancer see different halves of an attack, and a listing + // that did not name its scope would read like the fleet's. + scope = "this-edge", + note = policy.NetblockCandidateBans <= 0 + ? "the watch is off: netblockCandidateBans is 0, so nothing is grouped and nothing is offered" + : "candidates only: nothing here is banned and nothing here bans anything. " + + "POST /admin-api/blocks with the CIDR is the operator's decision", + netblocks = candidates.Select(c => new NetblockDto( + c.Match, c.Prefix, c.Bans, c.FirstBanAt, c.LastBanAt, c.Sample, c.AlreadyBanned)) + }); + }); + group.MapGet("/observations", async (OpenWafDbContext db, string? source, int? limit, int? offset, HttpContext ctx, CancellationToken ct) => { @@ -743,7 +775,7 @@ note = t.Note return Results.Ok(rows); }); - group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => + group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, NetblockWatcher netblocks, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; @@ -875,6 +907,17 @@ note = t.Note requestRulesAvailable = state.RulesAvailable, operatorRangesAvailable = state.RangesAvailable, requestRulesError = state.RulesError, + // The netblock watch (OPEN-67). Three answers, not one: whether the + // watch is switched on at all, what it last saw, and whether the scan + // that produced that number actually ran. "0 candidates" from a watch + // that is off, from one that failed and from one that genuinely found + // nothing are three different situations. + netblockCandidateBans = policyProvider.Current.NetblockCandidateBans, + netblockPrefixV4 = policyProvider.Current.NetblockPrefixV4, + netblockPrefixV6 = policyProvider.Current.NetblockPrefixV6, + netblockCandidates = netblocks.LastCandidates().Count, + netblockLastScanAt = netblocks.LastScanAt, + netblockScanError = netblocks.LastError, // The schema this edge is serving against (OPEN-55). A database that // predates a table used to be invisible: the pillar it needs answered // as if there were nothing to see. These four fields say which step @@ -1075,6 +1118,12 @@ note = t.Note return $"engineBlockStatus must be {PolicyBounds.RangeOf("engineBlockStatus")}; got {e}"; if (req.OperatorBlockStatus is { } o && !PolicyBounds.OperatorBlockStatusOk(o)) return $"operatorBlockStatus must be {PolicyBounds.RangeOf("operatorBlockStatus")}; got {o}"; + if (req.NetblockCandidateBans is { } ncb && !PolicyBounds.NetblockCandidateBansOk(ncb)) + return $"netblockCandidateBans must be {PolicyBounds.RangeOf("netblockCandidateBans")}; got {ncb}"; + if (req.NetblockPrefixV4 is { } np4 && !PolicyBounds.NetblockPrefixV4Ok(np4)) + return $"netblockPrefixV4 must be {PolicyBounds.RangeOf("netblockPrefixV4")}; got {np4}"; + if (req.NetblockPrefixV6 is { } np6 && !PolicyBounds.NetblockPrefixV6Ok(np6)) + return $"netblockPrefixV6 must be {PolicyBounds.RangeOf("netblockPrefixV6")}; got {np6}"; if (req.RefusalRange is not null && !StatusRangeUsable(req.RefusalRange)) return $"refusalRange must be {PolicyBounds.RangeOf("refusalRange")}; got \"{req.RefusalRange}\""; if (req.ServerErrorRange is not null && !StatusRangeUsable(req.ServerErrorRange)) @@ -1103,7 +1152,8 @@ note = t.Note p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus, p.OperatorBlockStatus, p.DefaultRedirectTargets, (int)p.ObservationRetention.TotalDays, (int)p.BanRetention.TotalDays, - p.Rate.ToString(), p.RateLimitPerWindow, p.RateWindow.TotalSeconds); + p.Rate.ToString(), p.RateLimitPerWindow, p.RateWindow.TotalSeconds, + p.NetblockCandidateBans, p.NetblockPrefixV4, p.NetblockPrefixV6); /// /// The provenance filter, parsed honestly. The old shape mapped any unrecognised diff --git a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs index c8df469..940eef1 100644 --- a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs +++ b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs @@ -67,6 +67,16 @@ internal sealed class EdgePolicyOptions public int ChangeRetentionDays { get; set; } = 30; public int ChangeLogMaxRows { get; set; } = 5000; + // The netblock watch (OPEN-67): how many live engine bans inside one block + // make that block worth offering the operator as a range, and how big the + // block is that they are grouped into. 0 bans is off and is a value, not a + // mistake — the watch only ever suggests. Out of range refuses startup like + // every other key here: a deployment that wrote 33 meant something, and + // reading it as 24 would be this build inventing a network nobody asked for. + public int NetblockCandidateBans { get; set; } = 5; + public int NetblockPrefixV4 { get; set; } = 24; + public int NetblockPrefixV6 { get; set; } = 48; + public const int RetentionDaysFloor = 1; public const int RetentionDaysCeiling = 365; public const int ChangeLogRowsFloor = 100; @@ -97,7 +107,10 @@ internal sealed class EdgePolicyOptions ObservationRetention = RetentionDays(ObservationRetentionDays, "OpenWaf:Policy:ObservationRetentionDays"), BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays"), ChangeRetention = RetentionDays(ChangeRetentionDays, "OpenWaf:Policy:ChangeRetentionDays"), - ChangeLogMaxRows = ChangeLogRows(ChangeLogMaxRows, "OpenWaf:Policy:ChangeLogMaxRows") + ChangeLogMaxRows = ChangeLogRows(ChangeLogMaxRows, "OpenWaf:Policy:ChangeLogMaxRows"), + NetblockCandidateBans = NetblockBans(NetblockCandidateBans, "OpenWaf:Policy:NetblockCandidateBans"), + NetblockPrefixV4 = NetblockPrefixV4Value(NetblockPrefixV4, "OpenWaf:Policy:NetblockPrefixV4"), + NetblockPrefixV6 = NetblockPrefixV6Value(NetblockPrefixV6, "OpenWaf:Policy:NetblockPrefixV6") }; private static int RateWindowLimit(int v) @@ -139,6 +152,32 @@ internal sealed class EdgePolicyOptions return rows; } + /// 0 is off and is honoured as such; anything outside the bound is + /// a deployment mistake named at startup. + private static int NetblockBans(int v, string configKey) + { + if (!PolicyBounds.NetblockCandidateBansOk(v)) + throw new InvalidOperationException( + $"{configKey} must be {PolicyBounds.RangeOf("netblockCandidateBans")}; got {v}"); + return v; + } + + private static int NetblockPrefixV4Value(int v, string configKey) + { + if (!PolicyBounds.NetblockPrefixV4Ok(v)) + throw new InvalidOperationException( + $"{configKey} must be {PolicyBounds.RangeOf("netblockPrefixV4")}; got {v}"); + return v; + } + + private static int NetblockPrefixV6Value(int v, string configKey) + { + if (!PolicyBounds.NetblockPrefixV6Ok(v)) + throw new InvalidOperationException( + $"{configKey} must be {PolicyBounds.RangeOf("netblockPrefixV6")}; got {v}"); + return v; + } + /// Accepts both 00:05:00 and a bare number of minutes. private static TimeSpan ParseWindow(string value, TimeSpan fallback) { diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 16336d3..ddc9c59 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -136,8 +136,13 @@ builder.Services.AddHostedService(); // alone does not make the implementation resolvable. builder.Services.AddSingleton(); builder.Services.AddSingleton(); +// The netblock watch (OPEN-67) is reachable as itself as well as hosted: the +// admin surface reads its last scan, and the tests force a scan rather than +// waiting five minutes for the timer. +builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddHostedService(); builder.Services.AddReverseProxy() diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs index eea4cf6..ae54d21 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs @@ -145,6 +145,9 @@ public sealed class EdgePolicyProvider if (Usable("ipv4KeyPrefixLength") && map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v }; if (Usable("engineBlockStatus") && map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv }; if (Usable("operatorBlockStatus") && map.TryGetValue("operatorBlockStatus", out var obs) && int.TryParse(obs, out var obsv)) p = p with { OperatorBlockStatus = obsv }; + if (Usable("netblockCandidateBans") && map.TryGetValue("netblockCandidateBans", out var ncb) && int.TryParse(ncb, out var ncbv)) p = p with { NetblockCandidateBans = ncbv }; + if (Usable("netblockPrefixV4") && map.TryGetValue("netblockPrefixV4", out var np4) && int.TryParse(np4, out var np4v)) p = p with { NetblockPrefixV4 = np4v }; + if (Usable("netblockPrefixV6") && map.TryGetValue("netblockPrefixV6", out var np6) && int.TryParse(np6, out var np6v)) p = p with { NetblockPrefixV6 = np6v }; if (map.TryGetValue("redirectTargets", out var rt) && !string.IsNullOrWhiteSpace(rt)) p = p with { DefaultRedirectTargets = rt.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }; diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs b/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs new file mode 100644 index 0000000..6e3bb96 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs @@ -0,0 +1,165 @@ +using System.Collections.Concurrent; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// The watch that turns the edge's own bans into an offer (OPEN-67). +/// +/// A scanner farm inside one /24 is twenty engine bans and twenty operator +/// decisions. OPEN-66 made a range enforceable; this is the half that notices +/// the range exists. It reads only what is already there — live engine bans — +/// and it writes nothing to the block list. The only thing it produces is a row +/// in the alert table and a line on a surface, both of which say the same +/// sentence: "these N bans sit inside this block, and here is the call that +/// would replace them". +/// +/// Why a timer rather than the request path: the answer changes on the scale of +/// minutes, and a per-request grouping over the block table would price a +/// decision nobody is reading. Why not a database view: the grouping has to +/// consult the operator's ranges to know whether the offer was already taken, +/// and the rules of that comparison live in where the +/// unit tests can reach them. +/// +public sealed class NetblockWatcher : BackgroundService +{ + /// The alert kind. It is one of the fixed kinds this codebase + /// writes, which is what lets it be a metric label and a table filter. + public const string AlertKind = "netblock_candidate"; + + private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5); + + /// How often the same block may raise the same alert. A /24 that is + /// still producing bans every five minutes is the same news, and an alert + /// that repeats is an alert the operator stops reading — the same reasoning + /// that made the push queue count attempts instead of firing more payloads. + private static readonly TimeSpan AlertCooldown = TimeSpan.FromHours(6); + + private readonly IServiceScopeFactory _scopeFactory; + private readonly EdgePolicyProvider _policy; + private readonly AlertWriter _alerts; + private readonly ILogger _log; + + private readonly ConcurrentDictionary _alerted = new(StringComparer.Ordinal); + private long _lastScanTicks; + private IReadOnlyList _last = []; + private string? _lastError; + + public NetblockWatcher( + IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, AlertWriter alerts, + ILogger log) + { + _scopeFactory = scopeFactory; + _policy = policy; + _alerts = alerts; + _log = log; + } + + /// When this process last looked, and what it saw. The state + /// surface shows both: a watch that is off, a watch that is failing and a + /// watch that found nothing have to read differently from the outside. + public DateTimeOffset LastScanAt => new(Interlocked.Read(ref _lastScanTicks), TimeSpan.Zero); + + /// The last scan's answer, without running one. Cheap enough for a + /// status surface that is scraped more often than anyone reads it. + public IReadOnlyList LastCandidates() => _last; + + public string? LastError => Volatile.Read(ref _lastError); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try { await Task.Delay(Interval, stoppingToken); } + catch (TaskCanceledException) { return; } + try { await ScanAndAlertAsync(CancellationToken.None); } + catch (Exception ex) { _log.LogWarning(ex, "NetblockWatcher: the scan failed."); } + } + } + + /// One scan. is false when a surface + /// asked for the answer: reading the list is not news, and an operator + /// refreshing a page must not be able to raise an alert per refresh. + public async Task> ScanAndAlertAsync(CancellationToken ct) + => await ScanAsync(true, ct); + + public async Task> ScanAsync(bool raiseAlerts, CancellationToken ct) + { + var policy = _policy.Current; + var now = DateTimeOffset.UtcNow; + + if (policy.NetblockCandidateBans <= 0) + { + // Off is an answer, not a failure: the cache is cleared so a surface + // cannot keep showing candidates the operator switched off. + _last = []; + Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); + Volatile.Write(ref _lastError, null); + return _last; + } + + IReadOnlyList candidates; + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var bans = await db.Blocks + .Where(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now)) + .Select(b => new { b.SourceKey, b.CreatedAt }) + .AsNoTracking() + .ToListAsync(ct); + + var ranges = await db.NetworkBans + .Where(r => r.ExpiresAt == null || r.ExpiresAt > now) + .AsNoTracking() + .ToListAsync(ct); + + candidates = Netblocks.Candidates( + bans.Select(b => (b.SourceKey, b.CreatedAt)), + policy, + new NetworkBanIndex(ranges), + now); + Volatile.Write(ref _lastError, null); + } + catch (Exception ex) + { + // The watch is a suggestion engine, so a failure here retires the + // suggestions rather than repeating the last ones: an operator + // offering a range from a scan that never ran is offering a fact + // that stopped being true. + _last = []; + Volatile.Write(ref _lastError, ex.Message); + _log.LogWarning(ex, "NetblockWatcher: the scan failed; no candidates are offered."); + Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); + return _last; + } + + _last = candidates; + Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); + + if (raiseAlerts) + { + foreach (var candidate in candidates) + { + if (candidate.AlreadyBanned) continue; + if (_alerted.TryGetValue(candidate.Match, out var at) && now - at < AlertCooldown) continue; + _alerted[candidate.Match] = now; + await _alerts.RaiseAsync( + AlertKind, candidate.Match, candidate.Bans, null, null, + $"{candidate.Bans} live engine bans sit inside {candidate.Match}; " + + $"the oldest is from {candidate.FirstBanAt:u} and the newest from {candidate.LastBanAt:u}. " + + "Nothing was banned: POST /admin-api/blocks with this CIDR would replace those rows with one.", + ct); + } + } + + return candidates; + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/NetblockWatchTests.cs b/dotnet/OpenWaf.Tests.Integration/NetblockWatchTests.cs new file mode 100644 index 0000000..5a559fa --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/NetblockWatchTests.cs @@ -0,0 +1,338 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// The edge notices a netblock behind its bans and offers it as a range (OPEN-67). +/// +/// OPEN-66 made a range enforceable. This is the half that decides an operator +/// should write one: a scanner farm inside one /24 is twenty engine bans and +/// twenty operator decisions, and nothing in the edge connected them. +/// +/// The rulings these tests hold: +/// * the evidence is the edge's own live engine bans — an operator's row and an +/// expired ban are not evidence about a netblock; +/// * an offer is an offer: nothing here changes what the edge answers a visitor; +/// * the operator's decision closes the offer, and the surface says so; +/// * the thresholds are configuration, refused outside their bounds by name; +/// * reading the list is not news, so it raises no alert, and the same block is +/// not alerted about twice in a row. +/// +public sealed class NetblockWatchTests +{ + private const string Block = "203.0.113.0/24"; + private const string Inside = "203.0.113.1"; + + /// Seed N live engine bans inside one /24, the way the engine writes + /// them: keyed on the source, expiring in an hour. + private static async Task SeedEngineBansAsync(EdgeFixture f, params string[] keys) + { + var now = DateTimeOffset.UtcNow; + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var i = 0; + foreach (var key in keys) + { + db.Blocks.Add(new BlockEntry + { + SourceKey = key, + Source = BlockSource.Engine, + CreatedAt = now.AddMinutes(-20 + i), + ExpiresAt = now.AddHours(1), + Reason = "12 consecutive refusals 400-499 in 5 min" + }); + i++; + } + await db.SaveChangesAsync(); + } + + private static async Task NetblocksAsync(EdgeFixture f) + { + using var response = await f.Client.GetAsync($"/admin-api/netblocks?token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> PolicyAsync(EdgeFixture f, object body) + { + using var response = await f.Client.PutAsJsonAsync( + $"/admin-api/policy?token={EdgeFixture.AdminToken}", body); + return (response.StatusCode, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone()); + } + + [Fact] + public async Task The_edge_offers_the_block_its_own_bans_point_at() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, + "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14", + "198.51.100.9"); + + var body = await NetblocksAsync(f); + Assert.Equal(5, body.GetProperty("threshold").GetInt32()); + Assert.Equal(24, body.GetProperty("prefixV4").GetInt32()); + Assert.Equal("this-edge", body.GetProperty("scope").GetString()); + // The rules the numbers were produced with travel with them: a candidate + // count without its threshold is a number an operator cannot read. + var candidate = Assert.Single(body.GetProperty("netblocks").EnumerateArray()); + Assert.Equal(Block, candidate.GetProperty("match").GetString()); + // Five of the six bans, because the sixth is in another block: the offer + // is one block, not "the edge has been busy". + Assert.Equal(5, candidate.GetProperty("bans").GetInt32()); + Assert.False(candidate.GetProperty("alreadyBanned").GetBoolean()); + Assert.Equal(3, candidate.GetProperty("sample").GetArrayLength()); + Assert.Contains("203.0.113.10", candidate.GetProperty("sample").ToString()); + Assert.True(candidate.GetProperty("firstBanAt").GetDateTime() < candidate.GetProperty("lastBanAt").GetDateTime()); + } + + [Fact] + public async Task An_expired_ban_and_an_operators_row_are_not_evidence_about_a_netblock() + { + await using var f = new EdgeFixture(); + var now = DateTimeOffset.UtcNow; + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var key in new[] { "203.0.113.10", "203.0.113.11", "203.0.113.12" }) + db.Blocks.Add(new BlockEntry + { + SourceKey = key, Source = BlockSource.Engine, ExpiresAt = now.AddHours(1) + }); + // Ages out on its own: the edge stopped honouring it, so it says + // nothing about a block that is still worth banning. + db.Blocks.Add(new BlockEntry + { + SourceKey = "203.0.113.13", Source = BlockSource.Engine, ExpiresAt = now.AddMinutes(-5) + }); + // The operator's own row is a decision already taken, not a pattern + // the watch should offer back. + db.Blocks.Add(new BlockEntry { SourceKey = "203.0.113.14", Source = BlockSource.Operator }); + await db.SaveChangesAsync(); + } + + Assert.Empty((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); + } + + [Fact] + public async Task An_offer_changes_nothing_on_the_wire() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + + // The block is offered; the visitor inside it is still served. A watch + // that started enforcing on its own would be a ban nobody authorised. + using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Inside); + using var response = await f.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + using var preview = await f.Client.GetAsync( + $"/admin-api/decide?ip={Inside}&token={EdgeFixture.AdminToken}"); + var verdict = JsonDocument.Parse(await preview.Content.ReadAsStringAsync()).RootElement; + Assert.Equal("pass", verdict.GetProperty("verdict").GetString()); + } + + [Fact] + public async Task Banning_the_offered_range_closes_the_offer() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + + using (var block = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", + new { ip = Block, reason = "the netblock the edge noticed" })) + Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); + + var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); + Assert.True(candidate.GetProperty("alreadyBanned").GetBoolean()); + + // And the range is in force, which is the point of taking the offer. + using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Inside); + using var response = await f.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode); + } + + [Fact] + public async Task The_threshold_is_a_key_and_zero_is_the_watch_off() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12"); + + var (status, body) = await PolicyAsync(f, new { netblockCandidateBans = 3 }); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(3, body.GetProperty("netblockCandidateBans").GetInt32()); + Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); + + (status, body) = await PolicyAsync(f, new { netblockCandidateBans = 0 }); + Assert.Equal(HttpStatusCode.OK, status); + var off = await NetblocksAsync(f); + Assert.Equal(0, off.GetProperty("threshold").GetInt32()); + Assert.Empty(off.GetProperty("netblocks").EnumerateArray()); + Assert.Contains("off", off.GetProperty("note").GetString()); + } + + [Fact] + public async Task A_netblock_key_outside_its_bounds_is_refused_by_name() + { + await using var f = new EdgeFixture(); + + var (status, body) = await PolicyAsync(f, new { netblockPrefixV4 = 33 }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("netblockPrefixV4", body.GetProperty("error").GetString()); + Assert.Contains("8..31", body.GetProperty("error").GetString()); + + (status, body) = await PolicyAsync(f, new { netblockCandidateBans = -1 }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("netblockCandidateBans", body.GetProperty("error").GetString()); + + (status, body) = await PolicyAsync(f, new { netblockPrefixV6 = 7 }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("netblockPrefixV6", body.GetProperty("error").GetString()); + + // Nothing moved: a refused write leaves the policy the edge is running on + // exactly where it was. + var current = await PolicyAsync(f, new { }); + Assert.Equal(24, current.Body.GetProperty("netblockPrefixV4").GetInt32()); + Assert.Equal(5, current.Body.GetProperty("netblockCandidateBans").GetInt32()); + } + + [Fact] + public async Task A_wider_block_is_a_different_offer() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "198.51.100.12", "192.0.2.13", "203.0.114.14"); + + var (status, _) = await PolicyAsync(f, new { netblockPrefixV4 = 16, netblockCandidateBans = 3 }); + Assert.Equal(HttpStatusCode.OK, status); + + var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); + Assert.Equal("203.0.0.0/16", candidate.GetProperty("match").GetString()); + Assert.Equal(3, candidate.GetProperty("bans").GetInt32()); + } + + [Fact] + public async Task The_watch_raises_one_alert_per_block_rather_than_one_per_scan() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + + await f.Service().ScanAndAlertAsync(CancellationToken.None); + await f.Service().ScanAndAlertAsync(CancellationToken.None); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var alerts = await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync(); + + var alert = Assert.Single(alerts); + Assert.Equal(Block, alert.SourceKey); + Assert.Equal(5, alert.Count); + Assert.Contains("203.0.113.0/24", alert.Detail); + // The sentence the alert owes: nothing was banned, and the operator holds + // the call that would change that. + Assert.Contains("Nothing was banned", alert.Detail); + } + + [Fact] + public async Task Reading_the_list_is_not_news_and_raises_no_alert() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + + await NetblocksAsync(f); + await NetblocksAsync(f); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync()); + } + + [Fact] + public async Task A_block_the_operator_already_wrote_is_not_shouted_at_again() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + using (var block = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Block })) + Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); + + await f.Service().ScanAndAlertAsync(CancellationToken.None); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync()); + } + + [Fact] + public async Task The_state_says_whether_the_watch_ran_and_what_it_saw() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); + await f.Service().ScanAndAlertAsync(CancellationToken.None); + + using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}"); + var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; + + Assert.Equal(5, state.GetProperty("netblockCandidateBans").GetInt32()); + Assert.Equal(24, state.GetProperty("netblockPrefixV4").GetInt32()); + Assert.Equal(48, state.GetProperty("netblockPrefixV6").GetInt32()); + Assert.Equal(1, state.GetProperty("netblockCandidates").GetInt32()); + Assert.True(state.GetProperty("netblockLastScanAt").GetDateTime() > DateTimeOffset.UnixEpoch); + Assert.True(state.GetProperty("netblockScanError").ValueKind == JsonValueKind.Null); + } + + [Fact] + public async Task v6_bans_are_offered_one_allocation_up_from_the_key_they_are_stored_under() + { + await using var f = new EdgeFixture(); + await SeedEngineBansAsync(f, + "2001:db8:1:1::/64", "2001:db8:1:2::/64", "2001:db8:1:3::/64", "2001:db8:1:4::/64", "2001:db8:1:5::/64"); + + var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); + Assert.Equal("2001:db8:1::/48", candidate.GetProperty("match").GetString()); + Assert.Equal(5, candidate.GetProperty("bans").GetInt32()); + } + + [Fact] + public async Task A_change_to_a_netblock_key_is_recorded_like_any_other_policy_change() + { + await using var f = new EdgeFixture(); + await PolicyAsync(f, new { netblockCandidateBans = 2 }); + + using var response = await f.Client.GetAsync( + $"/admin-api/changes?section=policy&token={EdgeFixture.AdminToken}"); + var rows = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; + Assert.Contains("netblockCandidateBans 5->2", rows.ToString()); + } + + [Fact] + public async Task The_netblock_knobs_travel_with_the_operators_config() + { + await using var source = new EdgeFixture(); + await PolicyAsync(source, new { netblockCandidateBans = 2, netblockPrefixV4 = 20 }); + + using var export = await source.Client.GetAsync( + $"/admin-api/export?token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.OK, export.StatusCode); + var document = await export.Content.ReadAsStringAsync(); + Assert.Contains("netblockCandidateBans", document); + Assert.Contains("netblockPrefixV4", document); + + await using var target = new EdgeFixture(); + using var import = await target.Client.PostAsync( + $"/admin-api/import?token={EdgeFixture.AdminToken}", + new StringContent(document, Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.OK, import.StatusCode); + + var policy = await PolicyAsync(target, new { }); + Assert.Equal(2, policy.Body.GetProperty("netblockCandidateBans").GetInt32()); + Assert.Equal(20, policy.Body.GetProperty("netblockPrefixV4").GetInt32()); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/NetblockWatchTests.cs b/dotnet/OpenWaf.Tests.Unit/NetblockWatchTests.cs new file mode 100644 index 0000000..be070c4 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/NetblockWatchTests.cs @@ -0,0 +1,249 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// The netblock watch (OPEN-67): the edge's own live engine bans, grouped into +/// the block they all sit under, so the operator is offered one range instead of +/// twenty rows. +/// +/// The arithmetic lives in as pure functions, and these +/// tests are the whole reason it is pure: the claim "these bans are one network" +/// is exactly the kind of claim that is easy to write and easy to get wrong by +/// one bit. A candidate that is one address too wide bans the neighbours of the +/// attacker; a candidate that never appears leaves the operator counting rows by +/// hand. +/// +public sealed class NetblockWatchTests +{ + private static EdgePolicy Policy(int threshold = 3, int v4 = 24, int v6 = 48) => new() + { + NetblockCandidateBans = threshold, + NetblockPrefixV4 = v4, + NetblockPrefixV6 = v6 + }; + + private static IEnumerable<(string Key, DateTimeOffset CreatedAt)> Bans(params string[] keys) + { + var start = new DateTimeOffset(2026, 10, 5, 4, 0, 0, TimeSpan.Zero); + return keys.Select((k, i) => (k, start.AddMinutes(i))); + } + + private static readonly DateTimeOffset Now = new(2026, 10, 5, 5, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_block_with_enough_bans_inside_it_is_a_candidate() + { + var found = Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(), NetworkBanIndex.Empty, Now); + + var candidate = Assert.Single(found); + Assert.Equal("203.0.113.0/24", candidate.Match); + Assert.Equal(24, candidate.Prefix); + Assert.Equal(3, candidate.Bans); + Assert.False(candidate.AlreadyBanned); + } + + [Fact] + public void A_block_below_the_threshold_is_not_offered() + { + // Two bans in a /24 is two unrelated visitors of one hosting provider as + // often as it is a farm, and offering it would train the operator to + // ignore the table. + Assert.Empty(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11"), Policy(), NetworkBanIndex.Empty, Now)); + } + + [Fact] + public void Addresses_in_different_blocks_never_add_up_to_one_candidate() + { + Assert.Empty(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.114.12"), Policy(), NetworkBanIndex.Empty, Now)); + } + + [Fact] + public void A_threshold_of_zero_is_the_watch_off_rather_than_a_candidate_for_everything() + { + // 0 has to mean off. Read as "every block with zero or more bans", it + // would offer every /24 the edge has ever seen — the arithmetic version + // of a switch that is not there. + Assert.Empty(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(threshold: 0), + NetworkBanIndex.Empty, Now)); + } + + [Fact] + public void The_prefix_the_operator_set_is_the_block_the_candidate_is_written_as() + { + var found = Netblocks.Candidates( + Bans("198.51.100.17", "198.51.100.18", "198.51.100.19"), Policy(v4: 16), + NetworkBanIndex.Empty, Now); + Assert.Equal("198.51.0.0/16", Assert.Single(found).Match); + } + + [Fact] + public void A_ban_whose_own_key_is_a_wider_block_is_not_evidence_about_one_netblock() + { + // The edge can be configured to key a streak on a block (ipv4KeyPrefixLength). + // Counting one such ban as "one ban inside 203.0.113.0/24" would invent a + // candidate out of a row that already claims more than a /24. + Assert.Empty(Netblocks.Candidates( + Bans("203.0.113.0/8", "203.0.113.0/8", "203.0.113.0/8"), Policy(), NetworkBanIndex.Empty, Now)); + } + + [Fact] + public void A_key_that_names_no_address_is_skipped_rather_than_grouped() + { + // The "*" a /0 source key becomes is not inside any block. + Assert.Equal(-1, Netblocks.KeyPrefix("*")); + Assert.Empty(Netblocks.Candidates(Bans("*", "*", "*"), Policy(), NetworkBanIndex.Empty, Now)); + } + + [Fact] + public void v6_bans_are_grouped_one_allocation_up_from_the_key_they_are_stored_under() + { + // The streak key is already a /64, so grouping at /64 would only repeat + // the key. /48 is where a rotating v6 farm first looks like one thing. + var found = Netblocks.Candidates( + Bans("2001:db8:1:1::/64", "2001:db8:1:2::/64", "2001:db8:1:3::/64"), + Policy(), NetworkBanIndex.Empty, Now); + + Assert.Equal("2001:db8:1::/48", Assert.Single(found).Match); + } + + [Fact] + public void A_range_the_operator_already_wrote_is_said_rather_than_offered_again() + { + var ranges = new NetworkBanIndex(new[] + { + new NetworkBan { Match = "203.0.113.0/24", CreatedAt = Now.AddDays(-1) } + }); + + var candidate = Assert.Single(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(), ranges, Now)); + Assert.True(candidate.AlreadyBanned); + } + + [Fact] + public void A_narrower_range_does_not_cover_the_block_it_sits_inside() + { + var ranges = new NetworkBanIndex(new[] + { + new NetworkBan { Match = "203.0.113.16/28", CreatedAt = Now.AddDays(-1) } + }); + + var candidate = Assert.Single(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(), ranges, Now)); + Assert.False(candidate.AlreadyBanned); + } + + [Fact] + public void A_broader_range_covers_the_block_and_closes_the_offer() + { + var ranges = new NetworkBanIndex(new[] + { + new NetworkBan { Match = "203.0.0.0/16", CreatedAt = Now.AddDays(-1) } + }); + + var candidate = Assert.Single(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(), ranges, Now)); + Assert.True(candidate.AlreadyBanned); + } + + [Fact] + public void The_oldest_and_newest_ban_of_a_block_travel_with_the_count() + { + var candidate = Assert.Single(Netblocks.Candidates( + Bans("203.0.113.10", "203.0.113.11", "203.0.113.12"), Policy(), NetworkBanIndex.Empty, Now)); + + Assert.Equal(new DateTimeOffset(2026, 10, 5, 4, 0, 0, TimeSpan.Zero), candidate.FirstBanAt); + Assert.Equal(new DateTimeOffset(2026, 10, 5, 4, 2, 0, TimeSpan.Zero), candidate.LastBanAt); + } + + [Fact] + public void The_sample_shows_a_few_of_the_bans_and_not_the_whole_block() + { + var keys = Enumerable.Range(10, 12).Select(i => $"203.0.113.{i}").ToArray(); + var candidate = Assert.Single(Netblocks.Candidates(Bans(keys), Policy(), NetworkBanIndex.Empty, Now)); + + Assert.Equal(12, candidate.Bans); + Assert.Equal(Netblocks.SampleSize, candidate.Sample.Count); + Assert.Contains("203.0.113.10", candidate.Sample); + } + + [Fact] + public void The_widest_farm_is_offered_first() + { + var keys = new List(); + keys.AddRange(Enumerable.Range(10, 5).Select(i => $"203.0.113.{i}")); + keys.AddRange(Enumerable.Range(20, 4).Select(i => $"198.51.100.{i}")); + + var found = Netblocks.Candidates(Bans(keys.ToArray()), Policy(), NetworkBanIndex.Empty, Now); + + Assert.Equal(2, found.Count); + Assert.Equal("203.0.113.0/24", found[0].Match); + Assert.Equal(5, found[0].Bans); + Assert.Equal("198.51.100.0/24", found[1].Match); + } + + [Fact] + public void The_block_a_ban_sits_under_is_the_block_the_block_form_takes() + { + // The string on the surface has to be the string POST /admin-api/blocks + // accepts, or the offer and the control disagree. + var match = Netblocks.Covering("203.0.113.137", Policy()); + Assert.Equal("203.0.113.128/25", Netblocks.Covering("203.0.113.137", Policy(v4: 25))); + Assert.Equal("203.0.113.0/24", match); + Assert.True(NetworkBans.TryNormalize(match, out var normalized, out _)); + Assert.Equal(match, normalized); + } + + [Fact] + public void The_prefix_a_ban_key_names_is_the_prefix_it_was_written_with() + { + Assert.Equal(32, Netblocks.KeyPrefix("203.0.113.10")); + Assert.Equal(64, Netblocks.KeyPrefix("2001:db8:1:2::/64")); + Assert.Equal(24, Netblocks.KeyPrefix("198.51.100.0/24")); + Assert.Equal(-1, Netblocks.KeyPrefix("not-an-address")); + Assert.Equal(-1, Netblocks.KeyPrefix(null)); + } + + [Fact] + public void The_defaults_are_the_allocation_sizes_this_project_assumes() + { + var policy = new EdgePolicy(); + Assert.Equal(5, policy.NetblockCandidateBans); + Assert.Equal(24, policy.NetblockPrefixV4); + Assert.Equal(48, policy.NetblockPrefixV6); + } + + [Fact] + public void The_bounds_refuse_a_block_that_is_most_of_the_address_space() + { + Assert.True(PolicyBounds.NetblockCandidateBansOk(0)); + Assert.False(PolicyBounds.NetblockCandidateBansOk(-1)); + Assert.False(PolicyBounds.NetblockCandidateBansOk(PolicyBounds.NetblockCandidateBansMax + 1)); + + // /8 is the floor and /0 is not: banning the floor is already a stretch, + // and banning below it is a shutdown dressed as a range — the same reason + // the block form itself refuses 0.0.0.0/0. + Assert.True(PolicyBounds.NetblockPrefixV4Ok(PolicyBounds.NetblockPrefixV4Min)); + Assert.False(PolicyBounds.NetblockPrefixV4Ok(0)); + Assert.False(PolicyBounds.NetblockPrefixV4Ok(32)); + Assert.True(PolicyBounds.NetblockPrefixV6Ok(PolicyBounds.NetblockPrefixV6Min)); + Assert.False(PolicyBounds.NetblockPrefixV6Ok(128)); + } + + [Fact] + public void A_stored_override_outside_the_bounds_is_named_rather_than_obeyed() + { + Assert.True(PolicyBounds.ValueOk("netblockCandidateBans", "0")); + Assert.False(PolicyBounds.ValueOk("netblockCandidateBans", "-3")); + Assert.True(PolicyBounds.ValueOk("netblockPrefixV4", "22")); + Assert.False(PolicyBounds.ValueOk("netblockPrefixV4", "33")); + Assert.False(PolicyBounds.ValueOk("netblockPrefixV6", "not-a-prefix")); + Assert.Contains("..", PolicyBounds.RangeOf("netblockPrefixV4")); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index baeaced..7200a24 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1651,6 +1651,50 @@ check 'the range is removable by its name, so the volume stays clean' '404' \ "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \ "$EDGE/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \ code -H "X-Forwarded-For: $RANGE_INSIDE" "$EDGE/anything")" +echo '- the shipped edge notices a netblock behind its bans' +# The watch (OPEN-67) on the deployed image: the edge groups its own live engine +# bans into the block they sit under and offers that block, and taking the offer +# is the same call as any other block. Aligned base chosen per run, so a row the +# named volume kept from an earlier run cannot answer for this one. +NET_BASE=$(( 192 + (RANDOM % 4) * 4 )) +NET_A="203.0.113.$NET_BASE" +NET_B="203.0.113.$(( NET_BASE + 1 ))" +NET_FRESH="203.0.113.$(( NET_BASE + 2 ))" +NET_RANGE="203.0.113.0/24" +NET_ON_JSON="{\"streakThreshold\":2,\"netblockCandidateBans\":2}" +NET_OFF_JSON="{\"streakThreshold\":10,\"netblockCandidateBans\":0}" +NET_RANGE_JSON="{\"ip\":\"$NET_RANGE\",\"reason\":\"the netblock the shipped edge noticed\"}" +check 'the watch threshold is a policy key on the shipped image' '2' \ + "$(admin -X PUT -H 'Content-Type: application/json' --data-binary "$NET_ON_JSON" \ + "$EDGE/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["netblockCandidateBans"])')" +# The named volume outlives the run, and an engine ban an earlier scene wrote +# inside this /24 would be counted by the watch as evidence. Clearing the +# engine's list first is what makes the count below this scene's own. +admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null +for src in "$NET_A" "$NET_B"; do + code -H "X-Forwarded-For: $src" "$EDGE/anything" >/dev/null + code -H "X-Forwarded-For: $src" "$EDGE/anything" >/dev/null +done +check 'the shipped edge offers the block its bans sit inside' "$NET_RANGE" \ + "$(admin "$EDGE/admin-api/netblocks" | python3 -c "import sys,json;print(next((n['match'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'), 'none'))")" +check 'the offer counts only the bans inside that block' '2' \ + "$(admin "$EDGE/admin-api/netblocks" | python3 -c "import sys,json;print(next(n['bans'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'))")" +check 'an offer is not a ban: a fresh source inside it is served' '404' \ + "$(code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")" +check 'the shipped edge takes the offer with the block form' '204' \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$NET_RANGE_JSON" "$EDGE/admin-api/blocks")" +check 'the taken range refuses a source the engine never saw' '301' \ + "$(code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")" +check 'the shipped state says what the watch is running on' 'yes' \ + "$(admin "$EDGE/admin-api/state" | python3 -c "import sys,json;d=json.load(sys.stdin);print('yes' if d.get('netblockCandidateBans')==2 and d.get('netblockPrefixV4')==24 and d.get('netblockScanError') is None else 'no')")" +check 'the range and the bans that produced it are cleaned, so the volume stays clean' '404' \ + "$(admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$NET_RANGE" >/dev/null; \ + admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null; \ + admin -X PUT -H 'Content-Type: application/json' --data-binary "$NET_OFF_JSON" \ + "$EDGE/admin-api/policy" >/dev/null; \ + code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 2bd0449..14004a3 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -410,6 +410,69 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); && rangeWire2.status === 404, `probe from ${RANGE_INSIDE} answered ${rangeWire2.status}`); + // --- the netblock watch (OPEN-67) ----------------------------------------- + // The seed wrote two engine bans inside one /24 and set the watch threshold to + // two, so the offer asserted here is this run's and not a residue of the named + // volume. The point of the scene is the difference between an offer and a ban: + // the block is on the page, nothing is enforced, one button changes that, and + // the change is the same call the block form makes. + const NETBLOCK = process.env.SEED_NETBLOCK || '192.0.2.0/24'; + const NET_FRESH = process.env.SEED_NETBLOCK_FRESH || '192.0.2.203'; + + const netRows = await cells('#netblocks tbody tr'); + const offered = netRows.find((r) => (r[0] || '').startsWith(NETBLOCK)); + check('the page offers the block the edge points at by its own bans', + !!offered, JSON.stringify(netRows.map((r) => r[0]))); + check('the offer says how many bans sit inside that block', + !!offered && Number(offered[1]) >= 2, offered ? offered[1] : 'no row'); + const netNote = (await page.textContent('#netblocknote')).replace(/\s+/g, ' ').trim(); + check('the page says an offer is not a ban', + /nothing here is in force|a candidate is an offer, not a ban/.test(netNote), netNote); + const beforeTaken = await probe(NET_FRESH); + check('an address inside the offered block is still served', + beforeTaken.status === 404, `probe from ${NET_FRESH} answered ${beforeTaken.status}`); + + await page.click(`#netblocks tbody button[data-act="banrange"][data-k="${NETBLOCK}"]`); + await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody tr')] + .some((tr) => tr.children[0].textContent.startsWith(net) && /range/.test(tr.children[0].textContent)), + NETBLOCK, { timeout: 15000 }).catch(() => {}); + const blocksAfterOffer = await cells('#blocks tbody tr'); + check('one button writes the offered range through the same block form', + blocksAfterOffer.some((r) => r[0].startsWith(NETBLOCK) && /range/.test(r[0]) + && /netblock the edge noticed/.test(r[2] || '')), + JSON.stringify(blocksAfterOffer.filter((r) => r[0].startsWith(NETBLOCK)).map((r) => [r[0], r[2]]))); + + const netRowsAfter = await cells('#netblocks tbody tr'); + const offeredAfter = netRowsAfter.find((r) => (r[0] || '').startsWith(NETBLOCK)); + check('the offer is then marked taken rather than repeated', + !!offeredAfter && /already banned/.test(offeredAfter.join(' ')), JSON.stringify(offeredAfter)); + + let takenWire = await probe(NET_FRESH); + for (let i = 0; i < 10 && takenWire.status === 404; i++) { + await new Promise((r) => setTimeout(r, 1000)); takenWire = await probe(NET_FRESH); + } + check('the range the page took is enforced on the wire for a source inside it', + takenWire.status === 301 || takenWire.status === 403, + `probe from ${NET_FRESH} answered ${takenWire.status}`); + const pillsAfterOffer = await page.$$eval('#summary .pill', (els) => els.map((e) => e.textContent.trim())); + check('the summary counts the offers apart from what is in force', + pillsAfterOffer.some((p) => /^netblock offers \d+$/.test(p)), JSON.stringify(pillsAfterOffer)); + + // Clean up: the range, and the engine bans that produced it, so the scenes + // after this one run on the stack they expect. + const adminDelete = async (path) => { + const r = await fetch(`${EDGE}${path}`, { method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } }); + await r.body.cancel(); + }; + await adminDelete(`/admin-api/blocks?source=operator&key=${encodeURIComponent(NETBLOCK)}`); + await adminDelete('/admin-api/blocks?source=engine'); + let cleanedWire = await probe(NET_FRESH); + for (let i = 0; i < 10 && cleanedWire.status !== 404; i++) { + await new Promise((r) => setTimeout(r, 1000)); cleanedWire = await probe(NET_FRESH); + } + check('the range and the bans that produced it are cleaned, so the stack stays clean', + cleanedWire.status === 404, `probe from ${NET_FRESH} answered ${cleanedWire.status}`); + await page.fill('#allowMatch', WRITE_CIDR); await page.fill('#allowNote', 'console gate: allow entry'); diff --git a/scripts/console-smoke.sh b/scripts/console-smoke.sh index cb74196..0f6b8de 100755 --- a/scripts/console-smoke.sh +++ b/scripts/console-smoke.sh @@ -28,7 +28,7 @@ SEED_ERROR="203.0.113.$(( 140 + RANDOM % 60 ))" # still in the table, the edge stopped honouring it a minute ago. Chosen per run, # so a leftover row in the data volume cannot satisfy the assertion. SEED_EXPIRED_CIDR="203.0.113.$(( 240 + RANDOM % 10 ))/32" -export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK SEED_EXPIRED_CIDR +export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK SEED_EXPIRED_CIDR SEED_NETBLOCK SEED_NETBLOCK_FRESH admin() { curl -s -m 10 -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; } @@ -108,6 +108,19 @@ admin -X POST -H 'Content-Type: application/json' \ -d "{\"ip\":\"$SEED_MARKUP_BLOCK\",\"reason\":\" probe\"}" \ "$EDGE/admin-api/blocks" >/dev/null +# The netblock watch (OPEN-67): two engine bans inside one /24, produced the only +# way they can be produced — by traffic — and the watch threshold lowered to two, +# so that two of them are a candidate. The block is TEST-NET-1 rather than the +# /24 the rest of this gate probes, because taking the offer means banning a +# whole block for the length of the scene. +SEED_NETBLOCK=192.0.2.0/24 +SEED_NETBLOCK_FRESH=192.0.2.203 +curl -s -X PUT -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + -d '{"netblockCandidateBans":2}' "$EDGE/admin-api/policy" >/dev/null +for src in 192.0.2.201 192.0.2.202; do + for _ in 1 2 3; do curl -s -o /dev/null -H "X-Forwarded-For: $src" "$EDGE/probe"; done +done + # An alert the page must show. /boom answers 502 (deploy/upstream.conf), and this # gate already set the threshold to 3, so four of them from one address write # server_error_streak rows. The alert is written after the response is, hence the @@ -129,8 +142,8 @@ if [ "${SEED_ONLY:-0}" = 1 ]; then # page in a browser image), so it cannot inherit these values. Writing them out # is what keeps the alert assertion honest: SEED_ERROR is chosen per run, and an # empty one on the driver side would silently weaken the check to "any alert". - printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\nSEED_EXPIRED_CIDR=%s\n' \ - "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" "$SEED_EXPIRED_CIDR" > "${SEED_FILE:-console-seed.env}" + printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\nSEED_EXPIRED_CIDR=%s\nSEED_NETBLOCK=%s\nSEED_NETBLOCK_FRESH=%s\n' \ + "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" "$SEED_EXPIRED_CIDR" "$SEED_NETBLOCK" "$SEED_NETBLOCK_FRESH" > "${SEED_FILE:-console-seed.env}" echo "- SEED_ONLY=1: stack is up and seeded at $EDGE; seed values in ${SEED_FILE:-console-seed.env}" trap - EXIT exit 0 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index fb60e1b..a351174 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -595,6 +595,67 @@ check 'and the range is removable by its name' 404 \ "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \ code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")" +echo '- the edge notices a netblock behind its bans' +# The watch (OPEN-67): the edge groups its own live engine bans into the block +# they sit under and offers that block to the operator. The bans are produced the +# only way they can be produced — by traffic — and the ban window is widened for +# the scene, because this edge runs a six-second sentence and a scan that arrives +# after it would be reading rows that are no longer live. +NET_A=203.0.113.201 +NET_B=203.0.113.202 +NET_FRESH=203.0.113.203 +NET_RANGE=203.0.113.0/24 +NET_ON_JSON='{"streakThreshold":2,"netblockCandidateBans":2,"banDurationMinutes":5}' +NET_OFF_JSON='{"streakThreshold":3,"netblockCandidateBans":0,"banDurationMinutes":0.01}' +NET_RANGE_JSON='{"ip":"203.0.113.0/24","reason":"the netblock the edge noticed"}' +check 'the watch threshold is a policy key' 2 \ + "$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$NET_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \ + | python3 -c 'import sys,json;print(json.load(sys.stdin)["netblockCandidateBans"])')" +check 'a netblock prefix outside its bounds is refused by name' yes \ + "$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d '{"netblockPrefixV4":33}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \ + | grep -q 'netblockPrefixV4 must be 8..31' && echo yes || echo no)" +for src in "$NET_A" "$NET_B"; do + code -H "X-Forwarded-For: $src" "$(from wp-admin)" >/dev/null + code -H "X-Forwarded-For: $src" "$(from wp-admin)" >/dev/null +done +check 'the two bans the edge wrote are inside one block' 2 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \ + | python3 -c "import sys,json;print(len([b for b in json.load(sys.stdin) if b['sourceKey'].startswith('203.0.113.2')]))")" +check 'the edge offers that block as a range' "$NET_RANGE" \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \ + | python3 -c "import sys,json;print(next(n['match'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'))")" +check 'and it says how many bans sit inside it' 2 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \ + | python3 -c "import sys,json;print(next(n['bans'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'))")" +check 'an offer is not a ban: a fresh address inside it is served' 404 \ + "$(code -H "X-Forwarded-For: $NET_FRESH" "$(from wp-admin)")" +check 'the operator takes the offer with the same call as any other block' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$NET_RANGE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" +check 'the offer is then marked taken rather than repeated' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \ + | python3 -c "import sys,json;print('yes' if next(n['alreadyBanned'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE') else 'no')")" +check 'the taken range refuses a source the engine never saw' 301 \ + "$(code -H "X-Forwarded-For: $NET_FRESH" "$(from wp-admin)")" +check 'and it answers ahead of the engine ban it replaces' 301 \ + "$(code -H "X-Forwarded-For: $NET_A" "$(from wp-admin)")" +check 'the state says the watch ran and what it saw' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \ + | python3 -c "import sys,json;d=json.load(sys.stdin);print('yes' if d['netblockCandidateBans']==2 and d['netblockPrefixV4']==24 and d['netblockScanError'] is None else 'no')")" +# Clean up: the range, the bans that produced it, and the policy the rest of the +# gate runs on. +curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$NET_RANGE" >/dev/null +curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" >/dev/null +curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$NET_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null +check 'the watch is off again and offers nothing' 0 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \ + | python3 -c 'import sys,json;print(len(json.load(sys.stdin)["netblocks"]))')" + echo '- admin surface' check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" check 'the policy is readable' Enforce \