Block attackers based on request URL in Ruby app


We know that bots and various forms of malicious attacks can pose a significant threat to our applications. These are challenges that we need to have practical defenses against, especially when it comes to protecting sensitive data. Although we often use IP addresses to block these intruders, different ranges of IP addresses can complicate the process.

That's where I come in - for the past three years I've been working with a honeypot, and my observations of its download and scan requests have led to the development of a gem called url_ban_list. In today's article, I'll explain the mechanism behind this gem and show you how you can use it to block bots and attackers based on the requested URL.

Understanding bots and attackers

Bots and attackers are typically programmed to retrieve or "scrape" sensitive data from an application. This data is then used for nefarious purposes-clever, right? Our defense is even smarter.

The URL Ban List Gem

The url_ban_list gem is a simple gem containing a list of suspicious URLs. Attempting to access the banned URLs triggers an immediate response, either blocking the request or redirecting the bot or attacker.

gem 'url_ban_list'

After adding the url_ban_list gem to your Gemfile, you can easily customize it. Just create an initializer with a configuration block, such as for the rack-attack gem.

# config/initializers/rack_attack.rb
class Rack::Attack
  # block bots targeting suspicious URLS - ban for 24 hours
  blocklist('ban-suspicious-url') do |req|
    Rack::Attack::Allow2Ban.filter("ban-get-#{req.ip}-#{OpenSSL::Digest::SHA256.hexdigest(req.user_agent.to_s)}",
                                   maxretry: 0,
                                   findtime: 1.minute,
                                   bantime: 24.hours) do
      ::UrlBanList::URLS.include?(req.path)
    end
  end
end

In this example based on IP and user-agent, we will ban potential bots for 24 hours.

Summary

Perhaps the most important takeaway is the understanding that while IP address blocking remains effective, URL-based blocking provides an additional layer of security to protect sensitive data. The url_ban_list gem provides an intuitive way to block bots and attackers using request URLs, increasing not only application security, but also peace of mind.

Gem link: https://github.com/Oxyconit/url_ban_list

Happy coding!