SSH 服務暴露於公網必面臨持續的字典攻擊。Fail2Ban 透過掃描日誌 (預設 /var/log/secure、/var/log/auth.log),匹配失敗特徵,自動調用 iptables/nftables/firewalld/tcpd 封鎖惡意 IP,是 Linux 伺服器必備的主動防禦組件。
# 下載源碼 RPM 重建 (避免 0.6.1 時間解析 Bug)
wget https://fail2ban.sourceforge.net/fail2ban-0.6.2-1brn.src.rpm
rpmbuild --rebuild fail2ban-0.6.2-1brn.src.rpm
rpm -Uvh /usr/src/redhat/RPMS/noarch/fail2ban-0.6.2-1brn.noarch.rpm
# 現代發布版直接安裝
# yum install fail2ban / apt install fail2ban / dnf install fail2ban
systemctl enable fail2ban
systemctl start fail2ban
systemctl status fail2ban
# 或傳統
service fail2ban {start|stop|status|restart|condrestart}
| 參數 | 建議值 | 說明 |
|---|---|---|
locale | en_US | 修正時間格式解析 Bug (0.6.1 缺此參數導致失效) |
maxfailures / maxretry | 3-5 | 觸發封鎖的失敗次數 |
findtime | 60-300 | 統計時間窗口 (秒) |
bantime | 3600-86400 | 封鎖時長 (秒),-1 永久 |
backend | systemd / pyinotify / gamin | 日誌讀取後端,systemd journald 最佳 |
action | iptables-multiport / firewallcmd-ipset | 封鎖動作,ipset 效能優於逐條 iptables |
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
backend = systemd
maxretry = 3
findtime = 300
bantime = 86400
action = iptables-allports[name=sshd]
# 或 firewallcmd-ipset[name=sshd] (Firewalld + ipset 高效能)
ignoreip = 127.0.0.1/8 10.0.0.0/8 192.168.0.0/16
# 查看當前封鎖
fail2ban-client status sshd
iptables -L -n -v | grep f2b-sshd
# 即時追蹤日誌
tail -f /var/log/fail2ban.log
# 手動解封
fail2ban-client set sshd unbanip 203.0.113.50
# Nginx 限流/掃描防護
[nginx-botsearch]
enabled = true
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 20
findtime = 60
bantime = 3600
# 針對屢犯 IP 加重懲罰
[recidive]
enabled = true
filter = recidive
logpath = /var/log/fail2ban.log
action = iptables-allports[name=recidive]
bantime = 604800 # 7 天
findtime = 86400 # 1 天
maxretry = 3
ipset 型 action:action = iptables-ipset-proto6[name=sshd],O(1) 查找替代 O(n) 鏈遍歷systemd backend 直接讀 journald,避免檔案 I/O 競爭dbfile (SQLite 資料庫) 放置 tmpfs:dbfile = /run/fail2ban/fail2ban.sqlite3logrotate 管理 /var/log/fail2ban.log 防止磁碟寫滿Fail2Ban 以「日誌分析 + 防火牆聯動」的輕量架構,提供了極高性價比的暴力破解緩解能力。關鍵在於:根據業務流量調整 maxretry/findtime/bantime、善用 ignoreip 避免誤封、升級至 ipset/action 效能模式、建立 Recidive 機制懲罰屢犯。配合 SSH 金鑰認證、非標準埠、Port Knocking、零信任堡壘機,構建多層次 SSH 存取防線。