Exemple #1
0
        private void ProcessClientMessage(AsynchronousSocket socket)
        {
            // Get the encrypted byte array from the client
            byte[] encryptedMessage = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            OnDebug("Received encrypted client message, length = " +
                    socket.ReceiveBufferLength);

            // Start file receive
            if (isReceivingCrashReport && !socket.IsReceivingFile)
            {
                OnDebug("Starting receive of crash report");
                receiveStream = new MemoryStream();
                socket.BeginFileReceive(receiveStream);
            }

            // FileReceive In-Progress
            if (socket.IsReceivingFile)
            {
                ProcessFileReceive(socket, encryptedMessage);
                return;
            }

            // Get the decrypted message
            byte[] message = srpServer.Decrypt(encryptedMessage);
            ProcessDecryptedClientMessages(socket, message);
        }
Exemple #2
0
        public AccountOpResult ChangePassword(uint accountId, string newPassword)
        {
            string username;

            if (!GetName(accountId, out username))
            {
                return(AccountOpResult.NameNotExist);                          // account doesn't exist
            }
            if (newPassword.Length > MaxAccountLength)
            {
                return(AccountOpResult.PassTooLong);
            }

            (byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(username, newPassword);

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON);

            stmt.AddValue(0, salt);
            stmt.AddValue(1, verifier);
            stmt.AddValue(2, accountId);
            DB.Login.Execute(stmt);

            {
                stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY);
                stmt.AddValue(0, CalculateShaPassHash(username, newPassword));
                stmt.AddValue(1, accountId);
                DB.Login.Execute(stmt);
            }

            return(AccountOpResult.Ok);
        }
Exemple #3
0
 public void SetScanCodeData(byte[] scanCodeData)
 {
     byte[] hashedScanCode = null;
     if (scanCodeData != null)
     {
         hashedScanCode = SRP6.Sha1Hash(scanCodeData);
     }
     if ((hashedScanCode != null) && (hashedScanCode.Length != 520))
     {
         byte[] originalScanCode = hashedScanCode;
         hashedScanCode = new byte[520];
         for (int i = 0; i < 520; i++)
         {
             if (i < originalScanCode.Length)
             {
                 hashedScanCode[i] = originalScanCode[i];
             }
             else
             {
                 hashedScanCode[i] = 0;
             }
         }
     }
     ScanCodeData = hashedScanCode;
 }
Exemple #4
0
        private void InitializeSrpServer(AsynchronousSocket socket)
        {
            byte[] identityHash = SRP6.SubArray(socket.ReceiveBuffer, 0, socket.ReceiveBufferLength);
            OnDebug("IdentityHash = " + SRP6.BytesToHex(identityHash));

            // Verify that the server knows this identity before proceeding
            if (!OnAuthenticationRequest(socket, identityHash))
            {
                return;
            }

            // Server generates (and sends to client) public-key, scrambler, and salt
            srpServer = new SRP6(identityHash, Modulus, 0x07, 256, 128);
            socket.Step++;

            byte[] salt        = srpServer.Salt.ToUnsignedByteArray();
            byte[] pubKey      = srpServer.PublicKey.ToUnsignedByteArray();
            byte[] scrambler   = srpServer.Scrambler.ToUnsignedByteArray();
            byte[] replyPacket = SRP6.ConcatArray(salt, pubKey, scrambler);

            OnDebug("Server->Salt, PublicKey, and Scrambler");
            OnDebug("Salt = " + srpServer.GetSalt());
            OnDebug("PublicKey = " + srpServer.GetPublicKey());
            OnDebug("Scrambler = " + srpServer.GetScrambler());
            socket.Send(replyPacket, 0, replyPacket.Length);
        }
Exemple #5
0
        private void ServerGreetingReceived(AsynchronousSocket socket)
        {
            if (socket.ReceiveBufferLength != 80)
            {
                OnDebug("Server did not send a proper greeting");
                socket.Disconnect();
                return;
            }
            string salt      = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 0, 32));
            string pubKey    = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 32, 32));
            string scrambler = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 64, 16));

            // Setup the SessionKey
            srpClient = new SRP6(IdentityHash, Modulus, 0x07, salt);
            srpClient.SetSessionKey(pubKey, scrambler);
            OnDebug("Salt = " + salt);
            OnDebug("Server's PublicKey = " + pubKey);
            OnDebug("Scrambler = " + scrambler);

            step++;

            // Send my public key to the server
            OnDebug("Client->PublicKey");
            OnDebug("PublicKey = " + srpClient.GetPublicKey());
            byte[] reply = srpClient.PublicKey.ToUnsignedByteArray();
            socket.Send(reply, 0, reply.Length);
            OnDebug("SessionKey = " + srpClient.GetSessionKey());
        }
Exemple #6
0
        private void ProcessServerMessages(AsynchronousSocket socket)
        {
            // Get the encrypted byte array from the client
            byte[] encryptedMessage = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);

            // Start file receive
            if (isReceivingUpdate && !socket.IsReceivingFile)
            {
                receiveStream = new MemoryStream();
                socket.BeginFileReceive(receiveStream);
            }

            // FileReceive In-Progress
            if (socket.IsReceivingFile)
            {
                ProcessFileReceive(socket, encryptedMessage);
                return;
            }

            // Get the decrypted message
            byte[] message = srpClient.Decrypt(encryptedMessage);
            ProcessDecryptedServerMessages(socket, message);
        }
Exemple #7
0
        /// <summary>
        /// Get an entry from the Employee table, for the matching scanCode
        /// </summary>
        public static Employee GetFromScanCode(string scanCode)
        {
#if DEBUG
            if (String.IsNullOrEmpty(scanCode))
            {
                IEnumerable <Employee> employees = Employee.GetAll();
                foreach (Employee employee in employees)
                {
                    if (employee.ScanCodeData == null)
                    {
                        return(employee);
                    }
                }
                return(null);
            }
#endif
            if (!String.IsNullOrEmpty(scanCode))
            {
                byte[] bytes       = Encoding.UTF8.GetBytes(scanCode);
                byte[] hashedBytes = SRP6.Sha1Hash(bytes);
                IEnumerable <Employee> employees = Employee.GetAll();
                foreach (Employee employee in employees)
                {
                    if (ScanCodesMatch(employee.ScanCodeData, hashedBytes))
                    {
                        return(employee);
                    }
                }
            }
            return(null);
        }
Exemple #8
0
 /// <summary>
 /// Socket constructor for crash reports
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <param name="ex"></param>
 public Srp6ClientSocket(string username, string password, Exception ex)
 {
     InitializeDefaultProperties();
     IdentityHash       = SRP6.GenerateIdentityHash(username, password);
     CrashException     = ex;
     UpdateFileLocation = null;
 }
Exemple #9
0
        public bool CheckPassword(uint accountId, string password)
        {
            string username;

            if (!GetName(accountId, out username))
            {
                return(false);
            }

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_CHECK_PASSWORD);

            stmt.AddValue(0, accountId);
            SQLResult result = DB.Login.Query(stmt);

            if (!result.IsEmpty())
            {
                byte[] salt     = result.Read <byte[]>(0);
                byte[] verifier = result.Read <byte[]>(1);
                if (SRP6.CheckLogin(username, password, salt, verifier))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #10
0
        public static Employee Add(int personId, Permissions[] permissions,
                                   byte[] scanCode, string federalTaxId)
        {
            byte[]   permissionBytes = GetPermissionBytes(permissions);
            byte[]   hashedScanCode  = SRP6.Sha1Hash(scanCode);
            Employee result          = null;

            SqlConnection cn = GetConnection();

            using (SqlCommand sqlCmd = new SqlCommand("AddEmployee", cn))
            {
                sqlCmd.CommandType = CommandType.StoredProcedure;
                BuildSqlParameter(sqlCmd, "@EmployeePersonId", SqlDbType.Int, personId);
                BuildSqlParameter(sqlCmd, "@EmployeeScanCode", SqlDbType.Binary, hashedScanCode);
                BuildSqlParameter(sqlCmd, "@EmployeePermissionsCode", SqlDbType.Binary, permissionBytes);
                BuildSqlParameter(sqlCmd, "@EmployeeFederalId", SqlDbType.Text, federalTaxId);
                BuildSqlParameter(sqlCmd, "@EmployeeId", SqlDbType.Int, ParameterDirection.ReturnValue);
                if (sqlCmd.ExecuteNonQuery() > 0)
                {
                    result = new Employee(Convert.ToInt32(sqlCmd.Parameters["@EmployeeId"].Value),
                                          personId, hashedScanCode, permissionBytes, federalTaxId,
                                          false, false);
                }
            }
            FinishedWithConnection(cn);
            return(result);
        }
Exemple #11
0
        private void ProcessDecryptedClientMessages(AsynchronousSocket socket, byte[] message)
        {
            string command = ASCIIEncoding.ASCII.GetString(message, 0, (message.Length > 128 ? 128 : message.Length));

            OnDebug("Client Message \"" + SRP6.ArrayToString(message, 0, message.Length) + "\"");

            if (command.StartsWith("SUBMIT_CRASH")) // Client wants to send us a crash report
            {
                OnDebug("Beginning submitting Crash Report");
                string   strMessage = SRP6.ArrayToString(message, 13, message.Length - 13);
                string[] strTokens  = strMessage.Split(' ');
                try
                {
                    crashReportSize = Convert.ToInt32(strTokens[0]);
                }
                catch { }
                try
                {
                    crashReportEncryptedSize = Convert.ToInt32(strTokens[1]);
                }
                catch { }

                if ((crashReportSize > 0) && (crashReportEncryptedSize >= crashReportSize))
                {
                    isReceivingCrashReport = true;
                    // We know what to expect now, send "PROCEED" message.
                    srpServer.EncryptAndSend(socket, "PROCEED");
                }
                else
                {
                    OnDebug(
                        "Failed to get valid transfer information from the client");
                }
            }
            else if (command.StartsWith("VERSION"))
            {
                srpServer.EncryptAndSend(socket, TemposVersionString);
            }
            else if (command.StartsWith("SEND"))
            {
                socket.SendStream          = new FileStream(UpdateFileLocation, FileMode.Open, FileAccess.Read);
                socket.EncryptedSendStream = srpServer.Encrypt(socket.SendStream);
                srpServer.EncryptAndSend(socket, socket.SendStream.Length.ToString() + " " +
                                         socket.EncryptedSendStream.Length.ToString());
            }
            else if (command.StartsWith("CONTINUE"))
            {
                if (socket.EncryptedSendStream != null)
                {
                    socket.SendFile(socket.EncryptedSendStream);
                }
            }
            else
            {
                socket.Disconnect();
                OnDebug("Unhandled: " + command);
            }
        }
Exemple #12
0
 private byte[] GetIdentityHash()
 {
     if (SelectedCustomer == null)
     {
         return(new byte[20]);
     }
     return(SRP6.GenerateIdentityHash(SelectedCustomer.BusinessName,
                                      textBoxSerialNumber.Text));
 }
Exemple #13
0
        bool CheckAccessLevelAndPassword(string email, string password)
        {
            //"SELECT a.id, a.username FROM account a LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id WHERE ba.email = ?"
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_GAME_ACCOUNT_LIST);

            stmt.AddValue(0, email);
            SQLResult result = DB.Login.Query(stmt);

            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.CommandsRA, $"User {email} does not exist in database");
                return(false);
            }

            uint   accountId = result.Read <uint>(0);
            string username  = result.Read <string>(1);

            stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_ACCESS_BY_ID);
            stmt.AddValue(0, accountId);
            result = DB.Login.Query(stmt);
            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.CommandsRA, $"User {email} has no privilege to login");
                return(false);
            }

            //"SELECT SecurityLevel, RealmID FROM account_access WHERE AccountID = ? and (RealmID = ? OR RealmID = -1) ORDER BY SecurityLevel desc");
            if (result.Read <byte>(0) < ConfigMgr.GetDefaultValue("Ra.MinLevel", (byte)AccountTypes.Administrator))
            {
                Log.outInfo(LogFilter.CommandsRA, $"User {email} has no privilege to login");
                return(false);
            }
            else if (result.Read <int>(1) != -1)
            {
                Log.outInfo(LogFilter.CommandsRA, $"User {email} has to be assigned on all realms (with RealmID = '-1')");
                return(false);
            }

            stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_CHECK_PASSWORD);
            stmt.AddValue(0, accountId);
            result = DB.Login.Query(stmt);
            if (!result.IsEmpty())
            {
                var salt     = result.Read <byte[]>(0);
                var verifier = result.Read <byte[]>(1);

                if (SRP6.CheckLogin(username, password, salt, verifier))
                {
                    return(true);
                }
            }

            Log.outInfo(LogFilter.CommandsRA, $"Wrong password for user: {email}");
            return(false);
        }
Exemple #14
0
 public bool CheckPassword(string scanCode)
 {
     byte[] bytes       = Encoding.UTF8.GetBytes(scanCode);
     byte[] hashedBytes = SRP6.Sha1Hash(bytes);
     for (int i = 0; i < hashedBytes.Length; i++)
     {
         if (hashedBytes[i] != ScanCodeData[i])
         {
             return(false);
         }
     }
     return(true);
 }
Exemple #15
0
        void socket_Connected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (Connected != null)
            {
                Connected.Invoke(this, new EventArgs());
            }

            // Send the server my identity hash
            socket.Send(IdentityHash, 0, IdentityHash.Length);
            OnDebug("Client->IdentityHash");
            OnDebug("IndetityHash = " + SRP6.BytesToHex(IdentityHash));
        }
Exemple #16
0
        private void ServerReadyReceived(AsynchronousSocket socket)
        {
            byte[] message = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            string strMessage = SRP6.ArrayToString(message, 0, message.Length);

            // Server and client are now both ready for encrypted communications
            if (strMessage.Equals("READY"))
            {
                OnDebug("Received \"READY\" from server");
                step++;
                if (Authenticated != null)
                {
                    Authenticated.Invoke(this, new EventArgs());
                }

                if (crashReportOnly)
                {
                    // Request to send a crash report to the server
                    OnDebug("Telling server we want to upload a crash report");
                    try
                    {
                        byte[] serializedObject = CrashException.SerializeObject();
                        socket.SendStream          = new MemoryStream(serializedObject);
                        socket.EncryptedSendStream = srpClient.Encrypt(socket.SendStream);
                        srpClient.EncryptAndSend(socket, "SUBMIT_CRASH " +
                                                 socket.SendStream.Length + " " +
                                                 socket.EncryptedSendStream.Length);
                    }
                    catch (Exception ex)
                    {
                        OnDebug("Exception: " + ex.Message);
                    }
                }
                else
                {
                    // Request the current version
                    OnDebug("Sending version-check request to server");
                    isCheckingVersion = true;
                    srpClient.EncryptAndSend(socket, "VERSION");
                }
            }
            else
            {
                OnDebug("Authentication Failed");
                socket.Disconnect();
            }
        }
Exemple #17
0
        private void ProcessClientsPublicKey(AsynchronousSocket socket)
        {
            byte[] pubKey = SRP6.SubArray(socket.ReceiveBuffer, 0, socket.ReceiveBufferLength);

            string pubKeyString = SRP6.BytesToHex(pubKey);

            srpServer.SetSessionKey(pubKeyString);

            socket.SessionKey = srpServer.SessionKey.ToUnsignedByteArray();
            OnDebug("Client's PublicKey = " + pubKeyString);
            OnDebug("SessionKey = " + srpServer.GetSessionKey());
            socket.Step++;

            // From this point on, both client and server use encrypted communications
            OnDebug("Sending READY to client");
            socket.Send("READY");
        }
Exemple #18
0
        public static bool Create(string[] args, CommandGroup command)
        {
            if (args.Length < 2)
            {
                return(false);
            }

            var accountName = args[0].ToUpper();
            var password    = args[1];

            if (accountName == string.Empty || password == string.Empty)
            {
                return(false);
            }

            if (!accountName.Contains("@"))
            {
                return(command.SendErrorMessage("Account name requires an email address"));
            }

            if (accountName.Length > 16)
            {
                return(command.SendErrorMessage(CypherStrings.TooLongName));
            }

            PreparedStatement stmt = DB.Auth.GetPreparedStatement(LoginStatements.Get_AccountIDByUsername);

            stmt.AddValue(0, accountName);
            SQLResult result = DB.Auth.Select(stmt);

            if (result.Count != 0)
            {
                return(command.SendSysMessage(CypherStrings.AccountAlreadyExist, accountName));
            }

            stmt = DB.Auth.GetPreparedStatement(LoginStatements.Ins_Account);
            stmt.AddValue(0, accountName);
            stmt.AddValue(1, SRP6.GenerateCredentialsHash(accountName, password).ToHexString());
            DB.Auth.Execute(stmt);

            stmt = DB.Auth.GetPreparedStatement(LoginStatements.Ins_RealmCharactersInit);
            DB.Auth.Execute(stmt);

            return(command.SendSysMessage(CypherStrings.AccountCreated, accountName));
        }
Exemple #19
0
        public AccountOpResult ChangeUsername(uint accountId, string newUsername, string newPassword)
        {
            // Check if accounts exists
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_BY_ID);

            stmt.AddValue(0, accountId);
            SQLResult result = DB.Login.Query(stmt);

            if (result.IsEmpty())
            {
                return(AccountOpResult.NameNotExist);
            }

            if (newUsername.Length > MaxAccountLength)
            {
                return(AccountOpResult.NameTooLong);
            }

            if (newPassword.Length > MaxAccountLength)
            {
                return(AccountOpResult.PassTooLong);
            }

            stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_USERNAME);
            stmt.AddValue(0, newUsername);
            stmt.AddValue(1, accountId);
            DB.Login.Execute(stmt);

            (byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(newUsername, newPassword);
            stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON);
            stmt.AddValue(0, salt);
            stmt.AddValue(1, verifier);
            stmt.AddValue(2, accountId);
            DB.Login.Execute(stmt);

            {
                stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY);
                stmt.AddValue(0, CalculateShaPassHash(newUsername, newPassword));
                stmt.AddValue(1, accountId);
                DB.Login.Execute(stmt);
            }

            return(AccountOpResult.Ok);
        }
