mitm.djigzo.web.services.security.AuthenticationEventListener.java Source code

Java tutorial

Introduction

Here is the source code for mitm.djigzo.web.services.security.AuthenticationEventListener.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Common Development and 
 * Distribution License (CDDL), Common Public License (CPL) the 
 * licensors of this Program grant you additional permission to 
 * convey the resulting work.
 */
package mitm.djigzo.web.services.security;

import mitm.common.event.EventLogger;
import mitm.common.event.EventLoggerFactory;
import mitm.common.util.Check;
import mitm.djigzo.web.services.LoginBanService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.Authentication;
import org.springframework.security.event.authentication.AbstractAuthenticationFailureEvent;
import org.springframework.security.event.authentication.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.event.authentication.AuthenticationFailureCredentialsExpiredEvent;
import org.springframework.security.event.authentication.AuthenticationFailureDisabledEvent;
import org.springframework.security.event.authentication.AuthenticationSuccessEvent;
import org.springframework.security.ui.WebAuthenticationDetails;

/**
 * Spring bean that listens for ApplicationEvent's and logs login events.
 * 
 * @author martijn
 *
 */
public class AuthenticationEventListener implements ApplicationListener {
    private final static Logger logger = LoggerFactory.getLogger(AuthenticationEventListener.class);

    private final static String AUTHENTICATION_FAILURE = "Authentication failure";
    private final static String AUTHENTICATION_SUCCESS = "Authentication success";
    private final static String BAD_CREDENTIALS = "Bad credentials";
    private final static String ACCOUNT_DISABLED = "Account disabled";
    private final static String CREDENTIALS_EXPIRED = "Credentials expired";

    /*
     * The logCategory can be used to differentiate between multiple AuthenticationEventListener instances
     */
    private final String logCategory;

    /*
     * The eventLoggerFactory is used for creating a logger that logs to the back-end
     */
    private EventLoggerFactory eventLoggerFactory;

    /*
     * The LoginBanService is used for the prevention of brute force login attacks
     */
    private LoginBanService loginBanService;

    public AuthenticationEventListener(String logCategory) {
        Check.notNull(logCategory, "logCategory");

        this.logCategory = logCategory;
    }

    public synchronized void setEventLoggerFactory(EventLoggerFactory eventLoggerFactory) {
        this.eventLoggerFactory = eventLoggerFactory;
    }

    private synchronized EventLogger createEventLogger() {
        EventLogger eventLogger = null;

        if (eventLoggerFactory != null) {
            eventLogger = eventLoggerFactory.create();
        }

        return eventLogger;
    }

    public void setLoginBanService(LoginBanService loginBanService) {
        this.loginBanService = loginBanService;
    }

    private void warn(String message) {
        logger.warn(message);

        EventLogger eventLogger = createEventLogger();

        if (eventLogger != null) {
            try {
                eventLogger.warn(logCategory, message);
            } catch (Exception e) {
                /*
                 * Can fail if the back-end is not running
                 */
                logger.error("Error eventLogger#warn.", e);
            }
        }
    }

    private void info(String message) {
        logger.info(message);

        EventLogger eventLogger = createEventLogger();

        if (eventLogger != null) {
            try {
                eventLogger.info(logCategory, message);
            } catch (Exception e) {
                /*
                 * Can fail if the back-end is not running
                 */
                logger.error("Error eventLogger#info.", e);
            }
        }
    }

    private void logAuthenticationFailure(String cause, AbstractAuthenticationFailureEvent event) {
        warn(AUTHENTICATION_FAILURE + ": " + cause + ", Source: " + event.getSource());
    }

    private void logAuthenticationSuccess(AuthenticationSuccessEvent event) {
        info(AUTHENTICATION_SUCCESS + ". Source: " + event.getSource());
    }

    private void badCredentialsEvent(AuthenticationFailureBadCredentialsEvent event) {
        logAuthenticationFailure(BAD_CREDENTIALS, event);

        if (loginBanService != null) {
            Authentication authentication = event.getAuthentication();

            if (authentication != null) {
                Object details = authentication.getDetails();

                if (details instanceof WebAuthenticationDetails) {
                    loginBanService.addFailure(((WebAuthenticationDetails) details).getRemoteAddress(),
                            authentication.getName());
                }
            }
        }
    }

    private void logUserBanned(BannedApplicationEvent event) {
        warn(AUTHENTICATION_FAILURE + ": " + event.getSource());
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof AuthenticationFailureBadCredentialsEvent) {
            badCredentialsEvent((AuthenticationFailureBadCredentialsEvent) event);
        } else if (event instanceof AuthenticationFailureDisabledEvent) {
            logAuthenticationFailure(ACCOUNT_DISABLED, (AuthenticationFailureDisabledEvent) event);
        } else if (event instanceof AuthenticationFailureCredentialsExpiredEvent) {
            logAuthenticationFailure(CREDENTIALS_EXPIRED, (AuthenticationFailureCredentialsExpiredEvent) event);
        } else if (event instanceof AuthenticationSuccessEvent) {
            logAuthenticationSuccess((AuthenticationSuccessEvent) event);
        } else if (event instanceof BannedApplicationEvent) {
            logUserBanned((BannedApplicationEvent) event);
        }
    }
}