fail2ban是一個通過監(jiān)視系統(tǒng)日志,匹配日志的錯誤信息執(zhí)行相應(yīng)的屏蔽操作(借用防火墻規(guī)則)以達到保護服務(wù)器的工具。
安裝要求
Python2 >= 2.6 or Python >= 3.2 or PyPy
安裝
# 解壓
tar -xzvf fail2ban-0.9.4.tar.gz
cd fail2ban-0.9.4
# 安裝
python setup.py install
# fail2ban將被安裝在python的包目錄中。 其可執(zhí)行腳本被放置到 /usr/bin 目錄下, 配置信息在 /etc/fail2ban
# 測試是否安裝成功
fail2ban-client -h
# 啟動腳本
cp files/redhat-init /etc/init.d/fail2ban
配置
提供兩種配置方式
- 使用配置文件, 在 /etc/fail2ban 目錄下
- 使用fail2ban-client
以配置文件為例:
- fail2ban.conf
該文件為軟件自身的配置,日志界別、日志路徑等等,為默認(rèn)配置即可,無需修改。如有需要,可新建fail2ban.local文件覆蓋需變更的配置即可
- jail.conf
該文件負(fù)責(zé)業(yè)務(wù)配置,官方推薦新建jail.local 或 在jail.d目錄下新建*.conf文件 覆蓋默認(rèn)配置, 因為軟件升級時該文件可能被覆蓋;
現(xiàn)直接以該文件為例, 查閱fail2ban的各配置項。
# 默認(rèn)日志路徑配置(如mail、authpriv、user、ftp等等),依據(jù)系統(tǒng)而定,fail2ban在/etc/fail2ban/目錄下提供了多種系統(tǒng)日志配置文件
before = paths-fedora.conf
# before = paths-debian.conf
[DEFAULT] #全局配置
ignoreip = 127.0.0.1 #忽略的IP列表,該Ip表將不受限制
bantime = 600 #被屏蔽時間, 單位:秒
findtime = 600 #時間間隔,這個時間段內(nèi)超過規(guī)定次數(shù)的主機將會被屏蔽
maxretry = 5 #最大嘗試此時
enabled = false #全局禁止,在jail.local或jail.d/*.conf中開啟相關(guān)聯(lián)的配置
destemail = root@localhost #郵件接收人
sender = root@localhost #郵件發(fā)送人
# action:觸發(fā)后的動作
#只屏蔽主機
action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", proto col="%(protocol)s", chain="%(chain)s"]
#屏蔽主機 并發(fā)送郵件
action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", pro tocol="%(protocol)s", chain="%(chain)s"]
%(mta)s-whois[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
.......
action = %(action_)s #默認(rèn)動作為只屏蔽主機,如需修改,只需在特定服務(wù)下配置該屬性即可
#服務(wù)配置, 以sshd 為例
[sshd]
# 開啟防護
enabled = true
# 動作,只屏蔽(action_為默認(rèn)動作,可省略)
action = %(action_)s
# 時間范圍(s)
findtim = 120
# 時間范圍內(nèi)最大嘗試次數(shù)
maxretry = 3
# 屏蔽時間(s)
bantime = 180
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
#保存后啟動fail2ban
service fail2ban start
驗證功能
#使用另外一臺主機(11.12.109.125)嘗試登陸,故意輸錯3次密碼:
[root@localhost ~]# ssh root@11.12.109.123
root@11.12.109.123's password:
Permission denied, please try again.
root@11.12.109.123's password:
Permission denied, please try again.
root@11.12.109.123's password:
^C
[root@localhost ~]# ssh root@11.12.109.123
ssh: connect to host 11.12.109.123 port 22: Connection refused
#可知道該主機已經(jīng)被屏蔽成功
#在服務(wù)器上查看防火墻規(guī)則
[root@ychost ~]# iptables -nL
#其中有一項Chain f2b-sshd
Chain f2b-sshd (1 references)
target prot opt source destination
REJECT all -- 11.12.109.125 0.0.0.0/0 reject-with icmp-port-unreachable
RETURN all -- 0.0.0.0/0 0.0.0.0/0
# 被屏蔽的主機會在iptables中顯示, 當(dāng)達到設(shè)定的屏蔽時間后,該規(guī)則會自動刪除
至此,fail2ban已經(jīng)配置完成,可防止別人使用ssh暴力破解系統(tǒng)登錄密碼, 至于其它服務(wù)器,用戶可按同樣的方法自己配置。