How can I search and replace all files recursively to remove some rogue code injected into php files on a wordpress installation? - perl

How can I search and replace all files recursively to remove some rogue code injected into php files on a wordpress installation? The hacker added some code (below) to ALL of the .php files in my wordpress installation, and it happens fairly often to many sites, and I spend hours manually removing the code.
Today I tried a number of techniques I found online, but had no luck due to the long code snippet and the many special characters in it that mess up the delimiters. I tried using different delimiters with perl:
perl -p -i -e 's/rogue_code//g' *
to
perl -p -i -e 's{rogue_code}{}g' *
and tried using backslashes to escape the slashes in the code, but nothing seems to work. I'm working on a shared server, so I don't have full access to all the directories outside my own.
Thanks a lot...here's the code:
< ?php /**/ eval(base64_decode("aWYoZnVuY3
... snip tons of this ...
sgIH1lbHNleyAgICB9ICB9"));? >

Without having a chance to poke around the files myself, it's hard to be sure; but it sounds like you need:
find -name '*.php' -exec perl -i -pe 's{<\?php /\*\*/ eval\(base64_decode\("[^"]+"\)\);\?>}{}g' '{}' ';'
(That said, I agree with the commenters above that trying to undo the damage, piecemeal, after it happens is not the best strategy.)

and it happens fairly often to many sites, and I spend hours manually
removing the code....
Sounds like you need to do a better job of cleaning the hack or change hosts. Replace all WP core files and foldere, all plugins, and then all you have to do is search theme files and wp-config.php for the injected scripts.
See How to completely clean your hacked wordpress installation and How to find a backdoor in a hacked WordPress and Hardening WordPress « WordPress Codex and Recommended WordPress Web Hosting

I have the same problem (Dreamhost?) and first run this clean.pl script:
#!/usr/bin/perl
$file0 =$ARGV[0];
open F0,$file0 or die "error opening $file0 : $!";
$t = <F0>;
$hacked = 0;
if($t =~ s#.*base64_decode.*?;\?>##) {
$hacked=1;
}
print "# $file0: " . ($hacked ? "HACKED" : "CLEAN") . "\n";
if(! $hacked) {
close F0;
exit 0;
}
$file1 = $file0 . ".clean";
open F1,">$file1 " or die "error opening $file1 for write : $!";
print F1 $t;
while(<F0>) {
print F1;
}
close F0;
close F1;
print "mv -f $file0 $file0.bak\n"; #comment this if you don't want backup files.
print "mv -f $file1 $file0\n";
with find . -name '*.php' -exec perl clean.pl '{}' \; > cleanfiles.sh
and then I run . cleanfiles.sh
I also found that there were other differently infected files ("boostrap" infecters, those which triggered the other infection), which instead of the base64_decode call had some hex-escaped command... To detect them, this suspicious_php.sh :
#!/bin/sh
# prints filename if first 2 lines has more than 5000 bytes
file=$1
bytes=`head -n 2 $file | wc --bytes `
if (( bytes > 5000 ))
then
echo $file
fi
And then: find . -name '*.php' -type f -exec ./suspicious_php.sh '{}' \;
Of course, all this is not foolproof at all.

Related

write filename as first line in a txt file + text around it / osx perl

I'm complete newby to perl and I hope you can help me with this line of code.
The issue is related to this one here, but it doesn't quite answer my question. I tried looking for it, but I just get more confused.
I have a txt input (batch) that I want to have a filename printed in the first line, but wrapped in a specific text. I am converting these files later into html and so I would like the .name to have "<div class="head">" printed before and "</div>" afterwards.
Here is the code I have and it works to print the name:
perl -i -pe 'BEGIN{undef $/;} s/^/$ARGV\n/' `find . -name '*.txt'`
I run this by first navigating to the directory where all the files are.
example of filename: 2016-05-20_18.32.08.txt
the files are plane text poetry and in the output i get:
./2016-05-20_18.32.08.txt
in the first line.
I tried something like this:
perl -i -pe 'BEGIN{undef $/;} s/^/$ARGV\n/' `find . -name ‘“<div class="head”>”’*.txt’”</div>”’
but of course it doesn't work. it just give me a >
I need to add the arguments in this part s/^/$ARGV\n/' but i already have troubles defining it.
Can you help pls?
In addition, the filename prints with ./ in the beginning, is there a simple way to exclude that?
perl -i -pe 'BEGIN{undef $/;} s/^/<div class=head> $ARGV <\/div>\n<div class=poem>\n/; s/$/\n<\/div>/' `find . -name '*.txt'`
This should work. But if you are new to perl, I suggest you try working with scripts rather than one-liners.
The -i flag will edit the file inplace. so if you want a html file, remove -i and redirect to another .html file.
I'm sure there is a more elegant way of doing it, but something like this will work
#!/usr/bin/perl
undef $/;
for (#ARGV){
open($fh,$_);
$content=<$fh>;
close($fh);
open($fh,">$_");
print $fh "<div class=\"head\">$_</head>\n$content";
close($fh)
}

Reading a file on a remote host

My code involves going to a host(doing with openSSH), getting the list of files matching a pattern(doing using remote find command-OpenSSH) and then opening each file I have got and processing each(grepping etc).
I am done with getting the file names and passing to a function. Now, I have to pass these filename to a function where I open each and process it. I am trying to do it using File::Remote as follows:
sub processFiles{
my $fileList =shift;
#Iterate over the file and try to find start and stop time stamps from the file
for my $file ( #{$fileList}) {
#finding start time of file:its found in lines of file
my $HEAD;
open $HEAD, "host:head -1000 $File|" or die "Unable to check file for starting time";
while ( <$HEAD> ) {
#process...
But I am unable to open the file on the host an I am getting an error.
When performing remote actions in batch, the first principle is to reduce the number of ssh connections (ideally only one). Using shell or perl one liner, you can do very complex actions. Here is my understanding of your need:
ssh hostname 'find dirname -name \*.pl| xargs grep -l pattern /dev/null'
You can pipe further processing in the same line. If you want to process the files locally, you can transfer all the files in a single command. Here is a full example:
use Archive::Tar;
open my $file, '-|', 'ssh -C hostname "find dirname -name \*.pl | xargs grep -l pattern /dev/null | xargs tar c"'
or die "Can't pipe: $!";
my $tar = Archive::Tar->new($file);
foreach my $file ($tar->get_files()) {
print $file->name, ', ', $file->size, "\n";
}
The File::Remote module is not part of a standard Perl installation. If you want to use this module, then you need to install it.
How you install it will depend on what platform you're using and how you have installed Perl. On a Linux installation where you are using the system Perl you could try sudo yum install perl-File-Remote (on a RedHat-based system) or sudo apt-get install libfile-remote-perl (on a Debian/Ubuntu-based system). You could also try using cpan or cpanm to install it.
I'd also suggest that as this module was last updated in 2005, it's quite likely that it is unmaintained, so I would be wary of using it.

How to execute cleartool command within perl

Sorry if its to naive. I am wanting to write a simple PERL script that will accept two arguments(Here Commit Labels) which are taken as inputs to cleartool command and provides me with a suitable output.
My Code:
#!/usr/bin/perl
$file1 = system('cleartool find . -version "lbtype($ARGV[0])" -print > filename1');
$file2 = system('cleartool find . -version "lbtype($ARGV[1])" -print > filename2');
$file3 = system('diff filename1 filename2 > changeset');
print $ARGV[0];
print $ARGV[1];
print $file3;
close filename1;
close filename2;
close changeset
The output now is 3 empty files: filename1,filename2 and changeset.
But i need the files committed between the two committed labels.
Could anyone shed light as to where i am going wrong!!
Thanks in advance.
try this:
$file1 = system("cleartool find . -version 'lbtype($ARGV[0])' -print > filename1");
instead of
$file1 = system('cleartool find . -version "lbtype($ARGV[0])" -print > filename1');
You have also some Perl package to facilitate the execution of cleartool commands.
package CCCmd: you can see it illustrated in "How can I interact with ClearCase from Perl?"
ClearCase::CtCmd
That would allow to directly get the result in an array, instead of a file (even though you can dump that array in a file if you need to)
#res = ClearCase::CtCmd::exec("find . -version 'lbtype($ARGV[0])' -print");

How do I run a Perl script on multiple input files with the same extension?

How do I run a Perl script on multiple input files with the same extension?
perl scriptname.pl file.aspx
I'm looking to have it run for all aspx files in the current directory
Thanks!
In your Perl file,
my #files = <*.aspx>;
for $file (#files) {
# do something.
}
The <*.aspx> is called a glob.
you can pass those files to perl with wildcard
in your script
foreach (#ARGV){
print "file: $_\n";
# open your file here...
#..do something
# close your file
}
on command line
$ perl myscript.pl *.aspx
You can use glob explicitly, to use shell parameters without depending to much on the shell behaviour.
for my $file ( map {glob($_)} #ARGV ) {
print $file, "\n";
};
You may need to control the possibility of a filename duplicate with more than one parameter expanded.
For a simple one-liner with -n or -p, you want
perl -i~ -pe 's/foo/bar/' *.aspx
The -i~ says to modify each target file in place, and leave the original as a backup with an ~ suffix added to the file name. (Omit the suffix to not leave a backup. But if you are still learning or experimenting, that's a bad idea; removing the backups when you're done is a much smaller hassle than restoring the originals from a backup if you mess something up.)
If your Perl code is too complex for a one-liner (or just useful enough to be reusable) obviously replace -e '# your code here' with scriptname.pl ... though then maybe refactor scriptname.pl so that it accepts a list of file name arguments, and simply use scriptname.pl *.aspx to run it on all *.aspx files in the current directory.
If you need to recurse a directory structure and find all files with a particular naming pattern, the find utility is useful.
find . -name '*.aspx' -exec perl -pi~ -e 's/foo/bar/' {} +
If your find does not support -exec ... + try with -exec ... \; though it will be slower and launch more processes (one per file you find instead of as few as possible to process all the files).
To only scan some directories, replace . (which names the current directory) with a space-separated list of the directories to examine, or even use find to find the directories themselves (and then perhaps explore -execdir for doing something in each directory that find selects with your complex, intricate, business-critical, maybe secret list of find option predicates).
Maybe also explore find2perl to do this directory recursion natively in Perl.
If you are on Linux machine, you could try something like this.
for i in `ls /tmp/*.aspx`; do perl scriptname.pl $i; done
For example to handle perl scriptname.pl *.aspx *.asp
In linux: The shell expands wildcards, so the perl can simply be
for (#ARGV) {
operation($_); # do something with each file
}
Windows doesn't expand wildcards so expand the wildcards in each argument in perl as follows. The for loop then processes each file in the same way as above
for (map {glob} #ARGV) {
operation($_); # do something with each file
}
For example, this will print the expanded list under Windows
print "$_\n" for(map {glob} #ARGV);
You can also pass the path where you have your aspx files and read them one by one.
#!/usr/bin/perl -w
use strict;
my $path = shift;
my #files = split/\n/, `ls *.aspx`;
foreach my $file (#files) {
do something...
}

How can I scan multiple log files to find which ones have a particular IP address in them?

Recently there have been a few attackers trying malicious things on my server so I've decided to somewhat "track" them even though I know they won't get very far.
Now, I have an entire directory containing the server logs and I need a way to search through every file in the directory, and return a filename if a string is found. So I thought to myself, what better of a language to use for text & file operations than Perl? So my friend is helping me with a script to scan all files for a certain IP, and return the filenames that contain the IP so I don't have to search for the attacker through every log manually. (I have hundreds)
#!/usr/bin/perl
$dir = ".";
opendir(DIR, "$dir");
#files = grep(/\.*$/,readdir(DIR));
closedir(DIR);
foreach $file(#files) {
open FILE, "$file" or die "Unable to open files";
while(<FILE>) {
print if /12.211.23.200/;
}
}
although it is giving me directory read errors. Any assistance is greatly appreciated.
EDIT: Code edited, still saying permission denied cannot open directory on line 10. I am just going to run the script from within the logs directory if you are questioning the directory change to "."
Mike.
Can you use grep instead?
To get all the lines with the IP, I would directly use grep, no need to show a list of files, it's a simple command:
grep 12\.211\.23\.200 *
I like to pipe it to another file and then open that file in an editor...
If you insist on wanting the filenames, it's also easy
grep -l 12\.211\.23\.200 *
grep is available on all Unix//Linux with the GNU tools, or on windows using one of the many implementations (unxutils, cygwin, ...etc.)
You have to concatenate $dirname with $filname when using files found through readdir, remember you haven't chdir'ed into the directory where those files resides.
open FH, "<", "$dirname/$filname" or die "Cannot open $filname:$!";
Incidentally, why not just use grep -r to recursively search all subdirectories under your log dir for your string?
EDIT: I see your edits, and two things. First, this line:
#files = grep(/\.*$/,readdir(DIR));
Is not effective, because you are searching for zero or more . characters at the end of the string. Since it's zero or more, it'll match everything in the directory. If you're trying to exclude files ending in ., try this:
#files = grep(!/\.$/,readdir(DIR));
Note the ! sign for negation if you're trying to exclude those files. Otherwise (if you only want those files and I'm misunderstanding your intent), leave the ! out.
In any case, if you're getting your die message on line 10, most likely you're hitting a file that has permissions such that you can't read it. Try putting the filename in the die output so you can see which file it's failing on:
open FILE, "$file" or die "Unable to open file: $file";
But as with other answers, and to reiterate: Why not use grep? The unix command, not the Perl function.
This will get the file names you are looking for in perl, and probably do it much faster than running and doing a perl regex.
#files = `find ~/ServerLogs -name "*.log" | xargs grep -l "<ip address>"`'
Although, this will require a *nix compliant system, or Cygwin on Windows.
Firstly get a list of files within your source directory:
opendir(DIR, "$dir");
#files = grep(/\.log$/,readdir(DIR));
closedir(DIR);
And then loop through those files
foreach $file(#files)
{
// file processing code
}
My first suggest would be to use grep instead. The right tool for the job, they say...
But to answer your question:
readdir just returns the filenames from the directory. You'll need to concatenate the directory name and filename together.
$path = "$dirname/$filname";
open FH, $path or die ...
Then you should ignore files that are actually directories, such as "." and "..". After getting the $path, check to see if it's a file.
if (-f $path) {
open FH, $path or die ...
while (<FH>)
BTW, I thought I would throw in a mention for File::Next. To iterate over all files in a directory (recursively):
use Path::Class; # always useful.
use File::Next;
my $files = File::Next::files( dir(qw/path to files/) ); # look in path/to/files
while( defined ( my $file = $files->() ) ){
$file = file( $file );
say "Examining $file";
say "found foo" if $file->slurp =~ /foo/;
}
File::Next is taint-safe.
~ doesn't auto-expand in Perl.
opendir my $fh, '~/' or die("Doin It Wrong"); # Doing It Wrong.
opendir my $fh, glob('~/') and die( "Thats right!" );
Also, if you must use readdir(), make sure you guard the expression thus:
while (defined(my $filename = readdir(DH))) {
...
}
If you don't do the defined() test, the loop will terminate if it finds a file called '0'.
Have you looked on CPAN for log parsers? I searched with 'log parse' and it yielded over 200 hits. Some (probably many) won't be relevant - some may be. It depends, in part, on which web server you are using.
Am I reading this right? Your line 10 that gives you the error is
open FILE, "$file" or die "Unable to open files";
And the $file you are trying to read, according to line 6,
#files = grep(/\.*$/,readdir(DIR));
is a file that ends with zero or more dot. Is this what you really wanted? This basically matches every file in the directory, including "." and "..". Maybe you don't have enough permission to open the parent directory for reading?
EDIT: if you only want to read all files (including hidden ones), you might want to use something like the following:
opendir(DIR, ".");
#files = readdir(DIR);
closedir(DIR);
foreach $file (#files) {
if ($file ne "." and $file ne "..") {
open FILE, "$file" or die "cannot open $file\n";
# do stuff with FILE
}
}
Note that this doesn't take care of sub directories.
I know I am way late to this discussion (ran across it while searching for grep related posts) but I am going to answer anyway:
It isn't specified clearly if these are web server logs (Apache, IIS, W3SVC, etc.) but the best tool for mining those for data is the LogParser tool from Microsoft. See logparser.com for more info.
LogParser will allow you to write SQL-like statements against the log files. It is very flexible and very fast.
Use perl from the command line, like a better grep
perl -wnl -e '/12.211.23.200/ and print;' *.log > output.txt
the benefit here is that you can chain logic far easier
perl -wnl -e '(/12.211.23.20[1-11]/ or /denied/i ) and print;' *.log
if you are feeling wacky you can also use more advanced command line options to feed perl one liner result into other perl one liners.
You really need to read "Minimal Perl: For UNIX and Linux People", awesome book on this very sort of thing.
First, use grep.
But if you don't want to, here are two small improvements you can make that I haven't seen mentioned yet:
1) Change:
#files = grep(/\.*$/,readdir(DIR));
to
#files = grep({ !-d "$dir/$_" } readdir(DIR));
This way you will exclude not just "." and ".." but also any other subdirectories that may exist in the server log directory (which the open downstream would otherwise choke on).
2) Change:
print if /12.211.23.200/;
to
print if /12\.211\.23\.200/;
"." is a regex wildcard meaning "any character". Changing it to "\." will reduce the number of false positives (unlikely to change your results in practice but it's more correct anyway).