Files
openwaf/dotnet/OpenWaf.Domain/Security/PathPattern.cs
T
Pavlo Ratushnyi 5e6a840731 a path rule refuses the request itself, before the upstream ever sees it
Every pillar this edge had until now judged the response or the source: a streak
of refusals the upstream produced, a country, an operator's list of addresses.
The request itself was never looked at. A known-bad request therefore always
reached the origin and cost it something, and became a defence only if the
origin's answer happened to fall in the refusal range three times in a row.

A request rule is a path pattern an operator writes: `GET/POST/DELETE
/admin-api/rules`, listed in the order they are enforced, with an action.
`observe` counts matches (one alert per rule per 15 minutes, the tally on the
listing) and lets the request through, which is how an operator learns what a
rule would have blocked before it blocks anything; `block` answers 403 naming the
rule id — the id, not the pattern, because a 403 body that quotes the pattern
tells the visitor which payload to change. It fires in Observe mode too: the mode
switches off what the edge decides by itself, not what a human wrote down. It
sits below the allowlist and above the two source-level lists, because "this path
is refused" is the more specific claim about this request.

The pattern language is a glob — `*` and `?`, anchored, case-insensitive, `*`
crossing `/` — and deliberately not a regex: the operator writes the pattern and
an anonymous visitor writes the path, and `(a+)+$` against 400 a's is a ReDoS
with the edge's CPU. A pattern that can only silently do nothing (no leading
`/`, `/*`, a control character, over 256 characters) is refused with the reason,
and at most 500 live rules exist because every request is checked against each.

Two things the run caught rather than the design assumed:

 * The rules read shared one statement block with the rest of the snapshot.
   `request_rules` is the newest table in the schema, and the default schema step
   is EnsureCreated, which creates a missing database and changes nothing about
   an existing one — so every database created before this feature has every
   table except that one, and the first refresh after startup would have thrown,
   frozen the operator's block list at its old contents, and looked healthy. The
   rules read is a statement of its own now: a missing table costs the rules
   pillar and says so (`requestRulesAvailable`, `requestRulesError`, a NOT READ
   line over the rules table) while every other pillar keeps enforcing. The
   migration set was stale in the same direction — it never had `source_streaks`
   either, so the `migrate` path could not create the table OPEN-52 added;
   `AddRequestRules` adds both.
 * The console gate banned its own probe address. The seed sets the streak
   threshold to 3 and the gate probes 404 paths, so the last assertion in the new
   scene read a `blocked_by_policy` as "the rule is still in force" — and the
   ban, unlike the rule, outlives `compose down` in the data volume. The scene
   probes its own address now and the cleanup clears engine bans.

Measured on this tree: build 0 warnings / 0 errors, unit 195/195 (44 new: the
glob's semantics and rejections, and where the new pillar sits in the order),
integration 208/208 in 25 s (14 new, including a fixture that drops the rules
table and asserts the operator block is still enforced), smoke 36/0 (7 new
against a running edge), console 85 assertions 0 failed (6 new, driving the rule
form in a real browser), compose 209/0 against the built image at 261 MB.
2026-10-04 19:48:52 +02:00

101 lines
4.6 KiB
C#

namespace OpenWaf.Domain.Security;
/// <summary>
/// The matcher behind <see cref="RequestRule.Pattern"/>.
///
/// A glob, deliberately not a regular expression. The pattern is evaluated on
/// the request path, in the guard, on every request. A regex the operator can
/// type is a ReDoS an anonymous visitor can trigger — <c>(a+)+$</c> against a
/// path of 40 a's is the textbook case, and the edge would spend the CPU, not
/// the operator. A glob with <c>*</c> and <c>?</c> matched by the two-pointer
/// loop below is linear in the path length times the number of stars, and
/// there is no way to write a pattern in it that backtracks exponentially.
///
/// Three semantics worth stating because they are where glob implementations
/// differ:
/// * anchored at both ends — <c>/env</c> matches <c>/env</c> and nothing else;
/// <c>/.env*</c> matches <c>/.env</c>, <c>/.env.local</c>;
/// * <c>*</c> crosses <c>/</c> — this matches request paths, not file names,
/// and <c>/admin*</c> blocking <c>/admin/users</c> is what an operator means
/// by writing it;
/// * case-insensitive — the same posture as the always-pass prefixes and the
/// country codes, and a scanner that cannot decide <c>/.ENV</c> from
/// <c>/.env</c> should not get through on the difference.
///
/// The query string is not part of the path and is never matched. A rule about
/// a query would need its own matching rules and would be a different feature.
/// </summary>
public static class PathPattern
{
/// <summary>The same budget the attacker-controlled path field already gets
/// (512) is generous here; 256 is four times what the longest real path
/// rule needs and keeps the listing readable.</summary>
public const int MaxLength = 256;
/// <summary>How many rules one edge evaluates per request. The scan is a
/// linear loop over live rules; 500 of them is a few microseconds, and the
/// cap is what stops the listing becoming the thing that decides whether a
/// request is served.</summary>
public const int MaxRules = 500;
public static bool IsValid(string? pattern) => ExplainRejection(pattern) is null;
/// <summary>Null when the pattern is usable, otherwise the reason it is
/// not — said to the operator at the moment they type it, because a rule
/// that can never match is a rule that silently does nothing.</summary>
public static string? ExplainRejection(string? pattern)
{
if (string.IsNullOrWhiteSpace(pattern))
return "pattern must not be empty";
// Checked before the trim, on what was actually sent. A tab or a NUL is
// not a path byte, and a pattern that survives trimming is a pattern
// whose meaning changed on the way in — the operator wrote one thing
// and the edge would enforce another.
foreach (var c in pattern)
{
if (c < 0x20 || c == 0x7f)
return "pattern must not contain control characters";
}
var trimmed = pattern.Trim();
if (trimmed.Length > MaxLength)
return $"pattern must be at most {MaxLength} characters; got {trimmed.Length}";
if (!trimmed.StartsWith('/'))
return "pattern must start with / — it is matched against the request path, which always does";
// A pattern made only of wildcards matches every request, which is a
// different act from writing a rule: it is "take the site down". It is
// refused rather than accepted, because nobody means it by typing "*".
if (trimmed is "*" or "/*" or "/**" or "/?")
return "pattern must name something more specific than every request on the site";
return null;
}
public static bool Matches(string? pattern, string? path)
{
if (pattern is null || path is null) return false;
var p = pattern.Trim();
// Two-pointer glob with one backtrack point per star: O(len(path) *
// stars), no exponential backtracking, no allocation.
int pi = 0, si = 0, star = -1, match = 0;
while (si < path.Length)
{
if (pi < p.Length && (p[pi] == '?' || char.ToUpperInvariant(p[pi]) == char.ToUpperInvariant(path[si])))
{
pi++; si++;
}
else if (pi < p.Length && p[pi] == '*')
{
star = pi++;
match = si;
}
else if (star >= 0)
{
pi = star + 1;
si = ++match;
}
else return false;
}
while (pi < p.Length && p[pi] == '*') pi++;
return pi == p.Length;
}
}