萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

配置 Fail2ban 保護 Apache HTTP 伺服器:啟用內建 Jail 並自訂防禦規則

生產環境 Apache 面臨暴力破解、惡意掃描、漏洞探測、垃圾郵件機器人等攻擊。Fail2ban 透過分析存取/錯誤日誌,自動以 iptables 封鎖惡意 IP,是輕量級入侵防禦利器。本文示範在 Debian/Ubuntu 及 CentOS/RHEL 上啟用內建 Apache Jail 並說明管理操作。

Fail2ban Jail 核心概念

Jail = 一組保護特定服務的策略,包含:

  • [name]:Jail 名稱
  • enabled:是否啟用
  • port:保護的埠(數字或服務名)
  • filter:日誌分析規則(對應 /etc/fail2ban/filter.d/)
  • logpath:監控的日誌檔路徑
  • maxretry:觸發封鎖前允許失敗次數
  • banaction:封鎖動作(預設 iptables-multiport)

配置檔 /etc/fail2ban/jail.local 覆蓋預設值,避免修改原始 jail.conf。

Debian/Ubuntu 啟用 Apache Jail

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

CentOS/RHEL/Fedora 啟用 Apache Jail

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

監控與手動管理封鎖狀態

  • 查看啟用的 Jail 列表:sudo fail2ban-client status
  • 查看特定 Jail 狀態(含被封 IP):sudo fail2ban-client status apache
  • 手動封鎖 IP:sudo fail2ban-client set apache banip 1.2.3.4
  • 手動解封 IP:sudo fail2ban-client set apache unbanip 1.2.3.4

進階建議

  • 根據實際日誌格式調整 filter.d 正則,減少誤判。
  • 整合 action.d 發送郵件/Slack/Webhook 通知。
  • 定期檢視 /var/log/fail2ban.log 分析攻擊趨勢。
  • 參考官方 GitHub:https://github.com/fail2ban/fail2ban 獲取最新 Jail/Filter 範例。
copyright © 萬盛學電腦網 all rights reserved