#!/usr/bin/perl
#
# Title: 	Snort Directoin Bit to SQL
#
# File: 	snortdirection.pl
#
# Version: 	1.0
#
# Written by:	raffael.marty@arcsight.com (ram)
#
# Comments:	This takes a snort rules file and assumes a database with all the
# 		Snort binary logs in it. The it will go through the rules file and 
# 		update the service-flag in the DB to reflect the direction of the 
# 		event reported
#
# Usage:	cat complete | perl /home/ram/afterglow/src/perl/snortdirection.pl
#			
# URL:		http://afterglow.sourceforge.net
#
# Changes:	
# 
# 10/06/04	Initial Version by ram
#
###############################################################################/

use strict;
use DBI; 

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

# prepare some queries
my $query = qq{update sans set service=? where snort_alert like ? };
my $sth = $dbh->prepare($query) or die ("SQL error: ").$dbh->errstr;

my $service = 0;
my $snort_alert;

while (<STDIN>) {
	chomp;
	next unless (/alert/);

	my $input = $_;

	my $snort_alert = $input;

	if ( $snort_alert =~ /alert tcp \$\S+ (\d+) -> /) {

		next if ($1 > 1024);
		
		$snort_alert =~ s/.*msg:"([^"]*)";.*/\1/;

		# print $snort_alert."\n";

		my $res;
		
		$res = $sth->execute("2","%$snort_alert%") or 
			print "failure: $snort_alert\n";

			# print "reverse: $snort_alert\n";

		if ($res>1) {
			print "updated: $snort_alert\n";
		} else {
			print "not found: $snort_alert\n";
		}
			
		$sth->finish();

	}


}

$dbh->disconnect();
