Skip to content

Instantly share code, notes, and snippets.

@etdsoft
Last active March 3, 2023 18:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save etdsoft/8218606 to your computer and use it in GitHub Desktop.
Save etdsoft/8218606 to your computer and use it in GitHub Desktop.
Simple Fail2banNotifier for exception_notification (will submit a pull request and update gist when accepted).See: https://dradisframework.com/academy/knowledge-base/ruby/ruby-on-rails/protect-rails-application-with-fail2ban.html
class Fail2banNotifier
def initialize(options)
@default_options = options
@default_options[:logfile] ||= Rails.root.join('log', 'fail2ban.log')
# Roll over every 30M, keep 10 files
@logger ||= Logger.new(@default_options[:logfile], 10, 30*1024*1024)
end
def call(exception, options={})
env = options[:env]
request = ActionDispatch::Request.new(env)
# <ip> : <exception class> : <method> <path> -- <params>
msg = "%s : %s : %s %s -- %s" % [
request.remote_ip,
exception.class,
request.request_method,
env["PATH_INFO"],
request.filtered_parameters.inspect
]
@logger.error(msg)
end
end
# Custom Rails app jail. Add to /etc/fail2ban/jail.local
[rails-app]
enabled = true
port = http,https
filter = rails-app
logpath = /path/to/app/log/fail2ban.log
bantime = 3600
findtime = 600
maxretry = 10
# Custom Rails app filter. Place in /etc/fail2ban/filter.d/
[Definition]
failregex = : <HOST> :
ignoreregex =
@cdekker
Copy link

cdekker commented Mar 6, 2016

Clean looking code! But am I missing a crucial piece or how is this tying into a, for example, login process? Am I supposed to throw an exception on a failed login that will trigger this fail2ban log? Won't this also trigger on 'regular' exceptions found, rewarding end users with a ban for finding a bug in my code? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment