Back to results for “Security”
PHP › Regular Expressions in PHP

What is catastrophic backtracking in regular expressions, and how can a poorly constructed pattern cause a severe performance problem or even hang a PHP application?

Advanced

Answer

Catastrophic backtracking occurs when a regular expression pattern containing nested or ambiguous repetition, such as multiple overlapping quantifiers that could match the same text in many different possible ways, is applied to certain input strings, causing the regular expression engine to explore an enormous, exponentially growing number of possible matching combinations before finally failing, which can consume massive amounts of processing time and effectively hang the application, making it important to carefully design patterns, particularly those handling user supplied input, to avoid this kind of ambiguous, deeply nested repetition.
// Potentially catastrophic pattern with nested quantifiers
// preg_match('/^(a+)+$/', $userInput);
// A carefully crafted malicious input could cause this to hang
Real-world example A security review flags a regular expression pattern used to validate user input as vulnerable to catastrophic backtracking, and the team rewrites the pattern using a more carefully constrained, unambiguous structure to eliminate the risk of a malicious input causing a denial of service.

Common follow-ups: How do you identify whether a specific regular expression pattern is vulnerable to catastrophic backtracking?;What tools or techniques help test a pattern's performance against a wide range of adversarial inputs?