Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs
T
Pavlo Ratushnyi dd10dd9839 the edge notices the netblock behind its bans and offers it as a range
A scanner farm inside one /24 is twenty engine bans and twenty operator
decisions: the streak rule works per source, and nothing in the edge connected
the rows. OPEN-66 made a range enforceable; this is the half that notices the
range is there.

The rulings:

- The evidence is the edge's own live engine 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
  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 tells them
  apart.
- Grouping is one allocation up from the key: v4 to /24, v6 to /48, because the
  v6 streak key is already a /64 and grouping there would only repeat the key.
  The count and both prefixes are policy keys with bounds, because a host that
  hands out /22s should be shown the block it can act on.
- A ban keyed on a block wider than the netblock prefix is skipped: that row
  already claims more than a /24, and counting it as one ban inside a /24 would
  invent a candidate out of it.
- 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 never for a
  block the operator has already banned.
- A failed scan retires the offers instead of repeating the last ones, and
  /admin-api/state says which of off / failed / found-nothing this is.

What the run caught:

- The console's "ban this range" button posted a body with no content type, and
  the edge refused it: the button did nothing and the page looked idle rather
  than wrong. It uses the page's own postJson now, and the console gate asserts
  the row it writes, the wire answer for a source inside it, and the offer
  turning into "already banned".
- The grouping parsed ban keys with SourceKey.TryParse, which fails on the
  "2001:db8:1:2::/64" spelling the engine stores v6 bans under — so no v6 ban
  was ever grouped. Keys are parsed as keys, prefix included.
- An assertion claimed 203.0.113.137 sits under 203.0.113.128/24. That is a /25:
  the arithmetic was wrong in the test, not in the mask.

build 0 warnings / 0 errors, unit 353/353, integration 326/326 in 31 s, console
114 assertions 0 failed, smoke passed 149 failed 0, compose 293 passed 0 failed
against the built image at 262 MB.

Refs OPEN-67.
2026-10-05 07:55:06 +02:00

166 lines
7.2 KiB
C#

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;
/// <summary>
/// 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 <see cref="Netblocks"/> where the
/// unit tests can reach them.
/// </summary>
public sealed class NetblockWatcher : BackgroundService
{
/// <summary>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.</summary>
public const string AlertKind = "netblock_candidate";
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5);
/// <summary>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.</summary>
private static readonly TimeSpan AlertCooldown = TimeSpan.FromHours(6);
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly AlertWriter _alerts;
private readonly ILogger<NetblockWatcher> _log;
private readonly ConcurrentDictionary<string, DateTimeOffset> _alerted = new(StringComparer.Ordinal);
private long _lastScanTicks;
private IReadOnlyList<NetblockCandidate> _last = [];
private string? _lastError;
public NetblockWatcher(
IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, AlertWriter alerts,
ILogger<NetblockWatcher> log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_alerts = alerts;
_log = log;
}
/// <summary>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.</summary>
public DateTimeOffset LastScanAt => new(Interlocked.Read(ref _lastScanTicks), TimeSpan.Zero);
/// <summary>The last scan's answer, without running one. Cheap enough for a
/// status surface that is scraped more often than anyone reads it.</summary>
public IReadOnlyList<NetblockCandidate> 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."); }
}
}
/// <summary>One scan. <paramref name="raiseAlerts"/> 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.</summary>
public async Task<IReadOnlyList<NetblockCandidate>> ScanAndAlertAsync(CancellationToken ct)
=> await ScanAsync(true, ct);
public async Task<IReadOnlyList<NetblockCandidate>> 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<NetblockCandidate> candidates;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
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;
}
}