Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 841
VusalIs Avatar asked Sep 13 '25 22:09

VusalIs


1 Answers

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.

like image 192
Pygy Avatar answered Sep 15 '25 11:09

Pygy