Skip to content

Instantly share code, notes, and snippets.

@ChatchaiJ
Created December 8, 2015 06:55
Show Gist options
  • Save ChatchaiJ/c627f0916189720bc7f9 to your computer and use it in GitHub Desktop.
Save ChatchaiJ/c627f0916189720bc7f9 to your computer and use it in GitHub Desktop.
Using iptable to filter ip that try to guess root's and other account's password
#!/usr/bin/perl -w-
# --------------------------------------------------------------------- #
# ban-ip-ssh-attack - using iptable to filter ip that try to #
# guess root's and other account's password. #
# #
# version 0.1 - cj (2005-05-05) initial version. #
# version 0.2 - cj (2005-05-09) working version. #
# version 0.3 - cj (2005-05-31) takasila version. #
# --------------------------------------------------------------------- #
use strict;
my $authfile = "/var/log/auth.log";
my $logfile = "/root/logs/ban-ip-ssh-attack.log";
my $authfilesz = 0;
my %count = ();
my @banList = ();
sub banLog() {
my ($mesg) = @_;
my $logger = "/usr/bin/logger -i -t 'SSH-Attack'";
system("$logger '$mesg'");
}
sub banIt() {
my ($ip) = @_;
my $cmd="/sbin/iptables -I INPUT -s $ip -p tcp --dport ssh -j DROP";
push(@banList,$ip);
&banLog("Detect attack from [$ip], run $cmd\n");
system($cmd);
}
sub processLine() {
my ($line) = @_;
if ( ($line =~ /Failed password for/) or
($line =~ /Illegal user \S+ from/) or
($line =~ /error: PAM: Authentication failure for/) ) {
my ($ip) = ($line =~ /from (\S+)/);
if ($ip =~ /::ffff:/) {
($ip) = ($ip =~ /::ffff:(.+)/);
}
if (!grep(/^$ip$/,@banList)) {
$count{$ip}++;
if ($count{$ip}>3) {
&banIt($ip);
}
}
}
}
sub processFile() {
my ($file) = @_;
open F,"$file" or die "Can't open file '$file' : $!\n";
while (1) {
while (<F>) { &processLine($_); }
my $size = (stat "$file")[7];
do sleep(1) while ($size == (stat "$file")[7]);
last if ((stat "$file")[7] < $size);
}
close F;
}
# main loop
while (1) {
&processFile("$authfile");
system( "/usr/bin/logger -i -t 'SSH-Attack'" .
"'Re-open new \"$authfile\" file!'");
}
# --------------------------------------------------------------------- #
# end of file. #
# --------------------------------------------------------------------- #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment