System administrators are always running across unauthorized access requests and reasons to ban/block IP addresses – on webservers, daemons, etc. I’ve long used some homemade scripts to facilitate this and figured I would include them here.
Here’s the ‘ban’ script, which just takes an IP address to ban via ipf (e.g. “ban 1.2.3.4”):
#!/bin/bash
CIDR=32
CONF=ipf.conf
IP=`echo $1 | /bin/tr -d '[:alpha:]\:[:space:]'`
ESC_IP=`echo $IP | /bin/sed 's/\./\\\./g'`
EXISTS=`/bin/grep "$ESC_IP" /etc/ipf/$CONF`
if [ -n "$EXISTS" ]; then
echo "$IP is already blocked"
exit
fi
REGEX="\.0$"
if [[ $IP =~ $REGEX ]]; then
CIDR=24
fi
CMD="block in quick from $IP/$CIDR to any"
echo $CMD | /usr/sbin/ipf -f -
/bin/echo $CMD >>/etc/ipf/$CONF
And here’s an unban script which reverses the ban:
#!/bin/bash
CIDR=32
CONF=ipf.conf
IP=`echo $1 | /bin/tr -d '[:alpha:]\:[:space:]'`
ESC_IP=`echo $IP | /bin/sed 's/\./\\\./g'`
EXISTS=`/bin/grep "$ESC_IP" /etc/ipf/ipf.conf`
if [ -z "$EXISTS" ]; then
echo "$IP is not blocked"
exit
fi
REGEX="\.0$"
if [[ $IP =~ $REGEX ]]; then
CIDR=24
fi
CMD="block in quick from $IP/$CIDR to any"
echo $CMD | /usr/sbin/ipf -r -f -
/bin/echo $CMD >>/etc/ipf/unban_log
perl -pi -e "s/block in quick from $ESC_IP\/$CIDR to any\n//" /etc/ipf/ipf.conf
These files (and the init.d startup script) are at https://github.com/heybige/ipf-ban-unban