Skip to main content

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.

Read below to find out how to fix this issue in your code.

Fixing Insecure Use of Regular Expressions

In order to double-check whether the regular expression is really vulnerable, there is a helpful web service that can be leveraged called recheck.

Option A: Create a safe regular expression

  1. Go through the issues that GuardRails identified in the PR

  2. Patterns will look like this:

    import re
    # insecure example A
    subject = 'x' * 64
    re.search(r'(x+x+)+y', subject)
    # insecure example B
    subject = 'a' * 64
    re.search(r'(.|[abc])+z', subject)
  3. Look into simplifying these patterns like so:

    import re
    # secure version of example A
    subject = 'x' * 64
    re.search(r'xx+y', subject)
    # secure version example B
    subject = 'a' * 64
    re.search(r'.+z', subject)
  4. Test it and ensure the regular expression is still working as expected

  5. Ship it 🚢 and relax 🌴

More information