使用Nginx fail2ban来抵御DDOS攻击
Zhongy0410
・5 分钟阅读
最近我们的一个客户服务器受到了DDOS攻击,我们一起使用Nginx的限制请求模块和fail2ban来阻止了这种攻击。
安装Fail2ban
在Ubuntu/Debian上,运行...
apt-get install fail2ban
配置
有2部分,首先,我们需要配置Nginx来限制IP地址的请求数量,Nginx将把禁止的IP信息记录到错误日志中,fail2ban将解析Nginx错误日志,并且禁止出现错误的IP地址。
Nginx配置
请按照以下文章进行Nginx配置部分。
fail2ban配置
筛选器配置
创建Nginx筛选器file:
vim /etc/fail2ban/filter.d/nginx-req-limit.conf
在其中添加以下内容:
# Fail2Ban configuration file # # supports: ngx_http_limit_req_module module [Definition] failregex = limiting requests, excess:.* by zone.*client: # Option: ignoreregex # Notes.: regex to ignore. If this regex matches, the line is ignored. # Values: TEXT # ignoreregex =
监狱配置
创建新的监狱配置:
vim /etc/fail2ban/jail.local
如果你没有看到jail.local
,只需运行:
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
向末尾添加以下内容:
[nginx-req-limit] enabled = true filter = nginx-req-limit action = iptables-multiport[name=ReqLimit, port="http,https", protocol=tcp] logpath = /var/log/nginx/*error.log findtime = 600 bantime = 7200 maxretry = 10
findtime
和maxretry
值非常重要,它们共同决定了被拒绝的IP被拒绝的频率,如果你让这些值变小,IP将会被更频繁地禁止,根据你的需要调整。
保存配置文件后,请使用以下命令重新启动fail2ban :
service fail2ban restart
测试
在退出shell之前,最好先确定fail2ban是否正常工作。
fail2ban日志
您可以监视fail2ban日志文件:
tail -f /var/log/fail2ban.log
你将看到如下所示的行:
2014-04-28 14:16:02,840 fail2ban.actions: WARNING [nginx-req-limit] Ban 95.211.117.202 2014-04-28 14:16:02,848 fail2ban.actions: WARNING [nginx-req-limit] Ban 78.187.45.204 2014-04-28 14:16:03,857 fail2ban.actions: WARNING [nginx-req-limit] 78.187.45.204 already banned 2014-04-28 14:17:36,952 fail2ban.actions: WARNING [nginx-req-limit] Ban 91.216.201.114
如果你认为有什么需要担心的,请跳到下面的调试部分。
fail2ban-client
你还可以使用以下命令使用fail2ban-client查找特定监狱的状态:
fail2ban-client status nginx-req-limit
这将显示:
Status for the jail: nginx-req-limit |- filter | |- File list: /var/log/nginx/test.com.error.log /var/log/nginx/example.com.error.log | |- Currently failed: 6 | `- Total failed: 389 `- action |- Currently banned: 3 | `- IP list: 95.211.117.202 78.187.45.204 91.216.201.114 `- Total banned: 3
你可以看到有3个IP监狱。
调试
如果事情不能按预期运行,你可以调试fail2ban配置。
检查调试输出
运行以下命令查看fail2ban-server使用的配置:
fail2ban-client -d
调试筛选器
运行以下命令查看fail2ban筛选器是否适用于特定日志文件:
fail2ban-regex /var/log/nginx/example.com.error.log /etc/fail2ban/filter.d/nginx-req-limit.conf
输出将包含以下内容(朝向结束):
Success, the total number of match is 861
如果是零匹配,那么正规表达式过滤器可能有问题。