#!/usr/bin/perl
print "Content-type: text/html \n\n";

use IO::File;
use Socket;
use Fcntl;
use File::Copy;
use File::stat;
use Time::localtime;
use Time::Local;
use strict;

#########################################################
# Apache reconfiguration, adding "deny from IP-address"	#
# form ban_ip.txt and modify httpd.conf			#
#########################################################

my ($date_time,$day,$month,$year,$T0,$ip,$ppp,$line1,$i_ban,$n_wr,$fl);
my ($line,$p,$pp,$i,$k,$m,$record,$j,$jj,$p3,$p4,$p5,$p_test,$Nmax);
my ($mt,$ip,$flag,$year,$month,$day,$hrs,$mints,$secnds,$tm,$cod_,$ip_);
my (@MMM,@records,@ip_b,@code_b,@flags,@dates,@b_date,@recs,@R_Rec);
$i=0;
$k=0;
my @ip=();	# Attack's IP-array
my @code=();	# Attack's code-array
my @recs=();	# record status array
my $point;
my $ppn;
my $last_code=0;
my $last_ip=" ";
my $wr_flag=0;	# Flag is set, if there was a ban writing
my @rrr=();	# config tail

$rrr[0]="</Directory>";			# The tail part of <httpd.conf>
$rrr[1]="";
$rrr[2]="<Directory '/home/httpd/icons'>";
$rrr[3]="  Options Indexes MultiViews";
$rrr[4]="  AllowOverride None";
$rrr[5]="  Allow from all";
$rrr[6]="  Order allow,deny";
$rrr[7]="</Directory>";
$rrr[8]="";

#########################################################
# Yu. Semenov		02-Jul-2019			#
# Use status-file <server_status.txt>			#
# Format: date-time status-code IP			#
# Script reads file:					#
# <http_bas.conf> - unchangeable part of config file	#
# Open <httpd.conf>, go to the end unchangeable part	#
#
# looking for the line:					#
# "<Directory "home/httpd/htdocs">			#
# introduce into configure file the lines: 		#
# ### Date-time code					#
# deny from IP-address					#
# and restart Apache.					#
# In <ban_ip.txt> are written records, which		#
# correspond to the already banned IP-addresses.	#
# Format of <ban_ip.txt>:				#
# Date status-code IP					#
# The lines of <server_status.txt> with	IP		#
# counciding with IP in <ban_ip.txt>.			#
# are marked with flags and ignored at putting		#
# down in addition to the list from <ban_ip.txt>	#
#########################################################
# At first I make a backup-copy of httpd.conf		#
#########################################################

copy("/etc/httpd/conf/httpd.conf","/etc/httpd/conf/httpd_b.conf") or die "Copy failed: $!";

#########################################################
# Current Date-time calculation>which will be written	#
# into the file <ban_ip.txt>				#
#########################################################

$tm=localtime;
$year=$tm->year+1900;
$month=$tm->mon;
$day=$tm->mday;
$secnds=$tm->sec;
$mints=$tm->min;
$hrs=$tm->hour;
$month=$month+1;
$date_time=$day."-".$month."-".$year." ".$hrs.":".$mints.":".$secnds;
#print "Date-time=",$date_time,"\n";

$p="/etc/httpd/conf/httpd.conf";		# Apache configuration file (debug)

#$p_test="/home/httpd/htdocs/saturn/attacks/ids/httpd.conf";

$point="/home/httpd/htdocs/saturn/attacks/ids/apache_restart.txt";
sysopen(restart,$point, O_RDWR|O_CREAT|O_APPEND) or die "Can't start restart: $!\n";

#$p="/home/httpd/htdocs/saturn/attacks/ids/httpd.conf";
#open(h_point,$p) or die "Can't start tst1: $!\n";		# Open <httpd.conf>

###	 Read stable part of the configuration file from <http_bas.conf>	#################
$ppn="/home/httpd/htdocs/saturn/attacks/ids/http_bas.conf";					#
open(h_po,$ppn) or die "Can't start tst20: $!\n";		# Open <http_bas.conf>		#
$j=0;					# record counter					#
while(!eof(h_po))	{			#################				#
	$R_Rec[$j]=readline(h_po);				# Read stable head of conf-file	#
	$j++;							# record index			#
			}			#################				#
close(h_po);									#################

$p3="/home/httpd/htdocs/saturn/attacks/ids/server_status.txt";	# The file showing the server status
sysopen(Fstat, $p3, O_RDWR) or die "Can't start tst3: $!\n";	# open status-file <server_status.txt>

$mt=readline(Fstat);		# Read lines number in <server_status.txt>; 
chomp($mt);			# $mt= line number in file server_status.txt
#print "linesN=", $mt,"\n";

#########################################
# Reading out file <server_status.txt>	#
#########################################

for($i=0;$i<$mt;$i++)	{	# read status-lines	#################################
$recs[$i]=readline(Fstat);	# Read lines with IP-addresses from <server_status.txt>	#
@MMM=split(/\s/,$recs[$i]);								#
$dates[$i]=$MMM[0]." ".$MMM[1];	# date of attack					#
$ip[$i]=$MMM[3];		# Form ip-array (deny IP)				#
chomp($ip[$i]);			#							#
$code[$i]=$MMM[2];		# Form code-array (ban reasons)				#
#print "dat_time=",$dates[$i]," cod=",$code[$i]," ip=",$ip[$i],"\n";			#
			}	#########################################################
close(Fstat);			# Close file <server_status.txt>

#print "STATUS mt=",$mt," IP=",$ip[0]," cod=",$code[0],"\n";	# Print line's number in <server_status.txt>
#print "RECS=",$recs[0],"\n",$recs[1],"\n";;

#print "IP=",$ip[0]," ",$ip[1],"\n","Cod=",$code[0]," ",$code[1],"\n";

#########################################
# Reading out file <ban_ip.txt>		#
#########################################

$p4="/home/httpd/htdocs/saturn/attacks/ids/ban_ip.txt";		# File with banned already IP
sysopen(ban_ip,$p4, O_RDWR) or die "Can't start tst4: $!\n";	# Open file ban_ip.txt

#print "BAN_line=",readline(ban_ip),"\n";

$i_ban=0;			# Init index counter
while(!eof(ban_ip))	{	#	#########################
$line=readline(ban_ip);		# Read line of <ban_ip.txt>	#
#print "BAN-LINE=",$line;					#
@MMM=split(/\s/,$line);						#
$b_date[$i_ban]=$MMM[0].$MMM[1];				#
$code_b[$i_ban]=$MMM[2];	# Form the code_b-array		#
$ip_b[$i_ban]=$MMM[3];		# Form the ip_b-array		#
chomp($ip_b[$i_ban]);						#
if($i_ban==0)	{print "DT=",$b_date[$i_ban]," IP=",$ip_b[$i_ban],"\n";}
$i_ban++;			# update pointer		#
			}	#################################
#print "i_ban=",$i_ban,"\n";

#########################################
# Compare lists @ip_b and @ip		#
#########################################

$m=$mt;					# records number in <server_status.txt>
for($j=0;$j<$mt;$j++){$flags[$j]=1;}	# Set default flags values
for($j=0;$j<$mt;$j++)	{		# take IP from <server_status.txt>	#####################
for($k=0;$k<$i_ban;$k++)	{	# take IP from <ban_ip.txt>		################### #
if($ip[$j] eq $ip_b[$k])	{	#	################################################# # #
$m=$m-1;				# Number of unique IP for deny				# # #
$flags[$j]=0;				# Set flag to ignore this IP from <server_status.txt>	# # #
				}	#	################################################# # #
				}			########################################### #
			}							#####################
#print "flags0=",$flags[0],"\n";
close(ban_ip);				# close file <ban_ip.txt>

#########################################
# Upgrade file <server_st_new.txt>	#
# removing old records			#
#########################################

$p3="/home/httpd/htdocs/saturn/attacks/ids/server_st_new.txt";	# The file showing the WEB-server status
sysopen(Fsta, $p3, O_RDWR|O_CREAT|O_TRUNC) or die "Can't start tst6: $!\n";	# open status-file <server_st_new.txt>
for($j=0;$j<$mt;$j++)	{
if($j==0)	{print Fsta $m,"\n";}				# file <server_st_new.txt>
if($flags[$j]!=0){print Fsta $dates[$j]," ",$code[$j]," ",$ip[$j],"\n";	# Write into <server_st_new.txt>
		  $recs[$j]=$dates[$j]." $code[$j] ".$ip[$j];	# array for putting into
		$last_code=$code[$j];
		$last_ip=$ip[$j];
		}
			}
close(Fsta);							# Close file <server_st_new.txt>
#print "RECS=",$recs[0],"\n",$recs[1],"\n";

##########################################################
## We start to develop records of file <httpd.conf>	##
##########################################################

$p="/etc/httpd/conf/httpd.conf";				# Apache configuration file (debug)
open(h_point,$p) or die "Can't start tst1: $!\n";		# Open <httpd.conf>
$i=0;
$wr_flag=0;
$jj=0;					# last part index

while (!eof(h_point)) 	{		# Cycle for <httpd.conf>-file ### Reading all lines of the file
if($wr_flag==0)	{
	$line=readline(h_point);				#
	$i++;
if($i==898)	{						#
#		print "Reco=", $line,"\n";			# We are at the end of unchageable part
		$wr_flag=1;					#  write flag is set
#		$jj++;
		}						# We at the beginning
		}						# of second part
if($wr_flag==1)	{					####	# 
#    $jj++;
	$records[$jj]=readline(h_point);		   #	# Write line into array
if($jj==0) {print "REC-0=",$records[0],"\n";}
	$jj++;		# reading lines after main rec	   #	#
		}		    			####	#
			}				   ######
#print "JJ=",$jj," Rec-4=", $records[$jj-4]," -3=",$records[$jj-3]," -2=",$records[$jj-2], "\n";
close(h_point);					# Close <httpd.conf>

sysopen(newW,$p, O_RDWR|O_CREAT|O_TRUNC|O_APPEND) or die "Can't start newWrite: $!\n";

for($jj=0;$jj<($#R_Rec+1); $jj++)	{
	print newW $R_Rec[$jj];		# write unchageable part of httpd.conf into <httpd.conf>
					}

#########################################
# Writing 2*$mt lines of codes and	#
# "deny from IP-address"		#
#########################################

for($j=0;$j<$mt;$j++)	{			   ######
if($flags[$j]==1)	{		#########	# is IP unique?
#print newW "### $dates[$j] $code[$j]","\n";	#	#
#$records[$i]="### $dates[$j] $code[$j]"."\n";	#	# Putting date-time and ban-code
#print "Rec_Write=",$records[$i]," II=",$i,"\n";#       #
$i++;						#	#
#print "deny_I=",$i,"\n";			#	#
						#	#
#################################		#	#
# Writing "deny from IP-address	#               #       #
#################################               #       #
print "wr_deny=",$ip[$j],"\n";
print newW "deny from ".$ip[$j]."\n";		#	# Write new Deny line
#$records[$i]="deny from ".$ip[$j]."\n";	#	#
						#	#
$wr_flag=7;					#	#
$ip_=$ip[$j];					#	#
$cod_=$code[$j];				#	#
		$i++;				#	#
			}		#########	#
			}			   ######

#print "Total_lines=",$i,"\n";

#################################
# Open and write <httpd.conf>	#
#################################

$Nmax=$#records;
print "Rec0=",$records[0],"\n";
if($Nmax>835)	{$Nmax=835;}
for($m=0; $m<$Nmax; $m++)	{	# Write old Deny;s
			print newW $records[$m];
				}

for($m=0; $m<9; $m++)	{
	print newW $rrr[$m],"\n";	# Write config file tail
			}

close(newW);			# close <httpd_test.conf>

#########################################
# Upgrading of file <ban_ip.txt>	#
#########################################

sysopen(ban, $p4, O_RDWR|O_APPEND|O_CREAT) or die "Can't start tst100: $!\n";	# Open ban_ip.txt
print "mt=",$mt," flag0=",$flags[0]," $i_ban=",$i_ban,"\n";

for($j=0;$j<$mt; $j++)  {	# cicle for <ban_ip.txt> list ###
if($flags[$j]!=0)	{	#				#
print ban $date_time," ",$code[$j]," ",$ip[$j],"\n";	# Writing into <ban_ip.txt>
$wr_flag=7;							#
			}					#
			}				   ######
close(ban);

$p5="/home/httpd/htdocs/saturn/attacks/ids/ban_ip1.txt";         # File with banned IP
sysopen(ban_ipr,$p5, O_RDWR|O_TRUNC|O_CREAT) or die "Can't start tst5: $!\n";

# File <ban_ip1.txt> upgrating

for($k=0;$k<$mt;$k++)	{  					# Write lines from server_status.txt>
if($flags[$k]!=0)       {
print ban_ipr $date_time," ",$code[$k]," ",$ip[$k],"\n";	# Write into ban_ip1.txt
			}
#print "Date=",$date_time," Cod=",$code[$k]," IP=",$ip[$k]," flags=",$flags[$k],"\n";
			}
close(ban_ip);
close(ban_ipr);

############################
#### Apache RESTART	####
############################

print "FL7=",$wr_flag,"\n";

if($wr_flag==7)	{				# If there are changes in httpd.conf, then restart
print "WRITING"," COD=",$cod_," IP=",$ip_,"\n";

print restart $date_time," COD=",$cod_," IP=",$ip_,"\n";	# Write into log-file apache_restart.txt
system("apachectl graceful");					# Apache restart
		}
close(restart);
exit(0);

