Cloudflare + Site Security

I am a big believer in Cloudflare for site security however many people out there activate Cloudflare for server security without thinking about their own infrastructure still leaving them open to attack so here is a simple, but effective guide on how to to secure things just a little more if you’re using Cloudflare.

For starters, all my guides are written with Debian GNU linux in mind. We’re also using UFW as the firewall. It doesn’t matter what web server you’re using.

So, Cloudflare publish all their IP ranges on their support page here: – as from this post the current IP ranges for both IPv4 and IPv6 are:

# File generated 05/03/2017

Right, since we know this we’re going to activate UFW and only allow traffic through Cloudflare. I’m going to assume you know how to pass traffic through Cloudflare + know how to manage DNS records. Also, ensure you have another way to access your server (either physically or another shell) just in case you somehow lock yourself out. I’d also recommend using Mosh for accessing your server.

First, lets set up a basic firewall – lets say your server is listening on HTTP (80) and HTTPS (443) as well as SSH (22) and MOSH.

sudo apt-get install ufw
sudo ufw allow ssh
sudo ufw allow mosh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

Now you have a basic firewall going – you can check it by running sudo ufw status numbered in your terminal. You should see both IPv4 and IPv6 (if enabled) rules spit out. If you’ve got Cloudflare running on your site you can continue – ensure traffic is going via Cloudflare else the following will take your site offline.

First – Create a new file in ~/cloudflare.txt with both the IPv4 and IPv6 addresses of the Cloudflare IP address ranges. Once you’re done lets get these into UFW:

while read line; do sudo ufw allow from $line to any port 80; done < ~/cloudflare.txt
while read line; do sudo ufw allow from $line to any port 443; done < ~/cloudflare.txt
sudo ufw delete allow 80/tcp
sudo ufw delete allow 443/tcp

Congrats, after this HTTP and HTTPS traffic will only be allowed via Cloudflare and direct traffic will be blocked. Your site will be filtered via Cloudflare going forward protecting you just that little bit further and making it just that little bit harder for people to find your backend server(s). Simple huh? Get securing!

Leave a Reply

Your email address will not be published. Required fields are marked *