namespace OpenWaf.Domain.Security;
///
/// The matcher behind .
///
/// 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 — (a+)+$ against a
/// path of 40 a's is the textbook case, and the edge would spend the CPU, not
/// the operator. A glob with * and ? 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 — /env matches /env and nothing else;
/// /.env* matches /.env, /.env.local;
/// * * crosses / — this matches request paths, not file names,
/// and /admin* blocking /admin/users 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 /.ENV from
/// /.env 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.
///
public static class PathPattern
{
/// 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.
public const int MaxLength = 256;
/// 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.
public const int MaxRules = 500;
public static bool IsValid(string? pattern) => ExplainRejection(pattern) is null;
/// 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.
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;
}
}