nginx服務器中的安全配置


一、關閉SELinux

安全增強型Linux(SELinux)的是一個Linux內核的功能,它提供支持訪問控制的安全政策保護機制。

但是,SELinux帶來的附加安全性和使用復雜性上不成比例,性價比不高

sed -i /SELINUX=enforcing/SELINUX=disabled/ /etc/selinux/config
/usr/sbin/sestatus -v  #查看狀態

二、通過分區掛載允許最少特權

服務器上 nginx 目錄單獨分區。例如,新建一個分區/dev/sda5(第一邏輯分區),並且掛載在/nginx。確保 /nginx是以noexec, nodev and nosetuid的權限掛載

以下是我的/etc/fstab的掛載/nginx的信息:LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2

注意:你需要使用fdisk和mkfs.ext3命令創建一個新分區。

三、配置/etc/sysctl.conf強化Linux安全

你可以通過編輯/etc/sysctl.conf來控制和配置Linux內核、網絡設置

# Avoid a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Turn on protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Turn on syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1
# Turn on and log spoofed, source routed, and redirect packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# No source routed packets here
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Turn on reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Make sure no one can alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
# Don’t act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# Turn on execshild
kernel.exec-shield = 1
kernel.randomize_va_space = 1
# Tuen IPv6
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.default.accept_ra_rtr_pref = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.default.dad_transmits = 0
net.ipv6.conf.default.max_addresses = 1
# Optimization for port usefor LBs
# Increase system file descriptor limit
fs.file-max = 65535
# Allow for more PIDs (to reduce rollover problems); may break some programs 32768
kernel.pid_max = 65536
# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000
# Increase TCP max buffer size setable using setsockopt()
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608
# Increase Linux auto tuning TCP buffer limits
# min, default, and max number of bytes to use
# set max to at least 4MB, or higher if you use very high BDP paths
# Tcp Windows etc
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

四、刪除所有不需要的Nginx模塊

你需要直接通過編譯Nginx源代碼使模塊數量最少化。通過限制只允許web服務器訪問模塊把風險降到最低。你可以只配置安裝nginx你所需要的模塊。例如,禁用SSL和autoindex模塊你可以執行以下命令:

./configure –without-http_autoindex_module –without-http_ssi_module
make && make install

更改nginx版本名稱、編輯文件/http/ngx_http_header_filter_module.c:

vim  src/http/ngx_http_header_filter_module.c

static char ngx_http_server_string[] = “Server: nginx” CRLF;
static char ngx_http_server_full_string[] = “Server: ” NGINX_VER CRLF;

//更改為

static char ngx_http_server_string[] = “Server: Ninja Web Server” CRLF;
static char ngx_http_server_full_string[] = “Server: Ninja Web Server” CRLF;

關閉nginx版本號的顯示

server_tokens off

五、基於Iptables防火牆的限制

下面的防火牆腳本阻止任何除了允許:

  • 來自HTTP(TCP端口80)的請求

  • 來自ICMP ping的請求

  • ntp(端口123)的請求輸出

  • smtp(TCP端口25)的請求輸出

六、控制緩沖區溢出攻擊

編輯和設置所有客戶端緩沖區的大小限制如下:

client_body_buffer_size  1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
  • 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,它所占用的緩沖區將被釋放。

你還需要控制超時來提高服務器性能並與客戶端斷開連接。按照如下編輯:

client_body_timeout   10;
client_header_timeout 10;
keepalive_timeout     5 5;
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將關閉連接。

七、控制並發連接

你可以使用NginxHttpLimitZone模塊來限制指定的會話或者一個IP地址的特殊情況下的並發連接。編輯nginx.conf:

### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###
### 1m can handle 32000 sessions with 32 bytes/session, set to 5m x 32000 session ###
limit_zone slimits $binary_remote_addr 5m;

### Control maximum number of simultaneous connections for one session i.e. ###
### restricts the amount of connections from a single ip address ###

limit_conn slimits 5;

上面表示限制每個遠程IP地址的客戶端同時打開連接不能超過5個。

八、只允許我們的域名的訪問

如果機器人只是隨機掃描服務器的所有域名,那拒絕這個請求。你必須允許配置的虛擬域或反向代理請求。你不必使用IP地址來拒絕。

if ($host !~ ^(test.in|www.test.in|images.test.in)$ ) {
    return 444;
}

九、限制可用的請求方法

GET和POST是互聯網上最常用的方法。 Web服務器的方法被定義在RFC 2616。如果Web服務器不要求啟用所有可用的方法,它們應該被禁用。下面的指令將過濾只允許GET,HEAD和POST方法:

## Only allow these request methods ##
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 444;
}
## Do not accept DELETE, SEARCH and other methods ##

更多關於HTTP方法的介紹

  • GET方法是用來請求,如文件http://www.moqifei.com/index.php

  • HEAD方法是一樣的,除非該服務器的GET請求無法返回消息體。

  • POST方法可能涉及到很多東西,如儲存或更新數據,或訂購產品,或通過提交表單發送電子郵件。這通常是使用服務器端處理,如PHP,Perl和Python等腳本。如果你要上傳的文件和在服務器處理數據,你必須使用這個方法。

十、如何拒絕一些User-Agents?

你可以很容易地阻止User-Agents,如掃描器,機器人以及濫用你服務器的垃圾郵件發送者。

## 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;
}

