Security

如何限制 Nginx Auth_Basic 重試?

  • March 12, 2022

我用 Nginx 的 Auth_Basic 模組保護了一個 web 文件夾。問題是,我們可以嘗試多個密碼直到它起作用(暴力攻擊)。有沒有辦法限制重試失敗的次數?

據我所知,Auth Basic模組不支持此功能,但您可以使用Fail2ban來做到這一點。

使用不存在的使用者進行測試,您將在錯誤日誌中看到如下內容:

2012/08/25 10:07:01 [error] 5866#0: *1 no user/password was provided for basic authentication, client: 127.0.0.1, server: localhost, request: "GET /pma HTTP/1.1", host: "localhost:81" 2012/08/25 10:07:04 [error] 5866#0: *1 user "ajfkla" was not found in "/etc/nginx/htpasswd", client: 127.0.0.1, server: localhost, request: "GET /pma HTTP/1.1", host: "localhost:81"

然後創建必要的過濾器:

/etc/fail2ban/filter.d/nginx-auth.conf

[Definition]
failregex = no user/password was provided for basic authentication.*client: <HOST>
             user .* was not found in.*client: <HOST>
             user .* password mismatch.*client: <HOST>
ignoreregex = </host></host></host> 

/etc/fail2ban/jail.conf

[nginx-auth]
enabled = true
filter = nginx-auth
action = iptables[name=NoAuthFailures, port=80, protocol=tcp]
logpath = /var/log/nginx*/*error*.log
bantime = 3600 # 1 hour
maxretry = 3

測試 Fail2Ban 規則:

fail2ban-regex /var/log/nginx/localhost.error_log /etc/fail2ban/filter.d/nginx-auth.conf

Failregex
|- Regular expressions:
|  [1] no user/password was provided for basic authentication.*client: <HOST>
|  [2] user .* was not found in.*client: <HOST>
|  [3] user .* password mismatch.*client: <HOST>
|
`- Number of matches:
  [1] 1 match(es)
  [2] 2 match(es)
  [3] 0 match(es)

Ignoreregex
|- Regular expressions:
|
`- Number of matches:

Summary
=======

Addresses found:
[1]
   127.0.0.1 (Sat Aug 25 10:07:01 2012)
[2]
   127.0.0.1 (Sat Aug 25 10:07:04 2012)
   127.0.0.1 (Sat Aug 25 10:07:07 2012)
[3]

PS:由於 Fail2ban 會獲取要禁止的日誌文件,因此請確保logpath與您的配置匹配。

引用自:https://serverfault.com/questions/421046