#!/usr/bin/perl -w # ------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42 - bzerk) # wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you can buy me a beer in # return. Ruben de Groot, 2006 # ------------------------------------------------------------------- # This script will monitor the /var/log/auth.log file for login # atempts through sshd. Too many failed logins will be punished # by giving the offending ip address static route to localhost; # basically making them incommunicado :) use strict; use Sys::Syslog qw(:standard); my $logfile = "/var/log/auth.log"; my $OS = `uname -s`; my %offenders; if ($#ARGV == 0) { $logfile = $ARGV[0]; } if (! -r $logfile) { printf("Can't read %s\n",$logfile); exit(1); } my $inode = (stat($logfile))[1]; open(LFILE,$logfile); # SEEK_END seek(LFILE, 0, 2); for (;;) { sleep 6; # check if logfile hasn't turned over below our feet if ($inode != (stat($logfile))[1]) { close(LFILE); $inode = (stat($logfile))[1]; open(LFILE,$logfile); } else { # SEEK_CUR seek(LFILE, 0, 1); } while (my $logline = ) { my ($ip,$deny) = 0; if ($logline =~ 'Invalid user') { $ip = (split(/ /,$logline))[9]; $deny = 2; } elsif ($logline =~ 'Failed password for') { $ip = (split(/ /,$logline))[10]; $deny = 1; } elsif ($logline =~ 'Accepted') { $ip = (split(/ /,$logline))[11]; $deny = 0; } if ($ip =~ /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/) { if (! defined ($offenders{$ip})) {# first time this ip address if ($deny) { $offenders{$ip} = 1; } else { $offenders{$ip} = 0; } # whitelist the good guys } elsif ($offenders{$ip} && $deny) { $offenders{$ip} +=1; } else { $offenders{$ip} = 0; } # good guy had some memory troubles, # but got it right at last if ($offenders{$ip} == 3) { # too many tries, you're busted! if ("$OS" =~ "BSD") { system("/sbin/route","add","-host",$ip,"127.0.0.1"); } elsif ("$OS" =~ "Linux") { system("/sbin/route","add","-host",$ip,"gw","127.0.0.1"); } openlog($0,'','security'); syslog('warning',"null-routing offending IP address: %s\n",$ip); closelog(); } } } }