From 81be9d21debe42349ae992cca9dd41b11ad9a179 Mon Sep 17 00:00:00 2001
From: Gravita <gravita@gravit.pro>
Date: Tue, 22 Jun 2021 11:13:12 +0700
Subject: [PATCH] [FIX] MySQLCoreProvider HWID fix

---
 .../auth/core/AuthCoreProvider.java           | 190 +++++++++---------
 .../auth/core/MySQLCoreProvider.java          |  47 +++--
 .../command/service/ClientsCommand.java       |   2 +-
 .../gravit/launcher/ClientPermissions.java    |   5 +-
 .../request/secure/HardwareReportRequest.java |   5 +-
 modules                                       |   2 +-
 6 files changed, 129 insertions(+), 122 deletions(-)

diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/AuthCoreProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/AuthCoreProvider.java
index 92b16aeb..e9860fd7 100644
--- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/AuthCoreProvider.java
+++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/AuthCoreProvider.java
@@ -177,107 +177,109 @@ public void invoke(String... args) throws Exception {
         }
         {
             var instance = isSupport(AuthSupportHardware.class);
-            map.put("gethardwarebyid", new SubCommand("[id]", "get hardware by id") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    UserHardware hardware = instance.getHardwareInfoById(args[0]);
-                    if (hardware == null) {
-                        logger.info("UserHardware {} not found", args[0]);
-                    } else {
-                        logger.info("UserHardware: {}", hardware);
+            if (instance != null) {
+                map.put("gethardwarebyid", new SubCommand("[id]", "get hardware by id") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        UserHardware hardware = instance.getHardwareInfoById(args[0]);
+                        if (hardware == null) {
+                            logger.info("UserHardware {} not found", args[0]);
+                        } else {
+                            logger.info("UserHardware: {}", hardware);
+                        }
                     }
-                }
-            });
-            map.put("gethardwarebydata", new SubCommand("[json data]", "fulltext search hardware by json data(slow)") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    UserHardware hardware = instance.getHardwareInfoByData(Launcher.gsonManager.gson.fromJson(args[0], HardwareReportRequest.HardwareInfo.class));
-                    if (hardware == null) {
-                        logger.info("UserHardware {} not found", args[0]);
-                    } else {
-                        logger.info("UserHardware: {}", hardware);
+                });
+                map.put("gethardwarebydata", new SubCommand("[json data]", "fulltext search hardware by json data(slow)") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        UserHardware hardware = instance.getHardwareInfoByData(Launcher.gsonManager.gson.fromJson(args[0], HardwareReportRequest.HardwareInfo.class));
+                        if (hardware == null) {
+                            logger.info("UserHardware {} not found", args[0]);
+                        } else {
+                            logger.info("UserHardware: {}", hardware);
+                        }
                     }
-                }
-            });
-            map.put("getuserhardware", new SubCommand("[username]", "get hardware by username") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    User user = getUserByUUID(UUID.fromString(args[0]));
-                    if (user == null) {
-                        logger.info("User {} not found", args[0]);
+                });
+                map.put("getuserhardware", new SubCommand("[username]", "get hardware by username") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        User user = getUserByUUID(UUID.fromString(args[0]));
+                        if (user == null) {
+                            logger.info("User {} not found", args[0]);
+                        }
+                        UserSupportHardware hardware = instance.fetchUserHardware(user);
+                        if (hardware == null) {
+                            logger.error("Method fetchUserHardware return null");
+                            return;
+                        }
+                        UserHardware userHardware = hardware.getHardware();
+                        if (userHardware == null) {
+                            logger.info("User {} not contains hardware info", args[0]);
+                        } else {
+                            logger.info("UserHardware: {}", userHardware);
+                            logger.info("HardwareInfo(JSON): {}", Launcher.gsonManager.gson.toJson(userHardware.getHardwareInfo()));
+                        }
                     }
-                    UserSupportHardware hardware = instance.fetchUserHardware(user);
-                    if (hardware == null) {
-                        logger.error("Method fetchUserHardware return null");
-                        return;
+                });
+                map.put("findmulti", new SubCommand("[hardware id]", "get all users in one hardware id") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        UserHardware hardware = instance.getHardwareInfoById(args[0]);
+                        if (hardware == null) {
+                            logger.info("UserHardware {} not found", args[0]);
+                            return;
+                        }
+                        Iterable<User> users = instance.getUsersByHardwareInfo(hardware);
+                        for (User user : users) {
+                            logger.info("User {}", user);
+                        }
                     }
-                    UserHardware userHardware = hardware.getHardware();
-                    if (userHardware == null) {
-                        logger.info("User {} not contains hardware info", args[0]);
-                    } else {
-                        logger.info("UserHardware: {}", userHardware);
-                        logger.info("HardwareInfo(JSON): {}", Launcher.gsonManager.gson.toJson(userHardware.getHardwareInfo()));
+                });
+                map.put("banhardware", new SubCommand("[hardware id]", "ban hardware by id") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        UserHardware hardware = instance.getHardwareInfoById(args[0]);
+                        if (hardware == null) {
+                            logger.info("UserHardware {} not found", args[0]);
+                            return;
+                        }
+                        instance.banHardware(hardware);
+                        logger.info("UserHardware {} banned", args[0]);
                     }
-                }
-            });
-            map.put("findmulti", new SubCommand("[hardware id]", "get all users in one hardware id") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    UserHardware hardware = instance.getHardwareInfoById(args[0]);
-                    if (hardware == null) {
-                        logger.info("UserHardware {} not found", args[0]);
-                        return;
+                });
+                map.put("unbanhardware", new SubCommand("[hardware id]", "ban hardware by id") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 1);
+                        UserHardware hardware = instance.getHardwareInfoById(args[0]);
+                        if (hardware == null) {
+                            logger.info("UserHardware {} not found", args[0]);
+                            return;
+                        }
+                        instance.unbanHardware(hardware);
+                        logger.info("UserHardware {} unbanned", args[0]);
                     }
-                    Iterable<User> users = instance.getUsersByHardwareInfo(hardware);
-                    for (User user : users) {
-                        logger.info("User {}", user.getUsername());
+                });
+                map.put("comparehardware", new SubCommand("[json data 1] [json data 2]", "compare hardware info") {
+                    @Override
+                    public void invoke(String... args) throws Exception {
+                        verifyArgs(args, 2);
+                        HardwareReportRequest.HardwareInfo hardware1 = Launcher.gsonManager.gson.fromJson(args[0], HardwareReportRequest.HardwareInfo.class);
+                        HardwareReportRequest.HardwareInfo hardware2 = Launcher.gsonManager.gson.fromJson(args[1], HardwareReportRequest.HardwareInfo.class);
+                        HWIDProvider.HardwareInfoCompareResult result = instance.compareHardwareInfo(hardware1, hardware2);
+                        if (result == null) {
+                            logger.error("Method compareHardwareInfo return null");
+                            return;
+                        }
+                        logger.info("Compare result: {} Spoof: {} first {} second", result.compareLevel, result.firstSpoofingLevel, result.secondSpoofingLevel);
                     }
-                }
-            });
-            map.put("banhardware", new SubCommand("[hardware id]", "ban hardware by id") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    UserHardware hardware = instance.getHardwareInfoById(args[0]);
-                    if (hardware == null) {
-                        logger.info("UserHardware {} not found", args[0]);
-                        return;
-                    }
-                    instance.banHardware(hardware);
-                    logger.info("UserHardware {} banned", args[0]);
-                }
-            });
-            map.put("unbanhardware", new SubCommand("[hardware id]", "ban hardware by id") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 1);
-                    UserHardware hardware = instance.getHardwareInfoById(args[0]);
-                    if (hardware == null) {
-                        logger.info("UserHardware {} not found", args[0]);
-                        return;
-                    }
-                    instance.unbanHardware(hardware);
-                    logger.info("UserHardware {} unbanned", args[0]);
-                }
-            });
-            map.put("comparehardware", new SubCommand("[json data 1] [json data 2]", "compare hardware info") {
-                @Override
-                public void invoke(String... args) throws Exception {
-                    verifyArgs(args, 2);
-                    HardwareReportRequest.HardwareInfo hardware1 = Launcher.gsonManager.gson.fromJson(args[0], HardwareReportRequest.HardwareInfo.class);
-                    HardwareReportRequest.HardwareInfo hardware2 = Launcher.gsonManager.gson.fromJson(args[1], HardwareReportRequest.HardwareInfo.class);
-                    HWIDProvider.HardwareInfoCompareResult result = instance.compareHardwareInfo(hardware1, hardware2);
-                    if (result == null) {
-                        logger.error("Method compareHardwareInfo return null");
-                        return;
-                    }
-                    logger.info("Compare result: {} Spoof: {} first {} second", result.compareLevel, result.firstSpoofingLevel, result.secondSpoofingLevel);
-                }
-            });
+                });
+            }
         }
         return map;
     }
diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/MySQLCoreProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/MySQLCoreProvider.java
index f473ad74..1f896b95 100644
--- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/MySQLCoreProvider.java
+++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/core/MySQLCoreProvider.java
@@ -22,7 +22,7 @@
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.sql.*;
-import java.util.Arrays;
+import java.util.Base64;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.UUID;
@@ -61,11 +61,11 @@ public class MySQLCoreProvider extends AuthCoreProvider implements AuthSupportHa
     private transient String updateAuthSQL;
     private transient String updateServerIDSQL;
 
-    public String defaultQueryByUUIDSQL;
-    public String defaultQueryByUsernameSQL;
-    public String defaultQueryByLoginSQL;
-    public String defaultUpdateAuthSQL;
-    public String defaultUpdateServerIdSQL;
+    public String customQueryByUUIDSQL;
+    public String customQueryByUsernameSQL;
+    public String customQueryByLoginSQL;
+    public String customUpdateAuthSQL;
+    public String customUpdateServerIdSQL;
 
     @Override
     public User getUserByUsername(String username) {
@@ -143,23 +143,26 @@ public void init(LaunchServer server) {
         if (table == null) logger.error("table cannot be null");
         // Prepare SQL queries
         String userInfoCols = String.format("%s, %s, %s, %s, %s, %s", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn, hardwareIdColumn);
-        queryByUUIDSQL = defaultQueryByUUIDSQL != null ? defaultQueryByUUIDSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1", userInfoCols,
+        queryByUUIDSQL = customQueryByUUIDSQL != null ? customQueryByUUIDSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1", userInfoCols,
                 table, uuidColumn);
-        queryByUsernameSQL = defaultQueryByUsernameSQL != null ? defaultQueryByUsernameSQL :  String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1",
+        queryByUsernameSQL = customQueryByUsernameSQL != null ? customQueryByUsernameSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1",
                 userInfoCols, table, usernameColumn);
-        queryByLoginSQL = defaultQueryByLoginSQL != null ? defaultQueryByLoginSQL : queryByUsernameSQL;
+        queryByLoginSQL = customQueryByLoginSQL != null ? customQueryByLoginSQL : queryByUsernameSQL;
 
-        updateAuthSQL = defaultUpdateAuthSQL != null ? defaultUpdateAuthSQL : String.format("UPDATE %s SET %s=?, %s=NULL WHERE %s=? LIMIT 1",
+        updateAuthSQL = customUpdateAuthSQL != null ? customUpdateAuthSQL : String.format("UPDATE %s SET %s=?, %s=NULL WHERE %s=? LIMIT 1",
                 table, accessTokenColumn, serverIDColumn, uuidColumn);
-        updateServerIDSQL = defaultUpdateServerIdSQL != null ? defaultUpdateServerIdSQL : String.format("UPDATE %s SET %s=? WHERE %s=? LIMIT 1",
+        updateServerIDSQL = customUpdateServerIdSQL != null ? customUpdateServerIdSQL : String.format("UPDATE %s SET %s=? WHERE %s=? LIMIT 1",
                 table, serverIDColumn, uuidColumn);
-        String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned";
+        String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
         if(sqlFindHardwareByPublicKey == null) sqlFindHardwareByPublicKey = String.format("SELECT %s FROM %s WHERE `publicKey` = ?", hardwareInfoCols, tableHWID);
         if(sqlFindHardwareById == null) sqlFindHardwareById = String.format("SELECT %s FROM %s WHERE `id` = ?", hardwareInfoCols, tableHWID);
         if(sqlUsersByHwidId == null) sqlUsersByHwidId = String.format("SELECT %s FROM %s WHERE `%s` = ?", userInfoCols, table, hardwareIdColumn);
-        if(sqlFindHardwareByData == null) sqlFindHardwareByData = String.format("SELECT %s FROM %s", hardwareInfoCols, tableHWID);
-        if(sqlCreateHardware == null) sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `battery`, `graphicCard`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID);
-        if(sqlCreateHWIDLog == null) sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog);
+        if (sqlFindHardwareByData == null)
+            sqlFindHardwareByData = String.format("SELECT %s FROM %s", hardwareInfoCols, tableHWID);
+        if (sqlCreateHardware == null)
+            sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `graphicCard`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID);
+        if (sqlCreateHWIDLog == null)
+            sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog);
         if(sqlUpdateHardwarePublicKey == null) sqlUpdateHardwarePublicKey = String.format("UPDATE %s SET `publicKey` = ? WHERE `id` = ?", tableHWID);
         sqlUpdateHardwareBanned = String.format("UPDATE %s SET `banned` = ? WHERE `id` = ?", tableHWID);
         sqlUpdateUsers = String.format("UPDATE %s SET `%s` = ? WHERE `%s` = ?", table, hardwareIdColumn, uuidColumn);
@@ -256,7 +259,7 @@ public UserHardware getHardwareInfoByPublicKey(byte[] publicKey) {
                 }
             }
         } catch (SQLException | IOException throwables) {
-            logger.error(throwables);
+            logger.error("SQL Error", throwables);
             return null;
         }
     }
@@ -275,7 +278,7 @@ public UserHardware getHardwareInfoByData(HardwareReportRequest.HardwareInfo inf
                 }
             }
         } catch (SQLException | IOException throwables) {
-            logger.error(throwables);
+            logger.error("SQL Error", throwables);
         }
         return null;
     }
@@ -293,7 +296,7 @@ public UserHardware getHardwareInfoById(String id) {
                 }
             }
         } catch (SQLException | IOException throwables) {
-            logger.error(throwables);
+            logger.error("SQL Error", throwables);
             return null;
         }
     }
@@ -323,7 +326,7 @@ public UserHardware createHardwareInfo(HardwareReportRequest.HardwareInfo hardwa
             }
             return null;
         } catch (SQLException throwables) {
-            logger.error(throwables);
+            logger.error("SQL Error", throwables);
             return null;
         }
     }
@@ -337,7 +340,7 @@ public void connectUserAndHardware(User user, UserHardware hardware) {
         try (Connection connection = mySQLHolder.getConnection()) {
             setUserHardwareId(connection, user.getUUID(), mySQLUserHardware.id);
         } catch (SQLException throwables) {
-            logger.error(throwables);
+            logger.error("SQL Error", throwables);
         }
     }
 
@@ -363,7 +366,7 @@ public Iterable<User> getUsersByHardwareInfo(UserHardware hardware) {
             s.setLong(1, Long.parseLong(hardware.getId()));
             s.setQueryTimeout(MySQLSourceConfig.TIMEOUT);
             try (ResultSet set = s.executeQuery()) {
-                while (set.next()) {
+                while (!set.isLast()) {
                     users.add(constructUser(set));
                 }
             }
@@ -503,7 +506,7 @@ public boolean isBanned() {
         public String toString() {
             return "MySQLUserHardware{" +
                     "hardwareInfo=" + hardwareInfo +
-                    ", publicKey=" + (publicKey == null ? null : SecurityHelper.toHex(publicKey)) +
+                    ", publicKey=" + (publicKey == null ? null : new String(Base64.getEncoder().encode(publicKey))) +
                     ", id=" + id +
                     ", banned=" + banned +
                     '}';
diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/service/ClientsCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/service/ClientsCommand.java
index 6c9b9d15..1e6ab17a 100644
--- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/service/ClientsCommand.java
+++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/service/ClientsCommand.java
@@ -48,7 +48,7 @@ public void invoke(String... args) {
                 logger.info("Data: checkSign {} | auth_id {}", client.checkSign ? "true" : "false",
                         client.auth_id);
                 if (client.trustLevel != null) {
-                    logger.info("trustLevel | key {} | pubkey {}", client.trustLevel.keyChecked ? "checked" : "unchecked", client.trustLevel.publicKey == null ? "null" : Base64.getEncoder().encode(client.trustLevel.publicKey));
+                    logger.info("trustLevel | key {} | pubkey {}", client.trustLevel.keyChecked ? "checked" : "unchecked", client.trustLevel.publicKey == null ? "null" : new String(Base64.getEncoder().encode(client.trustLevel.publicKey)));
                 }
                 logger.info("Permissions: {} (permissions {} | flags {})", client.permissions == null ? "null" : client.permissions.toString(), client.permissions == null ? 0 : client.permissions.permissions, client.permissions == null ? 0 : client.permissions.flags);
             }
diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/ClientPermissions.java b/LauncherAPI/src/main/java/pro/gravit/launcher/ClientPermissions.java
index 6ac38e6f..9b063f55 100644
--- a/LauncherAPI/src/main/java/pro/gravit/launcher/ClientPermissions.java
+++ b/LauncherAPI/src/main/java/pro/gravit/launcher/ClientPermissions.java
@@ -84,7 +84,10 @@ public final void setFlag(long mask, boolean value) {
 
     @Override
     public String toString() {
-        return String.format("permissions %d | flags %d", permissions, flags);
+        return "ClientPermissions{" +
+                "permissions=" + permissions +
+                ", flags=" + flags +
+                '}';
     }
 
     public enum PermissionConsts {
diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/request/secure/HardwareReportRequest.java b/LauncherAPI/src/main/java/pro/gravit/launcher/request/secure/HardwareReportRequest.java
index 5a7bf0ab..1b7e2cb9 100644
--- a/LauncherAPI/src/main/java/pro/gravit/launcher/request/secure/HardwareReportRequest.java
+++ b/LauncherAPI/src/main/java/pro/gravit/launcher/request/secure/HardwareReportRequest.java
@@ -2,9 +2,8 @@
 
 import pro.gravit.launcher.events.request.HardwareReportRequestEvent;
 import pro.gravit.launcher.request.Request;
-import pro.gravit.utils.helper.SecurityHelper;
 
-import java.util.Arrays;
+import java.util.Base64;
 
 public class HardwareReportRequest extends Request<HardwareReportRequestEvent> {
     public HardwareInfo hardware;
@@ -36,7 +35,7 @@ public String toString() {
                     ", processorMaxFreq=" + processorMaxFreq +
                     ", battery=" + battery +
                     ", hwDiskId='" + hwDiskId + '\'' +
-                    ", displayId=" + (displayId == null ? null : SecurityHelper.toHex(displayId)) +
+                    ", displayId=" + (displayId == null ? null : new String(Base64.getEncoder().encode(displayId))) +
                     ", baseboardSerialNumber='" + baseboardSerialNumber + '\'' +
                     ", graphicCard='" + graphicCard + '\'' +
                     '}';
diff --git a/modules b/modules
index e8bc82be..0472083e 160000
--- a/modules
+++ b/modules
@@ -1 +1 @@
-Subproject commit e8bc82be4d0fb86041fe464cad32314430552386
+Subproject commit 0472083e090ff249cb6795d209c34ad79f391f7a