1. 簡介
CentOS 中使用fail2ban
和firewalld
限制IP攔截cc攻擊
2. 安裝和啟動(dòng)
- 安裝
$ yum -y install fail2ban
安裝后可以使用以下命令查看版本
$ fail2ban-client -V
$ fail2ban-server -V
顯示如下
Fail2Ban v0.9.7
Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors
Copyright of modifications held by their respective authors.
Licensed under the GNU General Public License v2 (GPL).Written by Cyril Jaquier cyril.jaquier@fail2ban.org.
Many contributions by Yaroslav O. Halchenko debian@onerussian.com.
- 停止
$ systemctl stop fail2ban
- 啟動(dòng)
$ systemctl start fail2ban
- 重啟
$ systemctl restart fail2ban
- 開機(jī)啟動(dòng)
$ systemctl enable fail2ban
3. 配置
fail2ban
安裝后有兩個(gè)程序香追,fail2ban-server
和 fail2ban-client
,對應(yīng)的主配置文件是fail2ban.conf
和 jail.conf
。本次主要是修改 fail2ban-client
配置蛤签。
fail2ban
的.conf
配置文件都是可以被.local
覆蓋锌历,所以配置方式建議是添加.local
文件受扳,不修改原來的配置文件鞋真。
- jail.local 配置
$ vim /etc/fail2ban/jail.local
添加默認(rèn)配置
[DEFAULT]
ignoreip = 127.0.0.1/8
bantime = 86400
findtime = 600
maxretry = 5
banaction = firewallcmd-ipset
action = %(action_mwl)s
配置說明
ignoreip:白名單均函,不攔截螟凭,多個(gè)使用
,
分隔
bantime:攔截后禁止訪問的時(shí)間虚青,單位:秒
findtime:檢查的時(shí)間訪問,單位:秒
maxretry:最大失敗次數(shù), 在檢查時(shí)間內(nèi)達(dá)到次數(shù)就攔截
banaction:屏蔽ip的方法赂摆,firewallcmd-ipset
使用fiewallld
屏蔽
- 添加nginx攔截規(guī)則
$ vim /etc/fail2ban/filter.d/nginx-cc.conf
配置如下
[Definition]
failregex = <HOST> -.*- .*HTTP/1.* .* .*$
ignoreregex =
配置說明
failregex :攔截的正則規(guī)則, 可以使用
<HOST>
匹配主機(jī)名和IP地址挟憔;<HOST>
是正則表達(dá)式(?:::f{4,6}:)?(?P<host>\S+)
的別名
- 添加nginx-cc配置到
jail.local中
在jail.local
中添加配置
[nginx-cc]
enabled = true
port = http,https
filter = nginx-cc
action = %(action_mwl)s
maxretry = 200
findtime = 10
bantime = 86400
# 說明注釋
logpath = /var/log/nginx/access.log
以上配置是檢查 “20秒之內(nèi)訪問次數(shù)達(dá)到200次就攔截該IP”。其它的配置說明如下:
enabled :是否開啟檢測
port:檢查的端口
maxretry:最大失敗次數(shù), 在檢查時(shí)間內(nèi)達(dá)到次數(shù)就攔截
bantime:攔截后禁止訪問的時(shí)間烟号,單位:秒
findtime:檢查的時(shí)間訪問绊谭,單位:秒
logpath: 掃描的日志文件,fail2ban
按行掃描此文件汪拥,根據(jù)filter規(guī)則匹配失敗的項(xiàng)目并統(tǒng)計(jì)
注意: 配置文件文件可以換行添加注釋达传,但是不能在配置項(xiàng)后面跟注釋,例如以下的注釋是不允許的,failban
會(huì)檢查配置無效宪赶,將 bantime
設(shè)置成None
宗弯。
bantime = 86400 # 這里不能寫注釋
- 加載配置
重載配置是其生效
$ fail2ban-client reload
4. 其它命令
- 查看攔截狀態(tài)
$ fail2ban-client status nginx-cc
結(jié)果如下, Banned IP list
就是被攔截的IP
Status for the jail: nginx-cc
|- Filter
| |- Currently failed: 1
| |- Total failed: 100
| `- File list: /var/log/nginx/access.log
`- Actions
|- Currently banned: 3
|- Total banned: 3
`- Banned IP list: 101.2.2.1 101.2.2.3 101.2.2.4
- 手動(dòng)攔截IP
$ fail2ban-client set nginx-cc banip 101.2.2.1
- 解除攔截的IP
$ fail2ban-client set nginx-cc unbanip 101.2.2.1
- 檢查配置
修改后可以先使用以下命令檢查配置是否有誤
$ fail2ban-client -d
- 正則規(guī)則檢查
$ fail2ban-regex /var/log/nginx/access.log "<HOST> -.*- .*HTTP/1.* .* .*$"
- 根據(jù)配置文件檢查
fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-cc.conf