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

use IO::File;
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;

my ($con,$res,$start,$stop,$time,$date,$day,$month,$year,$T0,$ip,$abs_start,$p2,$img,$path);
my ($line,$p,$p1,$ppp,$i,$minutes,$hours,$seconds,$date_time,$record,$j,$r,$mark,$m,$fl);
my (@ary,@len,@nam,@LL,@LLL,@records,$form_data,$tm,$pin1);	# array, returned with request
my @mon=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
my @patern=("refused connect from","Failed password for root from","authentication failure;");
# "Too many authentication failures for root");
my (@tim,@t_mark,@L,@n_val,@file);
my ($key,$ip_max,$t_bin,$t_num,$n_max,$delt,$mon,$mins,$secs,$y_max,$y_min,$tm0,$tmm,$t_mid);
my ($dat1,$dat2,$y1,$y2,$y3,$y4,$y5);
$i=0;
my $k=0;
my %ip_at=();				# hash-array IP-number

#########################################
# Yu. Semenov				#
# Script reads file:			#
# <secure>, extracts the records    	#
# with patern, showing refused access 	#
# current day distribution		#
# 10 minute intervals. Format secure:	#
# Jan 24 21:22:17 saturn sshd[11814]: refused connect from 183.91.14.12 (183.91.14.12)
# Jan 24 21:25:41 saturn sshd[11853]: warning: /etc/hosts.allow, line 7: can't verify hostname: getaddrinfo(12.14.91.183-ftth.cmcti.vn, AF_INET) failed
# file ip_secure.txt IP-distribution	#
# taken from 00:00:00.			#
# file <ip_atk_sec.txt> Error records	#
# written from 00:00:00.		#
# file <time_dis_sec.txt> time		#
# distribution of pass events		#
# <ip_secure.txt> - IP-distribution	#
#########################################

#################################################################
# $abs_start is a time, corresponding to 00:00 of current day	#
#################################################################

$p="/var/log/secure";			# input file  <secure.>

# calculate <secure> file, taking the latest one

#$n_max=0;	# for log_rotation with time-dates in file names
#@file=grep {/secure/} readdir(DIR);
#for($i=0;$i<4;$i++)	{$LL[$i]=substr($file[$i],11);
#			if($LL[$i]>$n_max)	{$n_max=$LL[$i];
#			$m=$i;			}
#			}
#my $file_name="access_log"."-".$LL[$m];
#print "F_name=",$file_name," LL=",$LL[$m],"\n";
#closedir(DIR);
#$p=$p."-".$LL[$m];
#print "P=",$p,"\n";

#@list=grep {/secure/} readdir(DIR);

open(h_point,$p) or die "Can't start tst1: $!\n";		# Open <secure>-file
$i=0;
my $er_num=0;				# Error number
my $dt=600;				# delta time = 10 minute
my $counter=1440/10;			# max bin number
my $n_req=0;
my $flag=0;				# Is the data in memory? (not the first request)
$start=time;
$stop=$start-86400;			# one day before
$p1="/home/httpd/htdocs/saturn/attacks/ids/time_dis_sec.txt";	# output file  <time_dis_sec.txt>
$p2="/home/httpd/htdocs/saturn/attacks/ids/ip_secure.txt";	# output file  <ip_secure.txt>
$ppp="/home/httpd/htdocs/saturn/attacks/ids/ip_atk_sec.txt";	# input file  <ip_atk_sec.txt>
#$stop=time;				# The time of calculation
#$start=$stop-600;			# time of 10 minutes before
$tm=localtime;
$year=($tm->year);
$month=($tm->mon);
$day=$tm->mday;
print "Year=",$year," time=",$start,"\n";
$abs_start=timelocal(0,0,0,$day,$month,$year);	# current day 00:00:00
print "ABS_st=",$abs_start," cur_time=",time,"\n";
if((time-$abs_start)<$dt)	{	# $dt=10 min

#################################################
# Clear the file, at a new day beginning	#
#################################################

sysopen(p_tim, $p1, O_RDWR|O_TRUNC|O_CREAT) or die$!;	# open output <time_dis_sec.txt> file
sysopen(p_sec, $p2, O_RDWR|O_TRUNC|O_CREAT) or die$!;	# open output <ip_secure.txt> file
sysopen(Fip, $ppp, O_RDWR|O_TRUNC|O_CREAT|O_APPEND) or die$!;	# open output <ip_atk_sec.txt> file	???????
print "new-file\n";
}
else{sysopen(p_tim, $p1, O_RDWR|O_CREAT|O_TRUNC) or die$!;	# open output <time_dis_sec.txt> file
sysopen(p_sec, $p2, O_RDWR|O_CREAT|O_APPEND) or die$!;
#open(p_sec, "+>> $p2>") or die$!;		# open output <ip_secure.txt> file
sysopen(Fip, $ppp, O_RDWR|O_CREAT|O_APPEND) or die$!;		# open output <ip_atk_sec.txt> file	
print "old-file\n";
}
$tm=localtime;
$year=($tm->year);
#$month=($tm->mon);
#$day=$tm->mday;
print "Year=",$year," time=",$start,"\n";
for($i=0;$i<$counter;$i++)	{$tim[$i]=0;}	# Clear distribution array

