Commit b4ac0649 authored by Matija Obreza's avatar Matija Obreza
Browse files

Handle failed/successful login attempts and lock user accounts after X

failed attempts
parent c24519a4
......@@ -17,6 +17,7 @@
package org.genesys2.server.model.impl;
import java.beans.Transient;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
......@@ -30,6 +31,8 @@ import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import net.sf.oval.constraint.Email;
import net.sf.oval.constraint.NotEmpty;
......@@ -88,17 +91,17 @@ public class User extends BusinessModel {
@Column
private boolean enabled;
@Column
private boolean locked;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = true)
private Date lockedUntil;
@PrePersist
void ensureUUID() {
if (this.uuid == null) {
this.uuid = UUID.nameUUIDFromBytes(email.getBytes()).toString();
}
}
public String getEmail() {
return email;
}
......@@ -165,7 +168,6 @@ public class User extends BusinessModel {
public String toString() {
return "User id=" + id + " email=" + email;
}
public String getUuid() {
return uuid;
......@@ -175,7 +177,6 @@ public class User extends BusinessModel {
this.uuid = uuid;
}
public void setSystemAccount(boolean systemAccount) {
this.systemAccount = systemAccount;
}
......@@ -187,25 +188,30 @@ public class User extends BusinessModel {
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAccountLocked() {
return this.locked;
public Date getLockedUntil() {
return this.lockedUntil;
}
public void setLockedUntil(Date lockedUntil) {
this.lockedUntil = lockedUntil;
}
public void setAccountLocked(boolean locked) {
this.locked = locked;
@Transient
public boolean isAccountLocked() {
return this.lockedUntil != null && this.lockedUntil.after(new Date());
}
@Transient
public boolean isAccountExpired() {
// We don't support account expiration
return false;
}
@Transient
public boolean isPasswordExpired() {
// We don't support password expiration
......
/**
* Copyright 2013 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys2.server.security.lockout;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* {#link {@link AccountLockoutManager} keeps track of successive failed login
* attempts and locks the user account if there are more than {
* {@link #lockAfterXFailures} successive failures.
*
* @author Matija Obreza, matija.obreza@croptrust.org
*
*/
@Component
public class AccountLockoutManager {
private final Log _log = LogFactory.getLog(getClass());
private Map<String, AttemptStatistics> loginAttempts = new HashMap<String, AttemptStatistics>();
@Autowired
private UserService userService;
private int lockAfterXFailures = 5;
/**
* Set number of successive failed login attempts that result in account
* lockout
*
* @param lockAfterXFailures
*/
public void setLockAfterXFailures(int lockAfterXFailures) {
_log.info("Will lock user accounts after " + lockAfterXFailures + " successive failed attempts.");
this.lockAfterXFailures = lockAfterXFailures;
}
/**
* Reset failed attempt statistics on successful login
*
* @param userName
*/
synchronized void handleSuccessfulLogin(String userName) {
purge();
if (loginAttempts.containsKey(userName)) {
AttemptStatistics stats = loginAttempts.get(userName);
loginAttempts.remove(userName);
_log.info("Successful login. Removed failed login statistics for " + userName + " " + stats);
}
}
/**
* Update failed attempt statistics on failed login
*
* @param userName
*/
synchronized void handleFailedLogin(String userName) {
purge();
AttemptStatistics stats = null;
if (loginAttempts.containsKey(userName)) {
stats = loginAttempts.get(userName);
} else {
User user = userService.getUserByEmail(userName);
if (user != null) {
stats = new AttemptStatistics();
stats.uuid = user.getUuid();
loginAttempts.put(userName, stats);
} else {
_log.info("No such user username=" + userName);
}
}
if (stats != null) {
stats.count++;
stats.lastAttempt = new Date();
_log.info("Updated failed login statistics for username=" + userName + " " + stats);
if (stats.count >= lockAfterXFailures) {
_log.warn("Failed login attempts exceeded. Locking account for username=" + userName);
userService.setAccountLockLocal(stats.uuid, true);
}
}
}
/**
* Removes expired statistics
*/
synchronized void purge() {
if (loginAttempts.size() == 0)
return;
_log.debug("Purging expired entries");
List<String> userNames = new ArrayList<String>(loginAttempts.keySet());
long now = new Date().getTime();
for (String userName : userNames) {
AttemptStatistics stats = loginAttempts.get(userName);
if (stats == null) {
loginAttempts.remove(userName);
continue;
}
// Things older than 60minutes=60*60*1000
if (now - stats.lastAttempt.getTime() >= 60 * 60 * 1000) {
loginAttempts.remove(userName);
_log.info("Removed expired failed login statistics for " + userName + " " + stats);
}
}
_log.info("Number of failed login attempts in memory: " + loginAttempts.size());
}
private class AttemptStatistics {
String uuid;
int count = 0;
Date lastAttempt = new Date();
@Override
public String toString() {
return "count=" + count + " lastAttempt=" + lastAttempt;
}
}
}
\ No newline at end of file
/**
* Copyright 2013 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys2.server.security.lockout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
/**
* Log failed login attempt and notify {@link AccountLockoutManager}.
*
* @author Matija Obreza, matija.obreza@croptrust.org
*/
@Component
public class AuthenticationFailureBadCredentialsListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
private final Log _log = LogFactory.getLog(getClass());
@Autowired
private AccountLockoutManager lockoutManager;
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
String userName = (String) event.getAuthentication().getPrincipal();
Object details = event.getAuthentication().getDetails();
if (details != null && details instanceof WebAuthenticationDetails) {
WebAuthenticationDetails wad = (WebAuthenticationDetails) details;
// This can be picked up by fail2ban http://www.fail2ban.org/
_log.warn("Failed login attempt for username=" + userName + " from IP=" + wad.getRemoteAddress());
}
lockoutManager.handleFailedLogin(userName);
}
}
\ No newline at end of file
/**
* Copyright 2013 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys2.server.security.lockout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.security.AuthUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
/**
* Log successful login attempt and notify {@link AccountLockoutManager}.
*
* @author Matija Obreza, matija.obreza@croptrust.org
*/
@Component
public class AuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
private final Log _log = LogFactory.getLog(getClass());
@Autowired
private AccountLockoutManager lockoutManager;
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
AuthUserDetails authUser = (AuthUserDetails) event.getAuthentication().getPrincipal();
Object details = event.getAuthentication().getDetails();
if (details != null && details instanceof WebAuthenticationDetails) {
WebAuthenticationDetails wad = (WebAuthenticationDetails) details;
// This can be picked up by fail2ban http://www.fail2ban.org/
_log.info("Successful login attempt for username=" + authUser.getUser().getEmail() + " from IP=" + wad.getRemoteAddress());
}
lockoutManager.handleSuccessfulLogin(authUser.getUser().getEmail());
}
}
\ No newline at end of file
......@@ -68,4 +68,6 @@ public interface UserService {
void setAccountEnabled(String uuid, boolean enabled);
void setAccountLockLocal(String uuid, boolean locked);
}
......@@ -20,6 +20,8 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
......@@ -34,6 +36,7 @@ import org.springframework.stereotype.Component;
@Component("authUserDetailsService")
public class AuthUserDetailsService implements UserDetailsService {
private final Log LOG = LogFactory.getLog(getClass());
@Autowired
private UserService userService;
......@@ -52,6 +55,18 @@ public class AuthUserDetailsService implements UserDetailsService {
boolean credentialsNonExpired = !user.isPasswordExpired();
boolean accountNonLocked = !user.isAccountLocked();
if (!accountNonLocked) {
LOG.warn("Account is locked for user=" + user.getEmail() + " until=" + user.getLockedUntil());
}
if (!enabled) {
LOG.warn("Account is disabled for user=" + user.getEmail());
}
if (user.getLockedUntil() != null && accountNonLocked) {
LOG.warn("Account can be unlocked for user=" + user.getEmail());
userService.setAccountLockLocal(user.getUuid(), false);
}
AuthUserDetails userDetails = new AuthUserDetails(user.getUuid(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, getGrantedAuthorities(user));
......
......@@ -17,9 +17,12 @@
package org.genesys2.server.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.exception.NoUserFoundException;
import org.genesys2.server.exception.NotUniqueUserException;
import org.genesys2.server.exception.UserException;
......@@ -45,6 +48,7 @@ import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
private final Log LOG = LogFactory.getLog(getClass());
@Autowired
private UserPersistence userPersistence;
......@@ -52,6 +56,19 @@ public class UserServiceImpl implements UserService {
@Autowired
private PasswordEncoder passwordEncoder;
private long accountLockoutTime = 5 * 60 * 1000;
/**
* Set number of milliseconds for user account lockout
*/
public void setAccountLockoutTime(long accountLockoutTime) {
this.accountLockoutTime = accountLockoutTime;
}
public long getAccountLockoutTime() {
return accountLockoutTime;
}
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
public Page<User> listUsers(Pageable pageable) {
......@@ -183,21 +200,36 @@ public class UserServiceImpl implements UserService {
@PreAuthorize("hasRole('ADMINISTRATOR')")
public void setAccountEnabled(String uuid, boolean enabled) {
User user = userPersistence.findByUuid(uuid);
if (! enabled && user.getRoles().contains(UserRole.ADMINISTRATOR))
if (!enabled && user.getRoles().contains(UserRole.ADMINISTRATOR))
throw new SecurityException("Can't disable ADMINISTRATOR accounts");
user.setEnabled(enabled);
userPersistence.save(user);
LOG.warn("Disabled/enabled user account for user=" + user.getEmail() + " enabled=" + enabled);
}
/**
* For internal use only.
*/
@Override
@Transactional(readOnly = false)
public void setAccountLockLocal(String uuid, boolean locked) {
User user = userPersistence.findByUuid(uuid);
if (locked) {
// Lock for account until some time
user.setLockedUntil(new Date(System.currentTimeMillis() + accountLockoutTime));
LOG.warn("Locking user account for user=" + user.getEmail() + " until=" + user.getLockedUntil());
} else {
LOG.warn("Unlocking user account for user=" + user.getEmail());
user.setLockedUntil(null);
}
userPersistence.save(user);
}
@Override
@Transactional(readOnly = false)
@PreAuthorize("hasRole('ADMINISTRATOR')")
public void setAccountLock(String uuid, boolean locked) {
User user = userPersistence.findByUuid(uuid);
if (locked && user.getRoles().contains(UserRole.ADMINISTRATOR))
throw new SecurityException("Can't lock ADMINISTRATOR accounts");
user.setAccountLocked(locked);
userPersistence.save(user);
setAccountLockLocal(uuid, locked);
}
private void setPassword(User user, String rawPassword) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment