#!/usr/bin/perl
print "Content-type: text/html \n\n";

#########################################################
# Yu.Semenov ITEP	December 2010			#
# <access_log.filt> development				#
# The total IP-distribution <ip_total.txt> for the	#
# last day						#
#########################################################

use IO::File;
use Fcntl;
use Socket;
use Time::Local;
use DBI;
use GD;
use graf_dec;   		# Sher library
#use Chart::Gnuplot;
use strict;

my @mon=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
my @forbid=("cgiwrap",'"PUT','"TRACE','"DELETE','"OPTIONS','"PROPFIND');
my $l_len=1;			# init line index
my $n_req=0;
my $n_reqt=0;
my $N_rc=0;
my $marker=-1;
my $duration=0;
my $ipa_count=0;		# number of records in file <atk_ip.txt>
my $s_cur=0;
my $browser="";
my $day_night=86400;		# seconds
my $star_TIME=0;
my $count=0;
my %rec=();			# Hash-array of records
my $delt=0;
my $step=50;			# bin width
my $sum_len=0;			# sum length of all records
my @records=("","","","","","","","","","","");	#records array
my $tot_len=0;			# length from the file beginning
my $tot_rec_count=0;		# record counter in a file
my $local_rec_count=0;		# record counter in a second
my %ipa=();			# IP-hash-array
my %ipb=();			# hash array of ips{name}
my ($line,$con,$length,$p1,$p2,$year,$month,$day,$Tst,$path1);
my ($sigm,$D,$s_length,$len_avr,$tot_num,$pi,$K,$j,$datetime,$DT0,$stop_TIME);
my ($p_cgi,$name,$p_tot);
my ($hours,$minutes,$seconds,$TIME,$date,$date_time,$pr,$p_r,$img,$start_TIME,$cur_TIME);
my ($p_dens,$ip_num,$p,$p_del,$T0,$ip,$p_rec,$ip_adr,$p_len,$p_delta,$pin1,$ptd,$pdel,$counts,$p1_del);
my ($i,$nm,$s,$m,$pin,$key,$delta,$k,$ico,$jpg,$p_reqv,$fl,$M,$len,$num,$pp,$end_TIME,$cnt);
my (@ar,@L,@LL,@LLL,@Mi,@Lm,@R,@lengths,@recds,@MM,@MMM,@NNN,@t_bins,@tm,@ill);
@Mi=("","","","");
$R[0]="";

#$pin="e:/www/attacks/ids/access_log.filt";	# Basic log-file
$pin="/home/httpd/htdocs/saturn/attacks/ids/access_log.filt";

# Opening the access_log.filt-file
sysopen(AFIL, $pin, O_RDWR) or die$!;

#########################################
# Reading of file <access_log.filt>	#
#########################################

