Esempio n. 1
0
        private void LoadAccountsFromLocalSecureStore()
        {
            this.MigrateDataToRoamingAppData();

            var path     = ConfigurationInfo.SettingsDirectory;
            var filename = Path.Combine(path, ConfigurationFile_Accounts);

            if (!File.Exists(filename))
            {
                return;
            }

            var configString = File.ReadAllText(filename);

            if (string.IsNullOrEmpty(configString))
            {
                return;
            }

            try
            {
                var isEncryptionError = false;

                var settings = new JsonSerializerSettings
                {
                    Formatting        = Formatting.Indented,
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver  = new ProtectedDataStringPropertyResolver(),
                    Error             = (s, args) =>
                    {
                        if (args.ErrorContext.Error is JsonDecryptException)
                        {
                            isEncryptionError         = true;
                            args.ErrorContext.Handled = true;
                        }
                    }
                };

                this.Accounts = JsonConvert.DeserializeObject <IList <AccountConfiguration> >(configString, settings);

                if (isEncryptionError)
                {
                    var openTroubleshooting = MessageService.AskYesNo(
                        "Unable to parse the plugin's account configuration for the KeeAnywhere plugin from local secure store:\n" +
                        "Decryption of screts failed.\n\nWould you like to check Troubleshooting Documentation for that?",
                        "KeeAnywhere Plugin:"
                        );
                    if (openTroubleshooting)
                    {
                        Process.Start("https://keeanywhere.de/use/troubleshooting#could-not-read-account-configuration");
                    }
                }
            }
            catch (JsonSerializationException)
            {
                MessageService.ShowWarning(
                    "KeeAnywhere Plugin:",
                    "Unable to parse the plugin's account configuration for the KeeAnywhere plugin from local secure store.");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Called everytime a database is opened.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FileOpenedHandler(object sender, FileOpenedEventArgs e)
        {
            var ioInfo = e.Database.IOConnectionInfo;

            if (e.Database.CustomData.Get(ProductName) == null) // If there is no CustomData in this database
            {
                // Create CustomData to save global setting to enable or disable the plugin
                e.Database.CustomData.Set(ProductName, "true");
                e.Database.Modified = true;

                // Try to save the database
                try { e.Database.Save(null); }
                catch { }
            }

            // Global settings to be used in the Options Panel
            dbName        = Library.CharChange(ioInfo.Path);
            database      = e.Database;
            UWPLibrary.ck = database.MasterKey;
            if (e.Database.CustomData.Get(ProductName + "AT") == "true")
            {
                LockAfterAutoType = true;
            }
            else
            {
                LockAfterAutoType = false;
            }

            if (e.Database.CustomData.Get(ProductName) == "true")
            {
                enablePlugin = true;
            }
            if (e.Database.CustomData.Get(ProductName) == "false") // if plugin is disabled for the database
            {
                enablePlugin = false;
                return; // Don't do anything else
            }

            if (await UWPLibrary.FirstTime(dbName)) // If the database has no credentials saved
            {
                bool isHelloAvailable = await UWPLibrary.IsHelloAvailable();

                if (isHelloAvailable)
                {
                    // Ask the user if he/she wants to configure the plugin
                    bool yesOrNo = MessageService.AskYesNo("Do You want to set " +
                                                           WinHelloUnlockExt.ProductName + " for " + dbName + " now?", WinHelloUnlockExt.ShortProductName, true);

                    // In case he/she wants, create the credentials
                    if (yesOrNo)
                    {
                        await UWPLibrary.CreateHelloData(dbName);
                    }
                }
            }

            // Set global settings back to default
            tries  = 0;
            opened = true;
        }
Esempio n. 3
0
        internal static void Print(PwDatabase pd, bool bEmSheet, bool bKeyFile)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return;
            }
            if (!bEmSheet && !bKeyFile)
            {
                Debug.Assert(false); return;
            }

            if (!bEmSheet && bKeyFile)
            {
                string strText = KPRes.KeyFilePrintLocal + MessageService.NewParagraph +
                                 KPRes.AskContinue;
                if (!MessageService.AskYesNo(strText))
                {
                    return;
                }
            }

            try { PrintUtil.PrintHtml(GenerateDoc(pd, bEmSheet, bKeyFile)); }
            catch (Exception ex)
            {
                MessageService.ShowWarning(ex);
            }
        }
Esempio n. 4
0
        private bool ValidateOptions()
        {
            m_hkGlobalAutoType.ResetIfModifierOnly();
            m_hkSelectedAutoType.ResetIfModifierOnly();
            m_hkShowWindow.ResetIfModifierOnly();

            bool bAltMod = false;

            bAltMod |= ((m_hkGlobalAutoType.HotKeyModifiers == Keys.Alt) ||
                        (m_hkGlobalAutoType.HotKeyModifiers == (Keys.Alt | Keys.Shift)));
            bAltMod |= ((m_hkSelectedAutoType.HotKeyModifiers == Keys.Alt) ||
                        (m_hkSelectedAutoType.HotKeyModifiers == (Keys.Alt | Keys.Shift)));
            bAltMod |= ((m_hkShowWindow.HotKeyModifiers == Keys.Alt) ||
                        (m_hkShowWindow.HotKeyModifiers == (Keys.Alt | Keys.Shift)));

            if (bAltMod)
            {
                if (!MessageService.AskYesNo(KPRes.HotKeyAltOnly + MessageService.NewParagraph +
                                             KPRes.HotKeyAltOnlyHint + MessageService.NewParagraph +
                                             KPRes.HotKeyAltOnlyQuestion, null, false))
                {
                    return(false);
                }
            }

            return(true);
        }
    private void saveFileButton_Click(object sender, EventArgs e)
    {
        if (secureTextBox.TextLength <= 0 || _selectedCertificate == null || string.IsNullOrWhiteSpace(keyFileLocationTextBox.Text))
        {
            MessageService.ShowWarning("All the fields are required.");
            return;
        }

        bool overwrite = false;

        if (File.Exists(keyFileLocationTextBox.Text))
        {
            overwrite = MessageService.AskYesNo($"The file '{keyFileLocationTextBox.Text}' already exists. Overwrite?", "Warning");
            if (overwrite != true)
            {
                return;
            }
        }

        var cspKey = CryptoHelpers.EncryptPassphrase(_selectedCertificate, secureTextBox.TextEx);

        using (var fs = new FileStream(keyFileLocationTextBox.Text, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.Write, FileShare.Read))
        {
            XmlUtilEx.Serialize(fs, cspKey);
        }

        DialogResult = DialogResult.OK;
    }
