Rack-attack and Allow2Ban filtering in rails 4

2.1k Views Asked by At

I'm implementing Kickstarter's Rack-attack in my rails app.

The whitelist/blacklist filtering is working properly, but I'm having issues with using Allow2Ban to lock out ip addresses that are hammering my sign_in (Devise) page. Note: im testing this locally and have removed localhost from the whitelist.

# Lockout IP addresses that are hammering your login page.
# After 3 requests in 1 minute, block all requests from that IP for 1 hour.
Rack::Attack.blacklist('allow2ban login scrapers') do |req|
  # `filter` returns false value if request is to your login page (but still
  # increments the count) so request below the limit are not blocked until
  # they hit the limit.  At that point, filter will return true and block.
  Rack::Attack::Allow2Ban.filter(req.ip, :maxretry => 3, :findtime => 1.minute, :bantime => 1.hour) do
    # The count for the IP is incremented if the return value is truthy.
    req.path == '/sign_in' and req.post?
  end
end

In the Rack-attack documentation, it clearly states that caching is required for throttling functionality, ie:

Rack::Attack.throttle('req/ip', :limit => 5, :period => 1.second) do |req| )

, but it doesn't state this for Allow2Ban. Anyone know if cache is required for Allow2Ban, or am I implementing incorrectly with the code above on a Devise sign_in page

1

There are 1 best solutions below

0
On

Yes, Allow2Ban and Fail2Ban definitely need chaching (in https://github.com/kickstarter/rack-attack/blob/master/lib/rack/attack/fail2ban.rb you can see how and why). Btw. I suggest to use Redis as cache because it ensures that your application blocks an IP address even if you are using more than one application node. If you are using Rails cache in a multi-application node scenario, your filters will be managed per instance, which is not what you would want I assume.