The admin API answered 200 to anything. Measured on the shipped image
(openwaf:ci) before this commit:
PUT {"streakThreshold":0} -> 200, streakThreshold still 3, 0 log lines
PUT {"maxTrackedSources":0} -> 200, unchanged
PUT {"banDurationMinutes":-1} -> 200, unchanged
PUT {"streakWindowMinutes":0} -> 200, unchanged
PUT {"refusalRange":"not-a-range"} -> 200, unchanged
PUT {"engineBlockStatus":999} -> 200, and the edge answered HTTP/1.1 999
PUT {"engineBlockStatus":1000} -> 200, and every banned request died as
"curl: (1) Unsupported HTTP/1 subversion
in response" — no HTTP response at all
PUT {"ipv4KeyPrefixLength":0} -> 200, one 404 banned the key "*", and the
next three never-seen addresses were
refused on their first request
PUT {"ipv4KeyPrefixLength":999} -> 200, GET echoed 999, enforcement used 32
Two different failures hid behind that 200. A value the code did not want was
dropped without a word, so the operator read "OK" over a policy that had not
moved. A value the code did want was stored and obeyed literally, and one of
those (engineBlockStatus=1000) takes the site down for every banned visitor
from one admin call.
So the ranges now live in one place, PolicyBounds, next to the reason for each
one, and three layers read it:
* the admin endpoint answers 400 naming the key and the range — the same
shape mode, geo and the state TTL already used;
* the loader ignores a row outside the range and logs the key and the value,
for a backup restored or a row edited by hand;
* DecisionEngine refuses to put an unsendable status on the wire at all, and
answers 403 instead.
ipv4KeyPrefixLength keeps a floor of 8 rather than 0, because 0 is not a coarse
grouping, it is the literal key "*" — one streak and one ban shared by every
IPv4 address on the internet.
Tests: 46 unit (the bounds table, the "*" mechanism, the wire guard) and 18
integration (400 by name, a refused write changing nothing, an accepted value
reaching the wire as 451, a hand-edited row ignored). Teeth, each measured by
removing the layer: no API validation -> 16 integration tests fail; no wire
guard -> 3 unit tests fail; no loader gate -> 1 integration test fails.
120 lines
5.0 KiB
C#
120 lines
5.0 KiB
C#
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Domain.Engine;
|
|
|
|
/// <summary>
|
|
/// The single ordered decision point (architecture decision, OPEN-2).
|
|
///
|
|
/// Order is a documented property, not a side effect of middleware
|
|
/// registration:
|
|
/// 1. always-pass prefixes — an operator who blocked their own address must
|
|
/// still be able to reach the admin API and undo it;
|
|
/// 2. allowlist — the exemption path, evaluated on the raw
|
|
/// address so a CIDR means what the operator wrote;
|
|
/// 3. operator block — the human's list, which the toggle cannot
|
|
/// switch off;
|
|
/// 4. engine ban — enforced only in <see cref="EnforcementMode.Enforce"/>;
|
|
/// 5. geo policy — last, so an allowlisted operator inside a
|
|
/// denied country gets one defined answer: through.
|
|
///
|
|
/// Pure function over an <see cref="EdgeSnapshot"/>. No I/O, no clock of its
|
|
/// own — <c>now</c> is passed in, which is what makes the expiry and streak
|
|
/// rules testable without waiting.
|
|
/// </summary>
|
|
public static class DecisionEngine
|
|
{
|
|
public static EdgeDecision Decide(
|
|
EdgeSnapshot snapshot,
|
|
string? clientIp,
|
|
string path,
|
|
DateTimeOffset now,
|
|
string? countryCode = null)
|
|
{
|
|
var policy = snapshot.Policy;
|
|
|
|
if (IsAlwaysPass(path, policy)) return new EdgeDecision(EdgeVerdict.PassBypassed);
|
|
|
|
if (string.IsNullOrWhiteSpace(clientIp)) return EdgeDecision.Pass;
|
|
|
|
foreach (var entry in snapshot.AllowEntries)
|
|
{
|
|
if (!entry.IsLive(now)) continue;
|
|
if (NetworkMatch.Matches(clientIp, entry.Match))
|
|
{
|
|
return new EdgeDecision(EdgeVerdict.PassAllowlisted, Reason: entry.Note);
|
|
}
|
|
}
|
|
|
|
var key = SourceKey.For(clientIp, policy);
|
|
if (key.Length == 0) return EdgeDecision.Pass;
|
|
|
|
if (snapshot.OperatorBlocks.TryGetValue(key, out var manual) && manual.IsLive(now))
|
|
{
|
|
var (status, location) = BlockResponse(policy, manual.RedirectTo, policy.OperatorBlockStatus);
|
|
return new EdgeDecision(EdgeVerdict.BlockOperator, status, location, manual.Reason, key, manual.ExpiresAt);
|
|
}
|
|
|
|
if (policy.Mode == EnforcementMode.Enforce
|
|
&& snapshot.EngineBans.TryGetValue(key, out var ban) && ban.IsLive(now))
|
|
{
|
|
var (status, location) = BlockResponse(policy, ban.RedirectTo, policy.EngineBlockStatus);
|
|
return new EdgeDecision(EdgeVerdict.BlockEngine, status, location, ban.Reason, key, ban.ExpiresAt);
|
|
}
|
|
|
|
if (policy.Geo != GeoMode.Off && !string.IsNullOrWhiteSpace(countryCode))
|
|
{
|
|
var code = countryCode.Trim().ToUpperInvariant();
|
|
snapshot.Countries.TryGetValue(code, out var rule);
|
|
var denied = policy.Geo switch
|
|
{
|
|
GeoMode.DenyList => rule is { IsAllowed: false },
|
|
GeoMode.AllowList => rule is not { IsAllowed: true },
|
|
_ => false
|
|
};
|
|
if (denied)
|
|
{
|
|
return new EdgeDecision(EdgeVerdict.GeoReject, 451, Reason: $"country_{(policy.Geo == GeoMode.DenyList ? "denied" : "not_allowed")}_{code}", SourceKey: key);
|
|
}
|
|
}
|
|
|
|
return EdgeDecision.Pass;
|
|
}
|
|
|
|
/// <summary>Q6: a per-entry redirect overrides the kind's default. The
|
|
/// engine never sets one, so an engine ban stays a 403 an honest visitor
|
|
/// can read, while an operator can still send a scanner elsewhere.</summary>
|
|
private static (int Status, string? Location) BlockResponse(EdgePolicy policy, string? redirectTo, int defaultStatus)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(redirectTo)) return (301, redirectTo);
|
|
// The last line of defence, and the only one that is not the operator's
|
|
// problem to fix. A status the wire cannot carry does not produce a bad
|
|
// answer, it produces no answer: measured on the shipped image,
|
|
// engineBlockStatus=1000 made every banned request die as
|
|
// "curl: (1) Unsupported HTTP/1 subversion in response". The admin API
|
|
// refuses such a value; this is for a row that got there another way.
|
|
if (!PolicyBounds.IsSendableStatus(defaultStatus)) return (403, null);
|
|
if (defaultStatus == 301)
|
|
{
|
|
var targets = policy.DefaultRedirectTargets;
|
|
var target = targets.Count == 0
|
|
? "https://www.iana.org/help/example-domains"
|
|
: targets.Count == 1 ? targets[0] : targets[Random.Shared.Next(targets.Count)];
|
|
return (301, target);
|
|
}
|
|
return (defaultStatus, null);
|
|
}
|
|
|
|
public static bool IsAlwaysPass(string path, EdgePolicy policy)
|
|
{
|
|
foreach (var prefix in policy.AlwaysPassPrefixes)
|
|
{
|
|
if (path.Equals(prefix, StringComparison.OrdinalIgnoreCase)
|
|
|| path.StartsWith(prefix + "/", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|