本篇文章詳細的講訴了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 attacknet.ipv4.icmp_echo_ignore_broadcasts = 1# Turn on protection for bad icmp error messagesnet.ipv4.icmp_ignore_bogus_error_responses = 1# Turn on syncookies for SYN flood attack protectionnet.ipv4.tcp_syncookies = 1# Turn on and log spoofed, source routed, and redirect packetsnet.ipv4.conf.all.log_martians = 1net.ipv4.conf.default.log_martians = 1# No source routed packets herenet.ipv4.conf.all.accept_source_route = 0net.ipv4.conf.default.accept_source_route = 0# Turn on reverse path filteringnet.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1# Make sure no one can alter the routing tablesnet.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv4.conf.all.secure_redirects = 0net.ipv4.conf.default.secure_redirects = 0# Don't act as a routernet.ipv4.ip_forward = 0net.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0# Turn on execshildkernel.exec-shield = 1kernel.randomize_va_space = 1# Tuen IPv6net.ipv6.conf.default.router_solicitations = 0net.ipv6.conf.default.accept_ra_rtr_pref = 0net.ipv6.conf.default.accept_ra_pinfo = 0net.ipv6.conf.default.accept_ra_defrtr = 0net.ipv6.conf.default.autoconf = 0net.ipv6.conf.default.dad_transmits = 0net.ipv6.conf.default.max_addresses = 1# Optimization for port usefor LBs# Increase system file descriptor limitfs.file-max = 65535# Allow for more PIDs (to reduce rollover problems); may break some programs 32768kernel.pid_max = 65536# Increase system IP port limitsnet.ipv4.ip_local_port_range = 2000 65000# Increase TCP max buffer size setable using setsockopt()net.ipv4.tcp_rmem = 4096 87380 8388608net.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 etcnet.core.rmem_max = 8388608net.core.wmem_max = 8388608net.core.netdev_max_backlog = 5000net.ipv4.tcp_window_scaling = 1
四、刪除所有不需要的Nginx模塊
你需要直接通過編譯Nginx源代碼使模塊數量最少化。通過限制只允許web服務器訪問模塊把風險降到最低。你可以只配置安裝nginx你所需要的模塊。例如,禁用SSL和autoindex模塊你可以執行以下命令:
./configure –without-http_autoindex_module –without-http_ssi_modulemake && 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防火墻的限制
下面的防火墻腳本阻止任何除了允許:
六、控制緩沖區溢出攻擊
編輯和設置所有客戶端緩沖區的大小限制如下:
client_body_buffer_size 1K;client_header_buffer_size 1k;client_max_body_size 1k;large_client_header_buffers 2 1k;
你還需要控制超時來提高服務器性能并與客戶端斷開連接。按照如下編輯:
client_body_timeout 10;client_header_timeout 10;keepalive_timeout 5 5;send_timeout 10;
七、控制并發連接
你可以使用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方法的介紹
十、如何拒絕一些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 linkinglocation /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/confopenssl genrsa -des3 -out server.key 1024openssl req -new -key server.key -out server.csrcp server.key server.key.orgopenssl rsa -in server.key.org -out server.keyopenssl 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 functionsdisable_functions = phpinfo, system, mail, exec## Try to limit resources ### Maximum execution time of each script, in secondsmax_execution_time = 30# Maximum amount of time each script may spend parsing request datamax_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 usersdisplay_errors = Off# Turn on safe modesafe_mode = On# Only allow access to executables in isolated directorysafe_mode_exec_dir = php-required-executables-path# Limit external access to PHP environmentsafe_mode_allowed_env_vars = PHP_# Restrict PHP information leakageexpose_php = Off# Log all errorslog_errors = On# Do not register globals for input dataregister_globals = Off# Minimize allowable PHP post sizepost_max_size = 1K# Ensure PHP redirects appropriatelycgi.force_redirect = 0# Disallow uploading unless necessary# Enable SQL safe modesql.safe_mode = On# Avoid Opening remote filesallow_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 DROPservice iptables save
請根據你的具體情況來設置限制的連接數。
十七、配置操作系統保護Web服務器
像以上介紹的啟動SELinux.正確設置/nginx文檔根目錄的權限。Nginx以用戶nginx運行。但是根目錄(/nginx或者/usr /local/nginx/html)不應該設置屬于用戶nginx或對用戶nginx可寫。找出錯誤權限的文件可以使用如下命令:
find /nginx -user nginxfind /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或者第三方程序。
新聞熱點
疑難解答