Skip to content
DoS Advisory Intermediate CVE-2020-26305

GHSL-2020-291: Regular Expression Denial of Service (ReDoS) in CommonRegexJS - CVE-2020-26305

The CommonRegexJS library contains a regular expression for matching links that is vulnerable to ReDoS, allowing an attacker to cause excessive CPU usage by supplying a crafted input string. This can lead to a denial of service.

ghsecuritylab Follow

Originally disclosed on GitHub Security Lab

The project contains one or more regular expressions that are vulnerable to ReDoS (Regular Expression Denial of Service)

ghsecuritylab, on GitHub Security Lab

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

CommonRegexJS is a general purpose collection of regular expressions for matching various kinds of strings. The advisory concerns one of those expressions, the links regex, which is used to find links in a piece of text. The package is published on npm as commonregex.

The issue is a Regular Expression Denial of Service (ReDoS): a regular expression that can be forced into exponential backtracking by a crafted input string, making the matching engine take an impractical amount of time.

Setup

The advisory was produced by the GitHub Security Lab. The tested version was the latest commit at the time of reporting, 30 November 2020. No account, role or special configuration is described; the only tooling mentioned is the CodeQL query that found the problem and a Node.js runtime to run the proof of concept.

The vulnerability was found using a CodeQL query, which identified the links regex as vulnerable. The query run is linked in the advisory.

Finding it

ReDoS affects poorly constructed and potentially inefficient regular expressions, which can perform extremely badly given a creatively constructed input string. For the specific regular expression reported, it is possible to force it to work with an O(2^n) runtime performance when there is exponential backtracking.

ReDoS can be caused by ambiguity or overlap between some regex clauses. Such badly performing regular expressions become a security issue if a user can control the input. For example, if the project is an input validation library, then the project could be used by a server to validate untrusted user input. There is no one size fits all when it comes to fixing ReDoS; in general it is about removing ambiguity or overlap inside the regular expression.

The advisory illustrates the pattern with three examples before showing the vulnerable expression.

Example 1: HTML comments

JavaScript
var reg = /<!--(.|\s)*?-->/g;

This matches the start of an HTML comment, followed by any characters, followed by the end of an HTML comment. The dot (.) matches any character except newlines, and \s matches any whitespace. Both . and \s match whitespace such as the space character, so there are many possible ways for this regular expression to match a sequence of spaces. If the input is a string that starts with <!-- followed by a long sequence of spaces, the evaluator will try every possible way of matching the spaces. The fix removes the ambiguity:

JavaScript
var reg = /<!--(.|\r|\n)*?-->/g;

Example 2: snake_case identifiers

JavaScript
var reg = /(\w+_?)+_(\d+)/;

This matches a snake_case identifier that ends with some digits. For a string starting with lots of letters, there are many ways for the regular expression to match those letters, because the regex has a repetition matching letters (\w+) inside another repetition that can match letters ((\w+_?)+). The evaluator will try every possible grouping of letters into smaller groups of letters. The fix removes the ambiguity by changing the inner repetition to match groups of letters that must end with an underscore:

JavaScript
var reg = /(\w+_)+(\d+)/;

Example 3: a VS Code link pattern

Often the regular expressions are not as simple as the examples above, like the one that used to be part of VS Code. The top expression is the vulnerable one, the bottom is the fixed one:

JavaScript
var linkPattern = /(\[((!\[[^\]]*?\]\(\s*)([^\s\(\)]+?)\s*\)\]|(?:\\\]|[^\]])*\])\(\s*)(([^\s\(\)]|\(\S*?\))+)\s*(".*?")?\)/g;
var linkPattern = /(\[((!\[[^\]]*?\]\(\s*)([^\s\(\)]+?)\s*\)\]|(?:\\\]|[^\]])*\])\(\s*)(([^\s\(\)]|\([^\s\(\)]*?\))+)\s*(".*?")?\)/g;

