Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails using kickstarter rack-attack IP blacklisting with Cloudflare

Rails app, using Kickstarter's rack-attack

Within my config/rack-attack.rb file, I have:

class Rack::Attack
  Rack::Attack.blacklist ('block ip') do |req|
    # Request are blocked if the return value is truthy
    '68.888.23.22' == req.ip
    # req.ip if IPCat.datacenter?(req.ip)
  end
end

This worked fine until I started using CloudFlare. The req.ip is now a Cloudflare IP vs that actual end user's IP

I had a similar issue when trying to save the user's IP to my server logs (was saving the Cloudflare IPs). In order to fix this, I added the following to my application controller:

module ActionDispatch
  class Request < Rack::Request
    alias :remote_ip_orig :remote_ip
    def remote_ip
      @remote_ip ||= (@env['HTTP_CF_CONNECTING_IP'] || remote_ip_orig)
    end
  end
end

Is there a similar process in order to use the HTTP_CF_CONNECTING_IP as the req.ip within rack-attack?

like image 971
dmt2989 Avatar asked Aug 14 '14 02:08

dmt2989


1 Answers

Try to add:

class Rack::Attack::Request < ::Rack::Request
  def cf_ip
    @env['HTTP_CF_CONNECTING_IP'] ? @env['HTTP_CF_CONNECTING_IP'] : ip
  end
end

Then you can use:

throttle('req/ip', :limit => 300, :period => 5.minutes) do |req|
  req.cf_ip
end
like image 182
Aldekein Avatar answered Oct 04 '22 05:10

Aldekein