Skip to content

Solution to detect the real ip while blocking non cloudflare #3

@aseques

Description

@aseques

I'll post here the final approach I took to get at the same time

  • Block non cloudflare IPs (per server)
  • Identify incoming ips
  • No need for a firewall
    Add to nginx.conf (http scope):
geo $realip_remote_addr $cloudflare_ip {
        default          0;
        103.21.244.0/22  1;
        103.22.200.0/22  1;
        103.31.4.0/22    1;
        104.16.0.0/12    1;
        108.162.192.0/18 1;
        131.0.72.0/22    1;
        141.101.64.0/18  1;
        162.158.0.0/15   1;
        172.64.0.0/13    1;
        173.245.48.0/20  1;
        188.114.96.0/20  1;
        190.93.240.0/20  1;
        197.234.240.0/22 1;
        198.41.128.0/17  1;
        199.27.128.0/21  1;
    }

In the server block:

location /route/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:8051/;
        proxy_redirect off;
        if ($cloudflare_ip != 1) {
            return 403;
        }
        include /etc/nginx/snippets/allow_cloudflare.conf;
        deny all;
    }

Being allow_cloudflare.conf the following:

allow 103.21.244.0/22;
allow 103.22.200.0/22;
allow 103.31.4.0/22;
allow 104.16.0.0/12;
allow 108.162.192.0/18;
allow 131.0.72.0/22;
allow 141.101.64.0/18;
allow 162.158.0.0/15;
allow 172.64.0.0/13;
allow 173.245.48.0/20;
allow 188.114.96.0/20;
allow 190.93.240.0/20;
allow 197.234.240.0/22;
allow 198.41.128.0/17;

real_ip_header CF-Connecting-IP;

This works like a charm, if you still want extra security you can configure the firewall to block the other ips but it's not needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions