Files
src
build.gradle
gradle.properties
settings.gradle
Code
7 270
src/main/java/com/kodari/serverauth/ServerAuth.java
package com.kodari.serverauth;
import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.WorldSavePath;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class ServerAuth implements ModInitializer {
private static final Set<ServerPlayerEntity> AUTHENTICATED = ConcurrentHashMap.newKeySet();
private static final SecureRandom RANDOM = new SecureRandom();
private static final int ITERATIONS = 210_000;
@Override
public void onInitialize() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
AUTHENTICATED.remove(handler.player);
handler.player.sendMessage(Text.literal("Authenticate with /login <password> or create an account with /register <password>."));
});
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> AUTHENTICATED.remove(handler.player));
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
for (String name : new String[]{"register", "reg"}) {
dispatcher.register(CommandManager.literal(name)
.then(CommandManager.argument("password", StringArgumentType.word())
.executes(context -> register(context.getSource().getPlayerOrThrow(), StringArgumentType.getString(context, "password")))));
}
for (String name : new String[]{"login", "log"}) {
dispatcher.register(CommandManager.literal(name)
.then(CommandManager.argument("password", StringArgumentType.word())
.executes(context -> login(context.getSource().getPlayerOrThrow(), StringArgumentType.getString(context, "password")))));
}
});
}
public static boolean isAuthenticated(ServerPlayerEntity player) {
return AUTHENTICATED.contains(player);
}
private static Path accountFile(ServerPlayerEntity player) {
return player.getEntityWorld().getServer().getSavePath(WorldSavePath.ROOT)
.resolve("serverauth").resolve(player.getUuid().toString() + ".txt");
}
private static int register(ServerPlayerEntity player, String password) {
if (isAuthenticated(player)) {
player.sendMessage(Text.literal("You are already logged in."));
return 0;
}
if (password.length() < 6 || password.length() > 128) {
player.sendMessage(Text.literal("Password must be between 6 and 128 characters."));
return 0;
}
Path file = accountFile(player);
if (Files.exists(file)) {
player.sendMessage(Text.literal("You already have an account. Use /login <password>."));
return 0;
}
try {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
byte[] hash = hash(password, salt, ITERATIONS);
Files.createDirectories(file.getParent());
String record = ITERATIONS + ":" + Base64.getEncoder().encodeToString(salt) + ":" + Base64.getEncoder().encodeToString(hash);
Files.writeString(file, record, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
AUTHENTICATED.add(player);
player.sendMessage(Text.literal("Registration successful. You are now logged in."));
return 1;
} catch (IOException | GeneralSecurityException e) {
player.sendMessage(Text.literal("Could not create your account. Contact a server administrator."));
return 0;
}
}
private static int login(ServerPlayerEntity player, String password) {
if (isAuthenticated(player)) {
player.sendMessage(Text.literal("You are already logged in."));
return 0;
}
if (password.length() > 128) {
player.sendMessage(Text.literal("Incorrect password."));
return 0;
}
Path file = accountFile(player);
if (!Files.exists(file)) {
player.sendMessage(Text.literal("You do not have an account. Use /register <password>."));
return 0;
}
try {
String[] parts = Files.readString(file, StandardCharsets.UTF_8).split(":", -1);
if (parts.length != 3) throw new IllegalArgumentException();
int iterations = Integer.parseInt(parts[0]);
if (iterations < 1 || iterations > 1_000_000) throw new IllegalArgumentException();
byte[] salt = Base64.getDecoder().decode(parts[1]);
byte[] expected = Base64.getDecoder().decode(parts[2]);
if (!MessageDigest.isEqual(expected, hash(password, salt, iterations))) {
player.sendMessage(Text.literal("Incorrect password."));
return 0;
}
AUTHENTICATED.add(player);
player.sendMessage(Text.literal("Login successful."));
return 1;
} catch (IOException | GeneralSecurityException | IllegalArgumentException e) {
player.sendMessage(Text.literal("Could not read your account. Contact a server administrator."));
return 0;
}
}
private static byte[] hash(String password, byte[] salt, int iterations) throws GeneralSecurityException {
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, 256);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
}