Enterprise Java

Spring Security: Prevent brute force attack

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 of all 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 regiter 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 probably notice usage of LoginAttemptCacheService loginAttemptCacheService
Let’s implement it. This would be typical grails service

package com.picsel.officeanywhere

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 add next line to BuildConfig.groovy

    dependencies {
        runtime 'com.google.guava:guava:11.0.1'
        }

And the last step add service configuration to cinfig.groovy

brutforce {
    loginAttempts {
        time = 5
        allowedNumberOfAttempts = 3
    }

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

More about Spring Security Events
More about caching with google guava

Grails user can simple use this plugin https://github.com/grygoriy/bruteforcedefender

Happy coding and don’t forget to share!

Reference: Prevent brute force attack with Spring Security from our JCG partner Grygoriy Mykhalyuno at the Grygoriy Mykhalyuno’s blog blog.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Fahad Rafiq
Fahad Rafiq
9 years ago

Password crackers are using automated scripts to target websites to hack the passwords and Brute Force Attacks have become a common thing, but many don’t know the concept behind it and how these attacks are so successful at cracking the passwords of the websites.

The easiest method to block such attacks is by blacklisting the IPs that carry out such abuses, many hosting providers have added Brute Force Attacks protection in their added security features.

For more information about these attacks read: http://www.cloudways.com/blog/what-is-brute-force-attack/

Back to top button