/// <summary>
        /// The read.
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="packet">
        /// </param>
        public static void Read(Client client, byte[] packet)
        {
            LogUtil.Debug(DebugInfoDetail.Network, "\r\nReceived:\r\n" + HexOutput.Output(packet));

            MemoryStream m_stream = new MemoryStream(packet);
            BinaryReader m_reader = new BinaryReader(m_stream);

            // now we should do password check and then send OK or Error
            // sending OK now
            m_stream.Position = 8;

            short  userNameLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string userName       = Encoding.ASCII.GetString(m_reader.ReadBytes(userNameLength));
            short  loginKeyLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string loginKey       = Encoding.ASCII.GetString(m_reader.ReadBytes(loginKeyLength));

            LoginEncryption loginEncryption = new LoginEncryption();

            if (loginEncryption.IsValidLogin(loginKey, client.ServerSalt, userName))
            {
                client.IsBot = true;
                byte[] chars = AccountCharacterList.Create(userName);
                LogUtil.Debug(DebugInfoDetail.Network, "\r\nReceived:\r\n" + HexOutput.Output(chars));

                client.Send(chars);
            }
            else
            {
                byte[] loginerr = LoginError.Create();
                client.Send(loginerr);
                client.Server.DisconnectClient(client);
            }
        }
Example #2
0
        /// <summary>
        /// </summary>
        /// <param name="obj">
        /// </param>
        private static void SetHash(string[] obj)
        {
            Colouring.Push(ConsoleColor.Red);

            if (obj.Length != 2)
            {
                Console.WriteLine("The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces");
                Colouring.Pop();
                return;
            }

            string pass   = obj[1];
            var    le     = new LoginEncryption();
            string hashed = le.GeneratePasswordHash(pass);

            Colouring.Pop();
            Console.Write("The Hash for password '");
            Colouring.Push(ConsoleColor.Green);
            Console.Write(obj[1]);
            Colouring.Pop();
            Console.Write("' is '");
            Colouring.Push(ConsoleColor.Green);
            Console.Write(hashed);
            Colouring.Pop();
            Console.WriteLine("'");
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="LoginKey"></param>
        /// <returns></returns>
        public bool IsLoginCorrect(Client client, string LoginKey)
        {
            LoginEncryption le = new LoginEncryption();

            lp.GetLoginPassword(client.accountName);

            return(le.IsValidLogin(LoginKey, client.serverSalt, client.accountName, lp.PasswdL));
        }
Example #4
0
        /// <summary>
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="loginKey">
        /// </param>
        /// <returns>
        /// </returns>
        public bool IsLoginCorrect(Client client, string loginKey)
        {
            var le = new LoginEncryption();

            this.lp.GetLoginPassword(client.AccountName);

            return(le.IsValidLogin(loginKey, client.ServerSalt, client.AccountName, this.lp.PasswdL));
        }
Example #5
0
        private LoginEncryptionType GetClientEncryption(byte[] encryptedLoginPacket, out uint key1, out uint key2)
        {
            byte[] plain = PacketBuilder.LoginRequestShardList(Core.LaunchData.Username, Core.LaunchData.Password);

            if (memcmp(plain, encryptedLoginPacket, 61) != 0) // Encrypted client
            {
                if (!Core.ClientKeys.Calculated)
                {
                    if (!LoginEncryption.CalculateKeys(plain, encryptedLoginPacket, Seed, out key1, out key2))
                    {
                        throw new SocketException("Error while calculating login keys. Make sure you used same account and password as in launcher.", this, encryptedLoginPacket);
                    }

                    Core.ClientKeys.ClientInfo.Key1 = key1.ToString("X");
                    Core.ClientKeys.ClientInfo.Key2 = key2.ToString("X");
                    Core.ClientKeys.ClientInfo.Hash = Core.LaunchData.ClientHash;

                    Core.ClientKeys.Save();
                }
                else
                {
                    try {
                        key1 = UInt32.Parse(Core.ClientKeys.ClientInfo.Key1, System.Globalization.NumberStyles.HexNumber);
                        key2 = UInt32.Parse(Core.ClientKeys.ClientInfo.Key2, System.Globalization.NumberStyles.HexNumber);
                    }
                    catch (Exception e) {
                        throw new Exception("Error parsing client login keys.", e);
                    }
                }

                Trace.WriteLine(String.Format("Client key1: {1} key2: {2}", Seed.ToString("X"), key1.ToString("X"), key2.ToString("X")), "Communication");
                return(LoginEncryptionType.New);
            }
            else
            {
                key1 = 0;
                key2 = 0;

                if (!Core.ClientKeys.Calculated)
                {
                    Core.ClientKeys.ClientInfo.Key1 = key1.ToString("X");
                    Core.ClientKeys.ClientInfo.Key2 = key2.ToString("X");
                    Core.ClientKeys.ClientInfo.Hash = Core.LaunchData.ClientHash;

                    Core.ClientKeys.Save();
                }

                Trace.WriteLine("Non-encrypted client detected.", "Communication");
                return(LoginEncryptionType.None);
            }
        }
Example #6
0
        /// <summary>
        /// </summary>
        /// <param name="obj">
        /// </param>
        private static void SetPassword(string[] obj)
        {
            string Syntax =
                "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";

            if (obj.Length != 3)
            {
                Colouring.Push(ConsoleColor.Red);
                Console.WriteLine(Syntax);
                Colouring.Pop();
            }
            else
            {
                string username = obj[1];
                string newpass  = obj[2];
                var    le       = new LoginEncryption();
                string hashed   = le.GeneratePasswordHash(newpass);
                int    affected =
                    LoginDataDao.WriteNewPassword(new DBLoginData()
                {
                    Username = username, Password = hashed
                });
                if (affected == 0)
                {
                    Colouring.Push(ConsoleColor.Red);
                    Console.WriteLine("Could not set new password. Maybe username is wrong?");
                    Colouring.Pop();
                }
                else
                {
                    Colouring.Push(ConsoleColor.Green);
                    Console.WriteLine("New password is set.");
                    Colouring.Pop();
                }
            }
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="characterId"></param>
        /// <returns></returns>
        public bool IsCharacterOnAccount(Client client, int characterId)
        {
            LoginEncryption le = new LoginEncryption();

            return(le.IsCharacterOnAccount(client.accountName, characterId));
        }
Example #8
0
        public void InitClient()
        {
            messageIdentifier  = "msg";
            usernameIdentifier = "usr";
            splitCharacter     = '|';
            bool  validUsername;
            Regex regex = new Regex("^[a-zA-Z0-9_-]+$");

            do
            {
                Console.WriteLine("Please enter your username:"******"192.168.209.7", 9000);

            client.ServerConnected    = ServerConnected;
            client.ServerDisconnected = ServerDisconnected;
            client.MessageReceived    = MessageReceived;
            client.Debug = false;
            client.Start();
            client.Send(Encoding.UTF8.GetBytes(usernameIdentifier + splitCharacter + clientName));

            bool runForever = true;

            while (runForever)
            {
                Console.WriteLine("Command [q cls send auth]: ");
                string userInput = Console.ReadLine();
                if (string.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                switch (userInput)
                {
                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "send":
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (string.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    client.Send(Encoding.UTF8.GetBytes(messageIdentifier + splitCharacter + userInput));
                    break;

                case "auth":
                    Console.Write("Preshared key: ");
                    userInput = Console.ReadLine();
                    if (string.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    client.Authenticate(userInput);
                    break;
                }
            }
        }
Example #9
0
        /// <summary>
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="characterId">
        /// </param>
        /// <returns>
        /// </returns>
        public bool IsCharacterOnAccount(Client client, int characterId)
        {
            var le = new LoginEncryption();

            return(le.IsCharacterOnAccount(client.AccountName, (UInt32)characterId));
        }
Example #10
0
        /// <summary>
        /// The read.
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="packet">
        /// </param>
        public static void Read(Client client, ref byte[] packet)
        {
            MemoryStream m_stream = new MemoryStream(packet);
            BinaryReader m_reader = new BinaryReader(m_stream);

            // now we should do password check and then send OK or Error
            // sending OK now
            m_stream.Position = 12;

            short  userNameLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string userName       = Encoding.ASCII.GetString(m_reader.ReadBytes(userNameLength));
            short  loginKeyLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string loginKey       = Encoding.ASCII.GetString(m_reader.ReadBytes(loginKeyLength));

            uint characterId = BitConverter.ToUInt32(new[] { packet[11], packet[10], packet[9], packet[8] }, 0);

            LoginEncryption loginEncryption = new LoginEncryption();

            if (loginEncryption.IsValidLogin(loginKey, client.ServerSalt, userName) &&
                loginEncryption.IsCharacterOnAccount(userName, characterId))
            {
                byte[] loginok = LoginOk.Create();
                client.Send(loginok);
            }
            else
            {
                byte[] loginerr = LoginError.Create();
                client.Send(loginerr);
                client.Server.DisconnectClient(client);
                byte[] invalid = BitConverter.GetBytes(characterId);

                ZoneCom.Client.SendMessage(99, invalid);
                return;
            }

            // server welcome message
            string motd = ConfigReadWrite.Instance.CurrentConfig.Motd;

            // save characters ID in client - note, this is usually 0 if it is a chat client connecting
            client.Character = new Character(characterId, client);

            // add client to connected clients list
            if (!client.Server.ConnectedClients.ContainsKey(client.Character.characterId))
            {
                client.Server.ConnectedClients.Add(client.Character.characterId, client);
            }

            // add yourself to that list
            client.KnownClients.Add(client.Character.characterId);

            // and give client its own name lookup
            byte[] pname = PlayerName.New(client, client.Character.characterId);
            client.Send(pname);

            // send server welcome message to client
            byte[] anonv = MsgAnonymousVicinity.Create(
                string.Empty,
                string.Format(motd, AssemblyInfoclass.Description + " " + AssemblyInfoclass.AssemblyVersion),
                string.Empty);
            client.Send(anonv);

            // tell client to join channel "Global"
            // hardcoded right now
            foreach (ChannelsEntry channel in ChatChannels.ChannelNames)
            {
                byte[] chanGlobal = ChannelJoin.Create(
                    channel.Id, channel.Name, channel.ChannelMode, new byte[] { 0x00, 0x00 });
                client.Send(chanGlobal);
            }

            // First Attempt at Guild Channel....
            // This code is completly untested however if it works
            // we will have to add some what for you to join GuildChat on creation of guild
            // and when you join a guild...  this just connects you to it if you already exist in a guild
            // at character login.. enjoy hope it works.. I cant seem to test it my computer wont let me install the sql tables atm..

            if (client.Character.orgId == 0)
            {
            }
            else
            {
                ulong channelBuffer = (ulong)ChannelType.Organization << 32;
                channelBuffer |= (uint)client.Character.orgId;

                byte[] guildChannel = ChannelJoin.Create(channelBuffer, client.Character.orgName, 0x8044, new byte[] { 0x00, 0x00 });
                client.Send(guildChannel);
            }


            // Do Not Delete this just yet!
            // byte[] chn_global = new Packets.ChannelJoin().Create
            // (
            // new byte[] { 0x04, 0x00, 0x00, 0x23, 0x28 },
            // "Global",
            // 0x8044,
            // new byte[] { 0x00, 0x00 }
            // );
            // client.Send(chn_global);
        }
Example #11
0
        private static void Main(string[] args)
        {
            #region Console Texts...
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion

            //Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;
            loginLoginServer           = new LoginServer();
            loginLoginServer.EnableTCP = true;
            loginLoginServer.EnableUDP = false;
            try
            {
                loginLoginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }
            loginLoginServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/LoginEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug
            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            NBug.Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            //TODO: ADD More Handlers.
            #endregion

            loginLoginServer.MaximumPendingConnections = 100;

            #region Console Commands
            //Andyzweb: Added checks for start and stop
            //also added a running command to return status of the server
            //and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            loginLoginServer.Start();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = "";
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }
                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Start();
                    loginLoginServer.Start();
                    break;

                case "stop":
                    if (!loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Stop();
                    loginLoginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginLoginServer.Running)
                    {
                        //Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }
                    //Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....
                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;
                    #endregion

                default:

                    #region Adduser
                    //This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }
                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }
                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }
                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = String.Empty;
                        }
                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }
                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }
                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        const string FormatString =
                            "INSERT INTO `login` (`CreationDate`, `Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`, `GM`, `Email`, `FirstName`, `LastName`) VALUES "
                            + "(NOW(), '0', '0', '{0}', '{1}', {2}, {3}, {4}, '{5}', '{6}', '{7}');";

                        LoginEncryption le = new LoginEncryption();

                        string hashedPassword = le.GeneratePasswordHash(password);

                        string sql = String.Format(
                            FormatString,
                            username,
                            hashedPassword,
                            numChars,
                            expansions,
                            gm,
                            email,
                            firstname,
                            lastname);
                        SqlWrapper sqlWrapper = new SqlWrapper();
                        try
                        {
                            sqlWrapper.SqlInsert(sql);
                        }
                        catch (MySqlException ex)
                        {
                            switch (ex.Number)
                            {
                            case 1062:         //duplicate entry for key
                                Console.WriteLine("A user account with this username already exists.");
                                break;

                            default:
                                Console.WriteLine(
                                    "An error occured while trying to add a new user account:\n{0}", ex.Message);
                                break;
                            }
                            break;
                        }
                        Console.WriteLine("User added successfully.");
                        break;
                    }
                    #endregion

                    #region Hashpass
                    //This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          pass   = parts[1];
                        LoginEncryption le     = new LoginEncryption();
                        string          hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }
                    #endregion

                    #region setpass
                    //sets the password for the given username
                    //Added by Andyzweb
                    //Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          username = parts[1];
                        string          newpass  = parts[2];
                        LoginEncryption le       = new LoginEncryption();
                        string          hashed   = le.GeneratePasswordHash(newpass);
                        string          formatString;
                        formatString = "UPDATE `login` SET Password = '******' WHERE login.Username = '******'";

                        string sql = String.Format(formatString, hashed, username);

                        SqlWrapper updt = new SqlWrapper();
                        try
                        {
                            updt.SqlUpdate(sql);
                        }
                        //yeah this part here, some kind of exception handling for mysql errors
                        catch
                        {
                        }
                    }
                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }
            #endregion
        }
Example #12
0
    /// <summary>
    /// 处理从客户端收到的消息
    /// </summary>
    /// <param name="type">收到的消息类型</param>
    /// <param name="json">收到的json文件</param>
    /// <param name="client">对应的客户端连接</param>
    private void manipulationData(string type, JObject json, WebSocketSession client)
    {
        if (type == "register")
        {
            var account  = json["account"].ToString();
            var password = json["password"].ToString();

            //首先判断账号是否已经存在
            if (DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where account='" + account + "'", null).Tables[0].Rows.Count == 0)
            {
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "insert into game(account,password) values('" + account + "','" + password + "')", null);
                //不存的情况
                JObject js = new JObject();
                js.Add("type", "registerResult");
                js.Add("reason", "true");
                client.Send(js.ToString());
            }
            else
            {
                //账号已经存在的情况
                JObject js = new JObject();
                js.Add("type", "registerResult");
                js.Add("reason", "false");
                client.Send(js.ToString());
            }
        }
        else if (type == "login")
        {
            var account  = json["account"].ToString();
            var password = json["password"].ToString();

            var pas = selectMysqlPassword(account);
            if (pas == "")
            {
                //账号不存在
                showLog("客户端" + client.RemoteEndPoint + ":账号不存在");

                JObject js = new JObject();
                js.Add("type", "loginResult");
                js.Add("ifloginSuccess", "false");
                js.Add("reason", "NoAccount");

                client.Send(js.ToString());
            }
            else if (pas == password)
            {
                //登陆成功
                showLog("客户端" + client.RemoteEndPoint + ":登陆成功");
                //将密码和时间组合起来,通过秘钥进行加密
                pas = LoginEncryption.encryptionPassword(pas + DateTime.Now.ToLongTimeString().ToString(), "thisisapassword");

                var     playername = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where account=" + account, null).Tables[0].Rows[0]["playerName"].ToString();
                var     playerType = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where account=" + account, null).Tables[0].Rows[0]["PlayerType"].ToString();
                JObject js         = new JObject();
                js.Add("type", "loginResult");
                js.Add("ifloginSuccess", "true");
                js.Add("privatePassword", pas);
                js.Add("playerName", playername);
                if (playername != "")
                {
                    js.Add("playerType", playerType);
                }
                client.Send(js.ToString());
                dic.Add(client, pas);
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set secretkey='" + pas + "' where account=" + account, null);
                showData();
            }
            else
            {
                //密码错误
                showLog("客户端" + client.RemoteEndPoint + ":密码错误");
                JObject js = new JObject();
                js.Add("type", "loginResult");
                js.Add("ifloginSuccess", "false");
                js.Add("reason", "PasswordError");
                client.Send(js.ToString());
            }
        }
        else if (type == "createPlayer")
        {
            var secretKey  = json["secretKey"].ToString();
            var name       = json["playerName"].ToString();
            var playerType = json["playerType"].ToString();

            //先判断是和数据库中否有重名的情况
            if (DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where playerName='" + name + "'", null).Tables[0].Rows.Count == 0)
            {
                //创建成功
                showLog("客户端" + client.RemoteEndPoint + ":创建角色成功,角色名:" + name);
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set playerName='" + name + "',playerType='" + playerType + "',XPoint=300.0,YPoint=300.0,grade='1',blood='100',direction=1 where secretKey='" + secretKey + "'", null);

                JObject js = new JObject();
                js.Add("type", "craetePlayerResult");
                js.Add("ifSuccess", "true");
                js.Add("playerType", playerType);
                client.Send(js.ToString());
                showData();
            }
            else
            {
                //创建失败,有重名的情况
                showLog("客户端" + client.RemoteEndPoint + ":创建角色失败");

                JObject js = new JObject();
                js.Add("type", "craetePlayerResult");
                js.Add("ifSuccess", "false");
                client.Send(js.ToString());
            }
        }
        else if (type == "loginGameScene")
        {
            var secretKey = json["secretKey"].ToString();//获得通信秘钥

            var playername = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["playerName"].ToString();
            var playerType = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["PlayerType"].ToString();
            var XPoint     = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["XPoint"].ToString();
            var YPoint     = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["YPoint"].ToString();
            var grade      = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["grade"].ToString();
            var blood      = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["blood"].ToString();
            var direction  = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["direction"].ToString();

            JObject js = new JObject();
            js.Add("type", "playerInformation");
            js.Add("playerName", playername);
            js.Add("playerType", playerType);
            js.Add("XPoint", float.Parse(XPoint));
            js.Add("YPoint", float.Parse(YPoint));
            js.Add("grade", int.Parse(grade));
            js.Add("blood", float.Parse(blood));
            js.Add("direction", int.Parse(direction));
            client.Send(js.ToString());

            DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set Online='是' where secretKey='" + secretKey + "'", null);
            showData();

            showLog("角色" + playername + ":登录游戏");
        }
        else if (type == "nearPlayers")
        {
            var secretKey = json["secretKey"].ToString();//获得通信秘钥

            var playername = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["playerName"].ToString();
            var playerType = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["PlayerType"].ToString();
            var XPoint     = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["XPoint"].ToString();
            var YPoint     = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["YPoint"].ToString();
            var grade      = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["grade"].ToString();
            var blood      = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["blood"].ToString();
            var direction  = DbConnectionMySQL.GetDataSet(DbConnectionMySQL.Conn, CommandType.Text, "select * from game where secretKey='" + secretKey + "'", null).Tables[0].Rows[0]["direction"].ToString();

            JObject js = new JObject();
            js.Add("type", "nearPlayer");
            js.Add("playerName", playername);
            js.Add("playerType", playerType);
            js.Add("XPoint", float.Parse(XPoint));
            js.Add("YPoint", float.Parse(YPoint));
            js.Add("grade", int.Parse(grade));
            js.Add("blood", float.Parse(blood));
            js.Add("direction", int.Parse(direction));
            js.Add("state", "free");
            GetAllLayer(secretKey, client, js);
        }
        else if (type == "position")
        {
            var secretKey = json["secretKey"].ToString(); //获得通信秘钥
            var state     = json["state"].ToString();     //人物的当前状态

            if (state == "walk")
            {
                var XPoint      = float.Parse(json["XPoint"].ToString());  //人物的X坐标
                var YPoint      = float.Parse(json["YPoint"].ToString());  //人物的Y坐标
                var direction   = int.Parse(json["direction"].ToString()); //人物的朝向
                var playerState = json["state"].ToString();
                //更新数据库中人物的信息
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set XPoint=" + XPoint + " where secretKey='" + secretKey + "'", null);
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set YPoint=" + YPoint + " where secretKey='" + secretKey + "'", null);
                DbConnectionMySQL.ExecuteNonQuery(DbConnectionMySQL.Conn, CommandType.Text, "update game set direction=" + direction + " where secretKey='" + secretKey + "'", null);

                //广播其他玩家
                SendToAllPosition(secretKey, XPoint, YPoint, direction, playerState);
            }
            else if (state == "free")
            {
                SendToAllPosition(secretKey, 0.0f, 0.0f, 0, "free");
            }
            //   showData();
        }
        else if (type == "message")
        {
            var secretKey = json["secretKey"].ToString();  //获得通信秘钥
            var message   = json["message"].ToString();    //获得发送的内容
            var name      = json["playerName"].ToString(); //获得发送消息的玩家
            SendToMessage(secretKey, name, message);
            showLog("角色" + name + ":发送了一条消息,消息内容为:" + message);
        }
    }
Example #13
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        private static void Main(string[] args)
        {
            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/LoginEngineLog.txt", LogLevel.Trace);



            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;



            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            var ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();

            // Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;

            loginServer = Container.GetInstance <LoginServer>();
            bool TCPEnable = true;
            bool UDPEnable = false;
            int  Port      = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    loginServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    loginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            // TODO: ADD More Handlers.
            loginServer.MaximumPendingConnections = 100;

            #region Console Commands

            // Andyzweb: Added checks for start and stop
            // also added a running command to return status of the server
            // and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            loginServer.Start(TCPEnable, UDPEnable);
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = string.Empty;
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }

                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Start(TCPEnable, UDPEnable);
                    break;

                case "stop":
                    if (!loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginServer.IsRunning)
                    {
                        // Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }

                    // Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....

                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;

                    #endregion

                default:

                    #region Adduser

                    // This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }

                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }

                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = string.Empty;
                        }

                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }

                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }

                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        DBLoginData login = new DBLoginData
                        {
                            Username           = username,
                            AccountFlags       = 0,
                            Allowed_Characters = numChars,
                            CreationDate       = DateTime.Now,
                            Email      = email,
                            Expansions = expansions,
                            FirstName  = firstname,
                            LastName   = lastname,
                            GM         = gm,
                            Flags      = 0,
                            Password   = new LoginEncryption().GeneratePasswordHash(password)
                        };
                        try
                        {
                            LoginDataDao.WriteLoginData(login);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(
                                "An error occured while trying to add a new user account:\n{0}", ex.Message);
                            break;
                        }

                        Console.WriteLine("User added successfully.");
                        break;
                    }

                    #endregion

                    #region Hashpass

                    // This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string pass   = parts[1];
                        var    le     = new LoginEncryption();
                        string hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }

                    #endregion

                    #region setpass

                    // sets the password for the given username
                    // Added by Andyzweb
                    // Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string username = parts[1];
                        string newpass  = parts[2];
                        var    le       = new LoginEncryption();
                        string hashed   = le.GeneratePasswordHash(newpass);

                        try
                        {
                            LoginDataDao.WriteNewPassword(
                                new DBLoginData {
                                Username = username, Password = hashed
                            });
                        }
                        // yeah this part here, some kind of exception handling for mysql errors
                        catch (Exception ex)
                        {
                            Console.WriteLine("Could not set new Password\r\n" + ex.Message);
                            LogUtil.ErrorException(ex);
                        }
                    }

                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }

            #endregion
        }
        /// <summary>
        /// login packet
        /// </summary>
        /// <param name="loginPacket"></param>
        public void VerifyLogin(LoginPacket loginPacket)
        {
            if (loginPacket == null)
            {
                return;
            }

            UserDTO user = new UserDTO
            {
                Name     = loginPacket.Name,
                Password = ConfigurationManager.AppSettings["UseOldCrypto"] == "true" ? EncryptionBase.Sha512(LoginEncryption.GetPassword(loginPacket.Password)).ToUpper() : loginPacket.Password
            };
            AccountDTO loadedAccount = DAOFactory.AccountDAO.LoadByName(user.Name);

            if (loadedAccount != null && loadedAccount.Password.ToUpper().Equals(user.Password))
            {
                DAOFactory.AccountDAO.WriteGeneralLog(loadedAccount.AccountId, _session.IpAddress, null, GeneralLogType.Connection, "LoginServer");

                //check if the account is connected
                if (!CommunicationServiceClient.Instance.IsAccountConnected(loadedAccount.AccountId))
                {
                    AuthorityType type    = loadedAccount.Authority;
                    PenaltyLogDTO penalty = DAOFactory.PenaltyLogDAO.LoadByAccount(loadedAccount.AccountId).FirstOrDefault(s => s.DateEnd > DateTime.Now && s.Penalty == PenaltyType.Banned);
                    if (penalty != null)
                    {
                        _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("BANNED"), penalty.Reason, penalty.DateEnd.ToString("yyyy-MM-dd-HH:mm"))}");
                    }
                    else
                    {
                        switch (type)
                        {
                        case AuthorityType.Unconfirmed:
                        {
                            _session.SendPacket($"fail {Language.Instance.GetMessageFromKey("NOTVALIDATE")}");
                        }
                        break;

                        case AuthorityType.Banned:
                        {
                            _session.SendPacket($"fail {Language.Instance.GetMessageFromKey("IDERROR")}");
                        }
                        break;

                        case AuthorityType.Closed:
                        {
                            _session.SendPacket($"fail {Language.Instance.GetMessageFromKey("IDERROR")}");
                        }
                        break;

                        default:
                        {
                            int newSessionId = SessionFactory.Instance.GenerateSessionId();
                            Logger.Log.DebugFormat(Language.Instance.GetMessageFromKey("CONNECTION"), user.Name, newSessionId);

                            // inform communication service about new player from login server
                            try
                            {
                                CommunicationServiceClient.Instance.RegisterAccountLogin(loadedAccount.AccountId, newSessionId);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log.Error("General Error SessionId: " + newSessionId, ex);
                            }
                            _session.SendPacket(BuildServersPacket(loadedAccount.AccountId, newSessionId));
                        }
                        break;
                        }
                    }
                }
                else
                {
                    _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("ALREADY_CONNECTED"))}");
                }
            }
            else
            {
                _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("IDERROR"))}");
            }
        }
        public void DecodeIncomingPacket(Socket from, ref byte[] buffer, ref int length, bool ClientLocal)
        {
            #region m_Encryption != null
            //if (m_Encryption is GameEncryption && !ClientLocal && buffer[0] != 232)
            //{
            //  return;
            //}
            if (m_Encryption != null)
            {
                // If we're decrypting using LoginCrypt and we've already been relayed,
                // only decrypt a single packet using logincrypt and then disable it

                if (m_Encryption is LoginEncryption)
                {
                    uint newSeed = ((((LoginEncryption)(m_Encryption)).Key1 + 1) ^ ((LoginEncryption)(m_Encryption)).Key2);

                    // Swap the seed
                    newSeed = ((newSeed >> 24) & 0xFF) | ((newSeed >> 8) & 0xFF00) | ((newSeed << 8) & 0xFF0000) | ((newSeed << 24) & 0xFF000000);

                    // XOR it with the old seed
                    newSeed ^= m_Seed;

                    IClientEncryption newEncryption = new GameEncryption(newSeed);

                    // Game Encryption comes first
                    newEncryption.clientDecrypt(ref buffer, length);

                    // The login encryption is still used for this one packet
                    m_Encryption.clientDecrypt(ref buffer, length);

                    // Swap the encryption schemes
                    Encryption = newEncryption;
                    m_Seed     = newSeed;

                    return;
                }

                m_Encryption.clientDecrypt(ref buffer, length);
                return;
            }
            #endregion

            #region Port Scan
            //11JUN2008 RunUO SVN fix ** START ***
            // If the client did not connect on the game server port,
            // it's not our business to handle encryption for it
            //if (((IPEndPoint)from.Socket.LocalEndPoint).Port != Listener.Port)
            //{
            //    m_Encryption = new NoEncryption();
            //    return;
            //}
            bool handle = false;

            for (int i = 0; i < Listener.EndPoints.Length; i++)
            {
                IPEndPoint ipep = (IPEndPoint)Listener.EndPoints[i];

                if (((IPEndPoint)from.LocalEndPoint).Port == ipep.Port)
                {
                    handle = true;
                }
            }

            if (!handle)
            {
                Encryption = new NoEncryption();
                return;
            }
            //11JUN2008 RunUO SVN fix ** END ***
            #endregion

            #region !m_Seeded
            // For simplicities sake, enqueue what we just received as long as we're not initialized
            m_Buffer.Enqueue(buffer, 0, length);
            // Clear the array
            length = 0;

            // If we didn't receive the seed yet, queue data until we can read the seed
            //if (!m_Seeded)
            //{
            //    // Now check if we have at least 4 bytes to get the seed
            //    if (m_Buffer.Length >= 4)
            //    {
            //        byte[] m_Peek = new byte[m_Buffer.Length];
            //        m_Buffer.Dequeue( m_Peek, 0, m_Buffer.Length ); // Dequeue everything
            //        m_Seed = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]);
            //        m_Seeded = true;

            //        Buffer.BlockCopy(m_Peek, 0, buffer, 0, 4);
            //        length = 4;
            //    }
            //    else
            //    {
            //        return;
            //    }
            //}
            //http://uodev.de/viewtopic.php?t=5097&postdays=0&postorder=asc&start=15&sid=dfb8e6c73b9e3eb95c1634ca3586e8a7
            //if (!m_Seeded)
            //{
            //    int seed_length = m_Buffer.GetSeedLength();

            //    if (m_Buffer.Length >= seed_length)
            //    {
            //        byte[] m_Peek = new byte[m_Buffer.Length];
            //        m_Buffer.Dequeue(m_Peek, 0, seed_length);

            //        if (seed_length == 4)
            //            m_Seed = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]);
            //        else if (seed_length == 21)
            //            m_Seed = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]);

            //        m_Seeded = true;

            //        Buffer.BlockCopy(m_Peek, 0, buffer, 0, seed_length);
            //        length = seed_length;
            //    }
            //    else
            //    {
            //        return;
            //    }
            //}

            //11JUN2008 My Version

            if (!m_Seeded)
            {
                if (m_Buffer.Length <= 3) //Short Length, try again.
                {
                    Console.WriteLine("Encryption: Failed - Short Lenght");
                    return;
                }
                //else if ((m_Buffer.Length == 83) && (m_Buffer.GetPacketID() == 239)) //New Client
                //{
                //    byte[] m_Peek = new byte[21];
                //    m_Buffer.Dequeue(m_Peek, 0, 21);

                //    m_Seed = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]);
                //    m_Seeded = true;

                //    Buffer.BlockCopy(m_Peek, 0, buffer, 0, 21);
                //    length = 21;

                //    Console.WriteLine("Encryption: Passed - New Client");
                //}

                //05MAR2009 Smjert's fix for double log in.  *** START ***
                else if ((m_Buffer.Length == 83 || m_Buffer.Length == 21) && (m_Buffer.GetPacketID() == 239)) //New Client
                {
                    length = m_Buffer.Length;
                    byte[] m_Peek = new byte[21];
                    m_Buffer.Dequeue(m_Peek, 0, 21);

                    m_Seed   = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]);
                    m_Seeded = true;

                    Buffer.BlockCopy(m_Peek, 0, buffer, 0, 21);


                    Console.WriteLine("Encryption: Passed - New Client");

                    // We need to wait the next packet
                    if (length == 21)
                    {
                        return;
                    }

                    length = 21;
                }

                else if (m_Buffer.Length >= 4) //Old Client
                //05MAR2009 Smjert's fix for double log in.  *** END ***
                {
                    byte[] m_Peek = new byte[4];
                    m_Buffer.Dequeue(m_Peek, 0, 4);

                    m_Seed   = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]);
                    m_Seeded = true;

                    Buffer.BlockCopy(m_Peek, 0, buffer, 0, 4);
                    length = 4;

                    Console.WriteLine("Encryption: Passed - Old Client");
                }
                else //It should never reach here.
                {
                    Console.WriteLine("Encryption: Failed - It should never reach here");
                    return;
                }
            }
            #endregion

            // If the context isn't initialized yet, that means we haven't decided on an encryption method yet
            #region m_Encryption == null
            if (m_Encryption == null)
            {
                int packetLength = m_Buffer.Length;
                int packetOffset = length;
                m_Buffer.Dequeue(buffer, length, packetLength); // Dequeue everything
                length += packetLength;

                // This is special handling for the "special" UOG packet
                if (packetLength >= 3)
                {
                    if (buffer[packetOffset] == 0xf1 && buffer[packetOffset + 1] == ((packetLength >> 8) & 0xFF) && buffer[packetOffset + 2] == (packetLength & 0xFF))
                    {
                        Encryption = new NoEncryption();
                        return;
                    }
                }

                // Check if the current buffer contains a valid login packet (62 byte + 4 byte header)
                // Please note that the client sends these in two chunks. One 4 byte and one 62 byte.
                if (packetLength == 62)
                {
                    Console.WriteLine("Checking packetLength 62 == " + packetLength);
                    // Check certain indices in the array to see if the given data is unencrypted
                    if (buffer[packetOffset] == 0x80 && buffer[packetOffset + 30] == 0x00 && buffer[packetOffset + 60] == 0x00)
                    {
                        if (Configuration.AllowUnencryptedClients)
                        {
                            Encryption = new NoEncryption();
                        }
                    }
                    else
                    {
                        LoginEncryption encryption = new LoginEncryption();
                        if (encryption.init(m_Seed, buffer, packetOffset, packetLength))
                        {
                            Console.WriteLine("Client: {0}: Encrypted client detected, using keys of client {1}", "asd", encryption.Name);
                            Encryption = encryption;
                            Console.WriteLine("Encryption: Check 1");
                            byte[] packet = new byte[packetLength];
                            Console.WriteLine("Encryption: Check 2");
                            Buffer.BlockCopy(buffer, packetOffset, packet, 0, packetLength);
                            Console.WriteLine("Encryption: Check 3");
                            encryption.clientDecrypt(ref packet, packet.Length);
                            Console.WriteLine("Encryption: Check 4");
                            Buffer.BlockCopy(packet, 0, buffer, packetOffset, packetLength);
                            Console.WriteLine("Encryption: Check 5");
                            //return; //Just throwing this in.
                        }
                        else
                        {
                            Console.WriteLine("Detected an unknown client.");
                        }
                    }
                }
                else if (packetLength == 65)
                {
                    Console.WriteLine("Checking packetLength 65 == " + packetLength);
                    // If its unencrypted, use the NoEncryption class
                    if (buffer[packetOffset] == '\x91' && buffer[packetOffset + 1] == ((m_Seed >> 24) & 0xFF) && buffer[packetOffset + 2] == ((m_Seed >> 16) & 0xFF) && buffer[packetOffset + 3] == ((m_Seed >> 8) & 0xFF) && buffer[packetOffset + 4] == (m_Seed & 0xFF))
                    {
                        if (Configuration.AllowUnencryptedClients)
                        {
                            Encryption = new NoEncryption();
                        }
                    }
                    else
                    {
                        // If it's not an unencrypted packet, simply assume it's encrypted with the seed
                        Encryption = new GameEncryption(m_Seed);

                        byte[] packet = new byte[packetLength];
                        Buffer.BlockCopy(buffer, packetOffset, packet, 0, packetLength);
                        m_Encryption.clientDecrypt(ref packet, packet.Length);
                        Buffer.BlockCopy(packet, 0, buffer, packetOffset, packetLength);
                    }
                }

                // If it's still not initialized, copy the data back to the queue and wait for more
                if (m_Encryption == null)
                {
                    Console.WriteLine("Encryption: Check - Waiting");
                    m_Buffer.Enqueue(buffer, packetOffset, packetLength);
                    length -= packetLength;
                    return;
                }
            }
            #endregion
        }
Example #16
0
        public void VerifyLogin(string packet)
        {
            // TODO: implement check for maintenances
            string[] packetsplit = packet.Split(' ');
            UserDTO  user        = new UserDTO {
                Name = packetsplit[2], Password = ConfigurationManager.AppSettings["UseOldCrypto"] == "true" ? EncryptionBase.Sha512(LoginEncryption.GetPassword(packetsplit[3])).ToUpper() : packetsplit[3]
            };
            AccountDTO loadedAccount = DAOFactory.AccountDAO.LoadByName(user.Name);

            if (loadedAccount != null && loadedAccount.Password.ToUpper().Equals(user.Password))
            {
                DAOFactory.AccountDAO.WriteGeneralLog(loadedAccount.AccountId, _session.IpAddress, null, "Connection", "LoginServer");

                //check if the account is connected
                if (!ServerCommunicationClient.Instance.HubProxy.Invoke <bool>("AccountIsConnected", loadedAccount.Name).Result)
                {
                    AuthorityType type    = loadedAccount.Authority;
                    PenaltyLogDTO penalty = DAOFactory.PenaltyLogDAO.LoadByAccount(loadedAccount.AccountId).FirstOrDefault(s => s.DateEnd > DateTime.Now && s.Penalty == PenaltyType.Banned);
                    if (penalty != null)
                    {
                        _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("BANNED"), penalty.Reason, penalty.DateEnd.ToString("yyyy-MM-dd-HH:mm"))}");
                    }
                    else
                    {
                        switch (type)
                        {
                        case AuthorityType.Unconfirmed:
                        {
                            _session.SendPacket($"fail {Language.Instance.GetMessageFromKey("NOTVALIDATE")}");
                        }
                        break;

                        default:
                        {
                            int newSessionId = SessionFactory.Instance.GenerateSessionId();
                            DAOFactory.AccountDAO.UpdateLastSessionAndIp(user.Name, newSessionId, _session.IpAddress);
                            Logger.Log.DebugFormat(Language.Instance.GetMessageFromKey("CONNECTION"), user.Name, newSessionId);

                            // inform communication service about new player from login server
                            try
                            {
                                ServerCommunicationClient.Instance.HubProxy.Invoke("RegisterAccountLogin", user.Name, newSessionId);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log.Error("General Error SessionId: " + newSessionId, ex);
                            }
                            _session.SendPacket(BuildServersPacket(user.Name, newSessionId));
                        }
                        break;
                        }
                    }
                }
                else
                {
                    _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("ALREADY_CONNECTED"))}");
                }
            }
            else
            {
                _session.SendPacket($"fail {string.Format(Language.Instance.GetMessageFromKey("IDERROR"))}");
            }
        }
        /// <summary>
        /// login packet
        /// </summary>
        /// <param name="loginPacket"></param>
        public void VerifyLogin(LoginPacket loginPacket)
        {
            if (loginPacket == null)
            {
                return;
            }

            UserDTO user = new UserDTO
            {
                Name     = loginPacket.Name,
                Password = ConfigurationManager.AppSettings["UseOldCrypto"] == "true" ? EncryptionBase.Sha512(LoginEncryption.GetPassword(loginPacket.Password)).ToUpper() : loginPacket.Password
            };
            AccountDTO loadedAccount = DaoFactory.AccountDao.LoadByName(user.Name);

            if (loadedAccount != null && loadedAccount.Password.ToUpper().Equals(user.Password))
            {
                DaoFactory.AccountDao.WriteGeneralLog(loadedAccount.AccountId, _session.IpAddress, null, GeneralLogType.Connection, "LoginServer");

                //check if the account is connected
                if (!CommunicationServiceClient.Instance.IsAccountConnected(loadedAccount.AccountId))
                {
                    AuthorityType type    = loadedAccount.Authority;
                    PenaltyLogDTO penalty = DaoFactory.PenaltyLogDao.LoadByAccount(loadedAccount.AccountId).FirstOrDefault(s => s.DateEnd > DateTime.Now && s.Penalty == PenaltyType.Banned);
                    if (penalty != null)
                    {
                        _session.SendPacket($"failc 7");
                    }
                    else
                    {
                        switch (type)
                        {
                        // TODO TO ENUM
                        case AuthorityType.Unconfirmed:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.CantConnect}");
                        }
                        break;

                        case AuthorityType.Banned:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.Banned}");
                        }
                        break;

                        case AuthorityType.Closed:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.CantConnect}");
                        }
                        break;

                        default:
                        {
                            int newSessionId = SessionFactory.Instance.GenerateSessionId();
                            Logger.Log.DebugFormat(Language.Instance.GetMessageFromKey("CONNECTION"), user.Name, newSessionId);

                            if (CommunicationServiceClient.Instance.GetMaintenanceState() && _session.Account.Authority <= AuthorityType.GameMaster)
                            {
                                _session.SendPacket("failc 2");
                                return;
                            }
                            try
                            {
                                CommunicationServiceClient.Instance.RegisterAccountLogin(loadedAccount.AccountId, newSessionId, loadedAccount.Name);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log.Error("General Error SessionId: " + newSessionId, ex);
                            }
                            _session.SendPacket(BuildServersPacket(loadedAccount.AccountId, newSessionId));
                        }
                        break;
                        }
                    }
                }
                else
                {
                    _session.SendPacket($"failc {(byte)LoginFailType.AlreadyConnected}");
                }
            }
            else
            {
                _session.SendPacket($"failc {(byte)LoginFailType.AccountOrPasswordWrong}");
            }
        }
        /// <summary>
        /// The read.
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="packet">
        /// </param>
        public static void Read(Client client, ref byte[] packet)
        {
            MemoryStream m_stream = new MemoryStream(packet);
            BinaryReader m_reader = new BinaryReader(m_stream);

            // now we should do password check and then send OK or Error
            // sending OK now
            m_stream.Position = 12;

            short  userNameLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string userName       = Encoding.ASCII.GetString(m_reader.ReadBytes(userNameLength));
            short  loginKeyLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16());
            string loginKey       = Encoding.ASCII.GetString(m_reader.ReadBytes(loginKeyLength));

            uint characterId = BitConverter.ToUInt32(new[] { packet[11], packet[10], packet[9], packet[8] }, 0);

            LoginEncryption loginEncryption = new LoginEncryption();

            if (loginEncryption.IsValidLogin(loginKey, client.ServerSalt, userName) &&
                loginEncryption.IsCharacterOnAccount(userName, characterId))
            {
                byte[] loginok = LoginOk.Create();
                client.Send(loginok);
            }
            else
            {
                byte[] loginerr = LoginError.Create();
                client.Send(loginerr);
                client.Server.DisconnectClient(client);
                byte[] invalid = BitConverter.GetBytes(characterId);

                ZoneCom.SendMessage(99, invalid);
                return;
            }

            // save characters ID in client - note, this is usually 0 if it is a chat client connecting
            client.Character = new Character(characterId, client);

            // add client to connected clients list
            if (!client.ChatServer().ConnectedClients.ContainsKey(client.Character.CharacterId))
            {
                client.ChatServer().ConnectedClients.Add(client.Character.CharacterId, client);
            }

            // add yourself to that list
            client.KnownClients.Add(client.Character.CharacterId);

            // and give client its own name lookup
            byte[] pname = PlayerName.Create(client, client.Character.CharacterId);
            client.Send(pname);

            // send server welcome message to client
            byte[] anonv = MsgAnonymousVicinity.Create(
                string.Empty,
                string.Format(
                    client.ChatServer().MessageOfTheDay,
                    AssemblyInfoclass.RevisionName + " " + AssemblyInfoclass.AssemblyVersion),
                string.Empty);
            client.Send(anonv);

            client.ChatServer().AddClientToChannels(client);
        }
Example #19
0
        /// <summary>
        /// login packet
        /// </summary>
        /// <param name="loginPacket"></param>
        public void VerifyLogin(LoginPacket loginPacket)
        {
            if (loginPacket == null)
            {
                return;
            }

            UserDTO user = new UserDTO
            {
                Name     = loginPacket.Name,
                Password = ConfigurationManager.AppSettings["UseOldCrypto"] == "true" ? EncryptionBase.Sha512(LoginEncryption.GetPassword(loginPacket.Password)).ToUpper() : loginPacket.Password
            };
            AccountDTO loadedAccount = DAOFactory.AccountDAO.FirstOrDefault(s => s.Name == user.Name);

            if (loadedAccount != null && loadedAccount.Password.ToUpper().Equals(user.Password))
            {
                // TODO LOG LOGIN

                //check if the account is connected
                if (!CommunicationServiceClient.Instance.IsAccountConnected(loadedAccount.AccountId))
                {
                    AuthorityType type    = loadedAccount.Authority;
                    PenaltyLogDTO penalty = DAOFactory.PenaltyLogDAO.FirstOrDefault(s => s.AccountId.Equals(loadedAccount.AccountId) && s.DateEnd > DateTime.Now && s.Penalty == PenaltyType.Banned);
                    if (penalty != null)
                    {
                        _session.SendPacket($"failc 7");
                    }
                    else
                    {
                        switch (type)
                        {
                        // TODO TO ENUM
                        case AuthorityType.Unconfirmed:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.CantConnect}");
                        }
                        break;

                        case AuthorityType.Banned:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.Banned}");
                        }
                        break;

                        case AuthorityType.Closed:
                        {
                            _session.SendPacket($"failc {(byte)LoginFailType.CantConnect}");
                        }
                        break;

                        default:
                        {
                            int newSessionId = SessionFactory.Instance.GenerateSessionId();
                            Logger.Log.DebugFormat(Language.Instance.GetMessageFromKey("CONNECTION"), user.Name, newSessionId);

                            // TODO MAINTENANCE MODE (MASTER SERVER)
                            // IF MAINTENANCE
                            // _session.SendPacket($"failc 2");
                            // inform communication service about new player from login server
                            try
                            {
                                CommunicationServiceClient.Instance.RegisterAccountLogin(loadedAccount.AccountId, newSessionId, loadedAccount.Name);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log.Error("General Error SessionId: " + newSessionId, ex);
                            }
                            _session.SendPacket(BuildServersPacket(loadedAccount.AccountId, newSessionId));
                        }
                        break;
                        }
                    }
                }
                else
                {
                    _session.SendPacket($"failc {(byte)LoginFailType.AlreadyConnected}");
                }
            }
            else
            {
                _session.SendPacket($"failc {(byte)LoginFailType.AccountOrPasswordWrong}");
            }
        }