update_cloudflare_ips_for_ufw.sh 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/bin/bash
  2. # check root
  3. if [[ $EUID -ne 0 ]]; then
  4. exit 1
  5. fi
  6. # Cloudflare IPs URL
  7. CF_IPV4_URL="https://www.cloudflare.com/ips-v4"
  8. CF_IPV6_URL="https://www.cloudflare.com/ips-v6"
  9. # remove exist rules
  10. CF_RULES=$(ufw status numbered | grep '# Cloudflare' | grep -oP '\[\s*\K\d+(?=\])' | sort -rn)
  11. if [ -z "$CF_RULES" ]; then
  12. echo "no rule should be deleted"
  13. else
  14. for NUM in $CF_RULES; do
  15. ufw --force delete $NUM
  16. done
  17. fi
  18. # add rules for IPv4
  19. while read ip; do
  20. if [[ ! -z "$ip" ]]; then
  21. ufw allow proto tcp from $ip to any port 80 comment 'Cloudflare IPv4 HTTP'
  22. ufw allow proto tcp from $ip to any port 443 comment 'Cloudflare IPv4 HTTPS'
  23. fi
  24. done < <(curl -sL "$CF_IPV4_URL")
  25. # add rules for IPv6
  26. while read ip; do
  27. if [[ ! -z "$ip" ]]; then
  28. ufw allow proto tcp from $ip to any port 80 comment 'Cloudflare IPv6 HTTP'
  29. ufw allow proto tcp from $ip to any port 443 comment 'Cloudflare IPv6 HTTPS'
  30. fi
  31. done < <(curl -sL "$CF_IPV6_URL")
  32. # print latest rules
  33. ufw status numbered