Server Gigabit Guide

How do I whitelist Cloudflare’s IP addresses in iptables?

You are here:
Estimated reading time: 1 min

Cloudflare’s IP ranges can be add to iptables using the following steps below. This should be done to ensure none of our connections will be drop, 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 create is store 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 use for IPv4 and the bottom two for IPv6.

Debian/Ubuntu: iptables-save > /etc/iptables/rules.v4
RHEL/CentOS: iptables-save > /etc/sysconfig/iptables
Debian/Ubuntu: ip6tables-save > /etc/iptables/rules.v6
RHEL/CentOS: ip6tables-save > /etc/sysconfig/ip6tables

Was this article helpful?
Dislike 0
Views: 63