#!/usr/bin/perl
#
# This nagios sensor will check if there have been too many 
# FTP logins from different locations by looking at the 
# geoip lookup of the ip.
#
# Too many connections from different countries may indicate a 
# compromised FTP account being accessed from a botnet.
#
# -----------------------------------------------------------------------------
# Copyright (C) 2008 John Sennesael
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------------

use strict;
use Switch;

# globals
my $warn=3;
my $critical=4;
my $status='UNKNOWN';
my $retval=3;

# parse args.
my $n = 0 ; 
my $ARGC = scalar(@ARGV);
foreach my $arg (@ARGV)
{
  my $ARGC = @ARGV;
  switch ($arg)
  {
    case "-c" 
    {   
      if ( $ARGC < ($n+1) )
      {   
        die("No value specified for -c.") ;
      }   
      $critical = $ARGV[$n+1] ;
    }   
    case "-w" 
    {   
      if ( $ARGC < ($n+1) )
      {   
        die("No value specified for -w.") ;
      }   
      $warn = $ARGV[$n+1] ;
    }   
 }
  $n += 1;
}

# check logins.
my $str_lastlog = `/usr/bin/last | grep ftp`;
my @lastlog = split(/\n/,$str_lastlog);
my %users = ();
foreach(@lastlog)
{  
  my $log_entry = $_;
  my $user = (split(/\s+/,$log_entry))[0];
  my $ip = (split(/\s+/,$log_entry))[2];
  if ($ip eq '127.0.0.1')
  {
    next;
  }
  if ($user eq '')
  {
    next;
  }
  $ip = `geoiplookup $ip`;
  $ip = (split(/\s+/,$ip))[4];
  $users{$user}{$ip}++ ;
}
while (my($user,$ip) = each(%users))
{
  my $count = 0;
  my $addrs = '';
  while (my($addr,$addrcount) = each(%{$ip}))
  {
    $addrs .= $addr . " ";
    $count+=1;
  }
  if ($count >= $critical)
  {
    $retval = 2;
    $status = 'CRITICAL';
    print "User '$user' has logins from $count countries: $addrs";
    last;
  }
  elsif ($count >= $warn)
  {
    $retval = 1;
    $status = 'WARNING';
    print "User '$user' has logins from $count countries: $addrs";    
    last;
  }
  else
  {
    $retval = 0;
    $status = 'OK';
  }  
}

print " - $status\n";
exit($retval);




