Automate Raspberry Pi UFW to allow CloudFlare inbound

As IPv6 restores the ability to have end-to-end connectivity unlike IPv4 shielded by NAT, I needed to configure my Raspberry Pi firewall to allow only CloudFlare traffic inbound on port 443. Read on for the solution.

Solution overview

  1. Retrieve list of IPv4 and IPv6 addresses of CloudFlare.
  2. Loop through each to setup the firewall rule.
  3. Configure Cron to execute this on a schedule.

Prerequisites

Uncomplicated Firewall

UFW must be installed:

sudo apt-get install ufw

Ensure that IPv6 is enabled in /etc/default/ufw, you should see IPV6=yes.

Configure default rules; deny incoming, allow outgoing:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow all incoming traffic from your LAN. Change the subnet accordingly (i.e. if your IP address on LAN is 192.168.1.123, you need to allow 192.168.1.0/24):

sudo ufw allow from 192.168.0.0/24

This allows 192.168.0.x IP addresses. Please ensure this is correct or else you will not be able to SSH in thereafter.

Verify list of rules:

sudo ufw status

Enable UFW:

sudo ufw enabled

The script

#!/bin/sh

CLOUDFLARE_RUN_PATH=/run/cloudflare/
mkdir -p $CLOUDFLARE_RUN_PATH
cd $CLOUDFLARE_RUN_PATH
wget https://www.cloudflare.com/ips-v4 -O ips-v4.tmp
wget https://www.cloudflare.com/ips-v6 -O ips-v6.tmp
mv ips-v4.tmp ips-v4
mv ips-v6.tmp ips-v6

# Uncomment these 2 if you need port 80
#for cfip in `cat ips-v4`; do ufw allow from $cfip to any port 80 proto tcp; done
#for cfip in `cat ips-v6`; do ufw allow from $cfip to any port 80 proto tcp; done

for cfip in `cat ips-v4`; do ufw allow from $cfip to any port 443 proto tcp; done
for cfip in `cat ips-v6`; do ufw allow from $cfip to any port 443 proto tcp; done

I saved this file at /opt/cloudflare/cloudflare-ufw.sh and sudo chmod 744 /opt/cloudflare/cloudflare-ufw.sh.

To test it:

sudo /opt/cloudflare/cloudflare-ufw.sh

Check that appropriate firewall rules have been added:

sudo ufw status

Scheduling

Edit Cron:

sudo crontab -e

and add the following line:

0 0 * * 1 /opt/cloudflare/cloudflare-ufw.sh > /dev/null 2>&1

The firewall rules will now be updated once a week.

Support Me

If this post helped you, would you buy me a cup of tea/coffee?