This example is very similar to the first one: a section of the regular expression that was too general (\S) was changed to something a bit more specific ([^\s\(\)]) to remove overlap with another part of the regular expression.

Exploitation

Step 1: install the package

Bash
npm install commonregex

Step 2: run the proof of concept

Put the below in a .js file and run it with node:

JavaScript
var CommonRegex = require('commonregex');
var foo = new CommonRegex("https://www.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");
foo.getLinks()

The input is a URL prefix followed by a long run of single quote characters. The advisory does not record the observed runtime or any output from the call.

Root cause

The advisory identifies the links regex as vulnerable but does not reproduce the expression itself, so the exact overlapping clauses are not shown. The advisory does not reproduce the links expression itself, so the exact overlapping clauses are not shown.

Impact

This issue may lead to a denial of service. The advisory frames the risk conditionally: the badly performing expression becomes a security issue if a user can control the input.

Fix

The advisory describes the general remedy rather than a specific patch: remove the ambiguity or overlap inside the regular expression, as in the three examples, where a too general clause is replaced by a more specific one or an inner repetition is constrained. No fixed version or commit for CommonRegexJS is given.

Variants to test

  • Any library that exposes a general purpose set of regular expressions for parsing text (links, dates, phone numbers, email addresses) and is fed untrusted input. A positive result is a crafted string that makes a single match call take seconds or longer, growing sharply as the input length increases.
  • Expressions with a repetition inside another repetition that can match the same characters, like the snake_case example. A positive result is a long run of characters that the outer repetition can split in many ways without completing the match.
  • Expressions where a general character class overlaps a more specific one, like the HTML comment example. A positive result is a long run of characters matched by both clauses, such as spaces after <!--.
  • Expressions derived from the VS Code link pattern, where \S overlaps with the surrounding structure. A positive result is a long run of characters accepted by the general clause but not completing the overall match.

Hunting notes

This kind of bug hides in parsing and validation helpers that ship broad regular expressions and are applied to user controlled strings. The signal during review is a regex with nested quantifiers or overlapping character classes, especially one that is run over arbitrary text rather than a fixed format. Static analysis helps: the advisory credits a CodeQL query for identifying the links regex, which is a repeatable way to sweep a codebase for the same construction. The impact argument is the conditional one: the issue may lead to a denial of service if a user can control the input.

Timeline and credit

  • 2020-11-30: security contact requested via a GitHub issue on the project.
  • 2021-03-02: deadline expired.
  • 2021-07-13: published as per the GitHub SecLab disclosure policy.

The issue was discovered and reported by GitHub team member @erik-krogh (Erik Krogh Kristensen). It is tracked as CVE-2020-26305 and GHSL-2020-291.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

What happened, in plain words

A small piece of software called CommonRegexJS is a collection of ready-made patterns for matching various kinds of strings. One of those patterns, the one that finds links, can be made to run for an extremely long time by a specially crafted piece of text. This kind of problem is called a Regular Expression Denial of Service, or ReDoS for short.

A denial of service means that something which should answer quickly instead gets stuck and stops answering. Think of a checkout till that normally scans an item in a second. If someone hands it a barcode designed so the scanner tries every possible way of reading it, the queue behind it grows and the shop stops working. Nothing is stolen and no data leaks; the service simply becomes unavailable.

The GitHub Security Lab found the problem with an automated tool called CodeQL, requested a security contact, and published the details after a disclosure deadline passed. The issue is tracked as GHSL-2020-291 and CVE-2020-26305.

Background: what a regular expression is

A regular expression (often shortened to regex) is a tiny language for describing patterns in text. You write a pattern, and a matching engine walks through a piece of text looking for a part that fits the pattern. For example, a pattern can say "a word, then an underscore, then some digits".

Regexes are everywhere: form validation, search boxes, log parsing, link detection. They are convenient because one short line can describe a fairly complex rule.

The catch is that the matching engine has to try possibilities. When a pattern is written loosely, several different ways of matching the same text can exist, and the engine may explore all of them before giving up. That exploration is what this advisory is about.

