diff options
| author | mdxd44 <ogurec332@mail.ru> | 2021-12-17 19:31:55 +0900 | 
|---|---|---|
| committer | mdxd44 <ogurec332@mail.ru> | 2021-12-17 19:31:55 +0900 | 
| commit | cff1b4a22bb47c8bcf064d5e8da8c7d7ef67ea52 (patch) | |
| tree | 9fc8614b144288af2749c2376c8ca523cd2a0cc0 /src | |
| parent | f11b09654cc33f4c3d9239c04be5978cbe3cad2d (diff) | |
| download | LimboAuth-cff1b4a22bb47c8bcf064d5e8da8c7d7ef67ea52.tar.gz LimboAuth-cff1b4a22bb47c8bcf064d5e8da8c7d7ef67ea52.tar.bz2 LimboAuth-cff1b4a22bb47c8bcf064d5e8da8c7d7ef67ea52.zip | |
Split projects.
Diffstat (limited to 'src')
16 files changed, 2339 insertions, 0 deletions
| diff --git a/src/main/java/net/elytrium/limboauth/LimboAuth.java b/src/main/java/net/elytrium/limboauth/LimboAuth.java new file mode 100644 index 0000000..a901bc2 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/LimboAuth.java @@ -0,0 +1,371 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +import com.google.inject.Inject; +import com.google.inject.name.Named; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.field.FieldType; +import com.j256.ormlite.jdbc.JdbcPooledConnectionSource; +import com.j256.ormlite.table.TableUtils; +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Dependency; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.PluginContainer; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import net.elytrium.limboapi.api.Limbo; +import net.elytrium.limboapi.api.LimboFactory; +import net.elytrium.limboapi.api.chunk.Dimension; +import net.elytrium.limboapi.api.chunk.VirtualWorld; +import net.elytrium.limboapi.api.file.SchematicFile; +import net.elytrium.limboapi.api.file.WorldFile; +import net.elytrium.limboauth.command.ChangePasswordCommand; +import net.elytrium.limboauth.command.DestroySessionCommand; +import net.elytrium.limboauth.command.ForceUnregisterCommand; +import net.elytrium.limboauth.command.LimboAuthCommand; +import net.elytrium.limboauth.command.TotpCommand; +import net.elytrium.limboauth.command.UnregisterCommand; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.listener.AuthListener; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.elytrium.limboauth.utils.UpdatesChecker; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.slf4j.Logger; + +@Plugin( +    id = "limboauth", +    name = "LimboAuth", +    version = BuildConstants.AUTH_VERSION, +    url = "https://elytrium.net/", +    authors = {"hevav", "mdxd44"}, +    dependencies = {@Dependency(id = "limboapi")} +) +public class LimboAuth { + +  private static LimboAuth instance; + +  private final HttpClient client = HttpClient.newHttpClient(); +  private final Path dataDirectory; +  private final Logger logger; +  private final ProxyServer server; +  private final LimboFactory factory; + +  private Dao<RegisteredPlayer, String> playerDao; +  private Limbo authServer; +  private Map<String, CachedUser> cachedAuthChecks; +  private Component nicknameInvalid; +  private Pattern nicknameValidationPattern; + +  @Inject +  @SuppressWarnings("OptionalGetWithoutIsPresent") +  public LimboAuth(ProxyServer server, Logger logger, @Named("limboapi") PluginContainer factory, @DataDirectory Path dataDirectory) { +    setInstance(this); + +    this.server = server; +    this.logger = logger; +    this.dataDirectory = dataDirectory; +    this.factory = (LimboFactory) factory.getInstance().get(); +  } + +  @Subscribe +  public void onProxyInitialization(ProxyInitializeEvent event) throws SQLException { +    System.setProperty("com.j256.simplelogging.level", "ERROR"); + +    this.reload(); + +    UpdatesChecker.checkForUpdates(this.getLogger()); +  } + +  @SuppressWarnings("SwitchStatementWithTooFewBranches") +  public void reload() throws SQLException { +    Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml")); + +    this.cachedAuthChecks = new ConcurrentHashMap<>(); + +    Settings.DATABASE dbConfig = Settings.IMP.DATABASE; + +    JdbcPooledConnectionSource connectionSource; +    // requireNonNull prevents the shade plugin from excluding the drivers in minimized jar. +    switch (dbConfig.STORAGE_TYPE.toLowerCase(Locale.ROOT)) { +      case "h2": { +        Objects.requireNonNull(org.h2.Driver.class); +        Objects.requireNonNull(org.h2.engine.Engine.class); +        connectionSource = new JdbcPooledConnectionSource("jdbc:h2:" + this.dataDirectory.toFile().getAbsoluteFile() + "/" + "limboauth"); +        break; +      } +      case "mysql": { +        Objects.requireNonNull(com.mysql.cj.jdbc.Driver.class); +        Objects.requireNonNull(com.mysql.cj.conf.url.SingleConnectionUrl.class); +        connectionSource = new JdbcPooledConnectionSource( +            "jdbc:mysql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD +        ); +        break; +      } +      case "postgresql": { +        Objects.requireNonNull(org.postgresql.Driver.class); +        connectionSource = new JdbcPooledConnectionSource( +            "jdbc:postgresql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD +        ); +        break; +      } +      default: { +        this.getLogger().error("WRONG DATABASE TYPE."); +        this.server.shutdown(); +        return; +      } +    } + +    TableUtils.createTableIfNotExists(connectionSource, RegisteredPlayer.class); +    this.playerDao = DaoManager.createDao(connectionSource, RegisteredPlayer.class); +    this.nicknameValidationPattern = Pattern.compile(Settings.IMP.MAIN.ALLOWED_NICKNAME_REGEX); + +    this.migrateDb(this.playerDao); + +    CommandManager manager = this.server.getCommandManager(); +    manager.unregister("unregister"); +    manager.unregister("forceunregister"); +    manager.unregister("changepassword"); +    manager.unregister("destroysession"); +    manager.unregister("2fa"); +    manager.unregister("limboauth"); + +    manager.register("unregister", new UnregisterCommand(this, this.playerDao), "unreg"); +    manager.register("forceunregister", new ForceUnregisterCommand(this, this.server, this.playerDao), "forceunreg"); +    manager.register("changepassword", new ChangePasswordCommand(this.playerDao), "changepass"); +    manager.register("destroysession", new DestroySessionCommand(this)); +    if (Settings.IMP.MAIN.ENABLE_TOTP) { +      manager.register("2fa", new TotpCommand(this.playerDao), "totp"); +    } +    manager.register("limboauth", new LimboAuthCommand(), "la", "auth", "lauth"); + +    Settings.MAIN.AUTH_COORDS authCoords = Settings.IMP.MAIN.AUTH_COORDS; +    VirtualWorld authWorld = this.factory.createVirtualWorld( +        Dimension.valueOf(Settings.IMP.MAIN.DIMENSION), +        authCoords.X, authCoords.Y, authCoords.Z, +        (float) authCoords.YAW, (float) authCoords.PITCH +    ); + +    if (Settings.IMP.MAIN.LOAD_WORLD) { +      try { +        Path path = this.dataDirectory.resolve(Settings.IMP.MAIN.WORLD_FILE_PATH); +        WorldFile file; +        switch (Settings.IMP.MAIN.WORLD_FILE_TYPE) { +          case "schematic": { +            file = new SchematicFile(path); +            break; +          } +          default: { +            this.getLogger().error("Incorrect world file type."); +            this.server.shutdown(); +            return; +          } +        } + +        Settings.MAIN.WORLD_COORDS coords = Settings.IMP.MAIN.WORLD_COORDS; +        file.toWorld(this.factory, authWorld, coords.X, coords.Y, coords.Z); +      } catch (IOException e) { +        e.printStackTrace(); +      } +    } + +    this.authServer = this.factory.createLimbo(authWorld); + +    this.nicknameInvalid = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NICKNAME_INVALID); + +    this.server.getEventManager().unregisterListeners(this); +    this.server.getEventManager().register(this, new AuthListener(this.playerDao)); + +    Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(() -> +        this.checkCache(this.cachedAuthChecks, Settings.IMP.MAIN.PURGE_CACHE_MILLIS), +        Settings.IMP.MAIN.PURGE_CACHE_MILLIS, +        Settings.IMP.MAIN.PURGE_CACHE_MILLIS, +        TimeUnit.MILLISECONDS +    ); +  } + +  public void migrateDb(Dao<RegisteredPlayer, String> playerDao) { +    Set<FieldType> tables = new HashSet<>(); +    Collections.addAll(tables, playerDao.getTableInfo().getFieldTypes()); + +    String findSql; +    switch (Settings.IMP.DATABASE.STORAGE_TYPE) { +      case "h2": { +        findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" +            + playerDao.getTableInfo().getTableName() + "';"; +        break; +      } +      case "postgresql": +      case "mysql": { +        findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" + Settings.IMP.DATABASE.DATABASE +            + "' AND TABLE_NAME = '" + playerDao.getTableInfo().getTableName() + "';"; +        break; +      } +      default: { +        this.getLogger().error("WRONG DATABASE TYPE."); +        this.server.shutdown(); +        return; +      } +    } + +    try { +      playerDao.queryRaw(findSql).forEach(e -> tables.removeIf(q -> q.getColumnName().equalsIgnoreCase(e[0]))); + +      tables.forEach(t -> { +        try { +          String columnDefinition = t.getColumnDefinition(); +          StringBuilder builder = new StringBuilder("ALTER TABLE `auth` ADD "); +          List<String> dummy = new ArrayList<>(); +          if (columnDefinition == null) { +            playerDao.getConnectionSource().getDatabaseType().appendColumnArg(t.getTableName(), builder, t, dummy, dummy, dummy, dummy); +          } else { +            playerDao.getConnectionSource().getDatabaseType().appendEscapedEntityName(builder, t.getColumnName()); +            builder.append(" ").append(columnDefinition).append(" "); +          } + +          playerDao.executeRawNoArgs(builder.toString()); +        } catch (SQLException e) { +          e.printStackTrace(); +        } +      }); +    } catch (SQLException e) { +      e.printStackTrace(); +    } +  } + +  public void cacheAuthUser(Player player) { +    String username = player.getUsername(); +    this.cachedAuthChecks.remove(username); +    this.cachedAuthChecks.put(username, new CachedUser(player.getRemoteAddress().getAddress(), System.currentTimeMillis())); +  } + +  public void removePlayerFromCache(Player player) { +    this.cachedAuthChecks.remove(player.getUsername()); +  } + +  public boolean needAuth(Player player) { +    String username = player.getUsername(); + +    if (!this.cachedAuthChecks.containsKey(username)) { +      return true; +    } + +    return !this.cachedAuthChecks.get(username).getInetAddress().equals(player.getRemoteAddress().getAddress()); +  } + +  public void authPlayer(Player player) { +    String nickname = player.getUsername(); +    if (!this.nicknameValidationPattern.matcher(nickname).matches()) { +      player.disconnect(this.nicknameInvalid); +      return; +    } + +    if (!Settings.IMP.MAIN.ONLINE_MODE_NEED_AUTH && player.isOnlineMode()) { +      RegisteredPlayer registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, player.getUsername()); + +      if (registeredPlayer == null || registeredPlayer.getHash().isEmpty()) { +        this.factory.passLoginLimbo(player); +        return; +      } +    } + +    // Send player to auth virtual server. +    try { +      this.authServer.spawnPlayer(player, new AuthSessionHandler(this.playerDao, player, nickname)); +    } catch (Throwable t) { +      this.getLogger().error("Error", t); +    } +  } + +  public boolean isPremium(String nickname) { +    try { +      HttpRequest request = HttpRequest.newBuilder() +          .uri(URI.create(String.format(Settings.IMP.MAIN.ISPREMIUM_AUTH_URL, nickname))) +          .build(); +      HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString()); +      return response.statusCode() == 200; +    } catch (IOException | InterruptedException e) { +      this.getLogger().error("Unable to authenticate with Mojang", e); +      return true; +    } +  } + +  public Logger getLogger() { +    return this.logger; +  } + +  private void checkCache(Map<String, CachedUser> userMap, long time) { +    userMap.entrySet().stream() +        .filter(u -> u.getValue().getCheckTime() + time <= System.currentTimeMillis()) +        .map(Map.Entry::getKey) +        .forEach(userMap::remove); +  } + +  private static void setInstance(LimboAuth instance) { +    LimboAuth.instance = instance; +  } + +  public static LimboAuth getInstance() { +    return instance; +  } + +  private static class CachedUser { + +    private final InetAddress inetAddress; +    private final long checkTime; + +    public CachedUser(InetAddress inetAddress, long checkTime) { +      this.inetAddress = inetAddress; +      this.checkTime = checkTime; +    } + +    public InetAddress getInetAddress() { +      return this.inetAddress; +    } + +    public long getCheckTime() { +      return this.checkTime; +    } +  } +} diff --git a/src/main/java/net/elytrium/limboauth/Settings.java b/src/main/java/net/elytrium/limboauth/Settings.java new file mode 100644 index 0000000..9e59830 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/Settings.java @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +import java.io.File; +import net.elytrium.limboauth.config.Config; + +public class Settings extends Config { + +  @Ignore +  public static final Settings IMP = new Settings(); + +  @Final +  public String VERSION = BuildConstants.AUTH_VERSION; + +  public String PREFIX = "LimboAuth &6>>&f"; + +  @Create +  public MAIN MAIN; + +  public static class MAIN { + +    public boolean ENABLE_BOSSBAR = true; +    public boolean ONLINE_MODE_NEED_AUTH = true; +    public boolean FORCE_OFFLINE_UUID = false; +    @Comment({ +        "Forcibly set player's UUID to the value from the database", +        "If the player had the cracked account, and switched to the premium account, the cracked UUID will be used." +    }) +    public boolean SAVE_UUID = true; +    public boolean ENABLE_TOTP = true; +    public boolean TOTP_NEED_PASSWORD = true; +    public boolean REGISTER_NEED_REPEAT_PASSWORD = true; +    public boolean CHANGE_PASSWORD_NEED_OLD_PASSWORD = true; +    @Comment({ +        "If you want to migrate your database from another plugin, which is not using BCrypt", +        "You can set an old hash algorithm to migrate from. Currently, only AUTHME is supported yet" +    }) +    public String MIGRATION_HASH = ""; +    @Comment("Available dimensions: OVERWORLD, NETHER, THE_END") +    public String DIMENSION = "THE_END"; +    public long PURGE_CACHE_MILLIS = 3600000; +    @Comment("QR Generator URL, set {data} placeholder") +    public String QR_GENERATOR_URL = "https://api.qrserver.com/v1/create-qr-code/?data={data}&size=200x200&ecc=M&margin=30"; +    public String TOTP_ISSUER = "LimboAuth by Elytrium"; +    public int BCRYPT_COST = 10; +    public int LOGIN_ATTEMPTS = 3; +    public int IP_LIMIT_REGISTRATIONS = 3; +    public int TOTP_RECOVERY_CODES_AMOUNT = 16; +    @Comment("Time in milliseconds, when ip limit works, set to 0 for disable") +    public long IP_LIMIT_VALID_TIME = 21600000; +    @Comment({ +        "Regex of allowed nicknames", +        "^ means the start of the line, $ means the end of the line", +        "[A-Za-z0-9_] is a character set of A-Z, a-z, 0-9 and _", +        "{3,16} means that allowed length is from 3 to 16 chars" +    }) +    public String ALLOWED_NICKNAME_REGEX = "^[A-Za-z0-9_]{3,16}$"; + +    public boolean LOAD_WORLD = false; +    @Comment("World file type: schematic") +    public String WORLD_FILE_TYPE = "schematic"; +    public String WORLD_FILE_PATH = "world.schematic"; +    @Comment({ +        "Custom isPremium URL", +        "You can use Mojang one's API (set by default)", +        "Or CloudFlare one's: https://api.ashcon.app/mojang/v1/user/%s", +        "Or use this code to make your own API: https://blog.cloudflare.com/minecraft-api-with-workers-coffeescript/", +        "Or implement your own API, it should just respond with HTTP code 200 only if the player is premium" +    }) +    public String ISPREMIUM_AUTH_URL = "https://api.mojang.com/users/profiles/minecraft/%s"; + +    @Create +    public Settings.MAIN.WORLD_COORDS WORLD_COORDS; + +    public static class WORLD_COORDS { + +      public int X = 0; +      public int Y = 0; +      public int Z = 0; +    } + +    @Create +    public MAIN.STRINGS STRINGS; + +    //@Comment("Leave empty to disable.") +    public static class STRINGS { + +      public String RELOAD = "{PRFX} &aReloaded successfully!"; +      public String RELOAD_FAILED = "{PRFX} &cReload failed, check console for details."; +      public String ERROR_OCCURRED = "{PRFX} &cAn internal error has occurred!"; + +      public String NOT_PLAYER = "{PRFX} &cСonsole is not allowed to execute this command!"; +      public String NOT_REGISTERED = "{PRFX} &cYou are not registered!"; +      public String WRONG_PASSWORD = "{PRFX} &cPassword is wrong!"; + +      public String NICKNAME_INVALID = "{NL}{NL}&cYour nickname contains forbidden characters. Please, change your nickname!"; +      @Comment("6 hours by default in ip-limit-valid-time") +      public String IP_LIMIT = "{PRFX} &cYour IP has reached max registered accounts. If this is an error, restart your router, or wait about 6 hours."; +      public String WRONG_NICKNAME_CASE = "{NL}{NL}&cThe case of your nickname is wrong. Nickname is CaSe SeNsItIvE."; + +      public String LOGIN = "{PRFX} Please, login using &6/login &6<password>. You have &6{0} &cattempts."; +      public String LOGIN_SUCCESS = "{PRFX} &aSuccessfully logged in!"; +      public String LOGIN_WRONG_PASSWORD = "{PRFX} &cYou've entered the wrong password. You have &6{0} &cattempts left."; +      public String LOGIN_TITLE = ""; +      public String LOGIN_SUBTITLE = ""; +      public String LOGIN_SUCCESS_TITLE = ""; +      public String LOGIN_SUCCESS_SUBTITLE = ""; + +      @Comment("Or if register-need-repeat-password set to false remove the \"<repeat password>\" part.") +      public String REGISTER = "{PRFX} Please, register using &6/register <password> <repeat password>"; +      public String REGISTER_TITLE = ""; +      public String REGISTER_SUBTITLE = ""; +      public String DIFFERENT_PASSWORDS = "{PRFX} The entered passwords differ from each other."; +      public String KICK_PASSWORD_WRONG = "{NL}{NL}&cYou've entered the wrong password numerous times!"; + +      public String UNREGISTER_SUCCESSFUL = "{PRFX}{NL}{NL}&aSuccessfully unregistered!"; +      public String UNREGISTER_USAGE = "{PRFX} Usage: &6/unregister <current password> confirm"; + +      public String FORCE_UNREGISTER_SUCCESSFUL = "{PRFX} &a{0} successfully unregistered!"; +      public String FORCE_UNREGISTER_SUCCESSFUL_PLAYER = "{PRFX}{NL}{NL}&aYou have been unregistered by administrator!"; +      public String FORCE_UNREGISTER_NOT_SUCCESSFUL = "{PRFX} &cUnable to unregister {0}. Most likely this player has never been on this server."; +      public String FORCE_UNREGISTER_USAGE = "{PRFX} Usage: &6/forceunregister <nickname>"; + +      public String CHANGE_PASSWORD_SUCCESSFUL = "{PRFX} &aSuccessfully changed password!"; +      @Comment("Or if change-password-need-old-pass set to false remove the \"<old password>\" part.") +      public String CHANGE_PASSWORD_USAGE = "{PRFX} Usage: &6/changepassword <old password> <new password>"; + +      public String TOTP = "{PRFX} Please, enter your 2FA key using &6/2fa <key>"; +      public String TOTP_SUCCESSFUL = "{PRFX} &aSuccessfully enabled 2FA!"; +      public String TOTP_DISABLED = "{PRFX} &aSuccessfully disabled 2FA!"; +      @Comment("Or if totp-need-pass set to false remove the \"<current password>\" part.") +      public String TOTP_USAGE = "{PRFX} Usage: &6/2fa enable <current password>&f or &6/2fa disable <totp key>&f."; +      public String TOTP_WRONG = "{PRFX} &cWrong 2FA key!"; +      public String TOTP_ALREADY_ENABLED = "{PRFX} &c2FA is already enabled. Disable it using &6/2fa disable <key>&c."; +      public String TOTP_QR = "{PRFX} Click here to open 2FA QR code in browser."; +      public String TOTP_TOKEN = "{PRFX} &aYour 2FA token &7(Click to copy)&a: &6{0}"; +      public String TOTP_RECOVERY = "{PRFX} &aYour recovery codes &7(Click to copy)&a: &6{0}"; + +      public String DESTROY_SESSION_SUCCESSFUL = "{PRFX} &eYour session is now destroyed, you'll need to log in again after reconnecting."; +    } + +    @Create +    public MAIN.AUTH_COORDS AUTH_COORDS; + +    public static class AUTH_COORDS { + +      public double X = 0; +      public double Y = 0; +      public double Z = 0; +      public double YAW = 0; +      public double PITCH = 0; +    } +  } + +  @Create +  public DATABASE DATABASE; + +  @Comment("Database settings") +  public static class DATABASE { + +    @Comment("Database type: mysql, postgresql or h2.") +    public String STORAGE_TYPE = "h2"; + +    @Comment("Settings for Network-based database (like MySQL, PostgreSQL): ") +    public String HOSTNAME = "127.0.0.1:3306"; +    public String USER = "user"; +    public String PASSWORD = "password"; +    public String DATABASE = "limboauth"; +    public String CONNECTION_PARAMETERS = "?autoReconnect=true&initialTimeout=1&useSSL=false"; +  } + +  public void reload(File file) { +    if (this.load(file, this.PREFIX)) { +      this.save(file); +    } else { +      this.save(file); +      this.load(file, this.PREFIX); +    } +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java new file mode 100644 index 0000000..2373938 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import java.sql.SQLException; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ChangePasswordCommand implements SimpleCommand { + +  private final Dao<RegisteredPlayer, String> playerDao; + +  private final Component notPlayer; +  private final boolean needOldPass; +  private final Component notRegistered; +  private final Component wrongPassword; +  private final Component successful; +  private final Component errorOccurred; +  private final Component usage; + +  public ChangePasswordCommand(Dao<RegisteredPlayer, String> playerDao) { +    this.playerDao = playerDao; + +    this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); +    this.needOldPass = Settings.IMP.MAIN.CHANGE_PASSWORD_NEED_OLD_PASSWORD; +    this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); +    this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); +    this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_SUCCESSFUL); +    this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); +    this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_USAGE); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (!(source instanceof Player)) { +      source.sendMessage(this.notPlayer); +      return; +    } + +    if (this.needOldPass ? args.length == 2 : args.length == 1) { +      if (this.needOldPass) { +        RegisteredPlayer player = AuthSessionHandler.fetchInfo(this.playerDao, ((Player) source).getUsername()); +        if (player == null) { +          source.sendMessage(this.notRegistered); +          return; +        } else if (!AuthSessionHandler.checkPassword(args[0], player, this.playerDao)) { +          source.sendMessage(this.wrongPassword); +          return; +        } +      } + +      try { +        UpdateBuilder<RegisteredPlayer, String> updateBuilder = this.playerDao.updateBuilder(); +        updateBuilder.where().eq("nickname", ((Player) source).getUsername()); +        updateBuilder.updateColumnValue("hash", AuthSessionHandler.genHash(this.needOldPass ? args[1] : args[0])); +        updateBuilder.update(); + +        source.sendMessage(this.successful); +      } catch (SQLException e) { +        source.sendMessage(this.errorOccurred); +        e.printStackTrace(); +      } + +      return; +    } + +    source.sendMessage(this.usage); +  } + +  @Override +  public boolean hasPermission(SimpleCommand.Invocation invocation) { +    return invocation.source().getPermissionValue("limboauth.commands.changepassword") != Tristate.FALSE; +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java new file mode 100644 index 0000000..27dff72 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class DestroySessionCommand implements SimpleCommand { + +  private final LimboAuth plugin; + +  private final Component notPlayer; +  private final Component successful; + +  public DestroySessionCommand(LimboAuth plugin) { +    this.plugin = plugin; + +    this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); +    this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.DESTROY_SESSION_SUCCESSFUL); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); + +    if (!(source instanceof Player)) { +      source.sendMessage(this.notPlayer); +      return; +    } + +    this.plugin.removePlayerFromCache((Player) source); +    source.sendMessage(this.successful); +  } + +  @Override +  public boolean hasPermission(SimpleCommand.Invocation invocation) { +    return invocation.source().getPermissionValue("limboauth.commands.destroysession") != Tristate.FALSE; +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java new file mode 100644 index 0000000..d45eae9 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.google.common.collect.ImmutableList; +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ForceUnregisterCommand implements SimpleCommand { + +  private final LimboAuth plugin; +  private final ProxyServer server; +  private final Dao<RegisteredPlayer, String> playerDao; + +  private final Component successfulPlayer; +  private final String successful; +  private final String notSuccessful; +  private final Component usage; + +  public ForceUnregisterCommand(LimboAuth plugin, ProxyServer server, Dao<RegisteredPlayer, String> playerDao) { +    this.plugin = plugin; +    this.server = server; +    this.playerDao = playerDao; + +    this.successfulPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL_PLAYER); +    this.successful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL; +    this.notSuccessful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_NOT_SUCCESSFUL; +    this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_USAGE); +  } + +  @Override +  public List<String> suggest(SimpleCommand.Invocation invocation) { +    String[] args = invocation.arguments(); + +    if (args.length == 0) { +      return this.server.getAllPlayers().stream() +          .map(Player::getUsername) +          .collect(Collectors.toList()); +    } else if (args.length == 1) { +      return this.server.getAllPlayers().stream() +          .map(Player::getUsername) +          .filter(str -> str.regionMatches(true, 0, args[0], 0, args[0].length())) +          .collect(Collectors.toList()); +    } + +    return ImmutableList.of(); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (args.length == 1) { +      String playerNick = args[0]; +      try { +        this.playerDao.deleteById(playerNick.toLowerCase(Locale.ROOT)); +        this.server.getPlayer(playerNick).ifPresent(player -> { +          this.plugin.removePlayerFromCache(player); +          player.disconnect(this.successfulPlayer); +        }); +        source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(this.successful, playerNick))); +      } catch (SQLException e) { +        source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(this.notSuccessful, playerNick))); +        e.printStackTrace(); +      } + +      return; +    } + +    source.sendMessage(this.usage); +  } + +  @Override +  public boolean hasPermission(SimpleCommand.Invocation invocation) { +    return invocation.source().hasPermission("limboauth.admin.forceunregister"); +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java b/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java new file mode 100644 index 0000000..611b1c3 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/LimboAuthCommand.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.google.common.collect.ImmutableList; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class LimboAuthCommand implements SimpleCommand { + +  @Override +  public List<String> suggest(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (args.length == 0) { +      return this.getSubCommands() +          .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) +          .collect(Collectors.toList()); +    } else if (args.length == 1) { +      return this.getSubCommands() +          .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) +          .filter(str -> str.regionMatches(true, 0, args[0], 0, args[0].length())) +          .collect(Collectors.toList()); +    } + +    return ImmutableList.of(); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (args.length == 1) { +      if (args[0].equalsIgnoreCase("reload") && source.hasPermission("limboauth.admin.reload")) { +        try { +          LimboAuth.getInstance().reload(); +          source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD)); +        } catch (Exception e) { +          source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD_FAILED)); +          e.printStackTrace(); +        } +      } else { +        this.showHelp(source); +      } + +      return; +    } + +    this.showHelp(source); +  } + +  private void showHelp(CommandSource source) { +    source.sendMessage(Component.text("§eThis server is using LimboAuth and LimboAPI")); +    source.sendMessage(Component.text("§e(c) 2021 Elytrium")); +    source.sendMessage(Component.text("§ahttps://ely.su/github/")); +    source.sendMessage(Component.text("§r")); +    source.sendMessage(Component.text("§fAvailable subcommands:")); +    // Java moment +    this.getSubCommands() +        .filter(cmd -> source.hasPermission("limboauth.admin." + cmd)) +        .forEach(cmd -> { +          if (cmd.equals("reload")) { +            source.sendMessage(Component.text("    §a/limboauth reload §8- §eReload config")); +          } +        }); +  } + +  private Stream<String> getSubCommands() { +    return Stream.of("reload"); +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/TotpCommand.java b/src/main/java/net/elytrium/limboauth/command/TotpCommand.java new file mode 100644 index 0000000..d51da7d --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/TotpCommand.java @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import dev.samstevens.totp.qr.QrData; +import dev.samstevens.totp.recovery.RecoveryCodeGenerator; +import dev.samstevens.totp.secret.DefaultSecretGenerator; +import dev.samstevens.totp.secret.SecretGenerator; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.text.MessageFormat; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class TotpCommand implements SimpleCommand { + +  private final SecretGenerator secretGenerator = new DefaultSecretGenerator(); +  private final RecoveryCodeGenerator codesGenerator = new RecoveryCodeGenerator(); +  private final Dao<RegisteredPlayer, String> playerDao; + +  private final Component notPlayer; +  private final Component usage; +  private final boolean needPassword; +  private final Component notRegistered; +  private final Component wrongPassword; +  private final Component alreadyEnabled; +  private final Component errorOccurred; +  private final Component successful; +  private final String issuer; +  private final String qrGeneratorUrl; +  private final Component qr; +  private final String token; +  private final int recoveryCodesAmount; +  private final String recovery; +  private final Component disabled; +  private final Component wrong; + +  public TotpCommand(Dao<RegisteredPlayer, String> playerDao) { +    this.playerDao = playerDao; + +    this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); +    this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_USAGE); +    this.needPassword = Settings.IMP.MAIN.TOTP_NEED_PASSWORD; +    this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); +    this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); +    this.alreadyEnabled = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_ALREADY_ENABLED); +    this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); +    this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_SUCCESSFUL); +    this.issuer = Settings.IMP.MAIN.TOTP_ISSUER; +    this.qrGeneratorUrl = Settings.IMP.MAIN.QR_GENERATOR_URL; +    this.qr = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_QR); +    this.token = Settings.IMP.MAIN.STRINGS.TOTP_TOKEN; +    this.recoveryCodesAmount = Settings.IMP.MAIN.TOTP_RECOVERY_CODES_AMOUNT; +    this.recovery = Settings.IMP.MAIN.STRINGS.TOTP_RECOVERY; +    this.disabled = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_DISABLED); +    this.wrong = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP_WRONG); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (!(source instanceof Player)) { +      source.sendMessage(this.notPlayer); +      return; +    } + +    if (args.length == 0) { +      source.sendMessage(this.usage); +    } else { +      String username = ((Player) source).getUsername(); + +      RegisteredPlayer playerInfo; +      UpdateBuilder<RegisteredPlayer, String> updateBuilder; +      switch (args[0]) { +        case "enable": { +          if (this.needPassword ? args.length == 2 : args.length == 1) { +            playerInfo = AuthSessionHandler.fetchInfo(this.playerDao, username); + +            if (playerInfo == null) { +              source.sendMessage(this.notRegistered); +              return; +            } else if (this.needPassword && !AuthSessionHandler.checkPassword(args[1], playerInfo, this.playerDao)) { +              source.sendMessage(this.wrongPassword); +              return; +            } + +            if (!playerInfo.getTotpToken().isEmpty()) { +              source.sendMessage(this.alreadyEnabled); +              return; +            } + +            String secret = this.secretGenerator.generate(); + +            try { +              updateBuilder = this.playerDao.updateBuilder(); +              updateBuilder.where().eq("nickname", username); +              updateBuilder.updateColumnValue("totpToken", secret); +              updateBuilder.update(); +            } catch (SQLException e) { +              source.sendMessage(this.errorOccurred); +              e.printStackTrace(); +            } + +            source.sendMessage(this.successful); + +            QrData data = new QrData.Builder() +                .label(username) +                .secret(secret) +                .issuer(this.issuer) +                .build(); + +            String qrUrl = this.qrGeneratorUrl.replace("{data}", URLEncoder.encode(data.getUri(), StandardCharsets.UTF_8)); + +            source.sendMessage(this.qr.clickEvent(ClickEvent.openUrl(qrUrl))); + +            source.sendMessage( +                LegacyComponentSerializer.legacyAmpersand().deserialize( +                    MessageFormat.format(this.token, secret) +                ).clickEvent(ClickEvent.copyToClipboard(secret)) +            ); + +            String codes = String.join(", ", this.codesGenerator.generateCodes(this.recoveryCodesAmount)); + +            source.sendMessage( +                LegacyComponentSerializer.legacyAmpersand().deserialize( +                    MessageFormat.format(this.recovery, codes) +                ).clickEvent(ClickEvent.copyToClipboard(codes)) +            ); +          } else { +            source.sendMessage(this.usage); +          } +          break; +        } +        case "disable": { +          if (args.length != 2) { +            source.sendMessage(this.usage); +            return; +          } + +          playerInfo = AuthSessionHandler.fetchInfo(this.playerDao, username); + +          if (playerInfo == null) { +            source.sendMessage(this.notRegistered); +            return; +          } + +          if (AuthSessionHandler.getVerifier().isValidCode(playerInfo.getTotpToken(), args[1])) { +            try { +              updateBuilder = this.playerDao.updateBuilder(); +              updateBuilder.where().eq("nickname", username); +              updateBuilder.updateColumnValue("totpToken", ""); +              updateBuilder.update(); + +              source.sendMessage(this.disabled); +            } catch (SQLException e) { +              source.sendMessage(this.errorOccurred); +              e.printStackTrace(); +            } +          } else { +            source.sendMessage(this.wrong); +          } +          break; +        } +        default: { +          source.sendMessage(this.usage); +          break; +        } +      } +    } +  } + +  @Override +  public boolean hasPermission(SimpleCommand.Invocation invocation) { +    return invocation.source().getPermissionValue("limboauth.commands.totp") != Tristate.FALSE; +  } +} diff --git a/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java b/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java new file mode 100644 index 0000000..aeab6ec --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/UnregisterCommand.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import java.sql.SQLException; +import java.util.Locale; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class UnregisterCommand implements SimpleCommand { + +  private final LimboAuth plugin; +  private final Dao<RegisteredPlayer, String> playerDao; + +  private final Component notPlayer; +  private final Component notRegistered; +  private final Component successful; +  private final Component errorOccurred; +  private final Component wrongPassword; +  private final Component usage; + +  public UnregisterCommand(LimboAuth plugin, Dao<RegisteredPlayer, String> playerDao) { +    this.plugin = plugin; +    this.playerDao = playerDao; + +    this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); +    this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); +    this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.UNREGISTER_SUCCESSFUL); +    this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); +    this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); +    this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.UNREGISTER_USAGE); +  } + +  @Override +  public void execute(SimpleCommand.Invocation invocation) { +    CommandSource source = invocation.source(); +    String[] args = invocation.arguments(); + +    if (!(source instanceof Player)) { +      source.sendMessage(this.notPlayer); +      return; +    } + +    if (args.length == 2) { +      if (args[1].equalsIgnoreCase("confirm")) { +        RegisteredPlayer player = AuthSessionHandler.fetchInfo(this.playerDao, ((Player) source).getUsername()); +        if (player == null) { +          source.sendMessage(this.notRegistered); +        } else if (AuthSessionHandler.checkPassword(args[0], player, this.playerDao)) { +          try { +            this.playerDao.deleteById(((Player) source).getUsername().toLowerCase(Locale.ROOT)); +            this.plugin.removePlayerFromCache((Player) source); +            ((Player) source).disconnect(this.successful); +          } catch (SQLException e) { +            source.sendMessage(this.errorOccurred); +            e.printStackTrace(); +          } +        } else { +          source.sendMessage(this.wrongPassword); +        } + +        return; +      } +    } + +    source.sendMessage(this.usage); +  } + +  @Override +  public boolean hasPermission(SimpleCommand.Invocation invocation) { +    return invocation.source().getPermissionValue("limboauth.commands.unregister") != Tristate.FALSE; +  } +} diff --git a/src/main/java/net/elytrium/limboauth/config/Config.java b/src/main/java/net/elytrium/limboauth/config/Config.java new file mode 100644 index 0000000..ed5b007 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/config/Config.java @@ -0,0 +1,392 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import net.elytrium.limboauth.LimboAuth; +import org.slf4j.Logger; +import org.yaml.snakeyaml.Yaml; + +public class Config { + +  private static final Logger LOGGER = LimboAuth.getInstance().getLogger(); +  private String oldPrefix = ""; +  private String currentPrefix = ""; + +  /** +   * Set the value of a specific node. Probably throws some error if you supply non-existing keys or invalid values. +   * +   * @param key   config node +   * @param value value +   */ +  private void set(String key, Object value, Class<?> root) { +    String[] split = key.split("\\."); +    Object instance = this.getInstance(split, root); +    if (instance != null) { +      Field field = this.getField(split, instance); +      if (field != null) { +        try { +          if (field.getAnnotation(Final.class) != null) { +            return; +          } +          if (field.getType() == String.class && !(value instanceof String)) { +            value = value + ""; +          } +          field.set(instance, value); +          return; +        } catch (Throwable e) { +          e.printStackTrace(); +        } +      } +    } + +    LOGGER.debug("Failed to set config option: " + key + ": " + value + " | " + instance + " | " + root.getSimpleName() + ".yml"); +  } + +  @SuppressWarnings("unchecked") +  public void set(Map<String, Object> input, String oldPath) { +    for (Map.Entry<String, Object> entry : input.entrySet()) { +      String key = oldPath + (oldPath.isEmpty() ? "" : ".") + entry.getKey(); +      Object value = entry.getValue(); + +      if (value instanceof Map) { +        this.set((Map<String, Object>) value, key); +      } else if (value instanceof String) { +        if (key.equalsIgnoreCase("prefix") && !this.currentPrefix.equals(value)) { +          this.currentPrefix = (String) value; +        } + +        this.set(key, ((String) value).replace("{NL}", "\n").replace("{PRFX}", this.currentPrefix), this.getClass()); +      } else { +        this.set(key, value, this.getClass()); +      } +    } +  } + +  public boolean load(File file, String prefix) { +    this.oldPrefix = this.currentPrefix.isEmpty() ? prefix : this.currentPrefix; +    this.currentPrefix = prefix; +    if (!file.exists()) { +      return false; +    } + +    try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) { +      this.set(new Yaml().load(reader), ""); +    } catch (IOException e) { +      LOGGER.warn("Unable to load config ", e); +      return false; +    } + +    return true; +  } + +  /** +   * Indicates that a field should be instantiated / created. +   */ +  @Retention(RetentionPolicy.RUNTIME) +  @Target({ElementType.FIELD}) +  public @interface Create { + +  } + +  /** +   * Indicates that a field cannot be modified. +   */ +  @Retention(RetentionPolicy.RUNTIME) +  @Target({ElementType.FIELD}) +  public @interface Final { + +  } + +  /** +   * Creates a comment. +   */ +  @Retention(RetentionPolicy.RUNTIME) +  @Target({ElementType.FIELD, ElementType.TYPE}) +  public @interface Comment { + +    String[] value(); +  } + +  /** +   * Any field or class with is not part of the config. +   */ +  @Retention(RetentionPolicy.RUNTIME) +  @Target({ElementType.FIELD, ElementType.TYPE}) +  public @interface Ignore { + +  } + +  private String toYamlString(Object value, String spacing, String fieldName) { +    if (value instanceof List) { +      Collection<?> listValue = (Collection<?>) value; +      if (listValue.isEmpty()) { +        return "[]"; +      } +      StringBuilder m = new StringBuilder(); +      for (Object obj : listValue) { +        m.append(System.lineSeparator()).append(spacing).append("- ").append(this.toYamlString(obj, spacing, fieldName)); +      } + +      return m.toString(); +    } + +    if (value instanceof String) { +      String stringValue = (String) value; +      if (stringValue.isEmpty()) { +        return "\"\""; +      } + +      String quoted = "\"" + stringValue + "\""; +      if (fieldName.equalsIgnoreCase("prefix")) { +        return quoted; +      } else { +        return quoted.replace("\n", "{NL}").replace(this.currentPrefix.equals(this.oldPrefix) ? this.oldPrefix : this.currentPrefix, "{PRFX}"); +      } +    } + +    return value != null ? value.toString() : "null"; +  } + +  /** +   * Set all values in the file (load first to avoid overwriting). +   */ +  @SuppressWarnings("ResultOfMethodCallIgnored") +  @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") +  public void save(File file) { +    try { +      if (!file.exists()) { +        File parent = file.getParentFile(); +        if (parent != null) { +          file.getParentFile().mkdirs(); +        } +        file.createNewFile(); +      } + +      PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8); +      Object instance = this; +      this.save(writer, this.getClass(), instance, 0); +      writer.close(); +    } catch (Throwable e) { +      e.printStackTrace(); +    } +  } + +  private void save(PrintWriter writer, Class<?> clazz, final Object instance, int indent) { +    try { +      String lineSeparator = System.lineSeparator(); +      String spacing = this.repeat(" ", indent); + +      for (Field field : clazz.getFields()) { +        if (field.getAnnotation(Ignore.class) != null) { +          continue; +        } +        Class<?> current = field.getType(); +        if (field.getAnnotation(Ignore.class) != null) { +          continue; +        } + +        Comment comment = field.getAnnotation(Comment.class); +        if (comment != null) { +          for (String commentLine : comment.value()) { +            writer.write(spacing + "# " + commentLine + lineSeparator); +          } +        } + +        Create create = field.getAnnotation(Create.class); +        if (create != null) { +          Object value = field.get(instance); +          this.setAccessible(field); +          if (indent == 0) { +            writer.write(lineSeparator); +          } +          comment = current.getAnnotation(Comment.class); +          if (comment != null) { +            for (String commentLine : comment.value()) { +              writer.write(spacing + "# " + commentLine + lineSeparator); +            } +          } +          writer.write(spacing + this.toNodeName(current.getSimpleName()) + ":" + lineSeparator); +          if (value == null) { +            field.set(instance, value = current.getDeclaredConstructor().newInstance()); +          } +          this.save(writer, current, value, indent + 2); +        } else { +          String value = this.toYamlString(field.get(instance), spacing, field.getName()); +          writer.write(spacing + this.toNodeName(field.getName() + ": ") + value + lineSeparator); +        } +      } +    } catch (Throwable e) { +      e.printStackTrace(); +    } +  } + +  /** +   * Get the field for a specific config node and instance. +   * +   * <p>As expiry can have multiple blocks there will be multiple instances +   * +   * @param split    the node (split by period) +   * @param instance the instance +   */ +  private Field getField(String[] split, Object instance) { +    try { +      Field field = instance.getClass().getField(this.toFieldName(split[split.length - 1])); +      this.setAccessible(field); +      return field; +    } catch (Throwable ignored) { +      LOGGER.debug("Invalid config field: " + this.join(split, ".") + " for " + this.toNodeName(instance.getClass().getSimpleName())); +      return null; +    } +  } + +  /** +   * Get the instance for a specific config node. +   * +   * @param split the node (split by period) +   * @return The instance or null +   */ +  private Object getInstance(String[] split, Class<?> root) { +    try { +      Class<?> clazz = root == null ? MethodHandles.lookup().lookupClass() : root; +      Object instance = this; +      while (split.length > 0) { +        if (split.length == 1) { +          return instance; +        } else { +          Class<?> found = null; +          if (clazz == null) { +            return null; +          } + +          Class<?>[] classes = clazz.getDeclaredClasses(); +          for (Class<?> current : classes) { +            if (Objects.equals(current.getSimpleName(), this.toFieldName(split[0]))) { +              found = current; +              break; +            } +          } + +          if (found == null) { +            return null; +          } + +          try { +            Field instanceField = clazz.getDeclaredField(this.toFieldName(split[0])); +            this.setAccessible(instanceField); +            Object value = instanceField.get(instance); +            if (value == null) { +              value = found.getDeclaredConstructor().newInstance(); +              instanceField.set(instance, value); +            } + +            clazz = found; +            instance = value; +            split = Arrays.copyOfRange(split, 1, split.length); +            continue; +          } catch (NoSuchFieldException e) { +            // +          } + +          split = Arrays.copyOfRange(split, 1, split.length); +          clazz = found; +          instance = clazz.getDeclaredConstructor().newInstance(); +        } +      } +    } catch (Throwable e) { +      e.printStackTrace(); +    } + +    return null; +  } + +  /** +   * Translate a node to a java field name. +   */ +  private String toFieldName(String node) { +    return node.toUpperCase(Locale.ROOT).replaceAll("-", "_"); +  } + +  /** +   * Translate a field to a config node. +   */ +  private String toNodeName(String field) { +    return field.toLowerCase(Locale.ROOT).replace("_", "-"); +  } + +  /** +   * Set some field to be accessible. +   */ +  private void setAccessible(Field field) throws NoSuchFieldException, IllegalAccessException { +    field.setAccessible(true); +    if (Modifier.isFinal(field.getModifiers())) { +      Field modifiersField = Field.class.getDeclaredField("modifiers"); +      modifiersField.setAccessible(true); +      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); +    } +  } + +  @SuppressWarnings("SameParameterValue") +  private String repeat(String s, int n) { +    return IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining()); +  } + +  @SuppressWarnings("SameParameterValue") +  private String join(Object[] array, String delimiter) { +    switch (array.length) { +      case 0: { +        return ""; +      } +      case 1: { +        return array[0].toString(); +      } +      default: { +        final StringBuilder result = new StringBuilder(); +        for (int i = 0, j = array.length; i < j; ++i) { +          if (i > 0) { +            result.append(delimiter); +          } +          result.append(array[i]); +        } + +        return result.toString(); +      } +    } +  } +} diff --git a/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java b/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java new file mode 100644 index 0000000..38a464d --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/handler/AuthSessionHandler.java @@ -0,0 +1,297 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.handler; + +import at.favre.lib.crypto.bcrypt.BCrypt; +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.proxy.Player; +import dev.samstevens.totp.code.CodeVerifier; +import dev.samstevens.totp.code.DefaultCodeGenerator; +import dev.samstevens.totp.code.DefaultCodeVerifier; +import dev.samstevens.totp.time.SystemTimeProvider; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.elytrium.limboapi.api.Limbo; +import net.elytrium.limboapi.api.LimboSessionHandler; +import net.elytrium.limboapi.api.player.LimboPlayer; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.migration.MigrationHash; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class AuthSessionHandler implements LimboSessionHandler { + +  private static final CodeVerifier verifier = new DefaultCodeVerifier(new DefaultCodeGenerator(), new SystemTimeProvider()); + +  private final Dao<RegisteredPlayer, String> playerDao; +  private final Player proxyPlayer; +  private final RegisteredPlayer playerInfo; + +  private LimboPlayer player; +  private String ip; +  private int attempts = Settings.IMP.MAIN.LOGIN_ATTEMPTS; +  private boolean totp = false; + +  public AuthSessionHandler(Dao<RegisteredPlayer, String> playerDao, Player proxyPlayer, String lowercaseNickname) { +    this.playerDao = playerDao; +    this.proxyPlayer = proxyPlayer; +    this.playerInfo = this.fetchInfo(lowercaseNickname); +  } + +  @Override +  public void onSpawn(Limbo server, LimboPlayer player) { +    this.player = player; +    this.player.disableFalling(); +    this.ip = this.proxyPlayer.getRemoteAddress().getAddress().getHostAddress(); + +    if (this.playerInfo == null) { +      this.checkIp(); +    } else { +      this.checkCase(); +    } + +    this.sendMessage(); +  } + +  @Override +  public void onChat(String message) { +    String[] args = message.split(" "); +    if (args.length != 0 && this.checkArgsLength(args.length)) { +      switch (args[0]) { +        case "/reg": +        case "/register": +        case "/r": { +          if (!this.totp && this.playerInfo == null && this.checkPasswordsRepeat(args)) { +            this.register(args[1]); +            this.finishAuth(); +          } else { +            this.sendMessage(); +          } +          break; +        } +        case "/log": +        case "/login": +        case "/l": { +          if (!this.totp && this.playerInfo != null) { +            if (this.checkPassword(args[1])) { +              this.finishOrTotp(); +            } else if (--this.attempts != 0) { +              this.proxyPlayer.sendMessage( +                  LegacyComponentSerializer.legacyAmpersand().deserialize( +                      MessageFormat.format(Settings.IMP.MAIN.STRINGS.LOGIN_WRONG_PASSWORD, this.attempts) +                  ) +              ); +            } else { +              this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.KICK_PASSWORD_WRONG)); +            } +          } else { +            this.sendMessage(); +          } +          break; +        } +        case "/totp": +        case "/2fa": { +          if (this.totp) { +            if (verifier.isValidCode(this.playerInfo.getTotpToken(), args[1])) { +              this.finishAuth(); +            } else { +              this.sendMessage(); +            } +          } else { +            this.sendMessage(); +          } +          break; +        } +        default: { +          this.sendMessage(); +          break; +        } +      } +    } else { +      this.sendMessage(); +    } +  } + +  public static RegisteredPlayer fetchInfo(Dao<RegisteredPlayer, String> playerDao, String nickname) { +    List<RegisteredPlayer> playerList = null; +    try { +      playerList = playerDao.queryForEq("LOWERCASENICKNAME", nickname.toLowerCase(Locale.ROOT)); +    } catch (SQLException e) { +      e.printStackTrace(); +    } + +    return (playerList != null ? playerList.size() : 0) == 0 ? null : playerList.get(0); +  } + +  public static RegisteredPlayer fetchInfo(Dao<RegisteredPlayer, String> playerDao, UUID uuid) { +    List<RegisteredPlayer> playerList = null; +    try { +      playerList = playerDao.queryForEq("PREMIUMUUID", uuid.toString()); +    } catch (SQLException e) { +      e.printStackTrace(); +    } + +    return (playerList != null ? playerList.size() : 0) == 0 ? null : playerList.get(0); +  } + +  private RegisteredPlayer fetchInfo(String nickname) { +    return fetchInfo(this.playerDao, nickname); +  } + +  public static CodeVerifier getVerifier() { +    return verifier; +  } + +  public static boolean checkPassword(String password, RegisteredPlayer player, Dao<RegisteredPlayer, String> playerDao) { +    boolean isCorrect = BCrypt.verifyer().verify( +        password.getBytes(StandardCharsets.UTF_8), player.getHash().getBytes(StandardCharsets.UTF_8) +    ).verified; + +    if (!isCorrect && !Settings.IMP.MAIN.MIGRATION_HASH.isEmpty()) { +      isCorrect = MigrationHash.valueOf(Settings.IMP.MAIN.MIGRATION_HASH).checkPassword(player.getHash(), password); + +      if (isCorrect) { +        player.setHash(genHash(password)); +        try { +          playerDao.update(player); +        } catch (SQLException e) { +          e.printStackTrace(); +        } +      } +    } + +    return isCorrect; +  } + +  private boolean checkPassword(String password) { +    return checkPassword(password, this.playerInfo, this.playerDao); +  } + +  private void checkIp() { +    try { +      List<RegisteredPlayer> alreadyRegistered = this.playerDao.queryForEq("IP", this.ip); + +      if (alreadyRegistered == null) { +        return; +      } + +      AtomicInteger sizeOfValid = new AtomicInteger(alreadyRegistered.size()); + +      if (Settings.IMP.MAIN.IP_LIMIT_VALID_TIME != 0) { +        long checkDate = System.currentTimeMillis() - Settings.IMP.MAIN.IP_LIMIT_VALID_TIME; + +        alreadyRegistered.stream() +            .filter(e -> e.getRegDate() < checkDate) +            .forEach(e -> { +              try { +                e.setIP(""); +                this.playerDao.update(e); +                sizeOfValid.decrementAndGet(); +              } catch (SQLException ex) { +                ex.printStackTrace(); +              } +            }); +      } + +      if (sizeOfValid.get() >= Settings.IMP.MAIN.IP_LIMIT_REGISTRATIONS) { +        this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.IP_LIMIT)); +      } +    } catch (SQLException e) { +      e.printStackTrace(); +    } +  } + +  private void checkCase() { +    if (!this.proxyPlayer.getUsername().equals(this.playerInfo.getNickname())) { +      this.proxyPlayer.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_NICKNAME_CASE)); +    } +  } + +  private void register(String password) { +    RegisteredPlayer registeredPlayer = new RegisteredPlayer( +        this.proxyPlayer.getUsername(), +        this.proxyPlayer.getUsername().toLowerCase(Locale.ROOT), +        genHash(password), +        this.ip, +        "", +        System.currentTimeMillis(), +        this.proxyPlayer.getUniqueId().toString(), +        "" +    ); + +    try { +      this.playerDao.create(registeredPlayer); +    } catch (SQLException e) { +      e.printStackTrace(); +    } +  } + +  private void finishOrTotp() { +    if (this.playerInfo.getTotpToken().isEmpty()) { +      this.finishAuth(); +    } else { +      this.totp = true; +      this.sendMessage(); +    } +  } + +  private void finishAuth() { +    this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.LOGIN_SUCCESS)); +    LimboAuth.getInstance().cacheAuthUser(this.proxyPlayer); +    this.player.disconnect(); +  } + +  private void sendMessage() { +    if (this.totp) { +      this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.TOTP)); +    } else if (this.playerInfo == null) { +      this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.REGISTER)); +    } else { +      this.proxyPlayer.sendMessage( +          LegacyComponentSerializer.legacyAmpersand().deserialize(MessageFormat.format(Settings.IMP.MAIN.STRINGS.LOGIN, this.attempts)) +      ); +    } +  } + +  private boolean checkPasswordsRepeat(String[] args) { +    if (Settings.IMP.MAIN.REGISTER_NEED_REPEAT_PASSWORD && !args[1].equals(args[2])) { +      this.proxyPlayer.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.DIFFERENT_PASSWORDS)); +      return false; +    } + +    return true; +  } + +  private boolean checkArgsLength(int argsLength) { +    if (this.playerInfo == null && Settings.IMP.MAIN.REGISTER_NEED_REPEAT_PASSWORD) { +      return argsLength == 3; +    } else { +      return argsLength == 2; +    } +  } + +  public static String genHash(String password) { +    return BCrypt.withDefaults().hashToString(Settings.IMP.MAIN.BCRYPT_COST, password.toCharArray()); +  } +} diff --git a/src/main/java/net/elytrium/limboauth/listener/AuthListener.java b/src/main/java/net/elytrium/limboauth/listener/AuthListener.java new file mode 100644 index 0000000..2892d79 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/listener/AuthListener.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.listener; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.connection.PreLoginEvent; +import com.velocitypowered.api.util.UuidUtils; +import java.sql.SQLException; +import java.util.UUID; +import net.elytrium.limboapi.api.event.LoginLimboRegisterEvent; +import net.elytrium.limboapi.api.event.SafeGameProfileRequestEvent; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; + +public class AuthListener { + +  private final Dao<RegisteredPlayer, String> playerDao; + +  public AuthListener(Dao<RegisteredPlayer, String> playerDao) { +    this.playerDao = playerDao; +  } + +  @Subscribe +  public void onProxyConnect(PreLoginEvent event) { +    if (!event.getResult().isForceOfflineMode()) { +      if (Settings.IMP.MAIN.ONLINE_MODE_NEED_AUTH || !LimboAuth.getInstance().isPremium(event.getUsername())) { +        event.setResult(PreLoginEvent.PreLoginComponentResult.forceOfflineMode()); +      } else { +        event.setResult(PreLoginEvent.PreLoginComponentResult.forceOnlineMode()); +      } +    } +  } + +  @Subscribe +  public void onLogin(LoginLimboRegisterEvent event) { +    if (LimboAuth.getInstance().needAuth(event.getPlayer())) { +      event.addCallback(() -> LimboAuth.getInstance().authPlayer(event.getPlayer())); +    } +  } + +  @Subscribe +  public void onProfile(SafeGameProfileRequestEvent event) { +    if (Settings.IMP.MAIN.SAVE_UUID) { +      RegisteredPlayer registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, event.getOriginalProfile().getId()); + +      if (registeredPlayer != null) { +        event.setGameProfile(event.getOriginalProfile().withId(UUID.fromString(registeredPlayer.getUuid()))); +        return; +      } + +      registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, event.getUsername()); + +      if (registeredPlayer != null) { +        String currentUuid = registeredPlayer.getUuid(); + +        if (event.isOnlineMode()) { +          try { +            registeredPlayer.setPremiumUuid(event.getOriginalProfile().getId().toString()); +            registeredPlayer.setHash(""); + +            if (currentUuid.isEmpty()) { +              registeredPlayer.setUuid(UuidUtils.generateOfflinePlayerUuid(event.getUsername()).toString()); +            } + +            this.playerDao.update(registeredPlayer); +          } catch (SQLException e) { +            e.printStackTrace(); +          } + +          event.setGameProfile(event.getOriginalProfile().withId(UUID.fromString(currentUuid))); +        } else if (currentUuid.isEmpty()) { +          try { +            registeredPlayer.setUuid(event.getGameProfile().getId().toString()); +            this.playerDao.update(registeredPlayer); +          } catch (SQLException ex) { +            ex.printStackTrace(); +          } +        } +      } +    } else if (event.isOnlineMode()) { +      try { +        UpdateBuilder<RegisteredPlayer, String> updateBuilder = this.playerDao.updateBuilder(); +        updateBuilder.where().eq("nickname", event.getUsername()); +        updateBuilder.updateColumnValue("hash", ""); +        updateBuilder.update(); +      } catch (SQLException e) { +        e.printStackTrace(); +      } +    } + +    if (!Settings.IMP.MAIN.FORCE_OFFLINE_UUID) { +      event.setGameProfile(event.getOriginalProfile().withId(UuidUtils.generateOfflinePlayerUuid(event.getUsername()))); +    } +  } +} diff --git a/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java b/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java new file mode 100644 index 0000000..5296534 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/migration/MigrationHash.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.migration; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public enum MigrationHash { + +  @SuppressWarnings("unused") +  AUTHME((hash, password) -> { +    String[] arr = hash.split("\\$"); // $SHA$salt$hash +    return arr.length == 4 && arr[3].equals(MigrationHash.getSHA256(MigrationHash.getSHA256(password) + arr[2])); +  }); + +  final MigrationHashVerifier verifier; + +  MigrationHash(MigrationHashVerifier verifier) { +    this.verifier = verifier; +  } + +  public boolean checkPassword(String hash, String password) { +    return this.verifier.checkPassword(hash, password); +  } + +  private static String getSHA256(String string) { +    try { +      MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); +      messageDigest.reset(); +      messageDigest.update(string.getBytes(StandardCharsets.UTF_8)); +      byte[] array = messageDigest.digest(); +      return String.format("%0" + (array.length << 1) + "x", new BigInteger(1, array)); +    } catch (NoSuchAlgorithmException e) { +      throw new IllegalArgumentException(e); +    } +  } +} diff --git a/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java b/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java new file mode 100644 index 0000000..cbe5135 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/migration/MigrationHashVerifier.java @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.migration; + +public interface MigrationHashVerifier { + +  boolean checkPassword(String hash, String password); +} diff --git a/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java b/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java new file mode 100644 index 0000000..55a2e3c --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/model/RegisteredPlayer.java @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.model; + +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; + +@SuppressWarnings("unused") +@DatabaseTable(tableName = "AUTH") +public class RegisteredPlayer { + +  @DatabaseField(canBeNull = false, columnName = "NICKNAME") +  private String nickname; + +  @DatabaseField(id = true, columnName = "LOWERCASENICKNAME") +  private String lowercaseNickname; + +  @DatabaseField(canBeNull = false, columnName = "HASH") +  private String hash; + +  @DatabaseField(columnName = "IP") +  private String ip; + +  @DatabaseField(columnName = "TOTPTOKEN") +  private String totpToken; + +  @DatabaseField(columnName = "REGDATE") +  private Long regDate; + +  @DatabaseField(columnName = "UUID") +  private String uuid; + +  @DatabaseField(columnName = "PREMIUMUUID") +  private String premiumUuid; + +  public RegisteredPlayer(String nickname, String lowercaseNickname, +      String hash, String ip, String totpToken, Long regDate, String uuid, String premiumUuid) { +    this.nickname = nickname; +    this.lowercaseNickname = lowercaseNickname; +    this.hash = hash; +    this.ip = ip; +    this.totpToken = totpToken; +    this.regDate = regDate; +    this.uuid = uuid; +    this.premiumUuid = premiumUuid; +  } + +  public RegisteredPlayer() { + +  } + +  public void setNickname(String nickname) { +    this.nickname = nickname; +  } + +  public String getNickname() { +    return this.nickname; +  } + +  public void setLowercaseNickname(String lowercaseNickname) { +    this.lowercaseNickname = lowercaseNickname; +  } + +  public String getLowercaseNickname() { +    return this.lowercaseNickname; +  } + +  public void setHash(String hash) { +    this.hash = hash; +  } + +  public String getHash() { +    return this.hash; +  } + +  public void setIP(String ip) { +    this.ip = ip; +  } + +  public String getIP() { +    return this.ip; +  } + +  public void setTotpToken(String totpToken) { +    this.totpToken = totpToken; +  } + +  public String getTotpToken() { +    return this.totpToken; +  } + +  public void setRegDate(Long regDate) { +    this.regDate = regDate; +  } + +  public Long getRegDate() { +    return this.regDate; +  } + +  public void setUuid(String uuid) { +    this.uuid = uuid; +  } + +  public String getUuid() { +    return this.uuid; +  } + +  public void setPremiumUuid(String premiumUuid) { +    this.premiumUuid = premiumUuid; +  } + +  public String getPremiumUuid() { +    return this.premiumUuid; +  } +} diff --git a/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java b/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java new file mode 100644 index 0000000..71af1bb --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/utils/UpdatesChecker.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; +import net.elytrium.limboauth.Settings; +import org.slf4j.Logger; + +public class UpdatesChecker { + +  public static void checkForUpdates(Logger logger) { +    try { +      URLConnection conn = new URL("https://raw.githubusercontent.com/Elytrium/LimboAuth/master/VERSION").openConnection(); +      int timeout = (int) TimeUnit.SECONDS.toMillis(5); +      conn.setConnectTimeout(timeout); +      conn.setReadTimeout(timeout); +      try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { +        String latestVersion = in.readLine(); +        if (latestVersion == null) { +          logger.warn("Unable to check for updates."); +          return; +        } +        String latestVersion0 = getCleanVersion(latestVersion.trim()); +        String currentVersion0 = getCleanVersion(Settings.IMP.VERSION); +        int latestVersionId = Integer.parseInt(latestVersion0.replace(".", "").replace("$", "")); +        int currentVersionId = Integer.parseInt(currentVersion0.replace(".", "").replace("$", "")); +        if (latestVersion0.endsWith("$")) { +          --latestVersionId; +        } +        if (currentVersion0.endsWith("$")) { +          --currentVersionId; +        } + +        if (currentVersionId < latestVersionId) { +          logger.error("****************************************"); +          logger.warn("The new LimboAuth update was found, please update."); +          logger.error("https://github.com/Elytrium/LimboAuth/releases/"); +          logger.error("****************************************"); +        } +      } +    } catch (IOException e) { +      logger.warn("Unable to check for updates.", e); +    } +  } + +  private static String getCleanVersion(String version) { +    int indexOf = version.indexOf("-"); +    if (indexOf > 0) { +      return version.substring(0, indexOf) + "$"; // "$" - Indicates that the version is snapshot +    } else { +      return version; +    } +  } +} diff --git a/src/main/templates/net/elytrium/limboauth/BuildConstants.java b/src/main/templates/net/elytrium/limboauth/BuildConstants.java new file mode 100644 index 0000000..b8d7966 --- /dev/null +++ b/src/main/templates/net/elytrium/limboauth/BuildConstants.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +// The constants are replaced before compilation +public class BuildConstants { + +  public static final String AUTH_VERSION = "${version}"; +} | 
