#!/usr/bin/php -d safe_mode="Off" -w -q 
<?

### YOU CAN EDIT EDIT THESE LINES ###

### DON'T EDIT BELOW LINES ####
include dirname(__FILE__)."/ftp_clamscan_config.php";
include 
dirname(__FILE__)."/ftp_clamscan_patterns.php";

find_platform();

//write_log("init... ENV : ".var_export($GLOBALS["env"],true));
write_log("init... File : ".$argv[1]);

switch(
$argv[1]){
    case 
"--check":    check_requirements();break;
    default :        
scanner($argv);break;
}

write_log("end...\r\n");

print 
"\r\n";

// #######################################################################################################
function find_platform() {

    if (
file_exists("/usr/local/cpanel/cpkeyclt")) 
    {
        
$platform="cpanel";
    } 
// if sonu
    
elseif (file_exists("/etc/psa/psa.key")) 
    {
        
$platform="plesk";
    } 
// else sonu
    
else 
    {
        
$platform="other";
    } 
// else sonu

    
if (file_exists("/etc/init.d/pure-ftpd")) 
    {
        
$ftp="pure-ftpd";
    } 
// if sonu
    
elseif (file_exists("/etc/init.d/pro-ftpd")) 
    {
        
$ftp="pro-ftp";
    } 
// else sonu
    
else 
    {
        
$ftp="other";
    } 
// else sonu
    
    
$GLOBALS["env"]=array(
                    
"platform" => $platform,
                    
"os" => $os,
                    
"ftp" => $ftp,
                    );

    return 
$GLOBALS["env"];

// function sonu #######################################################################################


// #######################################################################################################
function get_user($file) {

    
$usr_arr=explode("/",$file);

    if (
$GLOBALS["env"]["platform"] == "cpanel"
    {
        
$user=$usr_arr[2];
    } 
// if sonu
    
elseif ($GLOBALS["env"]["platform"] == "plesk"
    {
        
$user=$usr_arr[4];
    } 
// else sonu
    
    //write_log("user ".$user." -- ".var_export($usr_arr,true));
    //write_log("user ".$user." -- ".var_export($usr_arr,true));
    
    
$GLOBALS["user"]=$user;
    
    return 
$user;

// function sonu #######################################################################################

// #######################################################################################################
function scanner($arg) {

    if (
file_exists($GLOBALS["clamscan"])) 
    {    
        if (
file_exists($arg[1])) 
        {

            if (!
is_dir($GLOBALS["quarantine"])) 
            {    
                
$path_arr=explode("/",$GLOBALS["quarantine"]);
                
$path="/";

                foreach (
$path_arr as $p
                {
                    
$path=$path."/".$p;
                    if (!
is_dir($path)) 
                    {
                        
mkdir($path);
                    } 
// if sonu
                
// foreach sonu
            
// if sonu
            
            
$signs=array(
                            
";" => "\\;",
                            
"<" => "\\<",
                            
">" => "\\>",
                        );


            
$ex =$GLOBALS["clamscan"]." --no-summary --infected --move=".$GLOBALS["quarantine"]." ".strtr($arg[1],$signs); 
            
$ret =shell_exec($ex);
            
$lines=explode("\n",$ret);
            
            foreach (
$lines as $line
            {
                if (
strpos($line,"FOUND")) 
                {
                    
write_log("antivirus scan...");
                    
$found="Y";
                    
$virus=substr($line,strlen($arg[1])+1,strlen($line)-(strlen($arg[1])+6));
                } 
// if sonu
                
if (strpos($line,"moved to")) 
                {
                    
$moved=$line;
                } 
// if sonu
            
// foreach sonu


            
if ($found != "Y"
            {
                
$ret=word_scan($arg[1]);
                
                if (
$ret[0]=="Y"
                {
                    
write_log("word scan...");
                    
$found="Y";
                    
$virus=$ret[1];
                    
$moved=$ret[2];
                } 
// if sonu
            
            
// if sonu

            
if ($found == "Y"
            {
                
$user=get_user($arg[1]);

                
/// Log
                
write_log($arg[1]."|".$virus."|".$GLOBALS["user"]);

                
/// Change Password
                
$new_pass=random_password("10","Y","Y","Y");
                
$ret.=$passret=password_change_cpanel($new_pass,$user);
                
write_log("pass change for user ".$GLOBALS["user"]." : ".$passret);

                
/// Kill IDLE connection
                
write_log("kill idle connection...");
                
$ret.=kill_idle($user);

                
/// Block IP
                
write_log("block attacker ip...");
                
$ret.=block_ip($user);

                
/// Restart Daemon
                //$ret.=restart_ftp();

                /// Send Mail
                
write_log("send mail...");
                
$to      $GLOBALS["mail"];
                
$subject "Gumblar Attack !!! user : ".$user;
                
$headers.= "From: " .$GLOBALS["mail"]. "\r\n" ;
                
$headers.= "Reply-To: " .$GLOBALS["mail"]. "\r\n" ;
                
$headers.= "X-Mailer: PHP/" phpversion();

                
$message.= "Warning !!!\r\n";
                
$message.= "\r\n";
                
$message.= date("d.m.Y H:i:s l");
                
$message.= "\r\n";
                
$message.= "There is a GUMBLAR ATTACK on account ".$user."\r\n";
                
$message.= "\r\n";
                
$message.= "Infected file : ".$arg[1]."\r\n";
                
$message.= "\r\n";
                
$message.= "Infection : ".$virus."\r\n";
                
$message.= "\r\n";
                
$message.= "Action : ".$moved."\r\n";
                
$message.= "\r\n";
                
$message.= "Password might be changed to : ".$new_pass."\r\n";
                
$message.= "\r\n";
                
$message.= "\r\n";
                
$message.= "\r\n";
                
$message.= "Ret : ".$ret."\r\n";

                
mail($to$subject$message$headers);

            } 
// if sonu
        
// if sonu
        
else 
        {
            
write_log("file not found : ".$arg[1]);
        } 
// else sonu
    
    
// if sonu
    
else 
    {
        
error("Error: ClamScan binary (_clamscan_) is not found. Please edit \$clamscan value in ".__FILE__);    
    } 
// else sonu


// function sonu #######################################################################################

// #######################################################################################################
function word_scan($file) {

    
$found="N";
    
$virus="";

    if (
file_exists($file)) 
    {
        
$fname=array_reverse(explode(".",$file));

        if (
count($fname) > 1
        {
            
$ext=$fname[0];
            
            if (
in_array($ext,$GLOBALS["wordscan_extensions"])) 
            {
                
$f=file($file) or die("dosya bulunamadi...");
                foreach (
$f as $line
                {    
                    
$lcnt++;
                    foreach (
$GLOBALS["pattern"] as $pattern
                    {
                        if(
stristr($line$pattern)) {$found="Y";$virus=$pattern." at line ".$lcnt;}
                    } 
// foreach sonu
                
// foreach sonu
            
// if sonu
        
// if sonu

        
if ($found=="Y"
        {
            
$new_name=$GLOBALS["quarantine"]."/".basename($file).".".date("YmdHis");
            @
copy($file,$new_name) or write_log("File copy error : $file -> $new_name");
            @
unlink($file);
            
            if (!
file_exists($file)) 
            {
                
$moved="File moved to : ".$new_name;
            } 
// if sonu
        
            
write_log("wordscan results : $virus FOUND and $moved ");

        } 
// if sonu
        
else 
        {
            
write_log("wordscan : NOT FOUND. ");
        } 
// else sonu
        
        
    
// if sonu
    
else 
    {
        
write_log("wordscan: file not found");
    } 
// else sonu
        

    
return array($found,$virus,$moved);

// function sonu #######################################################################################

// #######################################################################################################
function kill_idle($user) {

    
//pure-ftpd (IDLE)
    
$ex ='ps aux |grep "pure-ftpd (IDLE)"'
    
$ret =shell_exec($ex);
    
$lines=explode("\n",$ret);

    if (
count($lines) > 0
    {
//        write_log(var_export($lines,TRUE));
        
foreach ($lines as $line
        {
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);
            
$line=str_replace("  "," ",$line);

            
$line_arr=explode(" ",$line);
//            write_log(var_export($line_arr,TRUE));

            
if ($line_arr[0] == $user
            {
                if (
strval($line_arr[1]) > 1
                {
                    
$ex ="kill -s 9 ".trim($line_arr[1]); 
                    
write_log($ex);
                    
$ret =shell_exec($ex);
                    
$killed.="\nProcess Killed : ".$line_arr[1]."\n";
                    
                    
$killed_id[]=$line_arr[1];
                
                } 
// if sonu
            
// if sonu
        
// foreach sonu

        
if ($killed != ""
        {
            
write_log(" Killed process(es) : ".join(",",$killed_id));
        } 
// if sonu
        
else 
        {
            
write_log(" IDLE Process not found... ");
        } 
// else sonu
    
    
// if sonu

    
return $killed;

// function sonu #######################################################################################

// #######################################################################################################
function block_ip($user) {

    if (
strlen($user) > 0
    {
        
$ex ='cat /var/log/messages|grep logged|grep '.$user.'|tail -n 1'
        
$ret =shell_exec($ex);
        
$lines=explode("\n",$ret);

        if (
count($lines) > 0
        {
            foreach (
$lines as $line
            {
                
$line=str_replace("  "," ",$line);
                
$line=str_replace("  "," ",$line);
                
$line=str_replace("  "," ",$line);

                
$line_arr=explode(" ",$line);

                if (
$line_arr[7] == $user
                {
                    
$ip=str_replace(")","",trim($line_arr[5]));
                    
$ip=str_replace("(","",$ip);
                    
$ip=str_replace("?","",$ip);
                    
$ip=str_replace("@","",$ip);

                    
$ex=$GLOBALS["firewall"];
                    
$ex=str_replace("%%DESC%%","Gumblar attack on ".$user." !!!!!!! ",$ex);
                    
$ex=str_replace("%%IP%%",$ip,$ex);

                    
$ret =shell_exec($ex);
                    
write_log(str_replace("\n"," ",$ret));
                
                    
$return="IP Blocked : ".$ip;
                    
write_log("IP Blocked : ".$ip);
                } 
// if sonu
            
// foreach sonu
        
// if sonu
    
// if sonu

    
return $return;

// function sonu #######################################################################################

// #######################################################################################################
function firewall($ip) {

    
$ex =$GLOBALS["firewall"]." ".$ip
    
$ret =shell_exec($ex);

    
$lines=explode("\n",$ret);

    return 
$lines;

// function sonu #######################################################################################

// #######################################################################################################
function restart_ftp() {

    
$ex =$GLOBALS["ftpd"]; 
    
$ret=shell_exec($ex);

    
$lines=explode("\n",$ret);

    return 
$lines;

// function sonu #######################################################################################


// #######################################################################################################
function error($err) {

    
print_header();
    echo 
"\r\n";    
    echo 
"\r\n"." Error : ";    
    echo 
"\r\n";    
    echo 
$err;    
    echo 
"\r\n";    

// function sonu #######################################################################################

// #######################################################################################################
function print_header() {

    echo 
"# FCSA - FTP ClamAv Scanner and Alerter "."\r\n";    
    echo 
"# v 0.1 "."\r\n";    
    echo 
"# Hidayet Ok // hidonet@oxio.net // http://www.oxio.net"."\r\n";    

// function sonu #######################################################################################

// #######################################################################################################
function show_help() {

    
print_header();
    echo 
"Clamav ";    
    

// function sonu #######################################################################################

//############ Function ###################################################################
function random_password($uzunluk,$buyuk,$kucuk,$rakam) { // v1.0

    
$bharf="ABCDEFGHIJKLMNOPRSTUWXVYZ";
    
$kharf="abcdefghijklmnoprstuwxvyz";
    
$sayi="0123456789";

    if(
$buyuk=="Y") {$dize.=$bharf;} // if 
    
if($kucuk=="Y") {$dize.=$kharf;} // if 
    
if($rakam=="Y") {$dize.=$sayi;} // if 

    
if($uzunluk 50) {$uzunluk=50;} // if 


    
for($i=1$i $uzunluk $i++) {
        
$rand=mt_rand(0,strlen($dize)-1);
        
$rand_pass.=substr($dize,$rand,1);
    }  
## for sonu

    
Return $rand_pass;

//---------- End Function ----------

// #######################################################################################################
function password_change_cpanel($pass,$user) {

    
$whmusername "root";

    
$query "https://".$GLOBALS["main_ip"].":2087/xml-api/passwd?user=$user&pass=$pass";

    
$curl curl_init();                            # Create Curl Object
    
curl_setopt($curlCURLOPT_SSL_VERIFYHOST,0);    # Allow certs that do not match the domain
    
curl_setopt($curlCURLOPT_SSL_VERIFYPEER,0);    # Allow self-signed certs
    
curl_setopt($curlCURLOPT_RETURNTRANSFER,1);    # Return contents of transfer on curl_exec
    
$header[0] = "Authorization: WHM $whmusername:" preg_replace("'(\r|\n)'","",$GLOBALS["whmhash"]);    # Remove newlines from the hash
    
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);    # Set curl header
    
curl_setopt($curlCURLOPT_URL$query);        # Set your URL
    
$result curl_exec($curl);                        # Execute Query, assign to $result

    
if ($result == false) {
        return 
"curl error :".curl_error($curl);
    }
    elseif (
strpos(str_replace("\n","",$result),"Password changed for user ".trim($user)) === false
    {
        return 
"Pass not changed. Check whm remote access key.";
    } 
// else sonu
    
else 
    {
        return 
"Password changed.";
    } 
// else sonu
    
    
curl_close($curl);

    
// function sonu #######################################################################################

// #######################################################################################################
function write_log($msg) {

    if (!
file_exists($GLOBALS["log_file"])) 
    {
        
$fout=fopen($GLOBALS["log_file"],"w");
        
fwrite($fout,date("Y.m.d H:i:s")." --- ANTI GUMBLAR ( FTP CLAMSCAN ) LOG START\n");        
        
fclose($fout);
        @
shell_exec("chmod 777 ".$GLOBALS["log_file"]);
    } 
// if sonu
    
    
$fout=fopen($GLOBALS["log_file"],"a");
    
fwrite($fout,date("Y.m.d H:i:s")." --- ".$msg."\n");        
    
fclose($fout);

//    print "$msg\n";
    

// function sonu #######################################################################################


?>