diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java index 81727a1c..5da93a4f 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java @@ -7,6 +7,7 @@ import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launchserver.auth.handler.AuthHandler; import pro.gravit.launchserver.auth.protect.ProtectHandler; +import pro.gravit.launchserver.auth.protect.hwid.HWIDProvider; import pro.gravit.launchserver.auth.provider.AuthProvider; import pro.gravit.launchserver.auth.texture.TextureProvider; import pro.gravit.launchserver.components.Component; @@ -211,6 +212,7 @@ public static void registerAll() { WebSocketService.registerResponses(); DaoProvider.registerProviders(); AuthRequest.registerProviders(); + HWIDProvider.registerProviders(); } public static void generateConfigIfNotExists(Path configFile, CommandHandler commandHandler, LaunchServer.LaunchServerEnv env) throws IOException { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java b/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java index 0ac01be2..72a18b1d 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java @@ -175,6 +175,18 @@ private static InsnList serializeValue(Object value) { value.getClass())); } + public static boolean isSerializableValue(Object value) + { + if(value == null) return true; + if (primitiveLDCClasses.contains(value.getClass())) return true; + for (Map.Entry, Serializer> serializerEntry : serializers.entrySet()) { + if (serializerEntry.getKey().isInstance(value)) { + return true; + } + } + return false; + } + @Override public void transform(ClassNode classNode, String className, BuildContext context) { visit(classNode, values); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java index fe86458a..e23d4f48 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java @@ -3,14 +3,25 @@ import pro.gravit.launcher.events.request.GetSecureLevelInfoRequestEvent; import pro.gravit.launcher.events.request.HardwareReportRequestEvent; import pro.gravit.launcher.events.request.VerifySecureLevelKeyRequestEvent; +import pro.gravit.launchserver.Reconfigurable; +import pro.gravit.launchserver.auth.protect.hwid.HWIDException; +import pro.gravit.launchserver.auth.protect.hwid.HWIDProvider; import pro.gravit.launchserver.auth.protect.interfaces.HardwareProtectHandler; +import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler; import pro.gravit.launchserver.auth.protect.interfaces.SecureProtectHandler; import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.response.auth.AuthResponse; import pro.gravit.launchserver.socket.response.secure.HardwareReportResponse; +import pro.gravit.utils.command.Command; +import pro.gravit.utils.helper.LogHelper; -public class AdvancedProtectHandler extends StdProtectHandler implements SecureProtectHandler, HardwareProtectHandler { +import java.util.HashMap; +import java.util.Map; + +public class AdvancedProtectHandler extends StdProtectHandler implements SecureProtectHandler, HardwareProtectHandler, JoinServerProtectHandler, Reconfigurable { public boolean enableHardwareFeature; + public HWIDProvider provider; + @Override public boolean allowGetAccessToken(AuthResponse.AuthContext context) { return (context.authType == AuthResponse.ConnectTypes.CLIENT) && context.client.checkSign; @@ -38,7 +49,22 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { response.sendResult(new HardwareReportRequestEvent()); return; } - + try { + if(!client.isAuth || client.trustLevel == null || client.trustLevel.publicKey == null) + { + response.sendError("Access denied"); + return; + } + provider.normalizeHardwareInfo(response.hardware); + LogHelper.debug("[HardwareInfo] HardwareInfo received"); + boolean needCreate = !provider.addPublicKeyToHardwareInfo(response.hardware, client.trustLevel.publicKey, client); + LogHelper.debug("[HardwareInfo] HardwareInfo needCreate: %s", needCreate ? "true" : "false"); + if(needCreate) + provider.createHardwareInfo(response.hardware, client.trustLevel.publicKey, client); + client.trustLevel.hardwareInfo = response.hardware; + } catch (HWIDException e) { + throw new SecurityException(e.getMessage()); + } response.sendResult(new HardwareReportRequestEvent()); } @@ -46,8 +72,49 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { public VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) { if(enableHardwareFeature) { - return new VerifySecureLevelKeyRequestEvent(true); + if(provider == null) + { + LogHelper.warning("HWIDProvider null. HardwareInfo not checked!"); + } + else + { + try { + client.trustLevel.hardwareInfo = provider.findHardwareInfoByPublicKey(client.trustLevel.publicKey, client); + if(client.trustLevel.hardwareInfo == null) //HWID not found? + return new VerifySecureLevelKeyRequestEvent(true); + } catch (HWIDException e) { + throw new SecurityException(e.getMessage()); //Show banned message + } + } + return new VerifySecureLevelKeyRequestEvent(false); } return new VerifySecureLevelKeyRequestEvent(); } + + @Override + public Map getCommands() { + Map commands = new HashMap<>(); + if(provider instanceof Reconfigurable) + { + commands.putAll(((Reconfigurable) provider).getCommands()); + } + return commands; + } + + @Override + public boolean onJoinServer(String serverID, String username, Client client) { + return !enableHardwareFeature || (client.trustLevel != null && client.trustLevel.hardwareInfo != null); + } + + @Override + public void init() { + if(provider != null) + provider.init(); + } + + @Override + public void close() { + if(provider != null) + provider.close(); + } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java index 8bdaadc3..ce19e627 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java @@ -20,5 +20,15 @@ public static void registerHandlers() { public abstract boolean allowGetAccessToken(AuthResponse.AuthContext context); public abstract void checkLaunchServerLicense(); //Выдает SecurityException при ошибке проверки лицензии + + public void init() + { + + } + + public void close() + { + + } //public abstract } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDException.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDException.java new file mode 100644 index 00000000..df960144 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDException.java @@ -0,0 +1,22 @@ +package pro.gravit.launchserver.auth.protect.hwid; + +public class HWIDException extends Exception { + public HWIDException() { + } + + public HWIDException(String message) { + super(message); + } + + public HWIDException(String message, Throwable cause) { + super(message, cause); + } + + public HWIDException(Throwable cause) { + super(cause); + } + + public HWIDException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java new file mode 100644 index 00000000..1c46f734 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java @@ -0,0 +1,118 @@ +package pro.gravit.launchserver.auth.protect.hwid; + +import pro.gravit.launcher.request.secure.HardwareReportRequest; +import pro.gravit.launchserver.helper.DamerauHelper; +import pro.gravit.launchserver.socket.Client; +import pro.gravit.utils.ProviderMap; +import pro.gravit.utils.helper.LogHelper; +import pro.gravit.utils.helper.SecurityHelper; + +import java.util.Arrays; + +public abstract class HWIDProvider { + public static final ProviderMap providers = new ProviderMap<>("HWIDProvider"); + private static boolean registredProv = false; + public static void registerProviders() { + if(!registredProv) + { + providers.register("memory", MemoryHWIDProvider.class); + providers.register("mysql", MysqlHWIDProvider.class); + registredProv = true; + } + } + public abstract HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException; + public abstract void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException; + public abstract boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException; + + public void normalizeHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo) + { + if(hardwareInfo.baseboardSerialNumber != null) hardwareInfo.baseboardSerialNumber = hardwareInfo.baseboardSerialNumber.trim(); + if(hardwareInfo.hwDiskId != null) hardwareInfo.hwDiskId = hardwareInfo.hwDiskId.trim(); + } + public static class HardwareInfoCompareResult + { + public double firstSpoofingLevel = 0.0; + public double secondSpoofingLevel = 0.0; + public double compareLevel; + } + //Required normalize HardwareInfo + public HardwareInfoCompareResult compareHardwareInfo(HardwareReportRequest.HardwareInfo first, HardwareReportRequest.HardwareInfo second) + { + HardwareInfoCompareResult result = new HardwareInfoCompareResult(); + if(first.hwDiskId == null || first.hwDiskId.isEmpty()) result.firstSpoofingLevel += 0.9; + if(first.displayId == null || first.displayId.length < 4) result.firstSpoofingLevel += 0.3; + if(first.baseboardSerialNumber == null || first.baseboardSerialNumber.trim().isEmpty()) result.firstSpoofingLevel += 0.2; + if(second.hwDiskId == null || second.hwDiskId.trim().isEmpty()) result.secondSpoofingLevel += 0.9; + if(second.displayId == null || second.displayId.length < 4) result.secondSpoofingLevel += 0.3; + if(second.baseboardSerialNumber == null || second.baseboardSerialNumber.trim().isEmpty()) result.secondSpoofingLevel += 0.2; + if(first.hwDiskId != null && second.hwDiskId != null) + { + int hwDIskIdRate = DamerauHelper.calculateDistance(first.hwDiskId.toLowerCase(), second.hwDiskId.toLowerCase()); + if(hwDIskIdRate == 0) // 100% compare + { + result.compareLevel += 0.99; + } + else if(hwDIskIdRate < 3) //Very small change + { + result.compareLevel += 0.85; + } + else if(hwDIskIdRate < (first.hwDiskId.length()+second.hwDiskId.length()) / 4) + { + double addLevel = hwDIskIdRate / ( (double)(first.hwDiskId.length()+second.hwDiskId.length()) / 2.0 ); + if(addLevel > 0.0 && addLevel < 0.85) result.compareLevel += addLevel; + } + } + if(first.baseboardSerialNumber != null && second.baseboardSerialNumber != null) + { + int baseboardSerialRate = DamerauHelper.calculateDistance(first.baseboardSerialNumber.toLowerCase(), second.baseboardSerialNumber.toLowerCase()); + if(baseboardSerialRate == 0) // 100% compare + { + result.compareLevel += 0.3; + } + else if(baseboardSerialRate < 3) //Very small change + { + result.compareLevel += 0.15; + } + } + if(first.displayId != null && second.displayId != null) + { + if(Arrays.equals(first.displayId, second.displayId)) + { + result.compareLevel += 0.75; + } + } + //Check statistic info + if(first.logicalProcessors == 0 || first.physicalProcessors == 0 || first.logicalProcessors < first.physicalProcessors) //WTF + result.firstSpoofingLevel += 0.9; + if(second.logicalProcessors == 0 || second.physicalProcessors == 0 || second.logicalProcessors < second.physicalProcessors) //WTF + result.secondSpoofingLevel += 0.9; + if(first.physicalProcessors == second.physicalProcessors && first.logicalProcessors == second.logicalProcessors) + result.compareLevel += 0.05; + if(first.battery != second.battery) + result.compareLevel -= 0.05; + if(first.processorMaxFreq == second.processorMaxFreq) + result.compareLevel += 0.1; + if(first.totalMemory == second.totalMemory) + result.compareLevel += 0.1; + if(Math.abs(first.totalMemory - second.totalMemory) < 32*1024) + result.compareLevel += 0.05; + return result; + } + + protected void printHardwareInfo(LogHelper.Level logLevel, HardwareReportRequest.HardwareInfo info) + { + LogHelper.log(logLevel, String.format("[HardwareInfo] Processor: logical %d | physical %d | freq %d | bitness %d", info.logicalProcessors, info.physicalProcessors, info.processorMaxFreq, info.bitness) , false); + LogHelper.log(logLevel, String.format("[HardwareInfo] Memory max: %d | battery %s", info.totalMemory, info.battery ? "true" : "false") , false); + LogHelper.log(logLevel, String.format("[HardwareInfo] HWDiskID %s | baseboardSerialNumber %s | displayId hash: %s", info.hwDiskId, info.baseboardSerialNumber, SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.MD5, info.displayId))) , false); + } + + public void init() + { + + } + + public void close() + { + + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java new file mode 100644 index 00000000..9ec34510 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java @@ -0,0 +1,105 @@ +package pro.gravit.launchserver.auth.protect.hwid; + +import pro.gravit.launcher.request.secure.HardwareReportRequest; +import pro.gravit.launchserver.Reconfigurable; +import pro.gravit.launchserver.socket.Client; +import pro.gravit.utils.command.Command; +import pro.gravit.utils.command.SubCommand; +import pro.gravit.utils.helper.LogHelper; +import pro.gravit.utils.helper.SecurityHelper; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class MemoryHWIDProvider extends HWIDProvider implements Reconfigurable { + public double warningSpoofingLevel = -1.0; + public double criticalCompareLevel = 1.0; + + @Override + public Map getCommands() { + Map commands = new HashMap<>(); + commands.put("hardwarelist", new SubCommand() { + @Override + public void invoke(String... args) throws Exception { + for(MemoryHWIDEntity e : db) + { + printHardwareInfo(LogHelper.Level.INFO, e.hardware); + LogHelper.info("ID %d banned %s", e.id, e.banned ? "true" : "false"); + LogHelper.info("PublicKey Hash: %s", SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA1, e.publicKey))); + } + } + }); + commands.put("hardwareban", new SubCommand() { + @Override + public void invoke(String... args) throws Exception { + verifyArgs(args, 1); + long id = Long.parseLong(args[0]); + for(MemoryHWIDEntity e : db) + { + if(e.id == id) + { + e.banned = true; + LogHelper.info("HardwareID %d banned", e.id); + } + } + } + }); + return commands; + } + + static class MemoryHWIDEntity + { + public HardwareReportRequest.HardwareInfo hardware; + public byte[] publicKey; + public boolean banned; + public long id; + + public MemoryHWIDEntity(HardwareReportRequest.HardwareInfo hardware, byte[] publicKey) { + this.hardware = hardware; + this.publicKey = publicKey; + this.id = SecurityHelper.newRandom().nextLong(); + } + } + public Set db = ConcurrentHashMap.newKeySet(); + + @Override + public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException { + for(MemoryHWIDEntity e : db) { + if(Arrays.equals(e.publicKey, publicKey)) + { + if(e.banned) throw new HWIDException("You HWID banned"); + return e.hardware; + } + }; + return null; + } + + @Override + public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { + db.add(new MemoryHWIDEntity(hardwareInfo, publicKey)); + } + + @Override + public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { + boolean isAlreadyWarning = false; + for(MemoryHWIDEntity e : db) { + HardwareInfoCompareResult result = compareHardwareInfo(e.hardware, hardwareInfo); + if(warningSpoofingLevel > 0 && result.firstSpoofingLevel > warningSpoofingLevel && !isAlreadyWarning) + { + LogHelper.warning("HardwareInfo spoofing level too high: %d", result.firstSpoofingLevel); + isAlreadyWarning = true; + } + if(result.compareLevel > criticalCompareLevel) + { + LogHelper.debug("HardwareInfo publicKey change: compareLevel %d", result.compareLevel); + if(e.banned) throw new HWIDException("You HWID banned"); + e.publicKey = publicKey; + return true; + } + } + return false; + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java new file mode 100644 index 00000000..623593b0 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java @@ -0,0 +1,167 @@ +package pro.gravit.launchserver.auth.protect.hwid; + +import pro.gravit.launcher.request.secure.HardwareReportRequest; +import pro.gravit.launchserver.auth.MySQLSourceConfig; +import pro.gravit.launchserver.socket.Client; +import pro.gravit.utils.helper.IOHelper; +import pro.gravit.utils.helper.LogHelper; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.sql.*; + +public class MysqlHWIDProvider extends HWIDProvider { + public MySQLSourceConfig mySQLHolder; + public double warningSpoofingLevel = -1.0; + public double criticalCompareLevel = 1.0; + + public String tableHWID = "hwids"; + public String tableHWIDLog = "hwidLog"; + public String tableUsers; + public String usersNameColumn; + public String usersHWIDColumn; + + private String sqlFindByPublicKey; + private String sqlFindByHardware; + private String sqlCreateHardware; + private String sqlCreateHWIDLog; + private String sqlUpdateHardware; + private String sqlUpdateUsers; + + @Override + public void init() { + sqlFindByPublicKey = String.format("SELECT hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, banned FROM %s WHERE `publicKey` = ?", tableHWID); + sqlFindByHardware = String.format("SELECT hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, banned FROM %s", tableHWID); + sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID); + sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog); + sqlUpdateHardware = String.format("UPDATE %s SET `publicKey` = ? WHERE `id` = ?", tableHWID); + if(tableUsers != null && usersHWIDColumn != null && usersNameColumn != null) + { + sqlUpdateUsers = String.format("UPDATE %s SET `%s` = ? WHERE `%s` = ?", tableUsers, usersHWIDColumn, usersNameColumn); + } + } + + @Override + public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException { + try(Connection connection = mySQLHolder.getConnection()) + { + PreparedStatement s = connection.prepareStatement(sqlFindByPublicKey); + s.setBlob(1, new ByteArrayInputStream(publicKey)); + ResultSet set = s.executeQuery(); + if(set.next()) + { + if(set.getBoolean(11)) //isBanned + { + throw new SecurityException("You HWID banned"); + } + long id = set.getLong(10); + setUserHardwareId(connection, client.username, id); + return fetchHardwareInfo(set); + } + else + { + return null; + } + } catch (SQLException | IOException throwables) { + LogHelper.error(throwables); + throw new SecurityException("SQL error. Please try again later"); + } + } + + private HardwareReportRequest.HardwareInfo fetchHardwareInfo(ResultSet set) throws SQLException, IOException { + HardwareReportRequest.HardwareInfo hardwareInfo = new HardwareReportRequest.HardwareInfo(); + hardwareInfo.hwDiskId = set.getString(1); + hardwareInfo.baseboardSerialNumber = set.getString(2); + hardwareInfo.displayId = IOHelper.read(set.getBlob(3).getBinaryStream()); + hardwareInfo.bitness = set.getInt(4); + hardwareInfo.totalMemory = set.getLong(5); + hardwareInfo.logicalProcessors = set.getInt(6); + hardwareInfo.physicalProcessors = set.getInt(7); + hardwareInfo.processorMaxFreq = set.getLong(8); + hardwareInfo.battery = set.getBoolean(9); + return hardwareInfo; + } + + @Override + public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { + try(Connection connection = mySQLHolder.getConnection()) + { + PreparedStatement s = connection.prepareStatement(sqlCreateHardware, Statement.RETURN_GENERATED_KEYS); + s.setBlob(1, new ByteArrayInputStream(publicKey)); + s.setString(2, hardwareInfo.hwDiskId); + s.setString(3, hardwareInfo.baseboardSerialNumber); + s.setBlob(4, new ByteArrayInputStream(hardwareInfo.displayId)); + s.setInt(5, hardwareInfo.bitness); + s.setLong(6, hardwareInfo.totalMemory); + s.setInt(7, hardwareInfo.logicalProcessors); + s.setInt(8, hardwareInfo.physicalProcessors); + s.setLong(9, hardwareInfo.processorMaxFreq); + s.setBoolean(10, hardwareInfo.battery); + s.executeUpdate(); + try (ResultSet generatedKeys = s.getGeneratedKeys()) { + if (generatedKeys.next()) { + writeHwidLog(connection, generatedKeys.getLong(1), publicKey); + setUserHardwareId(connection, client.username, generatedKeys.getLong(1)); + } + } + } catch (SQLException throwables) { + LogHelper.error(throwables); + throw new SecurityException("SQL error. Please try again later"); + } + } + + @Override + public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { + try(Connection connection = mySQLHolder.getConnection()) + { + PreparedStatement s = connection.prepareStatement(sqlFindByHardware); + ResultSet set = s.executeQuery(); + while(set.next()) + { + HardwareReportRequest.HardwareInfo hw = fetchHardwareInfo(set); + long id = set.getLong(10); + HardwareInfoCompareResult result = compareHardwareInfo(hw, hardwareInfo); + if(result.compareLevel > criticalCompareLevel) + { + if(set.getBoolean(11)) //isBanned + { + throw new SecurityException("You HWID banned"); + } + writeHwidLog(connection, id, publicKey); + changePublicKey(connection, id, publicKey); + setUserHardwareId(connection, client.username, id); + return true; + } + } + } catch (SQLException | IOException throwables) + { + LogHelper.error(throwables); + throw new SecurityException("SQL error. Please try again later"); + } + return false; + } + private void changePublicKey(Connection connection, long id, byte[] publicKey) throws SQLException { + PreparedStatement s = connection.prepareStatement(sqlUpdateHardware); + s.setBlob(1, new ByteArrayInputStream(publicKey)); + s.setLong(2, id); + s.executeUpdate(); + } + private void writeHwidLog(Connection connection, long hwidId, byte[] newPublicKey) throws SQLException { + PreparedStatement s = connection.prepareStatement(sqlCreateHWIDLog); + s.setLong(1, hwidId); + s.setBlob(2, new ByteArrayInputStream(newPublicKey)); + s.executeUpdate(); + } + private void setUserHardwareId(Connection connection, String username, long hwidId) throws SQLException { + if(sqlUpdateUsers == null || username == null) return; + PreparedStatement s = connection.prepareStatement(sqlUpdateUsers); + s.setLong(1, hwidId); + s.setString(2, username); + s.executeUpdate(); + } + + @Override + public void close() { + mySQLHolder.close(); + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java new file mode 100644 index 00000000..dafedbe1 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java @@ -0,0 +1,10 @@ +package pro.gravit.launchserver.auth.protect.interfaces; + +import pro.gravit.launchserver.socket.Client; + +public interface JoinServerProtectHandler { + default boolean onJoinServer(String serverID, String username, Client client) + { + return true; + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/AuthProviderDAOResult.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/AuthProviderDAOResult.java new file mode 100644 index 00000000..debb953d --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/AuthProviderDAOResult.java @@ -0,0 +1,21 @@ +package pro.gravit.launchserver.auth.provider; + +import pro.gravit.launcher.ClientPermissions; +import pro.gravit.launchserver.dao.User; + +public class AuthProviderDAOResult extends AuthProviderResult { + public User daoObject; + + public AuthProviderDAOResult(String username, String accessToken) { + super(username, accessToken); + } + + public AuthProviderDAOResult(String username, String accessToken, ClientPermissions permissions) { + super(username, accessToken, permissions); + } + + public AuthProviderDAOResult(String username, String accessToken, ClientPermissions permissions, User daoObject) { + super(username, accessToken, permissions); + this.daoObject = daoObject; + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/HibernateAuthProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/HibernateAuthProvider.java index 8ce22cef..ef68d6ae 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/HibernateAuthProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/provider/HibernateAuthProvider.java @@ -26,7 +26,7 @@ public AuthProviderResult auth(String login, AuthRequest.AuthPasswordInterface p if (user == null) throw new AuthException("Username incorrect"); else throw new AuthException("Username or password incorrect"); } - return new AuthProviderResult(login, SecurityHelper.randomStringToken(), user.getPermissions()); + return new AuthProviderDAOResult(login, SecurityHelper.randomStringToken(), user.getPermissions(), user); } @Override diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetAllUsersCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetAllUsersCommand.java deleted file mode 100644 index 0cf91d4d..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetAllUsersCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -package pro.gravit.launchserver.command.dao; - -import pro.gravit.launchserver.LaunchServer; -import pro.gravit.launchserver.command.Command; -import pro.gravit.launchserver.dao.User; -import pro.gravit.utils.helper.LogHelper; - -public class GetAllUsersCommand extends Command { - public GetAllUsersCommand(LaunchServer server) { - super(server); - } - - @Override - public String getArgsDescription() { - return ""; - } - - @Override - public String getUsageDescription() { - return "get all users information"; - } - - @Override - public void invoke(String... args) { - int count = 0; - for (User user : server.config.dao.userDAO.findAll()) { - LogHelper.subInfo("[%s] UUID: %s", user.getUsername(), user.getUuid().toString()); - count++; - } - LogHelper.info("Print %d users", count); - } -} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetUserCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetUserCommand.java deleted file mode 100644 index 3fe4fb1a..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/GetUserCommand.java +++ /dev/null @@ -1,37 +0,0 @@ -package pro.gravit.launchserver.command.dao; - -import pro.gravit.launchserver.LaunchServer; -import pro.gravit.launchserver.command.Command; -import pro.gravit.launchserver.dao.User; -import pro.gravit.utils.helper.LogHelper; - -public class GetUserCommand extends Command { - public GetUserCommand(LaunchServer server) { - super(server); - } - - @Override - public String getArgsDescription() { - return "[username]"; - } - - @Override - public String getUsageDescription() { - return "get user information"; - } - - @Override - public void invoke(String... args) throws Exception { - verifyArgs(args, 1); - User user = server.config.dao.userDAO.findByUsername(args[0]); - if (user == null) { - LogHelper.error("User %s not found", args[0]); - return; - } - LogHelper.info("[%s] UUID: %s", user.getUsername(), user.getUuid().toString()); - //for(UserHWID hwid : user.hwids) - //{ - // LogHelper.info("[%s] HWID: memory: %d | serial %s | hwdiskserial: %s | processorID %s | macAddr %s", user.username, hwid.totalMemory, hwid.serialNumber, hwid.HWDiskSerial, hwid.processorID, hwid.macAddr); - //} - } -} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/RegisterCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/RegisterCommand.java deleted file mode 100644 index 7fabacc6..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/RegisterCommand.java +++ /dev/null @@ -1,35 +0,0 @@ -package pro.gravit.launchserver.command.dao; - -import pro.gravit.launchserver.LaunchServer; -import pro.gravit.launchserver.command.Command; -import pro.gravit.launchserver.dao.impl.UserHibernateImpl; -import pro.gravit.utils.helper.LogHelper; - -import java.util.UUID; - -public class RegisterCommand extends Command { - public RegisterCommand(LaunchServer server) { - super(server); - } - - @Override - public String getArgsDescription() { - return "[login] [password]"; - } - - @Override - public String getUsageDescription() { - return "Register new user"; - } - - @Override - public void invoke(String... args) throws Exception { - verifyArgs(args, 2); - UserHibernateImpl user = new UserHibernateImpl(); - user.username = args[0]; - user.setPassword(args[1]); - user.uuid = UUID.randomUUID(); - server.config.dao.userDAO.save(user); - LogHelper.info("User %s registered. UUID: %s", user.username, user.uuid.toString()); - } -} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/SetUserPasswordCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/SetUserPasswordCommand.java deleted file mode 100644 index d6a0a02e..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/dao/SetUserPasswordCommand.java +++ /dev/null @@ -1,36 +0,0 @@ -package pro.gravit.launchserver.command.dao; - -import pro.gravit.launchserver.LaunchServer; -import pro.gravit.launchserver.command.Command; -import pro.gravit.launchserver.dao.User; -import pro.gravit.utils.helper.LogHelper; - -public class SetUserPasswordCommand extends Command { - - public SetUserPasswordCommand(LaunchServer server) { - super(server); - } - - @Override - public String getArgsDescription() { - return "[username] [new password]"; - } - - @Override - public String getUsageDescription() { - return "Set user password"; - } - - @Override - public void invoke(String... args) throws Exception { - verifyArgs(args, 2); - User user = server.config.dao.userDAO.findByUsername(args[0]); - if (user == null) { - LogHelper.error("User %s not found", args[1]); - return; - } - user.setPassword(args[1]); - server.config.dao.userDAO.update(user); - LogHelper.info("[%s] UUID: %s | New Password: %s", user.getUsername(), user.getUuid().toString(), args[1]); - } -} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/handler/CommandHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/handler/CommandHandler.java index 7eb27214..45f01c24 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/handler/CommandHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/handler/CommandHandler.java @@ -5,10 +5,6 @@ import pro.gravit.launchserver.command.auth.UUIDToUsernameCommand; import pro.gravit.launchserver.command.auth.UsernameToUUIDCommand; import pro.gravit.launchserver.command.basic.*; -import pro.gravit.launchserver.command.dao.GetAllUsersCommand; -import pro.gravit.launchserver.command.dao.GetUserCommand; -import pro.gravit.launchserver.command.dao.RegisterCommand; -import pro.gravit.launchserver.command.dao.SetUserPasswordCommand; import pro.gravit.launchserver.command.dump.DumpSessionsCommand; import pro.gravit.launchserver.command.hash.*; import pro.gravit.launchserver.command.install.CheckInstallCommand; @@ -56,15 +52,6 @@ public static void registerCommands(pro.gravit.utils.command.CommandHandler hand Category updatesCategory = new Category(updates, "updates", "Update and Sync Management"); handler.registerCategory(updatesCategory); - //Register dao commands - BaseCommandCategory dao = new BaseCommandCategory(); - dao.registerCommand("register", new RegisterCommand(server)); - dao.registerCommand("setUserPassword", new SetUserPasswordCommand(server)); - dao.registerCommand("getUser", new GetUserCommand(server)); - dao.registerCommand("getAllUsers", new GetAllUsersCommand(server)); - Category daoCategory = new Category(dao, "DAO", "Data Management"); - handler.registerCategory(daoCategory); - // Register auth commands BaseCommandCategory auth = new BaseCommandCategory(); auth.registerCommand("auth", new AuthCommand(server)); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/config/LaunchServerConfig.java b/LaunchServer/src/main/java/pro/gravit/launchserver/config/LaunchServerConfig.java index 9cef565c..08ca4407 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/config/LaunchServerConfig.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/config/LaunchServerConfig.java @@ -183,6 +183,8 @@ public void init(LaunchServer.ReloadType type) { dao.init(server); } if (protectHandler != null) { + server.registerObject("protectHandler", protectHandler); + protectHandler.init(); protectHandler.checkLaunchServerLicense(); } if (components != null) { @@ -223,6 +225,10 @@ public void close(LaunchServer.ReloadType type) { } catch (Exception e) { LogHelper.error(e); } + if (protectHandler != null) { + server.unregisterObject("protectHandler", protectHandler); + protectHandler.close(); + } if (dao != null) { server.unregisterObject("dao", dao); if (dao instanceof AutoCloseable) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/HibernateUserDAOImpl.java b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/HibernateUserDAOImpl.java deleted file mode 100644 index e11fe09d..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/HibernateUserDAOImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -package pro.gravit.launchserver.dao.impl; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import pro.gravit.launchserver.dao.User; -import pro.gravit.launchserver.dao.UserDAO; - -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import java.util.List; -import java.util.UUID; - -public class HibernateUserDAOImpl implements UserDAO { - private final SessionFactory factory; - - public HibernateUserDAOImpl(SessionFactory factory) { - this.factory = factory; - } - - public UserHibernateImpl findById(int id) { - try (Session s = factory.openSession()) { - return s.get(UserHibernateImpl.class, id); - } - } - - public UserHibernateImpl findByUsername(String username) { - EntityManager em = factory.createEntityManager(); - em.getTransaction().begin(); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery personCriteria = cb.createQuery(UserHibernateImpl.class); - Root rootUser = personCriteria.from(UserHibernateImpl.class); - personCriteria.select(rootUser).where(cb.equal(rootUser.get("username"), username)); - List ret = em.createQuery(personCriteria).getResultList(); - em.close(); - return ret.size() == 0 ? null : ret.get(0); - } - - public UserHibernateImpl findByUUID(UUID uuid) { - EntityManager em = factory.createEntityManager(); - em.getTransaction().begin(); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery personCriteria = cb.createQuery(UserHibernateImpl.class); - Root rootUser = personCriteria.from(UserHibernateImpl.class); - personCriteria.select(rootUser).where(cb.equal(rootUser.get("uuid"), uuid)); - List ret = em.createQuery(personCriteria).getResultList(); - em.close(); - return ret.size() == 0 ? null : ret.get(0); - } - - public void save(User user) { - try (Session session = factory.openSession()) { - Transaction tx1 = session.beginTransaction(); - session.save(user); - tx1.commit(); - } - } - - public void update(User user) { - try (Session session = factory.openSession()) { - Transaction tx1 = session.beginTransaction(); - session.update(user); - tx1.commit(); - } - } - - public void delete(User user) { - try (Session session = factory.openSession()) { - Transaction tx1 = session.beginTransaction(); - session.delete(user); - tx1.commit(); - } - } - - @SuppressWarnings("unchecked") - public List findAll() { - try (Session s = factory.openSession()) { - return (List) s.createQuery("From User").list(); - } - } -} \ No newline at end of file diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/UserHibernateImpl.java b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/UserHibernateImpl.java deleted file mode 100644 index caf45f6d..00000000 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/impl/UserHibernateImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -package pro.gravit.launchserver.dao.impl; - -import pro.gravit.launcher.ClientPermissions; -import pro.gravit.launchserver.dao.User; -import pro.gravit.utils.helper.LogHelper; -import pro.gravit.utils.helper.SecurityHelper; - -import javax.persistence.*; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.UUID; - -@Entity(name = "User") -@Table(name = "users") -public class UserHibernateImpl implements User { - @Column(unique = true) - public String username; - public String email; - @Column(unique = true) - public UUID uuid; - public String serverID; - public long permissions; - public long flags; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - @Column(name = "password") - private byte[] password; - private String accessToken; - private String password_salt; - - public void setPassword(String password) { - password_salt = SecurityHelper.randomStringAESKey(); - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - LogHelper.error(e); - return; - } - this.password = digest.digest(password.concat(password_salt).getBytes(StandardCharsets.UTF_8)); - } - - public boolean verifyPassword(String password) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - LogHelper.error(e); - return false; - } - byte[] enpassword = digest.digest(password.concat(password_salt).getBytes(StandardCharsets.UTF_8)); - return Arrays.equals(enpassword, this.password); - } - - public ClientPermissions getPermissions() { - return new ClientPermissions(permissions, flags); - } - - public void setPermissions(ClientPermissions permissions) { - this.permissions = permissions.permissions; - this.flags = permissions.flags; - } - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - @Override - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public UUID getUuid() { - return uuid; - } - - public void setUuid(UUID uuid) { - this.uuid = uuid; - } - - @Override - public String getServerID() { - return serverID; - } - - @Override - public void setServerID(String serverID) { - this.serverID = serverID; - } -} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/DaoProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/DaoProvider.java index 9921ac47..a7fad686 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/DaoProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/DaoProvider.java @@ -9,7 +9,7 @@ public abstract class DaoProvider { public UserDAO userDAO; public static void registerProviders() { - providers.register("hibernate", HibernateDaoProvider.class); + // None } public abstract void init(LaunchServer server); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/HibernateDaoProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/HibernateDaoProvider.java index c08cc0e2..bae109bd 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/HibernateDaoProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/dao/provider/HibernateDaoProvider.java @@ -6,8 +6,7 @@ import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.Reconfigurable; import pro.gravit.launchserver.dao.User; -import pro.gravit.launchserver.dao.impl.HibernateUserDAOImpl; -import pro.gravit.launchserver.dao.impl.UserHibernateImpl; +import pro.gravit.launchserver.dao.UserDAO; import pro.gravit.utils.command.Command; import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.helper.CommonHelper; @@ -17,7 +16,7 @@ import java.util.HashMap; import java.util.Map; -public class HibernateDaoProvider extends DaoProvider implements Reconfigurable, AutoCloseable { +public abstract class HibernateDaoProvider extends DaoProvider implements Reconfigurable, AutoCloseable { public String driver; public String url; public String username; @@ -26,13 +25,13 @@ public class HibernateDaoProvider extends DaoProvider implements Reconfigurable, public String pool_size; public String hibernateConfig; public boolean parallelHibernateInit; - private transient SessionFactory sessionFactory; + protected transient SessionFactory sessionFactory; @Override public void init(LaunchServer server) { Runnable init = () -> { Configuration cfg = new Configuration() - .addAnnotatedClass(UserHibernateImpl.class) + //.addAnnotatedClass(UserHibernateImpl.class) .setProperty("hibernate.connection.driver_class", driver) .setProperty("hibernate.connection.url", url) .setProperty("hibernate.connection.username", username) @@ -42,8 +41,9 @@ public void init(LaunchServer server) { cfg.setProperty("hibernate.dialect", dialect); if (hibernateConfig != null) cfg.configure(Paths.get(hibernateConfig).toFile()); + onConfigure(cfg); sessionFactory = cfg.buildSessionFactory(); - userDAO = new HibernateUserDAOImpl(sessionFactory); + userDAO = newUserDAO(); }; if (parallelHibernateInit) CommonHelper.newThread("Hibernate Thread", true, init); @@ -51,6 +51,10 @@ public void init(LaunchServer server) { init.run(); } + protected abstract void onConfigure(Configuration configuration); + + protected abstract UserDAO newUserDAO(); + @Override public Map getCommands() { Map commands = new HashMap<>(); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/helper/DamerauHelper.java b/LaunchServer/src/main/java/pro/gravit/launchserver/helper/DamerauHelper.java new file mode 100644 index 00000000..31853004 --- /dev/null +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/helper/DamerauHelper.java @@ -0,0 +1,36 @@ +package pro.gravit.launchserver.helper; + +import java.util.Arrays; + +public class DamerauHelper { + //Расстояние Дамерау — Левенштейна. GitHub https://github.com/crwohlfeil/damerau-levenshtein + public static int calculateDistance(CharSequence source, CharSequence target) { + if (source == null || target == null) { + throw new IllegalArgumentException("Parameter must not be null"); + } + int sourceLength = source.length(); + int targetLength = target.length(); + if (sourceLength == 0) return targetLength; + if (targetLength == 0) return sourceLength; + int[][] dist = new int[sourceLength + 1][targetLength + 1]; + for (int i = 0; i < sourceLength + 1; i++) { + dist[i][0] = i; + } + for (int j = 0; j < targetLength + 1; j++) { + dist[0][j] = j; + } + for (int i = 1; i < sourceLength + 1; i++) { + for (int j = 1; j < targetLength + 1; j++) { + int cost = source.charAt(i - 1) == target.charAt(j - 1) ? 0 : 1; + dist[i][j] = Math.min(Math.min(dist[i - 1][j] + 1, dist[i][j - 1] + 1), dist[i - 1][j - 1] + cost); + if (i > 1 && + j > 1 && + source.charAt(i - 1) == target.charAt(j - 2) && + source.charAt(i - 2) == target.charAt(j - 1)) { + dist[i][j] = Math.min(dist[i][j], dist[i - 2][j - 2] + cost); + } + } + } + return dist[sourceLength][targetLength]; + } +} diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java b/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java index ec571b65..5c9c38a2 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java @@ -2,6 +2,7 @@ import pro.gravit.launcher.Launcher; import pro.gravit.launchserver.LaunchServer; +import pro.gravit.launchserver.asm.InjectClassAcceptor; import pro.gravit.launchserver.binary.tasks.MainBuildTask; import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.LogHelper; @@ -120,15 +121,17 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO targetConfig = Launcher.gsonManager.configGson.fromJson(reader, clazz); } } - Field[] fields = clazz.getFields(); - for (Field field : fields) { - if ((field.getModifiers() & Modifier.STATIC) != 0) continue; - Object obj = field.get(targetConfig); - String configPropertyName = "modules.".concat(entity.moduleConfigName.toLowerCase()).concat(".").concat(field.getName().toLowerCase()); - if (entity.propertyMap == null) entity.propertyMap = new HashMap<>(); - LogHelper.dev("Property name %s", configPropertyName); - entity.propertyMap.put(configPropertyName, obj); - } + //Field[] fields = clazz.getFields(); + //for (Field field : fields) { + // if ((field.getModifiers() & Modifier.STATIC) != 0) continue; + // Object obj = field.get(targetConfig); + // String configPropertyName = "modules.".concat(entity.moduleConfigName.toLowerCase()).concat(".").concat(field.getName().toLowerCase()); + // if (entity.propertyMap == null) entity.propertyMap = new HashMap<>(); + // LogHelper.dev("Property name %s", configPropertyName); + // entity.propertyMap.put(configPropertyName, obj); + //} + if (entity.propertyMap == null) entity.propertyMap = new HashMap<>(); + addClassFieldsToProperties(entity.propertyMap, "modules.".concat(entity.moduleConfigName.toLowerCase()), targetConfig, clazz); } catch (Throwable e) { LogHelper.error(e); } @@ -140,4 +143,21 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO return super.visitFile(file, attrs); } } + public void addClassFieldsToProperties(Map propertyMap, String prefix, Object object, Class classOfObject) throws IllegalAccessException { + Field[] fields = classOfObject.getFields(); + for (Field field : fields) { + if ((field.getModifiers() & Modifier.STATIC) != 0) continue; + Object obj = field.get(object); + String propertyName = prefix.concat(".").concat(field.getName()); + if(InjectClassAcceptor.isSerializableValue(obj)) + { + propertyMap.put(propertyName, obj); + } + else + { + //Try recursive add fields + addClassFieldsToProperties(propertyMap, propertyName, obj, obj.getClass()); + } + } + } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/LaunchServerGsonManager.java b/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/LaunchServerGsonManager.java index 4fde86f7..4b735948 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/LaunchServerGsonManager.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/LaunchServerGsonManager.java @@ -8,6 +8,7 @@ import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launchserver.auth.handler.AuthHandler; import pro.gravit.launchserver.auth.protect.ProtectHandler; +import pro.gravit.launchserver.auth.protect.hwid.HWIDProvider; import pro.gravit.launchserver.auth.provider.AuthProvider; import pro.gravit.launchserver.auth.texture.TextureProvider; import pro.gravit.launchserver.components.Component; @@ -36,6 +37,7 @@ public void registerAdapters(GsonBuilder builder) { builder.registerTypeAdapter(WebSocketServerResponse.class, new UniversalJsonAdapter<>(WebSocketService.providers)); builder.registerTypeAdapter(WebSocketEvent.class, new JsonResultSerializeAdapter()); builder.registerTypeAdapter(AuthRequest.AuthPasswordInterface.class, new UniversalJsonAdapter<>(AuthRequest.providers)); + builder.registerTypeAdapter(HWIDProvider.class, new UniversalJsonAdapter<>(HWIDProvider.providers)); modulesManager.invokeEvent(new PreGsonPhase(builder)); //ClientWebSocketService.appendTypeAdapters(builder); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java index 5506eb40..461e9fc7 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java @@ -2,8 +2,10 @@ import pro.gravit.launcher.ClientPermissions; import pro.gravit.launcher.profiles.ClientProfile; +import pro.gravit.launcher.request.secure.HardwareReportRequest; import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.auth.AuthProviderPair; +import pro.gravit.launchserver.dao.User; import pro.gravit.launchserver.socket.response.auth.AuthResponse; import pro.gravit.utils.helper.LogHelper; @@ -22,6 +24,8 @@ public class Client { public transient AuthProviderPair auth; + public transient User daoObject; + public Client(long session) { this.session = session; timestamp = System.currentTimeMillis(); @@ -52,5 +56,6 @@ public static class TrustLevel { public byte[] verifySecureKey; public boolean keyChecked; public byte[] publicKey; + public HardwareReportRequest.HardwareInfo hardwareInfo; } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java index 520d6675..15667812 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java @@ -8,6 +8,7 @@ import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.provider.AuthProvider; +import pro.gravit.launchserver.auth.provider.AuthProviderDAOResult; import pro.gravit.launchserver.auth.provider.AuthProviderResult; import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.response.SimpleResponse; @@ -84,6 +85,10 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti clientData.username = result.playerProfile.username; else clientData.username = login; + if(aresult instanceof AuthProviderDAOResult) + { + clientData.daoObject = ((AuthProviderDAOResult) aresult).daoObject; + } result.accessToken = aresult.accessToken; result.permissions = clientData.permissions; if (getSession) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java index 46a5542a..1fd65dc0 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java @@ -3,6 +3,7 @@ import io.netty.channel.ChannelHandlerContext; import pro.gravit.launcher.events.request.JoinServerRequestEvent; import pro.gravit.launchserver.auth.AuthException; +import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler; import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.utils.HookException; @@ -27,6 +28,15 @@ public void execute(ChannelHandlerContext ctx, Client client) { boolean success; try { server.authHookManager.joinServerHook.hook(this, client); + if(server.config.protectHandler instanceof JoinServerProtectHandler) + { + success = ((JoinServerProtectHandler) server.config.protectHandler).onJoinServer(serverID, username, client); + if(!success) + { + sendResult(new JoinServerRequestEvent(false)); + return; + } + } if (client.auth == null) { LogHelper.warning("Client auth is null. Using default."); success = server.config.getAuthProviderPair().handler.joinServer(username, accessToken, serverID); @@ -34,7 +44,7 @@ public void execute(ChannelHandlerContext ctx, Client client) { if (LogHelper.isDebugEnabled()) { LogHelper.debug("joinServer: %s accessToken: %s serverID: %s", username, accessToken, serverID); } - } catch (AuthException | HookException e) { + } catch (AuthException | HookException | SecurityException e) { sendError(e.getMessage()); return; } catch (Exception e) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RegisterResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RegisterResponse.java index c17428b9..79503396 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RegisterResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RegisterResponse.java @@ -3,7 +3,6 @@ import io.netty.channel.ChannelHandlerContext; import pro.gravit.launcher.ClientPermissions; import pro.gravit.launchserver.dao.User; -import pro.gravit.launchserver.dao.impl.UserHibernateImpl; import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.response.SimpleResponse; @@ -11,7 +10,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import java.util.UUID; public class RegisterResponse extends SimpleResponse { public String login; @@ -37,12 +35,6 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { sendError("User already register"); return; } - UserHibernateImpl user = new UserHibernateImpl(); - user.username = login; - user.email = email; - user.setPassword(password); - user.uuid = UUID.randomUUID(); - server.config.dao.userDAO.save(user); } @Override diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java index c5414576..df1610e5 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java @@ -19,7 +19,12 @@ public String getType() { public void execute(ChannelHandlerContext ctx, Client client) throws Exception { if(server.config.protectHandler instanceof HardwareProtectHandler) { - ((HardwareProtectHandler) server.config.protectHandler).onHardwareReport(this, client); + try { + ((HardwareProtectHandler) server.config.protectHandler).onHardwareReport(this, client); + } catch (SecurityException e) + { + sendError(e.getMessage()); + } } else { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java index 8037a821..2365757a 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java @@ -39,6 +39,12 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { } client.trustLevel.keyChecked = true; client.trustLevel.publicKey = publicKey; - sendResult(secureProtectHandler.onSuccessVerify(client)); + try { + sendResult(secureProtectHandler.onSuccessVerify(client)); + } catch (SecurityException e) + { + sendError(e.getMessage()); + } + } } diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/VerifySecureLevelKeyRequestEvent.java b/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/VerifySecureLevelKeyRequestEvent.java index c6a63041..a2833837 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/VerifySecureLevelKeyRequestEvent.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/VerifySecureLevelKeyRequestEvent.java @@ -4,6 +4,7 @@ public class VerifySecureLevelKeyRequestEvent extends RequestEvent { public boolean needHardwareInfo; + public boolean onlyStatisticInfo; public VerifySecureLevelKeyRequestEvent() { } diff --git a/LauncherCore/src/main/java/pro/gravit/utils/Version.java b/LauncherCore/src/main/java/pro/gravit/utils/Version.java index 614cc940..bc7eac8d 100644 --- a/LauncherCore/src/main/java/pro/gravit/utils/Version.java +++ b/LauncherCore/src/main/java/pro/gravit/utils/Version.java @@ -6,7 +6,7 @@ public final class Version { public static final int MAJOR = 5; public static final int MINOR = 1; - public static final int PATCH = 5; + public static final int PATCH = 6; public static final int BUILD = 1; public static final Version.Type RELEASE = Type.STABLE; public final int major; diff --git a/README.md b/README.md index da2f30ef..8c4282c1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Modification of the launcher sashok724's v3 from Gravit [![Build Status](https://travis-ci.com/GravitLauncher/Launcher.svg?branch=master)](https://travis-ci.com/GravitLauncher/Launcher) -* [Discord channel](https://discord.gg/XTAZevy) +* [Discord channel](https://discord.gg/RM7yjws) * [See license](LICENSE) * [See code of conduct](CODE_OF_CONDUCT.md) * [WIKI](https://launcher.gravit.pro) diff --git a/build.gradle b/build.gradle index b507c090..61f01261 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ id 'org.openjfx.javafxplugin' version '0.0.8' apply false } group = 'pro.gravit.launcher' -version = '5.1.5' +version = '5.1.6' apply from: 'props.gradle' diff --git a/modules b/modules index 04984c3c..5a9d5d27 160000 --- a/modules +++ b/modules @@ -1 +1 @@ -Subproject commit 04984c3c75c484671e5b286527403ab55da28a01 +Subproject commit 5a9d5d27ea3113bd6f2b899b331dddc61b3b1588