Background: what CommonRegexJS is

CommonRegexJS is a general purpose collection of regular expressions for matching various kinds of strings. Instead of writing your own patterns, you install the package and use its expressions. The package is published on npm as commonregex. npm is the standard package registry for JavaScript: a public library of reusable code that anyone can download with a single command.

The advisory concerns one of those expressions, the links regex, which is used to find links in a piece of text.

The vulnerability class: ReDoS

ReDoS, or Regular Expression Denial of Service, is a vulnerability affecting poorly constructed and potentially inefficient regular expressions which can make them perform extremely badly given a creatively constructed input string.

For the specific regular expression reported, it is possible to force it to work with an O(2^n) runtime performance when there is exponential backtracking.

Two terms need unpacking here.

Exponential backtracking. When the engine tries one way of matching and it fails, it goes back and tries another way. That is called backtracking. If each extra character in the input doubles the number of ways to try, the work grows exponentially. O(2^n) is a way of writing that: with n characters of input, the work is roughly 2 multiplied by itself n times. Ten characters is about a thousand attempts; forty characters is about a trillion. A string that is harmless at twenty characters can hang a machine at sixty.

Ambiguity or overlap. ReDoS can be caused by ambiguity or overlapping between some regex clauses. If two parts of a pattern can both match the same character, the engine has a choice at every position, and a long run of such characters multiplies the choices.

These badly performing regular expressions can become a security issue if a user can control the input. For example if the project is an input validation library, then the project could be used by a server to validate untrusted user input. A server is a computer that answers requests from other computers; untrusted input means text that arrives from strangers on the internet, such as the contents of a form. If the server runs a slow pattern over that text, one visitor can tie it up.

There is no one size fits all when it comes to fixing ReDoS. But in general it is about removing ambiguity/overlap inside the regular expression.

Three teaching examples

Before showing the vulnerable regex, the advisory shows some examples of regular expressions vulnerable to ReDoS and how to fix them. They are worth reading slowly, because the real bug is the same shape as the first one.

Example 1: HTML comments

JavaScript
var reg = /<!--(.|\s)*?-->/g;

The above regular expression matches the start of an HTML comment, followed by any characters, followed by the end of a HTML comment. HTML comments are the notes in a web page that start with <!-- and end with --> and are not shown to the visitor.

Line by line:

  • var reg = stores the pattern in a variable called reg.
  • / and /g are the delimiters of a JavaScript regex; the g means "find all matches", not just the first.
  • <!-- is the literal opening of a comment.
  • (.|\s)*? is the middle: a group that matches either any character (.) or any whitespace (\s), repeated any number of times, as few as possible.
  • --> is the literal closing of a comment.

The dot in the regular expression (.) matches any char except newlines, and \s matches any whitespace. Both . and \s matches whitespace such as the space character. There are therefore many possible ways for this regular expression to match a sequence of spaces.

This becomes a problem if the input is a string that starts with <!-- followed by a long sequence of spaces, because the regular expression evaluator will try every possible way of matching the spaces. Each space can be assigned to the dot or to the whitespace clause, so the number of combinations doubles with every space.

The fix is to remove the ambiguity, which can be done by changing the regular expression to the below, where there is no overlap between the different elements of the regular expression.

JavaScript
var reg = /<!--(.|\r|\n)*?-->/g;

Now the group matches any character, or a carriage return (\r), or a newline (\n). The dot already covers everything except newlines, so the alternatives no longer compete for the same characters: each character has exactly one way to be matched.

Example 2: snake_case identifiers

JavaScript
var reg = /(\w+_?)+_(\d+)/;

The above matches a snake_case identifier that ends with some digits. A snake_case identifier is a name written in lower case with underscores between words, like first_name_42.

Line by line:

  • (\w+_?)+ is an outer repetition. Inside it, \w+ matches one or more word characters (letters, digits and underscore) and _? optionally matches an underscore. The whole inner group can repeat.
  • _ then requires one more underscore.
  • (\d+) requires one or more digits at the end.

However, for a string starting with lots of letters, there many ways for the regular expression to match those letters, due to the regex having a repetition matching letters (\w+) inside another repetition that can match letters ((\w+_?)+). The regular expression evaluator will try every possible grouping of letters into smaller groups of letters. With twenty letters, there are a huge number of ways to split them into chunks.

The fix is again to remove ambiguity, by changing the inner repetition to match groups of letters that must end with an underscore.

JavaScript
var reg = /(\w+_)+(\d+)/;

Now each repetition of the outer group must consume a chunk of word characters followed by an underscore. The chunks can no longer be divided in several ways, because the underscore marks a fixed boundary.

Example 3: a VS Code link pattern

Often the regular expressions are not as simple as the examples above. Like the below regular expression that used to be part of VS Code, a popular code editor. The top regular expression is the vulnerable one, the bottom is the fixed one.

JavaScript
var linkPattern = /(\[((!\[[^\]]*?\]\(\s*)([^\s\(\)]+?)\s*\)\]|(?:\\\]|[^\]])*\])\(\s*)(([^\s\(\)]|\(\S*?\))+)\s*(".*?")?\)/g;
var linkPattern = /(\[((!\[[^\]]*?\]\(\s*)([^\s\(\)]+?)\s*\)\]|(?:\\\]|[^\]])*\])\(\s*)(([^\s\(\)]|\([^\s\(\)]*?\))+)\s*(".*?")?\)/g;

This pattern is long because it tries to recognise Markdown links, including links with images and titles. You do not need to read every character to get the point. The two lines are almost identical; the difference is in the middle, where the first line has \(\S*?\) and the second has \([^\s\(\)]*?\).

But this example is actually very similar to the first example. A section of the regular expression that was too general (\S, which means any non-whitespace character) was changed to something a bit more specific ([^\s\(\)], which means any character that is neither whitespace nor a parenthesis) to remove overlap with another part of the regular expression.

Finding the bug in CommonRegexJS

CommonRegexJS is a general purpose collection of regular expressions for matching various kinds of strings, as described above.

This vulnerability was found using a CodeQL query which identified the links regex as vulnerable. CodeQL is a tool that analyses source code the way a compiler does, then lets you ask questions about it in a query language. A query can, for instance, ask "show me every regex in this project that has a repetition inside a repetition". The advisory links to the query run.

Proof of concept

The advisory gives two steps. The first installs the package, the second runs a tiny program that triggers the slow behaviour.

Step 1: install the package

Bash
npm install commonregex

This command asks npm, the JavaScript package registry, to download the commonregex package and put it in the current project so that code can load it. You run it in a terminal, which is a text window where you type commands instead of clicking buttons.

Step 2: run the proof of concept

Put the below in a .js file and run with node.

JavaScript
var CommonRegex = require('commonregex');
var foo = new CommonRegex("https://www.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");
foo.getLinks()

Line by line:

  • var CommonRegex = require('commonregex'); loads the package that was installed in step 1 and stores it in a variable. require is Node.js's way of importing another file or package.
  • var foo = new CommonRegex("..."); creates an object from the package, handing it the text to work on. The text is a URL prefix, https://www., followed by a long run of single quote characters.
  • foo.getLinks() asks the object to find the links in that text. Internally this runs the links regex over the string.

Node.js is a program that runs JavaScript outside a browser, so you can execute this file directly on your computer.

The input is a URL prefix followed by a long run of single quote characters. The advisory does not record the observed runtime or any output from the call.

Why it happens

The advisory identifies the links regex as vulnerable but does not reproduce the expression itself, so the exact overlapping clauses are not shown. The advisory does not reproduce the links expression itself, so the exact overlapping clauses are not shown.

Impact

This issue may lead to a denial of service. The advisory frames the risk conditionally: the badly performing expression becomes a security issue if a user can control the input. If the text always comes from a trusted source, the slow path is much harder to trigger deliberately.

Fix

