Add Compromised Password Checker

Closes gh-7395
This commit is contained in:
Marcus Hert Da Coregio
2024-03-05 14:45:33 -03:00
parent 89175dfed0
commit 7d66525e23
19 changed files with 1100 additions and 3 deletions

View File

@@ -24,9 +24,13 @@ import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import org.springframework.context.MessageSource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.password.CompromisedPasswordCheckResult;
import org.springframework.security.core.password.CompromisedPasswordException;
import org.springframework.security.core.password.ReactiveCompromisedPasswordChecker;
import org.springframework.security.core.userdetails.ReactiveUserDetailsPasswordService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
@@ -34,6 +38,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
@@ -219,6 +224,41 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test
public void authenticateWhenPasswordCompromisedThenException() {
// @formatter:off
UserDetails user = User.withUsername("user")
.password("{noop}password")
.roles("USER")
.build();
// @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(user));
this.manager.setCompromisedPasswordChecker(new TestReactivePasswordChecker());
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(user,
"password");
StepVerifier.create(this.manager.authenticate(token))
.expectErrorSatisfies((ex) -> assertThat(ex).isInstanceOf(CompromisedPasswordException.class)
.withFailMessage("The provided password is compromised, please change your password"))
.verify();
}
@Test
public void authenticateWhenPasswordNotCompromisedThenSuccess() {
// @formatter:off
UserDetails user = User.withUsername("user")
.password("{noop}notcompromised")
.roles("USER")
.build();
// @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(user));
this.manager.setCompromisedPasswordChecker(new TestReactivePasswordChecker());
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(user,
"notcompromised");
StepVerifier.create(this.manager.authenticate(token))
.assertNext((authentication) -> assertThat(authentication.getPrincipal()).isEqualTo(user))
.verifyComplete();
}
@Test
public void setMessageSourceWhenNullThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setMessageSource(null));
@@ -233,4 +273,16 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
verify(source).getMessage(eq(code), any(), any());
}
static class TestReactivePasswordChecker implements ReactiveCompromisedPasswordChecker {
@Override
public Mono<CompromisedPasswordCheckResult> check(String password) {
if ("password".equals(password)) {
return Mono.just(new CompromisedPasswordCheckResult(true));
}
return Mono.just(new CompromisedPasswordCheckResult(false));
}
}
}

View File

@@ -36,6 +36,9 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.password.CompromisedPasswordCheckResult;
import org.springframework.security.core.password.CompromisedPasswordChecker;
import org.springframework.security.core.password.CompromisedPasswordException;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
@@ -48,6 +51,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -504,6 +508,42 @@ public class DaoAuthenticationProviderTests {
verify(encoder, times(0)).matches(anyString(), anyString());
}
@Test
void authenticateWhenPasswordLeakedThenException() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
provider.setUserDetailsService(withUsers(user));
provider.setCompromisedPasswordChecker(new TestCompromisedPasswordChecker());
assertThatExceptionOfType(CompromisedPasswordException.class).isThrownBy(
() -> provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")))
.withMessage("The provided password is compromised, please change your password");
}
@Test
void authenticateWhenPasswordNotLeakedThenNoException() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("strongpassword")
.roles("USER")
.build();
provider.setUserDetailsService(withUsers(user));
provider.setCompromisedPasswordChecker(new TestCompromisedPasswordChecker());
Authentication authentication = provider
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "strongpassword"));
assertThat(authentication).isNotNull();
}
private UserDetailsService withUsers(UserDetails... users) {
return new InMemoryUserDetailsManager(users);
}
private DaoAuthenticationProvider createProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
@@ -594,4 +634,16 @@ public class DaoAuthenticationProviderTests {
}
private static class TestCompromisedPasswordChecker implements CompromisedPasswordChecker {
@Override
public CompromisedPasswordCheckResult check(String password) {
if ("password".equals(password)) {
return new CompromisedPasswordCheckResult(true);
}
return new CompromisedPasswordCheckResult(false);
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* 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
*
* https://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.springframework.security.core.password;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
class HaveIBeenPwnedRestApiPasswordCheckerTests {
private final String pwnedPasswords = """
2CDE4CDCFA5AD7D223BD1800338FBEAA04E:1
2CF90F92EE1941547BB13DFC7D0E0AFE504:1
2D10A6654B6D75908AE572559542245CBFA:6
2D4FCF535FE92B8B950424E16E65EFBFED3:1
2D6980B9098804E7A83DC5831BFBAF3927F:1
2D8D1B3FAACCA6A3C6A91617B2FA32E2F57:1
2DC183F740EE76F27B78EB39C8AD972A757:300185
2DE4C0087846D223DBBCCF071614590F300:3
2DEA2B1D02714099E4B7A874B4364D518F6:1
2E750AE8C4756A20CE040BF3DDF094FA7EC:1
2E90B7B3C5C1181D16C48E273D9AC7F3C16:5
2E991A9162F24F01826D8AF73CA20F2B430:1
2EAE5EA981BFAF29A8869A40BDDADF3879B:2
2F1AC09E3846595E436BBDDDD2189358AF9:1
""";
private final MockWebServer server = new MockWebServer();
private final HaveIBeenPwnedRestApiPasswordChecker passwordChecker = new HaveIBeenPwnedRestApiPasswordChecker();
@BeforeEach
void setup() throws IOException {
this.server.start();
HttpUrl url = this.server.url("/range/");
this.passwordChecker.setRestClient(RestClient.builder().baseUrl(url.toString()).build());
}
@AfterEach
void tearDown() throws IOException {
this.server.shutdown();
}
@Test
void checkWhenPasswordIsLeakedThenIsCompromised() throws InterruptedException {
this.server.enqueue(new MockResponse().setBody(this.pwnedPasswords).setResponseCode(200));
CompromisedPasswordCheckResult check = this.passwordChecker.check("P@ssw0rd");
assertThat(check.isCompromised()).isTrue();
assertThat(this.server.takeRequest().getPath()).isEqualTo("/range/21BD1");
}
@Test
void checkWhenPasswordNotLeakedThenNotCompromised() {
this.server.enqueue(new MockResponse().setBody(this.pwnedPasswords).setResponseCode(200));
CompromisedPasswordCheckResult check = this.passwordChecker.check("My1nCr3d!bL3P@SS0W0RD");
assertThat(check.isCompromised()).isFalse();
}
@Test
void checkWhenNoPasswordsReturnedFromApiCallThenNotCompromised() {
this.server.enqueue(new MockResponse().setResponseCode(200));
CompromisedPasswordCheckResult check = this.passwordChecker.check("123456");
assertThat(check.isCompromised()).isFalse();
}
@Test
void checkWhenResponseStatusNot200ThenNotCompromised() {
this.server.enqueue(new MockResponse().setResponseCode(503));
assertThatNoException().isThrownBy(() -> this.passwordChecker.check("123456"));
this.server.enqueue(new MockResponse().setResponseCode(404));
assertThatNoException().isThrownBy(() -> this.passwordChecker.check("123456"));
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* 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
*
* https://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.springframework.security.core.password;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
class HaveIBeenPwnedRestApiReactivePasswordCheckerTests {
private final String pwnedPasswords = """
2CDE4CDCFA5AD7D223BD1800338FBEAA04E:1
2CF90F92EE1941547BB13DFC7D0E0AFE504:1
2D10A6654B6D75908AE572559542245CBFA:6
2D4FCF535FE92B8B950424E16E65EFBFED3:1
2D6980B9098804E7A83DC5831BFBAF3927F:1
2D8D1B3FAACCA6A3C6A91617B2FA32E2F57:1
2DC183F740EE76F27B78EB39C8AD972A757:300185
2DE4C0087846D223DBBCCF071614590F300:3
2DEA2B1D02714099E4B7A874B4364D518F6:1
2E750AE8C4756A20CE040BF3DDF094FA7EC:1
2E90B7B3C5C1181D16C48E273D9AC7F3C16:5
2E991A9162F24F01826D8AF73CA20F2B430:1
2EAE5EA981BFAF29A8869A40BDDADF3879B:2
2F1AC09E3846595E436BBDDDD2189358AF9:1
""";
private final MockWebServer server = new MockWebServer();
private final HaveIBeenPwnedRestApiReactivePasswordChecker passwordChecker = new HaveIBeenPwnedRestApiReactivePasswordChecker();
@BeforeEach
void setup() throws IOException {
this.server.start();
HttpUrl url = this.server.url("/range/");
this.passwordChecker.setWebClient(WebClient.builder().baseUrl(url.toString()).build());
}
@AfterEach
void tearDown() throws IOException {
this.server.shutdown();
}
@Test
void checkWhenPasswordIsLeakedThenIsCompromised() throws InterruptedException {
this.server.enqueue(new MockResponse().setBody(this.pwnedPasswords).setResponseCode(200));
StepVerifier.create(this.passwordChecker.check("P@ssw0rd"))
.assertNext((check) -> assertThat(check.isCompromised()).isTrue())
.verifyComplete();
assertThat(this.server.takeRequest().getPath()).isEqualTo("/range/21BD1");
}
@Test
void checkWhenPasswordNotLeakedThenNotCompromised() {
this.server.enqueue(new MockResponse().setBody(this.pwnedPasswords).setResponseCode(200));
StepVerifier.create(this.passwordChecker.check("My1nCr3d!bL3P@SS0W0RD"))
.assertNext((check) -> assertThat(check.isCompromised()).isFalse())
.verifyComplete();
}
@Test
void checkWhenNoPasswordsReturnedFromApiCallThenNotCompromised() {
this.server.enqueue(new MockResponse().setResponseCode(200));
StepVerifier.create(this.passwordChecker.check("P@ssw0rd"))
.assertNext((check) -> assertThat(check.isCompromised()).isFalse())
.verifyComplete();
}
@Test
void checkWhenResponseStatusNot200ThenNotCompromised() {
this.server.enqueue(new MockResponse().setResponseCode(503));
StepVerifier.create(this.passwordChecker.check("123456"))
.assertNext((check) -> assertThat(check.isCompromised()).isFalse())
.verifyComplete();
this.server.enqueue(new MockResponse().setResponseCode(404));
StepVerifier.create(this.passwordChecker.check("123456"))
.assertNext((check) -> assertThat(check.isCompromised()).isFalse())
.verifyComplete();
}
}