Esempio n. 6
0
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

            if (m_secPassword.ContentsEqualTo(m_secRepeat) == false)
            {
                MessageService.ShowWarning(KPRes.PasswordRepeatFailed);
                return(false);
            }

            if (m_secPassword.TextLength == 0)
            {
                if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                             null, false))
                {
                    return(false);
                }
            }

            uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength;

            if (m_secPassword.TextLength < uMinLen)
            {
                string strML = KPRes.MasterPasswordMinLengthFailed;
                strML = strML.Replace(@"{PARAM}", uMinLen.ToString());
                MessageService.ShowWarning(strML);
                return(false);
            }

            byte[] pb = m_secPassword.ToUtf8();

            uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality;

            if (QualityEstimation.EstimatePasswordBits(pb) < uMinQual)
            {
                string strMQ = KPRes.MasterPasswordMinQualityFailed;
                strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString());
                MessageService.ShowWarning(strMQ);
                Array.Clear(pb, 0, pb.Length);
                return(false);
            }

            string strValRes = Program.KeyValidatorPool.Validate(pb,
                                                                 KeyValidationType.MasterPassword);

            if (strValRes != null)
            {
                MessageService.ShowWarning(strValRes);
                Array.Clear(pb, 0, pb.Length);
                return(false);
            }

            m_pKey.AddUserKey(new KcpPassword(pb));
            Array.Clear(pb, 0, pb.Length);

            return(true);
        }
Esempio n. 7
0
        private static string ValidateNewMasterPassword(byte[] pbUtf8, uint cChars)
        {
            if (pbUtf8 == null)
            {
                Debug.Assert(false); throw new ArgumentNullException("pbUtf8");
            }

#if DEBUG
            char[] vChars = StrUtil.Utf8.GetChars(pbUtf8);
            Debug.Assert(vChars.Length == (int)cChars);
            MemUtil.ZeroArray <char>(vChars);
#endif

            uint cBits = QualityEstimation.EstimatePasswordBits(pbUtf8);

            uint cMinChars = Program.Config.Security.MasterPassword.MinimumLength;
            if (cChars < cMinChars)
            {
                return(KPRes.MasterPasswordMinLengthFailed.Replace(@"{PARAM}",
                                                                   cMinChars.ToString()));
            }

            uint cMinBits = Program.Config.Security.MasterPassword.MinimumQuality;
            if (cBits < cMinBits)
            {
                return(KPRes.MasterPasswordMinQualityFailed.Replace(@"{PARAM}",
                                                                    cMinBits.ToString()));
            }

            string strError = Program.KeyValidatorPool.Validate(pbUtf8,
                                                                KeyValidationType.MasterPassword);
            if (strError != null)
            {
                return(strError);
            }

            if (cChars == 0)
            {
                if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                             null, false))
                {
                    return(string.Empty);
                }
            }

            if (cBits <= PwDefs.QualityBitsWeak)
            {
                string str = KPRes.MasterPasswordWeak + MessageService.NewParagraph +
                             KPRes.MasterPasswordConfirm;
                if (!MessageService.AskYesNo(str, null, false, MessageBoxIcon.Warning))
                {
                    return(string.Empty);
                }
            }

            return(null);
        }
Esempio n. 8
0
        private void OnClearCache(object sender, EventArgs e)
        {
            var isOk = MessageService.AskYesNo("Do you really want to clear Offline Cache Folder?\r\nMaybe your unsynced changes get lost!", "Clear Offline Cache", false);

            if (isOk)
            {
                ClearCache();
            }
        }
