[Nelug] Blocking brute-force ssh attacks

Martin Ward martin at gkc.org.uk
Wed Aug 9 14:11:04 UTC 2006


Getting fed up with the various idiots who think that they can guess my ssh
attacks with a brute force dictionary attack, I decided to do something
about them.

I previously experimented with "port knocking" (see www.portknocking.org)
which worked, but is a bit tricky to use since many public internet access
points have a very limited set of ports open.

So instead, I wrote a small daemon which scans the log file and builds
a list of IP addresses which have cause too many failed login attempts:

#!/usr/local/bin/perl
# Monitor /var/log/messages for suspicious activity and create blocks file
#

use strict;
use warnings;

my $blocks = "/etc/rc.d/blocks";
my $max = 10; # Max number of failed password attempts allowed from any ip

while(1) {
  my %bad = ();
  open(LOG, "/var/log/messages");
  while (<LOG>) {
    $bad{$1}++
      if /sshd.*Failed password for.*::ffff:(\d+\.\d+\.\d+\.\d+) port/;
  }
  my $new = join("", map { "$_\n" }
                     grep { $bad{$_} > $max }
                     sort keys %bad);
  my $orig = "";
  open(BLOCKS, "$blocks");
  $orig .= join("", <BLOCKS>);
  close(BLOCKS);
  if ($orig ne $new) {
    open(BLOCKS, ">$blocks.new");
    print BLOCKS $new;
    close(BLOCKS);
    rename($blocks, "$blocks.old");
    rename("$blocks.new", $blocks);
    system "/etc/rc.d/masq";
  }
  sleep(300);
}


The file /etc/rc.d/masq is run in /etc/rc.d/rc.local and sets up IP
masquerading and port forwarding. It includes these lines:


for i in `cat /etc/rc.d/blocks`
do
iptables -A INPUT -p all --src $i -j DROP
done

# Allow ssh in unless blocked above:
iptables -A INPUT -p tcp --dport ssh -j ACCEPT



-- 
			Martin

martin at gkc.org.uk http://www.cse.dmu.ac.uk/~mward/ Erdos number: 4
G.K.Chesterton web site: http://www.cse.dmu.ac.uk/~mward/gkc/




More information about the Nelug mailing list