Skip to content

Commit

Permalink
Add IP blocking/safelisting
Browse files Browse the repository at this point in the history
  • Loading branch information
BGMP committed Jan 25, 2025
1 parent b58bce6 commit 36f1921
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ gem 'omniauth', '~> 2.1', '>= 2.1.1' # Flexible
gem 'puma', '>= 5.0' # Use the Puma web server [https://github.com/puma/puma]
gem 'rails', '~> 7.1' # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem 'recaptcha', '~> 5.18' # Helpers for the reCAPTCHA API
gem 'rack-attack', '~> 6.7' # A rack middleware for throttling and blocking abusive requests
gem 'redcarpet', '~> 3.6' # The safe Markdown parser, reloaded
gem 'redis', '>= 4.0.1' # Use Redis adapter to run Action Cable in production
gem 'responders', '~> 3.1' # A set of Rails responders to dry up your application
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ GEM
nio4r (~> 2.0)
racc (1.8.1)
rack (3.1.8)
rack-attack (6.7.0)
rack (>= 1.0, < 4)
rack-mini-profiler (3.1.1)
rack (>= 1.2.0)
rack-protection (3.0.6)
Expand Down Expand Up @@ -487,6 +489,7 @@ DEPENDENCIES
mongoid (~> 8.1, >= 8.1.3)
omniauth (~> 2.1, >= 2.1.1)
puma (>= 5.0)
rack-attack (~> 6.7)
rack-mini-profiler (~> 3.1, >= 3.1.1)
rails (~> 7.1)
recaptcha (~> 5.18)
Expand Down
47 changes: 47 additions & 0 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Rack::Attack
BLOCKED_RANGES = %w(
51.222.253 85.208.96 195.191.219 91.242.162
193.169 45.155 89.104 193.27 185.191
)

ALLOWED_CRAWLERS = {
'google' => {
ips: ['66.249'],
agent: /Googlebot/i
},
'bing' => {
ips: ['114.119', '40.74', '157.55.39', '199.30.228', '207.46.13'],
agent: /Bingbot/i
},
'apple' => {
ips: ['17'],
agent: /Applebot/i
},
'linkedin' => {
ips: ['52.142'],
agent: /LinkedInBot/i
},
'gpt' => {
ips: ['20.74'],
agent: /GPTBot/i
}
}

# Block malicious IPs
blocklist('block bad ips') do |req|
BLOCKED_RANGES.any? { |range| req.ip.start_with?(range) }
end

# Allow legitimate crawlers
ALLOWED_CRAWLERS.each do |name, config|
safelist("allow #{name}") do |req|
config[:ips].any? { |ip| req.ip.start_with?(ip) } &&
req.user_agent =~ config[:agent]
end
end

# Rate limiting
throttle('req/ip', limit: 1000, period: 5.minutes) do |req|
req.ip unless req.path.start_with?('/assets/')
end
end

0 comments on commit 36f1921

Please sign in to comment.