Search Our Database

Securing Server and Only Allow Cloudflare IPs using Iptables

Last updated on |
by

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

 

  1. Create a new file to be your new firewall.
    [user@server ~]# vi /root/firewall
  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/bashset -x#ALLOW YOUR IP BELOW
    ALLOW_IP="192.168.1.0/24 127.0.0.1"#CLOUDFLARE IP
    CF_IP="103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 104.16.0.0/12 108.162.192.0/18 141.101.64.0/18 162.158.0.0/15 172.64.0.0/13 173.245.48.0/20 188.114.96.0/20 190.93.240.0/20 197.234.240.0/22 198.41.128.0/17 199.27.128.0/21 $ALLOW_IP"

    iptables -P INPUT ACCEPT
    #FLUSH INPUT RULES
    iptables -F INPUT

    #ACCEPT CONNECTION TO PORT 80 AND 443 BASED ON $CF_IP
    for ip in $CF_IP; do
    iptables -A INPUT -p tcp -s $ip -m multiport --dport 80,443 -j ACCEPT
    done

    #DROP CONNECTION TO PORT 80 AND 443
    iptables -A INPUT -p tcp -m multiport --dport 80,443 -j DROP
  3. Change the file permission.
    [user@server ~]# chmod 755 /root/firewall
  4. Run the file.
    [user@server ~]# /root/firewall

 

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.