Reputation: 9
When we send this code to fortify scan
int len=inputString.length();
Pattern p= Pattern.compile("[0-9]{"+Integer.toString(len-1)+"}");
The second line is vulnerable to Denial of Service: regular expression.
How to resolve this issue? I tried different ways, but nothing is working out.
Upvotes: 0
Views: 294
Reputation: 1695
The fortify scanner is giving a good catch on this one, reason being user supplied pattern.
Pattern p= Pattern.compile("[0-9]{"+Integer.toString(len-1)+"}");
Fortify see the regex pattern constructed based on user input which may result in a DoS. Even so, the resulting pattern on your case at worst will ask the app to capture 2,147,483,646 characters - an enormous number but won't result in catastrophic backtracking. However, you should keep in mind that large enough integer in the quantifier may be rejected by the regex engine.
You could rewrite the code with regex only ensuring the string consist of only integers while length checking done using the good old String.length()
.
int len = inputString.length();
Pattern p= Pattern.compile("^[0-9]+$");
if(myString.length() == len && p.matcher(myString).find())
{
//success
}
else
{
//fail
}
Also, keep in mind there are many ways to broke regex.
Upvotes: 1