Fork me on GitHub

Saturday, 6 October 2012

Prevent brute force attack with Spring Security

,
Spring Security can do lot of stuff for you. Account blocking, password salt. But what about brute force blocker. That what you have to do by yourself. Fortunately spring is quite flexible framework so it is not a big deal to configure it.

Let me show you little guide how to do this for Grails application.

First you have to enable springSecurityEventListener in your Config.groovy
grails.plugins.springsecurity.useSecurityEventListener = true

then implement listeners
in /src/bruteforce create classes
/**
Registers all failed attempts to login. Main purpose to count attempts for particular account ant block user

*/
class AuthenticationFailureListener implements ApplicationListener {

    LoginAttemptCacheService loginAttemptCacheService

    @Override
    void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
        loginAttemptCacheService.failLogin(e.authentication.name)
    }
}

next we have to create listener for successful logins 
in same package
/**
 Listener for successfull logins. Used for reseting number on unsuccessfull logins for specific account
*/
class AuthenticationSuccessEventListener implements ApplicationListener{

    LoginAttemptCacheService loginAttemptCacheService

    @Override
    void onApplicationEvent(AuthenticationSuccessEvent e) {
        loginAttemptCacheService.loginSuccess(e.authentication.name)
    }
}
We were not putting them in our grails-app folder so we need to register these classes as spring beans.
Add next lines into grails-app/conf/spring/resources.groovy
beans = {
    authenticationFailureListener(AuthenticationFailureListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')
    }

    authenticationSuccessEventListener(AuthenticationSuccessEventListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')
    }
}
You've probably notice usage of LoginAttemptCacheService loginAttemptCacheService
Let's implement it. This would be typical grails service 
package com.grygoriy

import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache

import java.util.concurrent.TimeUnit
import org.apache.commons.lang.math.NumberUtils
import javax.annotation.PostConstruct

class LoginAttemptCacheService {

    private LoadingCache attempts;
    private int allowedNumberOfAttempts
    def grailsApplication

    @PostConstruct
    void init() {
        allowedNumberOfAttempts = grailsApplication.config.brutforce.loginAttempts.allowedNumberOfAttempts
        int time = grailsApplication.config.brutforce.loginAttempts.time

        log.info "account block configured for $time minutes"
        attempts = CacheBuilder.newBuilder()
                   .expireAfterWrite(time, TimeUnit.MINUTES)
                   .build({0} as CacheLoader);
    }

    /**
     * Triggers on each unsuccessful login attempt and increases number of attempts in local accumulator
     * @param login - username which is trying to login
     * @return
     */
    def failLogin(String login) {
        def numberOfAttempts = attempts.get(login)
        log.debug "fail login $login previous number for attempts $numberOfAttempts"
        numberOfAttempts++

        if (numberOfAttempts > allowedNumberOfAttempts) {
            blockUser(login)
            attempts.invalidate(login)
        } else {
            attempts.put(login, numberOfAttempts)
        }
    }

    /**
     * Triggers on each successful login attempt and resets number of attempts in local accumulator
     * @param login - username which is login
     */
    def loginSuccess(String login) {
        log.debug "successfull login for $login"
        attempts.invalidate(login)
    }

    /**
     * Disable user account so it would not able to login
     * @param login - username that has to be disabled
     */
    private void blockUser(String login) {
        log.debug "blocking user: $login"
        def user = User.findByUsername(login)
        if (user) {
            user.accountLocked = true;
            user.save(flush: true)
        }
    }
}
We will be using CacheBuilder from google guava library. So please add next lines to BuildConfig.groovy
    dependencies {
        runtime 'com.google.guava:guava:11.0.1'
        }
And the last step we will add service configuration to Config.groovy
brutforce {
    loginAttempts {
        time = 5
        allowedNumberOfAttempts = 3
    }

That is it, you ready to run you application.
For typical java project almost everything will be the same. Same listeners and same services.

More about Spring Security Events
More about caching with Google guava

Grails users can simple use this plugin https://github.com/grygoriy/bruteforcedefender
UPD: Plugin now at http://grails.org/plugin/bruteforce-defender
Enjoy :)

29 comments to “Prevent brute force attack with Spring Security”

  • 8 October 2012 18:36
    Anonymous says:

    Plugin?

    delete
  • 8 October 2012 18:37
    Anonymous says:

    Btw: bad english!

    delete
  • 8 October 2012 20:57

    >> Plugin?
    Plugin! :)

    delete
  • 11 October 2012 04:37
    Anonymous says:

    It's not necessarily brute force attack. Sometimes, people just forgot their password after long vacation.

    If implemented this way and many people got locked because forgot their passwords, The admin would have to do plenty of unlocking requests.

    It's like double edged sword

    delete
  • 11 October 2012 14:12

    Mainly you are right. But I would say it depends on your security policy and how you will use this approach.

    In general use case is that you are configuring some number of fails per period, Like 10 fails per 1 minute. Of cause it can be user but probable brute forcing. About unlocking again, you may configure schedule that will unlock such account for example in 10 minutes. Not bothering user too much, give gives you not bad protection. With policy 10 fails per minute with unblocking after 10 minutes will make brute-force pretty long operation.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 17 January 2013 13:10
    Anonymous says:

    http://ciprofloxacin-antibiotics.info#30152 - cipro Pourtant il nexiste aucun de ce service pour vous faire prescrire un est disponible en doses. cipro Cialis pilules sont largement de consommer cialis en fonction de leur etat probleme de. [url=http://ciprofloxacin-antibiotics.info#30969]cipro[/url] Permettant des erections plus pensez aux sites ou popularite du Cialis partout hommes et a rechercher un vecteur demotion.

    delete
  • 1 February 2013 13:36
    Anonymous says:

    clomid side effects in men | http://buyclomidcheap.webs.com/#15647 - buy clomid cheap online, ovulating on clomid but not pregnant

    delete
  • 2 February 2013 00:38
    Anonymous says:

    pregnancy and clomid | where can i buy clomid over the counter - buying clomid online uk, clomid results

    delete
  • 2 February 2013 13:56
    Anonymous says:

    clomid femara | [url=http://purchaseclomid.jimdo.com/#53389]clomid 50[/url] - buy clomid and nolvadex, gvxa clomid 100mg days 5'9 success stories

    delete
  • 5 May 2013 16:49
    Anonymous says:

    Truly when someone doesn't understand then its up to other viewers that they will help, so here it occurs.

    Here is my webpage; Wholesale Jerseys

    delete
  • 6 May 2013 02:32
    Anonymous says:

    You could definitely see your enthusiasm within the article you write.

    The arena hopes for more passionate writers such as you who aren't afraid to say how they believe. Always follow your heart.

    Take a look at my web page ... Louis Vuitton Outlet Online

    delete
  • 11 May 2013 21:58
    Anonymous says:

    Hi, There's no doubt that your blog could be having browser compatibility problems. Whenever I look at your blog in Safari, it looks fine however when opening in I.E., it has some overlapping issues. I simply wanted to provide you with a quick heads up! Aside from that, great site!

    Here is my homepage ... Michael Kors Bags

    delete
  • 13 May 2013 01:13
    Anonymous says:

    Great web site. A lot of helpful info here. I am sending it to several friends ans additionally sharing in delicious.
    And naturally, thanks to your sweat!

    Also visit my homepage; NFL Jerseys Cheap

    delete
  • 18 May 2013 12:22
    Anonymous says:

    Thank you for sharing your info. I really appreciate your efforts and I will
    be waiting for your further write ups thanks once again.


    Also visit my page :: Cheap Jerseys

    delete
  • 18 May 2013 20:45
    Anonymous says:

    Woah! I'm really digging the template/theme of this website. It's simple, yet effective.
    A lot of times it's hard to get that "perfect balance" between user friendliness and visual appearance. I must say that you've done a excellent job with this.

    Additionally, the blog loads very quick for me on Chrome. Outstanding Blog!


    my web page - Abercrombie France

    delete
  • 19 May 2013 03:05
    Anonymous says:

    Good day very nice website!! Man .. Excellent .. Wonderful .
    . I will bookmark your web site and take the feeds also?
    I'm glad to find so many helpful info here within the submit, we'd like develop extra
    strategies in this regard, thank you for sharing.
    . . . . .

    Feel free to visit my weblog :: Air Jordan Pas Cher

    delete
  • 22 May 2013 07:47
    Anonymous says:

    Magnificent beat ! I wish to apprentice at the same time as you
    amend your web site, how can i subscribe for a blog website?
    The account aided me a acceptable deal. I have been a little bit familiar of this your broadcast provided bright transparent idea

    my web blog; Cheap Jerseys

    delete
  • 22 May 2013 09:23
    Anonymous says:

    Nice post. I learn something new and challenging on websites I stumbleupon every day.
    It will always be exciting to read content from other
    authors and practice something from their web sites.

    Also visit my webpage - Nike Air Jordan

    delete
  • 22 May 2013 11:17
    Anonymous says:

    Excellent beat ! I would like to apprentice while you amend your
    web site, how can i subscribe for a blog web site? The account helped me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear
    idea

    my web site :: Abercrombie and Fitch

    delete
  • 23 May 2013 15:36
    Anonymous says:

    Great beat ! I wish to apprentice while you amend your site, how
    can i subscribe for a blog site? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast offered
    bright clear concept

    Feel free to visit my blog Cheap Louis Vuitton Handbags

    delete
  • 25 May 2013 14:59
    Anonymous says:

    Hi there i am kavin, its my first time to commenting anyplace, when i read this post i thought i could also
    create comment due to this good piece of writing.

    my homepage - Cheap Louis Vuitton Handbags

    delete
  • 26 May 2013 01:39
    Anonymous says:

    Great post. I was checking constantly this blog and I am impressed!
    Extremely useful info particularly the last part :) I care for
    such info much. I was looking for this particular information
    for a long time. Thank you and good luck.


    my blog - Gafas De Sol Oakley

    delete
 

Grygoriy Mykhalyuno Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger