Find PHP malware in Linux

Last Updated on October 15, 2023 by Dave Farquhar

A lot of people seem to be looking for help cleaning up hacked or infected web sites lately, so here’s a trick I used in the past to find PHP malware in Linux and clean up the infected files.

Find PHP malware in Linux
Any unreadable PHP file like this one is up to no good.

PHP malware is always obfuscated, to hide its purpose. And in my experience, the infection will generally live in the first line or two of the file. That way when the infected file runs, it does its malicious stuff, then runs normally, so you may not ever notice, except for stuff being slower all of a sudden because all of your PHP files are suddenly doing twice as much work.

So a good way to find an infection is to search for strings like x24, x27, x28 and x29, which represent innocent ASCII characters frequently found in code: the dollar sign, apostrophe and parenthesis characters. The only reason to hide those characters is to obfuscate code. Here’s a grep command to search for hex 24.

grep -r x24 * | more

Replace the piece in bold and repeat with some others like x27, x28, and x29.

Or, to find base64-encoded PHP malware, try this:

grep -r base64_decode * | more

If you get a lot of hits, you probably have an infection. Restore the infected files from a backup or original source and you’re good to go.

Or if you’re brave, you can clean it up manually–but be careful. It’s easy at this point to do more harm than good. Look for the beginning of the PHP malware, then use the Unix utility sed to remove the line. Here’s a sequence I used to clean up some malware once:

cd /var/www
find . -type f -name "*.php" -exec sed -i 's/<?php $vIIJ30Y.* ?>//g' {} +

The stuff in bold will vary based on your system and what it’s infected with. If you’re an experienced Unix administrator, I’ve told you all you need to know at this point. If you’re not, at this point I recommend you enlist the help of one, as it’s very easy to do more harm than good. Messing around with sed is much faster, but restoring them from backups is far more reliable.

Do this enough times, and like it or not, you have incident response experience. There’s a need for experienced incident responders, so that may not be a bad thing. Finding PHP malware in Linux is a useful skill, and the question of how you do it sometimes even comes up in job interviews.

If you found this post informative or helpful, please share it!