Properly Whitelisting Cloudflare IPs

If you’re hosting a web service behind Cloudflare, properly hiding your origin IP address(es) requires blocking all HTTP/HTTPS traffic that doesn’t come from Cloudflare. Whitelisting is important to prevent attackers from scanning the internet and finding your origin IP.

First, we block all http/https requests by dropping TCP requests to port 80/443.

# iptables -A INPUT -p tcp --dport http -j REJECT --reject-with tcp-reset
# iptables -A INPUT -p tcp --dport https -j REJECT --reject-with tcp-reset

We’ll use iptables with the reject-with tcp-reset flag. Without this flag, an attacker can still detect that a program is listening on the port, whereas with the flag, the port will appear to be closed. The difference can be seen in nmap, were a regular reject shows up as “FILTERED” and a tcp-reset reject shows up as “CLOSED”.

Next, we’ll add the Cloudflare IP ranges so they can connect to our host.

# for i in `curl https://www.cloudflare.com/ips-v4`; do iptables -I INPUT -p tcp -s $i --dport http -j ACCEPT; done
# for i in `curl https://www.cloudflare.com/ips-v4`; do iptables -I INPUT -p tcp -s $i --dport https -j ACCEPT; done

Now we’ve ensured that only Cloudflare servers can access ports 80/443! To everyone else, it appears that the server isn’t running anything on those ports.

If your server has IPv6 interfaces, you’ll also need to run the same commands using ip6tables:

# ip6tables -A INPUT -p tcp --dport http -j REJECT --reject-with tcp-reset
# ip6tables -A INPUT -p tcp --dport https -j REJECT --reject-with tcp-reset
# for i in `curl https://www.cloudflare.com/ips-v6`; do ip6tables -I INPUT -p tcp -s $i --dport http -j ACCEPT; done
# for i in `curl https://www.cloudflare.com/ips-v6`; do ip6tables -I INPUT -p tcp -s $i --dport https -j ACCEPT; done

3
Leave a Reply

2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Cat

Love the article

Alessandro

Hi. I tried your solution but it doesn’t seem to work. Cloudflare is being blocked too.
I never used Iptables (in fact I don’t have root access to my VPS so I had the Cloudways staff do this for me). Maybe this is a stupid question since I’m a novice, but could this be due to the fact that the REJECT part comes before the ALLOW part?

Chris

Alessandro, iptables processes the rules in order, from top to bottom. If you accept before you reject, the reject rule takes precedence and rejects everyone including Cloudflare. The article syntax is correct, AFAIK.