Esempio n. 9
0
        public static void AskCreate(PwDatabase pd)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return;
            }

            if (!Program.Config.UI.ShowEmSheetDialog)
            {
                return;
            }

            string str = KPRes.EmergencySheetInfo + MessageService.NewParagraph +
                         KPRes.EmergencySheetRec + MessageService.NewParagraph +
                         KPRes.EmergencySheetQ;

            VistaTaskDialog dlg = new VistaTaskDialog();

            dlg.CommandLinks    = true;
            dlg.Content         = str;
            dlg.DefaultButtonID = (int)DialogResult.OK;
            dlg.MainInstruction = KPRes.EmergencySheet;
            dlg.WindowTitle     = PwDefs.ShortProductName;

            dlg.AddButton((int)DialogResult.OK, KPRes.Print,
                          KPRes.EmergencySheetPrintInfo);
            dlg.AddButton((int)DialogResult.Cancel, KPRes.Skip, null);
            dlg.SetIcon(VtdCustomIcon.Question);

            bool bKeyFile = pd.MasterKey.ContainsType(typeof(KcpKeyFile));

            if (bKeyFile)
            {
                dlg.VerificationText = KPRes.KeyFilePrintAlso;
                dlg.FooterText       = KPRes.KeyFilePrintLocal;
                dlg.SetFooterIcon(VtdIcon.Information);
            }

            bool b;

            if (dlg.ShowDialog())
            {
                b = (dlg.Result == (int)DialogResult.OK);
            }
            else
            {
                b = MessageService.AskYesNo(str);
            }

            if (b)
            {
                bool bPrintKF = (bKeyFile ? dlg.ResultVerificationChecked : false);
                Print(pd, true, bPrintKF);
            }
        }
        internal static ProtectedString GenerateAcceptable(PwProfile prf,
                                                           byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx,
                                                           ref bool bAcceptAlways)
        {
            ProtectedString ps  = ProtectedString.Empty;
            SprContext      ctx = new SprContext(peOptCtx, pdOptCtx,
                                                 SprCompileFlags.NonActive, false, false);

            bool bAcceptable = false;

            while (!bAcceptable)
            {
                bAcceptable = true;

                PwGenerator.Generate(out ps, prf, pbUserEntropy, Program.PwGeneratorPool);
                if (ps == null)
                {
                    Debug.Assert(false); ps = ProtectedString.Empty;
                }

                if (bAcceptAlways)
                {
                }
                else
                {
                    string str    = ps.ReadString();
                    string strCmp = SprEngine.Compile(str, ctx);

                    if (str != strCmp)
                    {
                        if (prf.GeneratorType == PasswordGeneratorType.CharSet)
                        {
                            bAcceptable = false;                             // Silently try again
                        }
                        else
                        {
                            string strText = str + StrUtil.NewParagraph +
                                             KPRes.GenPwSprVariant + StrUtil.NewParagraph +
                                             KPRes.GenPwAccept;

                            if (!MessageService.AskYesNo(strText, null, false))
                            {
                                bAcceptable = false;
                            }
                            else
                            {
                                bAcceptAlways = true;
                            }
                        }
                    }
                }
            }

            return(ps);
        }
Esempio n. 11
0
        public static void EnsureConfigured(Form fParent)
        {
            SetFileSigKey(PwDefs.VersionUrl, AppDefs.Rsa4096PublicKeyXml);

            if (Program.Config.Application.Start.CheckForUpdateConfigured)
            {
                return;
            }

            // If the user has manually enabled the automatic update check
            // before, there's no need to ask him again
            if (!Program.Config.Application.Start.CheckForUpdate &&
                !Program.IsDevelopmentSnapshot())
            {
                string strHdr = KPRes.UpdateCheckInfo;
                string strSub = KPRes.UpdateCheckInfoRes + MessageService.NewParagraph +
                                KPRes.UpdateCheckInfoPriv;

                VistaTaskDialog dlg = new VistaTaskDialog();
                dlg.CommandLinks    = true;
                dlg.Content         = strHdr;
                dlg.MainInstruction = KPRes.UpdateCheckEnableQ;
                dlg.WindowTitle     = PwDefs.ShortProductName;
                dlg.AddButton((int)DialogResult.Yes, KPRes.Enable +
                              " (" + KPRes.Recommended + ")", null);
                dlg.AddButton((int)DialogResult.No, KPRes.Disable, null);
                dlg.SetIcon(VtdCustomIcon.Question);
                dlg.FooterText = strSub;
                dlg.SetFooterIcon(VtdIcon.Information);

                int iResult;
                if (dlg.ShowDialog(fParent))
                {
                    iResult = dlg.Result;
                }
                else
                {
                    string strMain = strHdr + MessageService.NewParagraph + strSub;
                    iResult = (MessageService.AskYesNo(strMain + MessageService.NewParagraph +
                                                       KPRes.UpdateCheckEnableQ, PwDefs.ShortProductName) ?
                               (int)DialogResult.Yes : (int)DialogResult.No);
                }

                Program.Config.Application.Start.CheckForUpdate = ((iResult ==
                                                                    (int)DialogResult.OK) || (iResult == (int)DialogResult.Yes));
            }

            Program.Config.Application.Start.CheckForUpdateConfigured = true;
        }
Esempio n. 12
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_bModified)
            {
                if (MessageService.AskYesNo(KPRes.SaveBeforeCloseQuestion))
                {
                    OnFileSave(sender, EventArgs.Empty);
                }
            }

            if (m_bURtfWithHighChar && (m_pbEditedData != null) &&
                !MemUtil.ArraysEqual(m_pbEditedData, m_pbData))
            {
                string strUrl = AppHelp.GetOnlineUrl(AppDefs.HelpTopics.KbFaq,
                                                     AppDefs.HelpTopics.KbFaqURtf);
                string strLink = VistaTaskDialog.CreateLink(strUrl, strUrl);
                string strMsg  = KPRes.URtfProblem + MessageService.NewParagraph +
                                 KPRes.URtfCheck + MessageService.NewParagraph +
                                 KPRes.URtfSuggestion + MessageService.NewParagraph +
                                 KPRes.MoreInfo + ":" + MessageService.NewLine;

                VistaTaskDialog dlg = new VistaTaskDialog();
                dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
                dlg.CommandLinks     = false;
                dlg.Content          = strMsg + strLink;
                dlg.DefaultButtonID  = (int)DialogResult.Cancel;
                dlg.EnableHyperlinks = true;
                dlg.SetIcon(VtdIcon.Warning);
                dlg.WindowTitle = PwDefs.ShortProductName;

                if (!dlg.ShowDialog())
                {
                    MessageService.ShowWarning(strMsg + strUrl);
                }
            }

            Debug.Assert(m_uBlockEvents == 0);

            string strRect = UIUtil.GetWindowScreenRect(this);

            if (strRect != m_strInitialFormRect)            // Don't overwrite ""
            {
                Program.Config.UI.DataEditorRect = strRect;
            }

            m_ctxText.Detach();
            GlobalWindowManager.RemoveWindow(this);
        }
