生產環境 Apache 面臨暴力破解、惡意掃描、漏洞探測、垃圾郵件機器人等攻擊。Fail2ban 透過分析存取/錯誤日誌,自動以 iptables 封鎖惡意 IP,是輕量級入侵防禦利器。本文示範在 Debian/Ubuntu 及 CentOS/RHEL 上啟用內建 Apache Jail 並說明管理操作。
Jail = 一組保護特定服務的策略,包含:
[name]:Jail 名稱enabled:是否啟用port:保護的埠(數字或服務名)filter:日誌分析規則(對應 /etc/fail2ban/filter.d/)logpath:監控的日誌檔路徑maxretry:觸發封鎖前允許失敗次數banaction:封鎖動作(預設 iptables-multiport)配置檔 /etc/fail2ban/jail.local 覆蓋預設值,避免修改原始 jail.conf。
sudo vi /etc/fail2ban/jail.local # 密碼驗證失敗 [apache] enabled = true port = http,https filter = apache-auth logpath = /var/log/apache*/*error.log maxretry = 6 # 掃描腳本漏洞 (phpMyAdmin, WordPress 等) [apache-noscript] enabled = true port = http,https filter = apache-noscript logpath = /var/log/apache*/*error.log maxretry = 6 # Apache 溢位攻擊 [apache-overflows] enabled = true port = http,https filter = apache-overflows logpath = /var/log/apache*/*error.log maxretry = 2 # 找不到主目錄 [apache-nohome] enabled = true port = http,https filter = apache-nohome logpath = /var/log/apache*/*error.log maxretry = 2
重啟生效:sudo service fail2ban restart
sudo vi /etc/fail2ban/jail.local [apache] enabled = true port = http,https filter = apache-auth logpath = /var/log/httpd/*error_log maxretry = 6 # 垃圾郵件機器人搜集 Email [apache-badbots] enabled = true port = http,https filter = apache-badbots logpath = /var/log/httpd/*access_log bantime = 172800 maxretry = 1 [apache-noscript] enabled = true port = http,https filter = apache-noscript logpath = /var/log/httpd/*error_log maxretry = 6 [apache-overflows] enabled = true port = http,https filter = apache-overflows logpath = /var/log/httpd/*error_log maxretry = 2 [apache-nohome] enabled = true port = http,https filter = apache-nohome logpath = /var/log/httpd/*error_log maxretry = 2 # 針對熱門 Web 應用不存在腳本的掃描 [apache-botsearch] enabled = true port = http,https filter = apache-botsearch logpath = /var/log/httpd/*error_log maxretry = 2
重啟:
CentOS 7 / Fedora:sudo systemctl restart fail2ban
CentOS 6:sudo service fail2ban restart
sudo fail2ban-client statussudo fail2ban-client status apachesudo fail2ban-client set apache banip 1.2.3.4sudo fail2ban-client set apache unbanip 1.2.3.4filter.d 正則,減少誤判。action.d 發送郵件/Slack/Webhook 通知。/var/log/fail2ban.log 分析攻擊趨勢。