十一、防止圖片盜鏈

圖片或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
}

十二、目錄限制

你可以對指定的目錄設置訪問權限。所有的網站目錄應該一一的配置,只允許必須的目錄訪問權限。
通過IP地址限制訪問
你可以通過IP地址來限制訪問目錄/admin/:

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;
}

通過密碼保護目錄,首先創建密碼文件並增加“user”用戶

mkdir /usr/local/nginx/conf/.htpasswd/
htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd user

編輯nginx.conf,加入需要保護的目錄

### Password Protect /personal-images/ and /delta/ directories ###
location ~ /(personal-images/.*|delta/.*) {
    auth_basic  “Restricted”;
    auth_basic_user_file   /usr/local/nginx/conf/.htpasswd/passwd;
}

一旦密碼文件已經生成,你也可以用以下的命令來增加允許訪問的用戶

htpasswd -s /usr/local/nginx/conf/.htpasswd/passwd userName

十三、Nginx SSL配置

HTTP是一個純文本協議,它是開放的被動監測。你應該使用SSL來加密你的用戶內容。
創建SSL證書,執行以下命令:

cd /usr/local/nginx/conf
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

編輯nginx.conf並按如下來更新:

server {
    server_name example.com;
    listen 443;
    ssl on;
    ssl_certificate /usr/local/nginx/conf/server.crt;
    ssl_certificate_key /usr/local/nginx/conf/server.key;
    access_log /usr/local/nginx/logs/ssl.access.log;
    error_log /usr/local/nginx/logs/ssl.error.log;
}

十四、Nginx與PHP安全建議

PHP是流行的服務器端腳本語言之一。如下編輯/etc/php.ini文件:

# Disallow dangerous functions
disable_functions = phpinfo, system, mail, exec
## Try to limit resources  ##
# Maximum execution time of each script, in seconds
max_execution_time = 30
# Maximum amount of time each script may spend parsing request data
max_input_time = 60
# Maximum amount of memory a script may consume (8MB)
memory_limit = 8M
# Maximum size of POST data that PHP will accept.
post_max_size = 8M
# Whether to allow HTTP file uploads.
file_uploads = Off
# Maximum allowed size for uploaded files.
upload_max_filesize = 2M
# Do not expose PHP error messages to external users
display_errors = Off
# Turn on safe mode
safe_mode = On
# Only allow access to executables in isolated directory
safe_mode_exec_dir = php-required-executables-path
# Limit external access to PHP environment
safe_mode_allowed_env_vars = PHP_
# Restrict PHP information leakage
expose_php = Off
# Log all errors
log_errors = On
# Do not register globals for input data
register_globals = Off
# Minimize allowable PHP post size
post_max_size = 1K
# Ensure PHP redirects appropriately
cgi.force_redirect = 0
# Disallow uploading unless necessary
# Enable SQL safe mode
sql.safe_mode = On
# Avoid Opening remote files
allow_url_fopen = Off

十五、如果可能讓Nginx運行在一個chroot監獄

把nginx放在一個chroot監獄以減小潛在的非法進入其它目錄。你可以使用傳統的與nginx一起安裝的chroot。如果可能,那使用FreeBSD jails,Xen,OpenVZ虛擬化的容器概念。

十六、在防火牆級限制每個IP的連接數

網絡服務器必須監視連接和每秒連接限制。PF和Iptales都能夠在進入你的nginx服務器之前阻止最終用戶的訪問。
Linux Iptables:限制每次Nginx連接數
下面的例子會阻止來自一個IP的60秒鍾內超過15個連接端口80的連接數。

/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –set
/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –update –seconds 60  –hitcount 15 -j DROP
service iptables save

請根據你的具體情況來設置限制的連接數。

十七、配置操作系統保護Web服務器

像以上介紹的啟動SELinux.正確設置/nginx文檔根目錄的權限。Nginx以用戶nginx運行。但是根目錄(/nginx或者/usr /local/nginx/html)不應該設置屬於用戶nginx或對用戶nginx可寫。找出錯誤權限的文件可以使用如下命令:

find /nginx -user nginx
find /usr/local/nginx/html -user nginx

確保你更所有權為root或其它用戶,一個典型的權限設置 /usr/local/nginx/html/

ls -l /usr/local/nginx/html/

示例輸出:

-rw-r–r– 1 root root 925 Jan  3 00:50 error4xx.html
-rw-r–r– 1 root root  52 Jan  3 10:00 error5xx.html
-rw-r–r– 1 root root 134 Jan  3 00:52 index.html

你必須刪除由vi或其它文本編輯器創建的備份文件:

find /nginx -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’
find /usr/local/nginx/html/ -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’

通過find命令的-delete選項來刪除這些文件。

十八、限制Nginx連接傳出

黑客會使用工具如wget下載你服務器本地的文件。使用Iptables從nginx用戶來阻止傳出連接。ipt_owner模塊試圖匹配本地產生的數據包的創建者。下面的例子中只允許user用戶在外面使用80連接。

/sbin/iptables -A OUTPUT -o eth0 -m owner –uid-owner vivek -p tcp –dport 80 -m state –state NEW,ESTABLISHED  -j ACCEPT

通過以上的配置,你的nginx服務器已經非常安全了並可以發布網頁。可是,你還應該根據你網站程序查找更多的安全設置資料。例如,wordpress或者第三方程序。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM