Unsafe preg_replace usage

Published on 24 Jun 2018
Vulnerability

The preg_replace is a function present in the PHP language to perform search and replace. The preg_replace is an obsolete function in PHP which can have major consequences in certain situations. An attacker can easily use the preg_replace function to perform attacks on the server to access sensitive information. The attacker uses the ‘e’ modifier to the preg_replace function to make the replaced content executable in PHP. Using this modifier, the attacker can execute any PHP functions to attack inside the server. Consider if the user controls the regex pattern and the replacement string parameter, the attacker will be able to perform PHP code execution attack.

Example

The below code will output the contents of passwd. Leaking this information can have catastrophic impacts on the application.

        preg_replace("/.*/e","system('echo /etc/passwd')");

    

Impact

The major impacts include:-

  • Malicious code execution
  • Possible information leakage

Mitigation / Precaution

  • Beagle recommends avoiding the usage of preg_replace in the application.
Rejah Rehim
Written by
Co-founder, Director

Rejah brings more than 12 years of industry experience in Information Technology. He is a fervent security enthusiast and serves as a Project Leader at OWASP Foundation, and Commander (Hon.) at Kerala Police. He has authored two books titled “Effective Python Penetration Testing” and “Python Penetration Testing Cookbook” and is the creator of 9 Mozilla add-ons.

Experience the Beagle Security platform
Unlock one full penetration test and all Advanced plan features free for 14 days
4.8 on G2 • ISO 27001 certified
See How Beagle Security Works
No credit card • No setup required
Launch interactive demo