Skip to content

Instantly share code, notes, and snippets.

Created March 31, 2011 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/896249 to your computer and use it in GitHub Desktop.
Save anonymous/896249 to your computer and use it in GitHub Desktop.
Blocks hack attempts against asterisk
#!/usr/bin/perl -w
use strict;
use warnings;
my (@failhost);
my %currblocked;
my %addblocked;
my $action;
open (MYINPUTFILE, "/var/log/asterisk/messages") or die "\n", $!, "Does log file file exist\?\n\n";
while (<MYINPUTFILE>) {
my ($line) = $_;
chomp($line);
if ($line =~ m/\' failed for \'(.*?)\' - No matching peer found/) {
push(@failhost,$1);
}
if ($line =~ m/\' failed for \'(.*?)\' – Wrong password/) {
push(@failhost,$1);
}
}
my $blockedhosts = `iptables -n -L asterisk`;
while ($blockedhosts =~ /(.*)/g) {
my ($line2) = $1;
chomp($line2);
if ($line2 =~ m/(\d+\.\d+\.\d+\.\d+)(\s+)/) {
$currblocked{ $1 } = 'blocked';
}
}
if (@failhost) {
&count_unique(@failhost);
while (my ($ip, $count) = each(%addblocked)) {
if (exists $currblocked{ $ip }) {
print "$ip already blocked\n";
} else {
if ($count >= 10) {
$action = `iptables -I asterisk -s $ip -j DROP`;
print "$ip blocked. Failed attempts: $count\n";
} else {
print "$ip NOT blocked. Only $count failed attempt(s).\n";
}
}
}
} else {
print "no failed registrations.\n";
}
sub count_unique {
my @array = @_;
my %count;
map { $count{$_}++ } @array;
map {($addblocked{ $_ } = ${count{$_}})} sort keys(%count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment