banner
moeyy

moeyy

一条有远大理想的咸鱼。
github
mastodon
email

Use ipset to set up a firewall port whitelist and only allow access from specified countries.

Note: The blogger previously posted a tutorial on blocking specific country IPs with a one-click setup for VPS. This is very useful for blocking access to websites from a specific country and 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's how it works, and it has been tested without any issues.

Method#

First, you need to obtain the IP ranges for the desired countries. Download link: http://www.ipdeny.com/ipblocks/. Here, we will use our own country as an example.

1. Install ipset

# For Debian/Ubuntu systems
apt-get -y install ipset

# For CentOS systems
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 the website is not allowed to be accessed by people in China, it is recommended not to close all ports. This way, your SSH will not be accessible. Instead, you can only close ports 80 and 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 cannot access your website. However, other ports can still be accessed.

5. Delete rules

# Change -A to -D in the parameters to delete the rule, 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, you need to use the iptables command to save them. The save command may not be universal across many systems, so it is not discussed here. You will need to search for a solution yourself. If you have the patience, you can also reset the firewall settings every time you restart.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.