Skip to content

Instantly share code, notes, and snippets.

@NotYusta
Last active March 28, 2025 17:07
Show Gist options
  • Save NotYusta/d1e227f6dbd27323b8c475586fe6d43d to your computer and use it in GitHub Desktop.
Save NotYusta/d1e227f6dbd27323b8c475586fe6d43d to your computer and use it in GitHub Desktop.
Firewall Cloudflare & SSH
#!/bin/sh
# Check if firewalld exists and stop/disable it if present
if command -v firewalld >/dev/null 2>&1; then
echo "Firewalld detected. Stopping and disabling firewalld..."
systemctl stop firewalld
systemctl disable firewalld
else
echo "Firewalld not found. Continuing with iptables..."
fi
if command -v dnf >/dev/null 2>&1; then
dnf update -y
dnf install -y iptables ipset curl
elif command -v apt >/dev/null 2>&1; then
apt update -y
apt install -y iptables ipset curl
else
echo "Unsupported OS" && exit 1
fi
# Create IP set for Cloudflare
ipset create cloudflare-v4 hash:net family inet -exist
# Fetch Cloudflare IPs dynamically
CLOUDFLARE_IPS=$(curl -s https://www.cloudflare.com/ips-v4)
for ip in $CLOUDFLARE_IPS; do
ipset add cloudflare-v4 "$ip" -exist
done
# Create iptables chain if it doesn't exist
iptables -N WEBSITE 2>/dev/null || true
iptables -F WEBSITE
iptables -A WEBSITE -m set --match-set cloudflare-v4 src -j ACCEPT
iptables -A WEBSITE -j DROP
# Ensure rules are not duplicated before adding
iptables -C INPUT -p tcp --dport 443 -j WEBSITE 2>/dev/null || iptables -A INPUT -p tcp --dport 443 -j WEBSITE
iptables -C INPUT -p tcp --dport 8443 -j WEBSITE 2>/dev/null || iptables -A INPUT -p tcp --dport 8443 -j WEBSITE
# SSH brute-force protection
iptables -C INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set 2>/dev/null || iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set
iptables -C INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP 2>/dev/null || iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP
# Protection against port scanning
iptables -N port-scanning 2>/dev/null || true
iptables -F port-scanning
iptables -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN
iptables -A port-scanning -j DROP
echo "Cloudflare filtering and security rules applied successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment