SonarQube Regex vulnerability issue in JavaScript
Wherever I use Regex in JavaScript code, SonarQube shows vulnerability issue. Is there any alternate for Regex in JavaScript?
Error : Make sure that using a regular expression is safe here.
Sample Regex : '(^(?=[A-Za-z0-9\._-]*$)(?=.*[A-Za-z0-9]).*$)'
Solution 1:
This is not really an issues, but a security warning.
Did you check the SonarQube description of the error ?
Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs.
The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users.
This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following characters: *+{.
Example: (a+)*
Ask Yourself Whether • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression. • your regular expression engine performance decrease with specially crafted inputs and regular expressions.
You may be at risk if you answered yes to any of those questions.
To solve the issue, you need to humanly check if the RegEx is at risk. If not, you can just flag it as a false positive, otherwise, reviewing the regex can be mandatory.
Additional information on regex DoS issues can be found on OWASP web site