Skip to content
Open
Show file tree
Hide file tree
Changes from all 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 @@ -80,6 +80,9 @@ public enum MessageKey {
/** The chosen password isn't safe, please choose another one... */
PASSWORD_UNSAFE_ERROR("password.unsafe_password"),

/** Your chosen password is not secure. It has been seen %pwned_count times before! */
PASSWORD_PWNED_ERROR("password.pwned_password", "%pwned_count"),

/** Your password contains illegal characters. Allowed chars: %valid_chars */
PASSWORD_CHARACTERS_ERROR("password.forbidden_characters", "%valid_chars"),

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package fr.xephi.authme.service;

import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.HashUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.OptionalLong;
import java.util.stream.Collectors;

/**
* Queries the Have I Been Pwned Pwned Passwords range API.
*/
public class PwnedPasswordService {

private static final String RANGE_API_URL = "https://api.pwnedpasswords.com/range/";
private static final String USER_AGENT = "AuthMeReloaded";
private static final int HASH_PREFIX_LENGTH = 5;
private static final int CONNECT_TIMEOUT_MILLIS = 5_000;
private static final int READ_TIMEOUT_MILLIS = 5_000;

private final ConsoleLogger logger = ConsoleLoggerFactory.get(PwnedPasswordService.class);

/**
* Returns how many times the password appears in the Pwned Passwords database.
*
* @param password the password to check
* @return the count, 0 when absent, or empty if the API could not be queried
*/
public OptionalLong getPwnedCount(String password) {
String hash = HashUtils.sha1(password).toUpperCase(Locale.ROOT);
String hashPrefix = hash.substring(0, HASH_PREFIX_LENGTH);
String hashSuffix = hash.substring(HASH_PREFIX_LENGTH);
Comment on lines +37 to +40
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getPwnedCount relies on HashUtils.sha1(password), but HashUtils.hash uses message.getBytes() without an explicit charset, so the SHA-1 can differ across platforms for non-ASCII passwords. For interoperability with the HIBP API and consistent behavior across JVMs/OSes, ensure the SHA-1 is computed over a fixed charset (typically UTF-8), either by updating HashUtils or by hashing with an explicit charset here.

Copilot uses AI. Check for mistakes.

try {
return parsePwnedCount(hashSuffix, requestHashRange(hashPrefix));
} catch (IOException e) {
logger.debug("Could not query the Pwned Passwords API: {0}", e.getMessage());
return OptionalLong.empty();
}
}

@VisibleForTesting
protected String requestHashRange(String hashPrefix) throws IOException {
HttpURLConnection connection = (HttpURLConnection) URI.create(RANGE_API_URL + hashPrefix)
.toURL()
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Add-Padding", "true");
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS);
connection.setReadTimeout(READ_TIMEOUT_MILLIS);

try {
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP " + responseCode);
}

try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
return reader.lines().collect(Collectors.joining("\n"));
}
} finally {
connection.disconnect();
}
}

private OptionalLong parsePwnedCount(String searchedHashSuffix, String response) {
String[] entries = response.split("\\R");
for (String entry : entries) {
int delimiterIndex = entry.indexOf(':');
if (delimiterIndex < 0) {
continue;
}

String hashSuffix = entry.substring(0, delimiterIndex);
if (hashSuffix.equalsIgnoreCase(searchedHashSuffix)) {
return parseCount(entry.substring(delimiterIndex + 1));
}
}
return OptionalLong.of(0);
}

private OptionalLong parseCount(String count) {
try {
return OptionalLong.of(Long.parseLong(count.trim()));
} catch (NumberFormatException e) {
logger.debug("Could not parse Pwned Passwords count: {0}", count);
return OptionalLong.empty();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.OptionalLong;
import java.util.Set;
import java.util.regex.Pattern;

Expand All @@ -48,6 +49,8 @@ public class ValidationService implements Reloadable {
private PermissionsManager permissionsManager;
@Inject
private GeoIpService geoIpService;
@Inject
private PwnedPasswordService pwnedPasswordService;

private Pattern passwordRegex;
private Multimap<String, String> restrictedNames;
Expand Down Expand Up @@ -82,6 +85,12 @@ public ValidationResult validatePassword(String password, String username) {
return new ValidationResult(MessageKey.INVALID_PASSWORD_LENGTH);
} else if (settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS).contains(passLow)) {
return new ValidationResult(MessageKey.PASSWORD_UNSAFE_ERROR);
} else if (settings.getProperty(SecuritySettings.ENABLE_PWNED_PASSWORD_CHECK)) {
OptionalLong pwnedCount = pwnedPasswordService.getPwnedCount(password);
int threshold = settings.getProperty(SecuritySettings.PWNED_PASSWORD_CHECK_THRESHOLD);
if (pwnedCount.isPresent() && pwnedCount.getAsLong() > threshold) {
return new ValidationResult(MessageKey.PASSWORD_PWNED_ERROR, Long.toString(pwnedCount.getAsLong()));
Comment on lines +88 to +92
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validatePassword now performs a synchronous network call to the HIBP API (pwnedPasswordService.getPwnedCount). This method is invoked directly on the command thread in some flows (e.g., RegisterAdminCommand calls validatePassword before any async handoff), and also when useAsyncTasks is disabled, which can block the server thread for up to the configured HTTP timeouts. Consider moving the pwned-password query to an async step (or providing an async validation API) so password validation cannot stall the main thread.

Copilot uses AI. Check for mistakes.
}
}
return new ValidationResult();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ public final class SecuritySettings implements SettingsHolder {
newLowercaseStringSetProperty("settings.security.unsafePasswords",
"123456", "password", "qwerty", "12345", "54321", "123456789", "help");

@Comment({
"Reject passwords found in the Have I Been Pwned Pwned Passwords database.",
"Only the first 5 SHA-1 hash characters are sent; the full hash and password stay local."
})
public static final Property<Boolean> ENABLE_PWNED_PASSWORD_CHECK =
newProperty("settings.security.pwnedPasswords.enabled", false);

@Comment("Reject passwords found more than this many times in the Pwned Passwords database")
public static final Property<Integer> PWNED_PASSWORD_CHECK_THRESHOLD =
newProperty("settings.security.pwnedPasswords.threshold", 0);

@Comment("Tempban a user's IP address if they enter the wrong password too many times")
public static final Property<Boolean> TEMPBAN_ON_MAX_LOGINS =
newProperty("Security.tempban.enableTempban", false);
Expand Down
1 change: 1 addition & 0 deletions authme-core/src/main/resources/messages/messages_en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ password:
match_error: '&cPasswords didn''t match, check them again!'
name_in_password: '&cYou can''t use your name as password, please choose another one...'
unsafe_password: '&cThe chosen password isn''t safe, please choose another one...'
pwned_password: '&cYour chosen password is not secure. It has been seen %pwned_count times before! Please use a stronger password...'
forbidden_characters: '&4Your password contains illegal characters. Allowed chars: %valid_chars'
wrong_length: '&cYour password is too short or too long! Please try with another one!'

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package fr.xephi.authme.service;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.OptionalLong;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
* Test for {@link PwnedPasswordService}.
*/
class PwnedPasswordServiceTest {

@Test
void shouldReturnPwnedCountForMatchingPasswordHash() {
// given
TestPwnedPasswordService service = new TestPwnedPasswordService(
"003D68EB55068C33ACE09247EE4C639306B:1\n"
+ "1E4C9B93F3F0682250B6CF8331B7EE68FD8:12345\n"
+ "FFFFF0AC487871FEEC1891C490136E006E2:0");

// when
OptionalLong count = service.getPwnedCount("password");

// then
assertThat(count.isPresent(), equalTo(true));
assertThat(count.getAsLong(), equalTo(12345L));
assertThat(service.requestedHashPrefix, equalTo("5BAA6"));
}

@Test
void shouldReturnZeroWhenPasswordHashIsAbsent() {
// given
TestPwnedPasswordService service = new TestPwnedPasswordService(
"003D68EB55068C33ACE09247EE4C639306B:1\n"
+ "FFFFF0AC487871FEEC1891C490136E006E2:0");

// when
OptionalLong count = service.getPwnedCount("password");

// then
assertThat(count.isPresent(), equalTo(true));
assertThat(count.getAsLong(), equalTo(0L));
}

@Test
void shouldReturnEmptyWhenRangeRequestFails() {
// given
TestPwnedPasswordService service = new TestPwnedPasswordService(new IOException("boom"));

// when
OptionalLong count = service.getPwnedCount("password");

// then
assertThat(count.isPresent(), equalTo(false));
}

private static final class TestPwnedPasswordService extends PwnedPasswordService {
private final String response;
private final IOException exception;
private String requestedHashPrefix;

private TestPwnedPasswordService(String response) {
this.response = response;
this.exception = null;
}

private TestPwnedPasswordService(IOException exception) {
this.response = null;
this.exception = exception;
}

@Override
protected String requestHashRange(String hashPrefix) throws IOException {
requestedHashPrefix = hashPrefix;
if (exception != null) {
throw exception;
}
return response;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.OptionalLong;
import java.util.logging.Logger;

import static com.google.common.collect.Sets.newHashSet;
Expand Down Expand Up @@ -56,6 +57,8 @@ public class ValidationServiceTest {
private PermissionsManager permissionsManager;
@Mock
private GeoIpService geoIpService;
@Mock
private PwnedPasswordService pwnedPasswordService;
@Captor
private ArgumentCaptor<String> stringCaptor;

Expand All @@ -65,6 +68,7 @@ public void createService() {
given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3);
given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20);
given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe"));
given(settings.getProperty(SecuritySettings.ENABLE_PWNED_PASSWORD_CHECK)).willReturn(false);
given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3);
given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc"));
given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(false);
Expand Down Expand Up @@ -116,6 +120,48 @@ public void shouldRejectUnsafePassword() {
assertErrorEquals(error, MessageKey.PASSWORD_UNSAFE_ERROR);
}

@Test
public void shouldRejectPwnedPasswordOverThreshold() {
// given
given(settings.getProperty(SecuritySettings.ENABLE_PWNED_PASSWORD_CHECK)).willReturn(true);
given(settings.getProperty(SecuritySettings.PWNED_PASSWORD_CHECK_THRESHOLD)).willReturn(10);
given(pwnedPasswordService.getPwnedCount("safePass")).willReturn(OptionalLong.of(42));

// when
ValidationResult error = validationService.validatePassword("safePass", "some_user");

// then
assertErrorEquals(error, MessageKey.PASSWORD_PWNED_ERROR, "42");
}

@Test
public void shouldAcceptPwnedPasswordAtThreshold() {
// given
given(settings.getProperty(SecuritySettings.ENABLE_PWNED_PASSWORD_CHECK)).willReturn(true);
given(settings.getProperty(SecuritySettings.PWNED_PASSWORD_CHECK_THRESHOLD)).willReturn(10);
given(pwnedPasswordService.getPwnedCount("safePass")).willReturn(OptionalLong.of(10));

// when
ValidationResult error = validationService.validatePassword("safePass", "some_user");

// then
assertThat(error.hasError(), equalTo(false));
}

@Test
public void shouldAcceptPasswordWhenPwnedCheckIsUnavailable() {
// given
given(settings.getProperty(SecuritySettings.ENABLE_PWNED_PASSWORD_CHECK)).willReturn(true);
given(settings.getProperty(SecuritySettings.PWNED_PASSWORD_CHECK_THRESHOLD)).willReturn(10);
given(pwnedPasswordService.getPwnedCount("safePass")).willReturn(OptionalLong.empty());

// when
ValidationResult error = validationService.validatePassword("safePass", "some_user");

// then
assertThat(error.hasError(), equalTo(false));
}

@Test
public void shouldAcceptValidPassword() {
// given/when
Expand Down Expand Up @@ -424,4 +470,3 @@ private static void assertErrorEquals(ValidationResult validationResult, Message
}
}


Loading