private static bool askForPasswordAndCompareToHashedPassword(string sebFileHashedAdminPassword, bool forEditing)
        {
            if (sebFileHashedAdminPassword.Length == 0)
            {
                return(true);
            }
            int    num1 = 5;
            string passwordRequestText = SEBUIStrings.enterAdminPasswordRequired;
            string input;
            bool   flag;

            do
            {
                --num1;
                input = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.loadingSettings + (string.IsNullOrEmpty(SEBClientInfo.LoadingSettingsFileName) ? "" : ": " + SEBClientInfo.LoadingSettingsFileName), passwordRequestText);
                if (input == null)
                {
                    return(false);
                }
                flag = string.Compare(input.Length != 0 ? SEBProtectionController.ComputePasswordHash(input) : "", sebFileHashedAdminPassword, StringComparison.OrdinalIgnoreCase) == 0;
                passwordRequestText = SEBUIStrings.enterAdminPasswordRequiredAgain;
            }while ((input == null || !flag) && num1 > 0);
            if (flag)
            {
                return(flag);
            }
            int num2 = (int)SEBMessageBox.Show(SEBUIStrings.loadingSettingsFailed, SEBUIStrings.loadingSettingsFailedWrongAdminPwd, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);

            return(false);
        }
Exemplo n.º 2
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Encrypt preferences using a password
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        // Encrypt preferences using a password
        public static byte[] EncryptDataUsingPassword(byte[] data, string password, bool passwordIsHash, SEBSettings.sebConfigPurposes configPurpose)
        {
            string prefixString;

            // Check if .seb file should start exam or configure client
            if (configPurpose == SEBSettings.sebConfigPurposes.sebConfigPurposeStartingExam)
            {
                // prefix string for starting exam: normal password will be prompted
                prefixString = PASSWORD_MODE;
            }
            else
            {
                // prefix string for configuring client: configuring password will either be hashed admin pw on client
                // or if no admin pw on client set: empty pw
                prefixString = PASSWORD_CONFIGURING_CLIENT_MODE;
                if (!String.IsNullOrEmpty(password) && !passwordIsHash)
                {
                    //empty password means no admin pw on clients and should not be hashed
                    //or we got already a hashed admin pw as settings pw, then we don't hash again
                    password = SEBProtectionController.ComputePasswordHash(password);
                }
            }
            byte[] encryptedData = SEBProtectionController.EncryptDataWithPassword(data, password);
            // Create byte array large enough to hold prefix and data
            byte[] encryptedSebData = new byte[encryptedData.Length + PREFIX_LENGTH];
            Buffer.BlockCopy(Encoding.UTF8.GetBytes(prefixString), 0, encryptedSebData, 0, PREFIX_LENGTH);
            Buffer.BlockCopy(encryptedData, 0, encryptedSebData, PREFIX_LENGTH, encryptedData.Length);

            return(encryptedSebData);
        }
 public static byte[] EncryptDataUsingIdentity(byte[] data, X509Certificate2 certificateRef)
 {
     byte[] hashFromCertificate = SEBProtectionController.GetPublicKeyHashFromCertificate(certificateRef);
     byte[] numArray1           = SEBProtectionController.EncryptDataWithCertificate(data, certificateRef);
     byte[] numArray2           = new byte[numArray1.Length + 4 + hashFromCertificate.Length];
     Buffer.BlockCopy((Array)Encoding.UTF8.GetBytes("pkhs"), 0, (Array)numArray2, 0, 4);
     Buffer.BlockCopy((Array)hashFromCertificate, 0, (Array)numArray2, 4, hashFromCertificate.Length);
     Buffer.BlockCopy((Array)numArray1, 0, (Array)numArray2, 4 + hashFromCertificate.Length, numArray1.Length);
     return(numArray2);
 }
        private static byte[] DecryptDataWithPublicKeyHashPrefix(byte[] sebData, bool forEditing, ref X509Certificate2 sebFileCertificateRef)
        {
            X509Certificate2 certificateFromStore = SEBProtectionController.GetCertificateFromStore(SEBConfigFileManager.GetPrefixDataFromData(ref sebData, 20));

            if (certificateFromStore == null)
            {
                int num = (int)SEBMessageBox.Show(SEBUIStrings.errorDecryptingSettings, SEBUIStrings.certificateNotFoundInStore, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                return((byte[])null);
            }
            if (forEditing)
            {
                sebFileCertificateRef = certificateFromStore;
            }
            sebData = SEBProtectionController.DecryptDataWithCertificate(sebData, certificateFromStore);
            return(sebData);
        }
Exemplo n.º 5
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Ask user to enter password and compare it to the passed (hashed) password string
        /// Returns true if correct password was entered
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        private static bool askForPasswordAndCompareToHashedPassword(string sebFileHashedAdminPassword, bool forEditing)
        {
            // Check if there wasn't a hashed password (= empty password)
            if (sebFileHashedAdminPassword.Length == 0)
            {
                return(true);
            }
            // We have to ask for the SEB administrator password used in the settings
            // and allow opening settings only if the user enters the right one
            // Allow up to 5 attempts for entering  admin password
            int    i        = 5;
            string password = null;
            string hashedPassword;
            string enterPasswordString = SEBUIStrings.enterAdminPasswordRequired;
            bool   passwordsMatch;

            do
            {
                i--;
                // Prompt for password
                password = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.loadingSettings + (String.IsNullOrEmpty(SEBClientInfo.LoadingSettingsFileName) ? "" : ": " + SEBClientInfo.LoadingSettingsFileName), enterPasswordString);
                // If cancel was pressed, abort
                if (password == null)
                {
                    return(false);
                }
                if (password.Length == 0)
                {
                    hashedPassword = "";
                }
                else
                {
                    hashedPassword = SEBProtectionController.ComputePasswordHash(password);
                }
                passwordsMatch = (String.Compare(hashedPassword, sebFileHashedAdminPassword, StringComparison.OrdinalIgnoreCase) == 0);
                // in case we get an error we allow the user to try it again
                enterPasswordString = SEBUIStrings.enterAdminPasswordRequiredAgain;
            } while ((password == null || !passwordsMatch) && i > 0);
            if (!passwordsMatch)
            {
                //wrong password entered in 5th try: stop reading .seb file
                SEBMessageBox.Show(SEBUIStrings.loadingSettingsFailed, SEBUIStrings.loadingSettingsFailedWrongAdminPwd, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                return(false);
            }
            // Right password entered
            return(passwordsMatch);
        }
Exemplo n.º 6
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Encrypt preferences using a certificate
        /// </summary>
        /// ----------------------------------------------------------------------------------------

        public static byte[] EncryptDataUsingIdentity(byte[] data, X509Certificate2 certificateRef)
        {
            //get public key hash from selected identity's certificate
            byte[] publicKeyHash = SEBProtectionController.GetPublicKeyHashFromCertificate(certificateRef);

            //encrypt data using public key
            byte[] encryptedData = SEBProtectionController.EncryptDataWithCertificate(data, certificateRef);

            // Create byte array large enough to hold prefix, public key hash and encrypted data
            byte[] encryptedSebData = new byte[encryptedData.Length + PREFIX_LENGTH + publicKeyHash.Length];
            // Copy prefix indicating data has been encrypted with a public key identified by hash into out data
            string prefixString = PUBLIC_KEY_HASH_MODE;
            Buffer.BlockCopy(Encoding.UTF8.GetBytes(prefixString), 0, encryptedSebData, 0, PREFIX_LENGTH);
            // Copy public key hash to out data
            Buffer.BlockCopy(publicKeyHash, 0, encryptedSebData, PREFIX_LENGTH, publicKeyHash.Length);
            // Copy encrypted data to out data
            Buffer.BlockCopy(encryptedData, 0, encryptedSebData, PREFIX_LENGTH + publicKeyHash.Length, encryptedData.Length);

            return encryptedSebData;
        }
Exemplo n.º 7
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Helper method which fetches the public key hash from a byte array, 
        /// retrieves the according cryptographic identity from the certificate store
        /// and returns the decrypted bytes 
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        private static byte[] DecryptDataWithPublicKeyHashPrefix(byte[] sebData, bool forEditing, ref X509Certificate2 sebFileCertificateRef)
        {
            // Get 20 bytes public key hash prefix
            // and remaining data with the prefix stripped
            byte[] publicKeyHash = GetPrefixDataFromData(ref sebData, PUBLIC_KEY_HASH_LENGTH);

            X509Certificate2 certificateRef = SEBProtectionController.GetCertificateFromStore(publicKeyHash);
            if (certificateRef == null)
            {
                SEBMessageBox.Show(SEBUIStrings.errorDecryptingSettings, SEBUIStrings.certificateNotFoundInStore, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                return null;
            }
            // If these settings are being decrypted for editing, we will return the decryption certificate reference
            // in the variable which was passed as reference when calling this method
            if (forEditing) sebFileCertificateRef = certificateRef;

            sebData = SEBProtectionController.DecryptDataWithCertificate(sebData, certificateRef);

            return sebData;
        }
Exemplo n.º 8
0
        protected override void OnClick(EventArgs e)
        {
            string restartExamTitle = (String)SEBClientInfo.getSebSetting(SEBSettings.KeyRestartExamText)[SEBSettings.KeyRestartExamText];

            // If there was no individual restart exam text set, we use the default text (which is localized)
            if (String.IsNullOrEmpty(restartExamTitle))
            {
                restartExamTitle = SEBUIStrings.restartExamDefaultTitle;
            }

            string quitPassword = (String)SEBClientInfo.getSebSetting(SEBSettings.KeyHashedQuitPassword)[SEBSettings.KeyHashedQuitPassword];

            if ((Boolean)SEBClientInfo.getSebSetting(SEBSettings.KeyRestartExamPasswordProtected)[SEBSettings.KeyRestartExamPasswordProtected] && !String.IsNullOrWhiteSpace(quitPassword))
            {
                var password = SebPasswordDialogForm.ShowPasswordDialogForm(restartExamTitle, SEBUIStrings.restartExamEnterPassword);

                //cancel button has been clicked
                if (password == null)
                {
                    return;
                }

                var hashedPassword = SEBProtectionController.ComputePasswordHash(password);
                if (String.IsNullOrWhiteSpace(password) ||
                    String.Compare(quitPassword, hashedPassword, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    SEBMessageBox.Show(restartExamTitle, SEBUIStrings.wrongQuitRestartPasswordText, MessageBoxIcon.Error, MessageBoxButtons.OK);
                    return;
                }
                else
                {
                    SEBXULRunnerWebSocketServer.SendRestartExam();
                    return;
                }
            }

            if (SEBMessageBox.Show(restartExamTitle, SEBUIStrings.restartExamConfirm, MessageBoxIcon.Question, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                SEBXULRunnerWebSocketServer.SendRestartExam();
            }
        }
Exemplo n.º 9
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            string userQuitPassword = this.txtQuitPassword.Text;

            string hPassword            = SEBProtectionController.ComputePasswordHash(userQuitPassword);
            string settingsPasswordHash = (string)SEBClientInfo.getSebSetting(SEBSettings.KeyHashedQuitPassword)[SEBSettings.KeyHashedQuitPassword];
            int    quit = String.Compare(settingsPasswordHash, hPassword, StringComparison.OrdinalIgnoreCase);

            if (quit != 0)
            {
                this.Hide();
                SEBMessageBox.Show(SEBUIStrings.quittingFailed, SEBUIStrings.quittingFailedReason, MessageBoxIcon.Error, MessageBoxButtons.OK);
                this.txtQuitPassword.Text = "";
                this.Visible = false;
            }
            else
            {
                this.Visible = false;
                SEBClientInfo.SebWindowsClientForm.ExitApplication();
            }
        }
Exemplo n.º 10
0
        private void ShowPasswordDialog(string processName, string quitPassword)
        {
            var password = SebPasswordDialogForm.ShowPasswordDialogForm(SEBUIStrings.prohibitedProcessDetectedTitle, SEBUIStrings.prohibitedProcessDetectedQuitPassword + processName);

            //cancel button has been clicked
            if (password == null)
            {
                ShowPasswordDialog(processName, quitPassword);
            }

            var hashedPassword = SEBProtectionController.ComputePasswordHash(password);

            if (String.IsNullOrWhiteSpace(password) ||
                String.Compare(quitPassword, hashedPassword, StringComparison.OrdinalIgnoreCase) != 0)
            {
                return;
            }
            else
            {
                ShowPasswordDialog(processName, quitPassword);
            }
        }
        public static byte[] EncryptDataUsingPassword(byte[] data, string password, bool passwordIsHash, SEBSettings.sebConfigPurposes configPurpose)
        {
            string s;

            if (configPurpose == SEBSettings.sebConfigPurposes.sebConfigPurposeStartingExam)
            {
                s = "pswd";
            }
            else
            {
                s = "pwcc";
                if (!string.IsNullOrEmpty(password) && !passwordIsHash)
                {
                    password = SEBProtectionController.ComputePasswordHash(password);
                }
            }
            byte[] numArray1 = SEBProtectionController.EncryptDataWithPassword(data, password);
            byte[] numArray2 = new byte[numArray1.Length + 4];
            Buffer.BlockCopy((Array)Encoding.UTF8.GetBytes(s), 0, (Array)numArray2, 0, 4);
            Buffer.BlockCopy((Array)numArray1, 0, (Array)numArray2, 4, numArray1.Length);
            return(numArray2);
        }
Exemplo n.º 12
0
        protected override void OnClick(EventArgs e)
        {
            string examDefaultTitle = (string)SEBClientInfo.getSebSetting("restartExamText")["restartExamText"];

            if (string.IsNullOrEmpty(examDefaultTitle))
            {
                examDefaultTitle = SEBUIStrings.restartExamDefaultTitle;
            }
            string strA = (string)SEBClientInfo.getSebSetting("hashedQuitPassword")["hashedQuitPassword"];

            if ((bool)SEBClientInfo.getSebSetting("restartExamPasswordProtected")["restartExamPasswordProtected"] && !string.IsNullOrWhiteSpace(strA))
            {
                string input = SebPasswordDialogForm.ShowPasswordDialogForm(examDefaultTitle, SEBUIStrings.restartExamEnterPassword);
                if (input == null)
                {
                    return;
                }
                string passwordHash = SEBProtectionController.ComputePasswordHash(input);
                if (string.IsNullOrWhiteSpace(input) || string.Compare(strA, passwordHash, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    int num = (int)SEBMessageBox.Show(examDefaultTitle, SEBUIStrings.wrongQuitRestartPasswordText, MessageBoxIcon.Hand, MessageBoxButtons.OK, false);
                }
                else
                {
                    SEBXULRunnerWebSocketServer.SendRestartExam();
                }
            }
            else
            {
                if (SEBMessageBox.Show(examDefaultTitle, SEBUIStrings.restartExamConfirm, MessageBoxIcon.Question, MessageBoxButtons.YesNo, false) != DialogResult.Yes)
                {
                    return;
                }
                SEBXULRunnerWebSocketServer.SendRestartExam();
            }
        }
        public static bool StoreDecryptedSEBSettings(byte[] sebData)
        {
            string                      sebFilePassword       = (string)null;
            bool                        passwordIsHash        = false;
            X509Certificate2            sebFileCertificateRef = (X509Certificate2)null;
            Dictionary <string, object> settingsDict          = SEBConfigFileManager.DecryptSEBSettings(sebData, false, ref sebFilePassword, ref passwordIsHash, ref sebFileCertificateRef);

            if (settingsDict == null)
            {
                return(false);
            }
            Logger.AddInformation("Reconfiguring", (object)null, (Exception)null, (string)null);
            SEBClientInfo.SebWindowsClientForm.closeSebClient = false;
            Logger.AddInformation("Attempting to CloseSEBForm for reconfiguration", (object)null, (Exception)null, (string)null);
            SEBClientInfo.SebWindowsClientForm.CloseSEBForm();
            Logger.AddInformation("Succesfully CloseSEBForm for reconfiguration", (object)null, (Exception)null, (string)null);
            SEBClientInfo.SebWindowsClientForm.closeSebClient = true;
            SEBClientInfo.CreateNewDesktopOldValue            = (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, "createNewDesktop");
            if ((int)settingsDict["sebConfigPurpose"] == 0)
            {
                Logger.AddInformation("Reconfiguring to start an exam", (object)null, (Exception)null, (string)null);
                Logger.AddInformation("Attempting to StoreSebClientSettings", (object)null, (Exception)null, (string)null);
                SEBSettings.StoreSebClientSettings(settingsDict);
                Logger.AddInformation("Successfully StoreSebClientSettings", (object)null, (Exception)null, (string)null);
                SEBClientInfo.examMode = true;
                SEBClientInfo.InitializeLogger();
                if (SEBClientInfo.CreateNewDesktopOldValue != (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, "createNewDesktop"))
                {
                    if (!SEBClientInfo.CreateNewDesktopOldValue)
                    {
                        int num1 = (int)SEBMessageBox.Show(SEBUIStrings.settingsRequireNewDesktop, SEBUIStrings.settingsRequireNewDesktopReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, false);
                    }
                    else
                    {
                        int num2 = (int)SEBMessageBox.Show(SEBUIStrings.settingsRequireNotNewDesktop, SEBUIStrings.settingsRequireNotNewDesktopReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, false);
                    }
                    SEBClientInfo.SebWindowsClientForm.ExitApplication(true);
                }
                Logger.AddInformation("Attemting to InitSEBDesktop for reconfiguration", (object)null, (Exception)null, (string)null);
                if (!SebWindowsClientMain.InitSEBDesktop())
                {
                    return(false);
                }
                Logger.AddInformation("Sucessfully InitSEBDesktop for reconfiguration", (object)null, (Exception)null, (string)null);
                Logger.AddInformation("Attempting to OpenSEBForm for reconfiguration", (object)null, (Exception)null, (string)null);
                int num = SEBClientInfo.SebWindowsClientForm.OpenSEBForm() ? 1 : 0;
                Logger.AddInformation("Successfully OpenSEBForm for reconfiguration", (object)null, (Exception)null, (string)null);
                return(num != 0);
            }
            Logger.AddInformation("Reconfiguring to configure a client", (object)null, (Exception)null, (string)null);
            List <object> objectList = (List <object>)settingsDict["embeddedCertificates"];

            for (int index = objectList.Count - 1; index >= 0; --index)
            {
                Dictionary <string, object> dictionary = (Dictionary <string, object>)objectList[index];
                if ((int)dictionary["type"] == 1)
                {
                    SEBProtectionController.StoreCertificateIntoStore((byte[])dictionary["certificateData"]);
                }
                objectList.RemoveAt(index);
            }
            SEBSettings.StoreSebClientSettings(settingsDict);
            SEBClientInfo.InitializeLogger();
            SEBSettings.WriteSebConfigurationFile(SEBClientInfo.SebClientSettingsAppDataFile, "", false, (X509Certificate2)null, SEBSettings.sebConfigPurposes.sebConfigPurposeConfiguringClient, false);
            if (!SebWindowsClientMain.InitSEBDesktop() || !SEBClientInfo.SebWindowsClientForm.OpenSEBForm())
            {
                return(false);
            }
            if (SEBClientInfo.CreateNewDesktopOldValue != (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, "createNewDesktop"))
            {
                int num = (int)SEBMessageBox.Show(SEBUIStrings.sebReconfiguredRestartNeeded, SEBUIStrings.sebReconfiguredRestartNeededReason, MessageBoxIcon.Exclamation, MessageBoxButtons.OK, false);
                SEBClientInfo.SebWindowsClientForm.ExitApplication(true);
            }
            if (SEBMessageBox.Show(SEBUIStrings.sebReconfigured, SEBUIStrings.sebReconfiguredQuestion, MessageBoxIcon.Question, MessageBoxButtons.YesNo, false) == DialogResult.No)
            {
                SEBClientInfo.SebWindowsClientForm.ExitApplication(true);
            }
            return(true);
        }
        // *******************************************************
        // Initialise the GUI widgets of this configuration editor
        // *******************************************************
        private void InitialiseGUIWidgets()
        {
            // At program start, the local client settings configuration file is loaded
            currentDireSebConfigFile = SEBClientInfo.SebClientSettingsAppDataDirectory;
            currentFileSebConfigFile = SEBClientInfo.SEB_CLIENT_CONFIG;
            StringBuilder sebClientSettingsAppDataBuilder = new StringBuilder(currentDireSebConfigFile).Append(currentFileSebConfigFile);

            currentPathSebConfigFile = sebClientSettingsAppDataBuilder.ToString();

            openFileDialogSebConfigFile.InitialDirectory = Environment.CurrentDirectory;
            saveFileDialogSebConfigFile.InitialDirectory = Environment.CurrentDirectory;
            //folderBrowserDialogDownloadDirectoryWin.RootFolder = Environment.SpecialFolder.DesktopDirectory;
            //folderBrowserDialogLogDirectoryWin     .RootFolder = Environment.SpecialFolder.MyDocuments;

            // Assign the fixed entries to the ListBoxes and ComboBoxes
            listBoxExitKey1.Items.AddRange(StringFunctionKey);
            listBoxExitKey2.Items.AddRange(StringFunctionKey);
            listBoxExitKey3.Items.AddRange(StringFunctionKey);

            // Assing the list of cryptographic identities/certificates to the ComboBox
            ArrayList certificateNames = new ArrayList();

            certificateReferences = SEBProtectionController.GetCertificatesAndNames(ref certificateNames);
            comboBoxCryptoIdentity.Items.Add("None");
            comboBoxCryptoIdentity.Items.AddRange(certificateNames.ToArray());
            comboBoxChooseIdentityToEmbed.Items.AddRange(certificateNames.ToArray());
            comboBoxChooseIdentityToEmbed.Text = SEBUIStrings.ChooseEmbeddedCert;

            ArrayList certificateSSLNames = new ArrayList();

            certificateSSLReferences = SEBProtectionController.GetSSLCertificatesAndNames(ref certificateSSLNames);
            comboBoxChooseSSLClientCertificate.Items.AddRange(certificateSSLNames.ToArray());
            comboBoxChooseSSLClientCertificate.Text = SEBUIStrings.ChooseEmbeddedCert;


            // At program start, no file has yet been opened, so revert is not possible
            buttonRevertToLastOpened.Enabled = false;

            comboBoxMainBrowserWindowWidth.Items.AddRange(StringWindowWidth);
            comboBoxMainBrowserWindowHeight.Items.AddRange(StringWindowHeight);
            listBoxMainBrowserWindowPositioning.Items.AddRange(StringWindowPositioning);

            comboBoxNewBrowserWindowWidth.Items.AddRange(StringWindowWidth);
            comboBoxNewBrowserWindowHeight.Items.AddRange(StringWindowHeight);
            listBoxNewBrowserWindowPositioning.Items.AddRange(StringWindowPositioning);

            comboBoxTaskBarHeight.Items.AddRange(StringTaskBarHeight);

            listBoxOpenLinksHTML.Items.AddRange(StringPolicyLinkOpening);
            listBoxOpenLinksJava.Items.AddRange(StringPolicyLinkOpening);

            listBoxChooseFileToUploadPolicy.Items.AddRange(StringPolicyFileUpload);
            listBoxSebServicePolicy.Items.AddRange(StringPolicySebService);

            // Initialise the DataGridViews:
            // Set "AllowUserToAddRows" to false, to avoid an initial empty first row
            // Set "RowHeadersVisible"  to false, to avoid an initial empty first column
            // Set "FullRowSelect"      to true , to select whole row when clicking on a cell
            dataGridViewPermittedProcesses.Enabled            = false;
            dataGridViewPermittedProcesses.ReadOnly           = false;
            dataGridViewPermittedProcesses.AllowUserToAddRows = false;
            dataGridViewPermittedProcesses.RowHeadersVisible  = false;
            dataGridViewPermittedProcesses.MultiSelect        = false;
            dataGridViewPermittedProcesses.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;

            dataGridViewPermittedProcessArguments.Enabled            = false;
            dataGridViewPermittedProcessArguments.ReadOnly           = false;
            dataGridViewPermittedProcessArguments.AllowUserToAddRows = false;
            dataGridViewPermittedProcessArguments.RowHeadersVisible  = false;
            dataGridViewPermittedProcessArguments.MultiSelect        = false;
            dataGridViewPermittedProcessArguments.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;

            dataGridViewProhibitedProcesses.Enabled            = false;
            dataGridViewProhibitedProcesses.ReadOnly           = false;
            dataGridViewProhibitedProcesses.AllowUserToAddRows = false;
            dataGridViewProhibitedProcesses.RowHeadersVisible  = false;
            dataGridViewProhibitedProcesses.MultiSelect        = false;
            dataGridViewProhibitedProcesses.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;

            dataGridViewEmbeddedCertificates.Enabled            = false;
            dataGridViewEmbeddedCertificates.ReadOnly           = false;
            dataGridViewEmbeddedCertificates.AllowUserToAddRows = false;
            dataGridViewEmbeddedCertificates.RowHeadersVisible  = false;
            dataGridViewEmbeddedCertificates.MultiSelect        = false;
            dataGridViewEmbeddedCertificates.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;

            dataGridViewProxyProtocols.Enabled            = false;
            dataGridViewProxyProtocols.ReadOnly           = false;
            dataGridViewProxyProtocols.AllowUserToAddRows = false;
            dataGridViewProxyProtocols.RowHeadersVisible  = false;
            dataGridViewProxyProtocols.MultiSelect        = false;
            dataGridViewProxyProtocols.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;


            dataGridViewPermittedProcesses.Columns[IntColumnProcessActive].ValueType     = typeof(Boolean);
            dataGridViewPermittedProcesses.Columns[IntColumnProcessOS].ValueType         = typeof(String);
            dataGridViewPermittedProcesses.Columns[IntColumnProcessExecutable].ValueType = typeof(String);
            dataGridViewPermittedProcesses.Columns[IntColumnProcessTitle].ValueType      = typeof(String);

            dataGridViewPermittedProcessArguments.Columns[IntColumnProcessActive].ValueType   = typeof(Boolean);
            dataGridViewPermittedProcessArguments.Columns[IntColumnProcessArgument].ValueType = typeof(String);

            dataGridViewProhibitedProcesses.Columns[IntColumnProcessActive].ValueType      = typeof(Boolean);
            dataGridViewProhibitedProcesses.Columns[IntColumnProcessOS].ValueType          = typeof(String);
            dataGridViewProhibitedProcesses.Columns[IntColumnProcessExecutable].ValueType  = typeof(String);
            dataGridViewProhibitedProcesses.Columns[IntColumnProcessDescription].ValueType = typeof(String);

            dataGridViewEmbeddedCertificates.Columns[IntColumnCertificateType].ValueType = typeof(String);
            dataGridViewEmbeddedCertificates.Columns[IntColumnCertificateName].ValueType = typeof(String);

            dataGridViewProxyProtocols.Columns[IntColumnProxyProtocolEnable].ValueType = typeof(Boolean);
            dataGridViewProxyProtocols.Columns[IntColumnProxyProtocolType].ValueType   = typeof(String);

            dataGridViewProxyProtocols.Columns[IntColumnProxyProtocolEnable].ReadOnly = false;
            dataGridViewProxyProtocols.Columns[IntColumnProxyProtocolType].ReadOnly   = true;

            // Assign the column names to the DataGridViews

/*
 *          dataGridViewPermittedProcesses.Columns.Add(StringColumnActive    , StringColumnActive);
 *          dataGridViewPermittedProcesses.Columns.Add(StringColumnOS        , StringColumnOS);
 *          dataGridViewPermittedProcesses.Columns.Add(StringColumnExecutable, StringColumnExecutable);
 *          dataGridViewPermittedProcesses.Columns.Add(StringColumnTitle     , StringColumnTitle);
 *
 *          dataGridViewPermittedProcessArguments.Columns.Add(StringColumnActive  , StringColumnActive);
 *          dataGridViewPermittedProcessArguments.Columns.Add(StringColumnArgument, StringColumnArgument);
 *
 *          dataGridViewProhibitedProcesses.Columns.Add(StringColumnActive     , StringColumnActive);
 *          dataGridViewProhibitedProcesses.Columns.Add(StringColumnOS         , StringColumnOS);
 *          dataGridViewProhibitedProcesses.Columns.Add(StringColumnExecutable , StringColumnExecutable);
 *          dataGridViewProhibitedProcesses.Columns.Add(StringColumnDescription, StringColumnDescription);
 *
 *          dataGridViewURLFilterRules.Columns.Add(StringColumnURLFilterRuleShow      , StringColumnURLFilterRuleShow);
 *          dataGridViewURLFilterRules.Columns.Add(StringColumnURLFilterRuleActive    , StringColumnURLFilterRuleActive);
 *          dataGridViewURLFilterRules.Columns.Add(StringColumnURLFilterRuleRegex     , StringColumnURLFilterRuleRegex);
 *          dataGridViewURLFilterRules.Columns.Add(StringColumnURLFilterRuleExpression, StringColumnURLFilterRuleExpression);
 *          dataGridViewURLFilterRules.Columns.Add(StringColumnURLFilterRuleAction    , StringColumnURLFilterRuleAction);
 *
 *          dataGridViewEmbeddedCertificates.Columns.Add(StringColumnCertificateType, StringColumnCertificateType);
 *          dataGridViewEmbeddedCertificates.Columns.Add(StringColumnCertificateName, StringColumnCertificateName);
 *
 *          dataGridViewProxyProtocols.Columns.Add(StringColumnProxyProtocolEnable, StringColumnProxyProtocolEnable);
 *          dataGridViewProxyProtocols.Columns.Add(StringColumnProxyProtocolType  , StringColumnProxyProtocolType);
 *
 *          dataGridViewBypassedProxies.Columns.Add(StringColumnDomainHostPort, StringColumnDomainHostPort);
 */
            groupBoxPermittedProcess.Enabled  = false;
            groupBoxProhibitedProcess.Enabled = false;

            listBoxPermittedProcessOS.Items.AddRange(StringOS);
            listBoxProhibitedProcessOS.Items.AddRange(StringOS);

            // Help data structures for table access to URL Filter Rules
            urlFilterTableRow        = -1;
            urlFilterTableRowIsTitle = false;
            urlFilterTableRuleIndex.Clear();
            urlFilterTableActionIndex.Clear();
            urlFilterTableIsTitleRow.Clear();
            urlFilterTableStartRow.Clear();
            urlFilterTableEndRow.Clear();
            urlFilterTableShowRule.Clear();
            urlFilterTableCellIsDisabled.Clear();

            // Auto-resize the columns and cells
            //dataGridViewPermittedProcesses  .AutoResizeColumns();
            //dataGridViewProhibitedProcesses .AutoResizeColumns();
            //dataGridViewURLFilterRules      .AutoResizeColumns();
            //dataGridViewEmbeddedCertificates.AutoResizeColumns();
            //dataGridViewProxyProtocols      .AutoResizeColumns();
            //dataGridViewBypassedProxies     .AutoResizeColumns();

            //dataGridViewPermittedProcesses  .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            //dataGridViewProhibitedProcesses .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            //dataGridViewURLFilterRules      .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            //dataGridViewEmbeddedCertificates.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            //dataGridViewProxyProtocols      .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            //dataGridViewBypassedProxies     .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }
Exemplo n.º 15
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Decrypt, parse and use new SEB settings
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        public static bool StoreDecryptedSEBSettings(byte[] sebData)
        {
            DictObj          sebPreferencesDict;
            string           sebFilePassword       = null;
            bool             passwordIsHash        = false;
            X509Certificate2 sebFileCertificateRef = null;

            sebPreferencesDict = DecryptSEBSettings(sebData, false, ref sebFilePassword, ref passwordIsHash, ref sebFileCertificateRef);
            if (sebPreferencesDict == null)
            {
                return(false);                            //Decryption didn't work, we abort
            }
            Logger.AddInformation("Reconfiguring");
            // Reset SEB, close third party applications
            SEBClientInfo.SebWindowsClientForm.closeSebClient = false;
            Logger.AddInformation("Attempting to CloseSEBForm for reconfiguration");
            SEBClientInfo.SebWindowsClientForm.CloseSEBForm();
            Logger.AddInformation("Succesfully CloseSEBForm for reconfiguration");
            SEBClientInfo.SebWindowsClientForm.closeSebClient = true;
            //SEBClientInfo.SebWindowsClientForm.Close();
            //SEBClientInfo.SebWindowsClientForm.Dispose();

            // We need to check if setting for createNewDesktop changed
            SEBClientInfo.CreateNewDesktopOldValue = (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, SEBSettings.KeyCreateNewDesktop);

            if ((int)sebPreferencesDict[SEBSettings.KeySebConfigPurpose] == (int)SEBSettings.sebConfigPurposes.sebConfigPurposeStartingExam)
            {
                ///
                /// If these SEB settings are ment to start an exam
                ///

                Logger.AddInformation("Reconfiguring to start an exam");
                /// If these SEB settings are ment to start an exam

                // Store decrypted settings
                Logger.AddInformation("Attempting to StoreSebClientSettings");
                SEBSettings.StoreSebClientSettings(sebPreferencesDict);
                Logger.AddInformation("Successfully StoreSebClientSettings");

                // Set the flag that SEB is running in exam mode now
                SEBClientInfo.examMode = true;

                //Re-initialize logger
                SEBClientInfo.InitializeLogger();

                // Check if SEB is running on the standard desktop and the new settings demand to run in new desktop (createNewDesktop = true)
                // or the other way around!
                if (SEBClientInfo.CreateNewDesktopOldValue != (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, SEBSettings.KeyCreateNewDesktop))
                {
                    // If it did, SEB needs to quit and be restarted manually for the new setting to take effekt
                    if (SEBClientInfo.CreateNewDesktopOldValue == false)
                    {
                        SEBMessageBox.Show(SEBUIStrings.settingsRequireNewDesktop, SEBUIStrings.settingsRequireNewDesktopReason, MessageBoxIcon.Error, MessageBoxButtons.OK);
                    }
                    else
                    {
                        SEBMessageBox.Show(SEBUIStrings.settingsRequireNotNewDesktop, SEBUIStrings.settingsRequireNotNewDesktopReason, MessageBoxIcon.Error, MessageBoxButtons.OK);
                    }

                    //SEBClientInfo.SebWindowsClientForm.closeSebClient = true;
                    SEBClientInfo.SebWindowsClientForm.ExitApplication();
                }

                // Re-Initialize SEB according to the new settings
                Logger.AddInformation("Attemting to InitSEBDesktop for reconfiguration");
                if (!SebWindowsClientMain.InitSEBDesktop())
                {
                    return(false);
                }
                Logger.AddInformation("Sucessfully InitSEBDesktop for reconfiguration");
                // Re-open the main form
                //SEBClientInfo.SebWindowsClientForm = new SebWindowsClientForm();
                //SebWindowsClientMain.singleInstanceController.SetMainForm(SEBClientInfo.SebWindowsClientForm);

                //return if initializing SEB with openend preferences was successful
                Logger.AddInformation("Attempting to OpenSEBForm for reconfiguration");
                var ret = SEBClientInfo.SebWindowsClientForm.OpenSEBForm();
                Logger.AddInformation("Successfully OpenSEBForm for reconfiguration");
                return(ret);
            }
            else
            {
                ///
                /// If these SEB settings are ment to configure a client
                ///

                Logger.AddInformation("Reconfiguring to configure a client");
                /// If these SEB settings are ment to configure a client

                // Check if we have embedded identities and import them into the Windows Certifcate Store
                ListObj embeddedCertificates = (ListObj)sebPreferencesDict[SEBSettings.KeyEmbeddedCertificates];
                for (int i = embeddedCertificates.Count - 1; i >= 0; i--)
                {
                    // Get the Embedded Certificate
                    DictObj embeddedCertificate = (DictObj)embeddedCertificates[i];
                    // Is it an identity?
                    if ((int)embeddedCertificate[SEBSettings.KeyType] == 1)
                    {
                        // Store the identity into the Windows Certificate Store
                        SEBProtectionController.StoreCertificateIntoStore((byte[])embeddedCertificate[SEBSettings.KeyCertificateData]);
                    }
                    // Remove the identity from settings, as it should be only stored in the Certificate Store and not in the locally stored settings file
                    embeddedCertificates.RemoveAt(i);
                }

                // Store decrypted settings
                SEBSettings.StoreSebClientSettings(sebPreferencesDict);

                //Re-initialize logger
                SEBClientInfo.InitializeLogger();

                // Write new settings to the localapp directory
                SEBSettings.WriteSebConfigurationFile(SEBClientInfo.SebClientSettingsAppDataFile, "", false, null, SEBSettings.sebConfigPurposes.sebConfigPurposeConfiguringClient);

                // Re-Initialize SEB desktop according to the new settings
                if (!SebWindowsClientMain.InitSEBDesktop())
                {
                    return(false);
                }

                if (SEBClientInfo.SebWindowsClientForm.OpenSEBForm())
                {
                    // Activate SebWindowsClient so the message box gets focus
                    //SEBClientInfo.SebWindowsClientForm.Activate();

                    // Check if setting for createNewDesktop changed
                    if (SEBClientInfo.CreateNewDesktopOldValue != (bool)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, SEBSettings.KeyCreateNewDesktop))
                    {
                        // If it did, SEB needs to quit and be restarted manually for the new setting to take effekt
                        SEBMessageBox.Show(SEBUIStrings.sebReconfiguredRestartNeeded, SEBUIStrings.sebReconfiguredRestartNeededReason, MessageBoxIcon.Warning, MessageBoxButtons.OK);
                        //SEBClientInfo.SebWindowsClientForm.closeSebClient = true;
                        SEBClientInfo.SebWindowsClientForm.ExitApplication();
                    }

                    if (SEBMessageBox.Show(SEBUIStrings.sebReconfigured, SEBUIStrings.sebReconfiguredQuestion, MessageBoxIcon.Question, MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        //SEBClientInfo.SebWindowsClientForm.closeSebClient = true;
                        SEBClientInfo.SebWindowsClientForm.ExitApplication();
                    }

                    return(true); //reading preferences was successful
                }
                else
                {
                    return(false);
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// JSON Serialization of Settings Dictionary
        /// </summary>
        public static string XULRunnerConfigDictionarySerialize(Dictionary <string, object> xulRunnerSettings)
        {
            // Add current Browser Exam Key
            if ((bool)xulRunnerSettings[SEBSettings.KeySendBrowserExamKey])
            {
                string browserExamKey = SEBProtectionController.ComputeBrowserExamKey();
                xulRunnerSettings[SEBSettings.KeyBrowserExamKey] = browserExamKey;
                xulRunnerSettings[SEBSettings.KeyBrowserURLSalt] = true;
            }

            // Eventually update setting
            if ((Boolean)SEBSettings.settingsCurrent[SEBSettings.KeyRestartExamUseStartURL] == true)
            {
                xulRunnerSettings[SEBSettings.KeyRestartExamURL] = xulRunnerSettings[SEBSettings.KeyStartURL];
            }

            // Check if URL filter is enabled and send according keys to XULRunner seb only if it is
            if ((bool)xulRunnerSettings[SEBSettings.KeyURLFilterEnable] == false)
            {
                xulRunnerSettings[SEBSettings.KeyUrlFilterBlacklist] = "";
                xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] = "";
            }
            else
            {
                // URL filter is enabled: Set trusted content flag to same value (what actually doesn't make sense, but it's implemented wrong in seb winctrl.jsm)
                xulRunnerSettings[SEBSettings.KeyUrlFilterTrustedContent] = (bool)xulRunnerSettings[SEBSettings.KeyURLFilterEnableContentFilter];

                //add the starturl to the whitelist if not yet added
                if (!xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist].ToString().Contains(xulRunnerSettings[SEBSettings.KeyStartURL].ToString()))
                {
                    if (!String.IsNullOrWhiteSpace(xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist].ToString()))
                    {
                        xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += @";";
                    }
                }
                xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += xulRunnerSettings[SEBSettings.KeyStartURL].ToString();

                //Add the socket address if content filter is enabled
                if ((bool)xulRunnerSettings[SEBSettings.KeyURLFilterEnableContentFilter] == true)
                {
                    if (!String.IsNullOrWhiteSpace(xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist].ToString()))
                    {
                        xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += @";";
                    }
                    //Add the Socket address with http protocoll instead of ws protocoll for the injected iframe
                    xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += String.Format("http://{0}", SEBXULRunnerWebSocketServer.ServerAddress.Substring(5));
                }
            }

            // Add websocket sever address to XULRunner seb settings
            xulRunnerSettings[SEBSettings.KeyBrowserMessagingSocket] = SEBXULRunnerWebSocketServer.ServerAddress;
            Logger.AddInformation("Socket: " + xulRunnerSettings[SEBSettings.KeyBrowserMessagingSocket].ToString(), null, null);

            // Expand environment variables in paths which XULRunner seb is processing
            string downloadDirectoryWin = (string)xulRunnerSettings[SEBSettings.KeyDownloadDirectoryWin];

            downloadDirectoryWin = Environment.ExpandEnvironmentVariables(downloadDirectoryWin);
            //downloadDirectoryWin = downloadDirectoryWin.Replace(@"\", @"\\");
            xulRunnerSettings[SEBSettings.KeyDownloadDirectoryWin] = downloadDirectoryWin;

            // Add proper browser user agent string to XULRunner seb settings

            if ((bool)xulRunnerSettings[SEBSettings.KeyTouchOptimized] == true)
            {
                // Switch off XULRunner seb reload warning
                xulRunnerSettings[SEBSettings.KeyShowReloadWarning] = false;

                // Set correct task bar height according to display dpi
                xulRunnerSettings[SEBSettings.KeyTaskBarHeight] = (int)Math.Round((int)xulRunnerSettings[SEBSettings.KeyTaskBarHeight] * 1.7);

                if ((int)xulRunnerSettings[SEBSettings.KeyBrowserUserAgentTouchMode] == 0)
                {
                    xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = SEBClientInfo.BROWSER_USERAGENT_TOUCH;
                }
                else if ((int)xulRunnerSettings[SEBSettings.KeyBrowserUserAgentTouchMode] == 1)
                {
                    xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = SEBClientInfo.BROWSER_USERAGENT_TOUCH_IPAD;
                }
                else if ((int)xulRunnerSettings[SEBSettings.KeyBrowserUserAgentTouchMode] == 2)
                {
                    xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = xulRunnerSettings[SEBSettings.KeyBrowserUserAgentTouchModeCustom];
                }
            }
            else
            {
                if ((int)xulRunnerSettings[SEBSettings.KeyBrowserUserAgentDesktopMode] == 0)
                {
                    xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = SEBClientInfo.BROWSER_USERAGENT_DESKTOP;
                }
                else
                {
                    xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = xulRunnerSettings[SEBSettings.KeyBrowserUserAgentDesktopModeCustom];
                }
            }
            xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] += " " + SEBClientInfo.BROWSER_USERAGENT_SEB + " " + Application.ProductVersion;

            // Set onscreen keyboard settings flag when touch optimized is enabled
            xulRunnerSettings[SEBSettings.KeyBrowserScreenKeyboard] = (bool)xulRunnerSettings[SEBSettings.KeyTouchOptimized];

            // Serialise
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonSettings             = serializer.Serialize(xulRunnerSettings);

            // Convert to Base64 String
            byte[] bytesJson  = Encoding.UTF8.GetBytes(jsonSettings);
            string base64Json = Convert.ToBase64String(bytesJson);

            //// remove the two chars "==" from the end of the string
            //string base64Json = base64String.Substring(0, base64String.Length - 2);

            return(base64Json);
        }
Exemplo n.º 17
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Helper method which decrypts the byte array using an empty password,
        /// or the administrator password currently set in SEB
        /// or asks for the password used for encrypting this SEB file
        /// for configuring the client
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        private static DictObj DecryptDataWithPasswordForConfiguringClient(byte[] sebData, bool forEditing, ref string sebFilePassword, ref bool passwordIsHash)
        {
            passwordIsHash = false;
            string password;
            // First try to decrypt with the current admin password
            // get admin password hash
            string hashedAdminPassword = (string)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, SEBSettings.KeyHashedAdminPassword);

            if (hashedAdminPassword == null)
            {
                hashedAdminPassword = "";
            }
            // We use always uppercase letters in the base16 hashed admin password used for encrypting
            hashedAdminPassword = hashedAdminPassword.ToUpper();
            DictObj sebPreferencesDict = null;

            byte[] decryptedSebData = SEBProtectionController.DecryptDataWithPassword(sebData, hashedAdminPassword);
            if (decryptedSebData == null)
            {
                // If decryption with admin password didn't work, try it with an empty password
                decryptedSebData = SEBProtectionController.DecryptDataWithPassword(sebData, "");
                if (decryptedSebData == null)
                {
                    // If decryption with empty and admin password didn't work, ask for the password the .seb file was encrypted with
                    // Allow up to 5 attempts for entering decoding password
                    int i = 5;
                    password = null;
                    string enterPasswordString = SEBUIStrings.enterEncryptionPassword;
                    do
                    {
                        i--;
                        // Prompt for password
                        password = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.reconfiguringLocalSettings, enterPasswordString);
                        // If cancel was pressed, abort
                        if (password == null)
                        {
                            return(null);
                        }
                        string hashedPassword = SEBProtectionController.ComputePasswordHash(password);
                        // we try to decrypt with the hashed password
                        decryptedSebData = SEBProtectionController.DecryptDataWithPassword(sebData, hashedPassword);
                        // in case we get an error we allow the user to try it again
                        enterPasswordString = SEBUIStrings.enterEncryptionPasswordAgain;
                    } while (decryptedSebData == null && i > 0);
                    if (decryptedSebData == null)
                    {
                        //wrong password entered in 5th try: stop reading .seb file
                        SEBMessageBox.Show(SEBUIStrings.reconfiguringLocalSettingsFailed, SEBUIStrings.reconfiguringLocalSettingsFailedWrongPassword, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                        return(null);
                    }
                    else
                    {
                        // Decrypting with entered password worked: We save it for returning it later
                        if (forEditing)
                        {
                            sebFilePassword = password;
                        }
                    }
                }
            }
            else
            {
                //decrypting with hashedAdminPassword worked: we save it for returning as decryption password
                sebFilePassword = hashedAdminPassword;
                // identify that password as hash
                passwordIsHash = true;
            }
            /// Decryption worked

            // Ungzip the .seb (according to specification >= v14) decrypted serialized XML plist data
            decryptedSebData = GZipByte.Decompress(decryptedSebData);

            // Check if the openend reconfiguring seb file has the same admin password inside like the current one

            try
            {
                sebPreferencesDict = (DictObj)Plist.readPlist(decryptedSebData);
            }
            catch (Exception readPlistException)
            {
                // Error when deserializing the decrypted configuration data
                // We abort reading the new settings here
                SEBMessageBox.Show(SEBUIStrings.loadingSettingsFailed, SEBUIStrings.loadingSettingsFailedReason, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                Console.WriteLine(readPlistException.Message);
                return(null);
            }
            // Get the admin password set in these settings
            string sebFileHashedAdminPassword = (string)SEBSettings.valueForDictionaryKey(sebPreferencesDict, SEBSettings.KeyHashedAdminPassword);

            if (sebFileHashedAdminPassword == null)
            {
                sebFileHashedAdminPassword = "";
            }
            // Has the SEB config file the same admin password inside as the current settings have?
            if (String.Compare(hashedAdminPassword, sebFileHashedAdminPassword, StringComparison.OrdinalIgnoreCase) != 0)
            {
                //No: The admin password inside the .seb file wasn't the same as the current one
                if (forEditing)
                {
                    // If the file is openend for editing (and not to reconfigure SEB)
                    // we have to ask the user for the admin password inside the file
                    if (!askForPasswordAndCompareToHashedPassword(sebFileHashedAdminPassword, forEditing))
                    {
                        // If the user didn't enter the right password we abort
                        return(null);
                    }
                }
                else
                {
                    // The file was actually opened for reconfiguring the SEB client:
                    // we have to ask for the current admin password and
                    // allow reconfiguring only if the user enters the right one
                    // We don't check this for the case the current admin password was used to encrypt the new settings
                    // In this case there can be a new admin pw defined in the new settings and users don't need to enter the old one
                    if (passwordIsHash == false && hashedAdminPassword.Length > 0)
                    {
                        // Allow up to 5 attempts for entering current admin password
                        int i = 5;
                        password = null;
                        string hashedPassword;
                        string enterPasswordString = SEBUIStrings.enterCurrentAdminPwdForReconfiguring;
                        bool   passwordsMatch;
                        do
                        {
                            i--;
                            // Prompt for password
                            password = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.reconfiguringLocalSettings, enterPasswordString);
                            // If cancel was pressed, abort
                            if (password == null)
                            {
                                return(null);
                            }
                            if (password.Length == 0)
                            {
                                hashedPassword = "";
                            }
                            else
                            {
                                hashedPassword = SEBProtectionController.ComputePasswordHash(password);
                            }
                            passwordsMatch = (String.Compare(hashedPassword, hashedAdminPassword, StringComparison.OrdinalIgnoreCase) == 0);
                            // in case we get an error we allow the user to try it again
                            enterPasswordString = SEBUIStrings.enterCurrentAdminPwdForReconfiguringAgain;
                        } while (!passwordsMatch && i > 0);
                        if (!passwordsMatch)
                        {
                            //wrong password entered in 5th try: stop reading .seb file
                            SEBMessageBox.Show(SEBUIStrings.reconfiguringLocalSettingsFailed, SEBUIStrings.reconfiguringLocalSettingsFailedWrongCurrentAdminPwd, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                            return(null);
                        }
                    }
                }
            }

            // We need to set the right value for the key sebConfigPurpose to know later where to store the new settings
            sebPreferencesDict[SEBSettings.KeySebConfigPurpose] = (int)SEBSettings.sebConfigPurposes.sebConfigPurposeConfiguringClient;

            // Reading preferences was successful!
            return(sebPreferencesDict);
        }
Exemplo n.º 18
0
        /// ----------------------------------------------------------------------------------------
        /// <summary>
        /// Decrypt and deserialize SEB settings
        /// When forEditing = true, then the decrypting password the user entered and/or
        /// certificate reference found in the .seb file is returned
        /// </summary>
        /// ----------------------------------------------------------------------------------------
        public static DictObj DecryptSEBSettings(byte[] sebData, bool forEditing, ref string sebFilePassword, ref bool passwordIsHash, ref X509Certificate2 sebFileCertificateRef)
        {
            // Ungzip the .seb (according to specification >= v14) source data
            byte[] unzippedSebData = GZipByte.Decompress(sebData);

            // if unzipped data is not null, then unzipping worked, we use unzipped data
            // if unzipped data is null, then the source data may be an uncompressed .seb file, we proceed with it
            if (unzippedSebData != null)
            {
                sebData = unzippedSebData;
            }

            string prefixString;

            // save the data including the first 4 bytes for the case that it's acutally an unencrypted XML plist
            byte[] sebDataUnencrypted = sebData.Clone() as byte[];

            // Get 4-char prefix
            prefixString = GetPrefixStringFromData(ref sebData);

            //// Check prefix identifying encryption modes

            // Prefix = pkhs ("Public Key Hash") ?

            if (prefixString.CompareTo(PUBLIC_KEY_HASH_MODE) == 0)
            {
                // Decrypt with cryptographic identity/private key
                sebData = DecryptDataWithPublicKeyHashPrefix(sebData, forEditing, ref sebFileCertificateRef);
                if (sebData == null)
                {
                    return(null);
                }

                // Get 4-char prefix again
                // and remaining data without prefix, which is either plain or still encoded with password
                prefixString = GetPrefixStringFromData(ref sebData);
            }

            // Prefix = pswd ("Password") ?

            if (prefixString.CompareTo(PASSWORD_MODE) == 0)
            {
                // Decrypt with password
                // if the user enters the right one
                byte[] sebDataDecrypted = null;
                string password;
                // Allow up to 5 attempts for entering decoding password
                string enterPasswordString = SEBUIStrings.enterPassword;
                int    i = 5;
                do
                {
                    i--;
                    // Prompt for password
                    password = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.loadingSettings, enterPasswordString);
                    if (password == null)
                    {
                        return(null);
                    }
                    //error = nil;
                    sebDataDecrypted    = SEBProtectionController.DecryptDataWithPassword(sebData, password);
                    enterPasswordString = SEBUIStrings.enterPasswordAgain;
                    // in case we get an error we allow the user to try it again
                } while ((sebDataDecrypted == null) && i > 0);
                if (sebDataDecrypted == null)
                {
                    //wrong password entered in 5th try: stop reading .seb file
                    SEBMessageBox.Show(SEBUIStrings.decryptingSettingsFailed, SEBUIStrings.decryptingSettingsFailedReason, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                    return(null);
                }
                sebData = sebDataDecrypted;
                // If these settings are being decrypted for editing, we return the decryption password
                if (forEditing)
                {
                    sebFilePassword = password;
                }
            }
            else
            {
                // Prefix = pwcc ("Password Configuring Client") ?

                if (prefixString.CompareTo(PASSWORD_CONFIGURING_CLIENT_MODE) == 0)
                {
                    // Decrypt with password and configure local client settings
                    // and quit afterwards, returning if reading the .seb file was successfull
                    DictObj sebSettings = DecryptDataWithPasswordForConfiguringClient(sebData, forEditing, ref sebFilePassword, ref passwordIsHash);
                    return(sebSettings);
                }
                else
                {
                    // Prefix = plnd ("Plain Data") ?

                    if (prefixString.CompareTo(PLAIN_DATA_MODE) != 0)
                    {
                        // No valid 4-char prefix was found in the .seb file
                        // Check if .seb file is unencrypted
                        if (prefixString.CompareTo(UNENCRYPTED_MODE) == 0)
                        {
                            // .seb file seems to be an unencrypted XML plist
                            // get the original data including the first 4 bytes
                            sebData = sebDataUnencrypted;
                        }
                        else
                        {
                            // No valid prefix and no unencrypted file with valid header
                            // cancel reading .seb file
                            SEBMessageBox.Show(SEBUIStrings.settingsNotUsable, SEBUIStrings.settingsNotUsableReason, MessageBoxIcon.Error, MessageBoxButtons.OK, neverShowTouchOptimized: forEditing);
                            return(null);
                        }
                    }
                }
            }
            // If we don't deal with an unencrypted seb file
            // ungzip the .seb (according to specification >= v14) decrypted serialized XML plist data
            if (prefixString.CompareTo(UNENCRYPTED_MODE) != 0)
            {
                sebData = GZipByte.Decompress(sebData);
            }

            // Get preferences dictionary from decrypted data
            DictObj sebPreferencesDict = GetPreferencesDictFromConfigData(sebData, forEditing);

            // If we didn't get a preferences dict back, we abort reading settings
            if (sebPreferencesDict == null)
            {
                return(null);
            }

            // We need to set the right value for the key sebConfigPurpose to know later where to store the new settings
            sebPreferencesDict[SEBSettings.KeySebConfigPurpose] = (int)SEBSettings.sebConfigPurposes.sebConfigPurposeStartingExam;

            // Reading preferences was successful!
            return(sebPreferencesDict);
        }
Exemplo n.º 19
0
        /// <summary>
        /// JSON Serialization of Settings Dictionary
        /// </summary>
        public static string XULRunnerConfigDictionarySerialize(Dictionary <string, object> xulRunnerSettings)
        {
            // Add current Browser Exam Key
            if ((bool)xulRunnerSettings[SEBSettings.KeySendBrowserExamKey])
            {
                string browserExamKey = SEBProtectionController.ComputeBrowserExamKey();
                xulRunnerSettings[SEBSettings.KeyBrowserExamKey] = browserExamKey;
                xulRunnerSettings[SEBSettings.KeyBrowserURLSalt] = true;
            }

            //If necessary replace the starturl with the path to the startResource
            xulRunnerSettings[SEBSettings.KeyStartURL] = GetStartupPathOrUrl();

            // Eventually update setting
            if ((Boolean)SEBSettings.settingsCurrent[SEBSettings.KeyRestartExamUseStartURL] == true)
            {
                xulRunnerSettings[SEBSettings.KeyRestartExamURL] = xulRunnerSettings[SEBSettings.KeyStartURL];
            }

            // Check if URL filter is enabled and send according keys to XULRunner seb only if it is
            if ((bool)xulRunnerSettings[SEBSettings.KeyURLFilterEnable] == false)
            {
                xulRunnerSettings[SEBSettings.KeyUrlFilterBlacklist] = "";
                xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] = "";
            }
            else
            {
                //Add the socket address
                if (!String.IsNullOrWhiteSpace(xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist].ToString()))
                {
                    xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += @";";
                }
                //Add the Socket address with http protocoll instead of ws protocoll for the injected iframe
                xulRunnerSettings[SEBSettings.KeyUrlFilterWhitelist] += String.Format("http://{0}", SEBXULRunnerWebSocketServer.ServerAddress.Substring(5));
            }

            // Add websocket sever address to XULRunner seb settings
            xulRunnerSettings[SEBSettings.KeyBrowserMessagingSocket]        = SEBXULRunnerWebSocketServer.ServerAddress;
            xulRunnerSettings[SEBSettings.KeyBrowserMessagingSocketEnabled] = true;
            Logger.AddInformation("Socket: " + xulRunnerSettings[SEBSettings.KeyBrowserMessagingSocket].ToString(), null, null);

            // Expand environment variables in paths which XULRunner seb is processing
            string downloadDirectoryWin = (string)xulRunnerSettings[SEBSettings.KeyDownloadDirectoryWin];

            downloadDirectoryWin = Environment.ExpandEnvironmentVariables(downloadDirectoryWin);
            //downloadDirectoryWin = downloadDirectoryWin.Replace(@"\", @"\\");
            xulRunnerSettings[SEBSettings.KeyDownloadDirectoryWin] = downloadDirectoryWin;

            if ((bool)xulRunnerSettings[SEBSettings.KeyTouchOptimized] == true)
            {
                // Switch off XULRunner seb reload warnings
                xulRunnerSettings[SEBSettings.KeyShowReloadWarning] = false;
                xulRunnerSettings[SEBSettings.KeyNewBrowserWindowShowReloadWarning] = false;


                // Set correct taskbar height according to display dpi
                xulRunnerSettings[SEBSettings.KeyTaskBarHeight] = (int)Math.Round((int)xulRunnerSettings[SEBSettings.KeyTaskBarHeight] * 1.7);
            }

            // Add proper browser user agent string to XULRunner seb settings
            xulRunnerSettings[SEBSettings.KeyBrowserUserAgent] = SEBClientInfo.BROWSER_USERAGENT_SEB + "/" + Application.ProductVersion +
                                                                 (String.IsNullOrEmpty((String)xulRunnerSettings[SEBSettings.KeyBrowserUserAgent]) ? "" : " " + xulRunnerSettings[SEBSettings.KeyBrowserUserAgent]);
            //Logger.AddInformation("Useragent String generated in SEBXulRunnerSettings: " + SEBClientInfo.BROWSER_USERAGENT_SEB + "/" + Application.ProductVersion +
            //  (String.IsNullOrEmpty((String)xulRunnerSettings[SEBSettings.KeyBrowserUserAgent]) ? "" : " " + xulRunnerSettings[SEBSettings.KeyBrowserUserAgent]));

            // Set onscreen keyboard settings flag when touch optimized is enabled
            xulRunnerSettings[SEBSettings.KeyBrowserScreenKeyboard] = (bool)xulRunnerSettings[SEBSettings.KeyTouchOptimized];

            //Remove all AdditionalResourceData from settings
            RecursivelyRemoveAdditionalResourceData((ListObj)xulRunnerSettings[SEBSettings.KeyAdditionalResources]);

            // The additional dictionary data is being extracted by the .NET-part, the browser only expects a path to the respective folder
            xulRunnerSettings.Remove(SEBSettings.KeyAdditionalDictionaries);

            xulRunnerSettings.Remove(SEBSettings.KeyPermittedProcesses);
            xulRunnerSettings.Remove(SEBSettings.KeyProhibitedProcesses);
            xulRunnerSettings.Remove(SEBSettings.KeyURLFilterRules);

            // The installed operating system culture for correct website localization
            xulRunnerSettings.Add("browserLanguage", System.Globalization.CultureInfo.CurrentCulture.Name);

            // Serialise
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonSettings             = serializer.Serialize(xulRunnerSettings);

            // Convert to Base64 String
            byte[] bytesJson  = Encoding.UTF8.GetBytes(jsonSettings);
            string base64Json = Convert.ToBase64String(bytesJson);

            //// remove the two chars "==" from the end of the string
            //string base64Json = base64String.Substring(0, base64String.Length - 2);

            return(base64Json);
        }
Exemplo n.º 20
0
 private void btnOk_Click(object sender, EventArgs e)
 {
     if (string.Compare((string)SEBClientInfo.getSebSetting("hashedQuitPassword")["hashedQuitPassword"], SEBProtectionController.ComputePasswordHash(this.txtQuitPassword.Text), StringComparison.OrdinalIgnoreCase) != 0)
     {
         this.Hide();
         int num = (int)SEBMessageBox.Show(SEBUIStrings.quittingFailed, SEBUIStrings.quittingFailedReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, false);
         this.txtQuitPassword.Text = "";
         this.Visible = false;
     }
     else
     {
         this.Visible = false;
         SEBClientInfo.SebWindowsClientForm.ExitApplication(true);
     }
 }
Exemplo n.º 21
0
        public static string XULRunnerConfigDictionarySerialize(Dictionary <string, object> xulRunnerSettings)
        {
            if ((bool)xulRunnerSettings["sendBrowserExamKey"])
            {
                string browserExamKey = SEBProtectionController.ComputeBrowserExamKey();
                xulRunnerSettings["browserExamKey"] = (object)browserExamKey;
                xulRunnerSettings["browserURLSalt"] = (object)true;
            }
            xulRunnerSettings["startURL"] = (object)SEBXulRunnerSettings.ResolveResourceUrl((string)xulRunnerSettings["startURL"]);
            SEBXulRunnerSettings.OverwriteSystemProxySettings(xulRunnerSettings);
            if ((bool)SEBSettings.settingsCurrent["restartExamUseStartURL"])
            {
                xulRunnerSettings["restartExamURL"] = xulRunnerSettings["startURL"];
            }
            if (!(bool)xulRunnerSettings["URLFilterEnable"])
            {
                xulRunnerSettings["blacklistURLFilter"] = (object)"";
                xulRunnerSettings["whitelistURLFilter"] = (object)"";
            }
            else
            {
                xulRunnerSettings["urlFilterTrustedContent"] = (object)(bool)xulRunnerSettings["URLFilterEnableContentFilter"];
                if (!xulRunnerSettings["whitelistURLFilter"].ToString().Contains(xulRunnerSettings["startURL"].ToString()) && !string.IsNullOrWhiteSpace(xulRunnerSettings["whitelistURLFilter"].ToString()))
                {
                    Dictionary <string, object> dictionary = xulRunnerSettings;
                    dictionary["whitelistURLFilter"] = (object)(dictionary["whitelistURLFilter"].ToString() + ";");
                }
                Dictionary <string, object> dictionary1 = xulRunnerSettings;
                dictionary1["whitelistURLFilter"] = (object)(dictionary1["whitelistURLFilter"].ToString() + xulRunnerSettings["startURL"].ToString());
                if ((bool)xulRunnerSettings["URLFilterEnableContentFilter"])
                {
                    if (!string.IsNullOrWhiteSpace(xulRunnerSettings["whitelistURLFilter"].ToString()))
                    {
                        Dictionary <string, object> dictionary2 = xulRunnerSettings;
                        dictionary2["whitelistURLFilter"] = (object)(dictionary2["whitelistURLFilter"].ToString() + ";");
                    }
                    Dictionary <string, object> dictionary3 = xulRunnerSettings;
                    dictionary3["whitelistURLFilter"] = (object)(dictionary3["whitelistURLFilter"].ToString() + string.Format("http://{0}", (object)SEBXULRunnerWebSocketServer.ServerAddress.Substring(5)));
                }
            }
            xulRunnerSettings["browserMessagingSocket"] = (object)SEBXULRunnerWebSocketServer.ServerAddress;
            Logger.AddInformation("Socket: " + xulRunnerSettings["browserMessagingSocket"].ToString(), (object)null, (Exception)null, (string)null);
            string str = Environment.ExpandEnvironmentVariables((string)xulRunnerSettings["downloadDirectoryWin"]);

            xulRunnerSettings["downloadDirectoryWin"] = (object)str;
            if ((bool)xulRunnerSettings["touchOptimized"])
            {
                xulRunnerSettings["showReloadWarning"] = (object)false;
                xulRunnerSettings["taskBarHeight"]     = (object)(int)Math.Round((double)(int)xulRunnerSettings["taskBarHeight"] * 1.7);
                if ((int)xulRunnerSettings["browserUserAgentWinTouchMode"] == 0)
                {
                    xulRunnerSettings["browserUserAgent"] = (object)"Mozilla/5.0 (Windows NT 6.3; rv:41.0; Touch) Gecko/20100101 Firefox/41";
                }
                else if ((int)xulRunnerSettings["browserUserAgentWinTouchMode"] == 1)
                {
                    xulRunnerSettings["browserUserAgent"] = (object)"Mozilla/5.0 (iPad; CPU OS 9_0_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A452 Safari/601.1";
                }
                else if ((int)xulRunnerSettings["browserUserAgentWinTouchMode"] == 2)
                {
                    xulRunnerSettings["browserUserAgent"] = xulRunnerSettings["browserUserAgentWinTouchModeCustom"];
                }
            }
            else if ((int)xulRunnerSettings["browserUserAgentWinDesktopMode"] == 0)
            {
                OperatingSystem osVersion = Environment.OSVersion;
                xulRunnerSettings["browserUserAgent"] = (object)string.Format("Mozilla/5.0 (Windows NT {0}.{1}; rv:41.0) Gecko/20100101 Firefox/41", (object)osVersion.Version.Major, (object)osVersion.Version.Minor);
            }
            else
            {
                xulRunnerSettings["browserUserAgent"] = xulRunnerSettings["browserUserAgentWinDesktopModeCustom"];
            }
            Dictionary <string, object> dictionary4 = xulRunnerSettings;

            dictionary4["browserUserAgent"]            = (object)(dictionary4["browserUserAgent"].ToString() + " SEB " + Application.ProductVersion);
            xulRunnerSettings["browserScreenKeyboard"] = (object)(bool)xulRunnerSettings["touchOptimized"];
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize((object)xulRunnerSettings))));
        }
        private static Dictionary <string, object> DecryptDataWithPasswordForConfiguringClient(byte[] sebData, bool forEditing, ref string sebFilePassword, ref bool passwordIsHash)
        {
            passwordIsHash = false;
            string upper = ((string)SEBSettings.valueForDictionaryKey(SEBSettings.settingsCurrent, "hashedAdminPassword") ?? "").ToUpper();

            byte[] input1 = SEBProtectionController.DecryptDataWithPassword(sebData, upper);
            string str1;

            if (input1 == null)
            {
                input1 = SEBProtectionController.DecryptDataWithPassword(sebData, "");
                if (input1 == null)
                {
                    int num1 = 5;
                    str1 = (string)null;
                    string passwordRequestText = SEBUIStrings.enterEncryptionPassword;
                    string input2;
                    do
                    {
                        --num1;
                        input2 = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.reconfiguringLocalSettings, passwordRequestText);
                        if (input2 == null)
                        {
                            return((Dictionary <string, object>)null);
                        }
                        string passwordHash = SEBProtectionController.ComputePasswordHash(input2);
                        input1 = SEBProtectionController.DecryptDataWithPassword(sebData, passwordHash);
                        passwordRequestText = SEBUIStrings.enterEncryptionPasswordAgain;
                    }while (input1 == null && num1 > 0);
                    if (input1 == null)
                    {
                        int num2 = (int)SEBMessageBox.Show(SEBUIStrings.reconfiguringLocalSettingsFailed, SEBUIStrings.reconfiguringLocalSettingsFailedWrongPassword, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                        return((Dictionary <string, object>)null);
                    }
                    if (forEditing)
                    {
                        sebFilePassword = input2;
                    }
                }
            }
            else
            {
                sebFilePassword = upper;
                passwordIsHash  = true;
            }
            byte[] data = GZipByte.Decompress(input1);
            Dictionary <string, object> dictionary;

            try
            {
                dictionary = (Dictionary <string, object>)Plist.readPlist(data);
            }
            catch (Exception ex)
            {
                int num = (int)SEBMessageBox.Show(SEBUIStrings.loadingSettingsFailed, SEBUIStrings.loadingSettingsFailedReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                Console.WriteLine(ex.Message);
                return((Dictionary <string, object>)null);
            }
            string str2 = (string)SEBSettings.valueForDictionaryKey(dictionary, "hashedAdminPassword") ?? "";

            if (string.Compare(upper, str2, StringComparison.OrdinalIgnoreCase) != 0)
            {
                if (forEditing)
                {
                    if (!SEBConfigFileManager.askForPasswordAndCompareToHashedPassword(str2, forEditing))
                    {
                        return((Dictionary <string, object>)null);
                    }
                }
                else if (!passwordIsHash && upper.Length > 0)
                {
                    int num1 = 5;
                    str1 = (string)null;
                    string passwordRequestText = SEBUIStrings.enterCurrentAdminPwdForReconfiguring;
                    bool   flag;
                    do
                    {
                        --num1;
                        string input2 = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.reconfiguringLocalSettings, passwordRequestText);
                        if (input2 == null)
                        {
                            return((Dictionary <string, object>)null);
                        }
                        flag = string.Compare(input2.Length != 0 ? SEBProtectionController.ComputePasswordHash(input2) : "", upper, StringComparison.OrdinalIgnoreCase) == 0;
                        passwordRequestText = SEBUIStrings.enterCurrentAdminPwdForReconfiguringAgain;
                    }while (!flag && num1 > 0);
                    if (!flag)
                    {
                        int num2 = (int)SEBMessageBox.Show(SEBUIStrings.reconfiguringLocalSettingsFailed, SEBUIStrings.reconfiguringLocalSettingsFailedWrongCurrentAdminPwd, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                        return((Dictionary <string, object>)null);
                    }
                }
            }
            dictionary["sebConfigPurpose"] = (object)1;
            return(dictionary);
        }
        public static Dictionary <string, object> DecryptSEBSettings(byte[] sebData, bool forEditing, ref string sebFilePassword, ref bool passwordIsHash, ref X509Certificate2 sebFileCertificateRef)
        {
            byte[] numArray1 = GZipByte.Decompress(sebData);
            if (numArray1 != null)
            {
                sebData = numArray1;
            }
            byte[] numArray2            = sebData.Clone() as byte[];
            string prefixStringFromData = SEBConfigFileManager.GetPrefixStringFromData(ref sebData);

            if (prefixStringFromData.CompareTo("pkhs") == 0)
            {
                sebData = SEBConfigFileManager.DecryptDataWithPublicKeyHashPrefix(sebData, forEditing, ref sebFileCertificateRef);
                if (sebData == null)
                {
                    return((Dictionary <string, object>)null);
                }
                prefixStringFromData = SEBConfigFileManager.GetPrefixStringFromData(ref sebData);
            }
            if (prefixStringFromData.CompareTo("pswd") == 0)
            {
                string passwordRequestText = SEBUIStrings.enterPassword;
                int    num1 = 5;
                string passphrase;
                byte[] numArray3;
                do
                {
                    --num1;
                    passphrase = ThreadedDialog.ShowPasswordDialogForm(SEBUIStrings.loadingSettings, passwordRequestText);
                    if (passphrase == null)
                    {
                        return((Dictionary <string, object>)null);
                    }
                    numArray3           = SEBProtectionController.DecryptDataWithPassword(sebData, passphrase);
                    passwordRequestText = SEBUIStrings.enterPasswordAgain;
                }while (numArray3 == null && num1 > 0);
                if (numArray3 == null)
                {
                    int num2 = (int)SEBMessageBox.Show(SEBUIStrings.decryptingSettingsFailed, SEBUIStrings.decryptingSettingsFailedReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                    return((Dictionary <string, object>)null);
                }
                sebData = numArray3;
                if (forEditing)
                {
                    sebFilePassword = passphrase;
                }
            }
            else
            {
                if (prefixStringFromData.CompareTo("pwcc") == 0)
                {
                    return(SEBConfigFileManager.DecryptDataWithPasswordForConfiguringClient(sebData, forEditing, ref sebFilePassword, ref passwordIsHash));
                }
                if (prefixStringFromData.CompareTo("plnd") != 0)
                {
                    if (prefixStringFromData.CompareTo("<?xm") == 0)
                    {
                        sebData = numArray2;
                    }
                    else
                    {
                        int num = (int)SEBMessageBox.Show(SEBUIStrings.settingsNotUsable, SEBUIStrings.settingsNotUsableReason, MessageBoxIcon.Hand, MessageBoxButtons.OK, forEditing);
                        return((Dictionary <string, object>)null);
                    }
                }
            }
            if (prefixStringFromData.CompareTo("<?xm") != 0)
            {
                sebData = GZipByte.Decompress(sebData);
            }
            Dictionary <string, object> dictFromConfigData = SEBConfigFileManager.GetPreferencesDictFromConfigData(sebData, forEditing);

            if (dictFromConfigData == null)
            {
                return((Dictionary <string, object>)null);
            }
            dictFromConfigData["sebConfigPurpose"] = (object)0;
            return(dictFromConfigData);
        }