#!/usr/bin/perl

open LOG, $ENV{'LOGCAT'} ;
open REPORT, ">$ENV{'LOGREPORT'}" ;
open FILTER, ">$ENV{'LOGFILTER'}" ;

my %r_refused ;
my %r_illegal ;
while ( <LOG> ) {
	chomp ;
	if ( m/sshd\[\d+\]: refused connect from ([\w\.]+)/ ) {
		print FILTER "$_\n" ;
		$r_refused{$1}++ ;
		next ;
	}
	if (( m/sshd\[\d+\]: [Ff]ailed.*for illegal user (.*?) from ([\w\.]+)/ )
	or ( m/sshd\[\d+\]: [Ii]llegal user (.*?) from ([\w\.]+)/ )) {
		print FILTER "$_\n" ;
		my $u = ( $1 eq '' ? "<none>" : $1 ) ;
		$r_illegal{"$u from $2"}++ ;
		next ;
	}
}
close LOG ;
close FILTER ;

if ( %r_refused ) {
	print REPORT "<h4>Refused SSH connections</h4>\n" ;
	print REPORT "<table width='100%' rules='cols' cellpadding='2'>\n" ;
	my $c = 0 ;
		foreach $k ( keys %r_refused ) {
			print REPORT "<tr" . ( $c%2 == 0 ? " bgcolor='#dddddd'" : "" ) .">" ;
			print REPORT "<td>$k  (" . $r_refused{$k} . ")</td></tr>\n" ;
		$c++ ;
	}
	print REPORT "</table>\n" ;
}

if ( %r_illegal ) {
	print REPORT "<h4>Illegal SSH users</h4>\n" ;
	print REPORT "<table width='100%' rules='cols' cellpadding='2'>\n" ;
	my $c = 0 ;
		foreach $k ( keys %r_illegal ) {
			print REPORT "<tr" . ( $c%2 == 0 ? " bgcolor='#dddddd'" : "" ) .">" ;
			print REPORT "<td>$k  (" . $r_illegal{$k} . ")</td></tr>\n" ;
		$c++ ;
	}
	print REPORT "</table>\n" ;
}
close REPORT ;
