2008年4月9日 星期三

[分享] php 每秒判斷加以封鎖 WEB DOS 攻擊 . - EcStart FIEND 布落格 - EcStart |BLOG - powered by X-Space

[分享] php 每秒判斷加以封鎖 WEB DOS 攻擊 . - EcStart FIEND 布落格 - EcStart |BLOG - powered by X-Space
請將程式放在 /root/bin/block_http

#!/usr/local/bin/php -q
set_time_limit(0);
$exception[] ="220.132.104.8" ;
$exception[] ="206.225.95.61" ;

$path_log = "/var/log/http_err/err_log_".strftime("%Y-%m-%d",time()) ;
$alert_limit = "48"; // 連線數超過 發出警告
$flow_limit = "72"; // 連線數最多 ... 封鎖
$block_range = "1"; // 偵測間距
$restart_httpd_num = "100"; // 連線數達N筆時重新啟動 http ...
while(1==1){

$msg = "";

@exec("netstat -tn | grep \":80 \" | grep -v \"0:0:0:0\" | cut -d: -f8 | sort ",$ip_list) ;
@exec("iptables -L INPUT -n | grep DROP | cut -d- -f3| cut -d/ -f1",$isblock_ip) ;
// DROP all -- 60.248.11.20 0.0.0.0/0
if(count($isblock_ip) >= 1){
foreach($isblock_ip as $ibv){
$isblock_ip_arr[] = trim(str_replace("0.0.0.0","",trim($ibv))) ;
}
$isblock_ip_arr = array_unique($isblock_ip_arr) ;
}
//print_r($isblock_ip_arr);

$ip_list = @array_count_values($ip_list) ;

foreach($ip_list as $ip => $num){
if($ip != "" and $num >= $alert_limit){
//$msg = "TIME"."\t"."IP"."\t"."QUANTITY"."\n";
$msg .= "ALERT\t".strftime("%Y-%m-%d %H:%M:%S",time())."\t".$ip."\t".$num."\n";
}
if($ip != "" and $num >= $flow_limit){
$block_ip[] = $ip;
}
}

/*
if(is_array($block_ip)){
foreach($block_ip as $kip){
echo "ALERT : ".$kip ." => ".$ip_list[$kip] . " -- ".strftime("%Y-%m-%d %H:%M:%S",time())." - amount than :".$flow_limit." \n";
}
unset($kip);
}
*/
if(is_array($block_ip)){
$block_ip = array_diff($block_ip,$exception); // 過濾例外清單
if(is_array($block_ip) and is_array($isblock_ip_arr)){
$block_ip = array_diff($block_ip,$isblock_ip_arr); // 過濾已封鎖清單
}

foreach($block_ip as $kip){
$msg .= "BLOCK\t".strftime("%Y-%m-%d %H:%M:%S",time())."\t".$kip."\t".$ip_list[$kip]."\n";
system("iptables -I INPUT -s ".$kip." -j DROP");
//system("iptables-save");
if($ip_list[$kip] >= $restart_httpd_num){
//echo $kip ." => ".$ip_list[$kip] . " -- ".strftime("%Y-%m-%d %H:%M:%S",time())."\n";
system("killall /usr/local/apache2/bin/httpd");
system("/usr/local/apache2/bin/apachectl restart");
}
}

}
//print_r($block_ip);
//echo "Last second ...... \n";
if(!is_dir(dirname($path_log))){
$action = "/bin/mkdir -p ".dirname($path_log);
system(escapeshellcmd($action));
}
$fp = fopen($path_log,"a+");
fwrite($fp,$msg,strlen($msg));
fclose($fp);



sleep($block_range); // 偵測間距
unset($ip_list);
unset($isblock_ip);
unset($isblock_ip_arr);
unset($num);
unset($ip);
unset($block_ip);
unset($msg);
}



?>
然後將這行程式的路徑放入

/etc/rc.local

nohup /root/bin/block_http &

沒有留言: