Cloudflare's IP ranges can be added to iptables using the following steps below. This should be done to ensure none of our connections will be dropped, which could otherwise result in timeouts and other connectivity issues.
IPv4: For each of the ranges listed here: https://www.cloudflare.com/ips-v4 , you'll need to enter the following command at the terminal, replacing $ip with one of the IPs in the list:
iptables -I INPUT -p tcp -m multiport --dports http,https -s "$ip" -j ACCEPT
IPv6: For each of the ranges listed here: https://www.cloudflare.com/ips-v6 , you'll need to enter the following command at the terminal, replacing $ip with one of the IPs in the list:
ip6tables -I INPUT -p tcp -m multiport --dports http,https -s "$ip" -j ACCEPT
An alternative to having a long list of iptables rules for each network range is to use a utility called ipset. If you don't have this installed on your origin server, you can install it using your package manager.
Debian: sudo apt-get install ipset
Create an ipset set:
ipset create cf hash:net
Now populate the set with Cloudflare IP ranges:
for x in $(curl https://www.cloudflare.com/ips-v4); do ipset add cf $x; done
Note: The ipset you have created is stored in memory and will be gone after reboot by default. Remember to save it and/or restore it after reboot.
You can use the 'cf' set now in a iptables rule like so:
iptables -A INPUT -m set --match-set cf src -p tcp -m multiport --dports http,https -j ACCEPT
Once you run the iptables commands, you will need to save the iptables rules. The top two commands are used for IPv4 and the bottom two for IPv6.
iptables-save > /etc/iptables/rules.v4
iptables-save > /etc/sysconfig/iptables
ip6tables-save > /etc/iptables/rules.v6
ip6tables-save > /etc/sysconfig/ip6tables
Note: These rules only apply to your iptables and do not work for any additional firewalls.