#!/usr/bin/perl -w

# This is an example script to generate e-mail with daily snort reports
# It rotates the snort.log file, generates a report in both text and html
# (as MIME multipart/alternate) and sends it to root.
#
# It uses snort-rep (http://people.ee.ethz.ch/~dws/software/snort-rep)

use strict;
use POSIX qw(strftime);
use MIME::Lite;

$ENV{PATH}='/usr/bin:/bin';

my $vault   = "/var/log/snort-old"; # where to place old snort logs
my $logname = "/var/log/snort.log"; # snort log-file
my $snort_rep = '/usr/local/sbin/snort-rep'; # snort-rep path
my @snort_rep_args =                         # snort-rep arguments
	qw(
	--narrow
	--resolve
	--local-file=/etc/snort-rep.local-nets
	--remove-name='\.ethz\.ch'
	);

sub TodayStr()
{
	return strftime("%Y%m%d",gmtime);
}

sub mv($$)
{
	my $from = shift;
	my $to = shift;
	# rename original
	rename "$from", "$from.$$" or die "ERROR: can't rename $from to $from.$$\n";
	# copy
	system "cp $from.$$ $to.$$" and exit 1;
	# delete original
	unlink "$from.$$" or die "ERROR: can't remove $from.$$: $!\n";
	# rename new
	rename "$to.$$", $to or die "ERROR: can't rename $to.$$ to $to: $!\n";
}

(stat($logname))[7]>0 or exit;

my $i=0;
my $base = "$vault/snort-".TodayStr();
while(-e "$base.$i") {
	$i++;
}
my $lastmoved = "$base.$i";
mv($logname, $lastmoved);
system "touch $logname";
system "kill -HUP `cat /etc/syslog.pid`"; # this is for Solaris...

my $msg = MIME::Lite->new(
	From => 'root',
	To => 'root',
	Subject => '[snort] report',
	Type => 'multipart/alternative',
	Datestamp => 0,
);

# make report
push @snort_rep_args, '--text';
push @snort_rep_args, '--html';
my $text = '';
my $html = '';
my $cmd = "$snort_rep ".join(' ',@snort_rep_args)." $lastmoved";
open(REPORT, "$cmd|") or die "can't execute $snort_rep: $!\n";
my $is_text=1;
while(<REPORT>) {
	if($is_text and /^<<<<</) { $is_text=0; next; }
	if($is_text) { $text .= $_; }
	else         { $html .= $_; }
}
close(REPORT);
$msg->attach(
	Type => 'TEXT',
	Data => $text,
);
$msg->attach(
	Type => 'text/html',
	Data => $html,
);
$msg->scrub;

# send it
$msg->send;
