public static Tuple <string, string> setNewAgentPassword(SecureString new_password)
    {
        /* With the given password return the corresponding hash with a new salt (which will have to be saved into the database)*/
        string salt            = DataProtection.getSaltForHashes();
        string hashed_password = DataProtection.getSaltHashedString(new_password, salt);

        return(Tuple.Create(hashed_password, salt));
    }
    public static bool certifyConnection(string id, SecureString secure_given_password, string ip_adress)
    {
        /* When online user want to change his account information, he have to enter is id and password again
         * to validate the changes.
         * When the user send us the changes with its actual id and password we check into the database if the id and the password
         * are the same for that agent than the one saved
         * The agent information from database are the one who was connected previously. In other word, only the user who register to acces
         * the app can change its account informations from the current session
         *
         * If the authentification informations matches the method return true, else false
         */

        bool certification = false;                                 //resul

        int   index         = getIndexAgentFromIpAdress(ip_adress); //can  not be equal to -1 because all agent are registered before the call of that function
        Agent current_agent = client_list[index];                   //get the agent infromation from the current open registered session
        Agent needed_agent  = database.getAgentByAuthentificationId(id);

        /* Get the informations of the agent found by the given id (into the database)
         * and not from the current agent because we want user to modify their account informations only from their own session and not from
         * other user session
         */


        //Hash the password with salt saved in the database
        if (needed_agent.hashedPassword != DataProtection.getSaltHashedString(secure_given_password, needed_agent.saltForHashe))
        {//if the stored hashe password is not equal to the given hashe password (with the salt saved in the database)
            //if user try too many times to changes its account informations with the wrong actual authentification informations we block that Ip adress
            setNewAttempForAgent(ref current_agent);
            certification = false;
        }
        else
        {
            //agent was found into the database
            current_agent.numberOfConnectionAttemps = 0;
            certification = true;
        }

        client_list[index] = current_agent;//save informations
        //again index will never be out of range

        return(certification);
    }
    public static int setConnection(string id, SecureString secure_given_password)
    {
        /*When a user is physically connected to the app we retrieve all the information about him in a structure Agent from the database
         * If an agent is find in the database from the input id and password (given after being in an hashing function)
         * then we set a timer (that represent the connection time left before disconection ) and save temporarily all the informations in a structure
         */

        if (id == "" || secure_given_password == null)
        {
            connected_agent.toDefault();

            return(ToolsClass.Definition.ERROR_INT_VALUE);;
        }


        Agent agent = database.getAgentByAuthentificationId(id);

        if (agent.error)
        {
            return(ToolsClass.Definition.ERROR_INT_VALUE);
        }


        //Hash the password with salt saved in the database
        if (agent.hashedPassword != DataProtection.getSaltHashedString(secure_given_password, agent.saltForHashe))
        {                      //if the stored hashe password is not equal to the given hashe password (with the salt saved in the database)
            agent.toDefault(); //reset agent
        }


        if (agent.tableId != -1)     //agent is found
        {
            connected_agent = agent; //save temporarily the information

            return(ToolsClass.Definition.NO_ERROR_INT_VALUE);
        }
        else
        {
            connected_agent.toDefault();
        }

        return(ToolsClass.Definition.ERROR_INT_VALUE);
    }
    public static Agent setOnlineConnection(string id, SecureString secure_given_password, string ip_adress)
    {
        /* When client try to establish a connection as a registered agent, he send his id and password.
         * Then we check in the database those informations matches with an agent into the database
         * If yes we gather all information about that agent into a structure and save it into a list "client_list"
         * and the information will stay in it until the client disconnect himself or the session expired
         * If no we save the ip adress of the client and update his number of attemps into the list "client_list"
         *
         *
         * If agent was found into the database that function return it
         * else retrun a standard agent with default values set
         *
         * On the server side, we have mutiple possible cases :
         *  - agent is recognise as registered agent into the database
         *  - agent is unknown but try to connect
         *  - agent is banned (because he fails to many time to connect)
         * All agents are (temporarily) indistinctly stored into memory (trough the list "client_list")
         * We can differianciate agent because of its internal parameters that are not the same if the agent is registered or banned or unknown
         * We delete those informations from memory only when user states evoluate (for exemple if agent has been banned but now he wait enough time
         * we remove information about that user from memory or when agent is disconnected we remove its informations)
         * In orther words, the only way to if agent is registered (so allow to access the website) is to look if the ip adress is saved in memory
         * and if he is not banned.
         *
         * The case "unknown agent" held to figure out the number of attemps client did : in that case we stored the ip adress and increase
         * the number of attemps by one each time he fails to connect. Then when he try again but the number of attemps is too high that client
         * became banned. In fact, if agent try to connect few time the ip adress of the user computer will be stored as long as a new agent
         * use the same computer and succeed in connecting with the server. In otherwise, the informations will remain into memory
         * The banishment is not assiociate to the a windows session but to a computer
         * But when agent is registered he is from its windows session on a specific computer (and not only from the computer)
         *
         * This is the only function that can add a new user
         *
         */

        Agent agent = new Agent();

        agent.toDefault();

        if (id == "" || secure_given_password == null)
        {
            return(agent);
        }

        /*When the database is not used form a while the cache are clear (the database become "cold")
         * So after a certain time if a user try to connect to the database it will have to wait
         * that the database end to load and then wait to have the result of the request
         * But the needed amount of time will almost always overpass the maximun connection time of the databse
         * which will procude an error
         */
        agent = database.getAgentByAuthentificationId(id);//could return an agent with error set to true

        if (agent.error)
        {//error from the server (not the fault of the client)
            return(agent);
        }

        //Hash the password with salt saved in the database
        if (agent.hashedPassword != DataProtection.getSaltHashedString(secure_given_password, agent.saltForHashe))
        {                      //if the stored hashe password is not equal to the given hashe password (with the salt saved in the database)
            agent.toDefault(); //reset agent
        }

        int index = getIndexAgentFromIpAdress(ip_adress);

        if (index == -1)//add new user
        {
            Agent temp_agent = new Agent();
            temp_agent.toDefault();

            setEssentialParmsForAgent(ref temp_agent, ip_adress);
            client_list.Add(temp_agent);
            index = client_list.Count - 1;
        }


        if (agent.tableId == -1)
        {//there is no corresponding agent into the database (wrong id or password or both)
            agent = client_list[index];

            /*All client that send a request to the server are saved into memory with there ip adress
             * So at that step when we search for a client define by its ip adress the result
             * will never be out of range
             */
            setNewAttempForAgent(ref agent);

            /* If the user fail to connect we already have its information into memory
             * In this case, we update the information abour that agent
             * We can not directly add the agent into the database because agent are found by their ip adress (at the first match)
             * In other words, if we have multiple agent set in memory with the same ip adress just one will be retrieve
             */
        }
        else
        {
            //agent was found into the database
            agent.numberOfConnectionAttemps = 0;
            //reset the number of attemp
            agent.sessionId = setCookiesForClient();
            //all the cookie are set at the connection and will remain the same until the next connection
        }


        setEssentialParmsForAgent(ref agent, ip_adress);
        //registerAgentNewAttemp use agent.lastConnectionTime so order insctruction is here important and setEssentialParmsForAgent() update lastConnectionTime


        client_list[index] = agent;
        //again index will never be out of range
        return(agent);
    }
Пример #5
0
        private void EmptyAdmin()
        {
            DataBase dataBase = new DataBase();

            //check if there is no agents (because it's the first use of the app or the database has been reset
            int numberAgent = dataBase.getNumberAgent();

            if (numberAgent == -1)
            {
                MessageBox.Show("Vérifier les paramètres de connexion à la base de données");
                return;
            }
            if (numberAgent != 0)// get the number of not deleted agent (computer agent excluded)
            {
                return;
            }

            //add default user for automatic task and admin
            using (var form = new AdminSetupBox())//get admin info
            {
                var result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    //set admin short secure id
                    SecureString short_secure_id_secureString = new SecureString();
                    String       short_secure_id = SecurityManager.setAgentShortSecureId();
                    foreach (char c in short_secure_id)
                    {
                        short_secure_id_secureString.AppendChar(c);
                    }
                    short_secure_id_secureString.MakeReadOnly();


                    //get encrypted value
                    string salt               = DataProtection.getSaltForHashes();
                    string hash_password      = DataProtection.getSaltHashedString(form.admin_password, salt);
                    string encrypted_short_id = DataProtection.protect(short_secure_id_secureString);
                    form.admin_password.Dispose();
                    short_secure_id_secureString.Dispose();


                    //add agents into the database
                    Tools.Agent agent = new Tools.Agent();

                    //default agent for automatic use only
                    agent.toDefault();
                    Random rand = new Random();
                    agent.lastName  = "Poste";
                    agent.firstName = "Informatisé";
                    agent.id        = Definition.COMPUTER_AUTHENTIFICATION_ID_DATABASE;
                    agent.setRigth(-1);
                    //add agent
                    if (dataBase.addNewAgent(agent) != Definition.NO_ERROR_INT_VALUE)
                    {
                        MessageBox.Show("Impossible d'ajouter un nouvel agent");
                        return;
                    }
                    //update database table id for the computer agent
                    Definition.COMPUTER_TABLE_ID_DATABASE = dataBase.getComputerTableId();

                    //add admin
                    agent.toDefault();

                    agent.firstName = form.admin_firstName;
                    agent.lastName  = form.admin_lastName;
                    agent.job       = "DEUS EX";
                    agent.setRigth(0);
                    agent.mailAdress     = "none";
                    agent.id             = form.admin_id;
                    agent.hashedPassword = hash_password;
                    agent.saltForHashe   = salt;
                    agent.shortSecureId  = encrypted_short_id;
                    //add agent
                    if (dataBase.addNewAgent(agent) != Definition.NO_ERROR_INT_VALUE)
                    {
                        MessageBox.Show("Impossible d'ajouter un nouvel agent");
                        return;
                    }

                    MessageBox.Show("La création du compte administrateur s'est terminée avec succès.\nVotre identifiant est : " + form.admin_id);
                }
                else
                {
                    MessageBox.Show("la création du compte administrateur a echouée");
                    return;
                }
            }
        }
Пример #6
0
        private void save_change_button_Click(object sender, EventArgs e)
        {
            if (!isDataCorrect())//if all the given data is correct
            {
                return;
            }


            int res;

            //save all the current information into a strcture
            agent.lastName   = last_name_textBox.Text;
            agent.firstName  = first_name_textBox.Text;
            agent.job        = job_textBox.Text;
            agent.mailAdress = mail_adress_textBox.Text;
            agent.setIntRightFromString(right_checkedListBox.CheckedItems[0].ToString());
            agent.id = id_textBox.Text;

            if (password_textBox.Text.Replace(" ", "").Length != 0)//password has been changed
            {
                SecureString password = new SecureString();
                foreach (char c in password_textBox.Text)
                {
                    password.AppendChar(c);
                }
                password.MakeReadOnly();

                //create hash for the password
                string salt = DataProtection.getSaltForHashes();
                agent.hashedPassword = DataProtection.getSaltHashedString(password, salt);
                agent.saltForHashe   = salt;
                //hashed the password
                if (password != null)
                {
                    password.Dispose();
                }
            }

            //send mail to the agent about all his confidential data
            string subject;
            string body = "";

            if (agent.tableId == -1)//if user add a new agent we automatically set a new short id for him
            {
                //user cannot create an account with higher priviledges
                if (!SecurityManager.rightLevelEnoughToAccesSystem(SecurityManager.getConnectedAgentRight(), agent.getRight()))
                {
                    MessageBox.Show("Vous ne pouvez pas créer un compte de plus haut privilege que le votre");
                    return;
                }

                agent.shortSecureId = SecurityManager.setAgentShortSecureId();
                res = database.addNewAgent(agent);

                subject = "Création de votre compte";

                body = agent.lastName.ToUpper() + " " + agent.firstName.ToLower() + " (" + agent.job.ToUpper() + ") : "
                       + "<br> L'agent " + SecurityManager.getFormatedSessionInfo() + " vient de créer votre compte"
                       + "<br><br>Identifiant : " + id_textBox.Text
                       + "<br>Mot de passe : " + password_textBox.Text
                       + "<br>Code d'identification : " + DataProtection.ToInsecureString(DataProtection.unprotect(agent.shortSecureId))
                       + "<br><br>Le code d'identification est unique et ne peut être changé pour des raisons de sécurité.";
            }
            else
            {
                //user cannot edit an account with higher or equal priviledges (except for the maximun privildge right user)
                if (SecurityManager.getConnectedAgentRight() != SecurityManager.RIGHTS_LIST.LastIndexOf(SecurityManager.RIGHT_DEUS))
                {
                    //an user cannot delete an account with higer or equal priviledges
                    if (SecurityManager.getConnectedAgentRight() == agent.getRight() || !SecurityManager.rightLevelEnoughToAccesSystem(SecurityManager.getConnectedAgentRight(), agent.getRight()))
                    {
                        MessageBox.Show("Vous ne disposez pas des droits éditer un compte de plus haut (ou égal) privilège");
                        return;
                    }
                }

                res = database.updateAgent(agent);

                //send mail to the user in order to notify him about the actual changes
                subject = "Modification de votre compte";

                body = agent.lastName.ToUpper() + " " + agent.firstName.ToLower() + " (" + agent.job.ToUpper() + ") : "
                       + "<br> L'agent " + SecurityManager.getFormatedSessionInfo() + " vient de modifier votre compte"
                       + "<br><br>Identifiant : " + id_textBox.Text
                       + "<br>Mot de passe : " + password_textBox.Text
                       + "<br>Code d'identification : " + DataProtection.ToInsecureString(DataProtection.unprotect(agent.shortSecureId))
                       + "<br>Le code d'identification est unique et ne peut être changé pour des raisons de sécurité.";
            }


            if (res == ToolsClass.Definition.NO_ERROR_INT_VALUE)//no error
            {
                /*if the user change the mail adress of an agent, we send mail to the old adress "old_mail_adress" to notify him
                 * that we change his mail adress
                 * Then we send mail to the new adress with the data that changed
                 */
                if ((old_mail_adress != null) && (old_mail_adress != "") && (old_mail_adress != agent.mailAdress))
                {
                    string text_body = agent.lastName.ToUpper() + " " + agent.firstName.ToLower() + " (" + agent.job.ToUpper() + ") : "
                                       + "<br> L'agent " + SecurityManager.getFormatedSessionInfo() + " vient de modifier votre compte"
                                       + "<br>Cette adresse mail n'est désormais plus assiocié à votre compte."
                                       + "En conséquence, vous ne receverez plus de notification à cette adresse";
                    ToolsClass.Tools.sendMail(subject, text_body, new List <string>(new string[] { old_mail_adress }));
                }

                //send mail to the current mail adress
                int res_mail = ToolsClass.Tools.sendMail(subject, body, new List <string>(new string[] { agent.mailAdress }));

                string message = "Les modifications ont été enregistrées avec succès";
                if (res_mail != ToolsClass.Definition.NO_ERROR_INT_VALUE)//fail to send data
                {
                    HtmlMessageBox box = new HtmlMessageBox("Information sur le compte", ref body);
                    box.ShowDialog();

                    message += "\nLe mail n'a pas pu être envoyé";
                }
                else
                {
                    message += "\nLe mail a correctement été envoyé";
                }
                MessageBox.Show(message);

                setListBox(); //update listbox
                setDefault(); //reset view
            }
            else//error
            {
                MessageBox.Show("Une erreur est survenue !");
            }
        }