Php Regex With User Input
Description
This vulnerability detector identifies PHP regular expression functions that use user-controlled input for both the pattern and subject parameters. When regex patterns are constructed from user input, attackers can inject malicious patterns that cause ReDoS (Regular expression Denial of Service) attacks or bypass input validation, leading to performance degradation or security bypasses.
Detection Strategy
• Identifies function calls to dangerous PHP regex functions (like preg_match, preg_replace, etc.)
• Verifies the function has at least 2 arguments (pattern and subject parameters)
• Checks if the first argument (regex pattern) originates from user-controlled input sources
• Checks if the second argument (subject string) also originates from user-controlled input sources
• Reports a vulnerability when both the regex pattern and subject string are derived from user input
Vulnerable code example
<?php
function search_content() {
$pattern = $_GET['regex']; // User controls regex pattern
preg_match($pattern, $_POST['text']); // VULNERABLE: ReDoS attack possible
$filter = $_REQUEST['filter'];
preg_match_all($filter, $data, $matches); // VULNERABLE: Unvalidated regex input...✅ Secure code example
<?php
function search_content() {
$pattern = preg_quote($_GET['regex'], '/'); // Escape special regex chars to prevent ReDoS
preg_match('/' . $pattern . '/', $_POST['text']);
$filter = preg_quote($_REQUEST['filter'], '/'); // Sanitize user input before regex use
preg_match_all('/' . $filter . '/', $data, $matches);...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.