Skip to main content

Nginx - 搭配Fail2ban檢測封鎖

運行環境

  • Ubuntu 22.04
安裝Fail2ban
# 安裝
apt install fail2ban -y

# 設定開機自動啟動
systemctl enable --now fail2ban

# 複製設定檔
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

設定Fail2ban

編輯/etc/fail2ban/jail.local

[nginx-4xx]
enabled = true
port = 80,443
logpath = %(nginx_access_log)s
maxretry = 10
findtime = 1m
bantime = 1d
[nginx-4xx-repeated]
enabled = true
port = 80,443
logpath = /var/log/fail2ban.log
maxretry = 3
findtime = 7d
bantime = 7d

抓取nginx_access_log判斷port 80 443 連線資訊
1 分鐘內,同 IP 發生 10 次 4xx 錯誤,封鎖 1 天
7 天內,同 IP 因 4xx 錯誤被累計封鎖 3 次,封鎖 7天

設定nginx-4xx

編輯/etc/fail2ban/filter.d/nginx-4xx.conf

[Definition]
failregex = ^<HOST>.*"(GET|POST).*" (400|403|404|444) .*$
ignoreregex =

只要回應4XX都會被偵測

設定nginx-4xx-repeated

編輯/etc/fail2ban/filter.d/nginx-4xx-repeated.conf

[Definition]
failregex = \[nginx-4xx]\s+[Bb]an\s+<HOST>
ignoreregex =
systemctl restart fail2ban
# 顯示 Fail2ban 狀態
fail2ban-client status
# 顯示 Filter 計數
fail2ban-client status nginx-4xx
# 查詢被 ban 的 IP
fail2ban-client get nginx-4xx banip
# 解除被 ban 的 IP
fail2ban-client set nginx-4xx unbanip <IP>
# 加入白名單
fail2ban-client set nginx-4xx addignoreip <IP>