Only allow access to the web server via CloudFlare (iptables)

  • Tutorial

Cloudflare is a great thing to protect sites from various computer rogues - hackers. However, if they still find out somehow the original IP of the web server on which the site is located, they will at least try to attack it by IP, bypassing the proxy. You can fence redirects, send NGINX-ohm resets with code 444 when trying to access non-existing domains, but the most iron way out of this situation is to open http / https traffic to the server only for the IP addresses of our security proxy.

By the way, this method can also make partly useless all sorts of sites like crimeflare.org . Well, the "detective" found out that the domain was once available at such an IP - it would be useless to check if it was there by attempting to go direct to IP: 443 or IP: 80.
And if you close all the ports on the server at all, disable ICMP and implement access only via IPMI / VNC, no one will know that something exists on our IP.

We do this in iptables.

CloudFlare has a huge number of addresses, but they all shrink to a small number of subnets. Anticipating such a request, the guys published an articlethat tells you where to find their current subnets and even what to write in iptables. One problem is that it is supposed to be done manually, which is rather inconvenient and unreliable: addressing in CloudFlare may change over time, and someday it may turn out that the proxy, located on new addresses, will not be allowed on your server. Accordingly, customers whose sessions will pass through these new addresses will not be able to access your site.

Fortunately, the problem is automated. So:

1. Forbid in iptables all HTTP / HTTPS traffic:

iptables -I INPUT 1 -p tcp -m multiport --dports http,https -j DROP

2. Put somewhere, for example, on /root/cloudflare-update.sh script cloudflare-update.sh with the following contents:

#!/bin/bashwhileread ip ; do iptables -D INPUT -p tcp -m multiport --dports http,https -s "$ip" -j ACCEPT ; done <<< "$(curl https://www.cloudflare.com/ips-v4)"whileread ip ; do iptables -I INPUT -p tcp -m multiport --dports http,https -s "$ip" -j ACCEPT ; done <<< "$(curl https://www.cloudflare.com/ips-v4)"
iptables-save > /etc/iptables/rules.v4

That is, we delete all existing entries added earlier, re-add everything that is in the CloudFlare address list. Thus, we avoid duplicate rules. By the end - save.

3. Making the script executable:

chmod +x /root/cloudflare-update.sh

4. In cron (for example, at the end of the / etc / crontab file) we add the task to update the addresses every 12 hours:

0 */12 * * * root /root/cloudflare-update.sh &> /dev/null

Everything! Now you can get on your server through 80 and 443 ports only through a proxy, because at any time, only the addresses belonging to the proxy are allowed on the server.

Also popular now: