是否将 "Pattern.LITERAL" 标志作为 Pattern.compile(String regex, int flags) 方法的一部分包含在 Java 中以减轻 String regex 注入?

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

在下面的代码库中,我提供 Pattern.LITERAL 作为 Pattern.compile(String regex, int flags) 方法的标志之一,并希望告知此标志是否可以减轻正则表达式注入( https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) 是否在 Java 中?下面是我作为示例提供的示例模式。检查此正则表达式的字符串是用户提供的输入。

私有最终 int 标志 = 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);

勾选 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.

所以,这个标志使任何模式成为纯文本。 \s 将匹配 \s 文本,而不是任何空格。

您需要确定的是:

  • 尝试编写模式,其中每个后续部分都不能匹配与前面部分相同的文本,以避免过多的回溯
  • 使用 Pattern.quote.
  • 转义模式中用户编写的文字部分

对于你的情况,你可以使用

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);