1
0
mirror of synced 2026-08-07 02:38:47 +00:00

Move HaveIBeenPwnedRestApiPasswordChecker to spring-security-web

Prior to this commit, the implementation was placed in spring-security-core, however we do not want to introduce a dependency on spring-web and spring-webflux for that module.

Issue gh-7395
This commit is contained in:
Marcus Hert Da Coregio
2024-04-10 14:56:44 -03:00
parent f689f3c3fc
commit 61eba00654
18 changed files with 36 additions and 34 deletions
@@ -0,0 +1,117 @@
/*
* 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.web.authentication.password;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.password.CompromisedPasswordCheckResult;
import org.springframework.security.authentication.password.CompromisedPasswordChecker;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
/**
* Checks if the provided password was leaked by relying on
* <a href="https://www.haveibeenpwned.com/API/v3#PwnedPasswords">Have I Been Pwned REST
* API</a>. This implementation uses the Search by Range in order to protect the value of
* the source password being searched for.
*
* @author Marcus da Coregio
* @since 6.3
*/
public final class HaveIBeenPwnedRestApiPasswordChecker implements CompromisedPasswordChecker {
private static final String API_URL = "https://api.pwnedpasswords.com/range/";
private static final int PREFIX_LENGTH = 5;
private final Log logger = LogFactory.getLog(getClass());
private final MessageDigest sha1Digest;
private RestClient restClient = RestClient.builder().baseUrl(API_URL).build();
public HaveIBeenPwnedRestApiPasswordChecker() {
this.sha1Digest = getSha1Digest();
}
@Override
@NonNull
public CompromisedPasswordCheckResult check(String password) {
byte[] hash = this.sha1Digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = new String(Hex.encode(hash)).toUpperCase();
String prefix = encoded.substring(0, PREFIX_LENGTH);
String suffix = encoded.substring(PREFIX_LENGTH);
List<String> passwords = getLeakedPasswordsForPrefix(prefix);
boolean isLeaked = findLeakedPassword(passwords, suffix);
return new CompromisedPasswordCheckResult(isLeaked);
}
/**
* Sets the {@link RestClient} to use when making requests to Have I Been Pwned REST
* API. By default, a {@link RestClient} with a base URL of {@link #API_URL} is used.
* @param restClient the {@link RestClient} to use
*/
public void setRestClient(RestClient restClient) {
Assert.notNull(restClient, "restClient cannot be null");
this.restClient = restClient;
}
private boolean findLeakedPassword(List<String> passwords, String suffix) {
for (String pw : passwords) {
if (pw.startsWith(suffix)) {
return true;
}
}
return false;
}
private List<String> getLeakedPasswordsForPrefix(String prefix) {
try {
String response = this.restClient.get().uri(prefix).retrieve().body(String.class);
if (!StringUtils.hasText(response)) {
return Collections.emptyList();
}
return response.lines().toList();
}
catch (RestClientException ex) {
this.logger.error("Request for leaked passwords failed", ex);
return Collections.emptyList();
}
}
private static MessageDigest getSha1Digest() {
try {
return MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
@@ -0,0 +1,111 @@
/*
* 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.web.authentication.password;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import org.springframework.security.authentication.password.CompromisedPasswordCheckResult;
import org.springframework.security.authentication.password.ReactiveCompromisedPasswordChecker;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
/**
* Checks if the provided password was leaked by relying on
* <a href="https://www.haveibeenpwned.com/API/v3#PwnedPasswords">Have I Been Pwned REST
* API</a>. This implementation uses the Search by Range in order to protect the value of
* the source password being searched for.
*
* @author Marcus da Coregio
* @since 6.3
*/
public class HaveIBeenPwnedRestApiReactivePasswordChecker implements ReactiveCompromisedPasswordChecker {
private static final String API_URL = "https://api.pwnedpasswords.com/range/";
private static final int PREFIX_LENGTH = 5;
private final Log logger = LogFactory.getLog(getClass());
private WebClient webClient = WebClient.builder().baseUrl(API_URL).build();
private final MessageDigest sha1Digest;
public HaveIBeenPwnedRestApiReactivePasswordChecker() {
this.sha1Digest = getSha1Digest();
}
@Override
public Mono<CompromisedPasswordCheckResult> check(String password) {
return getHash(password).map((hash) -> new String(Hex.encode(hash)))
.flatMap(this::findLeakedPassword)
.map(CompromisedPasswordCheckResult::new);
}
private Mono<Boolean> findLeakedPassword(String encodedPassword) {
String prefix = encodedPassword.substring(0, PREFIX_LENGTH).toUpperCase();
String suffix = encodedPassword.substring(PREFIX_LENGTH).toUpperCase();
return getLeakedPasswordsForPrefix(prefix).any((leakedPw) -> leakedPw.startsWith(suffix));
}
private Flux<String> getLeakedPasswordsForPrefix(String prefix) {
return this.webClient.get().uri(prefix).retrieve().bodyToMono(String.class).flatMapMany((body) -> {
if (StringUtils.hasText(body)) {
return Flux.fromStream(body.lines());
}
return Flux.empty();
})
.doOnError((ex) -> this.logger.error("Request for leaked passwords failed", ex))
.onErrorResume(WebClientResponseException.class, (ex) -> Flux.empty());
}
/**
* Sets the {@link WebClient} to use when making requests to Have I Been Pwned REST
* API. By default, a {@link WebClient} with a base URL of {@link #API_URL} is used.
* @param webClient the {@link WebClient} to use
*/
public void setWebClient(WebClient webClient) {
Assert.notNull(webClient, "webClient cannot be null");
this.webClient = webClient;
}
private Mono<byte[]> getHash(String password) {
return Mono.fromSupplier(() -> this.sha1Digest.digest(password.getBytes(StandardCharsets.UTF_8)))
.subscribeOn(Schedulers.boundedElastic())
.publishOn(Schedulers.parallel());
}
private static MessageDigest getSha1Digest() {
try {
return MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
@@ -0,0 +1,99 @@
/*
* 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.web.authentication.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.security.authentication.password.CompromisedPasswordCheckResult;
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"));
}
}
@@ -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.web.authentication.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();
}
}