Skip to content

Instantly share code, notes, and snippets.

@antonlindstrom
Created May 22, 2009 12:53
Show Gist options
  • Save antonlindstrom/116107 to your computer and use it in GitHub Desktop.
Save antonlindstrom/116107 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
#
# Checks auth.log for breakin attempts
#
# Author Anton Lindstrom
# antonlindstrom.com
use warnings;
use strict;
my $logfile = "/var/log/auth.log";
my $csvfile = "users.csv";
# Argument for block
my $argument = 0;
$argument = $ARGV[0] if ($ARGV[0]);
# Open $logfile
open(AUTH, $logfile) or die("File $logfile unreadable! \n$!");
my @auth = <AUTH>;
close(AUTH);
# Hashes with IPs and usernames
my %ips;
my %users;
# Go through rows in @auth
foreach (@auth) {
next if ($_ !~ /sshd/);
print "";
my $failedpassusers = "failed password for";
my $failedpassinvalid = "failed password for invalid user";
# time, server, process[id], trash, trash, trash, username, ip.
$_ =~ m/(\w+\s\d+\s\d+:\d+:\d+)\s([\w\-\.]+)\s(.+)\:\s((($failedpassusers|$failedpassinvalid) ([\w\-\_]+) from ([\d\.]+)?))/gi;
if ($1 && $8) {
# Set username and ip in hashes.
if ( exists($ips{$8}) ) { $ips{$8} += 1; }
else { $ips{$8} = 1; }
if ( exists($users{$7}) ) { $users{$7} += 1; }
else { $users{$7} = 1; }
}
}
my $cmd;
my $block = 0;
my @iptables_notblock = `iptables -L INPUT -n`;
print "IPs:\n";
foreach my $ip ( sort { $ips{$b} <=> $ips{$a} } keys %ips ) {
$block = 1 unless ( grep(/$ip/, @iptables_notblock) );
$cmd = "iptables -I INPUT -s $ip -p tcp --destination-port ssh -j DROP";
print " $ips{$ip}\tfailed login attempts from $ip\n";
system($cmd) if ($ips{$ip} > 5 && $argument eq "-b" && $block == 1);
}
print "\nBlocked:\n";
# Print iptables
my @iptables = `iptables -L INPUT -n 2>/dev/null`;
foreach (@iptables) {
$_ =~ m/([1-2]?(([0-9]{1,2})?\.\d+\.\d+\.\d+))/g;
print "\t[BLOCKED!] $1\n" if($1);
}
# Print users to csv.
open (CSV, "> $csvfile") or die ("File $csvfile unreadable! \n$!");
# Print
print "\nFrequent failed users are in $csvfile..\n";
foreach my $user ( sort { $users{$b} <=> $users{$a} } keys %users ) {
print CSV "$users{$user},$user\n";
}
# Close
close(CSV);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment