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);
A bad regex pattern can lead to low performance or even erroneous results. But can it also lead to vulnerabilities? Poorly designed regex patterns are actually a big source of vulnerabilities in modern web applications. They can lead to failed input validation, leaky firewalls, and even denial of service attacks.
Regular expressions (or regex) are incredibly helpful tools to have at your disposal as a software developer, but they're often dangerous tools.
At its most basic, a regular expression (or "regex") is just a string that describes a pattern to be matched. For example, imagine a program scanning lines in one or more files, looking for lines that contain the regular expression pattern of interest. When it finds a line with that pattern, it prints that line out.
Despite being hard to read, hard to validate, hard to document and notoriously hard to master, regexes are still widely used today. Supported by all modern programming languages, text processing programs and advanced text editors, regexes are now used in more than a third of both Python and JavaScript projects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With