Nginx:速率限制失败基本身份验证尝试

Jin*_*nKo 5 nginx authentication brute-force-attacks rate-limiting

在 Nginx(撰写本文时为 1.14.1)中给出一个简单的 HTTP 基本身份验证设置,如下所示:

server {
  ...
  location / {
    auth basic "HTTP Auth Required";
    auth basic user file "/path/to/htpasswd";
  }
}
Run Code Online (Sandbox Code Playgroud)

...如何对失败的登录尝试应用速率限制?例如,如果 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
Run Code Online (Sandbox Code Playgroud)

Nginx 是否可以实现这一点,而无需使用auth_request方法,也不必将请求限制应用于location阻止外部身份验证机制?

小智 0


  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;
  }


Run Code Online (Sandbox Code Playgroud)

注意:这仅在身份验证失败后生效,因此您必须使用突发限制来延迟下一个请求。我什至不确定是否可以通过这种方式保护事物免受暴力攻击。