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);
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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.