Esempio n. 13
0
        void AskShouldAutodetect()
        {
            var result = MessageService.AskYesNo(
                "No KeePass database entries are enabled for use with KeeAgent." +
                " Would you like to attempt to auto-detect and enable entries with SSH keys?",
                "KeeAgent", true);

            if (result)
            {
                InitalizeList(true);
            }
            else
            {
                Close();
            }
        }
Esempio n. 14
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_bModified)
            {
                if (MessageService.AskYesNo(KPRes.SaveBeforeCloseQuestion))
                {
                    OnFileSave(sender, EventArgs.Empty);
                }
            }

            Program.Config.UI.DataEditorWidth  = this.Width;
            Program.Config.UI.DataEditorHeight = this.Height;

            m_ctxText.Detach();
            GlobalWindowManager.RemoveWindow(this);
        }
Esempio n. 15
0
        public static void AskCreate(PwDatabase pd)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return;
            }

            if (!Program.Config.UI.ShowEmSheetDialog)
            {
                return;
            }

            string str = KPRes.EmergencySheetInfo + MessageService.NewParagraph +
                         KPRes.EmergencySheetRec + MessageService.NewParagraph +
                         KPRes.EmergencySheetQ;

            VistaTaskDialog dlg = new VistaTaskDialog();

            dlg.CommandLinks    = true;
            dlg.Content         = str;
            dlg.DefaultButtonID = (int)DialogResult.OK;
            dlg.MainInstruction = KPRes.EmergencySheet;
            dlg.WindowTitle     = PwDefs.ShortProductName;

            dlg.AddButton((int)DialogResult.OK, KPRes.Print,
                          KPRes.EmergencySheetPrintInfo);
            dlg.AddButton((int)DialogResult.Cancel, KPRes.Skip, null);
            dlg.SetIcon(VtdCustomIcon.Question);

            bool b;

            if (dlg.ShowDialog())
            {
                b = (dlg.Result == (int)DialogResult.OK);
            }
            else
            {
                b = MessageService.AskYesNo(str);
            }

            if (b)
            {
                Print(pd);
            }
        }
Esempio n. 16
0
        private void OnOfflineCacheChanged(object sender, EventArgs e)
        {
            UpdateCacheButtonState();

            var path = m_configService.PluginConfiguration.OfflineCacheFolder;

            if (m_chkOfflineCache.Checked || !Directory.Exists(path))
            {
                return;
            }

            var isOk = MessageService.AskYesNo("You are disabeling Offline Cache.\r\nDo you want to clear Offline Cache Folder?\r\nMaybe your unsynced changes get lost!", "Clear Offline Cache", false);

            if (isOk)
            {
                ClearCache();
            }
        }
Esempio n. 17
0
        public void DeleteSelected()
        {
            bool singleItem = (SelectedIndices.Count == 1);

            var prompt = new VistaTaskDialog
            {
                CommandLinks    = false,
                Content         = CreateSummaryList(from RowObject rowObject in SelectedObjects select rowObject.Name),
                MainInstruction = singleItem ? Properties.Resources.DeleteAttachmentQuestion :
                                  Properties.Resources.DeleteAttachmentsQuestion,
                WindowTitle = PwDefs.ShortProductName
            };

            prompt.SetIcon(VtdCustomIcon.Question);
            prompt.AddButton((int)DialogResult.OK, KPRes.DeleteCmd, null);
            prompt.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, null);

            if (prompt.ShowDialog())
            {
                if (prompt.Result == (int)DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                if (!MessageService.AskYesNo(singleItem ? Properties.Resources.DeleteAttachmentQuestion : Properties.Resources.DeleteAttachmentsQuestion,
                                             singleItem ? Properties.Resources.DeleteAttachmentTitle : Properties.Resources.DeleteAttachmentsTitle))
                {
                    return;
                }
            }

            Entry.CreateBackup(Database);

            foreach (RowObject rowObject in SelectedObjects)
            {
                Entry.Binaries.Remove(rowObject.Name);
            }
            RemoveObjects(SelectedObjects);

            OnEntryModified(EventArgs.Empty);
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            if (MessageService.AskYesNo(KPRes.ImportMustRead + MessageService.NewParagraph +
                                        KPRes.ImportMustReadQuestion) == false)
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.ImportExport,
                                 AppDefs.HelpTopics.ImportExportSteganos);
                return;
            }

            PwEntry pePrev = new PwEntry(true, true);

            for (int i = 0; i < 20; ++i)
            {
                Thread.Sleep(500);
                Application.DoEvents();
            }

            try
            {
                while (true)
                {
                    PwEntry pe = ImportEntry(pwStorage);

                    if (ImportUtil.EntryEquals(pe, pePrev))
                    {
                        if (pe.ParentGroup != null)                        // Remove duplicate
                        {
                            pe.ParentGroup.Entries.Remove(pe);
                        }
                        break;
                    }

                    ImportUtil.GuiSendKeysPrc(@"{DOWN}");
                    pePrev = pe;
                }

                MessageService.ShowInfo(KPRes.ImportFinished);
            }
            catch (Exception exImp) { MessageService.ShowWarning(exImp); }
        }
