Insecure Use of Regular Expressions
Why is this important?
Regular Expressions (Regex) are used in almost every application. Less known is the fact that a Regex can lead to Denial of Service (DOS) attacks, called ReDOS. This is due to the fact that regex engines may take a large amount of time when analyzing certain strings, depending on how the regex is defined.
Therefore, it is possible that a single request may cause a large amount of computation on the server side.
Over 100 npm packages have been affected by this vulnerability.
Read below to find out how to fix this issue in your code.
Fixing Insecure Use of Regular Expressions
Option A: Use Safe-Regex
- Install Safe-Regex as a dev dependency.
npm install --save-dev safe-regex
- Create a file named
safe.js
with the following content.
var safe = require("safe-regex");
var regex = process.argv.slice(2).join(" ");
console.log(safe(regex));
- Go through the issues that GuardRails identified in the PR.
- Identify any
*
or+
operators that are close to each other. - Remove them and test the new regex with the
safe.js
script until it returnstrue
.
$ node safe.js '(x+x+)+y'
false
$ node safe.js '(x+x+)y'
true
- Test it and ensure the regex is still working as expected.
- Ship it 🚢 and relax 🌴
Option B: Escape user input in regular expressions
- Go through the issues that GuardRails identified in the PR.
- Verify that user input is used to create a Regular Expression.
- Create a function that escapes user input for use in Regular Expressions.
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};
- Use the created function to escape all user input.
new RegExp(RegExp.escape(req.body.pattern));
- Test it and ensure the regular expression is still working as expected.
- Ship it 🚢 and relax 🌴