利用 Fail2ban 防止 Nginx 被 DDOS
等了好几天都没有收到信用卡扣费的通知,于是问了下中华电信的扣费周期(请不要问我等了多久才收到回复谢谢)。
信用卡认证后,会于费用产生次月之 6~8 号,向该信用卡扣款。
但是如果客户使用 hicloud 费用达 NT$10,000 者,将会于费用满 NT$10,000 该日之次周,
提前向信用卡扣款。
为了避免我的信用卡被刷爆,今天研究了一下怎样用 fail2ban 防止被 DDOS。
参考文献:
原理其实蛮简单,就是用正则表达式去查看 log 里面有没有同一个 IP 在某个区间段内频繁访问。
在/etc/fail2ban/filter.d/下建立一个新的规则 nginx-req-limit.conf:
1 2 3 4 5 6 7 8 9 10 11 12 |
[Definition] # Option: failregex # Notes.: Regexp to catch a generic call from an IP address. # Values: TEXT # failregex = <HOST> -.*"(GET|POST).*HTTP.*"$ # Option: ignoreregex # Notes.: regex to ignore. If this regex matches, the line is ignored. # Values: TEXT # ignoreregex = |
修改/etc/fail2ban/jail.conf,增加:
1 2 3 4 5 6 7 8 9 |
[nginx-req-limit] enabled = true port = http,https filter = nginx-req-limit logpath = /home/wwwlogs/*nginx.log findtime = 60 bantime = 7200 maxretry = 100 |
这样就是每 60 秒单 IP 只能访问 100 次,对比 log 文件,大概长这个模样:
1 2 |
180.76.15.20 - - [04/Aug/2015:07:14:32 +0800] "GET / HTTP/1.1" 301 178 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" IP.IP.IP.IP - - [04/Aug/2015:21:42:05 +0800] "GET /wp-admin/ HTTP/1.1" 200 12739 "https://icy.asia/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36" |
其实这是一个比较强的规则,所以为了避免误判,关闭一些对缓存文件的 log:
1 2 3 4 5 6 7 8 9 |
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ { expires 30d; access_log off; } location ~ .*\.(js|css)?$ { expires 7d; access_log off; } |
最后重启 nginx 和 fail2ban 即可,重启 fail2ban 时需注意有没有找不到 log 的错误提示。
我把 100 次改成了 3 次测试了一下,效果还不错,果然就打不开网站了,不过 ssh 还正常访问。
1 2 3 4 5 6 7 |
2015-08-04 22:57:33,402 fail2ban.jail : INFO Jail 'nginx-req-limit' started 2015-08-04 22:57:44,439 fail2ban.actions: WARNING [nginx-req-limit] Ban 113.*.*.* 2015-08-04 22:58:11,476 fail2ban.actions: WARNING [nginx-req-limit] Ban 117.*.*.* 2015-08-04 22:58:44,521 fail2ban.actions: WARNING [nginx-req-limit] Unban 113.*.*.* 2015-08-04 22:58:48,534 fail2ban.actions: WARNING [nginx-req-limit] Ban 113.*.*.* 2015-08-04 22:59:11,565 fail2ban.actions: INFO [nginx-req-limit] 117.*.*.* already banned 2015-08-04 22:59:11,565 fail2ban.actions: WARNING [nginx-req-limit] Unban 117.*.*.* |
比较奇怪的是这几天收到的邮件都说流量为 0,不知道是不是因为处于扣费周,总之这是个神奇的事情。
顺带用 ChinaZ 站长工具测了一下,可以看得出来移动的国际宽带出口是最好的,可惜我家没有移动宽带入户,在深圳估计能用上移动宽带的极少。
下面这个测的是首页加载速度: