Search Our Database
Securing Server by Only Allow Cloudflare IPs using Iptables
Introduction
Enabling Cloudflare Proxy is one of the ways to protect your server. Once the proxy is enabled, all the traffic will pass through Cloudflare before reaching to your server. To have further protection, you may configure your Linux server only allow Cloudflare IP to access website port 80 and 443. This guide will show you how to only allow Cloudflare IPs to access port 80 and 443 using IP Tables.
Prerequisite
- Root SSH access to server
- Knowledge on Linux command line and Iptables
- Domains are pointed to Cloudflare and proxied, else the website will inaccessible
Step by Step Guide
1. Create a new bash script in the home directory. Ensure that you are logged in as root user as iptables require root privilege.
vi iptables-setup.sh
2. Once you’re in the file, press the letter “i” until you see INSERT on the bottom left of the page. You may refer to this link for Cloudflare IPs. Then, paste these codes in the file.
#!/bin/bash # Flush existing rules iptables -F # Allow traffic from specific IP ranges on ports 80 and 443 ALLOWED_IP_RANGES=( "173.245.48.0/20" "103.21.244.0/22" "103.22.200.0/22" "103.31.4.0/22" "141.101.64.0/18" "108.162.192.0/18" "190.93.240.0/20" "188.114.96.0/20" "197.234.240.0/22" "198.41.128.0/17" "162.158.0.0/15" "104.16.0.0/13" "104.24.0.0/14" "172.64.0.0/13" "131.0.72.0/22" ) for ip_range in "${ALLOWED_IP_RANGES[@]}"; do iptables -A INPUT -p tcp -s "$ip_range" --dport 80 -j ACCEPT iptables -A INPUT -p tcp -s "$ip_range" --dport 443 -j ACCEPT done # Drop all other traffic intended for port 80 and 443 iptables -A INPUT -p tcp --dport 80 -j DROP iptables -A INPUT -p tcp --dport 443 -j DROP # Save the iptables rules iptables-save > /etc/iptables/rules.v4 echo "IPTables rules applied successfully."
3. Change the file permission.
chmod +x iptables-setup.sh
4. Run the script with root privillage
sudo ./iptables-setup.sh
Conclusion
By going through this guidance, your server will be secured by only allow traffics from Cloudflare to access the website.
For additional assistance or if you encounter any issues, please contact our support team at support@ipserverone.com.
article published on 4 April 2020 by IPSERVERONE