I run an FTP server on my machine, using Pure-FTPd. Lately, I was getting a lot of noise in my logs about unknown people trying to gain access on my FTP server. I wanted to automate the task of looking through the log and banning the bad IPs, so that my logs will be kept clean from all those try/fails attempts.
What I came up with is a bash script executed as a launchd user daemon whenever the file /var/log/ftp.log is being modified. Parts of the code come from , and irc2samus on the #bash channel (IRC on freenode.net) made the rest.
I thought this might help others, too, so here's the code.
I put the following in /etc/autoban/ftp_ban.sh:
#!/bin/bash
# this script scans /var/log/ftp.log file for IPs that
# repeatedly try to connect the server without proper credentials
# and ban them after their 3rd fail, so we can have clean logs
#
export secure_log=/var/log/ftp.log
export log=/var/log/ftp_ban.log
function ban_host {
rule_numbers=$(ipfw show | awk '{print $1}')
lowest_rule=1
lowest_rulet=$(printf %5.5i $lowest_rule);
while [[ "$rule_numbers" =~ "${lowest_rulet}" ]]; do
lowest_rule=$(( $lowest_rule + 1 ));
lowest_rulet=$(printf %5.5i $lowest_rule);
done
# the actual banning happens here
ipfw -q add $lowest_rule deny ip from $1 to any
echo "$(date +'%D %T') : Banned $1">>"$log"
}
export -f ban_host
fgrep 'Authentication failed for user' "$secure_log" | while read line; do
line=${line#*(\?@}; line=${line%)*}; echo $line;
done | sort | uniq -c | while read count suspected_host; do
if ((count>3)); then
ipfw show | fgrep "$suspected_host" | fgrep -q deny || ban_host "$suspected_host"
fi
doneMac OS X Hints
http://hints.macworld.com/article.php?story=20091030220955444