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 @@ -4,7 +4,6 @@
import fr.xephi.authme.process.Management;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.ValidationService.ValidationResult;
import org.bukkit.command.CommandSender;

import javax.inject.Inject;
Expand All @@ -31,11 +30,12 @@ public void executeCommand(CommandSender sender, List<String> arguments) {
final String playerPass = arguments.get(1);

// Validate the password
ValidationResult validationResult = validationService.validatePassword(playerPass, playerName);
if (validationResult.hasError()) {
commonService.send(sender, validationResult.getMessageKey(), validationResult.getArgs());
} else {
management.performPasswordChangeAsAdmin(sender, playerName, playerPass);
}
validationService.validatePasswordAsync(playerPass, playerName).thenAccept(validationResult -> {
if (validationResult.hasError()) {
commonService.send(sender, validationResult.getMessageKey(), validationResult.getArgs());
} else {
management.performPasswordChangeAsAdmin(sender, playerName, playerPass);
}
Comment on lines +33 to +38
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.ValidationService.ValidationResult;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

Expand Down Expand Up @@ -49,37 +48,39 @@ public void executeCommand(final CommandSender sender, List<String> arguments) {
final String playerNameLowerCase = playerName.toLowerCase(Locale.ROOT);

// Command logic
ValidationResult passwordValidation = validationService.validatePassword(playerPass, playerName);
if (passwordValidation.hasError()) {
commonService.send(sender, passwordValidation.getMessageKey(), passwordValidation.getArgs());
return;
}

bukkitService.runTaskOptionallyAsync(() -> {
if (dataSource.isAuthAvailable(playerNameLowerCase)) {
commonService.send(sender, MessageKey.NAME_ALREADY_REGISTERED);
validationService.validatePasswordAsync(playerPass, playerName).thenAccept(passwordValidation -> {
if (passwordValidation.hasError()) {
commonService.send(sender, passwordValidation.getMessageKey(), passwordValidation.getArgs());
return;
}
Comment on lines +51 to 55
HashedPassword hashedPassword = passwordSecurity.computeHash(playerPass, playerNameLowerCase);
PlayerAuth auth = PlayerAuth.builder()
.name(playerNameLowerCase)
.realName(playerName)
.password(hashedPassword)
.registrationDate(System.currentTimeMillis())
.build();

if (!dataSource.saveAuth(auth)) {
commonService.send(sender, MessageKey.ERROR);
return;
}
bukkitService.runTaskOptionallyAsync(() -> {
if (dataSource.isAuthAvailable(playerNameLowerCase)) {
commonService.send(sender, MessageKey.NAME_ALREADY_REGISTERED);
return;
}
HashedPassword hashedPassword = passwordSecurity.computeHash(playerPass, playerNameLowerCase);
PlayerAuth auth = PlayerAuth.builder()
.name(playerNameLowerCase)
.realName(playerName)
.password(hashedPassword)
.registrationDate(System.currentTimeMillis())
.build();

commonService.send(sender, MessageKey.REGISTER_SUCCESS);
logger.info(sender.getName() + " registered " + playerName);
final Player player = bukkitService.getPlayerExact(playerName);
if (player != null) {
bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(player,
() -> player.kickPlayer(commonService.retrieveSingleMessage(player, MessageKey.KICK_FOR_ADMIN_REGISTER)));
}
if (!dataSource.saveAuth(auth)) {
commonService.send(sender, MessageKey.ERROR);
return;
}

commonService.send(sender, MessageKey.REGISTER_SUCCESS);
logger.info(sender.getName() + " registered " + playerName);
final Player player = bukkitService.getPlayerExact(playerName);
if (player != null) {
bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(player,
() -> player.kickPlayer(
commonService.retrieveSingleMessage(player, MessageKey.KICK_FOR_ADMIN_REGISTER)));
}
});
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import fr.xephi.authme.process.Management;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.ValidationService.ValidationResult;
import org.bukkit.entity.Player;

import javax.inject.Inject;
Expand Down Expand Up @@ -54,13 +53,13 @@ public void runCommand(Player player, List<String> arguments) {
String newPassword = arguments.get(1);

// Make sure the password is allowed
ValidationResult passwordValidation = validationService.validatePassword(newPassword, name);
if (passwordValidation.hasError()) {
commonService.send(player, passwordValidation.getMessageKey(), passwordValidation.getArgs());
return;
}

management.performPasswordChange(player, oldPassword, newPassword);
validationService.validatePasswordAsync(newPassword, name).thenAccept(passwordValidation -> {
if (passwordValidation.hasError()) {
commonService.send(player, passwordValidation.getMessageKey(), passwordValidation.getArgs());
} else {
management.performPasswordChange(player, oldPassword, newPassword);
Comment on lines +56 to +60
}
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.PasswordRecoveryService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.ValidationService.ValidationResult;
import org.bukkit.entity.Player;

import javax.inject.Inject;
Expand Down Expand Up @@ -44,16 +43,17 @@ protected void runCommand(Player player, List<String> arguments) {
String name = player.getName();
String password = arguments.get(0);

ValidationResult result = validationService.validatePassword(password, name);
if (!result.hasError()) {
HashedPassword hashedPassword = passwordSecurity.computeHash(password, name);
dataSource.updatePassword(name, hashedPassword);
recoveryService.removeFromSuccessfulRecovery(player);
logger.info("Player '" + name + "' has changed their password from recovery");
commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS);
} else {
commonService.send(player, result.getMessageKey(), result.getArgs());
}
validationService.validatePasswordAsync(password, name).thenAccept(result -> {
if (!result.hasError()) {
HashedPassword hashedPassword = passwordSecurity.computeHash(password, name);
dataSource.updatePassword(name, hashedPassword);
recoveryService.removeFromSuccessfulRecovery(player);
logger.info("Player '" + name + "' has changed their password from recovery");
commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS);
} else {
commonService.send(player, result.getMessageKey(), result.getArgs());
}
});
} else {
commonService.send(player, MessageKey.CHANGE_PASSWORD_EXPIRED);
}
Expand Down
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
Expand Up @@ -7,11 +7,13 @@
import fr.xephi.authme.events.AuthMeAsyncPreRegisterEvent;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.process.register.executors.AbstractPasswordRegisterParams;
import fr.xephi.authme.process.register.executors.RegistrationExecutor;
import fr.xephi.authme.process.register.executors.RegistrationMethod;
import fr.xephi.authme.process.register.executors.RegistrationParameters;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.util.InternetProtocolUtils;
Expand All @@ -21,6 +23,7 @@
import javax.inject.Inject;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;

import static fr.xephi.authme.permission.PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS;

Expand All @@ -38,6 +41,8 @@ public class AsyncRegister implements AsynchronousProcess {
@Inject
private CommonService service;
@Inject
private ValidationService validationService;
@Inject
private SingletonStore<RegistrationExecutor> registrationExecutorFactory;

AsyncRegister() {
Expand All @@ -54,11 +59,30 @@ public <P extends RegistrationParameters> void register(RegistrationMethod<P> va
if (preRegisterCheck(variant, parameters.getPlayer())) {
RegistrationExecutor<P> executor = registrationExecutorFactory.getSingleton(variant.getExecutorClass());
if (executor.isRegistrationAdmitted(parameters)) {
executeRegistration(parameters, executor);
validatePwnedPassword(parameters).thenAccept(passwordValidation -> {
if (passwordValidation.hasError()) {
service.send(parameters.getPlayer(), passwordValidation.getMessageKey(),
passwordValidation.getArgs());
} else {
Comment on lines +62 to +66
executeRegistration(parameters, executor);
}
});
}
}
}

private CompletableFuture<ValidationService.ValidationResult> validatePwnedPassword(RegistrationParameters parameters) {
if (!(parameters instanceof AbstractPasswordRegisterParams)) {
return CompletableFuture.completedFuture(new ValidationService.ValidationResult());
}

AbstractPasswordRegisterParams passwordParams = (AbstractPasswordRegisterParams) parameters;
if (passwordParams.getPassword() == null) {
return CompletableFuture.completedFuture(new ValidationService.ValidationResult());
}
return validationService.validatePasswordAsync(passwordParams.getPassword(), passwordParams.getPlayerName());
}

/**
* Checks if the player is able to register, in that case the {@link AuthMeAsyncPreRegisterEvent} is invoked.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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 fr.xephi.authme.security.MessageDigestAlgorithm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
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 = sha1Utf8(password).toUpperCase(Locale.ROOT);
String hashPrefix = hash.substring(0, HASH_PREFIX_LENGTH);
String hashSuffix = hash.substring(HASH_PREFIX_LENGTH);
Comment thread
AlexProgrammerDE marked this conversation as resolved.

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();
}
}

private static String sha1Utf8(String password) {
MessageDigest digest = HashUtils.getDigest(MessageDigestAlgorithm.SHA1);
byte[] hashedPassword = digest.digest(password.getBytes(StandardCharsets.UTF_8));
return String.format("%0" + (hashedPassword.length << 1) + "x", new BigInteger(1, hashedPassword));
}
}
Loading
Loading