#!/usr/bin/perl
print "Content-type: text/html \n\n";

use IO::File;
use File::KGlob;
use Fcntl;
use Socket;
use Time::localtime;
use Time::Local;
use GD;
use graf_dec;   # Sher library
use Chart::Graph::Gnuplot qw(gnuplot);
use strict;

#################################################################
# $abs_start is a time, corresponding to 00:00 of current day	#
#################################################################

my ($con,$res,$start,$stop,$time,$date,$day,$month,$year,$T0,$ip,$ppp,$key,$abs_start,$img,$path);
my ($ip_max,$n_max,$date_time,$m);
my ($line,$p,$i,$minutes,$hours,$seconds,$record,$j,$r,$mark,$m,$fl,$pp,$p1,$t_bin,$p4,$p5);
my ($y1,$y2,$y3,$y4,$y5,$tmm,$tm,$tm0,$secs,$mins,$mon,$t_mid,$dat1,$dat2);
my ($y_max,$y_min,$delt,$secnds,$mints,$hrs);
my (@ary,@er_dis_time,@len,@nam,@LL,@LLL,@records,@tim,$form_data,$pin1);	# array, returned with request
my (@t_mark,@n_val,@L,@list,@file);
my @mon=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
my @incl=("MSOffice","_vti","guestbook","sitemap","dig.php","test.php","php-my-admin","contenido","websql","PHPMYADMIN","webdb","webadmin","info.php","phpmy","contact.php","login.php","phpinfo.php","scripts","myphpinfo.php","main.php","[ROOT]=http","appserv","xmlrpc.php","anna","stasovar","!!!","phpadmin","nosuichfile.php","noxdir","PMA2005","admin","dbadmin","myadmin","adminLogin.php");
my %ip_er=();					# hash-array IP-number (attacker_IP - number)
my %ip_at=();					# hash-array IP-number
my %ip_loc=();
$i=0;
my $er_num=0;					# Error number
my $k=0;
my @er_lines=();				# Error line array
my $dt=600;					# delta time = 10 minute
my $dt2=int($dt/2);				# $dt2=$dt/2=300
my $counter=1440/10;				# bin number
my $t_num=0;
my $n_req=0;					# index of attack lines
$ip_max=" ";
my $thresh=10;					# Alarm threshould for IP-banning
my $flag=0;					# Is the data in memory? (not the first request)
#print "includes=",$#incl,"\n";
#########################################
# Yu. Semenov				#
# Fast-current-version			#
# Delta-T = 10 minute			#
# Script reads file:			#
# <error_log>, extracts the records    	#
# with patern, showing illegal request 	#
# format: [Sun Jul 25 13:37:00 2010] [error] [client 69.36.187.26] File does not exist: /home/httpd/htdocs/book/result/main.php
# For the last 10 minute		#
#########################################

for($i=0;$i<$counter;$i++){$tim[$i]=0;}		# clear time-array
$p="/var/log/httpd/error_log";			# input file  <error_log.txt>

#my $path_d="/var/log/httpd/";
#opendir(DIR,$path_d);				# For case of date-time extentions for log-file name
#$n_max=0;
#@file=grep {/error_log/} readdir(DIR);
#for($i=0;$i<4;$i++)	{$LL[$i]=substr($file[$i],10);
#			if($LL[$i]>$n_max)	{$n_max=$LL[$i];
#			$m=$i;			}
#			}
#my $file_name="error_log-".$LL[$m];
#print "F_name=",$file_name,"\n";
#closedir(DIR);
#$p=$p."-".$LL[$m];
#print "P=",$p,"\n";

open(h_point,$p) or die "Can't start tst1: $!\n";		# open error_log

$pp="/home/httpd/htdocs/saturn/attacks/ids/attack_erl.txt";	# output file <attack_erl.txt>
$p1="/home/httpd/htdocs/saturn/attacks/ids/time_dis_er.txt";	# output file <time_dis_er.txt>
$ppp="/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.txt";	# input file  <ip_attack_er.txt>

# Format: IP-address number

$p4="/home/httpd/htdocs/saturn/attacks/ids/err_journal.txt";    # output file <err_journal.txt>
$p5="/home/httpd/htdocs/saturn/attacks/ids/ip_atck_er.txt";  	# input file  <ip_atck_er.txt>

# Format: time IP-address number [for ip_activity.htm (ip_error.cgi)]

$stop=time;							# The time of calculation
$start=$stop-600;						# time of 10 minutes before
$tm=localtime;
#$tm=$tm-300;
$year=$tm->year;
$month=$tm->mon;
$day=$tm->mday;
$secnds=$tm->sec;
$mints=$tm->min;
$hrs=$tm->hour;
#print "H=",$hrs," M=",$mints," S=",$secnds,"\n";
$abs_start=timelocal(0,0,0,$day,$month,$year);
print "ABS_st=",$abs_start," cur_time=",time," Start=",$start," Stop=",$stop,"\n";
if((time-$abs_start)<$dt)	{

#################################################
# Clear the file, at a new day beginning	#
#################################################

sysopen(p_tim, $p1, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <time_dis_er.txt> file
sysopen(F_ip, $ppp, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <ip_attack_er.txt> file
sysopen(F_ip1, $p5, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <ip_atck_er.txt> file
sysopen(AFIL, $pp, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <attack_erl.txt> file
sysopen(er_ju, $p4, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <err_journal.txt> file

#print "new-file\n";
				}
# O_RDWR|O_CREAT|O_APPEND 
else{sysopen(p_tim, $p1, O_RDWR|O_APPEND|O_CREAT) or die$!;		# open output <time_dis_er.txt> file
	sysopen(F_ip, $ppp, O_RDWR|O_APPEND|O_CREAT) or die$!;		# open output <ip_attack_er.txt> file
	sysopen(F_ip1, $p5, O_RDWR|O_APPEND|O_CREAT) or die$!;		# open output <ip_atck_er.txt> file
	sysopen(AFIL, $pp, O_RDWR|O_APPEND|O_CREAT) or die$!;		# open output <attack_erl.txt> file
        sysopen(er_ju, $p4, O_RDWR|O_APPEND|O_CREAT) or die$!;		# open output <err_journal.txt> file

#	print "old-file\n";
}
$j=0;
#####################################

while (!eof(F_ip))	{
$line=readline(F_ip);			# read line of <ip_attack_er.txt>
#print "L=",$line,"\n";
@LL=split/\s+/,$line;
$ip=$LL[0];
$ip_at{$ip}=$LL[1];			# IP-hash-array
			}
close(F_ip);

#while (!eof(F_ip1))	{
#$line=readline(F_ip1);			# read line of <ip_atck_er.txt>
#print "L=",$line,"\n";
#@LL=split/\s+/,$line;
#$ip=$LL[0];
#$ip_at{$ip}=$LL[1];			# IP-hash-array
#			}
#close(F_ip1);
sysopen(F_ip, $ppp, O_RDWR|O_TRUNC) or die$!;  # open output <ip_attack_er.txt> file

while (!eof(h_point)) 	{		# Cycle for <error_log>-file
$line=readline(h_point);		# read line of <error_log>
#print "L=",$line,"\n";
@LL=split/\s+/,$line;
@ary=split//,$line;
if($ary[0] eq "[")	{		# if normal record
$month=$LL[1];
for($i=0;$i<12;$i++)
{if($month eq $mon[$i]){$month=$i;}}	#
$day=$LL[2];
$time=$LL[3];
@LLL=split/\:/,$time;
$hours=$LLL[0];
$minutes=$LLL[1];
$seconds=$LLL[2];
#if($j==0)	{print "day=",$day," mon=",$month," hour=",$hours," min=",$minutes," sec=",$seconds,"\n";
#		$j++;
#		}
$T0=timelocal($seconds,$minutes,$hours,$day,$month,$year);	# Current time from error_log record
#if($j==1)	{print "ABS_t=",$abs_start," T0=",$T0," srart=",$start," stop=",$stop," ind=",(int(($T0-$abs_start)/$dt)),"\n";
#		$j++;
#		}
$t_bin=$abs_start+int(($T0-$abs_start)/$dt)*$dt+$dt2;
if($T0>$start && $T0<$stop)	{			#########
print "T0=",$T0," start=",$start," stop=",$stop," ind=",(int(($T0-$abs_start)/$dt)),"\n";
$t_num++;				# time array filling in	# Number of records in the interval
$fl=0;					# init includings flag	#
print "Line=",$line,"\n";
for($r=0;$r<$#incl+1;$r++)	{	#################  	#
	$ip=$LL[7];					#  	#
	$ip=substr($ip,0,-1);	# remove the last "]"	#  	#
#print "IP=",$ip," F=",$fl,"\n";			#  	#
if($fl==0)	{	#################		#  	#
if(index($line,$incl[$r])>=0){$fl=1;}	#		#  	#
		}	#################		#  	#
#print "FL=",$fl," I=",$r," LL=",$line,"\n";		#  	#
				}	#################  	#
print "FL=",$fl," I=",$r," LL=",$line,"\n";			#

if($fl!=0)	{	# There is a illegal request ####	#
$er_lines[$n_req]=$line;				#	#
if(exists($ip_at{$ip}))	{		#########	#	#
	$ip_at{$ip}=$ip_at{$ip}+1;		#	#	#
print "ip=",$ip," ip_n=",$ip_at{$ip},"\n";	#	#	#
			}		#########	#	#
else{$ip_at{$ip}=1;}					#	#
print "IP-loc=",$ip,"\n";
if(exists($ip_loc{$ip}))	{	#########	#	#
$ip_loc{$ip}=$ip_loc{$ip}+1;			#	#	#
				}	#########	#	#
else{$ip_loc{$ip}=1;}					#	#
							#	#
$n_req++;						#	#
		}				#########	#
if(exists($ip_er{$ip})) {               #########               #
	$ip_er{$ip}=$ip_er{$ip}+1;              #               #
#print "ip=",$ip," ip_n=",$ip_er{$ip},"\n";     #               #
	                }               #########               #
else{$ip_er{$ip}=1;}                                            #
				}	# end of time IF  #######
		}		# end IF eq "["
	}			# end of WHILE

#################################################
# The 10 minutes piece of data is developed	#
#################################################
#print "er_Req=",$n_req,"\n";
for($i=0;$i<$#er_lines;$i++)	{print er_ju $er_lines[$i];}
$fl=0;
$ip_max=" ";
$n_max=0;
foreach $key (reverse sort {$ip_er{$a} <=> $ip_er{$b}} keys %ip_er)
{
print "ipr=", $key," nr=",$ip_er{$key},"\n";
}
foreach $key (reverse sort {$ip_loc{$a} <=> $ip_loc{$b}} keys %ip_loc)
{
print "ip_loc=", $key," nr=",$ip_loc{$key},"\n";
if($fl==0)	{
    $fl=1;
    $ip_max=$key;
    $n_max=$ip_loc{$key};
		}
}
$time=$hrs.":".$mints.":".$secnds;
#print "TIME=",$time,"\n";
#print "H1=",$hrs," M=",$mints," S=",$secnds,"\n";
#print "D-T=",$time,"\n";
if($ip_max eq " ") {$ip_max="-";
		    $n_max=0;}	
#print "IP_m=",$ip_max," N_max=",$n_max,"\n";

foreach $key (reverse sort {$ip_at{$a} <=> $ip_at{$b}} keys %ip_at)
{
print "ipa=",$key," na=",$ip_at{$key},"\n";
print F_ip $key," ",$ip_at{$key},"\n";			# Writing into <ip_attack_er.txt>
}
print F_ip1 $time," ",$ip_max," ",$n_max,"\n";  	# Write <ip_atck_er.txt>
print "IP_m1=",$ip_max," N_max1=",$n_max,"\n";
print AFIL $ip_max," ",$n_max,"\n";			# Write <attack_erl.txt>

#################################################
#	Writing to the file <time_dis_er.txt>	#
#################################################
#print "Time=",$t_bin," Num=",$t_num,"\n";
print p_tim $t_bin," ",$t_num,"\n";		# Write <time_dis_er.txt>

close(h_point);
close(AFIL);
close(p_tim);
close(F_ip);
close(F_ip1);

#########################################################
# making up a picture from the file <ip_attack_er.txt>	#
# for <ip_attack_er.png>				#
#########################################################

#$path='/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.png';
$path="/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.png";		# input file  <ip_attack_er.txt>
# my ($dY,$maxX,$maxY,$Left,$Right,$w,$box,$path,$path_img,$stringX,$stringY,$col_osi,$col_graf,$nonlin,$polygon,$img)=@_;
#$img = &vert_diagr(15,600,400,15,'/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.txt',$path,1,7,3,$img,25);
$img = &vert_diagr(15,600,400,15,'/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.txt',$path,1,7,3,$img,25);
print"IP_attack_er\n";
open(PICTURE,"> $path") or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;

$i=0;
$y_max=0;
$y_min=0;
$p="/home/httpd/htdocs/saturn/attacks/ids/time_dis_er.txt";
sysopen(TD_Er,$p,O_RDWR) or die$!;	#

while (!eof(TD_Er))       {             # Cycle for <time_dis_er.txt>
$line=readline(TD_Er);
chop($line);
#print "LINe=",$line,"\n";
@L=split/\s+/,$line;
$t_mark[$i]=$L[0];
$n_val[$i]=$L[1];
#print "n_val=",$n_val[1],"\n";
if($n_val[$i]>$y_max)   {$y_max=$n_val[$i];}
if($n_val[$i]<$y_min)   {$y_min=$n_val[$i];}
$i++;
                        }
print "T-m=",$t_mark[0];
$delt=sprintf("%.4f",($y_max-$y_min)/5);
$y_min=sprintf("%.4f",$y_min);
print " y_min=",$y_min," delt=",$delt,"\n";
$y1=int($y_min);
$y2=int($y_min+$delt);
$y3=int($y_min+(2*$delt));
$y4=int($y_min+(3*$delt));
$y5=int($y_min+(4*$delt));
print "T_DISTR-y1=",$y1," y2=",$y2," y3=",$y3," y4=",$y4," y5=",$y5," ymin=",$y_min,"\n";
$t_mid=$t_mark[int(($i-1)/2)];
$tm0=$t_mark[0];
$tmm=$t_mark[$i-1];
$tm=localtime($tm0);
$year=$tm->year+1900;
$mon=($tm->mon);
$mon=$mon[$mon];
$day=$tm->mday;
$secs=$tm->sec;
$hours=$tm->hour;
$mins=$tm->min;
$dat1=$year."-".$mon."-".$day." ".$hours.":".$mins.":".$secs;
#print "DATE1=",$dat1,"\n";
$tm=localtime($tmm);
$year=$tm->year+1900;
$mon=($tm->mon);
$mon=$mon[$mon];
$day=$tm->mday;
$secs=$tm->sec;
$hours=$tm->hour;
$mins=$tm->min;
$dat2=$year."-".$mon."-".$day." ".$hours.":".$mins.":".$secs;
print "Y-max=",$y_max," tm0=",$tm0," tmm=",$tmm," mid=",$t_mid,"\n";

gnuplot({'title' => 'The last day request errors ('.$dat1.' - '.$dat2.')',
    'x2-axis label' => 'Time',
    'y-axis label'=> 'Error numbers per 10 minutes',
    'x-axis label' => 'time',
    'size'=>[1.2,0.6],
    'output type' => 'gif',
    'output file' => '/home/httpd/htdocs/saturn/attacks/ids/time_dis_er.gif',
    'ytics' => [$y1,$y2,$y3,$y4,$y5],
    'extra_opts' => 'set nokey',
    'uts' => [$tm0, $tmm,1,1]},
    [{'title' => 'data1',
    'style' => 'lines',
    'type' => 'file'}, '/home/httpd/htdocs/saturn/attacks/ids/time_dis_er.txt'],
        );
gnuplot({'title' => 'The last day request errors ('.$dat1.' - '.$dat2.')',
#    'x2-axis label' => 'Time',
    'y-axis label'=> 'Errors per 10 mins',
    'x-axis label' => 'time',
    'size'=>[1.0,0.4],
    'output type' => 'gif',
    'output file' => '/home/httpd/htdocs/saturn/attacks/ids/time_dis_er1.gif',
    'ytics' => [$y1,$y2,$y3,$y4,$y5],
    'extra_opts' => 'set nokey',
    'uts' => [$tm0, $tmm,1,1]},
[{'title' => 'data1',
    'style' => 'lines',
    'type' => 'file'}, '/home/httpd/htdocs/saturn/attacks/ids/time_dis_er.txt'],
);
close(TD_Er);

exit(0);

