Created
April 4, 2013 21:43
-
-
Save fclairamb/5314636 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Quick IP banning script | |
# This is a very simple and effective way to ban IP address from any kind of webapp. | |
# | |
# * To ban an IP for two minutes | |
# echo "120" >/tmp/iptables-banip/1.2.3.4 && /usr/local/bin/banip | |
# | |
# * To bypass the ban timeout and unban an IP sooner | |
# echo "0" >/tmp/iptables-unbanip/1.2.3.4 && /usr/local/bin/banip | |
# | |
# * To ban an IP for a PHP script | |
# <?PHP file_put_contents('/tmp/iptables-banip/1.2.3.4', '120'); ?> | |
# | |
# * To ban an IP from a Java (7) program | |
# try ( Writer w = new FileWriter("/tmp/iptables-banip/1.2.3.4") ) { w.write("120"); } | |
# | |
# You get the idea... | |
# | |
# These are the banning and unbanning directories | |
BANDIR=/tmp/iptables-banip | |
UNBANDIR=/tmp/iptables-unbanip | |
# We check that the dirs do exist | |
if [ ! -d ${BANDIR} ]; then | |
mkdir -p ${BANDIR} | |
chmod a+rwx ${BANDIR} | |
fi | |
if [ ! -d ${UNBANDIR} ]; then | |
mkdir -p ${UNBANDIR} | |
chmod a+rwx ${UNBANDIR} | |
fi | |
# function: ban( $ip ) | |
ban() { | |
ip=$1 | |
# If the file exists in the unban dir | |
if [ -f ${UNBANDIR}/$ip ]; then | |
# We remove it and do nothing | |
echo "IP $ip is already banned !" | |
rm ${BANDIR}/$ip | |
else | |
# Else | |
# We ban the IP | |
echo "Banning IP: $ip" | |
/sbin/iptables -I ufw-user-input 1 -s "$ip" -j DROP | |
mv -f ${BANDIR}/$ip ${UNBANDIR}/$ip | |
echo "Banned IP are:" | |
/sbin/iptables -n -L ufw-user-input|grep DROP | |
fi | |
} | |
# function: unban( $ip ) | |
unban() { | |
ip=$1 | |
file=${UNBANDIR}/$ip | |
# We calculate the age of the file | |
age=$(($(date +%s) - $(stat -c '%Y' "$file"))) | |
# And get the TTL from the file's contents | |
duration=$(head -n 1 $file) | |
# If the age of the file is greater than its TTL | |
test $age -gt $duration && { | |
# We delete the DROP rule for this IP | |
echo "Unbanning IP: $ip" | |
/sbin/iptables -D ufw-user-input -s "$ip" -j DROP | |
# And delete the file | |
rm $file | |
# Then we display all the banned IPs | |
echo "Banned IP are:" | |
/sbin/iptables -n -L ufw-user-input|grep DROP | |
} | |
} | |
# We execute the ban function for each file in the BANDIR dir | |
for ip in `ls ${BANDIR}` | |
do | |
ban $ip | |
done | |
# We execute the unban function for each file in the UNBANDIR dir | |
for ip in `ls ${UNBANDIR}` | |
do | |
unban $ip | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment