MariaDB+more modules

This commit is contained in:
Jess 2023-09-12 03:29:54 +01:00
parent c6a9ad40aa
commit 7f45bc8ea1
19 changed files with 436 additions and 280 deletions

View file

@ -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)
}
}
}

View file

@ -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;
}

View file

@ -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) {}
}
}

View file

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

View file

@ -39,7 +39,7 @@ public class SetCommand extends Command {
return e.getLocalizedMessage();
}
return "Succeeded. (Set "+settingName+" to "+value+")";
return "Succeeded.";
}
}

View file

@ -15,6 +15,8 @@ public class Module {
int key = 0;
List<Setting<?>> 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 extends Setting<?>> T register(T setting) {
settings.add(setting);

View file

@ -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()) {

View file

@ -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<String> stringSetting = register(new StringSetting("StringSetting","s"));
Setting<Level> levelSetting = register(new EnumSetting<>("Level", Level.HIGH));
enum Level {
LOW,
MEDIUM,
HIGH
}

View file

@ -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!

View file

@ -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'

View file

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

View file

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

View file

@ -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")) {

View file

@ -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'
}

View file

@ -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<String, Map<String, String>> entry : UserManager.users.getMap().entrySet()) {
StringBuilder stringBuilder = new StringBuilder("==============================").append("\n");
String outerKey = entry.getKey();
Map<String, String> 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<String, String> innerEntry : innerMap.entrySet()) {
String innerKey = innerEntry.getKey();
String innerValue = innerEntry.getValue();
stringBuilder.append("Key: [").append(innerKey).append("] Value: [").append(innerValue).append("]").append("\n");
List<Message> 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<Role> roles = member.getRoles();
return roles.stream().filter(role -> role.getName().equals(name)).findFirst().orElse(null);

View file

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

View file

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

View file

@ -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;
}
}

View file

@ -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<String, Map<String, String>> map = new HashMap<>();
public void put(String username, String password, String hwid, String resetStatus, String isBanned) {
Map<String, String> 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<String> 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<String, Map<String, String>> 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();
}
}