#################################################
while(!eof(p_sec))	{			# Reading file <ip_secure.txt>
$line=readline(p_sec);
@LL=split/\s/,$line;
$ip=$LL[0];					# Create hash-array
$ip_at{$ip}=$LL[1];				# IP-hash-array
			}
close(p_sec);

sysopen(p_sec, $p2, O_RDWR|O_TRUNC) or die$!;	# open output <ip_secure.txt> file

while (!eof(h_point)) 	{			# Cycle for <secure>-file
$line=readline(h_point);			# read lines of <secure>
@LL=split/\s+/,$line;
$month=$LL[0];
for($i=0;$i<12;$i++){if($month eq $mon[$i]){$month=$i;}}	#
$day=$LL[1];
$time=$LL[2];
@LLL=split/\:/,$time;
$hours=$LLL[0];
$minutes=$LLL[1];
$seconds=$LLL[2];
$T0=timelocal($seconds,$minutes,$hours,$day,$month,$year);	# time of given event
#print "T0=",$T0," stop=",$stop,"\n";
if($T0>$stop)		{	#################################
$fl=0;				# init includings flag		#

#### Is it attack?	comparing with known patterns		#

for($r=0;$r<$#patern+1;$r++)	{	#################	#
if(index($line,$patern[$r])>=0)	{	#########	#	#
	$ip=$LL[8];				#	#	#
if($r==2)	{				#	#	#
my $ind=index($line,'rhost');			#	#	#
my $lin=substr($line,($ind+6));			#	#	#
my @L=split/\s/,$lin;				#	#	#
$ip=$L[0];					#	#	#
		}				#	#	#
print "IP_new=",$ip,"\n";
#	$ip=substr($ip,1);	# IP-adr	# remove starting "(" for old format
#	$ip=substr($ip,0,-1);			# remove the last ")"
@LLL=split/\./,$ip;				#	#
if($#LLL!=3)	{		#########	#	#
$ip="-.-.-.-";				#	#	#
print "IP=",$ip," NN=",$#LLL,"\n";	#	#	#
		}		#########	#	#
						#	#
$tim[int(($T0-$start)/$dt)]++;	# time array filling in	#
				}	#########	#

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;}					#

if($fl==0)	{		#################	#	#
if(index($line,$patern[$r])>=0){$fl=1;}		#	#	#
		}		#################	#	#
#print "fl=",$fl," I=",$r," LL=",$line,"\n";			#
			}	#################################

if($fl!=0)	{	# There is a refusal of access	#####
#print "F=",$fl," LLL=",$line,"\n";			    #
$records[$n_req]=$line;	# put down the record		    #
print Fip $line;					    #
$n_req++;						    #
		}					#####

#print "time=",$TIME," Start=",$time_start," Stop=",$time_stop,"\n";
				}				#end of IF
					}			# end of WHILE

#print "date_time=",$date_time," time=",$TIME," tim_star=",$time_start," NNN=",$i,"\n";
close(h_point);
close(Fip);

$fl=0;
$ip_max=" ";
$n_max=0;
foreach $key (reverse sort {$ip_at{$a} <=> $ip_at{$b}} keys %ip_at)
{
print p_sec $key," ",$ip_at{$key},"\n";
if($fl==0)	{
$fl=1;
$ip_max=$key;
$n_max=$ip_at{$key};
		}
}
print "IP_m1=",$ip_max," N_max1=",$n_max,"\n";
#print Fip $date_time," ",$ip_max," ",$n_max,"\n";

#################################################
#	Writing to the file <time_dis_sec.txt>	#
#################################################
#print "Counter=",$counter,"\n";
for($i=0;$i<$counter;$i++)	{
$t_bin=$i*600+$abs_start;
$t_num=$tim[$i];
print p_tim $t_bin," ",$t_num,"\n";	# Writing into the file <time_dis_sec.txt>
				}
close(p_tim);

#########################
# Start of GNUPLOT	#
#########################
$i=0;
$y_max=0;
$y_min=0;
$p="/home/httpd/htdocs/saturn/attacks/ids/time_dis_sec.txt";
sysopen(TD_sec,$p,O_RDWR) or die$!;     #

while (!eof(TD_sec))     {		# Cycle for <time_dis_sec.txt>
$line=readline(TD_sec);
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 attacks ('.$dat1.' - '.$dat2.')',
'x2-axis label' => 'Time',
'y-axis label'=> 'Attacks 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_sec.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_sec.txt'],
);
close(TD_sec);

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

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

print "</head></html>";
exit(0);