Esempio n. 19
0
        public bool InitEx()
        {
            try
            {
                string strDir = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                         false, true);
                List <string> l = UrlUtil.GetFilePaths(strDir, "*." +
                                                       KPTranslation.FileExtension, SearchOption.TopDirectoryOnly);
                if (l.Count != 0)
                {
                    string str = KPRes.LngInAppDir + MessageService.NewParagraph;

                    const int cMaxFL = 6;
                    for (int i = 0; i < Math.Min(l.Count, cMaxFL); ++i)
                    {
                        if (i == (cMaxFL - 1))
                        {
                            str += "...";
                        }
                        else
                        {
                            str += l[i];
                        }
                        str += MessageService.NewLine;
                    }
                    str += MessageService.NewLine;

                    str += KPRes.LngInAppDirNote + MessageService.NewParagraph;
                    str += KPRes.LngInAppDirQ;

                    if (MessageService.AskYesNo(str, PwDefs.ShortProductName, true,
                                                MessageBoxIcon.Warning))
                    {
                        WinUtil.OpenUrlDirectly(strDir);
                        return(false);
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(true);
        }
Esempio n. 20
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_bModified)
            {
                if (MessageService.AskYesNo(KPRes.SaveBeforeCloseQuestion))
                {
                    OnFileSave(sender, EventArgs.Empty);
                }
            }

            string strRect = UIUtil.GetWindowScreenRect(this);

            if (strRect != m_strInitialFormRect)
            {
                Program.Config.UI.DataEditorRect = strRect;
            }

            m_ctxText.Detach();
            GlobalWindowManager.RemoveWindow(this);
        }
Esempio n. 21
0
        private bool ConfirmOperationOnAllEntries(string question, string command, PwEntry[] entries)
        {
            VistaTaskDialog dlg = new VistaTaskDialog();

            dlg.CommandLinks    = false;
            dlg.Content         = EntryUtil.CreateSummaryList(null, entries);
            dlg.MainInstruction = question;
            dlg.SetIcon(VtdCustomIcon.Question);
            dlg.WindowTitle = PwDefs.ShortProductName;
            dlg.AddButton((int)DialogResult.OK, command, null);
            dlg.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, null);

            if (dlg.ShowDialog())
            {
                return(dlg.Result == (int)DialogResult.OK);
            }
            else
            {
                return(MessageService.AskYesNo(question));
            }
        }
Esempio n. 22
0
        public override bool TryBeginImport()
        {
            string strTitle = KPRes.Warning + "!";
            string strMsg   = KPRes.RepairModeInt + MessageService.NewParagraph +
                              KPRes.RepairModeUse + MessageService.NewParagraph +
                              KPRes.RepairModeQ;

            int iYes = (int)DialogResult.Yes;
            int iNo  = (int)DialogResult.No;
            int r    = VistaTaskDialog.ShowMessageBoxEx(strMsg, strTitle,
                                                        PwDefs.ShortProductName, VtdIcon.Warning, null,
                                                        KPRes.YesCmd, iYes, KPRes.NoCmd, iNo);

            if (r < 0)
            {
                r = (MessageService.AskYesNo(strTitle + MessageService.NewParagraph +
                                             strMsg, PwDefs.ShortProductName, false, MessageBoxIcon.Warning) ?
                     iYes : iNo);
            }

            return((r == iYes) || (r == (int)DialogResult.OK));
        }
Esempio n. 23
0
        private void OnClickKeyFileBrowse(object sender, EventArgs e)
        {
            string           strFilter = AppDefs.GetKeyFileFilter();
            OpenFileDialogEx ofd       = UIUtil.CreateOpenFileDialog(KPRes.KeyFileUseExisting,
                                                                     strFilter, 1, null, false, AppDefs.FileDialogContext.KeyFile);

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string strFile = ofd.FileName;

            try
            {
                // Test whether we can read the file
                IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
                IOConnection.OpenRead(ioc).Close();

                // Check the file size?
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); return; }

            if (!KfxFile.CanLoad(strFile))
            {
                if (!MessageService.AskYesNo(strFile + MessageService.NewParagraph +
                                             KPRes.KeyFileNoXml + MessageService.NewParagraph +
                                             KPRes.KeyFileUseAnywayQ, null, false))
                {
                    return;
                }
            }

            m_cmbKeyFile.Items.Add(strFile);
            m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;

            EnableUserControls();
        }
Esempio n. 24
0
        private void OnClickKeyFileBrowse(object sender, EventArgs e)
        {
            string strFile = FileDialogsEx.ShowKeyFileDialog(false,
                                                             KPRes.KeyFileUseExisting, null, false, m_bSecureDesktop);

            if (string.IsNullOrEmpty(strFile))
            {
                return;
            }

            try
            {
                IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
                if (!IOConnection.FileExists(ioc, true))
                {
                    throw new FileNotFoundException();
                }

                // Check the file size?
            }
            catch (Exception ex) { MessageService.ShowWarning(strFile, ex); return; }

            if (!KfxFile.CanLoad(strFile))
            {
                if (!MessageService.AskYesNo(strFile + MessageService.NewParagraph +
                                             KPRes.KeyFileNoXml + MessageService.NewParagraph +
                                             KPRes.KeyFileUseAnywayQ, null, false))
                {
                    return;
                }
            }

            m_cmbKeyFile.Items.Add(strFile);
            m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;

            UpdateUIState();
        }
Esempio n. 25
0
        // Copied from PwEntryForm.SaveAttachmentTo (PwEntryForm.cs)
        private void SaveAttachmentTo(ProtectedBinary pb, string strFileName,
                                      bool bConfirmOverwrite)
        {
            Debug.Assert(pb != null); if (pb == null)
            {
                throw new ArgumentNullException("pb");
            }
            Debug.Assert(strFileName != null); if (strFileName == null)
            {
                throw new ArgumentNullException("strFileName");
            }

            if (bConfirmOverwrite && File.Exists(strFileName))
            {
                string strMsg = KPRes.FileExistsAlready + MessageService.NewLine +
                                strFileName + MessageService.NewParagraph +
                                KPRes.OverwriteExistingFileQuestion;

                if (MessageService.AskYesNo(strMsg) == false)
                {
                    return;
                }
            }

            Debug.Assert(pb != null); if (pb == null)
            {
                throw new ArgumentException();
            }

            byte[] pbData = pb.ReadData();
            try { File.WriteAllBytes(strFileName, pbData); }
            catch (Exception exWrite)
            {
                MessageService.ShowWarning(strFileName, exWrite);
            }
            MemUtil.ZeroByteArray(pbData);
        }
Esempio n. 26
0
 /// <summary>
 /// When the plugin detects a change in the MasterKey, it uses this method to prompt the user to update or delete the data
 /// </summary>
 /// <param name="ioInfo">IOConnectionInfo that represents the database.</param>
 /// <param name="dbPath">Name of the credential to update or delete.</param>
 /// <param name="opening">If the masterkey change was detected during database unlock use true.</param>
 internal static async Task HandleMasterKeyChange(IOConnectionInfo ioInfo, string dbPath, bool opening)
 {
     if (opening)
     {
         string str = WinHelloUnlockExt.ProductName + " could not unlock this database." +
                      " MasterKey must have changed. Delete " + WinHelloUnlockExt.ProductName + " data?";
         if (MessageService.AskYesNo(str, WinHelloUnlockExt.ProductName))
         {
             UWPLibrary.DeleteHelloData(dbPath);
         }
         WinHelloUnlockExt.opened = true;
         WinHelloUnlockExt.Host.MainWindow.OpenDatabase(ioInfo, null, false);
     }
     else
     {
         string str = "A change in MasterKey has been detected. Do you want to update " +
                      WinHelloUnlockExt.ProductName + " data?";
         if (MessageService.AskYesNo(str, WinHelloUnlockExt.ProductName))
         {
             UWPLibrary.DeleteHelloData(dbPath);
             await UWPLibrary.CreateHelloData(dbPath);
         }
     }
 }
