Search code examples
nginxopenshiftokd

nginx deny based on $http_x_forwarded_for


I have an nginx container in openshift. I am trying to limit the access from external IPs, more specifically, anything not in the 10.X.X.X range.

This is my config file

http {
    ....
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    ....

    }
    server {

        listen 8080;
        server_name app.okd.company.com;
        allow 10.0.0.0/8;
        deny all;
        location / {
        proxy_pass http://app/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_redirect off;
        }

        location /static/ {
        autoindex on;
        alias /app/static/;
        }
    }

The connection is allowed whether private or external. Here are some logs.

10.129.2.1 - - [16/Nov/2021:19:28:57 +0000] "POST /graphql/ HTTP/1.1" 200 53384 "https://app.okd.company.com/ " "Mozilla/5.0 (X11; Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0" "10.3.16.158"

10.131.2.1 - - [16/Nov/2021:19:42:56 +0000] "POST /graphql/ HTTP/1.1" 200 53384 "https://app.okd.company.com/ " "Mozilla/5.0 (X11; Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0" "73.177.XXX.XXX"

The first log seems to be allowing private IP connections, which is expected, but the second one is still being allowed. I'm not sure why it isn't blocking.

EDIT:

I realize the remote_addr is in the private IP range. I don't care which proxy it used access the nginx I have control over. I just care about the origin/http_x_forwarded_for. Is there a way I can allow or deny based off of that


Solution

  • To use the http_x_forwarded_for as the real IP, you should set that in the server config.

    ...
        server {
            set_real_ip_from 10.0.0.0/8;
            real_ip_header X-Forwarded-For;
    ...
    

    set_real_ip_from1 is not optional. It needs to contain all addresses that could be the forwarding proxy