站点图标 Linux-技术共享

Linux系统使用fail2ban防止暴力登入攻擊!并记录攻击者IP

image001

自己架設主機時,都很有可能會被暴力SSH登入攻擊,一旦密碼被人試出來了,後果不堪設想,本篇教學使用與設定fail2ban軟體,此軟體可設定當同個IP在幾分鐘內登入失敗次數超過幾次就會被防火牆擋下來。
首先輸入以下指令安裝fail2ban
谷歌或者Oracle先输入: sudo -i
apt -y install fail2ban (Debian等等系统)
yum -y install fail2ban (CentOS等等系统)


當安裝完畢後,會有一個設定檔在/etc/fail2ban/jail.conf,但是假如在下次更新fail2ban的時候這個檔案也會被更新的蓋過,所以我們要輸入以下指令複製出一個jail.local,fail2ban會優先看jail.local這樣之後即使更新也不會遺失原本設定的資料。
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
接著編輯fail2ban設定檔案:
sudo nano /etc/fail2ban/jail.local
這邊介紹一些比較常用的設定參數
ignoreip可用來設定白名單,用於設定哪些IP不會因登入次數超過限制而導致被鎖IP,如果有多個IP可以用空白分開
ignoreip = 127.0.0.1/8 192.168.0.1/16
而bantime findtime maxretry往往會一起被使用,用於設定當多少時間內登入幾次會被鎖幾秒,例如以下的設定就表示為當600秒內登入失敗超過5次就會被鎖800秒,可以依照自己的情況設定。
bantime = 800
findtime = 600
maxretry = 5
而假如想要設定為永久封鎖可以改成:
bantime = -1


而假如伺服器上有架設郵件伺服器,可以設定用寄信來通知封鎖的訊息,destemail為收通知的收信信箱,sender表示用哪個信箱寄信,mta為用哪個service來進行寄信,後面會說如果要啟用寄信通知需要。
destemail = root@localhost
sender = root@localhost
mta = sendmail


而fail2ban有很多種封鎖IP的做法,如果要自定義也可以,其中action_為只封鎖後不做其他事情,而action_mw為封鎖後寄信通知,action_mwl為寄信的信還會含有whois資訊
action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
action_mwl = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
%(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"]
預設為使用action_,可以修改成自己想要的設定
action = %(action_)s


當設定完後必須重新啟動fail2ban才能生效,輸入指令:
sudo service fail2ban restart
這樣被登入太多次失敗就會被封鎖,假如要看哪些IP現在是被封鎖狀態可以輸入以下指令查看
iptables -L   

可以查询到哪些攻击您服务器的IP,并且封禁他!

退出移动版