Nginx安全配置概述
本指南全面解析Nginx服务器的安全配置细节,具体实施步骤如下。
禁用SELinux与分区挂载
一、禁用SELinux
安全增强型Linux(SELinux)是Linux内核的一项功能,旨在提供基于安全策略的访问控制机制。
然而,SELinux带来的额外安全性与其使用复杂性相比并不成比例,性价比相对较低。
sed -i /SELINUX=enforcing/SELINUX=disabled/ /etc/selinux/config
/usr/sbin/sestatus -v #查看状态
二、通过分区挂载实现最小特权原则
将服务器上Ngin相关的目录单独划分到一个新分区。例如,创建一个新的逻辑分区/dev/sda5,并将其挂载至/nginx目录下。务必确保该挂载点使用了noexec、nodev和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服务器运行所需的模块。例如,若不需要SSL功能和自动索引功能,可执行以下命令进行配置:
./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较大,可能会超出此值。此时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的值,告知浏览器何时关闭连接,从而避免服务器重复关闭操作。若不指定此参数,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个。
域名访问与HTTP方法限制
八、仅允许指定域名访问
若机器人随机扫描服务器上的所有域名,应拒绝此类请求。必须仅允许配置的虚拟域或反向代理请求。无需使用IP地址进行拒绝操作。
if ($host !~ ^(test.in|www.test.in|images.test.in)$ ) {
return 444;
}
九、限制可用的HTTP请求方法
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-Agent拦截与防盗链
十、如何拒绝特定的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
}
目录权限与SSL配置
十二、目录访问限制
可对指定目录设置访问权限。应对所有网站目录逐一配置,仅允许必要的目录访问权限。
通过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;
}
PHP安全与Chroot隔离
十四、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或者第三方程序。