#!/usr/bin/perl

#File: IDS.pl
#Description: This is the intrusion detection system that monitors the
#				  secure files. It creates hashes of the secure files, encodes them
#				  and store them. It checks the files every 10 seconds. It reads the 
#				  saved digests it decodes them and compares it to a digest created
#				  from the actual file. When an intrusion is detected it sends a message
#					to the Host.


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


my $hostSocket = new IO::Socket::INET (
	PeerAddr => "pikespeak.uccs.edu",
	PeerPort => 8000,
	Proto => 'tcp'
);
die "Couldn't connect to host: $!" unless $hostSocket;


my $md = Digest::MD5->new();
my $SymKey = pack("H*","0123456789AAAAAA0123456789AAAAAA0123456789AAAAAA0123456789AAAAAA");
my $aes = Crypt::ECB -> new();
$aes -> padding(PADDING_AUTO);
$aes -> cipher("Rijndael");
$aes -> key($SymKey);
open(CONFIG, "config.log");
while(<CONFIG>){
	my $file = $_;
	print "hashing file: $file";
	open(FILE, "$file");
	my @contents = <FILE>;
	close(FILE);
	my $joined = join "",@contents;
	$md->add($joined);
	my $digest = $md->digest();
	my $hash = unpack("H*",$digest);
	$aes -> start("encrypt") or $aes -> errstring();
	$hash = $aes->crypt($hash);
	$hash .= $aes->finish();
	chomp($file);
	open(OUT, ">$file.hash");
	print OUT "$hash";
	close(OUT);
}
close(CONFIG);

my $count = 0;
while(){
	$count++;
	print "\n\nIteration: $count\n";
	open(CONFIG, "config.log");
	while(<CONFIG>){
		my $file = $_;
		print "Checking: $file";
		open(FILE, "$file");
		my @contents = <FILE>;
		close(FILE);
		my $joined = join "",@contents;
		$md->add($joined);
		my $currentdigest = $md->digest();
		my $currenthash = unpack("H*",$currentdigest);
		
		$aes->start("decrypt") or $aes->errstring();
		chomp($file);
		open(IN, "$file.hash");
		my @savedcontent = <IN>;
		close(IN);
		my $encryptedhash = join "",@savedcontent;
		my $hash = $aes->crypt($encryptedhash);
		$hash .= $aes->finish();

		if($hash == $currenthash){
			print "File: $file is secure\n";
		}
		else{
			print "Intrusion detected.\nFile: $file has been altered\n";
			print "saved hash: $hash\ncurrent hash: $currenthash\n";
			print "Warning sent to Host\n";
			print $hostSocket "intrusion\n";
			exit(1);
		}
	}
	close (CONFIG);
	print $hostSocket "allclear\n";
	sleep(10);
}
