Allow only Cloudflare CDN servers to your web servers

We love to use Cloudflare CDN because it improves latency and uptime, and the price is just right (free) for the starter pack.

Normally, a web server’s ports 80 and 443 would be opened to the public internet, with access restricted by selected IP ranges by either ASN or country, depending on what the administrator has configured. But if you are using Cloudflare’s CDN service, you can permit TCP 80/443 access only to their servers, and block all other incoming requests. You can then fine-tune access control using Cloudflare’s web application firewall. It would greatly reduce your web server’s attack surface.

Cloudflare has published its current definitive IP range in this document, which we can use to write our firewall rules. Simply add the following rules in UFW:

ufw limit ssh/tcp
ufw allow proto tcp from 173.245.48.0/20 to any port 80,443
ufw allow proto tcp from 173.245.48.0/20 to any port 80,443
ufw allow proto tcp from 103.21.244.0/22 to any port 80,443
ufw allow proto tcp from 103.22.200.0/22 to any port 80,443
ufw allow proto tcp from 103.31.4.0/22 to any port 80,443
ufw allow proto tcp from 141.101.64.0/18 to any port 80,443
ufw allow proto tcp from 108.162.192.0/18 to any port 80,443
ufw allow proto tcp from 190.93.240.0/20 to any port 80,443
ufw allow proto tcp from 188.114.96.0/20 to any port 80,443
ufw allow proto tcp from 197.234.240.0/22 to any port 80,443
ufw allow proto tcp from 198.41.128.0/17 to any port 80,443
ufw allow proto tcp from 162.158.0.0/15 to any port 80,443
ufw allow proto tcp from 104.16.0.0/12 to any port 80,443
ufw allow proto tcp from 172.64.0.0/13 to any port 80,443
ufw allow proto tcp from 131.0.72.0/22 to any port 80,443
ufw allow proto tcp from 2400:cb00::/32 to any port 80,443
ufw allow proto tcp from 2606:4700::/32 to any port 80,443
ufw allow proto tcp from 2803:f800::/32 to any port 80,443
ufw allow proto tcp from 2405:b500::/32 to any port 80,443
ufw allow proto tcp from 2405:8100::/32 to any port 80,443
ufw allow proto tcp from 2a06:98c0::/29 to any port 80,443
ufw allow proto tcp from 2c0f:f248::/32 to any port 80,443

and viola!

Remember to permit SSH access before enabling UFW, otherwise, you will be locked out of your instance!


Comments

Leave a Reply