Skip to content

Instantly share code, notes, and snippets.

@danifr
Forked from drmalex07/README-fail2ban-keycloak.md
Last active April 11, 2022 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danifr/8b4e99bc3a15331cc537caa3c262dfc4 to your computer and use it in GitHub Desktop.
Save danifr/8b4e99bc3a15331cc537caa3c262dfc4 to your computer and use it in GitHub Desktop.
Use fail2ban to block brute-force attacks to keycloak server. #keycloak #fail2ban #brute-force-attack #centos7 #nginx

Tested on Centos 7. Deployent: Keycloak with an Nginx proxy_pass

Add regular-expression filter under /etc/fail2ban/filter.d/keycloak.conf:

[INCLUDES]

before = common.conf

[Definition]

_threadName = [a-z][-_0-9a-z]*(\s[a-z][-_0-9a-z]*)*
_userId = (null|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})
_realmName = ([a-zA-Z][-_a-zA-Z0-9]*)

failregex =
    ^.*WARN\s+\[org\.keycloak\.events\]\s+\(%(_threadName)s\) type=LOGIN_ERROR, realmId=%(_realmName)s, clientId=security-admin-console, userId=%(_userId)s, ipAddress=<HOST> 

ignoreregex = 

Configure a new jail to get keycloak log messages directly from systemd, it will block http (80) and https (443) for the ofending IP. Create the file /etc/fail2ban/jail.d/keycloak.conf:

[keycloak]
enabled  = true
filter   = keycloak
maxretry = 2
findtime = 10 
bantime = 10
action = iptables-multiport[name=NoAuthFailures, port="http,https"]
backend  = systemd
journalmatch = _SYSTEMD_UNIT=keycloak.service

Simulate some failed logins and test your regular expressions:

sudo fail2ban-regex -v /opt/keycloak/standalone/log/server.log /etc/fail2ban/filter.d/keycloak.conf

Restart fail2ban for jail to be enabled:

sudo systemctl restart fail2ban.service

During normal operation of fail2ban, we can check the status of a particular jail:

sudo fail2ban-client status keycloak
@howkymike
Copy link

@danifr Thank you for the write-up, but I suppose there is a typo in the filter file's path - it should be /etc/fail2ban/filter.d/keycloak.conf

@danifr
Copy link
Author

danifr commented Apr 11, 2022

@howkymike you are absolutely right, I just fixed it. Thanks for pointing it out!

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