Skip to content

Instantly share code, notes, and snippets.

@konung
Forked from jwo/application.rb
Created April 10, 2018 14:43
Show Gist options
  • Save konung/8544f72ec4a0c8a1b67b038df75e2ca5 to your computer and use it in GitHub Desktop.
Save konung/8544f72ec4a0c8a1b67b038df75e2ca5 to your computer and use it in GitHub Desktop.
# And, to activate, you need to tell Rails to load it up:
# config/application.rb
config.middleware.insert_before 0, Rack::Attack
require 'resolv'
class Rack::Attack
class Request < ::Rack::Request
def remote_ip
@remote_ip ||= (env['HTTP_X_FORWARDED_FOR'] || ip).to_s
end
end
end
Rack::Attack.throttle('req/ip', :limit => 300, :period => 5.minutes) do |req|
req.remote_ip if ['/assets', '/check'].any? {|path| req.path.starts_with? path }
end
#Rack::Attack.blacklist('block very bad actors') do |req|
# ['10.0.0.1', '192.168.1.30'].include? req.remote_ip
#end
Rack::Attack.blacklist('googlebots who are not googlebots') do |req|
if req.user_agent =~ /Googlebot/i
begin
name = Resolv.getname(req.remote_ip.to_s)
reversed_ip = Resolv.getaddress(name)
resolves_correctly = name.end_with?("googlebot.com") || name.end_with?("google.com")
reverse_resolves = reversed_ip == req.remote_ip.to_s
is_google = resolves_correctly && reverse_resolves
!is_google
rescue Resolv::ResolvError
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment