rspec/rules/S2631/java/rule.adoc
Alban Auzeill 2c306d110e Fix code block ambiguity with old header style
Ensure blank line before list and clean the one leading space
2020-06-30 17:16:12 +02:00

36 lines
1.6 KiB
Plaintext

Regular expressions can have an https://en.wikipedia.org/wiki/Regular_expression#Implementations_and_running_times[exponential execution time] depending on the pattern and the length of the input string. The example below, for instance, can lead to a denial of service of the application:
* Pattern: <code>/(a+)+b/</code>
* Input string: <code>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacb</code>
It is recommended:
* to fix the hard-coded regex patterns that use CPU intensive features (avoid if possible captures, possessive quantifiers and back-references, for instance replace the above pattern with (/a+b/)).
* when the regex pattern is defined with an user-controlled input, this last should be sanitized in order to escape characters which are part of the https://en.wikipedia.org/wiki/Regular_expression#Syntax[regular expression syntax].
Java runtimes like OpenJDK 9+ are mitigating this problem by having additional protections in their implementation of regular expression evaluation to limit the CPU consumption but it is still recommended to validate/escape input strings.
== Noncompliant Code Example
----
public boolean validate(javax.servlet.http.HttpServletRequest request) {
String regex = request.getParameter("regex");
String input = request.getParameter("input");
input.matches(regex); // Noncompliant
}
----
== Compliant Solution
----
public boolean validate(javax.servlet.http.HttpServletRequest request) {
String regex = request.getParameter("regex");
String input = request.getParameter("input");
input.matches(Pattern.quote(regex)); // Compliant
}
----
include::../see.adoc[]