Note: The blogger previously posted a tutorial on blocking specific country IPs on VPS, which is useful for preventing access to websites from certain countries and for preventing CC attacks. However, considering that many people need a whitelist setup method, the blogger has done some research and found that it can also be done using ipset
. Here, we will explain how to do it. It has been tested and works fine.
Method#
First, you need to obtain the IP ranges for the countries. Download link: http://www.ipdeny.com/ipblocks/. Here, we will use our country as an example.
1. Install ipset
# Debian/Ubuntu system
apt-get -y install ipset
# CentOS system
yum -y install ipset
For CentOS 7
, you also need to disable the firewall
:
systemctl stop firewalld.service
systemctl disable firewalld.service
2. Clear previous rules
# To ensure that the settings take effect, it is recommended to clear the previous firewall rules
iptables -P INPUT ACCEPT
iptables -F
3. Create new rules
# Create a rule named cnip
ipset -N cnip hash:net
# Download the IP ranges for the country, here we use China as an example
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
# Add the IP ranges to the cnip rule
for i in $(cat /root/cn.zone ); do ipset -A cnip $i; done
4. Set IP range whitelist
# Allow IP ranges
iptables -A INPUT -p tcp -m set --match-set cnip src -j ACCEPT
# Close all ports
iptables -P INPUT DROP
Now, only the specified country's IP addresses can access the server.
If you are in China and do not want the website to be accessible to people in China, it is recommended not to close all ports. Otherwise, you will not be able to access your SSH. Instead, you can only close ports 80
/443
.
# Close specified ports, such as 80/443
iptables -A INPUT -p tcp --dport 80 -j DROP
iptables -A INPUT -p tcp --dport 443 -j DROP
Now, IP addresses from other countries will not be able to access your server's 80
/443
ports, which means they will not be able to access your website. Other ports can still be accessed.
5. Delete rules
# To delete a rule, change -A to -D, for example
iptables -D INPUT -p tcp -m set --match-set cnip src -j ACCEPT
iptables -D INPUT -p tcp --dport 443 -j DROP
Explanation#
After setting up the firewall, some servers may clear the firewall rules after restarting the system, causing the settings to be ineffective. Therefore, after setting up the rules, we need to use the iptables
command to save them. The save command may not be universal across many systems, so we won't go into it here. You can search for a solution yourself, or if you have the patience, you can reset the firewall every time you restart the system.