Scivic
Scivic

Reputation: 7

Regex to remove and preserve lines

I'm looking to use the following regex line to remove malicious code from my site;

find -type f -name \*.php -exec sed -i 's/.*eval(base64_decode(\"CmVycm.*/<?php/g' {} \;

This will preserve <?php which I want but I noticed that many of the injections are throughout php files on multiple lines, meaning not just the very first <?php So is it possible to do an if do otherwise statement where if its on line 1 of a php file preserve the php tag otherwise remove the entire line if its anywhere else?

Upvotes: 0

Views: 246

Answers (2)

Utopik
Utopik

Reputation: 3783

The response from devnull isnt accepted, so here's mine

If the malicious code takes one line, you can easily do :

sed -i "/eval(base64_decode(/d" filename

which will delete the all line.

if you worry about the first <?php

sed -i -e "/<?php/! {1 s/^/<?php /}" filename

It will add a <?php tag if it does not exist at the first line. How does it work ?

/<?php/! will match lines without <?php in it.

{1 s/^/<?php /} In the first line, add <?php at the beginning

More ?

If the code takes 2 lines :

<?php
exec(base64_decode() ... ?>

sed -i '/<?php/{N;/exec(base64_decode/d;}' filename

If a line matches <?php and the next line matches exec(base64_decode, delete both lines.

N; is for loading the next line in the current buffer. d; delete the current buffer ( = both lines )

If the code takes 3 lines :

<?php
exec(base64_decode() ...
?> 

sed -i '/<?php/{N;/exec(base64_decode/{N;d;};}' filename

Idem, but load the third line before deleting (N;d;)

Not enough?

Paste a full example of the string injected.

Hope this help, cheers

Upvotes: 1

devnull
devnull

Reputation: 123608

Instead of saying:

sed -i 's/.*eval(base64_decode(\"CmVycm.*/<?php/g'

say:

sed -i 's/eval[(]base64_decode[(]["]CmVycm.*//g'

This would preserve the <?php tag and also remove the malicious code from lines where the tag doesn't exist!

EDIT: As commented by Birei, you can say:

sed -i -e '1 s/.*eval[(]base64_decode[(]["]CmVycm.*/<?php/g' -e '2,$ s/.*eval[(]base64_decode[(]["]CmVycm.*//g'

Upvotes: 1

Related Questions