I recently found some code vulnerable to this attack in the wild, so I thought I’d put together a quick write up for pentesters and PHP coders who may not be familiar with the danger. The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings.
To exploit the code, all the attacker has to do is provide some PHP code to execute, generate a regular expression which replaces some or all of the string with the code, and set the `e` modifier on the regular expression/pattern
PHP provides a function named as preg_quote() which will quote all nasty characters in the input string and prevent this code execution vulnerability.
Its subtle yet deadly nature make it an easy vulnerability to miss when developing and reviewing code.