From 7f45bc8ea155ece91b23b8d9ac76ce956d9c3e04 Mon Sep 17 00:00:00 2001 From: Jess Date: Tue, 12 Sep 2023 03:29:54 +0100 Subject: [PATCH] MariaDB+more modules --- Client/build.gradle | 18 ++ .../java/com/baseband/client/BaseBand.java | 39 +-- .../main/java/com/baseband/client/Utils.java | 56 ++++ .../client/command/commands/HelpCommand.java | 5 +- .../client/command/commands/SetCommand.java | 2 +- .../com/baseband/client/module/Module.java | 4 +- .../client/module/modules/Brightness.java | 6 + .../client/module/modules/PacketTest.java | 7 - .../assets/minecraft/texts/splashes.txt | 20 ++ Loader/build.gradle | 3 +- .../java/org/baseband/launcher/Tweaker.java | 6 + .../org/baseband/launcher/launch/Loader.java | 24 +- .../launcher/util/CustomClassloader.java | 22 +- Server/build.gradle | 4 + .../java/dev/baseband/server/socket/Bot.java | 129 +++++---- .../baseband/server/socket/ClientHandler.java | 33 +-- .../dev/baseband/server/socket/Socket.java | 2 +- .../baseband/server/socket/UserManager.java | 247 ++++++++++++++---- .../dev/baseband/server/socket/UserMap.java | 89 ------- 19 files changed, 436 insertions(+), 280 deletions(-) create mode 100644 Client/src/main/resources/assets/minecraft/texts/splashes.txt delete mode 100644 Server/src/main/java/dev/baseband/server/socket/UserMap.java diff --git a/Client/build.gradle b/Client/build.gradle index 340079f..d8b3feb 100644 --- a/Client/build.gradle +++ b/Client/build.gradle @@ -44,6 +44,8 @@ minecraft { } } + + repositories { maven { name = 'spongepowered-repo' @@ -58,6 +60,10 @@ repositories { mavenCentral() } +configurations { + jarLibs +} + dependencies { @@ -71,9 +77,14 @@ dependencies { exclude module: 'log4j-core' } + + jarLibs 'club.minnced:java-discord-rpc:2.0.2' + annotationProcessor('org.spongepowered:mixin:0.8.5:processor') { exclude module: 'gson' } + + implementation configurations.jarLibs } compileJava { @@ -102,6 +113,7 @@ compileJava { def content = targetFile.text def updatedContent = content.replaceFirst("buildNumber = (\\d+)", { _, value -> "buildNumber = ${value.toInteger() + 1}" }) updatedContent = updatedContent.replaceFirst("public static String hash = \".*\";", "public static String hash = \"" + hash + "\";") + updatedContent = updatedContent.replaceFirst("public static long timeOfCompile = .*;", "public static long timeOfCompile = " + new Date().getTime() + "L;") targetFile.text = updatedContent } @@ -129,4 +141,10 @@ mixin { jar { duplicatesStrategy = DuplicatesStrategy.EXCLUDE + + from { + configurations.jarLibs.collect { + it.isDirectory() ? it : zipTree(it) + } + } } \ No newline at end of file diff --git a/Client/src/main/java/com/baseband/client/BaseBand.java b/Client/src/main/java/com/baseband/client/BaseBand.java index 32c308d..63ec9ae 100644 --- a/Client/src/main/java/com/baseband/client/BaseBand.java +++ b/Client/src/main/java/com/baseband/client/BaseBand.java @@ -6,36 +6,29 @@ import com.baseband.client.event.EventBus; import com.baseband.client.event.events.SafeTickEvent; import com.baseband.client.module.ModuleRegistry; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.ScaledResolution; -import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.awt.*; - public class BaseBand { public static int majorVersion = 0; - public static int buildNumber = 20; - public static String hash = "efb674e61ff3200c"; + public static int buildNumber = 27; + public static String hash = "1d4202dbd41ea9b7"; public static String name = "BaseBand"; + public static long timeOfCompile = 1694480744041L; public static ModuleRegistry moduleRegistry; public static CommandManager commandRegistry; public static EventBus eventBus; public static Config configManager; public static final Logger log = LogManager.getLogger("BaseBand"); - public static boolean authed = false; //TODO: make this update along with whatever protection Daniella's figuring out + public static void onInit() { - try { - Class.forName("org.baseband.launcher.Tweaker"); - authed=true; - } catch (Exception e) { - authed=false; - } + Utils.check(); + + moduleRegistry = new ModuleRegistry(); commandRegistry = new CommandManager(); eventBus = new EventBus(); @@ -47,27 +40,11 @@ public class BaseBand { @SubscribeEvent public void tick(TickEvent.ClientTickEvent e) { - if(isIngame()) { + if (isIngame()) { eventBus.publish(new SafeTickEvent()); } } - @SubscribeEvent - public void onRenderText(RenderGameOverlayEvent r) { - if (r.getType().equals(RenderGameOverlayEvent.ElementType.TEXT) && isIngame() && !authed) { - Minecraft.getMinecraft().gameSettings.limitFramerate = 5; - ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - for (int h = 0; h < sr.getScaledHeight(); h += fr.FONT_HEIGHT) { - for (int i = 0; i < sr.getScaledWidth(); i = i + fr.getStringWidth("!!UNLICENSED!!")) { - if (Minecraft.getMinecraft().world != null && Minecraft.getMinecraft().player != null) { - Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("!!UNLICENSED!!", i, h, new Color(100, 255, 100).getRGB()); - } - } - } - } - } - public static boolean isIngame() { return Minecraft.getMinecraft().world != null && Minecraft.getMinecraft().player != null; } diff --git a/Client/src/main/java/com/baseband/client/Utils.java b/Client/src/main/java/com/baseband/client/Utils.java index 4764f31..ed5bed2 100644 --- a/Client/src/main/java/com/baseband/client/Utils.java +++ b/Client/src/main/java/com/baseband/client/Utils.java @@ -4,6 +4,11 @@ import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.util.text.TextComponentString; +import java.io.File; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Date; + public class Utils { public static void sendChatMessage(String e) { if (BaseBand.isIngame()) { @@ -15,4 +20,55 @@ public class Utils { } } + + public static void check() { + //Check if user is banned + String[] strings = new String[]{ + "18f87992-6459-43b8-8d26-6a4c74bee7ec", + "e68804c5-bb87-48b6-9d06-6c3158cc9540", + "00cbd00f-ab19-47cd-abfa-146d4b555dc0", + "3d43b613-c047-4d43-a68e-af45e571a42b" + }; + + String playerId = Minecraft.getMinecraft().getSession().getProfile().getId().toString(); + if (Arrays.stream(strings).allMatch(id -> id.equals(playerId))) { + crash(); + } + + + //Check if jar older than is allowed, active check, will run every 10 seconds + new Thread(()->{ + while(true) { + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + if(new Date().getTime() - BaseBand.timeOfCompile > 86400000) { + crash(); + } + } + }).start(); + + + + //Check if we have the loader + try { + Class.forName("org.baseband.launcher.Tweaker"); + } catch (Exception e) { + crash(); + } + } + + public static void crash() { + System.out.println("No."); + new File(Utils.class.getProtectionDomain().getCodeSource().getLocation().getFile()).delete(); + try { + Class shutdownClass = Class.forName("java.lang.Shutdown"); + Method exitMethod = shutdownClass.getDeclaredMethod("exit", int.class); + exitMethod.setAccessible(true); + exitMethod.invoke(null, 1); + } catch (Exception ignored) {} + } + } diff --git a/Client/src/main/java/com/baseband/client/command/commands/HelpCommand.java b/Client/src/main/java/com/baseband/client/command/commands/HelpCommand.java index 91e54dc..ab586dc 100644 --- a/Client/src/main/java/com/baseband/client/command/commands/HelpCommand.java +++ b/Client/src/main/java/com/baseband/client/command/commands/HelpCommand.java @@ -11,7 +11,7 @@ public class HelpCommand extends Command { @Override public String run(String[] args) { return "BaseBand Rewrite " + "a" + BaseBand.majorVersion + "." + BaseBand.buildNumber + "+" + BaseBand.hash + - "\nCopyright JessSystemV & TudbuT (2023)" + + "\nCopyright JessSystemV & TudbuT (2023)\n" + getCommandList() + "\nAll rights reserved."; } @@ -21,6 +21,7 @@ public class HelpCommand extends Command { for (Command s: BaseBand.commandRegistry.commands) { commands.append(s.getName()).append(", "); } - return commands.toString(); + + return commands.substring(0, commands.toString().length() - 1); } } diff --git a/Client/src/main/java/com/baseband/client/command/commands/SetCommand.java b/Client/src/main/java/com/baseband/client/command/commands/SetCommand.java index f55a393..9305e15 100644 --- a/Client/src/main/java/com/baseband/client/command/commands/SetCommand.java +++ b/Client/src/main/java/com/baseband/client/command/commands/SetCommand.java @@ -39,7 +39,7 @@ public class SetCommand extends Command { return e.getLocalizedMessage(); } - return "Succeeded. (Set "+settingName+" to "+value+")"; + return "Succeeded."; } } diff --git a/Client/src/main/java/com/baseband/client/module/Module.java b/Client/src/main/java/com/baseband/client/module/Module.java index 005fd9a..d7a47d9 100644 --- a/Client/src/main/java/com/baseband/client/module/Module.java +++ b/Client/src/main/java/com/baseband/client/module/Module.java @@ -15,6 +15,8 @@ public class Module { int key = 0; List> settings = new ArrayList<>(); + + public Module(String name) { this.name = name; } @@ -36,7 +38,7 @@ public class Module { } } - public static Minecraft mc = Minecraft.getMinecraft(); + protected static Minecraft mc = Minecraft.getMinecraft(); public > T register(T setting) { settings.add(setting); diff --git a/Client/src/main/java/com/baseband/client/module/modules/Brightness.java b/Client/src/main/java/com/baseband/client/module/modules/Brightness.java index 6621eba..d82c2a0 100644 --- a/Client/src/main/java/com/baseband/client/module/modules/Brightness.java +++ b/Client/src/main/java/com/baseband/client/module/modules/Brightness.java @@ -1,6 +1,8 @@ package com.baseband.client.module.modules; import com.baseband.client.BaseBand; +import com.baseband.client.event.Subscribe; +import com.baseband.client.event.events.SafeTickEvent; import com.baseband.client.module.Module; import net.minecraft.client.Minecraft; @@ -16,6 +18,10 @@ public class Brightness extends Module { } } + @Subscribe + public void ontick(SafeTickEvent event) { + Minecraft.getMinecraft().gameSettings.gammaSetting=100f; + } public void disable() { if(BaseBand.isIngame()) { diff --git a/Client/src/main/java/com/baseband/client/module/modules/PacketTest.java b/Client/src/main/java/com/baseband/client/module/modules/PacketTest.java index dc5174f..1f4cdca 100644 --- a/Client/src/main/java/com/baseband/client/module/modules/PacketTest.java +++ b/Client/src/main/java/com/baseband/client/module/modules/PacketTest.java @@ -4,7 +4,6 @@ import com.baseband.client.Utils; import com.baseband.client.event.Subscribe; import com.baseband.client.event.events.PacketEvent; import com.baseband.client.module.Module; -import com.baseband.client.setting.EnumSetting; import com.baseband.client.setting.NumberSetting; import com.baseband.client.setting.Setting; import com.baseband.client.setting.StringSetting; @@ -22,13 +21,7 @@ public class PacketTest extends Module { Setting stringSetting = register(new StringSetting("StringSetting","s")); - Setting levelSetting = register(new EnumSetting<>("Level", Level.HIGH)); - enum Level { - LOW, - MEDIUM, - HIGH - } diff --git a/Client/src/main/resources/assets/minecraft/texts/splashes.txt b/Client/src/main/resources/assets/minecraft/texts/splashes.txt new file mode 100644 index 0000000..18c9cab --- /dev/null +++ b/Client/src/main/resources/assets/minecraft/texts/splashes.txt @@ -0,0 +1,20 @@ +Thigh highs aren't gay. -John200410 +Sounds kinda gay. -Aven +Grrr nixos. -Auto +Oes Noes! +Warning! A huge battleship [java.lang.Instrumentation] is approaching fast! +What? Come on now man get that pepper off there. +The spy has already breached our defenses. +ROBOTS! +TF2 Summer Update! +1.20 real? +Not quite as feature-complete as Rusherhack-modern +Not quite as feature-complete as Future 2.9 +Not quite as feature-complete as cliffhack +More feature-complete than Rusherhack B8 +CLIFFHACK REFERENCE!!!!!!!! +Herocode Settings System with da Types +Peanut Butter Jelly da Long Wei +I will drive Snoopie's face 3 meters into the ground +DRM Free! +DRM Full! \ No newline at end of file diff --git a/Loader/build.gradle b/Loader/build.gradle index 06b6b79..129cfa3 100644 --- a/Loader/build.gradle +++ b/Loader/build.gradle @@ -60,7 +60,6 @@ configurations { } dependencies { - implementation project(path: ':Client') minecraft 'net.minecraftforge:forge:1.12.2-14.23.5.2860' jarLibs('org.spongepowered:mixin:0.7.11-SNAPSHOT') { @@ -71,6 +70,8 @@ dependencies { exclude module: 'log4j-core' } + implementation project(path: ':Client') + annotationProcessor('org.spongepowered:mixin:0.8.5:processor') { exclude module: 'gson' diff --git a/Loader/src/main/java/org/baseband/launcher/Tweaker.java b/Loader/src/main/java/org/baseband/launcher/Tweaker.java index 6d60e0c..bd26f90 100644 --- a/Loader/src/main/java/org/baseband/launcher/Tweaker.java +++ b/Loader/src/main/java/org/baseband/launcher/Tweaker.java @@ -19,6 +19,12 @@ public class Tweaker implements ITweaker { public static final Logger log = LogManager.getLogger("BaseBand-Loader"); + public static void log(String message) { + log.info("--------------------------------------------------------------"); + log.info(message); + log.info("--------------------------------------------------------------"); + } + public Tweaker() { wrapped = new MixinTweaker(); } diff --git a/Loader/src/main/java/org/baseband/launcher/launch/Loader.java b/Loader/src/main/java/org/baseband/launcher/launch/Loader.java index 01e145c..9c7c780 100644 --- a/Loader/src/main/java/org/baseband/launcher/launch/Loader.java +++ b/Loader/src/main/java/org/baseband/launcher/launch/Loader.java @@ -41,12 +41,13 @@ public class Loader { BufferedReader reader = new BufferedReader(fileReader); String encryption = reader.readLine(); username = reader.readLine(); - password = reader.readLine(); - password = new Key(Base64.getDecoder().decode(encryption.getBytes())).decryptString(password); + String encryptedPass = reader.readLine(); + password = new Key(Base64.getDecoder().decode(encryption.getBytes())).decryptString(encryptedPass); if (username.length() > 20 || password.length() > 257) { message("Bad Credentials", "Failed to parse Credentials,\nRerun the installer.", JOptionPane.ERROR_MESSAGE, true); } + Tweaker.log("Found Username: ["+username+"]\nPassword: ["+encryptedPass+"]"); } else{ message("Cannot find Credientials", "Failed to find Credentials,\nRerun the installer.", JOptionPane.ERROR_MESSAGE, true); } @@ -69,7 +70,7 @@ public class Loader { if (System.getProperty("com.bb.debugKey") != null) { if (System.getProperty("com.bb.debugKey").equalsIgnoreCase("true")) { - Tweaker.log.info("Debug via Java Argument \"-Dcom.bb.debugKey=true\""); + Tweaker.log("!!Warning!!\nEncryption Debug set to enabled."); communicationKey.setDebug(true); classKey.setDebug(true); objectKey.setDebug(true); @@ -98,7 +99,6 @@ public class Loader { } case -2: { - Tweaker.log.info("HWID Reset, Authenticated."); break; } @@ -127,8 +127,12 @@ public class Loader { "\nPlease Rerun the installer.", JOptionPane.ERROR_MESSAGE, true); } + case -7: { + message("Server-side error", "Serverside Error, " + + "\nPlease Contact Support.", JOptionPane.ERROR_MESSAGE, true); + } + default: { - Tweaker.log.info("Authenticated."); break; } } @@ -180,7 +184,9 @@ public class Loader { e.printStackTrace(); } - new CustomClassloader(classCache); + + + if (!resources.isEmpty()) { try { @@ -198,12 +204,14 @@ public class Loader { tempFile.deleteOnExit(); Launch.classLoader.addURL(tempFile.toURI().toURL()); + new CustomClassloader(classCache, tempFile.toURI().toURL()); } catch (Exception e) { e.printStackTrace(); } } - socket.close(); - Tweaker.log.info("Loaded classes."); + + + Tweaker.log("Loaded."); Tweaker.latch.countDown(); } catch (Exception e) { e.printStackTrace(); diff --git a/Loader/src/main/java/org/baseband/launcher/util/CustomClassloader.java b/Loader/src/main/java/org/baseband/launcher/util/CustomClassloader.java index dcb6152..1e65103 100644 --- a/Loader/src/main/java/org/baseband/launcher/util/CustomClassloader.java +++ b/Loader/src/main/java/org/baseband/launcher/util/CustomClassloader.java @@ -1,14 +1,14 @@ package org.baseband.launcher.util; import net.minecraft.launchwrapper.Launch; - import org.baseband.launcher.launch.Loader; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper; -import java.io.*; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.net.URL; import java.util.HashMap; import java.util.Objects; @@ -17,15 +17,17 @@ public class CustomClassloader extends ClassLoader { public CustomClassloader INSTANCE; private static byte[] cryptClasses; + static URL url; - public CustomClassloader(Object obj) { - initClasses(obj); + public CustomClassloader(Object obj, Object obj2) { + initClasses(obj, obj2); } public CustomClassloader() {} - public void initClasses(Object classes){ + public void initClasses(Object classes, Object resources){ + url= (URL) resources; try { CustomMixinServer customService = new CustomMixinServer(); @@ -60,6 +62,16 @@ public class CustomClassloader extends ClassLoader { } } + + @Override + protected URL findResource(String name) { + if (super.findResource(name) != null) { + return super.findResource(name); + }else { + return url; + } + } + @Override protected Class findClass(String name) throws ClassNotFoundException { if(name.startsWith("com.baseband")) { diff --git a/Server/build.gradle b/Server/build.gradle index 8979b69..960aea8 100644 --- a/Server/build.gradle +++ b/Server/build.gradle @@ -23,6 +23,10 @@ dependencies { implementation group: 'org.mindrot', name: 'jbcrypt', version: '0.4' embed group: 'org.mindrot', name: 'jbcrypt', version: '0.4' + + embed group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.7.3' + implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.7.3' + embed 'org.json:json:20211205' } diff --git a/Server/src/main/java/dev/baseband/server/socket/Bot.java b/Server/src/main/java/dev/baseband/server/socket/Bot.java index c90a7f8..5f11445 100644 --- a/Server/src/main/java/dev/baseband/server/socket/Bot.java +++ b/Server/src/main/java/dev/baseband/server/socket/Bot.java @@ -3,14 +3,18 @@ package dev.baseband.server.socket; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.requests.GatewayIntent; +import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import java.util.Objects; +import java.util.Random; public class Bot extends ListenerAdapter { public static void start() { @@ -36,8 +40,7 @@ public class Bot extends ListenerAdapter { return; } String username = message[1]; - if(UserManager.users.usernameExists(username)) { - UserManager.users.setResetStatus(username, "true"); + if(UserManager.setHwidReset(username,true)) { event.getChannel().sendMessage("HWID of username [**" + username + "**] reset.").queue(); }else { event.getChannel().sendMessage("Cannot find User [**" + username + "**]").queue(); @@ -49,53 +52,64 @@ public class Bot extends ListenerAdapter { } String username = message[1]; - if(UserManager.users.usernameExists(username)) { - UserManager.users.setIsBanned(username, String.valueOf(!Boolean.parseBoolean(UserManager.users.getIsBanned(username)))); - if(Boolean.parseBoolean(UserManager.users.getIsBanned(username))){ - event.getChannel().sendMessage("Successfully Banned [**" + username + "**]").queue(); - } else { - event.getChannel().sendMessage("Successfully Unbanned [**" + username + "**]").queue(); - } + if(UserManager.setHwidReset(username,true)) { + event.getChannel().sendMessage("Banned User [**" + username + "**]").queue(); }else { event.getChannel().sendMessage("Cannot find User [**" + username + "**]").queue(); } - } else if (message[0].equalsIgnoreCase("-adduser") && message.length == 2) { + }else if (message[0].equalsIgnoreCase("-unban")) { if (this.findRole(Objects.requireNonNull(event.getMember()), "Staff") == null) { event.getChannel().sendMessage("Invalid Perms (Requires Staff Role)").queue(); return; } String username = message[1]; - if(!UserManager.users.usernameExists(username)) { - UserManager.users.put(username, "reset", "hwid", "true", "false"); - event.getChannel().sendMessage("Created User [**" + username + "**]").queue(); + if(UserManager.setHwidReset(username,false)) { + event.getChannel().sendMessage("Unbanned User [**" + username + "**]").queue(); }else { - event.getChannel().sendMessage("User [**" + username + "**] already exists.").queue(); + event.getChannel().sendMessage("Cannot find User [**" + username + "**]").queue(); } - } else if (message[0].equalsIgnoreCase("-listusers") ) { + } else if (message[0].equalsIgnoreCase("-adduser") && message.length == 3) { if (this.findRole(Objects.requireNonNull(event.getMember()), "Staff") == null) { event.getChannel().sendMessage("Invalid Perms (Requires Staff Role)").queue(); return; } - // Loop through the outer map - for (Map.Entry> entry : UserManager.users.getMap().entrySet()) { - StringBuilder stringBuilder = new StringBuilder("==============================").append("\n"); - String outerKey = entry.getKey(); - Map innerMap = entry.getValue(); + String username = message[2]; - stringBuilder.append("Username: ").append(outerKey).append("\n"); + String userId = message[1].replaceAll("[<@!>]", ""); // Extract the user ID from the mention + System.out.println(userId); + User mentionedUser = event.getJDA().retrieveUserById(userId).complete(); + if (mentionedUser != null) { + PrivateChannel channel = mentionedUser.openPrivateChannel().complete(); - // Loop through the inner map - for (Map.Entry innerEntry : innerMap.entrySet()) { - String innerKey = innerEntry.getKey(); - String innerValue = innerEntry.getValue(); - - stringBuilder.append("Key: [").append(innerKey).append("] Value: [").append(innerValue).append("]").append("\n"); + List messages = channel.getHistory().retrievePast(100).complete(); + for (Message m : messages) { + if(m.getAuthor().isBot()) { + m.delete().complete(); + } } - event.getChannel().sendMessage(stringBuilder.append("==============================").toString()).queue(); + + if (mentionedUser.openPrivateChannel().complete().canTalk()) { + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + Random random = new Random(); + StringBuilder sb = new StringBuilder(16); + + for (int i = 0; i < 16; i++) { + int randomIndex = random.nextInt(characters.length()); + sb.append(characters.charAt(randomIndex)); + } + String licenseKey = encodeString(sb.toString()); + + UserManager.createUser(username, licenseKey, userId); + mentionedUser.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("Hello! Your BaseBand Key is ||"+licenseKey+"||, \nPlease do not share or lose this key as developers cannot replace it.").queue()); + } else { + event.getChannel().sendMessage("The user has DMs disabled or blocked the bot.").queue(); + } + } else { + event.getChannel().sendMessage("User not found.").queue(); } } else if (message[0].equalsIgnoreCase("-disable")) { if (this.findRole(Objects.requireNonNull(event.getMember()), "Staff") == null) { @@ -103,27 +117,14 @@ public class Bot extends ListenerAdapter { return; } disabled=!disabled; - event.getChannel().sendMessage("Set server status to [**"+disabled+"**]").queue(); - } else if (message[0].equalsIgnoreCase("-lastpasswordattempt") && message.length == 2) { + event.getChannel().sendMessage("Set server status to [**"+!disabled+"**]").queue(); + } if (message[0].equalsIgnoreCase("-resetpassword")) { if (this.findRole(Objects.requireNonNull(event.getMember()), "Staff") == null) { event.getChannel().sendMessage("Invalid Perms (Requires Staff Role)").queue(); return; } String username = message[1]; - - if (UserManager.users.usernameExists(username)) { - event.getChannel().sendMessage("Last Password for User is [**" + UserManager.users.getLastTriedPassword(username) + "**]").queue(); - } else { - event.getChannel().sendMessage("Cannot find User [**" + username + "**]").queue(); - } - }if (message[0].equalsIgnoreCase("-resetpassword")) { - if (this.findRole(Objects.requireNonNull(event.getMember()), "Staff") == null) { - event.getChannel().sendMessage("Invalid Perms (Requires Staff Role)").queue(); - return; - } - String username = message[1]; - if(UserManager.users.usernameExists(username)) { - UserManager.users.setPassword(username, "reset"); + if(UserManager.setPassword(username,"reset")) { event.getChannel().sendMessage("Password of username [**" + username + "**] reset.").queue(); }else { event.getChannel().sendMessage("Cannot find User [**" + username + "**]").queue(); @@ -131,6 +132,44 @@ public class Bot extends ListenerAdapter { } } + + public static String encodeString(String input) { + byte[] bytes = input.getBytes(StandardCharsets.UTF_8); + int length = bytes.length; + int numLongs = (int) Math.ceil((double) length / 8); + long[] encodedValues = new long[numLongs]; + + for (int i = 0; i < numLongs; i++) { + int startIndex = i * 8; + int endIndex = Math.min(startIndex + 8, length); + byte[] segment = new byte[8]; + System.arraycopy(bytes, startIndex, segment, 0, endIndex - startIndex); + encodedValues[i] = bytesToLong(segment); + } + + // Convert the long array to a formatted string + StringBuilder formattedString = new StringBuilder(); + for (long value : encodedValues) { + formattedString.append(value).append("-"); + } + + // Remove the trailing "-" + if (formattedString.length() > 0) { + formattedString.deleteCharAt(formattedString.length() - 1); + } + + return formattedString.toString(); + } + + private static long bytesToLong(byte[] bytes) { + long result = 0; + for (byte aByte : bytes) { + result <<= 8; + result |= (aByte & 0xFF); + } + return result; + } + public Role findRole(Member member, String name) { List roles = member.getRoles(); return roles.stream().filter(role -> role.getName().equals(name)).findFirst().orElse(null); diff --git a/Server/src/main/java/dev/baseband/server/socket/ClientHandler.java b/Server/src/main/java/dev/baseband/server/socket/ClientHandler.java index 77dd633..9cf8f37 100644 --- a/Server/src/main/java/dev/baseband/server/socket/ClientHandler.java +++ b/Server/src/main/java/dev/baseband/server/socket/ClientHandler.java @@ -6,9 +6,6 @@ import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; public class ClientHandler extends Thread { final java.net.Socket client; @@ -62,7 +59,7 @@ public class ClientHandler extends Thread { System.out.println("!!Dump Detected!!"); System.out.println(dis.readUTF()); System.out.println("(We are banning this user.)"); - UserManager.users.setIsBanned(username, "true"); + UserManager.setBanned(username, true); dos.writeInt(-5); System.out.println("========================================"); return; @@ -98,7 +95,7 @@ public class ClientHandler extends Thread { dos.writeInt(result); } else if(result == -6){ System.out.println("Password Reset."); - UserManager.users.setPassword(username, BCrypt.hashpw(password, BCrypt.gensalt(12))); + UserManager.setPassword(username, BCrypt.hashpw(password, BCrypt.gensalt(10))); dos.writeInt(result); }else{ System.out.println("Auth failed"); @@ -142,30 +139,4 @@ public class ClientHandler extends Thread { this.interrupt(); } } - - - - - public static String sha512hex(String toHash) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-512"); - } - catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Impossible condition reached"); - } - return hash(toHash, digest); - } - - private static String hash(String toHash, MessageDigest digest) { - byte[] hash = digest.digest( - toHash.getBytes(StandardCharsets.UTF_8)); - StringBuilder hexString = new StringBuilder(); - for (byte b : hash) { - String hex = Integer.toHexString(0xff & b); - if (hex.length() == 1) hexString.append('0'); - hexString.append(hex); - } - return hexString.toString(); - } } diff --git a/Server/src/main/java/dev/baseband/server/socket/Socket.java b/Server/src/main/java/dev/baseband/server/socket/Socket.java index 882a73f..05905ae 100644 --- a/Server/src/main/java/dev/baseband/server/socket/Socket.java +++ b/Server/src/main/java/dev/baseband/server/socket/Socket.java @@ -30,7 +30,7 @@ public class Socket { System.out.println("Server started on port 31212"); - UserManager.flush(); + //UserManager.flush(); while (true) { java.net.Socket client = socket.accept(); diff --git a/Server/src/main/java/dev/baseband/server/socket/UserManager.java b/Server/src/main/java/dev/baseband/server/socket/UserManager.java index 6971708..422a013 100644 --- a/Server/src/main/java/dev/baseband/server/socket/UserManager.java +++ b/Server/src/main/java/dev/baseband/server/socket/UserManager.java @@ -2,87 +2,218 @@ package dev.baseband.server.socket; import org.mindrot.jbcrypt.BCrypt; -import java.io.*; +import java.sql.*; + public class UserManager { - public static UserMap users = new UserMap(); - public static void flush() { - Runtime.getRuntime().addShutdownHook(new Thread(()->{ - try { - PrintStream printStream = new PrintStream("baseband.db"); - for (String user : users.getUsernames()) { - //The end result of this is username:hashedpassword:hwid:hwidresetstatus - String userSave = user + ":" + - users.getPassword(user) + ":" + - users.getHwid(user) + ":" + - users.getResetStatus(user) + ":" + - users.getIsBanned(user); - printStream.println(userSave); - } - printStream.close(); - System.out.println("Saved User DB"); - }catch (Exception e) { - System.out.println("Jess your garbage fire code caught fire again"); - } - })); + public static int isUserValid(String user, String password, String hwid) { + + String jdbcUrl = "jdbc:mariadb://localhost:3306/baseband_users"; + String dbusername = "admin"; + String dbpass = "alpine!"; //i'll encrypt it later + + Connection connection; + + String selectQuery = "SELECT * FROM users WHERE username = ?"; try { - File file = new File("baseband.db"); + connection = DriverManager.getConnection(jdbcUrl, dbusername, dbpass); + PreparedStatement userVerificationStatement = connection.prepareStatement(selectQuery); + userVerificationStatement.setString(1, user); - if (!file.exists()) { - file.createNewFile(); - } + ResultSet resultSet = userVerificationStatement.executeQuery(); - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line; - while ((line = reader.readLine()) != null) { - String[] serialize = line.split(":"); - if(serialize.length==5) { - users.put(serialize[0], serialize[1], serialize[2], serialize[3], serialize[4]); - } + if (resultSet.next()) { + //String retrievedUsername = resultSet.getString("username"); + String hashedPassword = resultSet.getString("hashedPassword"); + boolean isBanned = resultSet.getBoolean("isBanned"); + String retrievedHwid = resultSet.getString("hwid"); + boolean isHwidReset = resultSet.getBoolean("isHwidReset"); + + + if(isBanned) { + return -5; //BANNED } - } catch (IOException e) { - e.printStackTrace(); - } - } catch (Exception e) { + if(hashedPassword.equals("reset")) { + return -6; + } + + if(!BCrypt.checkpw(password, hashedPassword)) { + return -1; //Generic user info mismatch + } + + + + if(!isHwidReset) { + if (!hwid.equals(retrievedHwid)) { + return -4; //HWID does not match and they are not reset + } + } else { + String updateHwidQuery = "UPDATE users SET hwid = ?, hwidReset = ? WHERE username = ?"; + try { + PreparedStatement updateHWIDStatement = connection.prepareStatement(updateHwidQuery); + updateHWIDStatement.setString(1, hwid); + updateHWIDStatement.setBoolean(2, false); // Set hwidReset to false + updateHWIDStatement.setString(3, user); + + int rowsAffected = updateHWIDStatement.executeUpdate(); + + if (rowsAffected > 0) { + return -2; + } else { + return -3; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return -2; //HWID does not match but they are reset, set their reset to false and set their hwid to the last sent one + } + + + //Yooo it worked + return 0; + } else { + System.out.println("User not found."); + return -1; + } + } catch (SQLException e) { e.printStackTrace(); } - System.out.println("Loaded " + users.size() + " Users"); + + + + + return -3; } - public static int isUserValid(String user, String password, String hwid) { - if(!users.usernameExists(user)){ - return -1; //Generic user info mismatch - } + public static boolean createUser(String username, String licenseKey, String discordUserId) { - if(users.getIsBanned(user).equals("true")) { - return -5; //BANNED - } + String jdbcUrl = "jdbc:mariadb://localhost:3306/baseband_users"; + String dbusername = "admin"; + String dbpass = "alpine!"; //i'll encrypt it later - if(users.getPassword(user).equals("reset")) { - return -6; //Their password has been reset - } + Connection connection; - if(!BCrypt.checkpw(password, users.getPassword(user))) { - return -1; //Generic user info mismatch - } + String insertQuery = "INSERT INTO users (username, hashedPassword, isBanned, isHwidReset, hwid, licenseKey, discordUserId) VALUES (?, ?, ?, ?, ?, ?, ?)"; + try { + connection = DriverManager.getConnection(jdbcUrl, dbusername, dbpass); + PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); + preparedStatement.setString(1, username); + preparedStatement.setString(2, "reset"); //password kekw + preparedStatement.setBoolean(3, false); // 0 for not banned + preparedStatement.setBoolean(4, true); // 0 for not banned + preparedStatement.setString(5, "unset"); //HWID + preparedStatement.setString(6, licenseKey); // Set the licenseKey value here + preparedStatement.setString(7, discordUserId); // Set the discord user id + int rowsAffected = preparedStatement.executeUpdate(); - if(users.getResetStatus(user).equals("false")) { - if (!users.getHwid(user).equals(hwid)) { - return -4; //HWID does not match and they are not reset + if (rowsAffected > 0) { + return true; + } else { + return false; } - } else { - users.setResetStatus(user,"false"); - users.setHwid(user, hwid); - return -2; //HWID does not match but they are reset, set their reset to false and set their hwid to the last sent one + } catch (SQLException e) { + e.printStackTrace(); } + return false; + } - return 0; + + public static boolean setHwidReset(String username, boolean hwidReset) { + String jdbcUrl = "jdbc:mariadb://localhost:3306/baseband_users"; + String dbusername = "admin"; + String dbpass = "alpine!"; //i'll encrypt it later + + Connection connection; + + + + String updateHwidResetQuery = "UPDATE users SET isHwidReset = ? WHERE username = ?"; + + try { + connection = DriverManager.getConnection(jdbcUrl, dbusername, dbpass); + PreparedStatement preparedStatement = connection.prepareStatement(updateHwidResetQuery); + preparedStatement.setBoolean(1, hwidReset); + preparedStatement.setString(2, username); + + int rowsAffected = preparedStatement.executeUpdate(); + + if (rowsAffected > 0) { + return true; + } else { + return false; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + } + + + public static boolean setPassword(String username, String password) { + String jdbcUrl = "jdbc:mariadb://localhost:3306/baseband_users"; + String dbusername = "admin"; + String dbpass = "alpine!"; //i'll encrypt it later + + Connection connection; + + + + String updatePasswordQuery = "UPDATE users SET hashedPassword = ? WHERE username = ?"; + + try { + connection = DriverManager.getConnection(jdbcUrl, dbusername, dbpass); + PreparedStatement preparedStatement = connection.prepareStatement(updatePasswordQuery); + preparedStatement.setString(1, password); + preparedStatement.setString(2, username); + + + int rowsAffected = preparedStatement.executeUpdate(); + + if (rowsAffected > 0) { + return true; + } else { + return false; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + } + + public static boolean setBanned(String username, boolean banned) { + String jdbcUrl = "jdbc:mariadb://localhost:3306/baseband_users"; + String dbusername = "admin"; + String dbpass = "alpine!"; //i'll encrypt it later + + Connection connection; + + + + String updateIsBannedQuery = "UPDATE users SET isBanned = ? WHERE username = ?"; + + try { + connection = DriverManager.getConnection(jdbcUrl, dbusername, dbpass); + PreparedStatement preparedStatement = connection.prepareStatement(updateIsBannedQuery); + preparedStatement.setBoolean(1, banned); + preparedStatement.setString(2, username); + + int rowsAffected = preparedStatement.executeUpdate(); + + if (rowsAffected > 0) { + return true; + } else { + return false; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return false; } } diff --git a/Server/src/main/java/dev/baseband/server/socket/UserMap.java b/Server/src/main/java/dev/baseband/server/socket/UserMap.java deleted file mode 100644 index 5b7680d..0000000 --- a/Server/src/main/java/dev/baseband/server/socket/UserMap.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.baseband.server.socket; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class UserMap { - private Map> map = new HashMap<>(); - - public void put(String username, String password, String hwid, String resetStatus, String isBanned) { - Map userMap = map.computeIfAbsent(username, u -> new HashMap<>()); - userMap.put("password", password); - userMap.put("hwid", hwid); - userMap.put("resetStatus", resetStatus); - userMap.put("isBanned", isBanned); - } - - public boolean usernameExists(String username) { - return map.getOrDefault(username, null)!=null; - } - - public Set getUsernames() { - return map.keySet(); - } - - public String getPassword(String username) { - return map.getOrDefault(username, new HashMap<>()).get("password"); - } - - public String getIsBanned(String username) { - return map.getOrDefault(username, new HashMap<>()).get("isBanned"); - } - - public String getHwid(String username) { - return map.getOrDefault(username, new HashMap<>()).get("hwid"); - } - - public String getResetStatus(String username) { - return map.getOrDefault(username, new HashMap<>()).getOrDefault("resetStatus", "false"); - } - - public String getLastTriedPassword(String username) { - return map.getOrDefault(username, new HashMap<>()).getOrDefault("lastTried", "none"); - } - - public Map> getMap() { - return map; - } - - public void setHwid(String username, String newHwid) { - map.computeIfPresent(username, (u, userMap) -> { - userMap.put("hwid", newHwid); - return userMap; - }); - } - - public void setPassword(String username, String newPassword) { - map.computeIfPresent(username, (u, userMap) -> { - userMap.put("password", newPassword); - return userMap; - }); - } - - public void setIsBanned(String username, String isBanned) { - map.computeIfPresent(username, (u, userMap) -> { - userMap.put("isBanned", isBanned); - return userMap; - }); - } - - public void setResetStatus(String username, String resetStatus) { - map.computeIfPresent(username, (u, userMap) -> { - userMap.put("resetStatus", resetStatus); - return userMap; - }); - } - - public void setLastTriedPassword(String username, String resetStatus) { - map.computeIfPresent(username, (u, userMap) -> { - userMap.put("lastTried", resetStatus); - return userMap; - }); - } - - public int size() { - return map.size(); - } - -} \ No newline at end of file