Kubernetes – Allow Only Cloudflare CDN Through Nginx Ingress

If you are like me, and enjoy the world-encompassing CDN from Cloudflare, you “proxy” your domain through Cloudflare towards your Kubernetes Ingress. Why then, should you allow any other traffic to the Ingress? Here’s how to whitelist Cloudflare only in Nginx Ingress.

Cloudflares IP-ranges can be found here: https://www.cloudflare.com/ips/

Whitelist them on the Nginx Ingress like so:

nginx.ingress.kubernetes.io/whitelist-source-range: >-
  173.245.48.0/20,
  103.21.244.0/22,
  103.22.200.0/22,
  103.31.4.0/22,
  141.101.64.0/18,
  108.162.192.0/18,
  190.93.240.0/20,
  188.114.96.0/20,
  197.234.240.0/22,
  198.41.128.0/17,
  162.158.0.0/15,
  104.16.0.0/13,
  104.24.0.0/14,
  172.64.0.0/13,
  131.0.72.0/22,
  2400:cb00::/32,
  2606:4700::/32,
  2803:f800::/32,
  2405:b500::/32,
  2405:8100::/32,
  2a06:98c0::/29,
  2c0f:f248::/32

Example Ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/whitelist-source-range: >-
      173.245.48.0/20,
      103.21.244.0/22,
      103.22.200.0/22,
      103.31.4.0/22,
      141.101.64.0/18,
      108.162.192.0/18,
      190.93.240.0/20,
      188.114.96.0/20,
      197.234.240.0/22,
      198.41.128.0/17,
      162.158.0.0/15,
      104.16.0.0/13,
      104.24.0.0/14,
      172.64.0.0/13,
      131.0.72.0/22,
      2400:cb00::/32,
      2606:4700::/32,
      2803:f800::/32,
      2405:b500::/32,
      2405:8100::/32,
      2a06:98c0::/29,
      2c0f:f248::/32
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: example-service
            port:
              number: 80

You can test accessing the ingress directly (outside Cloudflare) and you should get a “403 Forbidden”:

~$ curl http://www.example.com --resolve www.example.com:80:[K8S-INGRESS-IP]
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

Filter the Internet 👾

Leave a Reply

Your email address will not be published. Required fields are marked *