#!/usr/bin/perl
# logfiretero 0.1 - log analyzer example for firetero iptables syslog/ulogd
# (c) 2006  Tero Karvinen http://www.iki.fi/karvinen

use strict;
use Getopt::Long; # Does this require anything?
use Socket; # gethostbyaddr()
use Net::IP; # Requires: libnet-ip-perl (main). For iptype()

#my $file="/var/log/ulog/syslogemu.log";
my $file="/dev/stdin";
my $help=0;
my $verbose=0;
GetOptions(
        'file|f=s' => \$file,
        'help|h' => \$help,
        'verbose|v' => \$verbose
);
# constants (that are defined as variables because the syntax is easier)
my $EXIT_SUCCESS=0;

### functions
sub v   # verbose, if criteria met. Read global variable $verbose
{       # future: log
        my ($s, $cond) = @_;
        if ($cond =~ m/^$/) { $cond=$verbose } # Global variable
        chomp($s);
        if ($cond) { print "$s\n" }
}

sub help
{
        print "logfiretero - log analyzer for firetero iptables syslog\n";
        print "usage: tail -f /var/log/ulog/syslogemu.log| logfiretero\n";
        exit $EXIT_SUCCESS;
}

sub ispublic {  # return true if $1-address is public ip address
                # called by score()
                # from wheretero (c) Tero Karvinen
        my $address;
        ($address) = @_;
        my $ip = new Net::IP ($address)   # needs Net::IP
         || die("ERROR getting name for $address.");
        return ( $ip->iptype() =~ m/^PUBLIC$/ );
}

sub dns
{
        my ($address)=@_;
        my $name;
        if (ispublic($address)) {
                $name = gethostbyaddr(inet_aton($address), AF_INET); # "use Socket"
        } else {
                $name = $address;
        }
        return $name;
}

### main
open(FILE, "$file");

my $s; # temporary string
my $line;

my $src;
my $dst;
my $dpt;
my $spt;
my $proto;

if ($help) { help(); }

while(<FILE>) { # walk FILE by line
        $line = $_;
        chomp $line;
        foreach $s (split(/\s+/,$line)) {
                if ($s=~ m/SRC=(\d+\.\d+\.\d+\.\d+)/) { $src=$1; }
                if ($s=~ m/SPT=(\d+)/) { $spt=$1; }
                if ($s=~ m/PROTO=(\w+)/) { $proto="\L$1"; } # \L converts to lower case
                if ($s=~ m/DST=(\d+\.\d+\.\d+\.\d+)/) { $dst=$1; };
                if ($s=~ m/DPT=(\d+)/) { $dpt=$1; }     
        }
        print(dns($src).":$spt \t->\t".dns($dst).":$dpt");
        if (!($proto =~ m/tcp/)) { print "\t$proto" }
        print "\n";
}