Nginx (執筆時点では 1.14.1) で次のようなシンプルな HTTP 基本認証を設定するとします。
server {
...
location / {
auth basic "HTTP Auth Required";
auth basic user file "/path/to/htpasswd";
}
}
... 失敗したログイン試行にレート制限を適用するにはどうすればよいでしょうか。たとえば、30 秒以内に 10 回のログイン試行が失敗した場合、そのソース IP が 1 時間サイトにアクセスできないようにしたいとします。limit_req_zone
および関連ディレクティブを利用したいと考えていますが、リクエストの認証状態にフックする方法が見つかりません。
これは、次の実際の例のようなものを使用して、スティック テーブルと ACL を備えた HAproxy では非常に簡単です。
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
このアプローチを使用したり、外部認証メカニズムをauth_request
location
ブロックするためのリクエスト制限を適用したりすることなく、Nginx でこれが可能ですか?
答え1
fail2ban を使用し、その後 nginx 用の jail を使用することもできます。
答え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;
}
注意: これは認証が失敗した後にのみ有効になるため、次のリクエストを遅らせるにはバースト制限を調整する必要があります。この方法でブルートフォース攻撃から保護できるかどうかはわかりません。