4){ system("iptables -A INPUT -s $2 [...]" />

Elliott C. Back: Internet & Technology

Blocking Hackers With Perl, Cron, Shell

Posted in Blogging, Code, Security by Elliott Back on September 6th, 2006.

I just wrote a little shell script for this server:

cat /var/log/messages | grep "authentication failure" | sed 's/^.*rhost=//g' | cut -d " " -f 1 | sort | uniq -c | ban-hackers.pl && cp /var/log/messages /var/log/messages.`date '+%s'` && >/var/log/messages

The ban-hackers.pl file looks like this:

#!/usr/bin/perl -w
use strict;

while(<stdin>){
	chomp($_);
	$_ =~ m/^\s*(\d+)\s+([^ ]*)$/i;

	if($1 > 4){
		system("iptables -A INPUT -s $2 -j DROP");
	}
}

1;

When this command gets scheduled to run, say, every hour, what it means is that attackers trying to brute-force the system will be added to the banlist. Or, I could have rewritten the program all in perl to glom up entries from particular addresses discarding only the violators, and remembering the rest in case they try again later.

I’m new to shell scripting and perl, so point out anything horrible with this hack, please!

This entry was posted on Wednesday, September 6th, 2006 at 11:34 pm and is tagged with authentication failure, little shell, shell script, rhost, log messages, banlist, chomp, stdin, violators, brute force, attackers, usr bin, hackers, hack, lt, pl. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback.

4 Responses to “Blocking Hackers With Perl, Cron, Shell”

  1. kevin says:

    Nice script, I am working on the same thing.
    However I run snortsam and after awhile it will delete the iptables chain also, so script kiddies and people on dialup won’t inherit bad ip addresses.
    kevin

  2. Elliott Back says:

    Yep, you’re right. Except, when the server reboots–which is usually every few months or so, the rules *should* drop anyway :D

  3. al:x says:

    If I see it right, this will only add rules. You should from time to time remove them again, most script kiddies do not have static IP addresses and you will lock out valid visitors…

  4. Mark Hutton says:

    Nice work

    DenyHosts is also good for preventing automated SSH dictionary attacks

Leave a Reply

Powered by WP Hashcash