Does including "Pattern.LITERAL" flag as part of the Pattern.compile(String regex, int flags) method in Java mitigate String regex injection?

Viewed 174

In the below code base, I am providing Pattern.LITERAL as one of the flags to Pattern.compile(String regex, int flags) method and wanted advise whether this flag can mitigate regular expression injection(https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) in Java or not? Below is an example pattern i have provided as an example. The string this regex is checked against is an user provided input.

private final int flags = Pattern.CASE_INSENSITIVE | Pattern.LITERAL;

   Pattern patternCheck = Pattern.compile("check\\s+test\\s+([\\w\\s-]+)cd(\\s+" + variable1 +
    "|\\s+abc\\s+" + variable2 + ")\\s+to\\s+(abc|xyz)\\s+test\\s+ab\\s+xyz",flags);
1 Answers

Check the Pattern.LITERAL documentation:

When this flag is specified then the input string that specifies the pattern is treated as a sequence of literal characters. Metacharacters or escape sequences in the input sequence will be given no special meaning.

So, this flag makes any pattern a plain text. \s will match \s text, not any whitespace.

What you need to make sure of is:

  • Try to write patterns where each subsequent part cannot match the same text as the preceding part to avoid excessive backtracking
  • Escape the user-written literal parts of the pattern using Pattern.quote.

In your case, you can use

Pattern patternCheck = Pattern.compile("check\\s+test\\s+([\\w\\s-]+)cd(\\s+" + Pattern.quote(variable1) + "|\\s+abc\\s+" + Pattern.quote(variable2) + ")\\s+to\\s+(abc|xyz)\\s+test\\s+ab\\s+xyz", Pattern.CASE_INSENSITIVE);
Related