To block IP by country, we need IP blocks for particular country. This step needs IP blocks from
http://ipdeny.com/.
We need to convert IP blocks into ipset format, this bash script will do:
- Download block ip by country from http://www.ipdeny.com
- Convert block ip into ipset format
For IPV4:
http://www.ipdeny.com/ipblocks/data/countries/ For IPV6:
http://www.ipdeny.com/ipv6/ipaddresses/blocks/
Here is bash script blockcountryip.sh or download from
https://garasiku.web.id/ipset/blockcountryip.sh.txt:
#!/bin/bash
# 2017-05-23
if [ "$1" != "" ]; then
echo $1
# download ipv4 block
echo "Download ipv4 $1"
wget http://www.ipdeny.com/ipblocks/data/countries/$1.zone -O zone.ipv4.$1
# download ipv6 block
echo "Download ipv6 $1"
wget http://www.ipdeny.com/ipv6/ipaddresses/blocks/$1.zone -O zone.ipv6.$1
mfile1="./zone.ipv4.$1"
ofile1="./ipv4.ipset.$1"
touch $ofile1
echo "creating ipset rules $ofile1 for ipv4"
echo "create ipv4_$1 hash:net" > $ofile1
while read line; do
echo "add ipv4_$1 $line" >> $ofile1
done <"$mfile1"
echo "Done creating $ofile1"
mfile2="./zone.ipv6.$1"
ofile2="./ipv6.ipset.$1"
echo "creating ipset rules $ofile2 for ipv6"
echo "create ipv6_$1 hash:net" > $ofile2
while read line; do
echo "add ipv6_$1 $line" >> $ofile2
done <"$mfile2"
echo "Done creating $ofile2"
else
echo "Usage .//blockcountryip.sh countrycode2"
fi
To use this bash script:
# ./blockcountryip.sh [countrycode]
for example to generate IP blocks for China CN
# ./blockcountryip.sh cn
Note: you can download IP block for China from this
http://garasiku.web.id/ipset/ipv4.ipset.cn with some additional IP block.
To load it in memory
# ipset restore -! < ipv4.ipset.[countrycode]
[countrycode] is 2 character country code
https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
To apply in iptables
# iptables -A INPUT -p tcp -m multiport --dports [any port you wish] -m set --match-set ipv4_[countrycode] src -j DROP
For example to block all IPV4 from China for port 21, 22, 80, 443 and 2222
# iptables -A INPUT -p tcp -m multiport --dports 21,22,80,443,2222 -m set --match-set ipv4_cn src -j DROP
# iptables -A INPUT -p udp -m multiport --dports 22,2222 -m set --match-set ipv4_cn src -j DROP
Who will care if I block all of their connection:
# iptables -A INPUT -m set --match-set ipv4_cn src -j DROP
To make it persistent, follow your distribution guide how to load
ipset and iptables rules every time system start/restart or network
start/restart.
Not Working IPV6
Note:
- Tunneling SSH may used UDP protocol
- Proftpd listen on port 2222
- Port 25 uses to communicate with/to other mail server
My github.com:
https://github.com/dedetok/bash-block-ip-by-country
References: