Ejemplo n.º 1
0
        public bool ReceivedProtocol(networkServer.networkClientInterface NetworkClient, string protocolString)
        {
            Protocol protocol = new Protocol(protocolString);

            switch (protocol.GetKey())
            {
            case 600:
                return(CheckPing(ref NetworkClient, protocol));

            case 500:
                return(AuthenticateUser(NetworkClient, protocol));

            case 701:
                return(HackDetection_Heuristic(NetworkClient, protocol));

            case 702:
                return(HackDetection_VirtualMemory(NetworkClient, protocol));

            case 703:
                return(HackDetection_File(NetworkClient, protocol));

            default:
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, "Received invalid protocol: " + protocolString);
                return(false);
            }
        }
Ejemplo n.º 2
0
        private bool AuthenticateUser(networkServer.networkClientInterface ClientInterface, Protocol prot)
        {
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authenticating new user ({0})", prot.GetUserID()));
            ArrayList Objects = prot.GetValues();

            if (Objects.Count != 4)
            {
                //Log error - protocol size not as expected
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, String.Format("Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                return(false);
            }

            //Computer ID, Computer Architecture, Language, Version
            string ApplicationHash = Objects[1].ToString();
            string architecture    = Objects[2].ToString();
            string language        = Objects[3].ToString();
            double version;

            if (!Double.TryParse(Objects[0].ToString(), out version))
            {
                //Log error - protocol index 3 is not as expected
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, "Double expected but received " + Objects[3].ToString());
                return(false);
            }
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authentification protocol correct. ApplicationHash={0}, Architecture={1}, Language={2}, Version={3}", ApplicationHash, architecture, language, version));

            //Check if user exists and add it to the list
            return(AddUserToActiveConnections(ref ClientInterface, ApplicationHash, prot.GetUserID(), architecture, language, version));
        }
Ejemplo n.º 3
0
 public void NetworkProtocol(ref networkServer.networkClientInterface NetworkClient, string message)
 {
     //Public for the Unit Tests
     CCstData.GetInstance(Application).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Protocol received: " + message);
     try
     {
         //Öañ4\u001b3[\b\nÎbÞö}\u0010VDYZ‚\u009d\u0005sQ˜e@p•\u001e\ab{󥟛¨YÉ`\\wõˆ¹éî\0
         if (message[message.Length - 1] == '\0')
         {
             message = message.Substring(0, message.Length - 1);
         }
         //Decrypt received protocol
         // QUESTION: Can we somehow see if we get something that isn't encrypted like traffic?
         // QUESTION: Is it possible to decrypt something that isn't enchrypted and send it to the ProtocolController?
         // QUESTION: Or does the decryption function checck all this?
         List <char> Chars = message.ToList();
         message = AES_Converter.DecryptFromCBC(CCstData.GetInstance(Application).EncryptionKey, CCstData.GetInstance(Application).EncryptionIV, message);
         if (message[message.Length - 1] == '\0')
         {
             message = message.Substring(0, message.Length - 1);
         }
     }
     catch (Exception e)
     {
         //If decryption failed, something was probably manipulated -> Log it
         CCstData.GetInstance(Application).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.SERVER, "Protocol Decryption failed! Message: " + message + ", Error: " + e.ToString());
         return;
     }
     CCstData.GetInstance(Application).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, "Protocol received decrypted: " + message);
     ProtocolController.ReceivedProtocol(NetworkClient, message);
 }
Ejemplo n.º 4
0
        private bool HackDetection_File(networkServer.networkClientInterface Client, Protocol prot)
        {
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, "File-Detection received. User: "******"F-Detection: User found in the active connections");
                ArrayList Objects = prot.GetValues();
                if (Objects.Count != 2)
                {
                    //Log error - protocol size not as expected
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, String.Format("F-Detection: Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                    SendProtocol("401;5", ClientInterface);
                    KickUser(ClientInterface);
                    return(false);
                }

                //The section ID defines which hack detection method triggered
                int SectionID;
                if (!Int32.TryParse(Objects[0].ToString(), out SectionID))
                {
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, String.Format("F-Detection: Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                    SendProtocol("401;16", ClientInterface);
                    KickUser(ClientInterface);
                }

                string Content = Convert.ToString(Objects[1]);

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "F-Detection: Saved protocol values: CaseID: " + SectionID + ", Content: " + Content);

                int Counter = 0;
                while (!SHackFile.Insert(ClientInterface.User.ID, ClientInterface.User.Application.ID, SectionID, Content))
                {
                    Counter++;
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.DATABASE, String.Format("F-Detection: Insertion in database failed! Attempt: {0}, Protocol: {1}", Counter, prot.GetOriginalString()));
                    if (Counter > 3)
                    {
                        SendProtocol("401;15", ClientInterface);
                        KickUser(ClientInterface);
                        return(false);
                    }
                }

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.DATABASE, "F-Detection: Database interaction successful");
                SendProtocol("400;14", ClientInterface);

                KickUser(ClientInterface);
                return(true);
            }
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.SERVER, "F-Detection: User not found in active connections!");
            SendProtocol("401;17", ClientInterface);
            KickUser(ClientInterface);
            return(false);
        }
Ejemplo n.º 5
0
 public void Start()
 {
     if (TcpServer.startListening())
     {
         CCstData.GetInstance(Application).Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.SERVER, "Server has been started successfully!");
     }
     else
     {
         CCstData.GetInstance(Application).Logger.writeInLog(1, LogCategory.ERROR, Support.LoggerType.SERVER, "The server was not able to start!");
     }
 }
Ejemplo n.º 6
0
        private bool CheckPing(ref networkServer.networkClientInterface Client, Protocol prot)
        {
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Ping: Protocol received. User: "******"Ping: User found in the list.");

                int    AdditionalInfos = prot.HasValues() ? Convert.ToInt32(prot.GetValues()[0]) : -1;
                string AdditionalInfo  = "";
                switch (AdditionalInfos)
                {
                case 1:
                    AdditionalInfo = ";123";
                    break;

                default:
                    break;
                }

                //Reset the Ping timer

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Ping: Resetting timer.");
                Client.ResetPingTimer();
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Ping resetted.");

                //zhCCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, "Additional Infos: "+AdditionalInfo);
                if (AdditionalInfo.Length == 0)
                {
                    SendProtocol("300", Client);
                }
                else
                {
                    SendProtocol(String.Format("301;{0}", AdditionalInfo), Client);
                }

                return(true);
            }

            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.CLIENT, String.Format("Ping: User does not exist in the active connections ({0})", prot.GetUserID()));
            try
            {
                Client.Dispose();
            }
            catch (Exception)
            {
            }
            return(false);
        }
Ejemplo n.º 7
0
        public void SendProtocol(string Protocol, networkServer.networkClientInterface ClientInterface)
        {
            //encrypt protocol
            string EncryptedProt  = AES_Converter.EncryptWithCBC(CCstData.GetInstance(Application).EncryptionKey, CCstData.GetInstance(Application).EncryptionIV, Protocol);
            string LengthAddition = EncryptedProt.Length.ToString();

            while (LengthAddition.Length < 3)
            {
                LengthAddition = "0" + LengthAddition;
            }
            EncryptedProt = LengthAddition + EncryptedProt;
            CCstData.GetInstance(Application).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Protocol encrypted: {0} ({1})", EncryptedProt, Protocol));

            TcpServer.sendMessage(EncryptedProt, ClientInterface);
        }
Ejemplo n.º 8
0
        private bool HackDetection_VirtualMemory(networkServer.networkClientInterface Client, Protocol prot)
        {
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Virtual-Detection received. User: "******"V-Detection: Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                    SendProtocol("401;9", ClientInterface);
                    KickUser(ClientInterface);
                    return(false);
                }

                string BaseAddress   = Convert.ToString(Objects[0]);
                string Offset        = Convert.ToString(Objects[1]);
                string DetectedValue = Convert.ToString(Objects[2]);
                string DefaultValue  = Convert.ToString(Objects[3]);

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, "V-Detection: Saved protocol successfully. Values: BaseAddress: " + BaseAddress + ", Offset: " + Offset + ", DetectedValue: " + DetectedValue + ", DefaultValue: " + DefaultValue);

                int Counter = 0;
                while (!SHackVirtual.Insert(ClientInterface.User.ID, ClientInterface.User.Application.ID, BaseAddress, Offset, DetectedValue, DefaultValue))
                {
                    Counter++;
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.DATABASE, String.Format("V-Detection: Insertion in database failed! Protocol: {0}", prot.GetOriginalString()));
                    if (Counter > 3)
                    {
                        SendProtocol("401;10", ClientInterface);
                        KickUser(ClientInterface);
                        return(false);
                    }
                }
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "V-Detection: Database interaction successful");

                SendProtocol("400;11", ClientInterface);
                KickUser(ClientInterface);
                return(true);
            }
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.SERVER, "V-Detection: User not found in active connections!");
            SendProtocol("401;12", ClientInterface);
            KickUser(ClientInterface);
            return(false);
        }
Ejemplo n.º 9
0
 public void DatabaseLogging()
 {
     try
     {
         for (int i = 0; i < 5; i++)
         {
             CCstData.GetInstance(Core.Application.ID).Logger.writeInLog(1, Support.LogCategory.ERROR, Support.LoggerType.SERVER, "Test" + i.ToString());
             CCstData.GetInstance(Core.Application.ID).Logger.writeInLog(1, Support.LogCategory.CRITICAL, Support.LoggerType.SERVER, "Test" + i.ToString());
             CCstData.GetInstance(Core.Application.ID).Logger.writeInLog(1, Support.LogCategory.OK, Support.LoggerType.SERVER, "Test" + i.ToString());
         }
         Assert.IsTrue(true);
     }
     catch (Exception)
     {
         Assert.Fail();
     }
 }
Ejemplo n.º 10
0
        public static ECollectionLoggerType GetList()
        {
            SqlDataReader oReader = null;

            try
            {
                //Initialize the return object
                ECollectionLoggerType oCollData = new ECollectionLoggerType();

                //Call the request
                using (DBEngine DBInstance = CCstData.GetInstance("").DatabaseEngine)
                {
                    oReader = DBInstance.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_LoggerType_GetList);
                }



                //If there is a result (not null)
                if (oReader != null)
                {
                    while (oReader.Read())
                    {
                        ELoggerType oData = new ELoggerType();
                        //Read the data and convert the SqlDataReader in the waiting object
                        oData = ReadData(oReader);
                        //Add the data to the return list
                        oCollData.Add(oData);
                    }
                }
                return(oCollData);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (oReader != null && !oReader.IsClosed)
                {
                    oReader.Close();
                }
            }
        }
Ejemplo n.º 11
0
        /*public static ECollectionPlayer GetList(EPlayer _pPlayer)
         * {
         *  SqlDataReader oReader = null;
         *  try
         *  {
         *      //Initialize the return object
         *      ECollectionPlayer oCollData = new ECollectionPlayer();
         *
         *      //Fill the request's parameters
         *      SqlParameter[] p_sqlParams = RegisterSqlParameter(_pPlayer);
         *
         *      //Call the request
         *      oReader = CCstDatabase.DatabaseEngine.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_User_GetByName, p_sqlParams);
         *
         *      //If there is a result (not null)
         *      if (oReader != null)
         *      {
         *          while (oReader.Read())
         *          {
         *              EPlayer oData = new EPlayer();
         *              //Read the data and convert the SqlDataReader in the waiting object
         *              oData = ReadData(oReader);
         *              //Add the data to the return list
         *              oCollData.Add(oData);
         *          }
         *      }
         *      return oCollData;
         *  }
         *  catch(Exception e)
         *  {
         *      throw e;
         *  }
         *  finally
         *  {
         *      if (oReader != null && !oReader.IsClosed) oReader.Close();
         *  }
         *
         * }*/

        /*public static EPlayer GetByName(string Name)
         * {
         *  SqlDataReader dataReader = null;
         *
         *  try
         *  {
         *      EPlayer odata = new EPlayer();
         *
         *      SqlParameter[] Param = new SqlParameter[1];
         *      Param[0] = new SqlParameter("@Name", SqlDbType.VarChar);
         *      Param[0].Value = Name;
         *
         *      dataReader = CCstDatabase.DatabaseEngine.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_User_GetByName, Param);
         *
         *      if(dataReader != null)
         *      {
         *          while(dataReader.Read())
         *          {
         *              odata = ReadData(dataReader);
         *          }
         *      }
         *      return odata;
         *  }
         *  catch (SqlException e)
         *  {
         *      throw e;
         *  }
         *  catch (Exception e)
         *  {
         *      throw e;
         *  }
         *  finally
         *  {
         *      if (dataReader != null && !dataReader.IsClosed) dataReader.Close();
         *  }
         * }*/

        public static EPlayer Authenticate(EPlayer _User)
        {
            SqlDataReader oReader = null;

            try
            {
                //Fill the request's parameters
                SqlParameter[] p_sqlParams = RegisterSqlParameter(_User);

                //Call the request
                oReader = CCstData.GetInstance(_User.Application.Hash).DatabaseEngine.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_User_Authenticate, p_sqlParams);

                //If there is a result (not null)
                if (oReader != null)
                {
                    EPlayer oData = new EPlayer();
                    while (oReader.Read())
                    {
                        oData = ReadData(oReader);
                    }

                    if (oData.ID == "-1")
                    {
                        //If an error occurs, ID -1 is given
                        return(null);
                    }
                    return(oData);
                }
                return(null);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (oReader != null && !oReader.IsClosed)
                {
                    oReader.Close();
                }
            }
        }
Ejemplo n.º 12
0
        public static bool Insert(EHackVirtual _pdata)
        {
            SqlDataReader oReader = null;

            try
            {
                //Initialize the return object
                EHackVirtual oData = new EHackVirtual();

                //Fill the request's parameters
                SqlParameter[] p_sqlParams = RegisterSqlParameter(_pdata);

                //Call the request
                oReader = CCstData.GetInstance(_pdata.ApplicationID).DatabaseEngine.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_HackDetection_Insert_VirtualMemory, p_sqlParams);

                //If there is a result (not null)
                if (oReader != null)
                {
                    while (oReader.Read())
                    {
                        //Read the data and convert the SqlDataReader in the waiting object
                        object Test = oReader.GetOrdinal("ID");
                        return(oReader.GetString(oReader.GetOrdinal("ID")) == "0");
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (oReader != null && !oReader.IsClosed)
                {
                    oReader.Close();
                }
            }
        }
Ejemplo n.º 13
0
        public static ELoggerData Insert(ELoggerData iData)
        {
            SqlDataReader oReader = null;

            try
            {
                //Fill the request's parameters
                SqlParameter[] p_sqlParams = RegisterSqlParameter(iData);

                //Call the request
                oReader = CCstData.GetInstance(iData.ApplicationID).DatabaseEngine.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_LoggerData_Insert, p_sqlParams);
                //If there is a result (not null)
                if (oReader != null)
                {
                    ELoggerData oData = new ELoggerData();
                    while (oReader.Read())
                    {
                        oData = ReadData(oReader);
                    }
                    //If an error occurs, ID -1 is given
                    return(oData);
                }
                return(null);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (oReader != null && !oReader.IsClosed)
                {
                    oReader.Close();
                }
            }
        }
Ejemplo n.º 14
0
        bool AddUserToActiveConnections(ref networkServer.networkClientInterface ClientInterface, string ApplicationHash, string ComputerID, string architecture, String language, double version)
        {
            if (!CCstData.InstanceExists(ApplicationHash))
            {
                //Instance does not exist. The player must have manipulated the protocol!
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.SERVER, String.Format("Invalid application hash received in authentification protocol! ComputerID: {0}, ApplicationHash: {1}", ComputerID, ApplicationHash));
                return(false);
            }

            if (CCstData.GetInstance(ApplicationHash).LatestClientVersion != version)
            {
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.ERROR, Support.LoggerType.CLIENT, String.Format("Invalid version! Having {0}, expected {1}. Hardware ID {2}", version, CCstData.GetInstance(ApplicationHash).LatestClientVersion, ComputerID));
                SendProtocol("201;35;Antihack Client version outdated!", ClientInterface);
                return(false);
            }

            ////Check if user is already connected
            //foreach (networkServer.networkClientInterface item in ActiveConnections)
            //{
            //    if(item.User.ID==ComputerID
            //        && item.User.Application.Hash==ApplicationHash)
            //    {
            //        //User is already registered
            //        CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.CLIENT, "Authentification: User is already added to list!");
            //        SendProtocol("201;2;Still logged in. Please try again", ClientInterface);
            //        return false;
            //    }
            //}

            CCstData.GetInstance(ApplicationID).Logger.writeInLog(4, LogCategory.OK, Support.LoggerType.DATABASE, "Authentification: Checking user in the database");
            EPlayer dataClient = SPlayer.Authenticate(ComputerID, ApplicationHash, architecture, language, ClientInterface.IP.ToString());

            CCstData.GetInstance(ApplicationID).Logger.writeInLog(4, LogCategory.OK, Support.LoggerType.DATABASE, "Authentification: User found!");

            if (dataClient == null)
            {
                //If a computer ID exists multiple times in the database, a null object is returned
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.DATABASE, "Authentification: Hardware ID exists multiple times in the database");
                SendProtocol("201;3;Contact Admin", ClientInterface);
                return(false);
            }
            dataClient.Application.Hash = ApplicationHash;

            //Check if user is banned
            if (dataClient.isBanned == true)
            {
                //Do something and dont let him enter
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authentification: Banned user tried to authentificate. User: {0}", dataClient.ID));
                //Send protocol to client that user is banned
                SendProtocol("201;4;Too many hacks", ClientInterface);
                return(false);
            }

            //Add EPlayer to ClientInterface and to the list
            ClientInterface.User = dataClient;

            //Generate unique Session ID for network communication
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Authentification: Start creating a unique session ID");
            while (true)
            {
                string SessionID = AdditionalFunctions.GenerateSessionID(CCstData.GetInstance(ApplicationHash).SessionIDLength);
                //Checks if that connection exists already. Gives back the amount of matching ClientInterfaces
                if (ActiveConnections.Where(Client => Client.SessionID == SessionID).ToList().Count == 0)
                {
                    ClientInterface.SessionID = SessionID;
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, String.Format("New user authentificated! HardwareID: {0}, Session ID: {1}", dataClient.ID, SessionID));
                    break;
                }
            }

            //Add the new connection to the list of connected connections
            ClientInterface.SetPingTimer(CCstData.GetInstance(dataClient.Application.ID).PingTimer, KickUser);

            bool IpExistsAlready = false;

            foreach (var Client in ActiveConnections)
            {
                if (Client.IP == ClientInterface.IP)
                {
                    IpExistsAlready = true;
                }
            }


            //Linux takes ages to connect. Therefore contact the client before it sends another request

            if (!IpExistsAlready)
            {
                if (!CCstData.GetInstance(ApplicationID).GameDLL.AllowUser(ClientInterface.IP, ClientInterface.User.ID))
                {
                    //Do something and dont let him enter
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.GAMEDLL, String.Format("Linux exception failed. User: {0}", dataClient.ID));
                    //Send protocol to client that user is banned
                    SendProtocol("201;30;Access verification failed", ClientInterface);
                    return(false);
                }
            }
            else
            {
                CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authentication: IP already exists ({0})", ClientInterface.IP.ToString()));
            }

            ActiveConnections.Add(ClientInterface);

            SendProtocol("200;" + ClientInterface.SessionID, ClientInterface);
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authenticated new user. Computer ID: {0}, Session ID: {1}", ClientInterface.User.ID, ClientInterface.SessionID));

            /*if (!IpExistsAlready)
             * {
             *  //If there is already an IP exception, we dont need another
             *  try
             *  {
             *      ClientInterface.unixSshConnectorAccept.Connect();
             *  }
             *  catch (Exception)
             *  {
             *
             *  }
             *  if (ClientInterface.unixSshConnectorAccept.IsConnected)
             *  {
             *      List<int> Ports = new List<int>();
             *      Ports.Add(50001);
             *      Ports.Add(50002);
             *      Ports.Add(50003);
             *      Ports.Add(50004);
             *      Ports.Add(50005);
             *      Ports.Add(50006);
             *      Ports.Add(50007);
             *      Ports.Add(50008);
             *      Ports.Add(50009);
             *      Ports.Add(50010);
             *      Ports.Add(50011);
             *      Ports.Add(50012);
             *      Ports.Add(50013);
             *      Ports.Add(50014);
             *      Ports.Add(50015);
             *      Ports.Add(50016);
             *      Ports.Add(50017);
             *      Ports.Add(50018);
             *      Ports.Add(50019);
             *      Ports.Add(50020);
             *      string LinuxPorts = "";
             *      foreach (int item in Ports)
             *      {
             *          LinuxPorts += "iptables -I INPUT -p tcp -s " + ClientInterface.IP + " --dport " + item + " -j ACCEPT && ";
             *      }
             *      if(LinuxPorts.Length > 0)
             *      {
             *          LinuxPorts = LinuxPorts.TrimEnd(' ');
             *          LinuxPorts = LinuxPorts.TrimEnd('&');
             *          using (SshCommand Result = ClientInterface.unixSshConnectorAccept.RunCommand(LinuxPorts))
             *          {
             *              if (Result.Error.Length > 0)
             *                  CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.GAMEDLL, "Linux exception failed! Session ID: " + ClientInterface.SessionID + ", Error: " + Result.Error);
             *              else
             *                  CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.GAMEDLL, "Linux exception successful. Session ID: " + ClientInterface.SessionID + ", Result: " + Result.Result);
             *          }
             *      }
             *
             *      ClientInterface.unixSshConnectorAccept.Disconnect();
             *  }
             *  else
             *  {
             *      //Fehlerinfo
             *      CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.CLIENT, "Client could not be connected to the Linux Server. Session ID: " + ClientInterface.SessionID);
             *      return false;
             *  }
             * }
             * else
             * {
             *  string AllIPs = "";
             *  foreach (var item in ActiveConnections)
             *  {
             *      AllIPs += String.Format(" User: {0}, IP: {1} -", item.User.ID, item.IP);
             *  }
             *  CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, String.Format("Authentication: IP already exists ({0})", AllIPs));
             * }*/

            return(true);
        }
Ejemplo n.º 15
0
        void KickUser(networkServer.networkClientInterface ClientInterface)
        {
            //System.Threading.Thread.Sleep(1000);

            bool IpExistsAlready = false;

            foreach (var item in ActiveConnections)
            {
                if (item.IP == ClientInterface.IP)
                {
                    if (item.SessionID != ClientInterface.SessionID)
                    {
                        IpExistsAlready = true;
                    }
                }
            }

            string t1 = ClientInterface.User.ID;
            string t2 = ClientInterface.SessionID;

            CCstData.GetInstance(ClientInterface.User.Application.ID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, String.Format("User disconnected. {0} - {1}", t1, t2));
            ActiveConnections.Remove(ClientInterface);

            if (!IpExistsAlready)
            {
                if (!CCstData.GetInstance(ApplicationID).GameDLL.KickUser(ClientInterface.IP, ClientInterface.User.ID))
                {
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.GAMEDLL, String.Format("Linux exception removal failed. IP {0}, User: {1}", ClientInterface.IP, ClientInterface.User.ID));
                }
            }

            /*if (!IpExistsAlready)
             * {
             *  //If there is another user with the same IP, we have to keep it in the IPTables
             *  try
             *  {
             *      ClientInterface.unixSshConnectorAccept.Connect();
             *  }
             *  catch (Exception e)
             *  {
             *  }
             *  if (!ClientInterface.unixSshConnectorAccept.IsConnected)
             *  {
             *      //Log error
             *
             *  }
             *  List<int> Ports = new List<int>();
             *  Ports.Add(50001);
             *  Ports.Add(50002);
             *  Ports.Add(50003);
             *  Ports.Add(50004);
             *  Ports.Add(50005);
             *  Ports.Add(50006);
             *  Ports.Add(50007);
             *  Ports.Add(50008);
             *  Ports.Add(50009);
             *  Ports.Add(50010);
             *  Ports.Add(50011);
             *  Ports.Add(50012);
             *  Ports.Add(50013);
             *  Ports.Add(50014);
             *  Ports.Add(50015);
             *  Ports.Add(50016);
             *  Ports.Add(50017);
             *  Ports.Add(50018);
             *  Ports.Add(50019);
             *  Ports.Add(50020);
             *
             *  string LinuxPorts = "";
             *  foreach (int item in Ports)
             *  {
             *      LinuxPorts += "iptables -D INPUT -p tcp -s " + ClientInterface.IP + " --dport " + item + " -j ACCEPT && ";
             *  }
             *  if (LinuxPorts.Length > 0)
             *  {
             *      LinuxPorts=LinuxPorts.TrimEnd(' ');
             *      LinuxPorts=LinuxPorts.TrimEnd('&');
             *      using (SshCommand Result = ClientInterface.unixSshConnectorAccept.RunCommand(LinuxPorts))
             *      {
             *          if (Result.Error.Length > 0)
             *              CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.GAMEDLL, "Linux exception deny failed! Session ID: " + ClientInterface.SessionID + ", Error: " + Result.Error);
             *          else
             *              CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.GAMEDLL, "Linux exception deny successful. Session ID: " + ClientInterface.SessionID+", Result: "+Result.Result);
             *      }
             *  }
             *  ClientInterface.unixSshConnectorAccept.Disconnect();
             * }*/

            ClientInterface.Dispose();
        }
Ejemplo n.º 16
0
        private bool HackDetection_Heuristic(networkServer.networkClientInterface Client, Protocol prot)
        {
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.SERVER, "Heuristic-Detection received. User: "******"H-Detection: User found in the active connections");
                ArrayList Objects = prot.GetValues();
                if (Objects.Count != 2)
                {
                    //Log error - protocol size not as expected
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, String.Format("H-Detection: Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                    SendProtocol("401;5", ClientInterface);
                    KickUser(ClientInterface);
                    return(false);
                }

                //The section ID defines which hack detection method triggered
                int SectionID;
                if (!Int32.TryParse(Objects[0].ToString(), out SectionID))
                {
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.CLIENT, String.Format("H-Detection: Unexpected size of protocol. Expected are 4 but it was {0}. Protocol: {1}", Objects.Count, prot.GetOriginalString()));
                    SendProtocol("401;13", ClientInterface);
                    KickUser(ClientInterface);
                }

                string ProcessName = null;
                string WindowName  = null;
                string ClassName   = null;
                string MD5Value    = null;

                switch (SectionID)
                {
                case 1:
                    ProcessName = Convert.ToString(Objects[1]);
                    break;

                case 2:
                    MD5Value = Convert.ToString(Objects[1]);
                    break;

                default:
                    break;
                }

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.OK, Support.LoggerType.SERVER, "H-Detection: Saved protocol values: ProcessName: " + ProcessName + ", WindowName: " + WindowName + ", ClassName: " + ClassName + ", MD5Value: " + MD5Value);

                int Counter = 0;
                while (!SHackHeuristic.Insert(ClientInterface.User.ID, ClientInterface.User.Application.ID, ProcessName, WindowName, ClassName, MD5Value))
                {
                    Counter++;
                    CCstData.GetInstance(ApplicationID).Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.DATABASE, String.Format("H-Detection: Insertion in database failed! Attempt: {0}, Protocol: {1}", Counter, prot.GetOriginalString()));
                    if (Counter > 3)
                    {
                        SendProtocol("401;6", ClientInterface);
                        KickUser(ClientInterface);
                        return(false);
                    }
                }

                CCstData.GetInstance(ApplicationID).Logger.writeInLog(3, LogCategory.OK, Support.LoggerType.DATABASE, "H-Detection: Database interaction successful");
                SendProtocol("400;8", ClientInterface);

                KickUser(ClientInterface);
                return(true);
            }
            CCstData.GetInstance(ApplicationID).Logger.writeInLog(2, LogCategory.ERROR, Support.LoggerType.SERVER, "H-Detection: User not found in active connections!");
            SendProtocol("401;7", ClientInterface);
            KickUser(ClientInterface);
            return(false);
        }
Ejemplo n.º 17
0
        //Konstruktor
        /// <summary>
        /// To initial the core we need to know many parameters to be flexible for different clients.
        /// We for example want the client to decide where to save the log file
        /// </summary>
        /// <param name="_ApplicationName"></param> Name of the application, that each client can have more then one game running on this server
        /// <param name="LatestClientVersion"></param> ////////////////////////////////////////// what is this for? usecase?
        /// <param name="_iPort"></param> port for connection to the clients. Connection is made with the NetworkServer
        /// <param name="_cProtocolDelimiter"></param> This is the delemiter used to seperate the values of each protocol for the client site! Only the c code is using this dilimiter. The recieved protocols have all ; as delemiter
        /// <param name="_EncryptionKey"></param> ///////////////////////////////////////////////
        /// <param name="_EncryptionIV"></param> ////////////////////////////////////////////////
        /// <param name="_PingTimer"></param> The client can decide how often the clients need to ping, e.g. every second. This is to check if the client somehow killed our application
        /// <param name="SessionLength"></param> How long shall be the session ID, that is generated randomly
        /// <param name="_sDatabaseDriver"></param> only mssql supported yet. Mysql in planning
        /// <param name="_sDBHostIp"></param> ///////////////////////////////////////////////////
        /// <param name="_sDBPort"></param> /////////////////////////////////////////////////////
        /// <param name="_sDBUser"></param> /////////////////////////////////////////////////////
        /// <param name="_sDBPass"></param> /////////////////////////////////////////////////////
        /// <param name="_sDBDefaultDB"></param> ////////////////////////////////////////////////
        /// <param name="_sLogPath"></param> Where is the logging file going to be saved
        /// <param name="LogLevel"></param> What level shall be logged? Everything = 3, All but debug = 2, Critical and Error = 1, only critical = 0
        /// <param name="PathGameDll"></param> Where is the game specific dll saved? This is needed for dynamicaly use functions for all kind of games like blocking a user.
        public ControllerCore(string _ApplicationName, int LatestClientVersion, short _iPort, char _cProtocolDelimiter, string _EncryptionKey, string _EncryptionIV, int _PingTimer, int SessionLength, string _sDatabaseDriver,
                              string _sDBHostIp, short _sDBPort, string _sDBUser, string _sDBPass, string _sDBDefaultDB, string _sLogPath, int LogLevel, string PathGameDll)
        {
            //Logging initialisations
            Support.logWriter Logger = new logWriter(_sLogPath, LogLevel);
            Logger.Seperate();
            Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.SERVER, "Logging class initialized!");
            DBEngine dBEngine = null;

            //Database Initialisations
            if (_sDatabaseDriver == "mysql")
            {
                // mysql isn't supported yet
                // CCstDatabase.DatabaseEngine = new DBMysqlDataManager(_sDBHostIp,_sDBUser,_sDBPass,_sDBPort,_sDBDefaultDB);
            }
            else if (_sDatabaseDriver == "mssql")
            {
                // create the mssql manager
                dBEngine = new DBMssqlDataManager(_sDBHostIp, _sDBUser, _sDBPass, _sDBPort, _sDBDefaultDB);
            }


            //Database test
            if (dBEngine.testDBConnection())
            {
                Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.DATABASE, "Database test successfull!");
            }
            else
            {
                Logger.writeInLog(1, LogCategory.ERROR, Support.LoggerType.DATABASE, "Database test was not successfull!");
                return;
            }
            // try to get the application ID for the given application out of the DB
            Application = SApplication.GetByName(_ApplicationName, dBEngine);
            // QUESTION: usually the procedure creates a new ID for a new application so this case should never apear?
            if (Application == null)
            {
                Logger.writeInLog(1, LogCategory.ERROR, Support.LoggerType.DATABASE, "The application name was not found in the database!");
                return;
            }

            Logger.ApplicationID = Application.ID;
            // Create a new config object to be able to use specific functions like logging in all classes by getting the insance via application information
            CCstData Config = new CCstData(Application, dBEngine, Logger);

            // test if connection to database is still working after safing it in the config
            if (CCstData.GetInstance(Application.ID).DatabaseEngine.testDBConnection())
            {
                CCstData.GetInstance(Application.ID).Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.SERVER, "Instance successfully created!");
            }
            else
            {
                Logger.writeInLog(1, LogCategory.ERROR, Support.LoggerType.SERVER, "Instance could not be created!");
                return;
            }

            // fill the config with the needed values
            CCstData.GetInstance(Application.ID).LatestClientVersion = LatestClientVersion;
            CCstData.GetInstance(Application.ID).EncryptionKey       = _EncryptionKey;
            CCstData.GetInstance(Application.ID).EncryptionIV        = _EncryptionIV;
            CCstData.GetInstance(Application.ID).PingTimer           = _PingTimer;
            CCstData.GetInstance(Application.ID).SessionIDLength     = SessionLength;

            // Check if the user really included the path with the needed URL.
            if (!File.Exists(PathGameDll))
            {
                // this would be a critical error because we need the functions of the DLL to be a productive server
                Logger.writeInLog(1, LogCategory.CRITICAL, LoggerType.SERVER, String.Format("Game Dll not found! Path: {0}", PathGameDll));
                return;
            }
            // create the path to the config file. It always MUST have the name: config.ini
            string ConfigPath = Path.Combine(Path.GetDirectoryName(PathGameDll), "config.ini");

            if (!File.Exists(ConfigPath))
            {
                // this would be a critical error because we need the functions of the config file to be a productive server
                Logger.writeInLog(1, LogCategory.CRITICAL, Support.LoggerType.SERVER, String.Format("Game Config file not found! Path: ", ConfigPath));
                return;
            }
            // save the found DLL in our universal config object
            CCstData.GetInstance(Application).GameDLL = new Utility.ApplicationAdapter(Path.GetFullPath(PathGameDll), Application);
            // check if the constructor of the given DLL is working. This is important to make sure that we included the right DLL
            if (!CCstData.GetInstance(Application).GameDLL.ConstructorSuccessful)
            {
                return;
            }

            CCstData.GetInstance(Application).GameDLL.PrepareServer(ConfigPath);



            //Block Linux Ports

            /*SshClient unixSshConnectorAccept = new SshClient(LinuxIP, LinuxPort, LinuxLogin, LinuxPass);
             *
             * try
             * {
             *  unixSshConnectorAccept.Connect();
             *  if (!unixSshConnectorAccept.IsConnected)
             *      return;
             *  unixSshConnectorAccept.RunCommand("/root/.firewall.sh");
             *  Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.GAMEDLL, "IP Table command executed!");
             *  //if (Res.Error.Length != 0)
             *      //CCstData.GetInstance(Application).Logger.writeInLog(1, LogCategory.CRITICAL, LoggerType.GAMEDLL, "Cannot execute start command!");
             * }
             * catch (Exception e)
             * {
             *  Logger.writeInLog(1, LogCategory.ERROR, Support.LoggerType.GAMEDLL, "Cannot connect to Linux Server");
             *  return;
             * }
             * finally
             * {
             *  unixSshConnectorAccept.Disconnect();
             * }
             *
             * string PuttyStringBuilder = "";
             * //PuttyStringBuilder += " service iptables stop";
             * //PuttyStringBuilder += " && iptables -F";
             * //PuttyStringBuilder += " && iptables -Z";
             * //PuttyStringBuilder += " && iptables -X";
             * //PuttyStringBuilder += " && iptables -A INPUT -p tcp --destination-port 80 -j DROP";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 112.211.180.233 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 62.138.6.50 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 167.88.15.104 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 142.44.136.74 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 169.255.124.234 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 169.255.124.206 -j ACCEPT";
             * //PuttyStringBuilder += " && iptables -I INPUT -p all -s 167.88.15.102 -j ACCEPT";
             * //PuttyStringBuilder += " && service iptables save";
             * //PuttyStringBuilder += " && service iptables start";
             *
             * //SshCommand testing = unixSshConnectorAccept.RunCommand(PuttyStringBuilder);
             * //string Result1 = testing.Result;
             * //string Err = testing.Error;
             * //SshCommand test = unixSshConnectorAccept.RunCommand("service iptables stop");
             *
             * //SshCommand Test4 = unixSshConnectorAccept.RunCommand("cd ../etc/ppp/");
             * //SshCommand Test3 = unixSshConnectorAccept.RunCommand("ls -l");
             * //string Res = Test3.Result;
             * //string Res2 = Test2.Result;
             *
             * //SshCommand Test1=unixSshConnectorAccept.RunCommand("./PX2000.sh");
             * //string Error = Test1.Error;
             * //string Error2 = Test2.Error;
             *
             *
             *
             * //Clear IPTables
             * //unixSshConnectorAccept.RunCommand("iptables -F");
             * //unixSshConnectorAccept.RunCommand("iptables -Z");
             * //unixSshConnectorAccept.RunCommand("iptables -X");
             * //unixSshConnectorAccept.RunCommand("iptables -F FORWARD");
             *
             * //unixSshConnectorAccept.RunCommand("iptables -F OUTPUT");
             * //Block World-Ports
             * if (DeactivatePortBlocking)
             *  return;
             *
             * List<string> Ports = new List<string>();
             * Ports.Add("12001");
             * Ports.Add("12002");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * Ports.Add("12003");
             * //Ports.Add("entextnetwk");
             *
             *
             * foreach (string item in Ports)
             * {
             *  //Bestimmte Ports blocken
             *  //unixSshConnectorAccept.RunCommand("iptables -I INPUT -p tcp --dport " + item + " -j DROP");
             *  //unixSshConnectorAccept.RunCommand("iptables -A INPUT -p tcp --destination-port " + item + " -j DROP");
             * }
             *
             * //unixSshConnectorAccept.RunCommand("service iptables save");
             * //unixSshConnectorAccept.RunCommand("service iptables start");
             *
             * //unixSshConnectorAccept.Disconnect();
             */

            //Network Initialisations, this list includes all active connections to the client part of our project
            // this is needed for sending them protocols because there is no permanent connection to each client
            // it is also needed to check if all of them are still pinging
            ActiveConnections       = new List <networkServer.networkClientInterface>();
            sAesKey                 = "";
            this.cProtocolDelimiter = _cProtocolDelimiter;
            this.cDataDelimiter     = _cProtocolDelimiter;
            TcpServer               = new networkServer(NetworkProtocol, sAesKey, Application.ID, IPAddress.Any, _iPort, AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // QUESTION: What is this doing?
            ProtocolController.SendProtocol += this.SendProtocol;
            Logger.writeInLog(1, LogCategory.OK, Support.LoggerType.SERVER, "TCP Server ready for start!");
            Logger.Seperate();
            ProtocolController = new ProtocolController(ref ActiveConnections, Application.ID);


            /*//TESTCASE
             * networkServer.networkClientInterface dummy = new networkServer.networkClientInterface();
             * //Registration
             * ProtocolController.ReceivedProtocol(dummy, "500;98765;Test;Windoofs 7;Deutsch;1");
             * string SessionID = "ASDASD";
             * ActiveConnections[0].SessionID = SessionID;
             *
             * ProtocolController.ReceivedProtocol(dummy, String.Format("600;{0}", SessionID));
             * System.Threading.Thread.Sleep(1000);
             * ProtocolController.ReceivedProtocol(dummy, String.Format("600;{0}", SessionID));
             *
             * //ProtocolController.ReceivedProtocol(dummy, String.Format("701;{0};Prozess", SessionID));
             *
             * dummy.SessionID = SessionID;
             * ProtocolController.ReceivedProtocol(dummy, String.Format("701;{0};Process;Window;Class;MD5",SessionID));
             */
            //Auth
            //  networkProtocol("#104;Anderson2;Lars;Pickelin;miau1234;[email protected]", ref dummy);
            //  networkProtocol("#102;Anderson2;miau1x234", ref dummy);
            //Content
            //Get all rooms
            //  networkProtocol("#201", ref dummy);
            //Get all rooms of a specific user
            //  NetworkProtocol("#218", ref dummy);
            //Add new or update room
            //NetworkProtocol("#203;5;1;Avelinas Test raum;Hallo Welt;1;http://www.AvelinaLerntArrays.net", ref dummy);
            //Get all workouts of room id 2
            //  NetworkProtocol("#205;Hadd e", ref dummy);
            //Get Levels of workout with id 1
            //  NetworkProtocol("#207;1", ref dummy);
            //Get all excercises of workout 1
            //  NetworkProtocol("#209;1", ref dummy);
            //Delete room
            //NetworkProtocol("#213;114", ref dummy);
        }
Ejemplo n.º 18
0
 public bool PrepareServer(string ConfigPath)
 {
     return((bool)_PrepareServer.Invoke(_adapter, new object[3] {
         ConfigPath, Application.Name, CCstData.GetInstance(Application).Logger.writeLog
     }));
 }