Recipe Name:
Regex Injection
Description:
Use Pattern#quote to include untrusted input in regexes.
Level:
error
Language:
- java
Tags:
- security
- SEI CERT
- Java basic
- injection
- OWASP Top 10
Documentation
Allowing untrusted input in regular expressions can lead to the unintentional inclusion of sensitive data or denial-of-service vulnerabilities.
Untrusted input should be sanitized before it is used as part of regular expressions. To do so, the Pattern
class provides the Quote
method.
public static void FindLogEntry(String search) { // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; }After
public static void FindLogEntry(String search) { // Sanitize search string search = Pattern.quote(search); // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; }References
Recipe
id: scw:java:regex-injection version: 10 metadata: name: Regex Injection shortDescription: Use Pattern#quote to include untrusted input in regexes. level: error language: java cweCategory: 625 enabled: true descriptionFile: descriptions/Regex_Injection.html tags: security;SEI CERT;Java basic;injection;OWASP Top 10 search: methodcall: args: 1: type: java.lang.String value: containsUntrustedInput: true trustedSources: - methodcall: name: quote type: java.util.regex.Pattern name: compile type: java.util.regex.Pattern availableFixes: - name: Wrap the untrusted input in Pattern#quote actions: - rewrite: to: java.util.regex.Pattern.quote({{{.}}}) target: self