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: https://www.cloudflare.com/ips/ – as from this post the current IP ranges for both IPv4 and IPv6 are:

# File generated 05/03/2017
103.21.244.0/22
103.22.200.0/22
103.31.4.0/22
104.16.0.0/12
108.162.192.0/18
131.0.72.0/22
141.101.64.0/18
162.158.0.0/15
172.64.0.0/13
173.245.48.0/20
188.114.96.0/20
190.93.240.0/20
197.234.240.0/22
198.41.128.0/17
199.27.128.0/21
2400:cb00::/32
2405:8100::/32
2405:b500::/32
2606:4700::/32
2803:f800::/32
2c0f:f248::/32
2a06:98c0::/29

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 *