#!/usr/bin/perl
#
# Title: 	Find Attack Chains
#
# File: 	attackchains.pl
#
# Version: 	1.0
#
# Written by:	raffael.marty@arcsight.com (ram)
#
# Description:	This script is used to find attack chains in snort alerts. 
# 		The initialEvent might have to be changed to start finding certain
# 		attack chains.
#
# Usage:	./attackchains.pl
#
# URL:		http://afterglow.sourceforge.net
#			
# Changes:	
# 
# 10/23/04	Initial Version by ram
# 12/05/04	Adding some comments
#
###############################################################################/

use strict;
use DBI; 

# This is the first event in the attack chain. This could be set to anything, but will 
# blow up the whole query. If the database is not too big, that would be fine.
my $initialEvent = "P2P";


my $dbh = DBI->connect('DBI:mysql:tcpdump:localhost', 'root', 'pass')
	or die "Couldn't connect to database: " . DBI->errstr;

my $query1 = qq{select destip, sourceip from sans where (snort_alert like '%?%') order by destip};
my $sth1 = $dbh->prepare($query1) or die ("SQL error: ").$dbh->errstr;
my $res1 = $sth1->execute($initialEvent) or die ("SQL error: ").$dbh->errstr;

my $query2 = qq{select snort_alert, destip, sourceip, destport, sourceport from sans where (destip=? and sourceip=?) or (sourceip=? and destip=?) order by destip};
my $sth2 = $dbh->prepare($query2) or die ("SQL error: ").$dbh->errstr;

my %alerts;

while (my @data = $sth1->fetchrow_array()) {

	my $res2 = $sth2->execute($data[0],$data[1],$data[0],$data[1]);

	while (my @out = $sth2->fetchrow_array()) {
	
		$alerts{$out[0]." ".$out[1]." ".$out[2]." ".$out[3]." ".$out[4]} = $alerts{$out[0]}+1;
	}	
}

for my $entry (keys %alerts) {
	print "$entry\n";
}

$sth2->finish();
$dbh->disconnect();
