Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active March 25, 2025 04:53
Show Gist options
  • Save devhammed/8edec1fef644038661829bc6ffc01282 to your computer and use it in GitHub Desktop.
Save devhammed/8edec1fef644038661829bc6ffc01282 to your computer and use it in GitHub Desktop.
Script to reject TCP connections that are not coming from Cloudfare except if it is SSH.
#!/bin/bash
set -eu
# Get the Cloudflare IPs.
curl -s https://www.cloudflare.com/ips-v4 -o /tmp/cloudflare_ips
echo "" >> /tmp/cloudflare_ips
curl -s https://www.cloudflare.com/ips-v6 >> /tmp/cloudflare_ips
# Reset the firewall to clean stuff.
ufw --force reset > /dev/null
# Make sure the firewall is enabled and started, as the above command stops it.
ufw enable
# Allow SSH.
ufw allow 22 > /dev/null
# Allow traffic from Cloudflare IPs on all ports.
for ip in $(cat /tmp/cloudflare_ips)
do
ufw allow proto tcp from $ip comment 'Cloudflare' > /dev/null
done
# Deny every other request.
ufw default deny > /dev/null
# Reload ufw.
ufw reload > /dev/null
# Show the rules to verify it worked.
ufw status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment