Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Banning people with Rack::Attack
# Gemfile
gem 'rack-attack'
# config/application.rb
config.middleware.use Rack::Attack
# config/initializers/rack_attack.rb
BANNED_DOMAINS = %w(
google-liar.ru
).freeze
BANNED_PATHS = %w(
wp-admin
wp_admin
wp-login
wp_login
/etc/passwd
phpmyadmin
).freeze
Rack::Attack.blocklist('fail2ban pentesters') do |req|
# ::filter returns truthy value if request fails, or
# if it's from a previously banned IP so the request is blocked
Rack::Attack::Fail2Ban.filter(
"pentesters-#{req.ip}",
maxretry: 1,
findtime: 10.minutes,
bantime: 1.day
) do
# The count for the IP is incremented if the return value is truthy
CGI.unescape(req.query_string) =~ %r{/etc/passwd} ||
BANNED_PATHS.any? { |banned_path| req.path.include? banned_path } ||
BANNED_DOMAINS.any? { |banned_domain| req.referer&.include? banned_domain }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.