Rack::Attack isn't blocklisting ip addresses

1k Views Asked by At

I have installed and configured Rack::Attack, but the blacklisted ip addresses are still hitting my site constantly.

In config/application.rb:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module MyApp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1
    config.middleware.use Rack::Attack


    ActionController::Base.config.relative_url_root = ''
  end
end

and in initializers/rack_attack.rb

class Rack::Attack

  Rack::Attack.blocklist_ip("46.229.168.154")
  Rack::Attack.blocklist_ip("23.101.169.3")

  RANGE = (IPAddr.new('54.36.0.0').to_i..IPAddr.new('54.38.255.255').to_i)
  Rack::Attack.blocklist('block_local_network')  do|req|
    RANGE.include?(IPAddr.new(req.ip).to_i)
  end


end

After install an configuring, the same ip_addresses are still hitting my site. I got all excited because my traffic was up 5X usual, only to find these spambots having a hayday.

1

There are 1 best solutions below

0
On

Check your safelist to see if there is a range or placeholder for the IP addresses you want to block. If an IP address is covered by the safelist, it will not be blocked even if it is in the blocklist. By the way, your code can be simplified a bit by IP ranges. In addition, IPAddr.new(req.ip).to_i is not necessary, simply use req.ip instead.

RANGE = IPAddr.new '54.36.0.0/14'
puts RANGE.to_range                  # 54.36.0.0..54.39.255.255
puts RANGE.include? '54.36.0.0'      # true
puts RANGE.include? '54.39.255.255'  # true