18、在防火墙级限制每个IP的连接
Web服务器必须时刻关注连接和每秒的连接限制,pf和iptables都可以在访问Nginx服务器之前卡住最终用户。
Linux iptables:每秒卡住的Nginx连接
下面的例子表示如果某个IP在60秒尝试连接到80端口的次数超过了15,iptables将会丢掉来自它的入站连接:
/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 |
BSD PF:每秒卡住的Nginx连接
编辑/etc/pf.conf,做如下更新,下面的命令限制了每个来源的最大连接数为100,15/5指定某时间跨度内的连接数限制,这里就是5秒内的最大连接数为
15,如果有人违背这条规则,将被加入到abusive_ips表,那么他以后就不能再连接了。最后刷新所有状态。
ebserver_ip="202.54.1.1" table block in quick from pass in on $ext_if proto tcp to $webserver_ip port www flags S/SA keep state (max-src-conn 100, max-src-conn-rate 15/5, overload |
请根据你的需要和通信流量调整所有的值(浏览器可能会打开多个连接)。
另外,请参考“PF防火墙脚本示例”(http://bash.cyberciti.biz/firewall/pf-firewall-script/),“iptables防火墙脚本示例”(http://bash.cyberciti.biz/firewall/linux-iptables-firewall-shell-script-for-standalone-server/)。
19、配置操作系统保护Web服务器
除了开启SELinux外,还要给/nginx目录设置正确的权限,运行Nginx的系统用户名是nginx,但在DocumentRoot(/nginx或/usr/local/nginx/html)中的文件不应该
属于该用户,他也不能进行修改。使用下面的命令找出权限设置不当的文件:
# find /nginx -user nginx # find /usr/local/nginx/html -user nginx |
请确保将文件的所有者修改为root或其它用户,一个典型的权限设置如下:
# 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参数,它就会自动删除这些文件。
20、限制出站Nginx连接
攻击者可能要在你的Web服务器上使用如wget等工具下载文件,使用iptables阻止来自Nginx用户的出站连接,ipt_owner模块可以匹配各种包创建者的特征,只有在OUTPUT链中的才有效,在这里,允许vivek用户使用80端口连接外部资源(对RHN访问或通过仓库抓取CentOS更新特别有用)。
/sbin/iptables -A OUTPUT -o eth0 -m owner --uid-owner vivek -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT |
将上述规则添加到你的iptables基础shell脚本中,不允许nginx Web服务器用户连接外部资源。
附送技巧:观察日志和审核
检查日志文件,可以从中找到攻击者的一些行踪和攻击手段。
# grep "/login.php??" /usr/local/nginx/logs/access_log # grep "...etc/passwd" /usr/local/nginx/logs/access_log # egrep -i "denied|error|warn" /usr/local/nginx/logs/error_log |
Auditd服务提供了系统审核功能,启动SELinux事件,认证事件,文件修改,帐户修改等的审核服务,象往常一样首先关闭所有服务,然后打开我在“Linux服务器加固”(http://www.cyberciti.biz/tips/linux-security.html)一文中指出的服务。
总结
通过这些设置,你的Nginx服务器就可以对外提供服务了,但你应该根据应用程序安全需要进一步查看另外的资源。例如,WordPress或其它第三方程序都有其自身的安全要求。
原文:Top 20 Nginx WebServer Best Security Practices 作者:VIVEK GITE
【51CTO.COM 独家翻译,转载请注明出处及作者!】
【编辑推荐】
| 第 1 页:通过/etc/sysctl.conf加固 | 第 2 页:移除所有不需要的Nginx模块 |
| 第 3 页:配置SELinux策略加固Nginx | 第 4 页:通过iptables防火墙设置限制 |
| 第 5 页:控制缓冲区溢出攻击 | 第 6 页:控制并发连接 |
| 第 7 页:如何阻止某些用户代理 | 第 8 页:Nginx和PHP安全技巧 |
| 第 9 页:在防火墙级限制每个IP的连接 |






















