Linux – How to remove injected code between two strings recursively in PHP files using SSH

linuxPHPsshubuntu-14.04

We have in-house Linux(Ubuntu) development server. Few days ago suspicious code was injected. Just to mention here that we have more than 300 projects. Code is injected in almost every file recursively.

We tried Dreamweaver on Windows on LAN to search and replace but found another reason that did not work using DreamWeaver;

Injected code getting started with PHP starting TAG:

<?php $ldtxxk

and in between there is lot of encrypted code but all files have different code BUT ending with PHP ending TAG. So due to completely changed code in all files, we are unable to clean it using any software to find and replace.

So we need some kind of SED command with regular expression in SSH which can do a recursive job on specific director to

find from

<?php $ldtxxk

to

?>

and remove everything between including PHP starting and ending TAGs.

Thanks in advance.

Best Answer

At first try something like this. It deletes(d) the text between the two patterns (delimited by slashes):

sed '/<?php $ldtxxk/,/?>/d' file_with_injected_code.php

If the output looks good, you can insert a "-i" so that the content of the file gets replaced:

sed '/<?php $ldtxxk/,/?>/d' file_with_injected_code.php

Then you can combine the sed command with a find command to search recursively for php files beginning in the working directory:

find -name '*.php' -exec sed -i '/<?php $ldtxxk/,/?>/d' '{}' \;

If you fixed the php files you should investigate how the attacker got access. Check the log files!

Is your machine accessible from the internet?

  • Do you run a FTP server? Perhaps with weak passwords? Consider changing these passwords or use SFTP with public keys.
  • Do you have a vulnerable php application? Perhaps the attacker used it to upload a php script. Move upload folder outside the webroot, deny php file upload or remove permission from files so that they don't get interpreted/delivered by the webserver.