#!/usr/bin/perl
# Done by James Seng (jseng@technet.sg)
# Finger Deamon with enhanced logging

# modify the next line if there if you are not using BSD netstat
$file_netstat='/usr/bin/netstat -n -f inet';
$file_finger='finger';
$file_log='/var/log/trap/fingerd';

$_=`/bin/date`;
($day,$mth,$date,$time,@null)=split;

open(NET,"$file_netstat |");
while (<NET>) {
    ($proto,$recv,$send,$local,$other,$state)=split;
    ($n1,$n2,$n3,$n4,$n5)=split(/\./,$local);
    if (($n5=~ /79/) && ($state=~ /ESTABLISHED/)) {
        ($n1,$n2,$n3,$n4,$rport)=split(/\./,$other);
        $remote=join('.',$n1,$n2,$n3,$n4);
        $remoteip=pack('CCCC',$n1,$n2,$n3,$n4);
        last;
    }
}
close(NET);

$remote=~s/\s+(.*)/\1/;

$auth=`/usr/libexec/authuser $remote $rport 79`;
chop($auth);
chop($auth);
($state,$userid,$hosttype,$user)=split(/:/,$auth);
$user=~s/^\s+(.*)/\1/;

($name,$aliases,$addrtype,$length,@null)=gethostbyaddr($remoteip,2);

open(LOG,">>$file_log");
$input=<STDIN>;
print(LOG "$date $mth $time : Finger $user@$name[$remote] : $input");
close(LOG);

if ($input =~ /[!,@,#,$,%,^,&,*,(,),_,-,+,=,,,|,;,]/) { exit; }

open(FIN,"$file_finger $input|");
while(<FIN>) {
    print;
}
close(FIN);
