IPdeny provides IP address lists organized by country code. For example, you can download cn.zone:
Once you have all the IP addresses for a specific country, blocking them is straightforward. You can write a script to read the cn.zone file line by line and add each IP to iptables:
# Block traffic from a specific country
# written by yunwei123.com
COUNTRY=”cn”
IPTABLES=/sbin/iptables
EGREP=/bin/egrep
if [ “$(id -u)” != “0” ]; then
echo “you must be root” 1>&2
exit 1
fi
resetrules() {
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F
$IPTABLES -X
}
resetrules
for c in $COUNTRY
do
country_file=$c.zone
IPS=$($EGREP -v “^#|^$” $country_file)
for ip in $IPS
do
echo “blocking $ip”
$IPTABLES -A INPUT -s $ip -j DROP
done
done
exit 0
The above script can be extended to defend against DDoS attacks!