Is it safe to use user's RegEx?

2019-04-04 03:18发布

问题:

I want to add a feature to my website to let users search the texts with RegEx. But, is it safe to let the users do something like that ?

preg_match('/' . $user_input_regex . '/', $subject);

回答1:

There is a possible attack on this code called a ReDoS attack (Regular expression Denial of Service).

The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). An attacker can then cause a program using a Regular Expression to enter these extreme situations and then hang for a very long time.

Specifically with preg_match there is a known issue that can cause a PHP Segmentation Fault.

So the answer is no, it is not safe because of issues such as these.



回答2:

Security wise you should never trust user input, so it depends what you do with the input. In your given case you should at least escape the used delimiter (backslash) in the user input to ensure the regex works.