Class TimeLimitedRegex

java.lang.Object
org.apache.wiki.util.TimeLimitedRegex

public final class TimeLimitedRegex extends Object
Evaluates java.util.regex matches with an upper bound on matching time. The JDK regex engine backtracks, so a pathological pattern such as (a+)+$ matched against a long non-matching subject takes exponential time and pins a CPU ("catastrophic backtracking" / ReDoS). When either the pattern or the subject is user-controlled — as with wiki plugin parameters matched against page content — every match must be time-boxed.

The subject is wrapped in a deadline-checking CharSequence: the engine reads the subject on every matching step, so a runaway match is aborted shortly after the deadline passes and reported as a non-match.

Since:
3.0.1
  • Field Details

  • Method Details

    • matches

      public static boolean matches(CharSequence subject, Pattern pattern)
      Attempts to match the whole subject against the given pattern, giving up after DEFAULT_TIMEOUT_MILLIS milliseconds.
      Parameters:
      subject - the character sequence to match.
      pattern - the compiled pattern.
      Returns:
      true if the whole subject matches; false if it doesn't, or if the time budget was exceeded.
    • matches

      public static boolean matches(CharSequence subject, Pattern pattern, long timeoutMillis)
      Attempts to match the whole subject against the given pattern, giving up after timeoutMillis milliseconds. A match that exceeds its budget is logged as a warning and treated as a non-match.
      Parameters:
      subject - the character sequence to match.
      pattern - the compiled pattern.
      timeoutMillis - time budget for this match, in milliseconds.
      Returns:
      true if the whole subject matches; false if it doesn't, or if the time budget was exceeded.