Esempio n. 27
0
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

            if (m_cbPassword.Checked)            // Use a password
            {
                if (!m_icgPassword.ValidateData(true))
                {
                    return(false);
                }

                uint uPwLen = m_icgPassword.PasswordLength;
                if (uPwLen == 0)
                {
                    if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                                 MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                                 MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                                 null, false))
                    {
                        return(false);
                    }
                }

                uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength;
                if (uPwLen < uMinLen)
                {
                    string strML = KPRes.MasterPasswordMinLengthFailed;
                    strML = strML.Replace(@"{PARAM}", uMinLen.ToString());
                    MessageService.ShowWarning(strML);
                    return(false);
                }

                byte[] pb = m_icgPassword.GetPasswordUtf8();

                uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality;
                if (QualityEstimation.EstimatePasswordBits(pb) < uMinQual)
                {
                    string strMQ = KPRes.MasterPasswordMinQualityFailed;
                    strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString());
                    MessageService.ShowWarning(strMQ);
                    MemUtil.ZeroByteArray(pb);
                    return(false);
                }

                string strValRes = Program.KeyValidatorPool.Validate(pb,
                                                                     KeyValidationType.MasterPassword);
                if (strValRes != null)
                {
                    MessageService.ShowWarning(strValRes);
                    MemUtil.ZeroByteArray(pb);
                    return(false);
                }

                m_pKey.AddUserKey(new KcpPassword(pb));
                MemUtil.ZeroByteArray(pb);
            }

            string strKeyFile = m_cmbKeyFile.Text;
            bool   bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(strKeyFile);

            if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                !bIsKeyProv)
            {
                try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile, true)); }
                catch (InvalidDataException exID)                // Selected database file
                {
                    MessageService.ShowWarning(strKeyFile, exID);
                    return(false);
                }
                catch (Exception exKF)
                {
                    MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKF);
                    return(false);
                }
            }
            else if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                     bIsKeyProv)
            {
                KeyProviderQueryContext ctxKP = new KeyProviderQueryContext(
                    m_ioInfo, true, false);

                bool   bPerformHash;
                byte[] pbCustomKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP,
                                                                    out bPerformHash);
                if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                {
                    try { m_pKey.AddUserKey(new KcpCustomKey(strKeyFile, pbCustomKey, bPerformHash)); }
                    catch (Exception exCKP)
                    {
                        MessageService.ShowWarning(exCKP);
                        return(false);
                    }

                    MemUtil.ZeroByteArray(pbCustomKey);
                }
                else
                {
                    return(false);                 // Provider has shown error message
                }
            }

            if (m_cbUserAccount.Checked)
            {
                try { m_pKey.AddUserKey(new KcpUserAccount()); }
                catch (Exception exUA)
                {
                    MessageService.ShowWarning(exUA);
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 28
0
        private static byte[] OpenExternal(string strName, byte[] pbData,
                                           BinaryDataOpenOptions opt)
        {
            byte[] pbResult = null;

            try
            {
                string strBaseTempDir = UrlUtil.EnsureTerminatingSeparator(
                    UrlUtil.GetTempPath(), false);

                string strTempID, strTempDir;
                while (true)
                {
                    byte[] pbRandomID = CryptoRandom.Instance.GetRandomBytes(8);
                    strTempID = Convert.ToBase64String(pbRandomID);
                    strTempID = StrUtil.AlphaNumericOnly(strTempID);
                    if (strTempID.Length == 0)
                    {
                        Debug.Assert(false); continue;
                    }

                    strTempDir = strBaseTempDir + strTempID;
                    if (!Directory.Exists(strTempDir))
                    {
                        Directory.CreateDirectory(strTempDir);

                        strTempDir = UrlUtil.EnsureTerminatingSeparator(
                            strTempDir, false);

                        // Mark directory as encrypted, such that new files
                        // are encrypted automatically; there exists no
                        // Directory.Encrypt method, but we can use File.Encrypt,
                        // because this internally uses the EncryptFile API
                        // function, which works with directories
                        try { File.Encrypt(strTempDir); }
                        catch (Exception) { Debug.Assert(false); }

                        break;
                    }
                }

                string strFile = strTempDir + strName;
                File.WriteAllBytes(strFile, pbData);

                // Encrypt again, in case the directory encryption above failed
                try { File.Encrypt(strFile); }
                catch (Exception) { Debug.Assert(false); }

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName         = strFile;
                psi.UseShellExecute  = true;
                psi.WorkingDirectory = strTempDir;

                ParameterizedThreadStart pts = new ParameterizedThreadStart(
                    BinaryDataUtil.ShellOpenFn);
                Thread th = new Thread(pts);
                th.Start(psi);

                string strMsgMain = KPRes.AttachExtOpened + MessageService.NewParagraph +
                                    KPRes.AttachExtOpenedPost + ":";
                string strMsgImp        = KPRes.Import;
                string strMsgImpDesc    = KPRes.AttachExtImportDesc;
                string strMsgCancel     = KPRes.DiscardChangesCmd;
                string strMsgCancelDesc = KPRes.AttachExtDiscardDesc;

                VistaTaskDialog vtd = new VistaTaskDialog();
                vtd.CommandLinks    = true;
                vtd.Content         = strMsgMain;
                vtd.MainInstruction = strName;
                vtd.WindowTitle     = PwDefs.ShortProductName;
                vtd.SetIcon(VtdCustomIcon.Question);

                vtd.AddButton((int)DialogResult.OK, strMsgImp, strMsgImpDesc);
                vtd.AddButton((int)DialogResult.Cancel, strMsgCancel, strMsgCancelDesc);

                vtd.FooterText = KPRes.AttachExtSecDel;
                vtd.SetFooterIcon(VtdIcon.Information);

                bool bImport;
                if (vtd.ShowDialog())
                {
                    bImport = ((vtd.Result == (int)DialogResult.OK) ||
                               (vtd.Result == (int)DialogResult.Yes));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(strName);
                    sb.AppendLine();
                    sb.AppendLine(strMsgMain);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.Yes + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgImp) +
                                  " - " + strMsgImpDesc);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.No + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgCancel) +
                                  " - " + strMsgCancelDesc);
                    sb.AppendLine();
                    sb.AppendLine(KPRes.AttachExtSecDel);

                    bImport = MessageService.AskYesNo(sb.ToString(),
                                                      PwDefs.ShortProductName);
                }

                if (bImport && !opt.ReadOnly)
                {
                    while (true)
                    {
                        try
                        {
                            pbResult = File.ReadAllBytes(strFile);
                            break;
                        }
                        catch (Exception exRead)
                        {
                            if (!AskForRetry(strFile, exRead.Message))
                            {
                                break;
                            }
                        }
                    }
                }

                string strReportObj = null;
                while (true)
                {
                    try
                    {
                        strReportObj = strFile;
                        if (File.Exists(strFile))
                        {
                            FileInfo fiTemp = new FileInfo(strFile);
                            long     cb     = fiTemp.Length;
                            if (cb > 0)
                            {
                                byte[] pbOvr = new byte[cb];
                                Program.GlobalRandom.NextBytes(pbOvr);
                                File.WriteAllBytes(strFile, pbOvr);
                            }

                            File.Delete(strFile);
                        }

                        strReportObj = strTempDir;
                        if (Directory.Exists(strTempDir))
                        {
                            Directory.Delete(strTempDir, true);
                        }

                        break;
                    }
                    catch (Exception exDel)
                    {
                        if (!AskForRetry(strReportObj, exDel.Message))
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageService.ShowWarning(ex.Message);
            }

            return(pbResult);
        }
        private async void OnOkClick(object sender, EventArgs e)
        {
            DialogResult = DialogResult.None;
            if (string.IsNullOrEmpty(m_txtFilename.Text))
            {
                return;
            }

            // Ckech whether an extension is given for saving
            if (m_mode == Mode.Save && !CloudPath.HasExtension(m_txtFilename.Text))
            {
                m_txtFilename.Text = CloudPath.ChangeExtension(m_txtFilename.Text, "kdbx");
            }

            var filename = m_txtFilename.Text;

            if (string.IsNullOrEmpty(filename))
            {
                return;
            }

            var itemInfo = await GetItemInfo(m_selectedItem);

            var subItem = itemInfo.Children.SingleOrDefault(_ => _.Name == filename);

            switch (m_mode)
            {
            case Mode.Open:
                if (subItem == null)
                {
                    MessageService.ShowWarning("File/Folder does not exist.");
                }
                else
                {
                    switch (subItem.Type)
                    {
                    case StorageProviderItemType.File:
                        DialogResult = DialogResult.OK;
                        break;

                    case StorageProviderItemType.Folder:
                        SetWaitState(true);

                        m_txtFilename.Text = null;
                        m_stack.Push(subItem);
                        await SetSelectedItem(subItem);

                        SetWaitState(false);
                        break;
                    }
                }

                break;

            case Mode.Save:
                if (!m_provider.IsFilenameValid(filename))
                {
                    MessageService.ShowWarning("Filename is invalid.");
                }
                else if (subItem == null)
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    switch (subItem.Type)
                    {
                    case StorageProviderItemType.File:
                        var result = MessageService.AskYesNo("The file already exists.\nWould you like to override?",
                                                             "Overwrite file");

                        if (result)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        break;

                    case StorageProviderItemType.Folder:
                        SetWaitState(true);

                        m_txtFilename.Text = null;
                        m_stack.Push(subItem);
                        await SetSelectedItem(subItem);

                        SetWaitState(false);
                        break;
                    }
                }

                break;

            default:
                throw new NotImplementedException();
            }
        }
