简体   繁体   English

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

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

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?在下面的代码库中,我提供 Pattern.LITERAL 作为 Pattern.compile(String regex, int flags) 方法的标志之一,并希望告知此标志是否可以减轻正则表达式注入( https://owasp.org/www -community/attacks/Regular_expression_Denial_of_Service__-_ReDoS ) 在 Java 中与否? 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 | 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 :检查Pattern.LITERAL文档

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. \\s将匹配\\s文本,而不是任何空格。

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 .使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM