One effective way to protect your server from threats is by restricting access to only trusted entities. For example, if you are using a proxy service like Cloudflare, you can configure your server’s firewall to only accept requests from Cloudflare IPs for HTTP (port 80) and HTTPS (port 443) services. This article will discuss practical steps to achieve this using firewalld.

Why Choose This Configuration?

Cloudflare acts as a proxy between users and your server. By limiting access to only Cloudflare IPs, direct requests from other sources (that do not go through Cloudflare) will be rejected by the firewall, thus preventing potential attacks such as DDoS.

Configuration Steps

To simplify management, we will create a dedicated zone named cloudflare in firewalld. This zone will be used to group all rules related to Cloudflare IPs.

sudo firewall-cmd --new-zone=cloudflare --permanent
sudo firewall-cmd --reload

Next, add all Cloudflare IPs (both IPv4 and IPv6) to the cloudflare zone. Use the following commands:

for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
    sudo firewall-cmd --zone=cloudflare --add-source=$ip --permanent
done

for ip in $(curl -s https://www.cloudflare.com/ips-v6); do
    sudo firewall-cmd --zone=cloudflare --add-source=$ip --permanent
done

The above commands will automatically add all Cloudflare IPs to the cloudflare zone.

After adding the Cloudflare IPs, allow HTTP (80) and HTTPS (443) ports in the cloudflare zone:

sudo firewall-cmd --zone=cloudflare --add-service=http --permanent
sudo firewall-cmd --zone=cloudflare --add-service=https --permanent

To ensure that only Cloudflare IPs can access HTTP and HTTPS services, block access from the default zone (public):

sudo firewall-cmd --zone=public --remove-service=http --permanent
sudo firewall-cmd --zone=public --remove-service=https --permanent

After completing all configurations, reload firewalld to apply the changes:

sudo firewall-cmd --reload

To verify that the configuration has been applied correctly, run the following command:

Check the cloudflare zone:

sudo firewall-cmd --zone=cloudflare --list-all

The output should show that only Cloudflare IPs are allowed, and the HTTP/HTTPS services are enabled.

Check the public zone:

sudo firewall-cmd --zone=public --list-all