Last active
March 25, 2025 04:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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