[Code Execution] – preg_replace() PHP Function Exploitation

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 modifier with 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 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 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:

Sarcastic Writer

Step by step hacking tutorials about wireless cracking, kali linux, metasploit, ethical hacking, seo tips and tricks, malware analysis and scanning.

Related Posts