andrux
andrux

Reputation: 2922

How can I remove a malicious line of code and replace it with the opening php tag using regex, in multiple files?

I use a domain in my server for dev websites, I have put them all as subdomains in the same domain, like client1.mydomain.com, client2.mydomain.com, and so on. Well, all of these websites were targeted by a malicious code, it seems it's always the very first line in the files - all the files in the sites it seems.

I'm looking for a way of removing this malicious line of code, but replace it with the opening php tag - or anything that will only remove the malicious code and not my opening php tag where it exists.

Here's what the malicious line looks like:

<?php $vhilmjpo = 'x53 105 x53 137 ........ (it goes like this with random strings and numbers for a long while) .... (and it finishes with the ending php tag) ... ?>

The problem is that sometimes my files start with the php opening tag and sometimes it's plain html, so I can't just remove the complete line and replace with <?php

So, sometimes, the files start like this:

<?php $vhilmjpo = 'x53 .......?><?php

and sometimes it's like this:

<?php $vhilmjpo = 'x53 .......?><div class="whatever">

I have used sed in the past, and it proves to be of great help, but I don't know how to do it for this particular case.

Something like this could work if all of my files had the malicious line on a line of its own, but that's not the case:

sed -i '/vhilmjpo/d'

Any idea of how to do this? I was thinking probably a regex to match only between the php tags, something like <?php $vhilmjpo[.+?]\?>, and replace all of that with an empty string.

Upvotes: 0

Views: 193

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

You can try this one:

sed '1{s/<?php \$vhilmjpo\([^?]\|??*[^?>]\)*?>//}' file

and if it works as expected then add the -i switch.

details:

1   # if the first line is processed then: 
{
    s/<?php \$vhilmjpo\([^?]\|??*[^?>]\)*?>// # replace from the opening tag followed
                                # by "$vhilmjpo" until the next closing tag
}

Upvotes: 1

Related Questions