Files
src
verification
build.gradle
IMPORTANT.txt
manifest.kod
README.md
SECURITY-TEST-REPORT.md
SECURITY.md
settings.gradle
Code
38 2,722
src/main/java/com/lunarlogin/LunarLogin.java
package com.lunarlogin;
import com.lunarlogin.authentication.AuthenticationManager;
import com.lunarlogin.authentication.MicrosoftVerificationService;
import com.lunarlogin.authentication.PremiumIdentityService;
import com.lunarlogin.commands.LunarLoginCommand;
import com.lunarlogin.commands.RegisterCommand;
import com.lunarlogin.configuration.ConfigurationManager;
import com.lunarlogin.database.DatabaseManager;
import com.lunarlogin.listeners.AuthenticationListener;
import com.lunarlogin.listeners.FailClosedListener;
import com.lunarlogin.security.ChallengeManager;
import com.lunarlogin.security.HttpsCredentialServer;
import com.lunarlogin.security.PasswordHasher;
import com.lunarlogin.security.RateLimiter;
import com.lunarlogin.security.SecurityMonitor;
import com.lunarlogin.session.SessionManager;
import com.lunarlogin.utilities.MessageManager;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.IllegalPluginAccessException;
import java.io.File;
import java.sql.SQLException;
import java.util.function.Consumer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public final class LunarLogin extends JavaPlugin {
private ConfigurationManager configurationManager;
private ExecutorService executor;
private DatabaseManager database;
private SessionManager sessionManager;
private ChallengeManager challengeManager;
private AuthenticationManager authenticationManager;
private SecurityMonitor securityMonitor;
private MicrosoftVerificationService microsoftVerification;
private HttpsCredentialServer httpsCredentialServer;
private ExecutorService microsoftExecutor;
private MessageManager messageManager;
private volatile boolean runtimeReady;
private volatile boolean shuttingDown;
private record RuntimeSettings(File dataFolder, DatabaseManager.Settings database, int auditAlertThreshold,
int auditRetentionDays, int argonIterations, int argonMemoryKiB, int argonParallelism,
int minimumPasswordLength, int maximumPasswordLength, int maximumLoginAttempts,
int authenticationTimeoutSeconds, long sessionDurationMillis, boolean premiumEnabled,
String premiumClientId, String premiumScope, int premiumTimeoutSeconds,
boolean httpsEnabled, String httpsBindAddress, int httpsPort, String httpsKeystorePath,
String httpsKeystoreType, String httpsPasswordEnv, String httpsPublicBaseUrl) {
}
@Override
public void onEnable() {
this.shuttingDown = false;
this.configurationManager = new ConfigurationManager(this);
this.configurationManager.saveResources();
this.messageManager = new MessageManager(this);
try {
this.configurationManager.validate();
RuntimeSettings settings = this.snapshotSettings();
this.initializeExecutors();
this.startInitialization(settings);
} catch (Exception exception) {
this.getLogger().severe("LunarLogin could not start securely: " + exception.getMessage());
this.closeServices();
new FailClosedListener(this, () -> this.runtimeReady);
}
}
private void startInitialization(RuntimeSettings settings) {
new FailClosedListener(this, () -> this.runtimeReady);
try {
this.executor.execute(() -> {
Exception failure = null;
try {
this.initializeServices(settings);
} catch (Exception exception) {
failure = exception;
}
if (this.shuttingDown) {
this.closeServices();
return;
}
Exception result = failure;
try {
Bukkit.getScheduler().runTask(this, () -> this.finishStartup(result));
} catch (IllegalPluginAccessException exception) {
this.closeServices();
}
});
} catch (java.util.concurrent.RejectedExecutionException exception) {
this.finishStartup(exception);
}
}
private void initializeExecutors() {
AtomicInteger threadNumber = new AtomicInteger();
ThreadFactory factory = task -> {
Thread thread = new Thread(task, "LunarLogin-worker-" + threadNumber.incrementAndGet());
thread.setDaemon(true);
return thread;
};
this.executor = new ThreadPoolExecutor(4, 4, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(64), factory, new ThreadPoolExecutor.AbortPolicy());
this.microsoftExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(16), factory, new ThreadPoolExecutor.AbortPolicy());
}
private RuntimeSettings snapshotSettings() {
var config = this.getConfig();
var database = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "database.yml"));
var security = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "security.yml"));
var premium = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "premium.yml"));
DatabaseManager.Settings databaseSettings = new DatabaseManager.Settings(
database.getString("type", "SQLITE"), database.getString("sqlite-file", "accounts.db"),
database.getInt("connection-timeout-seconds", 5), database.getString("mysql.host", "127.0.0.1"),
database.getInt("mysql.port", 3306), database.getString("mysql.database", "lunarlogin"),
database.getString("mysql.username", "lunarlogin"), database.getString("mysql.password-env", "LUNARLOGIN_MYSQL_PASSWORD"),
database.getString("mysql.ssl-mode", "VERIFY_IDENTITY"));
return new RuntimeSettings(this.getDataFolder(), databaseSettings, security.getInt("monitor.alert-threshold", 5),
security.getInt("monitor.retain-events-days", 90), config.getInt("security.password.argon2id-iterations"),
config.getInt("security.password.argon2id-memory-kib"), config.getInt("security.password.argon2id-parallelism"),
config.getInt("security.password.minimum-length"), config.getInt("security.password.maximum-length"),
config.getInt("security.maximum-login-attempts", 5), config.getInt("security.authentication-timeout-seconds"),
this.configurationManager.sessionDurationMillis(), premium.getBoolean("enabled", false),
premium.getString("device-code.client-id", ""), premium.getString("device-code.scope", "XboxLive.signin offline_access"),
premium.getInt("device-code.timeout-seconds", 900), config.getBoolean("security.credentials.https-enabled", false),
config.getString("security.credentials.bind-address", "0.0.0.0"), config.getInt("security.credentials.port", 9443),
config.getString("security.credentials.keystore-path", "plugins/LunarLogin/https.p12"),
config.getString("security.credentials.keystore-type", "PKCS12"),
config.getString("security.credentials.keystore-password-env", "LUNARLOGIN_KEYSTORE_PASSWORD"),
config.getString("security.credentials.public-base-url", ""));
}
private void finishStartup(Exception failure) {
if (failure != null) {
this.getLogger().severe("LunarLogin could not start securely: " + failure.getMessage());
this.closeServices();
return;
}
Bukkit.getPluginManager().registerEvents(new AuthenticationListener(this), this);
LunarLoginCommand command = new LunarLoginCommand(this);
this.getCommand("lunarlogin").setExecutor(command);
this.getCommand("lunarlogin").setTabCompleter(command);
this.getCommand("lunarregister").setExecutor(new RegisterCommand(this));
for (Player player : Bukkit.getOnlinePlayers()) this.beginAuthentication(player);
this.runtimeReady = true;
this.getLogger().info("LunarLogin enabled in fail-closed mode.");
}
private void initializeServices(RuntimeSettings settings) throws Exception {
this.database = new DatabaseManager(settings.dataFolder(), settings.database(), settings.auditRetentionDays());
this.sessionManager = new SessionManager(this);
this.challengeManager = new ChallengeManager(10000);
this.securityMonitor = new SecurityMonitor(this, this.database, this.executor, settings.auditAlertThreshold());
PasswordHasher passwordHasher = new PasswordHasher(settings.argonIterations(), settings.argonMemoryKiB(), settings.argonParallelism(),
settings.minimumPasswordLength(), settings.maximumPasswordLength());
RateLimiter rateLimiter = new RateLimiter(settings.maximumLoginAttempts(), 1000, 300000, 100000);
long sessionDuration = settings.sessionDurationMillis();
PremiumIdentityService identities = new PremiumIdentityService(this.database, this.securityMonitor);
this.authenticationManager = new AuthenticationManager(this, this.database, passwordHasher, identities, this.sessionManager, this.messageManager,
this.challengeManager, this.securityMonitor, rateLimiter, this.executor,
settings.authenticationTimeoutSeconds(), settings.maximumPasswordLength(), sessionDuration);
this.microsoftVerification = new MicrosoftVerificationService(this, this.authenticationManager, identities, this.securityMonitor,
this.microsoftExecutor, settings.premiumEnabled(), settings.premiumClientId(), settings.premiumScope(), settings.premiumTimeoutSeconds(), sessionDuration);
if (settings.httpsEnabled()) {
this.httpsCredentialServer = new HttpsCredentialServer(this, this.authenticationManager, this.securityMonitor, this.executor,
settings.httpsBindAddress(), settings.httpsPort(), settings.httpsKeystorePath(), settings.httpsKeystoreType(),
settings.httpsPasswordEnv(), settings.httpsPublicBaseUrl());
}
}
public void beginAuthentication(Player player) {
this.authenticationManager.beginConnection(player);
if (player.hasPermission("lunarlogin.bypass")) return;
this.messageManager.send(player, "login-required", "Authenticate before using server features.");
if (this.httpsCredentialServer != null) this.sendCredentialLink(player);
else this.messageManager.send(player, "https-unavailable", "Secure HTTPS credential login is not configured.");
if (this.microsoftVerification.start(player)) player.sendMessage("§bIf this is a Premium account, complete the Microsoft device verification shown shortly.");
long timeoutSeconds = Math.max(this.getConfig().getLong("security.authentication-timeout-seconds", 120), this.microsoftVerification.pendingTimeoutSeconds());
long timeout = timeoutSeconds * 20;
Bukkit.getScheduler().runTaskLater(this, () -> {
if (player.isOnline() && !this.isAuthenticated(player.getUniqueId()) && !player.hasPermission("lunarlogin.bypass")) {
player.kickPlayer("Authentication timed out. Reconnect and authenticate securely.");
}
}, timeout);
}
public void sendCredentialLink(Player player) {
if (this.httpsCredentialServer == null) {
this.messageManager.send(player, "https-unavailable", "Secure HTTPS credential login is not configured.");
return;
}
try {
String challenge = this.authenticationManager.newCredentialChallenge(player);