The streak engine raised an alert on every response once the count was past the threshold, and neither condition ends on its own: a 5xx never bans, and in Observe mode nothing bans at all, so the source stays observable on every request. Measured on the shipped image in the compose gate: 12 upstream 502s at N=3 wrote 10 alert rows, and 11 refusals in a dry run wrote 9. That is attacker-shaped growth kept for the whole retention window, and the operator's alert list (newest 100 in the console, limit=500 on the endpoint) showed one source and nothing else. Both kinds are now edge-triggered: one row on the crossing, then one per doubling. Same two measurements answer 3 and 2. A gap past the window or a clean answer ends the episode, so the next outage announces itself again — alerting once per source per process would hide an outage that got ten times worse while nobody was looking. Teeth, measured rather than asserted: with IsEscalation forced to the old level-triggered answer, exactly the four new unit tests and the two new integration tests fail, and the compose gate reports 10 and 9 and fails those two checks; the other 41 compose checks stay green. Gates on this commit — host (macOS): build 0 warnings, unit 58/58, integration 32/32, smoke 19/19, image 261 MB, compose-smoke 43/43. Linux rehearsal (scripts/ci-linux-rehearsal.sh): source, compose and console gates all PASS, exit 0.
150 lines
6.8 KiB
C#
150 lines
6.8 KiB
C#
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Infrastructure.Geo;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Edge.Pipeline;
|
|
|
|
/// <summary>
|
|
/// Runs after the guard, awaits the upstream, and classifies what the
|
|
/// application actually answered. This is the seam the reference repo already
|
|
/// established in <c>SuspiciousHitTrackerMiddleware</c> — inspect the status
|
|
/// after the pipeline, not before it — widened from "one status code" to a
|
|
/// configurable predicate plus a streak.
|
|
///
|
|
/// Being inside the guard is load-bearing in two directions:
|
|
/// * a request the guard already refused is not observed, so a ban can never
|
|
/// feed its own streak (a 403 we generate would otherwise re-ban forever);
|
|
/// * the status it sees is the upstream's, which is the whole signal.
|
|
///
|
|
/// Nothing here blocks. It records, and the only durable consequence is a ban
|
|
/// row written once, out of band, when a streak matures.
|
|
/// </summary>
|
|
public sealed class ResponseObservationMiddleware(
|
|
RequestDelegate next,
|
|
EdgeStateStore state,
|
|
StreakTracker tracker,
|
|
BlockStore blocks,
|
|
AlertWriter alerts,
|
|
IGeoIpLookup geo,
|
|
ILogger<ResponseObservationMiddleware> log)
|
|
{
|
|
public async Task InvokeAsync(HttpContext ctx)
|
|
{
|
|
await next(ctx);
|
|
|
|
var snapshot = state.Current;
|
|
var policy = snapshot.Policy;
|
|
if (policy.Mode == EnforcementMode.Off && policy.Geo == GeoMode.Off) return;
|
|
|
|
var status = ctx.Response.StatusCode;
|
|
var responseClass = ResponseClassifier.Classify(status, policy);
|
|
if (responseClass == ResponseClass.Neutral)
|
|
{
|
|
// A clean answer is the end of a run of refusals, and the tracker
|
|
// only knows that if it is told. Returning here — which is what this
|
|
// used to do — left the documented mitigation ("one honest click
|
|
// resets it", README) unenforced end to end: a visitor alternating
|
|
// 404 and a normal page view accumulated refusals across every
|
|
// honest request and still got banned. The reset is the only thing
|
|
// done for a 2xx: no evidence is built, so no MMDB read is paid.
|
|
var neutralIp = ClientIp.Resolve(ctx, policy.TrustProxyHeaders);
|
|
if (string.IsNullOrWhiteSpace(neutralIp)) return;
|
|
tracker.ResetIfTracked(SourceKey.For(neutralIp, policy));
|
|
return;
|
|
}
|
|
|
|
var ip = ClientIp.Resolve(ctx, policy.TrustProxyHeaders);
|
|
if (string.IsNullOrWhiteSpace(ip)) return;
|
|
|
|
var key = SourceKey.For(ip, policy);
|
|
if (key.Length == 0) return;
|
|
|
|
var path = ctx.Request.Path.Value ?? string.Empty;
|
|
|
|
// The always-pass surface is also never observed. The guard lets an
|
|
// operator through to the admin API even from a blocked address; if a
|
|
// mistyped admin call still counted as a refusal, the operator would
|
|
// ban themselves with a syntax error — the one failure mode a recovery
|
|
// hatch must not have.
|
|
if (DecisionEngine.IsAlwaysPass(path, policy)) return;
|
|
|
|
var evidence = BuildEvidence(ctx, ip, responseClass);
|
|
|
|
var outcome = tracker.Observe(key, status, responseClass, policy, DateTimeOffset.UtcNow, evidence);
|
|
|
|
if (outcome.AlertTriggered)
|
|
{
|
|
log.LogWarning(
|
|
"edge: {Count} consecutive server errors from {Key} (last {Status} {Path}) — alerting, not banning",
|
|
outcome.ConsecutiveServerErrors, key, status, path);
|
|
|
|
await alerts.RaiseAsync(
|
|
"server_error_streak", key, outcome.ConsecutiveServerErrors, status, path,
|
|
$"{outcome.ConsecutiveServerErrors} consecutive responses in {policy.ServerErrorRange} " +
|
|
$"within {policy.StreakWindow.TotalMinutes:0.#} min. Server errors never ban: a broken deploy " +
|
|
$"must not lock out the site's own visitors.");
|
|
}
|
|
|
|
if (!outcome.BanTriggered) return;
|
|
|
|
var streak = tracker.Peek(key);
|
|
if (streak is null) return;
|
|
|
|
if (policy.Mode == EnforcementMode.Observe)
|
|
{
|
|
// Dry run: the decision is recorded so an operator can judge the
|
|
// rule before it is allowed to act, but nothing is blocked.
|
|
//
|
|
// Gated on BanAlertDue, not BanTriggered. BanTriggered is true on
|
|
// every response once the threshold is behind it, and in Observe
|
|
// mode nothing ever blocks, so the source keeps being observed:
|
|
// raising on that flag made the dry run write one alert row per
|
|
// request, which turns the safest mode into the one an attacker
|
|
// can use to grow the operator's alert table at request rate.
|
|
if (!outcome.BanAlertDue) return;
|
|
|
|
await alerts.RaiseAsync(
|
|
"candidate_ban", key, outcome.ConsecutiveRefusals, status, path,
|
|
$"would ban for {policy.BanDuration.TotalMinutes:0.#} min at N={policy.StreakThreshold} " +
|
|
$"within {policy.StreakWindow.TotalMinutes:0.#} min (mode=Observe, not enforced)");
|
|
return;
|
|
}
|
|
|
|
// Deliberately not ctx.RequestAborted: this runs after the response
|
|
// has been written, so the client is free to hang up at any moment and
|
|
// a cancelled token would silently drop the ban — the request that
|
|
// proves the source is abusive would be the one that fails to record
|
|
// it. The write is bounded by the database, not by the visitor.
|
|
var ban = await blocks.BanAsync(streak, status, DateTimeOffset.UtcNow);
|
|
if (ban is not null)
|
|
{
|
|
log.LogWarning("edge: banned {Key} until {Until} — {Reason}", key, ban.ExpiresAt, ban.Reason);
|
|
}
|
|
}
|
|
|
|
/// <summary>Geo is resolved only for responses that mean something, so an
|
|
/// MMDB read is not paid on every 200.</summary>
|
|
private RequestEvidence BuildEvidence(HttpContext ctx, string ip, ResponseClass responseClass)
|
|
{
|
|
_ = responseClass;
|
|
var headerCountry = ClientIp.HeaderCountry(ctx);
|
|
var detail = headerCountry is null ? geo.LookupDetail(ip) : new GeoIpResult(headerCountry, null, null);
|
|
if (headerCountry is not null && detail.City is null)
|
|
{
|
|
var local = geo.LookupDetail(ip);
|
|
detail = detail with { City = local.City, Region = local.Region };
|
|
}
|
|
|
|
return new RequestEvidence(
|
|
Truncate(ctx.Request.Path.Value, 512),
|
|
Truncate(ctx.Request.Headers.UserAgent.ToString(), 256),
|
|
detail.CountryCode,
|
|
Truncate(detail.City, 128),
|
|
Truncate(detail.Region, 128));
|
|
}
|
|
|
|
private static string? Truncate(string? value, int max)
|
|
=> string.IsNullOrEmpty(value) ? null : (value.Length <= max ? value : value[..max]);
|
|
}
|