Nginx 增加 X-Content-Type-Options Header

在弱點掃描中被掃出一個弱點:
    
Missing X-Content-Type-Options Header
LOW 1
Invicti Standard detected a missing X-Content-Type-Options header which means that this website could be at risk of a MIME-sniffing
attacks.
Impact
MIME type sniffing is a standard functionality in browsers to find an appropriate way to render data where the HTTP headers sent by
the server are either inconclusive or missing.
This allows older versions of Internet Explorer and Chrome to perform MIME-sniffing on the response body, potentially causing the
response body to be interpreted and displayed as a content type other than the intended content type.
The problem arises once a website allows users to upload content which is then published on the web server. If an attacker can carry
out XSS (Cross-site Scripting) attack by manipulating the content in a way to be accepted by the web application and rendered as
HTML by the browser, it is possible to inject code in e.g. an image file and make the victim execute it by viewing the image

    

簡單來說就是 Header 缺少了 X-Content-Type-Options

我們先使用 CURL 指令確認回應資訊:
    
curl -I https://localhost
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 20 Jan 2025 11:01:01 GMT
Content-Type: text/html;charset=utf-8
Connection: keep-alive
x-powered-by: Nuxt
    

確實沒有 X-Content-Type-Options

編輯 nginx 設定檔:
    
sudo vi /etc/nginx/nginx.conf
    

在設定檔中使用 add_header 增加 X-Content-Type-Options 設定:
    
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    server_tokens off;
    add_header X-Content-Type-Options "nosniff" always;

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;


    sendfile        on;

    keepalive_timeout  65;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
    

檢查設定檔是否正確
    
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
    

重新啟動 nginx:
    
sudo systemctl reload nginx
    

再次使用 CURL 指令查詢,就會發現多出了 X-Content-Type-Options
    
curl -I https://localhost
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 20 Jan 2025 11:01:56 GMT
Content-Type: text/html;charset=utf-8
Connection: keep-alive
x-powered-by: Nuxt
X-Content-Type-Options: nosniff
    

留言