Rails Using Kickstarter IP Attack Rack Blacklist with Cloudflare

Rails app using Kickstarter rack-attack

In 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. Now req.ip is the cloud IP address, and the actual IP address of the end user

I had a similar problem when trying to save a user's IP address in my server logs (this is saving Cloudflare IP addresses). To fix this, I added the following to the 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 for using HTTP_CF_CONNECTING_IP as req.ip in a rack?

+5
source share
2 answers

Try adding:

 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 
+4
source

If you want to solve the problem for both ActionPack and Rack :: Attack :: Request , you can do this:

 module ActionPack module Cloudflare module Request def remote_ip remote_ip_cloudflare || super end private def remote_ip_cloudflare @env['HTTP_CF_CONNECTING_IP'] end end end end ActionDispatch::Request.class_eval do prepend ActionPack::Cloudflare::Request end Rack::Attack::Request.class_eval do prepend ActionPack::Cloudflare::Request end 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1200286/


All Articles