The advisory describes the general remedy rather than a specific patch: remove the ambiguity or overlap inside the regular expression, as in the three examples, where a too general clause is replaced by a more specific one or an inner repetition is constrained. No fixed version or commit for CommonRegexJS is given.

Variants to test

If you want to look for the same bug elsewhere, these are the shapes to look for.

  • Any library that exposes a general purpose set of regular expressions for parsing text (links, dates, phone numbers, email addresses) and is fed untrusted input. A positive result is a crafted string that makes a single match call take seconds or longer, growing sharply as the input length increases.
  • Expressions with a repetition inside another repetition that can match the same characters, like the snake_case example. A positive result is a long run of characters that the outer repetition can split in many ways without completing the match.
  • Expressions where a general character class overlaps a more specific one, like the HTML comment example. A positive result is a long run of characters matched by both clauses, such as spaces after <!--.
  • Expressions derived from the VS Code link pattern, where \S overlaps with the surrounding structure. A positive result is a long run of characters accepted by the general clause but not completing the overall match.

Hunting notes

This kind of bug hides in parsing and validation helpers that ship broad regular expressions and are applied to user controlled strings. The signal during review is a regex with nested quantifiers or overlapping character classes, especially one that is run over arbitrary text rather than a fixed format. Static analysis helps: the advisory credits a CodeQL query for identifying the links regex, which is a repeatable way to sweep a codebase for the same construction. The impact argument is the conditional one: the issue may lead to a denial of service if a user can control the input.

Timeline and credit

  • 2020-11-30: security contact requested via a GitHub issue on the project.
  • 2021-03-02: deadline expired.
  • 2021-07-13: published as per the GitHub SecLab disclosure policy.

The issue was discovered and reported by GitHub team member @erik-krogh (Erik Krogh Kristensen). It is tracked as CVE-2020-26305 and GHSL-2020-291.

Glossary

  • Regular expression (regex): a short pattern language for describing text, used to find or validate strings.
  • Matching engine: the part of a language runtime that walks through text trying to fit a regex to it.
  • ReDoS (Regular Expression Denial of Service): a denial of service caused by a regex that becomes extremely slow on crafted input.
  • Denial of service: making a service unavailable to its normal users, without necessarily stealing or changing data.
  • Backtracking: when a matcher abandons a failed attempt and goes back to try a different way of matching.
  • Exponential backtracking: backtracking where each extra input character multiplies the number of attempts, so the work explodes.
  • O(2^n): notation for work that roughly doubles with each additional input character.
  • Ambiguity or overlap: when two parts of a regex can match the same characters, giving the engine several choices at each position.
  • Character class: a regex construct that matches one character from a set, such as \s for whitespace or \w for word characters.
  • Quantifier: a regex symbol saying how many times something repeats, such as + (one or more) or *? (as few as possible).
  • Nested quantifier: a repetition placed inside another repetition, the usual source of exponential backtracking.
  • CommonRegexJS: a JavaScript package offering a general purpose collection of regexes for matching common kinds of strings.
  • npm: the public package registry for JavaScript, and the command line tool that installs packages from it.
  • Node.js: a program that runs JavaScript outside a browser.
  • CodeQL: a static analysis tool that turns source code into a queryable database so you can search for patterns such as risky regexes.
  • Static analysis: examining code without running it, to find problems automatically.
  • Proof of concept (PoC): a small, concrete demonstration that a reported problem really happens.
  • Server: a computer that answers requests from other computers over a network.
  • Untrusted input: text that comes from strangers and could be deliberately crafted.
  • CVE: a public identifier assigned to a known security vulnerability so people can refer to it unambiguously.
  • GHSL: GitHub Security Lab, the team that found and published this advisory.
  • Disclosure deadline: an agreed date after which a reported issue may be published even if it is not yet fixed.
  • Commit: a saved snapshot of a code repository at a particular point in time.

More by ghsecuritylab

View all

132 more disclosed reports, best first.

More from GitHub Security Lab

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.