Skip to content

Instantly share code, notes, and snippets.

@SilverCory
Last active November 10, 2018 11:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilverCory/eb40ccae3ea0425296f6090c281e8ffe to your computer and use it in GitHub Desktop.
Save SilverCory/eb40ccae3ea0425296f6090c281e8ffe to your computer and use it in GitHub Desktop.
Make sure cloudflare is the only people who can view the site, as well as setting the realip.
#!/bin/bash
#
# Update cloudflare.conf with new IPs
#
cloudFlareConf="/etc/nginx/conf.d/cloudflare.conf"
cloudFlareList="/etc/nginx/conf.d/cloudflare-whitelist.conf"
IPV4=$(curl -s "https://www.cloudflare.com/ips-v4")
IPV6=$(curl -s "https://www.cloudflare.com/ips-v6")
DATE="$(date)"
######## Whitelist #########
## Headers
echo "# Last updated ${DATE}" > ${cloudFlareList}
echo 'geo $realip_remote_addr $cloudflare_ip {' >> ${cloudFlareList}
echo -e "\tdefault\t\t0;" >> ${cloudFlareList}
## Insert CF IPv4
echo -e "\n\t##IPv4" >> ${cloudFlareList}
for IPV4ip in ${IPV4}
do
echo -e "\t${IPV4ip}\t\t1;" >> ${cloudFlareList}
done
## Add additional IPv4's to whitelist here.
echo -e "\n\t#### Non cloudflare IP's but whitelisted" >> ${cloudFlareList}
echo -e "\t127.0.0.0/8\t\t1;" >> ${cloudFlareList}
## Insert CF IPv6
echo -e "\n\t##IPv6" >> ${cloudFlareList}
for IPV6ip in ${IPV6}
do
echo -e "\t${IPV6ip}\t\t1;" >> ${cloudFlareList}
done
## Add additional IPv6's to whitelist here.
echo -e "\n\t#### Non cloudflare IP's but whitelisted" >> ${cloudFlareList}
echo -e "\t::1/128\t\t1;" >> ${cloudFlareList}
echo "}" >> ${cloudFlareList}
######## Config #########
echo "# Last updated ${DATE}" > ${cloudFlareConf}
## IPv4 header
echo -e "\n\n# IPV4" >> ${cloudFlareConf}
## Insert CF IPv4
for IPV4ip in ${IPV4}
do
echo "set_real_ip_from ${IPV4ip};" >> ${cloudFlareConf}
done
## IPv6 header
echo -e "\n\n# IPV6" >> ${cloudFlareConf}
## Insert CF IPv6
for IPV6ip in ${IPV6}
do
echo "set_real_ip_from ${IPV6ip};" >> ${cloudFlareConf}
done
## Set the real cloudflare ip.
echo -e "\n\nreal_ip_header CF-Connecting-IP;" >> ${cloudFlareConf}
nginx -s reload
### Cloudflare hacker check.
### Redirect to a website if it's not going through cloudflare
if ($cloudflare_ip != 1) {
return 302 https://website.to.redirect.to/;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment