How to prevent "host header injection vulnerability" in Nginx proxy server

aravindks asked:

Please help me to prevent "host header injection vulnerability" in the given "Nginx configuration file"

 server {
    listen 80 default_server;
    listen [::]:80 default_server;       
    root /var/www/html;        
    index index.html index.htm index.nginx-debian.html;
    server_name _;
            location / {
            proxy_pass http://IP_1/;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;
            add_header Cache-Control "no-cache";                
    }
    location /kuphubadmin/ {                
            proxy_pass http://IP_2/;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;
            add_header Cache-Control "no-cache";
   }}

Note: The above server is used as a proxy server.

My answer:


The "host header injection vulnerability" means that your server is accepting any Host header even if it is not a valid hostname for any of your web sites. In your case you have configured a catch-all server block that responds to any hostname and sends all such requests to your web application.

This is easy to fix in nginx.

First, you need to leave alone the default server block that shipped with nginx. Do not change it in any way. This will catch requests with invalid Host headers and send them only a harmless "the web server is working" document, or a 403 Forbidden error, or both.

Second, you need to specify only the valid hostnames for your site in the server_name directive of your custom server block. Don’t use _. For example server_name example.com www.example.com;


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.