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.
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 22.214.171.124/22 126.96.36.199/22 188.8.131.52/22 184.108.40.206/12 220.127.116.11/18 18.104.22.168/22 22.214.171.124/18 126.96.36.199/15 188.8.131.52/13 184.108.40.206/20 220.127.116.11/20 18.104.22.168/20 22.214.171.124/22 126.96.36.199/17 188.8.131.52/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!