There are times when you’ll want to limit access and block whole countries. Why? Because there are times when it’s necessary.
Here’s a script that builds a script….
It downloads the IP ranges from www.ipdeny.com, works through a list of two letter country codes to create a bash script that will:
Delete an existing iptables chain.
Creates a new chain “BadCountry”.
Adds this to the top of the INPUT chain to pass anything on port 80 to the BadCountry chain.
Adds all the IP blocks in the relevant countries to the BadCountry chain with a reject/unreachable.
Feel free to adapt it to your needs.
(Oh, and you can also call the script with the parameter undo and it’ll delete the chain.)
#!/bin/bash PARAM=${1} if [ "${PARAM}" == "undo" ] ; then iptables -D INPUT -p tcp -m tcp --dport 80 -j BadCountry iptables --flush BadCountry iptables -X BadCountry else echo $(date) IP Blocking GLOBAL START #First call ourselves to undo (delete the chain) ${0} undo #This is where the executable script that does the table update will live. TABLESCRIPT=/root/scripts/countrytables.sh #Change this to a folder you can write to cd /root/ipblocks #and delete any zone file tar/zip files rm -f all-zones.tar.* echo $(date) Download Countries START wget "http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz" tar -zxvf all-zones.tar.gz > /dev/null echo $(date) Download Countries FINISH echo $(date) Build Countries START echo "#!/bin/bash" > ${TABLESCRIPT} echo "iptables -N BadCountry" >> ${TABLESCRIPT} echo "iptables -I INPUT -p tcp -m tcp --dport 80 -j BadCountry" >> ${TABLESCRIPT} echo "iptables -A BadCountry -j RETURN" >> ${TABLESCRIPT} for COUNTRY in hk cn in id kr my ph tw th vn pk ; do awk {'print "iptables -I BadCountry -s "$1" -j REJECT --reject-with icmp-port-unreachable"'} ${COUNTRY}.zone >> ${TABLESCRIPT} done echo $(date) Build Countries FINISH echo $(date) Updating iptables START #Make our script executable chmod 700 ${TABLESCRIPT} #And now execute it ${TABLESCRIPT} echo $(date) Updating iptables FINISH fi # Elvis Has Left The Server.
Comments are closed, but trackbacks and pingbacks are open.