#!/usr/bin/perl
print "Content-type: text/html \n\n";

use IO::File;
use Fcntl;
use Socket;
use Time::Local;
use Time::localtime;
use Chart::Graph::Gnuplot qw(gnuplot);	# Gnuplot library
use GD;					# Graphic Library
use graf_dec;   # Sher library
use strict;

print "ERROR.pl\n";

my ($con,$res,$start,$stop,$time,$date,$day,$month,$year,$T0,$ip,$ppp,$key,$ipdat,$p4,$img);
my ($line,$p,$i,$minutes,$hours,$seconds,$date_time,$record,$j,$r,$mark,$m,$fl,$pp,$p1,$p2,$path1);
my ($delt,$y1,$y2,$y3,$y4,$y5,$tm0,$tmm,$y_min,$mon,$mins,$secs,$t_mid,$dat1,$dat2);
my (@L,@ary,@array,@arr,@len,@nam,@LL,@LLL,@records,@tim,@file);	# array, returned with request
my ($form_data,$tm,$pin1);
my @mon=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

# @incl is an array with file names, we need to find
my @incl=("admin","adminLogin.php","appserv","contact.php","signup.php","viewforum.php","zboard.php","member.php","join.php","post.php","wp-login.php","reg.php","ucp.php","register.php","contenido","dbadmin","details.php","dig.php","info.php","login.php","main.php","MSOffice","myadmin","myphpinfo.php","nosuchfile.php","noxdir","phpinfo.php","phpmy","phpmyadmin","phpMyadmin","PMA2005","print.php","[ROOT]=http","scripts","sitemap","test.php","_vti","webadmin","webdb","websql");
my %ip_er=();				# hash-array IP-number
my %ip_tot=();
$i=0;
@array=(" "," "," "," "," ");
my $k=0;
my $dt=300;				# delta time = 5 minutes
my $counter=1440/5;			# bin number
my $n_req=0;
my $flag=0;				# Is the data in memory? (not the first request)
$ipdat=" ";
#########################################
# Yu. Semenov				#
# Script reads file:			#
# <error_log-...>, extracts the records #
# with pattern, 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 day			#
#########################################

for($i=0;$i<$counter;$i++){$tim[$i]=0;}			# clear time-array
$p="/var/log/httpd/error_log";				# input file  <error_log>

my $path_d="/var/log/httpd/";		#-------------------------------+
#opendir(DIR,$path_d);			#				#

# calculate error_log file, taking the latest one			#

my $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," LL=",$LL[$m],"\n";			#
#closedir(DIR);								#
#$p=$p."-".$LL[$m];							#
#print "P=",$p,"\n";			#-------------------------------#

open(h_point,$p) or die "Can't start tst1: $!\n";

$pp="/home/httpd/htdocs/saturn/attacks/ids/attack_tst.txt";	# output file  <attack_tst.txt>
sysopen(AFIL, $pp, O_RDWR|O_TRUNC|O_CREAT) or die$!;		# open output <attack_tst.txt> file

$p1="/home/httpd/htdocs/saturn/attacks/ids/time_distrib.txt";	# output file  <time_distrib.txt>
sysopen(Ptm, $p1, O_RDWR|O_TRUNC|O_CREAT) or die$!;		# open output <time_distrib.txt> file

$ppp="/home/httpd/htdocs/saturn/attacks/ids/ip_attacks.txt";	# input file  <ip_attacks.txt>
sysopen(Fip, $ppp, O_RDWR|O_TRUNC|O_CREAT) or die$!;		# open output <ip_attacks.txt> file

$p4="/home/httpd/htdocs/saturn/attacks/ids/ip_total1.txt";	# input file  <ip_total1.txt>
sysopen(Fipt, $p4, O_RDWR|O_TRUNC|O_CREAT) or die$!;		# open output <ip_total1.txt> file

$stop=time-900;							# The time of calculation
$start=$stop-86400;						# time of one day before
$tm=localtime;
$year=($tm->year);
$month=($tm->mon);
$day=$tm->mday;
#print "Year=",$year," time=",$start,"\n";

#####################################
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;
@array=split/\[/,$line;
    $ipdat=$array[3];
if(!defined $array[3])	{$ipdat=" ";}
#print "IPdat=",$ipdat,"\n";
@arr=split/\s/,$ipdat;
$ip=$arr[1];
if(!defined $ip)	{$ip="1.1.1.1";}
else{$ip=substr($ip,0,-1);}				# remove the last "]"
#print "IP=",$ip,"\n";
if($ip ne "")			{
if(exists($ip_tot{$ip}))	{	#########	# All IP in error_log
	$ip_tot{$ip}=$ip_tot{$ip}+1;		#
#print "ip=",$ip," ip_n=",$ip_tot{$ip},"\n";	#
				}		#
else{$ip_tot{$ip}=1;}			#########
				}
if($ary[0] eq "[")	{
$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];
#print "day=",$day," mon=",$month," hour=",$hours," min=",$minutes," sec=",$seconds,"\n";
$T0=timelocal($seconds,$minutes,$hours,$day,$month,$year);	# Current time from error_log record
#print "T0=",$T0," srart=",$start," stop=",$stop," ind=",(($T0-$start)/$dt),"\n";
if($T0>$start && $T0<$stop)	{			#########	Time interval selection
#print "T0=",$T0," srart=",$start," stop=",$stop," ind=",(($T0-$start)/$dt),"\n";
$tim[int(($T0-$start)/$dt)]++;		# time array		#
$fl=0;					# init includings flag	#
for($r=0;$r<$#incl+1;$r++)	{	#########		# Looking for suspicious files
	$ip=$LL[7];				#		#
	$ip=substr($ip,0,-1);		# remove the last "]"	#
#print "IP=",$ip,"\n";				#		#
if($fl==0)	{		#########	#		#
if(index($line,$incl[$r])>=0){$fl=1;}	#	#		#
		}		#########	#		#
#print "fl=",$fl," I=",$r," LL=",$line,"\n";	#		#
				}	#########		#
if($fl!=0)	{		# There is an ill request ##	#
#$records[$n_req]=$line;	# put down the record	   #	#
if(exists($ip_er{$ip}))	{		#########	   #	#
	$ip_er{$ip}=$ip_er{$ip}+1;		# Req ill  #	#
#print "ip=",$ip," ip_n=",$ip_er{$ip},"\n";	#	   #	#
			}		#########	   #	#
else{$ip_er{$ip}=1;}					   #	#
print AFIL $line;				#	   #	#
$n_req++;						   #	#
		}					####	#
		}	#	end of time IF		#########
		}		# end IF eq "["
	}			# end of WHILE
close(h_point);
foreach $key (reverse sort {$ip_er{$a} <=> $ip_er{$b}} keys %ip_er)
{
print Fip $key," ",$ip_er{$key},"\n";		# Write into <ip_attacks.txt>
}
for($i=0;$i<$counter;$i++)	{ 
print Ptm $start+($i*$dt)," ",$tim[$i],"\n";	# Write into <time_distrib.txt>
				}

close(AFIL);
close(Fip);
close(Ptm);

my $y_max=0;
$y_min=0;
my (@t_mark,@n_val);
$i=0;
my @mons=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

#########################
# GNUPLOT programm
#########################

$p2="/home/httpd/htdocs/saturn/attacks/ids/time_distrib.txt";
sysopen(TDS, $p2, O_RDWR) or die$!;     #

while (!eof(TDS))       {               # Cycle for <time_distrib.txt>
$line=readline(TDS);
#print "Line=",$line,"\n";
chop($line);
@L=split/\s/,$line;
$t_mark[$i]=$L[0];
$n_val[$i]=$L[1];
#if($L[1]!=0){
#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++;
                        }
$delt=sprintf("%.2f",($y_max-$y_min)/5);
$y_min=sprintf("%.2f",$y_min);
#print "y_min=",$y_min," delt=",$delt,"\n";
$y1=$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 "TIME_Distr-y1=",$y1," y2=",$y2," y3=",$y3," y4=",$y4," y5=",$y5," ymax=",$y_max,"\n";
	$t_mid=$t_mark[int($counter/2)];
	$tm0=$t_mark[0];
	$tmm=$t_mark[$counter-1];
	$tm=localtime($tm0);
	$year=$tm->year+1900;
	$mon=($tm->mon);
	$mon=$mons[$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=$mons[$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 ERRORS ('.$dat1.' - '.$dat2.')',
        'x2-axis label' => 'time',
        'y-axis label'=> 'error record number in 5 mins',
        'x-axis label' => 'time',
        'size'=>[1.2,0.7],
        'output type' => 'gif',
        'output file' => '/home/httpd/htdocs/saturn/attacks/ids/time_distrib.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_distrib.txt'],
        );
close(TDS);

#print "TIME_DISTR","\n\n";
#########################################
# Writing the file <ip_total1.txt>	#
# PNG-graphics with horizontal bars	#
#########################################

foreach $key (reverse sort {$ip_tot{$a} <=> $ip_tot{$b}} keys %ip_tot)
{
print Fipt $key," ",$ip_tot{$key},"\n";
}

#####################################################
# making up a picture from the file <ip_total1.txt> #
#####################################################

$path1='/home/httpd/htdocs/saturn/attacks/ids/ip_total1.png';
#$path1='e:/www//attacks/ids/ip_total1.png';
# 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_total1.txt',$path1,1,7,3,$img,15);
#$img = &vert_diagr(15,600,400,15,'e:/www/attacks/ids/ip_total1.txt',$path1,1,7,3,$img,25);
print "IP_total\n";
open(PICTURE,"> $path1") or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;
close(Fipt);

######################################################
# making up a picture from the file <ip_attacks.txt> #
######################################################

$path1='/home/httpd/htdocs/saturn/attacks/ids/ip_attack_er.png';

$img = &vert_diagr(15,600,400,15,'/home/httpd/htdocs/saturn/attacks/ids/ip_attacks.txt',$path1,1,7,3,$img,15);

print "IP_total2\n";
open(PICTURE,"> $path1") or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;
#close(Fipt);
print "do...\n";

 "/home/crontab_files/secur.pl";	# start secur.pl
#exit(0);

