天天看點

Nginx正常配置-安全加強Nginx配置

Nginx配置

一、隐藏版本号:

(操作後即隻顯示WebServ使用的是Nginx)

Nginx正常配置-安全加強Nginx配置

1、進入nginx配置檔案的目錄(此目錄根據安裝時決定),用vim編輯打開

[[email protected] nginx]# vim /etc/nginx/nginx.conf
           

2、在http {—}裡加上server_tokens off; 如:

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

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

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    server_tokens off;

    include /etc/nginx/conf.d/*.conf;

}
           

3、重新加載Nginx服務

[[email protected] nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[[email protected] nginx]# nginx -s reload
           

這樣就完全對外隐藏了nginx版本号了,就是出現404、501等頁面也不會顯示nginx版本。

Nginx正常配置-安全加強Nginx配置
Nginx正常配置-安全加強Nginx配置

二、為用戶端設定緩沖區大小限制:

設定自定義緩存以限制緩沖區溢出攻擊。nginx.conf配置如下:

http{
    ... ...
    server{
        ... ...
        client_body_buffer_size  16K;
        client_header_buffer_size  1k;
        client_max_body_size  1m;
        large_client_header_buffers  4  8k;
        ... ...
        ... ...
        ... ...
    }
}
           

注:上述的參數不是最優參數,僅供參考。加強檢查: 確定server子產品中配置了上述标紅的配置。

  • client_body_buffer_size 1k(預設8k或16k)這個指令可以指定連接配接請求實體的緩沖區大小。如果連接配接請求超過緩存區指定的值,那麼這些請求實體的整體或部分将嘗試寫入一個臨時檔案。
  • client_header_buffer_size 1k 指令指定用戶端請求頭部的緩沖區大小。絕大多數情況下一個請求頭不會大于1k,不過如果有來自于wap用戶端的較大的cookie它可能會大于 1k,Nginx将配置設定給它一個更大的緩沖區,這個值可以在large_client_header_buffers裡面設定。
  • client_max_body_size 1k 指令指定允許用戶端連接配接的最大請求實體大小,它出現在請求頭部的Content-Length字段。如果請求大于指定的值,用戶端将收到一個”Request Entity Too Large” (413)錯誤。記住,浏覽器并不知道怎樣顯示這個錯誤。
  • large_client_header_buffers 指定用戶端一些比較大的請求頭使用的緩沖區數量和大小。請求字段不能大于一個緩沖區大小,如果用戶端發送一個比較大的頭,nginx将傳回”Request URI too large” (414)
  • 同樣,請求的頭部最長字段不能大于一個緩沖區,否則伺服器将傳回”Bad request” (400)。緩沖區隻在需求時分開。預設一個緩沖區大小為作業系統中分頁檔案大小,通常是4k或8k,如果一個連接配接請求最終将狀态轉換為keep- alive,它所占用的緩沖區将被釋放。

設定timeout

設定timeout設低來防禦DOS攻擊,nginx.conf配置如下:

http{
    ... ...
    server{
        ... ...
        client_body_timeout		10;
        client_header_timeout	30;
        keepalive_timeout		30  30;
        send_timeout			10;
        ... ...
        ... ...
        ... ...
    }
}
           
  • client_body_timeout 10;-指令指定讀取請求實體的逾時時間。這裡的逾時是指一個請求實體沒有進入讀取步驟,如果連接配接超過這個時間而用戶端沒有任何響應,Nginx将傳回一個”Request time out” (408)錯誤。
  • client_header_timeout 10;-指令指定讀取用戶端請求頭标題的逾時時間。這裡的逾時是指一個請求頭沒有進入讀取步驟,如果連接配接超過這個時間而用戶端沒有任何響應,Nginx将傳回一個”Request time out” (408)錯誤。
  • keepalive_timeout 5 5; – 參數的第一個值指定了用戶端與伺服器長連接配接的逾時時間,超過這個時間,伺服器将關閉連接配接。參數的第二個值(可選)指定了應答頭中Keep-Alive: timeout=time的time值,這個值可以使一些浏覽器知道什麼時候關閉連接配接,以便伺服器不用重複關閉,如果不指定這個參數,nginx不會在應 答頭中發送Keep-Alive資訊。(但這并不是指怎樣将一個連接配接“Keep-Alive”)參數的這兩個值可以不相同。
  • send_timeout 10; 指令指定了發送給用戶端應答後的逾時時間,Timeout是指沒有進入完整established狀态,隻完成了兩次握手,如果超過這個時間用戶端沒有任何響應,nginx将關閉連接配接。

三、禁用所有不需要的 HTTP 方法

Http請求中8種請求方法

  • opions 傳回伺服器針對特定資源所支援的HTML請求方法 或web伺服器發送測試伺服器功能(允許用戶端檢視伺服器性能)
  • Get 向特定資源送出請求(請求指定頁面資訊,并傳回實體主體)
  • Post 向指定資源送出資料進行處理請求(送出表單、上傳檔案),又可能導緻新的資源的建立或原有資源的修改
  • Put 向指定資源位置上上傳其最新内容(從用戶端向伺服器傳送的資料取代指定文檔的内容)
  • Head 與伺服器索與get請求一緻的相應,響應體不會傳回,擷取包含在小消息頭中的原資訊(與get請求類似,傳回的響應中沒有具體内容,用于擷取報頭)
  • Delete 請求伺服器删除request-URL所标示的資源(請求伺服器删除頁面)
  • Trace 回顯伺服器收到的請求,用于測試和診斷
  • Connect HTTP/1.1協定中能夠将連接配接改為管道方式的代理伺服器

​ http伺服器至少能實作get、head、post方法,其他都是可選的;從安全防護角度考慮,一般我們要禁用不安全的 HTTP 方法,僅保留 GET、HEAD、POST 方法。過濾掉 DELETE 和 TRACE 等。

​ nginx 禁用不安全的http方法,既可以在nginx配置檔案 server 下進行全局設定,也可以在某個location下進行設定。

1、全局設定方式一

if ($request_method ~ ^(PUT|DELETE|TRACE|HEAD)$) {    #需要将所有不允許的請求方法都寫到裡面
            return 404;
        }
# ~ ^(PUT|DELETE|TRACE|HEAD)$ :比對PUT|DELETE|TRACE|HEAD的請求方法
           

2、全局設定方式二

if ($request_method !~ ^(GET|POST)$) {
            return 403;
        }

# 大概的意思就是,如果頁面使用這二種(GET、POST)之外的方法,
# 網站直接傳回403頁面,無法擷取更多資訊,進而加強了伺服器的安全性能,
# 添加完成後儲存,重載nginx配置檔案就行了。

# !~ ^(GET|POST)$ :比對非GET|POST的請求方法
           

​ 比如:

server {
        listen       80;
        server_name  www.iwen.com;
        #return 301 https://$server_name$request_uri;
 
        if ($request_method !~ ^(GET|POST)$) {
            return 404;
        }
        .......
        .......
}
           

3、局部設定方式一:

location /knowlege_app {
        include /usr/local/nginx/allow_ip_list.conf;
        if ($request_method = PUT ) {
                return 404;
        } 
        if ($request_method = DELETE ) {
                return 404;
        }
        if ($request_method = OPTIONS ) {
                return 404;
        }
        if ($request_method = TRACE ) {
                return 404;
        }
        proxy_pass http://serverKnowlege_app;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
           

4、局部設定方式二:

location /knowlege_app {
	include /usr/local/nginx/allow_ip_list.conf;
	if ($request_method !~ ^(GET|POST|HEAD)$) {
		return 403;
	}
        proxy_pass http://serverKnowlege_app;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
           

​ 測試配置:

Nginx正常配置-安全加強Nginx配置

四、Header頭設定

server {
    listen       80;
    server_name xjbt.test.nercoa.com;
# X-Frame-Options頭部可以保護你的網站内容
	add_header X-Frame-Options "SAMEORIGIN";
# XSS審計
	add_header X-XSS-Protection "1; mode=block";
# Content Type選項,設定X-Content-Type-Options為nosniff ,就是強迫浏覽器尊重伺服器端指定的檔案類型。	
	add_header X-Content-Type-Options nosniff;
#阻止浏覽器拒絕被黑客從HTTPS切換到HTTP等不安全的網址下載下傳内容,HSTS頭部選項會強迫使用者開始通過HTTPS連接配接時,以後的連接配接都是通過HTTPS。	
	add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

#激活内容安全政策Content Security Policy (CSP) ,大部分浏覽器支援
# 告訴浏覽器隻能從本域名和你顯式指定的網址下載下傳腳本。
# http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
	add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";
	location / {
		...
	}
	...
}
           

五、添加location限制***----未配置***

不符合請示路徑設定的外部請求,統一轉到404報錯頁;首先要擷取出允許通路的路徑集合資訊。

server {
    listen 80;
    listen 443 ssl;
    server_name www.nvic.edu.cn nvic.edu.cn;
	·····
	忽略資訊
	·····
# 比對允許通路的位址資訊:
 	location  ~* ^/((\w+\.aspx)|(admin/)|(data/)|(download/)|(Libs/)|(Scripts/)|(Service/)|(staticFile/)|(Templates/)|(Web/)|(Content/)) {
       #隻允許符合以上的路徑(admin、data、download等)通路,
       proxy_pass http://127.0.0.1:8002;
       proxy_http_version 1.1;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

# 比對首頁位址資訊:
    location  ~ ^/$ {
       proxy_pass http://127.0.0.1:8002;
       proxy_http_version 1.1;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
           

六、禁止檔案被下載下傳

zip|rar|sql|bak|7z等内部備份但忘記删除的檔案。

#Deny Download
location ~ \.(zip|rar|sql|bak|gz|7z)$ {
  return 404;
}
           
Nginx正常配置-安全加強Nginx配置

七、屏蔽蜘蛛爬蟲:

if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
     return 404;
}
           
Nginx正常配置-安全加強Nginx配置

八、拒絕一些User-Agents

可以很容易地阻止User-Agents,如soso、已知惡意代理、掃描器,機器人以及濫用你伺服器的垃圾郵件發送者。

## Block download agents ##
if	($http_user_agent ~* LWP::Simple|BBBike|wget) {
  return 403;
}
### 阻止Soso和有道的機器人:
## Block some robots ##
if ($http_user_agent ~* Sosospider|YodaoBot) {
  return 403;
}
           
Nginx正常配置-安全加強Nginx配置

九、禁止上傳檔案夾及圖檔、樣式等檔案夾執行.net程式等等:

比如網站上傳目錄,通常存放的都是靜态檔案,如果因程式驗證不嚴謹被上傳木馬程式,導緻網站被黑。以下規則請根據自身情況改為您自己的目錄,需要禁止的腳本字尾也可以自行添加。

#uploads|templets|data 這些目錄禁止執行.net
location ~* ^/(uploads|templets|data)/.*.(exe|aspx)$ {
    return 404;
}
           
Nginx正常配置-安全加強Nginx配置

十、屏蔽某個IP或IP段***----未配置***

如果網站被惡意灌水或CC攻擊,可從網站日志中分析特征IP,将其IP或IP段進行屏蔽。子產品 ngx_http_access_module 允許限制某些IP位址的用戶端通路。

location/ {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}
##或者通過IP位址來限制通路目錄/docs/:
location /docs/ {
  ## block one workstation
  deny  192.168.1.1;
  ## allow anyone in 192.168.1.0/24
  allow  192.168.1.0/24;
  ## drop rest of the world
  deny  all;
}
           

注:規則按照順序依次檢測,直到比對到第一條規則。 在這個例子裡,IPv4的網絡中隻有 10.1.1.0/16 和 192.168.1.0/24允許通路,但 192.168.1.1除外, 對于IPv6的網絡,隻有2001:0db8::/32允許通路。

上面大部分規則傳回444狀态碼而不是403,因為444狀态碼在nginx中有特殊含義。nginx的444狀态是直接由伺服器中斷連接配接,不會向用戶端再傳回任何消息,比傳回403更加暴力。若有不足還請補充和指正。

十一、防止圖檔盜鍊***----未配置***

圖檔或HTML盜鍊的意思是有人直接用你網站的圖檔位址來顯示在他的網站上。最終的結果,你需要支付額外的寬帶費用。這通常是在論壇和部落格。我強烈建議您封鎖,并阻止盜鍊行為。

# Stop deep linking or hot linking
location /images/ {
  valid_referers none blocked www.example.com example.com;
  if ($invalid_referer) {
    return  403;
  }
}
           

例如:重定向并顯示指定圖檔

valid_referers blocked www.example.com example.com;
  
if ($invalid_referer) {
  rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last
}
           
server {
    listen       80;
    server_name xjbt.test.nercoa.com;
# X-Frame-Options頭部可以保護你的網站内容
	add_header X-Frame-Options "SAMEORIGIN";
# XSS審計
	add_header X-XSS-Protection "1; mode=block";
# Content Type選項,設定X-Content-Type-Options為nosniff ,就是強迫浏覽器尊重伺服器端指定的檔案類型。	
	add_header X-Content-Type-Options nosniff;
#阻止浏覽器拒絕被黑客從HTTPS切換到HTTP等不安全的網址下載下傳内容,HSTS頭部選項會強迫使用者開始通過HTTPS連接配接時,以後的連接配接都是通過HTTPS。	
	add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

#激活内容安全政策Content Security Policy (CSP) ,大部分浏覽器支援
# 告訴浏覽器隻能從本域名和你顯式指定的網址下載下傳腳本。
# http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
	add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

	add_header Access-Control-Allow-Origin: * # 允許所有域請求
#	add_header Access-Control-Allow-Origin: http://someone.com # 允許特定域請求

#禁用所有不需要的 HTTP 方法
    if ($request_method !~ ^(GET|POST|HEAD)$) {
        return 404;
    }
    
#為用戶端設定緩沖區大小限制
     client_body_buffer_size  16K;
     client_header_buffer_size  1k;
     client_max_body_size  1m;
     large_client_header_buffers  4  8k;
#    client_max_body_size 100M;

#設定逾時時間
    client_body_timeout		10;
    client_header_timeout	30;
    keepalive_timeout		30  30;
    send_timeout		    10;

    location / {
       proxy_pass http://202.205.161.84:9332;
       proxy_set_header   Host             $host;
       proxy_set_header   X-Real-IP        $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
#Proxy Settings
       proxy_redirect     off;
       proxy_set_header   Connection       close;
       proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
       proxy_max_temp_file_size 0;
       proxy_connect_timeout      90;
       proxy_send_timeout         90;
       proxy_read_timeout         90;
       proxy_buffer_size          4k;
       proxy_buffers              4 32k;
       proxy_busy_buffers_size    64k;

#屏蔽蜘蛛爬蟲
       if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
             return 404;
     }
#拒絕一些User-Agents
       if ($http_user_agent ~* Sosospider|YodaoBot) {
             return 403;
     }
       if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
             return 403;
     }
  }

    location ~* \.(?:ico|css|js|gif|jpe?g|png|svg|woff|ttf|eot)$ {
       proxy_pass http://202.205.161.84:9332;
       proxy_set_header   Host             $host;
       proxy_set_header   X-Real-IP        $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
#Proxy Settings
       proxy_redirect     off;
       proxy_set_header   Connection       close;
       proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
       proxy_max_temp_file_size 0;
       proxy_connect_timeout      90;
       proxy_send_timeout         90;
       proxy_read_timeout         90;
       proxy_buffer_size          4k;
       proxy_buffers              4 32k;
       proxy_busy_buffers_size    64k;
       add_header Cache-Control "max-age=86400, public";
  }
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
  }

#禁止指定格式檔案被下載下傳
    location ~ \.(zip|rar|sql|bak|gz|7z)$ {
       return 404;
  }
  
#禁止上傳檔案夾及圖檔、樣式等檔案夾執行.net程式等等
    location ~* ^/(uploads|templets|data)/.*.(exe|aspx)$ {
        return 404;
  }
}
           

參考連結:

  1. Content Security Policy 入門教程
  2. Nginx提高安全與性能的最好配置
  3. HTTP 安全頭配置
  4. 七種HTTP頭部設定保護你的網站應用安全