while (!eof(AFIL)) {	# Cycle for <access_log.filt>-file ## Development START ###
$line="";							#
$line=readline(AFIL);						#
@ar=split(//,$line);                            		#
if($#ar>52)	{			# line length control	#
#print "Line=",$line,"\n";					#
$N_rc++;					# Next record	#
@MM=split/\s+/,$line;						#
#########################################################################
# First record in the file <access_log.filt> is a last in time		#
# pool-93-186-96-64.lanta-net.ru - - [22/Nov/2009:04:09:51 +0300]	#
# Date-Time format: [22/Nov/2009:04:09:51 +0300]			#
#########################################################################
$date_time=substr($MM[3],1,20);	# leading [-symbol removing		#
@MMM=split(/\:/,$date_time);						#
if($#MMM==3){		# date terms number control			#
$date=$MMM[0];							#	#
#if($N_rc==1)	{print " DA=",$date,"\n";}			#	#
@NNN=split(/\//,$date);						#	#
if(!(defined$NNN[0]))	{$NNN[0]=1;}				#	#
$day=$NNN[0];							#	#
if(!(defined$NNN[1]))	{$NNN[1]=1;}				#	#
$month=$NNN[1];							#	#
for($i=0;$i<12;$i++){if($month eq $mon[$i]){$month=$i;}}	#
if(!(defined$NNN[2]))	{$NNN[2]=2;}				#	#
$year=$NNN[2];							#	#
#if($N_rc==1)	{print " Y=",$year,"\n";}			#	#
$year=$year-1900;						#	#
if(!(defined$MMM[1]))	{$MMM[1]=1;}				#	#
$hours=$MMM[1];							#	#
if(!(defined$MMM[2]))	{$MMM[2]=1;}				#	#
$minutes=$MMM[2];						#	#
if(!(defined$MMM[3]))	{$MMM[3]=1;}				#	#
$seconds=$MMM[3];							#
$cur_TIME=timelocal($seconds,$minutes,$hours,$day,$month,$year);
#print " year=",$year," mon=",$month," day=",$day," hour=",$hours," min=",$minutes," sec=",$seconds,"\n";											#
if($N_rc==1)	{print "S=",$seconds,"\n";}			#
if($N_rc==1)	{					#####
print "start-time=",$cur_TIME,"\n";			    #	#
#$end_TIME=$cur_TIME+$day_night;			    #	#
				}			#####	#

$records[$n_req]=$line;			# put down the record	#
$rec{$records[$n_req]}=$cur_TIME;	# hash rec		#
$n_req++;							#
    }		# control number of terms in date ###
	}		# if for line length control
		}	# end of basic WHILE	########################

$stop_TIME=timelocal($seconds,$minutes,$hours,$day,$month,$year);
$start_TIME=$stop_TIME-$day_night;

print "stop-time=",$stop_TIME," hrs=",$hours," day=",$day," mon=",$month,"\n";
close(AFIL);			# Close file <access_log>	#
#print "useful records=",$n_req,"\n";

$counts=0;
foreach $key (sort {$rec{$a}<=>$rec{$b}} keys %rec)
{
	if($rec{$key}>$start_TIME)	{
		$records[$counts]="$key";		# Writing into file <record-array>
		# print "rec=",$records[$counts],"\n";
		$counts++;
								}
}
#print "counts=",$counts," rec0=",$records[0],"\n","rec_last=",$records[$counts-1],"\n";

# template for the file <date_time.txt>
$p_rec="/home/httpd/htdocs/saturn/attacks/ids/";
#$p_rec="e:/www/attacks/ids/";

$p_tot=$p_rec."ip_total.txt";

# Opening file <ip_total.txt>: IP-number		#
sysopen(Fipt, $p_tot, O_RDWR|O_TRUNC|O_CREAT) or die$!;	#

#########################################################
# Start of record array development			#
#########################################################

for($K=0;$K<$counts;$K++)	{	# Records-array CYCLE ###
$line=$records[$K];						#
#print "K=",$K," line=",$line," R=",$records[$K],"\n";
@L=split/\s+/,$line;	# Split request line			#
$l_len=$#L;		# number of words in request line	#
$name=$L[0];		# request source name
print "name=",$name,"\n";

#########################################################
# 		Record analysis				#
#########################################################

@Mi=split/\./,$L[0];		# Name analysis	(is it IP?)
@ar=split(//,$L[0]);

if($#ar<16)	{							#############
if($#Mi==3)		{		# Is it IP-address?		#########	#
if($Mi[0]!~/\D/)		{	# if number	#################	#	#
	if($Mi[0]>0 && $Mi[0]<255)	{				#####	#	#
if($Mi[1]!~/\D/)	{		# if number 	#####	#	#	#	#
	if($Mi[1]>0 && $Mi[1]<255)	{		#####	#	#	#	#
if($Mi[2]!~/\D/)		{	# if numbr  #####	#	#	#	#
	if($Mi[2]>0 && $Mi[2]<255)	{	######	#	# 	#	#	#
	if($Mi[3]>0 && $Mi[3]<255)	{	###  #  #	# #	#	#	#
	$ipb{$L[0]}=$L[0];			  #  #	# 	#	#	#	#
$ip=$L[0];					  #  #
print "L0=",$L[0]," IP=",$ip,"\n";		  #  #
if(exists($ipa{$L[0]}))	{	#####		  #  #
	$ipa{$L[0]}++;	}	    #		  #  #
else{$ipa{$L[0]}=1;}		#####		  #  #
#print "ipa=",$ipa{$L[0]},"\n";	   		  #  #	# 	#	#	#	#
					}     #####  #	# 	#	#	#	#
					}	######	# 	#	#	#	#
				}		######### 	#	#	#	#
			}		   	#####	#	#	#	#	#
		}					#####	#	#	#	#
		}					#####	#	#	#
						}		 #################	#
				}		#####	#
		}					  #####

if(exists($ipb{$L[0]}))	{	#####
	$ip=$ipb{$L[0]};			#
print "IP=",$ip,"\n";			#
						}#####
else{		# find out if nothing in hash	#####
$ip_adr= gethostbyname($L[0]);				#
if (defined $ip_adr) 	{	#####			#
$ip = inet_ntoa($ip_adr);	    # IP-adr 		#
#print "iipp=",$ip,"\n";		    #
			}	#####	#
else{$ip="1.1.1.1";}						#
	if(exists($ipa{$ip}))	{	# IP-hash updating	#####
		$ipa{$ip}++;					#
#		print "ipa=",$ip," n=",$ipa{$ip},"\n";		#
	}					  #######
	else{$ipa{$ip}=1;
		print "IPP=",$ip,"\n";
	}								#
    }								    	#####
}
#print "name=",$L[0],"\n";	# fix IP

#####################################################
# %ipa-hash creating & updating			    #
#####################################################
#print "IPa=",$ipa{$ip},"\n";

$ipa_count=0;
foreach $key (reverse sort {$ipa{$a}<=>$ipa{$b}} keys %ipa)
{print Fipt "$key $ipa{$key}\n";		# Writing into file <ip_total.txt>
	$ipa_count++;
print "IPA= $key $ipa{$key}\n";
}
#print "Tst=",$Tst," TIME=",$TIME,"\n";

close(Fipt);

#}	# end of WHILE

#print "useful records=",$n_req," Total length=",$sum_len," Total_recs=",$n_reqt,"\n";
#print "START=",$DT0," FINISH=",$datetime,"\n";

####################################################
# making up a picture from the file <ip_total.txt> #
####################################################

$path1='/home/httpd/htdocs/saturn/attacks/ids/ip_total.png';
#$path1='e:/www//attacks/ids/ip_total.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_total.txt',$path1,1,7,3,$img,25);
#$img = &vert_diagr(15,600,400,15,'e:/www/attacks/ids/ip_total.txt',$path1,1,7,3,$img,25);
print"len_distrib\n";
open(PICTURE,"> $path1") or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;

#########################################
sub ip_to_num
{
#########################################
# IP-address to a number conversion	#
#########################################
my @Lm;
my ($s)=@_;
@Lm=split/\./,$s;
if($#Lm < 3) {return -1;}
else    { return ((((($Lm[0]<<8)+$Lm[1])<<8)+$Lm[2])<<8)+$Lm[3];
		}
}
exit;
#END { }
