SWAMPTHING.DK

Ban clients attacking FTP

By Torben Schou Jensen - Last update 2008.06.15 00.00

One evening I created the following perl script to take care of attacks.
Currently started by cron every 3 minutes.

ban_ftp_users.pl to be created in /root/bin
#!/usr/bin/perl
#
# Debian: script depends on libtimedate-perl
# Scheduled by cron
#
# Maintenance:
# 2007.04.20 Changes due to Debian 4.0
#   - tail command changed
#   - each reject now 3 times in log so nr changed from 30 to 90
# 2007.12.03 Changes...
#   Mon Dec  3 19:28:56 2007 [pid 27554] [raquel] FAIL LOGIN: Client "212.187.162.226"
#   "uniq -c -f 7" => "uniq -c -f 8"
#
	use Date::Format;
	use Sys::Syslog;
	
	# Intruder log file in /var/log to write in if we have future attacks
	$intruderlog="ban_intruder_alert";

	$backup=0;
#	$tmp=`tail -n 500 /var/log/vsftpd.log|uniq -c -f 5`;
	$tmp=`tail -n 500 /var/log/vsftpd.log|grep "FAIL LOGIN"|sort -k12|uniq -c -f 8`;
	@tmpline = split(/\n/,$tmp);
	foreach $tmp (@tmpline) {
		$_=$tmp;
		if (/.(\d+)/) {
			$nr=$1;
		if (/"(.+)"/) {
			$client=$1;
		if (/\[pid.(\d+)\]/) {
			$pid=$1;
#		if ($nr>30) {
		if ($nr>90) {
		if (/FAIL LOGIN/) {
			&action;
		}
		}
		}
		}
		}
	}
	exit;

sub action {
	$deny="/etc/hosts.deny";
	$chk=`grep " $client " $deny|wc -l`;
	if ($chk==0) {
		print time2str("%Y%m%d.%H%M%S",time)." - FTP attack - $client - $nr \"FAIL LOGIN\" detected on pid $pid now we kill it\n";
		$line=$_;
		$line =~ s/^\s+//;
		# Check pid and kill it if it is running vsftpd
		$_=`ps ax|grep $pid|grep -v grep`;
		if (/vsftpd/) {
			$_=`kill $pid`;
		}
		&actionbackup;
		open (F,">>/etc/hosts.deny") || die "Can't open /etc/hosts.deny: $!\n";
		print F "ALL: $client : spawn /bin/echo `/bin/date` - ban ftp - %c - %d >> /var/log/$intruderlog\n";
		close (F);
		syslog("auth|info","$0: $client banned");
	}
}

sub actionbackup {
	if ($backup<1) {
		$backupcmd="/etc/!backup/hosts.deny.".time2str("%Y%m%d.%H%M%S",time);
		$backupcmd=`cp /etc/hosts.deny $backupcmd`;
		$backup=1;
	}
}
(remember to set execute attribute)
(remember to create backup directory "mkdir /etc/\!backup")

A few facts:

Action in case of attack:

Using hosts.deny:

Current ban_intruder_alert:

Current ban_users.log:

Valid HTML 4.01 Transitional