Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added brute-force protection #410

Merged
merged 15 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import greencity.exception.exceptions.PasswordsDoNotMatchesException;
import greencity.exception.exceptions.UserAlreadyHasPasswordException;
import greencity.exception.exceptions.UserAlreadyRegisteredException;
import greencity.exception.exceptions.UserBlockedException;
import greencity.exception.exceptions.WrongEmailException;
import greencity.exception.exceptions.WrongIdException;
import greencity.exception.exceptions.WrongPasswordException;
Expand Down Expand Up @@ -499,4 +500,21 @@ public ResponseEntity<Object> handleBase64DecodedException(Base64DecodedExceptio

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse);
}

/**
* Handles exceptions of type {@link UserBlockedException}.
*
* @param exception the UserBlockedException instance
* @param request the current web request
* @return a ResponseEntity containing the HTTP status code and error response
* body
*/
@ExceptionHandler(UserBlockedException.class)
public ResponseEntity<Object> handleUserBlockedException(UserBlockedException exception,
WebRequest request) {
log.error(exception.getMessage());
ExceptionResponse exceptionResponse = new ExceptionResponse(getErrorAttributes(request));

return ResponseEntity.status(HttpStatus.LOCKED).body(exceptionResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package greencity.security.listener;

import greencity.constant.AppConstant;
import greencity.security.service.LoginAttemptService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

/**
* Listens for {@link AuthenticationFailureBadCredentialsEvent} events and
* delegates work of tracking of login attempts to {@link LoginAttemptService}.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
private final HttpServletRequest request;
private final LoginAttemptService loginAttemptService;

@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
final String xfHeader = request.getHeader(AppConstant.XFF_HEADER);

if (StringUtils.isEmpty(xfHeader) || !xfHeader.contains(request.getRemoteAddr())) {
loginAttemptService.loginFailed(request.getRemoteAddr());
} else {
String[] xfHeaderParts = xfHeader.split(",");

if (xfHeaderParts.length > 0) {
loginAttemptService.loginFailed(xfHeaderParts[0]);
} else {
log.warn("Invalid xfHeader value: {}", xfHeader);
}
}
}
}
6 changes: 5 additions & 1 deletion core/src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,8 @@ greencityubs.server.address = http://localhost:8050
greencitychat.server.address = ${CHAT_LINK}

#Swagger
springdoc.swagger-ui.doc-expansion=none
springdoc.swagger-ui.doc-expansion=none

#BruteForceSettings
bruteForceSettings.maxAttempts=${MAX_ATTEMPTS:5}
bruteForceSettings.blockTimeInHours=${BLOCK_TIME_IN_HOURS:1}
4 changes: 4 additions & 0 deletions core/src/main/resources/application-docker.properties
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,7 @@ greencitychat.server.address = ${CHAT_LINK}

#Swagger
springdoc.swagger-ui.doc-expansion=none

#BruteForceSettings
bruteForceSettings.maxAttempts=${MAX_ATTEMPTS:5}
bruteForceSettings.blockTimeInHours=${BLOCK_TIME_IN_HOURS:1}
6 changes: 5 additions & 1 deletion core/src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,8 @@ spring.web.resources.static-locations=classpath:/static/
greencity.authorization.googleApiKey=${GOOGLE_API_KEY:default-key}

#Swagger
springdoc.swagger-ui.doc-expansion=none
springdoc.swagger-ui.doc-expansion=none

#BruteForceSettings
bruteForceSettings.maxAttempts=${MAX_ATTEMPTS:5}
bruteForceSettings.blockTimeInHours=${BLOCK_TIME_IN_HOURS:1}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import greencity.exception.exceptions.LanguageNotSupportedException;
import greencity.exception.exceptions.NotFoundException;
import greencity.exception.exceptions.UserAlreadyRegisteredException;
import greencity.exception.exceptions.UserBlockedException;
import greencity.exception.exceptions.WrongEmailException;
import greencity.exception.exceptions.WrongIdException;
import greencity.exception.exceptions.WrongPasswordException;
Expand Down Expand Up @@ -301,4 +302,14 @@ void handleBase64DecodedExceptionTest() {
assertEquals(customExceptionHandler.handleBase64DecodedException(actual, webRequest),
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse));
}

@Test
void handleUserBlockedExceptionTest() {
UserBlockedException actual = new UserBlockedException("Some string");
ExceptionResponse exceptionResponse = new ExceptionResponse(objectMap);
when(errorAttributes.getErrorAttributes(eq(webRequest),
any(ErrorAttributeOptions.class))).thenReturn(objectMap);
assertEquals(customExceptionHandler.handleUserBlockedException(actual, webRequest),
ResponseEntity.status(HttpStatus.LOCKED).body(exceptionResponse));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package greencity.security.listener;

import greencity.constant.AppConstant;
import greencity.security.service.LoginAttemptService;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class AuthenticationFailureListenerTest {
@Mock
private HttpServletRequest request;

@Mock
private LoginAttemptService loginAttemptService;

@InjectMocks
private AuthenticationFailureListener listener;

@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}

@Test
void testOnApplicationEventWithXForwardedForHeader() {
String xfHeader = "192.168.1.1";
when(request.getHeader(AppConstant.XFF_HEADER)).thenReturn(xfHeader);
when(request.getRemoteAddr()).thenReturn("192.168.0.1");

UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken("user@example.com", "password");
AuthenticationFailureBadCredentialsEvent event =
new AuthenticationFailureBadCredentialsEvent(authentication,
new BadCredentialsException("Bad credentials"));

listener.onApplicationEvent(event);

verify(loginAttemptService).loginFailed("192.168.0.1");
}

@Test
void testOnApplicationEventWithoutXForwardedForHeader() {
when(request.getHeader(AppConstant.XFF_HEADER)).thenReturn(null);
when(request.getRemoteAddr()).thenReturn("192.168.0.1");

UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken("user@example.com", "password");
AuthenticationFailureBadCredentialsEvent event =
new AuthenticationFailureBadCredentialsEvent(authentication,
new BadCredentialsException("Bad credentials"));

listener.onApplicationEvent(event);

verify(loginAttemptService).loginFailed("192.168.0.1");
}

@Test
void testOnApplicationEventWithMultipleIPsInXForwardedForHeader() {
String xfHeader = "203.0.113.195, 198.51.100.101";
when(request.getHeader(AppConstant.XFF_HEADER)).thenReturn(xfHeader);
when(request.getRemoteAddr()).thenReturn("203.0.113.195");

UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken("user@example.com", "password");
AuthenticationFailureBadCredentialsEvent event =
new AuthenticationFailureBadCredentialsEvent(authentication,
new BadCredentialsException("Bad credentials"));

listener.onApplicationEvent(event);

verify(loginAttemptService).loginFailed("203.0.113.195");
}
}
6 changes: 6 additions & 0 deletions service-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<jjwt.version>0.12.3</jjwt.version>
<passay.version>1.6.0</passay.version>
<apache.commons.version>4.4</apache.commons.version>
<guava.version>32.0.0-jre</guava.version>
</properties>

<artifactId>service-api</artifactId>
Expand Down Expand Up @@ -156,6 +157,11 @@
<version>2.2.19</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
</dependency>
</dependencies>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ public class AppConstant {
public static final String PASSWORD = "password";
public static final String USER_STATUS = "user_status";
public static final String GOOGLE_API = "Google API";
public static final String XFF_HEADER = "X-Forwarded-For";
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,6 @@ public class ErrorMessage {
public static final String YOU_DO_NOT_HAVE_PERMISSIONS_TO_DEACTIVATE_THIS_USER =
"You do not have permission to deactivate this user";
public static final String BASE64_DECODE_MESSAGE = "Can't decode from base64 format";
public static final String BRUTEFORCE_PROTECTION_MESSAGE =
"User account is blocked due to too many failed login attempts. Try again in an hour";
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package greencity.security.service;

/**
* Service to control brute-force attacks.
*
* @author Kizerov Dmytro
* @version 1.0
*/
public interface LoginAttemptService {
/**
* This method is called when login failed.
*
* @param key identifies user, usually IP address.
*/
void loginFailed(String key);

/**
* Checks if user is blocked.
*
* @return true if user is blocked, false otherwise.
*/
boolean isBlocked();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package greencity.security.service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import greencity.constant.AppConstant;
import jakarta.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginAttemptServiceImpl implements LoginAttemptService {
private final LoadingCache<String, Integer> attemptsCache;
private final HttpServletRequest request;
@Value("${bruteForceSettings.maxAttempts}")
private int maxAttempt;

public LoginAttemptServiceImpl(HttpServletRequest request,
@Value("${bruteForceSettings.blockTimeInHours}") long blockTimeInHours) {
this.request = request;
this.attemptsCache = CacheBuilder.newBuilder()
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
.expireAfterWrite(blockTimeInHours, TimeUnit.HOURS)
.build(new CacheLoader<>() {
@Override
public Integer load(final String key) {
return 0;
}
});
}

/**
* {@inheritDoc}
*/
@Override
public void loginFailed(final String key) {
attemptsCache.asMap().merge(key, 1, Integer::sum);
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* {@inheritDoc}
*/
@Override
public boolean isBlocked() {
try {
return attemptsCache.get(getClientIP()) >= maxAttempt;
} catch (final ExecutionException e) {
return false;
}
}

private String getClientIP() {
final String xfHeader = request.getHeader(AppConstant.XFF_HEADER);
if (StringUtils.isNotEmpty(xfHeader)) {
String[] xfHeaderParts = xfHeader.split(",");
if (xfHeaderParts.length > 0) {
return xfHeaderParts[0];
}
log.warn("Invalid xfHeader value: {}", xfHeader);
}
return request.getRemoteAddr();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@
import org.apache.commons.lang3.RandomStringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -63,6 +67,8 @@ public class OwnSecurityServiceImpl implements OwnSecurityService {
private final UserRepo userRepo;
private final EmailService emailService;
private final AuthorityRepo authorityRepo;
private final LoginAttemptService loginAttemptService;
private final ApplicationEventPublisher eventPublisher;
@Value("${verifyEmailTimeHour}")
private Integer expirationTime;

Expand Down Expand Up @@ -189,12 +195,19 @@ private LocalDateTime calculateExpirationDateTime() {
* {@inheritDoc}
*/
@Override
@Transactional
public SuccessSignInDto signIn(final OwnSignInDto dto) {
if (loginAttemptService.isBlocked()) {
log.error("Brute force protection, email is blocked - {}", dto.getEmail());
throw new UserBlockedException(ErrorMessage.BRUTEFORCE_PROTECTION_MESSAGE);
}
UserVO user = userService.findByEmail(dto.getEmail());
if (user == null) {
publishFailureEvent(dto.getEmail(), ErrorMessage.USER_NOT_FOUND_BY_EMAIL);
throw new WrongEmailException(ErrorMessage.USER_NOT_FOUND_BY_EMAIL + dto.getEmail());
}
if (!isPasswordCorrect(dto, user)) {
publishFailureEvent(dto.getEmail(), ErrorMessage.BAD_PASSWORD);
throw new WrongPasswordException(ErrorMessage.BAD_PASSWORD);
}
if (user.getVerifyEmail() != null) {
Expand All @@ -208,6 +221,15 @@ public SuccessSignInDto signIn(final OwnSignInDto dto) {
return new SuccessSignInDto(user.getId(), accessToken, refreshToken, user.getName(), true);
}

private void publishFailureEvent(String email, String errorMessage) {
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(email, null);
eventPublisher
.publishEvent(
new AuthenticationFailureBadCredentialsEvent(auth,
new BadCredentialsException(errorMessage)));
}

private boolean isPasswordCorrect(OwnSignInDto signInDto, UserVO user) {
if (user.getOwnSecurity() == null) {
return false;
Expand Down
Loading
Loading