Today we’re gonna exploit one of the most popular PHP function i.e. preg_replace() which is used by many developers and can further lead to a Code Execution vulnerability.
The preg_replace() function operates just like POSIX function ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
Here, we’ve a simple vulnerable code:
<?php
$abc = ‘Wow, Thank you Yeahhub’;
echo preg_replace($_GET[‘replace’], $_GET[‘with’], $abc);
?>
This code will take a user input and replace whatever it matches with string. So if we were to call preg.php?replace=/you/i&with=you so much, the script would perform a case-insensitive regex search (with i modifier) and echo something as shown below:
Read More: About pattern modifiers
As you can see, we successfully replaced the you string with you so much. Now for further exploitation, you need to replace the i modifier with e modifier which will cause PHP to execute the result of preg_replace() operation as PHP code.
To exploit the above code, the attacker has to pass some PHP code to execute, generate a regular expression which replaces some string with the code with e modifier as shown below:
Exploit Code: preg.php?replace=/you/e&with=phpinfo();
As you can see that, the complete command output is displayed in screen with just e modifier and similarly you can also call system() function followed by the string with the match replaced with the last line of output as shown below:
In later versions of PHP (PHP >= 5.5.0), this has been completely depreciated because of insecure nature but there are still so many web servers who are still using older version of PHP (5.2 or 5.3).
Prevention –
PHP provides a handy function named as preg_quote() which will quote all nasty characters in the input string and prevent this code execution vulnerability.
<?php
$abc = ‘Wow, Thank you Yeahhub’;
echo preg_replace(‘#’ . preg_quote($_GET[‘replace’], ‘#’) . ‘#’, $_GET[‘with’], $abc);
?>
Using the above function i.e. preg_quote() renders all the regex characters, so if you need to allow some access to use regular expressions, you’ll need to escape your delimitation character by hand.
Ultimately the use of such a function is always going to be a problem. Instead we should be using functions which allow us to specify the search strings and replacement strings as separate parameters, removing control from the attacker.
You may also like:- Top Skills Needed to Become a Cybersecurity Analyst
- Mastering Windows Management with WMIC Commands – Top 20 Examples
- Edit and Compile Code with the Best 5 Code Editors
- 50+ Top DevSecOps Tools You Need To Know
- Learn How to Add Proxy and Multiple Accounts in MoreLogin
- Some Useful PowerShell Cmdlets
- Create Free SSL Certificate – ZEROSSL.COM [2020 Tutorial]
- Generate Self-Signed SSL Certificate with OPENSSL in Kali Linux
- RDP – CredSSP Encryption Oracle Remediation Solution 2020
- Scan Open Ports using Ss, Netstat, Lsof and Nmap