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
Thanks for stopping by my page! I’m Magdalena May. Even though I jokingly credit my aunt for my writing talent, I know that it is a talent I have fostered from childhood. Though my mother is a writer, I also started out young. I’ve always had a way with words, according to my favorite educator. I was always so excited in history when we had to do a research writing assignment. Now, I help current learners achieve the grades that have always come easily to me. It is my way of giving back to schools because I understand the troubles… Read more »
Love the article
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?
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.