#!/usr/bin/perl

#File: Host.pl
#Description: This is the host server whose file the intruder tries to modify.
#				  The host has a host based intrusion detection system like Tripwire
#				  that uses a configuration file to get the list of secure files.
#				  When one of the protected file is modified it raises an alarm and
#				  sends an encrypted message to the administrator. It maintains a log
#					of all the events that have taken place.

use IO::Socket;
use Net::hostent;
use Digest::MD5;
use strict;

#Set up the host port
my $PORT = 8000;
my %socket = ( Proto => 'tcp',
					LocalPort => $PORT,
					Listen => 5,
					Reuse => 1);

my $Server = IO::Socket::INET -> new(%socket);
die "Cannot create server: $!" unless $Server;
print "Server is waiting for Client requests...\n";

my ($client, $data, $processID);
#read in comming messages
while ($client = $Server -> accept()) {
	#fork to handle multiple clients
	$processID = fork();
	die "Cannot fork:  $!" unless defined ($processID);
	next if ($processID > 0);
	serviceAClient($client);
	close $client;
}


###########  Subroutines  ####################
sub endhost(){
	exit 0;
}


#service a client connection
sub serviceAClient{
	my($socket) = @_;
	my $close = 0;
	my $hostInfo = gethostbyaddr($socket -> peeraddr());
	print "[Connect from ", $hostInfo -> name, "]\n";
	open(LOG, ">>$0log.txt");
 	print LOG "[Connect from ", $hostInfo -> name, "] ",`date`;
	close(LOG);

	print $socket "Welcome to server $0 on $ENV{'HOST'}\n";

	#Read commands from the socket
	while (my $socketCommand = <$socket>){
		#Process the read command
		if($socketCommand =~ (/read (.+)/)){
			print "Client wants to read file: $1\n";
			if(open(IN,"$1")){
				close(IN);
				#Update the log file
				open(LOG, ">>$0log.txt");
 				print LOG "Client read file $1 ",`date`;
				close(LOG);
			}
			else{
				print "Cannot open file $1: $!\n";
			}
		}
		#process the update command
		elsif($socketCommand =~ (/update (.+)/)){
			print "Client wants to update file: $1\n";
			#Update the log file
			open(LOG, ">>$0log.txt");
 			print LOG "Client updated file $1 ",`date`;
			close(LOG);
			open(OUT, ">>$1");
			print OUT "Modified\n";
			close(OUT);
		}
		#process the allclear command
		elsif($socketCommand =~ (/allclear/)){
			print "All clear received from IDS\n";
			#Update the log file
			open(LOG, ">>$0log.txt");
 			print LOG "***Clear*** ",`date`,"\n";
			close(LOG);
		}
		#process the intrusion command
		elsif($socketCommand =~ (/intrusion/)){
			print "IDS detects intrusion at ",`date`;
			print "Intrusion being reported to administrator..\n";
			print "All connections terminated due to intrusion\n";
			#Update the log file
			open(LOG, ">>$0log.txt");
 			print LOG "Intrusion reported on ",`date`,"\n";
			close(LOG);
			endhost();
		}
		else{
			print $socket "Invalid command.\n";
		}
	}
}
