Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Regular expression injection

ID: java/regex-injectionKind: path-problemSecurity severity: 7.5Severity: errorPrecision: highTags:   - security   - external/cwe/cwe-730   - external/cwe/cwe-400Query suites:   - java-code-scanning.qls   - java-security-extended.qls   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Constructing a regular expression with unsanitized user input is dangerous as a malicious user may be able to modify the meaning of the expression. In particular, such a user may be able to provide a regular expression fragment that takes exponential time in the worst case, and use that to perform a Denial of Service attack.

Recommendation

Before embedding user input into a regular expression, use a sanitization function such asPattern.quote to escape meta-characters that have special meaning.

Example

The following example shows an HTTP request parameter that is used to construct a regular expression.

In the first case the user-provided regex is not escaped. If a malicious user provides a regex whose worst-case performance is exponential, then this could lead to a Denial of Service.

In the second case, the user input is escaped usingPattern.quote before being included in the regular expression. This ensures that the user cannot insert characters which have a special meaning in regular expressions.

importjava.util.regex.Pattern;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;publicclassRegexInjectionDemoextendsHttpServlet{publicbooleanbadExample(javax.servlet.http.HttpServletRequestrequest){Stringregex=request.getParameter("regex");Stringinput=request.getParameter("input");// BAD: Unsanitized user input is used to construct a regular expressionreturninput.matches(regex);}publicbooleangoodExample(javax.servlet.http.HttpServletRequestrequest){Stringregex=request.getParameter("regex");Stringinput=request.getParameter("input");// GOOD: User input is sanitized before constructing the regexreturninput.matches(Pattern.quote(regex));}}

References


[8]ページ先頭

©2009-2025 Movatter.jp