Only allow connections from Cloudflare using UFW

I guess youre here because you want to configure your server correctly & configure your firewall using UFW to allow http & https connections from cloudflare's network or more specifically from their IPs. Great news! You've just found a complete guide including a script. If you want to learn something about ufw, just keep on reading. Just want some copy & paste bash commands? Klick here, to scroll to the "Dont waste my time"-section.

Below i posted a script which outputs commands which you need to manually copy, check & paste into your promt. This is only really useful if you configured your firewall to block every other connection.

Prequisites

Before you execute the script below, you may want to pre-configure your ufw wrapped firewall - or even setup first.

First you make sure you have installed ufw, which is a noob-friendly wrapper for iptables.

apt install ufw -y

Then you need to allow ssh connections, if you haven't changed your default Port from 22 to something different, you can either use the bare command, or use their app feature which checks your system for known software and their corresponding ports while installing.

You can find all available preconfigured ports for well known software:

ufw app list

If you want to know which ports will be affected by the app, you can inspect it using the info subcommand.

ufw app info OpenSSH

Which will give you a result like

root@dev:~# ufw app info OpenSSH
Profile: OpenSSH
Title: Secure shell server, an rshd replacement
Description: OpenSSH is a free implementation of the Secure Shell protocol.

Port:
  22/tcp

Don't waste my time, let's get to configuring everything

Okay, seems like you're more the copy & paste type of guy. Then here you go:

sudo apt install ufw wget -y
sudo ufw reset
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow "OpenSSH"
sudo ufw enable

## The next commands will just be writte into stdout, you still need to copy & paste and manually execute the commands.

wget https://gist.githubusercontent.com/Padrio/6ba4cba4378d1dc49f90636131355ef6/raw/490cc3349a0ff317625fc48fde16d572a20c55d1/allow-cf.sh | bash - 
## The commands above needs to be copied & pasted into your prompt.

What am i executing there?

If you're suspicious what youre executing there, you can check the code here:

#!/bin/sh
cd /tmp
wget https://www.cloudflare.com/ips-v4 -O ips-v4-$$.tmp
wget https://www.cloudflare.com/ips-v6 -O ips-v6-$$.tmp

for cfip in `cat ips-v4-$$.tmp`; do echo "ufw allow from $cfip to any port 80 proto tcp"; done
for cfip in `cat ips-v6-$$.tmp`; do echo "ufw allow from $cfip to any port 80 proto tcp"; done
for cfip in `cat ips-v4-$$.tmp`; do echo "ufw allow from $cfip to any port 443 proto tcp"; done
for cfip in `cat ips-v6-$$.tmp`; do echo "ufw allow from $cfip to any port 443 proto tcp"; done
Kommentare anzeigen