Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Fail2Ban 實戰部署:阻擋 SSH 暴力破解的自動化防火牆整合指南

編輯:Linux 教學

前言:暴力破解攻擊的自動化緩解利器

SSH 服務暴露於公網必面臨持續的字典攻擊。Fail2Ban 透過掃描日誌 (預設 /var/log/secure、/var/log/auth.log),匹配失敗特徵,自動調用 iptables/nftables/firewalld/tcpd 封鎖惡意 IP,是 Linux 伺服器必備的主動防禦組件。

安裝與編譯 (以 RHEL/CentOS 為例)


# 下載源碼 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}

核心配置檔 : /etc/fail2ban.conf (舊版) / /etc/fail2ban/jail.local (新版)

關鍵參數調優

參數建議值說明
localeen_US修正時間格式解析 Bug (0.6.1 缺此參數導致失效)
maxfailures / maxretry3-5觸發封鎖的失敗次數
findtime60-300統計時間窗口 (秒)
bantime3600-86400封鎖時長 (秒),-1 永久
backendsystemd / pyinotify / gamin日誌讀取後端,systemd journald 最佳
actioniptables-multiport / firewallcmd-ipset封鎖動作,ipset 效能優於逐條 iptables

SSH 專用 Jail 配置範例 (/etc/fail2ban/jail.d/sshd.local)


[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/Apache、Postfix、WordPress、Recidive


# 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.sqlite3
  • 配合 logrotate 管理 /var/log/fail2ban.log 防止磁碟寫滿

結語

Fail2Ban 以「日誌分析 + 防火牆聯動」的輕量架構,提供了極高性價比的暴力破解緩解能力。關鍵在於:根據業務流量調整 maxretry/findtime/bantime、善用 ignoreip 避免誤封、升級至 ipset/action 效能模式、建立 Recidive 機制懲罰屢犯。配合 SSH 金鑰認證、非標準埠、Port Knocking、零信任堡壘機,構建多層次 SSH 存取防線。

Copyright © Windows教程網 All Rights Reserved