nginx服務器中的安全配置

1、關閉SELinux

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

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

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

2、經過分區掛載容許最少特權

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

如下是個人/etc/fstab的掛載/nginx的信息:LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2linux

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

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

你能夠經過編輯/etc/sysctl.conf來控制和配置Linux內核、網絡設置web

# 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

4、刪除全部不須要的Nginx模塊

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

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

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

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

5、基於Iptables防火牆的限制

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

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

  • 來自ICMP ping的請求

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

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

6、控制緩衝區溢出攻擊

編輯和設置全部客戶端緩衝區的大小限制以下:

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將關閉鏈接。

7、控制併發鏈接

你可使用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個。

8、只容許咱們的域名的訪問

若是機器人只是隨機掃描服務器的全部域名,那拒絕這個請求。你必須容許配置的虛擬域或反向代理請求。你沒必要使用IP地址來拒絕。

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

9、限制可用的請求方法

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等腳本。若是你要上傳的文件和在服務器處理數據,你必須使用這個方法。

10、如何拒絕一些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;
}

11、防止圖片盜鏈

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

12、目錄限制

你能夠對指定的目錄設置訪問權限。全部的網站目錄應該一一的配置,只容許必須的目錄訪問權限。
經過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

十3、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;
}

十4、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

十5、若是可能讓Nginx運行在一個chroot監獄

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

十6、在防火牆級限制每一個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

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

十7、配置操做系統保護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選項來刪除這些文件。

十8、限制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或者第三方程序。

相關文章
相關標籤/搜索