10 Oct
Rack Attack 404 errors and custom response message - Rails Tricks Issue 20
This week I will show you another Rack Attack trick.
But before I get to that, I’d like to let you know that my book is finally done and if you want to learn about how to avoid security issues during code review, you should read it: Secure code review for Rails Developers .
Now let’s get to today's trick. If you don’t want to play whack-a-mole with bots, but and you don’t have a WAF like Wafris set up, you can block hosts if they make too many requests to the 404 page of your site with rack attack. To make this work, you need to redirect all your 404 traffic to a single URL and make sure it goes through your middleware stack instead of hitting the static 404.html file in the public filter. To achieve this, you can setup a custom exception app in config/application.rb
.png)
Then you create a controller and a view, and route 404 errors to that page:
.png)
And in your application controller, you can rescue from ActiveRecord::Notfound and redirect to the error page:
.png)
And the final step is to delete public/404.html.
Now that we have all 404 error pages ending up on /404, let’s add a rule to Rack Attack to block a client if hits more than 5 times the 404 page withing a 3 minutes interval:

This blocking might be triggered by legitimate users too, so I recommend to create a custom response to tell them to contact support in case they got blocked:
.png)
That’s it for this week, until next time!