fail2ban 阻擋CC (以CentOS測試)

原理:該服務過濾log,若有同一IP在某個區間內頻繁訪問,則設置禁止訪問

此測試 CentOS搭配WEB服務器平台nginx

安裝
1.centos6下,直接加入 EPEL 套件庫
yum -y install http://mirror01.idc.hinet.net/EPEL/6/x86_64/epel-release-6-8.noarch.rpm

centos7 加入 EPEL 套件庫
yum install epel-release

2.yum install fail2ban -y

設定篇
1.建立過濾原則
vi /etc/fail2ban/filter.d/nginx-req-limit.conf
-----貼入以下資料-----
[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 =
----------------------
調整fail2ban的log輸出路徑,編輯fail2ban設定檔
mkdir /var/log/fail2ban
vi /etc/fail2ban/fail2ban.conf
調整 logtarget的路徑
logtarget = /var/log/fail2ban/fail2ban.log


2.修改/etc/fail2ban/jail.conf,增加

vi /etc/fail2ban/jail.conf
-----貼入以下資料-----
[nginx-req-limit]
 
enabled = true
port = http,https
filter = nginx-req-limit
logpath = /var/log/nginx/access.log
findtime = 60
bantime = 300
maxretry = 60
----------------------
filter = nginx-req-limit     #載入在/etc/fail2ban/filter.d的過濾原則
logpath = /var/log/nginx/access.log #對應的log檔,此範例為nginx的log
findtime = 60         #時間範圍,秒
bantime = 300        #封鎖時間,秒
maxretry = 60        #訪問次數
----------------------
以上的限制就會是:同1個IP,每60秒訪問超過100次則封鎖600秒
※若需新增白名單,編輯 /etc/fail2ban/jail.conf,在ignoreip新增IP
vi /etc/fail2ban/jail.conf
ignoreip = 127.0.0.1/8 192.168.1.1/32  ※以空白間隔開來即可

開啟服務與設置開機自動啟動
chkconfig fail2ban on && service fail2ban start
sync;sync;sync

3.查看目前封鎖IP、與解除IP
查看封鎖IP(REJECT是封鎖IP)
iptables -L
Chain f2b-nginx-req-limit (1 references)
target     prot opt source               destination
REJECT     all  --  192.168.1.1        anywhere            reject-with icmp-port-unreachable
RETURN     all  --  anywhere             anywhere

手動解除IP
iptables -D f2b-nginx-req-limit -s 192.168.1.1 -j REJECT


參考資料
安裝部分:https://blog.xuite.net/tolarku/blog/64894490-%E5%9C%A8+CentOS+%E4%B8%8A%E5%AE%89%E8%A3%9D+Fail2ban
設定部分:https://lord.pub/2015/08/04/fail2ban-nginx-ddos-protection/
解除IP:https://linux.cn/article-6718-1.html

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *