Unsanitized dynamic input in regular expression

  • Rule ID: javascript_lang_dynamic_regex
  • Languages: javascript
  • Source: dynamic_regex.yml

Description

Creating regular expressions from dynamic input can lead to a vulnerability known as Regular Expression Denial of Service (ReDoS). This issue arises because some regular expressions can be processed with exponential time complexity. When attackers exploit this, it can significantly drain CPU resources, effectively causing a denial of service.

Remediations

  • Do validate all dynamic and user-supplied input against a strict safelist of allowed characters before using it in regular expressions. This step helps prevent attackers from injecting malicious patterns.
  • Do restrict the length of input that can be processed. Limiting input size is a straightforward way to mitigate many ReDoS vulnerabilities.
  • Do implement timeouts for regular expression evaluation to avoid excessive resource consumption. This can be achieved using JavaScript environments or libraries that allow setting execution time limits.
  • Do simplify complex regular expressions to reduce the risk of catastrophic backtracking. Breaking down expressions into simpler parts makes them safer and more manageable.
  • Do not directly concatenate user input into regular expressions. This practice can introduce unsafe patterns and lead to vulnerabilities.
    var dynamicRegex = new RegExp('^' + userInput); // unsafe

References

Associated CWE

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=javascript_lang_dynamic_regex

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=javascript_lang_dynamic_regex