Friday, March 29, 2019

Block countries in CentOS 7.6 with ipset blacklist and firewalld using ipdeny.com

I'm very new to firewalld in CentOS 7 but it does support ipset out of the box.  You use it differently than previous versions of CentOS with iptables though.
You can use the following site to get your country IP blocks: http://www.ipdeny.com/ipblocks/data/aggregated/  http://www.ipdeny.com/ipblocks/
You might check this out too for CentOS 6:  https://curtcorwin.blogspot.com/2019/03/block-countries-in-centos-6-with-ipset.html

1.  Build your ipset and make it permanent:
firewall-cmd --permanent --new-ipset=blacklist --type=hash:net

2.  Use the ipdeny.com site to get your country IP blocks.  The script below will automate this but will take a very long time to populate since there are quite a few blocks to import.
cd /root
nano RunIPSet

---------------copy---------------
#!/bin/bash
for IP in $(wget -O - http://www.ipdeny.com/ipblocks/data/aggregated/{cn-aggregated,ru-aggregated,kr-aggregated,pk-aggregated,tw-aggregated,sg-aggregated,hn-aggregated,hk-aggregated,ir-aggregated,ua-aggregated,vn-aggregated,it-aggregated,de-aggregated,my-aggregated,nl-aggregated,ng-aggregated,pk-aggregated}.zone)
do
firewall-cmd --permanent --ipset=blacklist --add-entry=$IP
done
---------------save---------------
Make it executable: chmod u+x RunIPSet
Run it:  ./RunIPSet

This could take a long time depending on how many countries you chose.  First you'll the files wget downloads and then you see "success" over and over for every block it imports into the ipset.

**EDIT***The above script took way too long*****Over 2 hours to complete*****
It's WAY faster to just download each country file locally and use the following command to import each of them into the ipset:
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./cn.zone
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./de.zone
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./hk.zone
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./hn.zone
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./ie.zone
firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./il.zone
etc...

3.  Redirect the blacklist to the drop zone and reload:
firewall-cmd --permanent --zone=drop --add-source=ipset:blacklist
firewall-cmd --reload



More useful Commands:
Add ipset entry:  firewall-cmd --permanent --ipset=blacklist --add-entry=10.10.10/24
List ipset: firewall-cmd --permanent --get-ipsets
List entries in blacklist ipset: firewall-cmd --permanent --ipset=blacklist --get-entries
Remove firewalld entry: firewall-cmd --permanent --zone=drop --remove-source=ipset:blacklist
Delete ipset: firewall-cmd --permanent --delete-ipset=blacklist




No comments: