Script I wrote to only allow Cloudflare IPs to access your web server

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
To ensure that L7 attacks have to go through Cloudflare's reverse proxy (allowing me to enable rate limiting and other features), I wrote an iptables script which drops all traffic on ports 80 and 443 except for traffic from Cloudflare IPs. This is far from a perfect solution and still requires an L3/L4 filter to handle the rest of DDoS Protection (OVH is pretty solid there), but I figured I'd share it for other website owners who might want to take advantage from it. You'll need to either use full ssl mode OR swap to port 80.

Bash:
[email protected]:~# iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -s 173.245.48.0/20 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 103.21.244.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 103.22.200.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 103.31.4.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 141.101.64.0/18 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 108.162.192.0/18 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 190.93.240.0/20 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 188.114.96.0/20 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 197.234.240.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 198.41.128.0/17 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 162.158.0.0/15 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 104.16.0.0/12 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 172.64.0.0/13 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 131.0.72.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j DROP
-A INPUT -p tcp -m tcp --dport 443 -j DROP
[email protected]:~# cat iptables.sh
#Allow Cloudflare IPs
iptables -A INPUT -p tcp -s 173.245.48.0/20 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 103.21.244.0/22 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 103.22.200.0/22 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 103.31.4.0/22 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 141.101.64.0/18 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 108.162.192.0/18 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 190.93.240.0/20 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 188.114.96.0/20 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 197.234.240.0/22 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 198.41.128.0/17 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 162.158.0.0/15 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 104.16.0.0/12 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 172.64.0.0/13 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 131.0.72.0/22 --dport 443 -j ACCEPT

# Drop HTTP and HTTPS for all other IPs
iptables -A INPUT -p tcp -s 0.0.0.0/0 --dport 80 -j DROP
iptables -A INPUT -p tcp -s 0.0.0.0/0 --dport 443 -j DROP