Exemple #20
0
        public AccountOpResult CreateAccount(string username, string password, string email = "", uint bnetAccountId = 0, byte bnetIndex = 0)
        {
            if (username.Length > MaxAccountLength)
            {
                return(AccountOpResult.NameTooLong);
            }

            if (password.Length > MaxAccountLength)
            {
                return(AccountOpResult.PassTooLong);
            }

            if (GetId(username) != 0)
            {
                return(AccountOpResult.NameAlreadyExist);
            }

            (byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(username, password);

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_ACCOUNT);

            stmt.AddValue(0, username);
            stmt.AddValue(1, salt);
            stmt.AddValue(2, verifier);
            stmt.AddValue(3, email);
            stmt.AddValue(4, email);
            if (bnetAccountId != 0 && bnetIndex != 0)
            {
                stmt.AddValue(5, bnetAccountId);
                stmt.AddValue(6, bnetIndex);
            }
            else
            {
                stmt.AddValue(5, null);
                stmt.AddValue(6, null);
            }
            DB.Login.DirectExecute(stmt); // Enforce saving, otherwise AddGroup can fail

            stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_REALM_CHARACTERS_INIT);
            DB.Login.Execute(stmt);

            return(AccountOpResult.Ok);
        }
        static void Socket_ReceiveCompleted(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (socket == null)
            {
                return;
            }
            byte[] message = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            string strMessage =
                Encoding.ASCII.GetString(message, 0, message.Length);

            if (ReceivedMessage != null)
            {
                ReceivedMessage.Invoke(strMessage, new EventArgs());
            }
        }
        private static void clientSocket_ReceiveCompleted(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            byte[] message = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            foreach (AsynchronousSocket client in clients)
            {
                if (client == socket)
                {
                    continue;
                }
                if (client.IsConnected)
                {
                    client.Send(message, 0, message.Length);
                }
            }
        }
Exemple #23
0
        static void FixLegacyAuthHashes()
        {
            Log.outInfo(LogFilter.Server, "Updating password hashes...");
            uint start = Time.GetMSTime();
            // the auth update query nulls salt/verifier if they cannot be converted
            // if they are non-null but s/v have been cleared, that means a legacy tool touched our auth DB (otherwise, the core might've done it itself, it used to use those hacks too)
            SQLResult result = DB.Login.Query("SELECT id, sha_pass_hash, IF((salt IS null) AND (verifier IS null), 0, 1) AS shouldWarn FROM account WHERE s != DEFAULT(s) OR v != DEFAULT(v) OR salt IS NULL OR verifier IS NULL");

            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.Server, $"No password hashes to update - this took us {Time.GetMSTimeDiffToNow(start)} ms to realize");
                return;
            }

            bool           hadWarning = false;
            uint           count      = 0;
            SQLTransaction trans      = new();

            do
            {
                uint id = result.Read <uint>(0);
                (byte[] salt, byte[] verifier) = SRP6.MakeRegistrationDataFromHash(result.Read <string>(1).ToByteArray());

                if (result.Read <long>(2) != 0 && !hadWarning)
                {
                    hadWarning = true;
                    Log.outWarn(LogFilter.Server, "(!) You appear to be using an outdated external account management tool.\n(!!) This is INSECURE, has been deprecated, and will cease to function entirely in the near future.\n(!) Update your external tool.\n(!!) If no update is available, refer your tool's developer to https://github.com/TrinityCore/TrinityCore/issues/25157.");
                }

                PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON);
                stmt.AddValue(0, salt);
                stmt.AddValue(1, verifier);
                stmt.AddValue(2, id);
                trans.Append(stmt);

                ++count;
            } while (result.NextRow());

            DB.Login.CommitTransaction(trans);

            Log.outInfo(LogFilter.Server, $"{count} password hashes updated in {Time.GetMSTimeDiffToNow(start)} ms");
        }
Exemple #24
0
        static void CreateAccount(string username, string password, string email)
        {
            username = username.ToUpperInvariant();
            password = password.ToUpperInvariant();

            var stmt = DB.LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT);

            Span <byte> salt     = stackalloc byte[32];
            Span <byte> verifier = stackalloc byte[32];

            stmt.Parameters[0] = username;
            var data = SRP6.MakeRegistrationData(username, password, salt, verifier);

            stmt.Parameters[1] = salt.ToArray();     // salt
            stmt.Parameters[2] = verifier.ToArray(); // verifier
            stmt.Parameters[3] = email;
            stmt.Parameters[4] = email;

            DB.LoginDatabase.DirectExecute(stmt);

            stmt = DB.LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS_INIT);
            DB.LoginDatabase.Execute(stmt);
        }
Exemple #25
0
 /// <summary>
 /// Used to check for a valid license
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 public Srp6ClientSocket(string username, string password)
 {
     InitializeDefaultProperties();
     IdentityHash = SRP6.GenerateIdentityHash(username, password);
     noop         = true;
 }
Exemple #26
0
 /// <summary>
 /// Socket constructor for download updates
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <param name="updateFileLocation"></param>
 public Srp6ClientSocket(string username, string password, string updateFileLocation)
 {
     InitializeDefaultProperties();
     IdentityHash       = SRP6.GenerateIdentityHash(username, password);
     UpdateFileLocation = updateFileLocation;
 }
Exemple #27
0
        private void ProcessDecryptedServerMessages(AsynchronousSocket socket, byte[] message)
        {
            // Server is going to tell us the size of the update
            if (isRequestingSend)
            {
                isRequestingSend = false;
                string   strMessage = SRP6.ArrayToString(message, 0, message.Length);
                string[] strTokens  = strMessage.Split(' ');
                try
                {
                    UpdateFileSize = Convert.ToInt32(strTokens[0]);
                }
                catch { }
                try
                {
                    encryptedFileSize = Convert.ToInt32(strTokens[1]);
                }
                catch { }

                if ((UpdateFileSize > 0) && (encryptedFileSize >= UpdateFileSize))
                {
                    isReceivingUpdate = true;
                    srpClient.EncryptAndSend(socket, "CONTINUE");
                }
                else
                {
                    OnDebug("Bad transfer information sent from the server");
                }
                return;
            }

            {
                string strMessage = SRP6.ArrayToString(message, 0, message.Length);
                OnDebug("Server Message \"" + strMessage + "\"");

                if (strMessage.Equals("PROCEED")) // CrashException != null
                {
                    // Send the CrashException to the server (serialized)
                    OnDebug("Sending crash report to server");
                    srpClient.EncryptAndSend(socket, CrashException.SerializeObject());
                }
            }
            if (isCheckingVersion)
            {
                isCheckingVersion = false;
                string text = SRP6.ArrayToString(message, 0, message.Length);
                OnDebug("Server reports that version is \"" + text + "\"");
                Srp6ClientSocket.NewestUpdateVersion = text;
                if (ReceivedVersion != null)
                {
                    ReceivedVersion.Invoke(this, new EventArgs());
                }
                if (checkVersionOnly)
                {
                    isCheckingVersion = false;
                    socket.Disconnect();
                }
                else
                {
                    isRequestingSend = true;
                    srpClient.EncryptAndSend(socket, "SEND");
                }
            }
        }
Exemple #28
0
        public void HandleAuthLogonChallenge(RealmClass session, PacketReader data)
        {
            Log.Message(LogType.NORMAL, "AuthLogonChallenge");

            data.Skip(10);
            ushort ClientBuild = data.ReadUInt16();

            data.Skip(8);
            account.Language = data.ReadStringFromBytes(4);
            data.Skip(4);

            account.IP   = data.ReadIPAddress();
            account.Name = data.ReadAccountName();

            SQLResult result = DB.Realms.Select("SELECT id, name, password, expansion, gmlevel, securityFlags FROM accounts WHERE name = '{0}'", account.Name);

            PacketWriter logonChallenge = new PacketWriter();

            logonChallenge.WriteUInt8((byte)ClientLink.CMD_AUTH_LOGON_CHALLENGE);
            logonChallenge.WriteUInt8(0);

            if (result.Count != 0)
            {
                account.Id            = result.Read <Int32>(0, "id");
                account.Expansion     = result.Read <Byte>(0, "expansion");
                account.SecurityFlags = result.Read <Byte>(0, "securityFlags");

                DB.Realms.Execute("UPDATE accounts SET ip = '{0}', language = '{1}' WHERE id = {2}", account.IP, account.Language, account.Id);

                byte[] username = Encoding.ASCII.GetBytes(result.Read <String>(0, "name").ToUpper());
                byte[] password = Encoding.ASCII.GetBytes(result.Read <String>(0, "password").ToUpper());

                // WoW 5.1.0.16309 (5.1.0)
                if (ClientBuild == 16309)
                {
                    session.SecureRemotePassword.CalculateX(username, password);
                    byte[] buf = new byte[0x10];
                    SRP6.RAND_bytes(buf, 0x10);

                    logonChallenge.WriteUInt8((byte)AuthResults.WOW_SUCCESS);
                    logonChallenge.WriteBytes(session.SecureRemotePassword.B);
                    logonChallenge.WriteUInt8(1);
                    logonChallenge.WriteUInt8(session.SecureRemotePassword.g[0]);
                    logonChallenge.WriteUInt8(0x20);
                    logonChallenge.WriteBytes(session.SecureRemotePassword.N);
                    logonChallenge.WriteBytes(session.SecureRemotePassword.salt);
                    logonChallenge.WriteBytes(buf);

                    // Security flags
                    logonChallenge.WriteUInt8(account.SecurityFlags);

                    // Enable authenticator
                    if ((account.SecurityFlags & 4) != 0)
                    {
                        logonChallenge.WriteUInt8(1);
                    }
                }
            }
            else
            {
                logonChallenge.WriteUInt8((byte)AuthResults.WOW_FAIL_UNKNOWN_ACCOUNT);
            }

            session.Send(logonChallenge);
        }
Exemple #29
0
        public void HandleAuthLogonChallenge(AuthClass session, PacketReader data)
        {
            data.Skip(10);
            ClientBuild = data.ReadUInt16();
            data.Skip(8);
            account.Locale = data.ReadStringFromBytes(4);
            data.Skip(4);

            byte[] ip = new byte[4];

            for (int i = 0; i < 4; ++i)
            {
                ip[i] = data.ReadUInt8();
            }

            account.LastIP = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];

            StringBuilder nameBuilder = new StringBuilder();
            byte          nameLength  = data.ReadUInt8();

            char[] name = new char[nameLength];

            for (int i = 0; i < nameLength; i++)
            {
                name[i] = data.ReadChar();
                nameBuilder.Append(name[i]);
            }

            account.Name = nameBuilder.ToString().Trim(new char[] { '@' }).ToUpper();
            //             0,            1,       2,       3,          4
            //"SELECT a.sha_pass_hash, a.id, a.locked, a.last_ip, aa.gmlevel FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?"
            PreparedStatement stmt = DB.Auth.GetPreparedStatement(LoginStatements.Sel_LogonChallenge);

            stmt.AddValue(0, account.Name);

            SQLResult result = DB.Auth.Select(stmt);

            PacketWriter logonChallenge = new PacketWriter();

            logonChallenge.WriteUInt8((byte)ClientLink.AuthLogonChallenge);
            logonChallenge.WriteUInt8(0);

            if (result.Count != 0)
            {
                account.Id = result.Read <uint>(0, 1);
                SRP        = new SRP6(account.Name, result.Read <string>(0, 0).ToByteArray(), true);

                logonChallenge.WriteUInt8((byte)AuthResults.Success);
                logonChallenge.WriteBytes(SRP.PublicEphemeralValueB.GetBytes());
                logonChallenge.WriteUInt8(1);
                logonChallenge.WriteBytes(SRP.Generator.GetBytes());
                logonChallenge.WriteUInt8(0x20);
                logonChallenge.WriteBytes(SRP.Modulus.GetBytes());
                logonChallenge.WriteBytes(SRP.Salt.GetBytes());
                logonChallenge.WriteBytes(SRP6.RandomNumber(0x10).GetBytes());
                // GMLevel
                logonChallenge.WriteUInt8(0);
            }
            else
            {
                logonChallenge.WriteUInt8((byte)AuthResults.FailUnknownAccount);
            }

            session.Send(logonChallenge);
        }
Exemple #30
0
 public RealmClass()
 {
     account = new Account();
     SecureRemotePassword = new SRP6();
 }