In one of the servers I am managing I’ve noticed a lot of ftp login attempts recently (server is running ncftp). The pattern of login failures is pretty straightforward hence I’m using tail -f combined with grep to monitor /var/log/messages real-time and add the bad ips to /etc/hosts.deny as soon as attacks are detected. It’s also a good idea to lower the maximum number of failure thread-hold in Ncftpd. This script has been tested on OpenSuSE but it should run with none or little modification on other Linux systems. Here’s the code, don’t forget to change the admin’s email address.
#!/bin/bash
DEBUG=0
LOG=/var/log/messages
ACTION() {
DENY=/etc/hosts.deny
ADMIN=change_to_admin@email.address
while read line; do
grep -q $line $DENY
if [ $? -ne 0 ]; then
if [ $DEBUG == 1 ]; then
echo "will append $line to $DENY"
else
echo "ALL:$line">>$DENY
[ -n "$ADMIN" ] && echo $line | \
mail -s "ftp attacks `hostname -f`:action taken" $ADMIN
fi
fi
done
#change ALL to NcFTPd to block FTP access
}
tail -f $LOG|while read line; do echo $line |grep "Too many login failures from"|\
awk 'BEGIN{FS="[ ;]+"} {print $11}'|ACTION; done &