Removing malicious code with perl and sed…
by Eric on Feb.10, 2009, under Linux, One-liners
Today, I had an instance where a customer's site had been attacked with a code injection affected all of his .php files. In this case, it was an old vBulletin install that had several known exploits on milw0rm (proof you should update often) that caused it.
Fortunately, the code was injected as a single line, and was the same in every file, and had the added benefit of being on the top line of the file. So, I could use abit of perl to remove it, and then a bit of sed magic to remove the blank line left by Perl (because for some reason, it didn't want to remove the newline).
The perl code was relatively straightforward. Using -pi -e, we were able to edit in place each file (with much escapism to avoid regex traps, when in doubt escape anything consider special to regex):
for i in `find -iname "*.php"`;do perl -pi -e s/"\<\?php \/\*\*\/eval\(base64_decode\('SomeObfuscatedCodeHereThatIWontDisplayForObviousReasons'\)\); \?\>"//g $i;done
Once all of the files were edite, and the code removed, we used a quick sed one-liner to remove the line at the beginning of the file, as a lot of php scripts (vBulletin, included) will b0rk if there's anything before the opening <?
for i in `find -iname "*.php"`;do sed '1d' $i > $i.fixed && mv -f $i.fixed $i;done
With those two snippets, I removed the code from around a hundred php files in less than two minutes (the sed work took a bit to process on some files). Only one file had an issue, and that was the config.php that apparently was not infected. All-in-all, the ticket resolution took less than 8 minutes, including testing and writing out the reply. Edit 100 files, remove a bunch of code, test, reply to user in 8 minutes? Not too bad.





