Measured on the shipped image (openwaf:ci). POST /admin-api/blocks answered 204 for every one of these, and the next request from that source paid for it: "https://example.com/ok" 301 Location: https://example.com/ok "http://bad target" 301 Location: http://bad target "http://x.invalid/<CRLF>X-Injected: 1" 500 Internal Server Error, Content-Length: 0 "javascript:alert(1)" 301 Location: javascript:alert(1) "not-a-url" 301 Location: not-a-url The CRLF row is the defect rather than the wart: Kestrel refuses to write the header, so the operator's own block — written with a 204 — became a server error for that visitor. Nothing was injected; the server validated the header, which is the only part of the old behaviour that was safe. javascript: and data: are absolute URIs too, and a redirect is a navigation, so those are an execution request made on the operator's behalf by a string somebody typed into a form. RedirectTarget.IsSendable is now the one judge: absolute, http(s), no control characters or surrounding whitespace. The API answers 400 naming the field, and DecisionEngine ignores a target it cannot send and answers the block's own default instead — for a row that arrived by a restored backup or a hand edit, where the API guard never ran. The console gate also asserts the other half of the same boundary: every value that came from the API is rendered through esc(), and two of those values are not authored by the person reading the page — the path in an observation row is whatever an anonymous visitor asked for, and a block reason is a form field. The seed now sends a percent-encoded path carrying <img onerror=...> and an operator block whose reason carries <svg onload=...>, and the page must show both as text and create no elements from them. unit 105 -> 126 (+21: the target table, and the decision point's fallback) integration 55 -> 62 (+7: 400 by name for five targets, a valid target reaching the wire as 301, and a hand-written row with CRLF answering 301 to the default target instead of the 500 it used to answer) console 33 -> 37 assertions Teeth, each measured by removing the thing: esc() reduced to identity in the shipped page makes the console gate go red with 6 failures, and the page title becomes "XSS" — the anonymous visitor's path executed script in the operator's browser. Dropping the API guard fails exactly 5 integration tests; dropping the decision-point guard fails exactly 6 unit tests and the 1 hand-written-row test.
128 lines
5.6 KiB
C#
128 lines
5.6 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)
|
|
{
|
|
// A per-entry redirect is honoured only if it can actually be sent.
|
|
// The shipped image used to write whatever string the entry held
|
|
// straight into Location: a CRLF in there made Kestrel refuse the
|
|
// header, and the blocked request came back as 500 with no body — the
|
|
// operator's own block, accepted with 204, turned into a server error
|
|
// for that visitor. Falling back to the kind's default status is the
|
|
// defined answer for a target that arrived by a route the API did not
|
|
// police (a restored row, a hand edit).
|
|
if (Security.RedirectTarget.IsSendable(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;
|
|
}
|
|
}
|