'Avoiding Redos Attacks

Using regular expressions is a little bit tricky especially in Node.js applications. Because It can cause REDOS attacks. I thought that maybe running all regular expression matches in another thread than the event loop. But I am not sure that it is a good practice or not. Could you help to identify that if I run all matches in another thread, It will be able to help me to avoid this kind of attack?



Solution 1:[1]

You can avoid ReDOS by using atomic groups and possessive quantifiers.

While these features are not supported natively in JS (there is a proposal pending), you can emulate them by using the /(?=(...))\1/ pattern around the bit that would otherwise backtrack. That pattern means that whatever \1 matches will be set in stone for this parse, since the JS RegExp engines won't backtrack into look ahead assertions (/(?=...)/), per spec.

Adding visual noise to an already complex RegExp may not be everyone's cup of tea though, and in that case, you may want to use a library like compose-regrexp that provides an atomic() helper that can be composed with other RegExp-building functions:

import {atomic, sequence} from 'compose-regexp'

// classic ReDOS-vulnerable RegExp:
const ReDOS = /^(([a-z])+.)+[A-Z]([a-z])+$/

// fixed with compose-regexp, this does not backtrack
const fixed = sequence(/^/, atomic(/(([a-z])+.)+/), /[A-Z]([a-z])+$/)

You can see it in action here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1