#!/usr/local/bin/php
<?
// 개요
// secure log 를 분석해서 sshd로 불법적인 접속을 시도하는 IP를 /etc/hosts.deny에 등록하는 작업을 한다.
// Log Example : Jun 5 07:49:18 p1 sshd[1110]: Failed password for root from 211.114.190.196 port 52944 ssh2
// 추출 명령어 : grep "Jun 7 09" secure | grep "sshd" | grep "Failed password" | awk -F "from" '{print $2}' | awk '{print $1}'
// 지정된 입력값을 입력하지 않으면 실행하지 않는다.
if($argc > 1)
{
$RECEIVE_EMAIL = "수신 메일주소";
$Hostname = trim(exec("hostname"));
$Date = date("Y-m-d H:i:s");
// 10분전 분을 구한다.
$TenAgo = substr(date("i",mktime (date("H"), date("i")-10, 0, date("m"), date("d"), date("Y"))),0,1);
if(!file_exists("/service/log_temp"))
{
exec("mkdir -p /service/log_temp");
}
if(!file_exists("/service/log_temp/secure_analysis.log"))
{
exec("touch /service/log_temp/secure_analysis.log");
}
// 날짜에 따라서 검색어의 공백처리가 틀린 관계로 ... =,.=;
$DayLength = strlen(date("j"));
if($DayLength == 2)
{
$now = date("M j H:");
}
else
{
$now = date("M j H:");
}
if($argv[1] == "sshd")
{
exec("grep \"$now$TenAgo\" /var/log/secure | grep \"sshd\" | grep \"Failed password\" | awk -F \"from\" '{print \$2}' | awk '{print \$1}' > /service/log_temp/secure_log_".$argv[1]);
}
$Fail_IP_File = file("/service/log_temp/secure_log_".$argv[1]);
for($i=0; $i < count($Fail_IP_File); $i++)
{
$Fail_IP_File[$i] = trim($Fail_IP_File[$i]);
}
$Fail_Statistics = array_count_values($Fail_IP_File);
exec("echo \"\" > /service/log_temp/DenyIP.list_".$argv[1]);
while (list ($Ip, $Count) = each ($Fail_Statistics))
{
// 여기의 20을 조정하여 등록을 조절할 수 있다.
if($Count > 20)
{
$Now_Time = date("Y년 m월 d일 H시 i분 s초");
exec("echo \"#Regist $Now_Time\" >> /etc/hosts.deny");
exec("echo \"ALL : $Ip\" >> /etc/hosts.deny");
$Restart_Xinetd = 1;
exec("echo \"$Now_Time | $Ip | $Count 회\" >> /service/log_temp/DenyIP.list_".$argv[1]);
}
exec("echo \"$Date\t$Ip\t$Count\" >> /service/log_temp/secure_analysis.log");
}
if($Restart_Xinetd)
{
exec("killall -HUP xinetd");
exec("cat \"/service/log_temp/DenyIP.list_".$argv[1]."\" | mail -s \"$Hostname Deny IP List - $Date \" $RECEIVE_EMAIL");
}
}
else
{
echo("Missing Argument... Confirm Execute ...\n");
}
?>