Insecure Use of Regular Expressions

Why is this important?

Regular Expressions (Regex) are used in almost every application. Yet, few people know that improper use of a Regex can cause your app to stop responding. This vulnerability is called Regular Expression Denial of Service, or ReDOS for short.

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

  1. Install Safe-Regex as a dev dependency.

    npm install --save-dev safe-regex
    
  2. 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));
    
  3. Go through the issues that GuardRails identified in the PR.

  4. Identify any * or + operators that are close to each other.
  5. Remove them and test the new regex with the safe.js script until it returns true.

    $ node safe.js '(x+x+)+y'
    false
    $ node safe.js '(x+x+)y'
    true
    
  6. Test it and ensure the regex is still working as expected.

  7. Ship it 🚢 and relax 🌴

Option B: Escape user input in regular expressions

  1. Go through the issues that GuardRails identified in the PR.
  2. Verify that user input is used to create a Regular Expression.
  3. Create a function that escapes user input for use in Regular Expressions.

    RegExp.escape = function(str) {
    return String(str).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    };
    
  4. Use the created function to escape all user input.

    new RegExp(RegExp.escape(req.body.pattern));
    
  5. Test it and ensure the regular expression is still working as expected.

  6. Ship it 🚢 and relax 🌴

More information: