mirror of
https://github.com/samsonjs/rack-attack.git
synced 2026-04-27 15:07:41 +00:00
Fail2Ban helper
based on gist from @ktheory https://gist.github.com/ktheory/5723534 Modified slightly to use fail2ban `filter` terminology to simplify Rack::Attack initializer configuration (only one block is requred for this approach instead of 2)
This commit is contained in:
parent
6c259ea9be
commit
3f1c98a868
2 changed files with 43 additions and 0 deletions
|
|
@ -7,6 +7,7 @@ module Rack::Attack
|
||||||
autoload :Blacklist, 'rack/attack/blacklist'
|
autoload :Blacklist, 'rack/attack/blacklist'
|
||||||
autoload :Track, 'rack/attack/track'
|
autoload :Track, 'rack/attack/track'
|
||||||
autoload :StoreProxy,'rack/attack/store_proxy'
|
autoload :StoreProxy,'rack/attack/store_proxy'
|
||||||
|
autoload :Fail2Ban, 'rack/attack/fail2ban'
|
||||||
|
|
||||||
class << self
|
class << self
|
||||||
|
|
||||||
|
|
|
||||||
42
lib/rack/attack/fail2ban.rb
Normal file
42
lib/rack/attack/fail2ban.rb
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
module Rack
|
||||||
|
module Attack
|
||||||
|
class Fail2Ban
|
||||||
|
class << self
|
||||||
|
def filter(name, discriminator, options)
|
||||||
|
bantime = options[:bantime] or raise ArgumentError, "Must pass bantime option"
|
||||||
|
findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option"
|
||||||
|
maxretry = options[:maxretry] or raise ArgumentError, "Must pass maxretry option"
|
||||||
|
|
||||||
|
if yield
|
||||||
|
fail!(name, discriminator, bantime, findtime, maxretry)
|
||||||
|
else
|
||||||
|
banned?(discriminator)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
def fail!(name, discriminator, bantime, findtime, maxretry)
|
||||||
|
count = cache.count("#{name}:#{discriminator}", findtime)
|
||||||
|
if count >= maxretry
|
||||||
|
ban!(discriminator, bantime)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Return true for blacklist
|
||||||
|
true
|
||||||
|
end
|
||||||
|
|
||||||
|
def ban!(discriminator, bantime)
|
||||||
|
cache.write("fail2ban:#{discriminator}", 1, bantime)
|
||||||
|
end
|
||||||
|
|
||||||
|
def banned?(discriminator)
|
||||||
|
cache.read("fail2ban:#{discriminator}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def cache
|
||||||
|
Rack::Attack.cache
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
Loading…
Reference in a new issue