Esempio n. 30
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            m_Config.Key2Transformations = (ulong)numTransformations.Value;
            m_Config.Algorithm1          = ((KeyValuePair <SymAlgoCode, string>)cmbAlgo1.SelectedItem).Key;
            m_Config.Algorithm2          = ((KeyValuePair <SymAlgoCode, string>)cmbAlgo2.SelectedItem).Key;

            if (grp2ndKey.Enabled)
            {
                if (rdoDual.Checked)
                {
                    if (m_Config.GetNewDualPassword() == null)
                    {
                        return;
                    }
                    m_Config.KeyOption = KeyOption.DualPassword;
                }
                else if (rdoSingle.Checked)
                {
                    m_Config.DeriveDualKey();
                    m_Config.KeyOption = KeyOption.SinglePassword;
                }
                else if (rdoYubikeyHMACMode.Checked)
                {
                    if (!rdoSlot1.Checked && !rdoSlot2.Checked)
                    {
                        MessageService.ShowWarning("MultiCipher Plugin:", "Please Choose Yubikey Slot");
                        return;
                    }

                    if (!rdoVariable.Checked && !rdoFixed.Checked)
                    {
                        MessageService.ShowWarning("MultiCipher Plugin:", "Please Choose Variable or Fixed Challenge Input");
                        return;
                    }


                    byte YubikeySlot     = 2;
                    byte ChallengeLength = ConfigYubikey.CHALLENGE_LEN_64;

                    if (rdoSlot1.Checked)
                    {
                        YubikeySlot = 1;
                    }

                    if (rdoVariable.Checked)
                    {
                        ChallengeLength = ConfigYubikey.CHALLENGE_LEN_VARIABLE;
                    }

                    bool            ValidateKey = MessageService.AskYesNo("It is highly recommended that you validate the secret key to make sure that Challenge/Response is working correctly.\r\n\r\nDo you want to validate the secret key", "Please Confirm", true, MessageBoxIcon.Question);
                    ProtectedBinary Response;
                    if (ValidateKey)
                    {
                        var             f            = new VerifyFrm();
                        DialogResult    dr           = f.ShowDialog();
                        ProtectedBinary SecProtected = f.SecretKey;
                        UIUtil.DestroyForm(f);

                        if (dr != DialogResult.OK || SecProtected == null)
                        {
                            return;
                        }
                        Response = m_Config.Yubikey.GetYubikeyResponse(YubikeySlot, ChallengeLength, SecProtected, false);
                    }
                    else
                    {
                        Response = m_Config.Yubikey.GetYubikeyResponse(YubikeySlot, ChallengeLength, null, false);
                    }

                    if (Response == null)
                    {
                        MessageService.ShowWarning("Yubikey Challenge/Response Failed");
                        return;
                    }

                    if (ValidateKey)
                    {
                        MessageService.ShowInfo("Key Validation Successful!");
                    }

                    m_Config.GetFromRecovery(Response);  // Set the 2nd key
                    m_Config.YubikeySlot            = YubikeySlot;
                    m_Config.YubikeyChallengeLength = ChallengeLength;
                    m_Config.KeyOption = KeyOption.Yubikey_HMAC_SHA1;

                    // Show the newly generated 2nd key to the user
                    var fRecovery = new RecoveryKeyFrm(Response);
                    fRecovery.ShowDialog();
                    UIUtil.DestroyForm(fRecovery);
                }
                else
                {
                    MessageService.ShowWarning("MultiCipher Plugin:", "Please Choose Password Mode");
                    return;
                }
            }

            m_Config.Host.Database.Modified = true;

            DialogResult = DialogResult.OK;
        }