在 Nginx(撰寫本文時為 1.14.1)中給出一個簡單的 HTTP 基本驗證設置,如下所示:
server {
...
location / {
auth basic "HTTP Auth Required";
auth basic user file "/path/to/htpasswd";
}
}
...如何對失敗的登入嘗試套用速率限制?例如,如果 30 秒內有 10 次登入嘗試失敗,我想阻止該來源 IP 在一個小時內訪問該網站。我希望利用limit_req_zone
和 相關指令,但找不到一種方法來連接請求的身份驗證狀態。
這在 HAproxy 中相當簡單,使用棒表和 ACL,使用類似以下工作範例的內容。
userlist users
user me password s3cr3t
frontend https.local
...
# Set up the stick table to track our source IPs, both IPv4 & IPv6
stick-table type ipv6 size 100k expire 1h store http_req_rate(30s)
# Check if the user has authenticated
acl auth_ok http_auth(users)
# Track the client IP
http-request track-sc0 src
# Deny the connection if it exceeds 10 requests within the defined
# stick-table period AND if the client isn't authenticated already
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 10 } !auth_ok
# Define the auth realm if the users isn't authenticated and made it this far
http-request auth realm Authorization\ Required unless auth_ok
Nginx 是否可以實現這一點,而無需使用該外部身份驗證機制?auth_request
方法,也不必將請求限制應用於location
阻止
答案1
您也可以使用fail2ban,然後使用nginx 的監獄。
答案2
limit_req_status 429;
auth_basic "-";
auth_basic_user_file "...";
error_page 401 = @nein;
proxy_intercept_errors on; # not needed if not proxying
location / {
# note you cannot use a short circuiting `return` here.
try_files /dev/null =204;
}
location @nein {
internal ;
limit_req zone=<zone>;
# this is the magic trick, `try_files` takes place AFTER `limit_req`.
try_files /dev/null =401;
}
注意:這僅在身份驗證失敗後生效,因此您必須使用突發限制來延遲下一個請求。我什至不確定是否可以通過這種方式保護事物免受暴力攻擊。