The unexpected dangers of preg_replace()
Published
I was reminded by a recent article of an obscure and dangerous property of PHP's preg_replace() function which can lead to code execution in some not-all-that-uncommon circumstances. I recently found some code vulnerable to this attack in the wild, so I thought I'd put together a quick writeup for pentesters and PHP coders who may not be familiar with the danger.
Let's start with a code example:
<?php
$in = 'Somewhere, something incredible is waiting to be known';
echo preg_replace($_GET['replace'], $_GET['with'], $in);
?>
The code will take a user-supplied regular expression and replace whatever it matches with a user-supplied string. So if we were to call preg_replace.php?replace=/Known/i&with=eaten, the script would perform a case-insensitive regex search (the i modifier) and echo Somewhere, something incredible is waiting to be eaten. Seems safe enough, right?