20步打造最安全的Nginx Web服務器

  轉載:https://help.aliyun.com/knowledge_detail/5974693.html?spm=5176.788314853.2.18.oJa9yk

   Nginx是一個輕量級的,高性能的Web服務器以及反向代理和郵箱 (IMAP/POP3)代理服務器。它運行在UNIX,GNU /linux,BSD 各種版本,Mac OS X,Solaris和Windows。根據調查統計,6%的網站使用Nginx Web服務器。Nginx是少數能處理C10K問題的服務器之一。跟傳統的服務器不同,Nginx不依賴線程來處理請求。相反,它使用了更多的可擴展的事 件驅動(異步)架構。Nginx爲一些高流量的網站提供動力,比如WordPress,人人網,騰訊,網易等。這篇文章主要是介紹如何提高運行在 Linux或UNIX系統的Nginx Web服務器的安全性。

 

默認配置文件和Nginx端口

  • /usr/local/nginx/conf/ – Nginx配置文件目錄,/usr/local/nginx/conf/nginx.conf是主配置文件

  • /usr/local/nginx/html/ – 默認網站文件位置

  • /usr/local/nginx/logs/ – 默認日誌文件位置

  • Nginx HTTP默認端口 : TCP 80

  • Nginx HTTPS默認端口: TCP 443

你可以使用以下命令來測試Nginx配置文件準確性。

/usr/local/nginx/sbin/nginx -t

將會輸出:
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
執行以下命令來重新加載配置文件。

/usr/local/nginx/sbin/nginx -s reload

執行以下命令來停止服務器。

/usr/local/nginx/sbin/nginx -s stop

 

一、配置SELinux

安全增強型Linux(SELinux)的是一個Linux內核的功能,它提供支持訪問控制的安全政策保護機制。它可以大部分的***。下面我們來看如何啓動基於centos/RHEL系統的SELinux。


安裝SELinux

rpm -qa | grep selinux

libselinux-1.23.10-2
selinux-policy-targeted-1.23.16-6
如果沒有返回任何結果,代表沒有安裝 SELinux,如果返回了類似上面的結果,則說明系統安裝了 SELinux。

布什值鎖定
運行命令getsebool -a來鎖定系統。

getsebool -a | less

getsebool -a | grep off

getsebool -a | grep o

 

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

服務器上的網頁/html/php文件單獨分區。例如,新建一個分區/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服務器時哪個模塊能開戶或關閉:

./configure –help | less

禁用你用不到的nginx模塊。
(可選項)更改nginx版本名稱。
編輯文件/http/ngx_http_header_filter_module.c:

vi +48 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.conf文件來關閉nginx版本號的顯示。

server_tokens off

 

五、使用mod_security(只適合後端Apache服務器)

mod_security爲Apache提供一個應用程序級的防火牆。爲後端Apache Web服務器安裝mod_security,這會阻止很多注入式***。

 

六、安裝SELinux策略以強化Nginx Web服務器

默認的SELinux不會保護Nginx Web服務器,但是你可以安裝和編譯保護軟件。
1、安裝編譯SELinux所需環境支持

yum -y install selinux-policy-targeted selinux-policy-devel

2、下載SELinux策略以強化Nginx Web服務器。

cd /opt

wget ‘http://downloads.sourceforge.net/project/selinuxnginx/se-ngix_1_0_10.tar.gz?use_mirror=nchc’

3、解壓文件

tar -zxvf se-ngix_1_0_10.tar.gz

4、編譯文件

cd se-ngix_1_0_10/nginx

make

將會輸出如下:
Compiling targeted nginx module
/usr/bin/checkmodule: loading policy configuration from tmp/nginx.tmp
/usr/bin/checkmodule: policy configuration loaded
/usr/bin/checkmodule: writing binary representation (version 6) to tmp/nginx.mod
Creating targeted nginx.pp policy package

rm tmp/nginx.mod.fc tmp/nginx.mod

5、安裝生成的nginx.pp SELinux模塊:

/usr/sbin/semodule -i nginx.pp

七、基於Iptables防火牆的限制

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

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

  • 來自ICMP ping的請求

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

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

#!/bin/bash

IPT=”/sbin/iptables”

#### IPS ######

# Get server public ip

SERVER_IP=$(ifconfig eth0 | grep ‘inet addr:’ | awk -F’inet addr:’ ‘{ print $2}’ | awk ‘{ print $1}’)

LB1_IP=”204.54.1.1″

LB2_IP=”204.54.1.2″

# Do some smart logic so that we can use damm script on LB2 too

OTHER_LB=”"

SERVER_IP=”"

[[ "$SERVER_IP" == "$LB1_IP" ]] && OTHER_LB=”$LB2_IP” || OTHER_LB=”$LB1_IP”

[[ "$OTHER_LB" == "$LB2_IP" ]] && OPP_LB=”$LB1_IP” || OPP_LB=”$LB2_IP”

### IPs ###

PUB_SSH_ONLY=”122.xx.yy.zz/29″

#### FILES #####

BLOCKED_IP_TDB=/root/.fw/blocked.ip.txt

SPOOFIP=”127.0.0.0/8 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8 169.254.0.0/16 0.0.0.0/8 240.0.0.0/4 255.255.255.255/32 168.254.0.0/16 224.0.0.0/4 240.0.0.0/5 248.0.0.0/5 192.0.2.0/24″

BADIPS=$( [[ -f ${BLOCKED_IP_TDB} ]] && egrep -v “^#|^$” ${BLOCKED_IP_TDB})

### Interfaces ###

PUB_IF=”eth0″   # public interface

LO_IF=”lo”      # loopback

***_IF=”eth1″   # *** / private net

### start firewall ###

echo “Setting LB1 $(hostname) Firewall…”

# DROP and close everything

$IPT -P INPUT DROP

$IPT -P OUTPUT DROP

$IPT -P FORWARD DROP

# Unlimited lo access

$IPT -A INPUT -i ${LO_IF} -j ACCEPT

$IPT -A OUTPUT -o ${LO_IF} -j ACCEPT

# Unlimited *** / pnet access

$IPT -A INPUT -i ${***_IF} -j ACCEPT

$IPT -A OUTPUT -o ${***_IF} -j ACCEPT

# Drop sync

$IPT -A INPUT -i ${PUB_IF} -p tcp ! –syn -m state –state NEW -j DROP

# Drop Fragments

$IPT -A INPUT -i ${PUB_IF} -f -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL FIN,URG,PSH -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL ALL -j DROP

# Drop NULL packets

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL NONE -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” NULL Packets “

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL NONE -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,RST SYN,RST -j DROP

# Drop XMAS

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,FIN SYN,FIN -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” XMAS Packets “

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,FIN SYN,FIN -j DROP

# Drop FIN packet scans

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags FIN,ACK FIN -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” Fin Packets Scan “

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags FIN,ACK FIN -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

# Log and get rid of broadcast / multicast and invalid

$IPT  -A INPUT -i ${PUB_IF} -m pkttype –pkt-type broadcast -j LOG –log-prefix ” Broadcast “

$IPT  -A INPUT -i ${PUB_IF} -m pkttype –pkt-type broadcast -j DROP

$IPT  -A INPUT -i ${PUB_IF} -m pkttype –pkt-type multicast -j LOG –log-prefix ” Multicast “

$IPT  -A INPUT -i ${PUB_IF} -m pkttype –pkt-type multicast -j DROP

$IPT  -A INPUT -i ${PUB_IF} -m state –state INVALID -j LOG –log-prefix ” Invalid “

$IPT  -A INPUT -i ${PUB_IF} -m state –state INVALID -j DROP

# Log and block spoofed ips

$IPT -N spooflist

for ipblock in $SPOOFIP

do

$IPT -A spooflist -i ${PUB_IF} -s $ipblock -j LOG –log-prefix ” SPOOF List Block “

$IPT -A spooflist -i ${PUB_IF} -s $ipblock -j DROP

done

$IPT -I INPUT -j spooflist

$IPT -I OUTPUT -j spooflist

$IPT -I FORWARD -j spooflist

# Allow ssh only from selected public ips

for ip in ${PUB_SSH_ONLY}

do

$IPT -A INPUT -i ${PUB_IF} -s ${ip} -p tcp -d ${SERVER_IP} –destination-port 22 -j ACCEPT

$IPT -A OUTPUT -o ${PUB_IF} -d ${ip} -p tcp -s ${SERVER_IP} –sport 22 -j ACCEPT

done

# allow incoming ICMP ping pong stuff

$IPT -A INPUT -i ${PUB_IF} -p icmp –icmp-type 8 -s 0/0 -m state –state NEW,ESTABLISHED,RELATED -m limit –limit 30/sec  -j ACCEPT

$IPT -A OUTPUT -o ${PUB_IF} -p icmp –icmp-type 0 -d 0/0 -m state –state ESTABLISHED,RELATED -j ACCEPT

# allow incoming HTTP port 80

$IPT -A INPUT -i ${PUB_IF} -p tcp -s 0/0 –sport 1024:65535 –dport 80 -m state –state NEW,ESTABLISHED -j ACCEPT

$IPT -A OUTPUT -o ${PUB_IF} -p tcp –sport 80 -d 0/0 –dport 1024:65535 -m state –state ESTABLISHED -j ACCEPT

# allow outgoing ntp

$IPT -A OUTPUT -o ${PUB_IF} -p udp –dport 123 -m state –state NEW,ESTABLISHED -j ACCEPT

$IPT -A INPUT -i ${PUB_IF} -p udp –sport 123 -m state –state ESTABLISHED -j ACCEPT

# allow outgoing smtp

$IPT -A OUTPUT -o ${PUB_IF} -p tcp –dport 25 -m state –state NEW,ESTABLISHED -j ACCEPT

$IPT -A INPUT -i ${PUB_IF} -p tcp –sport 25 -m state –state ESTABLISHED -j ACCEPT

### add your other rules here ####

#######################

# drop and log everything else

$IPT -A INPUT -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” DEFAULT DROP “

$IPT -A INPUT -j DROP

exit 0

 

八、控制緩衝區溢出***

編輯nginx.conf,爲所有客戶端設置緩衝區的大小限制。

vi /usr/local/nginx/conf/nginx.conf

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

## Start: Size Limits & Buffer Overflows ##

client_body_buffer_size  1K;

client_header_buffer_size 1k;

client_max_body_size 1k;

large_client_header_buffers 2 1k;

## END: Size Limits & Buffer Overflows ##

解釋:
1、client_body_buffer_size 1k-(默認8k或16k)這個指令可以指定連接請求實體的緩衝區大小。如果連接請求超過緩存區指定的值,那麼這些請求實體的整體或部分將嘗試寫入一個臨時文件。
2、client_header_buffer_size 1k-指令指定客戶端請求頭部的緩衝區大小。絕大多數情況下一個請求頭不會大於1k,不過如果有來自於wap客戶端的較大的cookie它可能會大於 1k,Nginx將分配給它一個更大的緩衝區,這個值可以在large_client_header_buffers裏面設置。
3、client_max_body_size 1k-指令指定允許客戶端連接的最大請求實體大小,它出現在請求頭部的Content-Length字段。
如果請求大於指定的值,客戶端將收到一個”Request Entity Too Large” (413)錯誤。記住,瀏覽器並不知道怎樣顯示這個錯誤。
4、large_client_header_buffers-指定客戶端一些比較大的請求頭使用的緩衝區數量和大小。請求字段不能大於一個緩衝區大小,如果客戶端發送一個比較大的頭,nginx將返回”Request URI too large” (414)
同樣,請求的頭部最長字段不能大於一個緩衝區,否則服務器將返回”Bad request” (400)。緩衝區只在需求時分開。默認一個緩衝區大小爲操作系統中分頁文件大小,通常是4k或8k,如果一個連接請求最終將狀態轉換爲keep- alive,它所佔用的緩衝區將被釋放。
你還需要控制超時來提高服務器性能並與客戶端斷開連接。按照如下編輯:

## Start: Timeouts ##

client_body_timeout   10;

client_header_timeout 10;

keepalive_timeout     5 5;

send_timeout          10;

## End: Timeouts ##

1、client_body_timeout 10;-指令指定讀取請求實體的超時時間。這裏的超時是指一個請求實體沒有進入讀取步驟,如果連接超過這個時間而客戶端沒有任何響應,Nginx將返回一個”Request time out” (408)錯誤。
2、client_header_timeout 10;-指令指定讀取客戶端請求頭標題的超時時間。這裏的超時是指一個請求頭沒有進入讀取步驟,如果連接超過這個時間而客戶端沒有任何響應,Nginx將返回一個”Request time out” (408)錯誤。
3、keepalive_timeout 5 5; – 參數的第一個值指定了客戶端與服務器長連接的超時時間,超過這個時間,服務器將關閉連接。參數的第二個值(可選)指定了應答頭中Keep-Alive: timeout=time的time值,這個值可以使一些瀏覽器知道什麼時候關閉連接,以便服務器不用重複關閉,如果不指定這個參數,nginx不會在應 答頭中發送Keep-Alive信息。(但這並不是指怎樣將一個連接“Keep-Alive”)參數的這兩個值可以不相同。
4、send_timeout 10; 指令指定了發送給客戶端應答後的超時時間,Timeout是指沒有進入完整established狀態,只完成了兩次握手,如果超過這個時間客戶端沒有任何響應,nginx將關閉連接。

 

九、控制併發連接

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

  1. ### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###

  2. ### 1m can handle 32000 sessions with 32 bytes/session, set to 5m x 32000 session ###

  3. limit_zone slimits $binary_remote_addr 5m;

  4. ### Control maximum number of simultaneous connections for one session i.e. ###

  5. ### restricts the amount of connections from a single ip address ###

  6. limit_conn slimits 5;

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

 

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

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

## Only requests to our Host are allowed i.e. nixcraft.in, p_w_picpaths.nixcraft.in and www.nixcraft.in

if ($host !~ ^(nixcraft.in|www.nixcraft.in|p_w_picpaths.nixcraft.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 /p_w_picpaths/ {

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 ^/p_w_picpaths/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-p_w_picpaths/ and /delta/ directories ###

location ~ /(personal-p_w_picpaths/.*|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:

/usr/local/nginx/sbin/nginx -s reload

 

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

file_uploads = Off

# 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或者第三方程序。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章