コード例 #1
0
ファイル: Library.cs プロジェクト: ii0/WinHelloUnlock
        /// <summary>
        /// Unlocks the database prompted to unlock on the KeyPromptForm
        /// </summary>
        /// <param name="ioInfo">IOConnectionInfo that represents the database.</param>
        /// <param name="keyPromptForm">KeyPromptForm to unlock the database from.</param>
        internal async static void UnlockDatabase(IOConnectionInfo ioInfo, KeyPromptForm keyPromptForm)
        {
            // Only one try is allowed
            if (WinHelloUnlockExt.tries < 1)
            {
                if (KeePass.Program.Config.Security.MasterKeyOnSecureDesktop)
                {
                    WinHelloUnlockExt.secureChaged = true;
                    WinHelloUnlockExt.isMonitoring = true;
                    var _ = Task.Factory.StartNew(() => CloseWarning());
                    KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = false;

                    UWPLibrary.Unlock(keyPromptForm, new CompositeKey());
                }
                else
                {
                    await UWPLibrary.UnlockDatabase(ioInfo, keyPromptForm);

                    ++WinHelloUnlockExt.tries;

                    if (WinHelloUnlockExt.secureChaged)
                    {
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                        WinHelloUnlockExt.secureChaged = false;
                    }
                }
            }
            else
            {
                keyPromptForm.Visible = true;
                keyPromptForm.Opacity = 1;
            }

            WinHelloUnlockExt.opened = true;
        }
コード例 #2
0
            private CompositeKey OTPDB_RequestPassword(bool bSetNewPassword, out bool bCancel)
            {
                bCancel = false;
                if (!bSetNewPassword && Program.Config.Security.MasterKeyOnSecureDesktop &&
                    KeePass.Util.WinUtil.IsAtLeastWindows2000 && !NativeLib.IsUnix())
                {
                    CompositeKey ck = new CompositeKey();
                    try { ck = OTPDB_RequestPasswordSecure(bSetNewPassword, out bCancel); }
                    catch (Exception ex) { Tools.ShowError(ex.Message); }
                    return(ck);
                }
                if (!bSetNewPassword)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    SetKeyPromptFormTitle(kpf);
                    bCancel = kpf.ShowDialog() != DialogResult.OK;
                    if (bCancel)
                    {
                        return(new CompositeKey());
                    }
                    return(kpf.CompositeKey);
                }
                KeyCreationForm kcf = new KeyCreationForm();

                kcf.InitEx(null, true);
                bCancel = kcf.ShowDialog() != DialogResult.OK;
                if (bCancel)
                {
                    return(OTPDB.MasterKey);
                }
                return(kcf.CompositeKey);
            }
コード例 #3
0
        private void GlobalWindowManager_WindowAdded(object sender, GwmWindowEventArgs e)
        {
            // get references for password fields on unlocking and creating a database
            // if a yubikey is inserted, the password field is overwriten with a value
            // derived from the password and the yubikey-challenge-response

            if (e.Form is KeyPromptForm)
            {
                _keyPromtForm            = (KeyPromptForm)e.Form;
                _keyPromtForm_okButton   = (Button)_keyPromtForm.Controls.Find("m_btnOK", false)[0];
                _keyPromtForm_usePw      = (CheckBox)_keyPromtForm.Controls.Find("m_cbPassword", false)[0];
                _keyPromtForm_secureEdit = (SecureEdit)typeof(KeyPromptForm)
                                           .GetField("m_secPassword", BindingFlags.NonPublic | BindingFlags.Instance)
                                           .GetValue(_keyPromtForm);

                injectHandler(_keyPromtForm_okButton, keyPromtForm_onConfirmClick);
            }

            else if (e.Form is KeyCreationForm)
            {
                _createKeyForm              = (KeyCreationForm)e.Form;
                _createKeyForm_okButton     = (Button)_createKeyForm.Controls.Find("m_btnCreate", false)[0];
                _createKeyForm_usePw        = (CheckBox)_createKeyForm.Controls.Find("m_cbPassword", false)[0];
                _createKeyForm_pwInputGroup = (PwInputControlGroup)typeof(KeyCreationForm)
                                              .GetField("m_icgPassword", BindingFlags.NonPublic | BindingFlags.Instance)
                                              .GetValue(_createKeyForm);

                _createKeyForm.VisibleChanged += _createKeyForm_VisibleChanged;

                injectHandler(_createKeyForm_okButton, keyCreateForm_onConfirmClick);
            }
        }
コード例 #4
0
 private void WindowRemoved(object sender, GwmWindowEventArgs e)
 {
     if ((m_kpf != null) && (e.Form is KeyPromptForm))
     {
         m_kpf = null;
     }
 }
コード例 #5
0
ファイル: KeyUtil.cs プロジェクト: matt2005/keepass2
        public static bool ReAskKey(PwDatabase pwDatabase, bool bFailWithUI)
        {
            if (pwDatabase == null)
            {
                Debug.Assert(false); return(false);
            }

            KeyPromptForm dlg = new KeyPromptForm();

            dlg.InitEx(pwDatabase.IOConnectionInfo, false, true,
                       KPRes.EnterCurrentCompositeKey);
            if (UIUtil.ShowDialogNotValue(dlg, DialogResult.OK))
            {
                return(false);
            }

            CompositeKey ck      = dlg.CompositeKey;
            bool         bResult = ck.EqualsValue(pwDatabase.MasterKey);

            if (!bResult)
            {
                MessageService.ShowWarning(KLRes.InvalidCompositeKey,
                                           KLRes.InvalidCompositeKeyHint);
            }

            UIUtil.DestroyForm(dlg);
            return(bResult);
        }
コード例 #6
0
        public void OnKeyPrompt(KeyPromptForm keyPromptForm)
        {
            if (keyPromptForm.SecureDesktopMode)
            {
                return;
            }

            if (!Settings.Instance.Enabled)
            {
                return;
            }

            CompositeKey compositeKey;

            if (ExtractCompositeKey(GetDbPath(keyPromptForm), out compositeKey))
            {
                SetCompositeKey(keyPromptForm, compositeKey);
                // Remove flushing
                keyPromptForm.Visible = false;
                keyPromptForm.Opacity = 0;

                keyPromptForm.DialogResult = DialogResult.OK;
                keyPromptForm.Close();
            }
        }
コード例 #7
0
ファイル: KeyUtil.cs プロジェクト: 0xfeeddeadbeef/KeePass
        public static bool ReAskKey(PwDatabase pd, bool bFailWithUI)
        {
            if (pd == null)
            {
                Debug.Assert(false); return(false);
            }

            KeyPromptFormResult r;
            DialogResult        dr = KeyPromptForm.ShowDialog(pd.IOConnectionInfo,
                                                              false, KPRes.EnterCurrentCompositeKey, out r);

            if ((dr != DialogResult.OK) || (r == null))
            {
                return(false);
            }

            CompositeKey ck     = r.CompositeKey;
            bool         bEqual = ck.EqualsValue(pd.MasterKey);

            if (!bEqual && bFailWithUI)
            {
                MessageService.ShowWarning(KLRes.InvalidCompositeKey,
                                           KLRes.InvalidCompositeKeyHint);
            }

            return(bEqual);
        }
コード例 #8
0
        private static void SetCompositeKey(KeyPromptForm keyPromptForm, CompositeKey compositeKey)
        {
            var fieldInfo = keyPromptForm.GetType().GetField("m_pKey", BindingFlags.Instance | BindingFlags.NonPublic);

            if (fieldInfo != null)
            {
                fieldInfo.SetValue(keyPromptForm, compositeKey);
            }
        }
コード例 #9
0
ファイル: Library.cs プロジェクト: ii0/WinHelloUnlock
        /// <summary>
        /// Closes the KeyPromptForm with a specific result (Equivalent to click the specific button)
        /// </summary>
        /// <param name="keyPromptForm">KeyPromptForm to close.</param>
        /// <param name="result">Result to close the form with.</param>
        internal static void CloseFormWithResult(KeyPromptForm keyPromptForm, DialogResult result)
        {
            // Remove flushing
            keyPromptForm.Visible = false;
            keyPromptForm.Opacity = 0;

            keyPromptForm.DialogResult = result;
            keyPromptForm.Close();
        }
コード例 #10
0
        private static string GetDbPath(KeyPromptForm keyPromptForm)
        {
            var ioInfo = GetIoInfo(keyPromptForm);

            if (ioInfo == null)
            {
                return(null);
            }
            return(ioInfo.Path);
        }
コード例 #11
0
        private static IOConnectionInfo GetIoInfo(KeyPromptForm keyPromptForm)
        {
            var fieldInfo = keyPromptForm.GetType().GetField("m_ioInfo", BindingFlags.Instance | BindingFlags.NonPublic);

            if (fieldInfo == null)
            {
                return(null);
            }
            return(fieldInfo.GetValue(keyPromptForm) as IOConnectionInfo);
        }
コード例 #12
0
            private Form OdKpfConstruct(object objParam)
            {
                System.Reflection.MethodInfo mi = typeof(MainForm).GetMethod("OdKpfConstruct", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                KeyPromptForm kpf = mi.Invoke(null, new object[] { objParam }) as KeyPromptForm;

                if (kpf != null)
                {
                    SetKeyPromptFormTitle(kpf);
                }
                return(kpf);
            }
コード例 #13
0
        public void OnKeyPrompt(KeyPromptForm keyPromptForm, MainForm mainWindow)
        {
            if (!Settings.Instance.Enabled)
            {
                return;
            }

            string dbPath = GetDbPath(keyPromptForm);

            if (keyPromptForm.SecureDesktopMode)
            {
                if (IsKeyForDataBaseExist(dbPath))
                {
                    if (_cancellationTokenSource == null)
                    {
                        _cancellationTokenSource = new CancellationTokenSource();
                    }

                    Task.Factory.StartNew(() => MonitorWarning(_cancellationTokenSource.Token), _cancellationTokenSource.Token);

                    try
                    {
                        int masterKeyTries = KeePass.Program.Config.Security.MasterKeyTries;
                        Interlocked.Exchange(ref _masterKeyTries, masterKeyTries);
                        KeePass.Program.Config.Security.MasterKeyTries           = ++masterKeyTries;
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = false;
                        SetCompositeKey(keyPromptForm, new CompositeKey());
                        CloseFormWithResult(keyPromptForm, DialogResult.OK);
                    }
                    catch
                    {
                        StopMonitorWarning();
                        throw;
                    }
                }
            }
            else
            {
                StopMonitorWarning();

                int oldTriesValue = Interlocked.Exchange(ref _masterKeyTries, NoChanges);
                if (oldTriesValue != NoChanges)
                {
                    KeePass.Program.Config.Security.MasterKeyTries           = oldTriesValue;
                    KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                }

                Unlock(keyPromptForm, dbPath);
            }
        }
コード例 #14
0
 private void Unlock(KeyPromptForm keyPromptForm, string dbPath)
 {
     try
     {
         CompositeKey compositeKey;
         if (ExtractCompositeKey(dbPath, out compositeKey))
         {
             SetCompositeKey(keyPromptForm, compositeKey);
             CloseFormWithResult(keyPromptForm, DialogResult.OK);
         }
     }
     catch (AuthProviderUserCancelledException)
     {
         CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
     }
 }
コード例 #15
0
ファイル: UWPLibrary.cs プロジェクト: mikalv/WinHelloUnlock
        /// <summary>
        /// Unlocks the database using KeyPromptForm
        /// </summary>
        internal static void Unlock(KeyPromptForm keyPromptForm, CompositeKey compositeKey)
        {
            try
            {
                var fieldInfo = keyPromptForm.GetType().GetField("m_pKey", BindingFlags.Instance | BindingFlags.NonPublic);
                if (fieldInfo != null)
                {
                    fieldInfo.SetValue(keyPromptForm, compositeKey);
                }
                //keyPromptForm.Visible = false;
                //keyPromptForm.Opacity = 1;

                keyPromptForm.DialogResult = DialogResult.OK;
                keyPromptForm.Close();
            }
            catch (Exception) { }
        }
コード例 #16
0
        public void OnKeyPrompt(KeyPromptForm keyPromptForm, MainForm mainWindow)
        {
            if (!Settings.Instance.Enabled)
            {
                return;
            }

            string dbPath = GetDbPath(keyPromptForm);

            if (keyPromptForm.SecureDesktopMode)
            {
                if (IsKeyForDataBaseExist(dbPath))
                {
                    var dbFile = GetIoInfo(keyPromptForm);
                    CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
                    Task.Factory.StartNew(() =>
                    {
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = false;
                        _isSecureDesktopSettingChanged = true;
                        Thread.Yield();
                        ReOpenKeyPromptForm(mainWindow, dbFile);
                    })
                    .ContinueWith(_ =>
                    {
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                        _isSecureDesktopSettingChanged = false;
                    });
                }
            }
            else
            {
                CompositeKey compositeKey;
                if (ExtractCompositeKey(dbPath, out compositeKey))
                {
                    SetCompositeKey(keyPromptForm, compositeKey);
                    CloseFormWithResult(keyPromptForm, DialogResult.OK);
                }
                else if (_isSecureDesktopSettingChanged)
                {
                    var dbFile = GetIoInfo(keyPromptForm);
                    CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
                    Task.Factory.StartNew(() => ReOpenKeyPromptForm(mainWindow, dbFile));
                }
            }
        }
コード例 #17
0
ファイル: Library.cs プロジェクト: ii0/WinHelloUnlock
        /// <summary>
        /// Reopens the KeyPromptForm whenever a change in MasterKeyOnSecureDesktop is made.
        /// </summary>
        internal static void ReopenKeyPromptForm(KeyPromptForm keyPromptForm)
        {
            if (WinHelloUnlockExt.secureChaged)
            {
                KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                WinHelloUnlockExt.secureChaged = false;

                WinHelloUnlockExt.isMonitoring = true;
                var _ = Task.Factory.StartNew(() => Library.CloseWarning());

                UWPLibrary.Unlock(keyPromptForm, new CompositeKey());
            }
            else
            {
                keyPromptForm.Visible = true;
                keyPromptForm.Opacity = 1;
            }
        }
コード例 #18
0
        /// <summary>
        /// Only perform update check if last used database has to be opened automatically
        /// If this is not the case, use KeePass standard check for updates
        /// </summary>
        private void KeyPromptFormAdded()
        {
            if (!PluginConfig.Active)
            {
                return;
            }
            UpdateCheckType uct = UpdateCheckRequired();

            if (uct == UpdateCheckType.NotRequired)
            {
                return;
            }
            if (uct == UpdateCheckType.OnlyTranslations)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckPluginLanguages));
                return;
            }
            m_kpf = GlobalWindowManager.TopWindow as KeyPromptForm;
            UpdateCheckEx.EnsureConfigured(m_host.MainWindow);
            //Try calling the internal method UpdateCheckEx.RunPriv
            //==> Running this in a seperate threads does not force the user to wait
            //    in case of e. g. connection issues
            //==> Creating this seperate thread manually allows
            //      - to check for completion of the update check
            //      - show the update window BEFORE "Open Database" window is shown
            //      - Skip waiting in case of e. g. connection issues
            //
            //As fallback the public method UpdateCheckRunEx.Run is called
            //This method runs in a separate thread
            //==> Update window might be shown AFTER "Open Database" window is shown
            if (PluginConfig.CheckSync)
            {
                UpdateCheckBackground();
            }
            if ((m_UpdateCheckStatus == UpdateCheckStatus.NotChecked) || (m_UpdateCheckStatus == UpdateCheckStatus.Error))
            {
                UpdateCheckEx.Run(false, null);
            }
        }
コード例 #19
0
 private void Unlock(KeyPromptForm keyPromptForm, string dbPath)
 {
     try
     {
         CompositeKey compositeKey;
         if (ExtractCompositeKey(dbPath, out compositeKey))
         {
             SetCompositeKey(keyPromptForm, compositeKey);
             CloseFormWithResult(keyPromptForm, DialogResult.OK);
         }
     }
     catch (AuthProviderKeyNotFoundException ex)
     {
         // It's expected not to throw exceptions
         ClaimCurrentCacheType(AuthCacheType.Local);
         ErrorHandler.ShowError(ex, "Credential Manager storage has been turned off. Use Options dialog to turn it on.");
         CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
     }
     catch (AuthProviderUserCancelledException)
     {
         CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
     }
 }
コード例 #20
0
            private CompositeKey OTPDB_RequestPassword(bool bSetNewPassword, out bool bCancel)
            {
                if (!bSetNewPassword)
                {
                    KeyPromptForm kpf   = new KeyPromptForm();
                    string        title = string.Format(PluginTranslate.OTP_OpenDB, string.IsNullOrEmpty(DB.Name) ? UrlUtil.GetFileName(DB.IOConnectionInfo.Path) : DB.Name);
                    kpf.InitEx(OTPDB.IOConnectionInfo, false, false, title);
                    bCancel = kpf.ShowDialog() != DialogResult.OK;
                    if (bCancel)
                    {
                        return(new CompositeKey());
                    }
                    return(kpf.CompositeKey);
                }
                KeyCreationForm kcf = new KeyCreationForm();

                kcf.InitEx(null, true);
                bCancel = kcf.ShowDialog() != DialogResult.OK;
                if (bCancel)
                {
                    return(OTPDB.MasterKey);
                }
                return(kcf.CompositeKey);
            }
コード例 #21
0
        private static void RunScriptLine(CommandLineArgs args)
        {
            string strCommand = args[ParamCommand];

            if (strCommand == null)
            {
                throw new InvalidOperationException(KSRes.NoCommand);
            }

            if (args.FileName == null)
            {
                RunSingleCommand(strCommand.ToLower());
                return;
            }

            IOConnectionInfo ioc = new IOConnectionInfo();

            ioc.Url          = args.FileName;
            ioc.CredSaveMode = IOCredSaveMode.NoSave;

            CompositeKey cmpKey = null;

            if (args[ParamGuiKey] != null)
            {
                EnsureGuiInitialized();
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc.GetDisplayName(), false);
                if (kpf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                cmpKey = kpf.CompositeKey;
            }
            else if (args[ParamConsoleKey] != null)
            {
                cmpKey = new CompositeKey();

                Console.WriteLine(KSRes.NoKeyPartHint);
                Console.WriteLine();
                Console.WriteLine(KSRes.KeyPrompt);

                Console.Write(KSRes.PasswordPrompt + " ");
                string strPw = Console.ReadLine().Trim();
                if ((strPw != null) && (strPw.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpPassword(strPw));
                }

                Console.Write(KSRes.KeyFilePrompt + " ");
                string strFile = Console.ReadLine().Trim();
                if ((strFile != null) && (strFile.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpKeyFile(strFile));
                }

                Console.Write(KSRes.UserAccountPrompt + " ");
                string strUA = Console.ReadLine().Trim();
                if (strUA != null)
                {
                    string strUal = strUA.ToLower();
                    if ((strUal == "y") || (strUal == "j") ||
                        (strUal == "o") || (strUal == "a") ||
                        (strUal == "u"))
                    {
                        cmpKey.AddUserKey(new KcpUserAccount());
                    }
                }
            }
            else
            {
                cmpKey = KeyFromCmdLine(args);
            }

            PwDatabase pwDb = new PwDatabase();

            pwDb.Open(ioc, cmpKey, null);

            bool bNeedsSave;

            RunFileCommand(strCommand.ToLower(), args, pwDb, out bNeedsSave);

            if (bNeedsSave)
            {
                pwDb.Save(null);
            }

            pwDb.Close();
        }
コード例 #22
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool     bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool     bAllSuccess = true;
            MainForm mf          = Program.MainForm;    // Null for KPScript

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog ||
                ((mf != null) && !mf.HasFormLoaded))
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if (!string.IsNullOrEmpty(exSingular.Message))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(iocIn.GetDisplayName(),
                                               KPRes.FileImportFailed, strMsgEx);

                    bAllSuccess = false;
                    continue;
                }
                finally { s.Close(); }

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (UIUtil.ShowDialogNotValue(imf, DialogResult.OK))
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                                  KPRes.SavingDatabase + ")", LogStatusType.Info);

                if (mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            string strSource = pwDatabase.IOConnectionInfo.Path;
                            if (!string.Equals(ioc.Path, strSource, StrUtil.CaseIgnoreCmp))
                            {
                                bool bSaveAs = true;

                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    // Do not try to copy an encrypted file;
                                    // https://sourceforge.net/p/keepass/discussion/329220/thread/9c9eb989/
                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx
                                    if ((long)(File.GetAttributes(strSource) &
                                               FileAttributes.Encrypted) == 0)
                                    {
                                        File.Copy(strSource, ioc.Path, true);
                                        bSaveAs = false;
                                    }
                                }

                                if (bSaveAs)
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            // else { } // No assert (sync on save)

                            if (mf != null)
                            {
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                                       ioc.CloneDeep());
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return(bAllSuccess);
        }
コード例 #23
0
        private static void ImportIntoCurrentDatabase(EcasAction a, EcasContext ctx)
        {
            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);

            if (string.IsNullOrEmpty(strPath))
            {
                return;
            }
            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strPath);

            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            FileFormatProvider ff = Program.FileFormatPool.Find(strFormat);

            if (ff == null)
            {
                throw new Exception(KPRes.Unknown + ": " + strFormat);
            }

            uint          uMethod = EcasUtil.GetParamUInt(a.Parameters, 2);
            Type          tMM     = Enum.GetUnderlyingType(typeof(PwMergeMethod));
            object        oMethod = Convert.ChangeType(uMethod, tMM);
            PwMergeMethod mm      = PwMergeMethod.None;

            if (Enum.IsDefined(typeof(PwMergeMethod), oMethod))
            {
                mm = (PwMergeMethod)oMethod;
            }
            else
            {
                Debug.Assert(false);
            }
            if (mm == PwMergeMethod.None)
            {
                mm = PwMergeMethod.CreateNewUuids;
            }

            CompositeKey cmpKey = KeyFromParams(a, 3, 4, 5);

            if ((cmpKey == null) && ff.RequiresKey)
            {
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc, false, true);

                if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                {
                    return;
                }

                cmpKey = kpf.CompositeKey;
                UIUtil.DestroyForm(kpf);
            }

            bool?b = true;

            try { b = ImportUtil.Import(pd, ff, ioc, mm, cmpKey); }
            finally
            {
                if (b.GetValueOrDefault(false))
                {
                    Program.MainForm.UpdateUI(false, null, true, null, true, null, true);
                }
            }
        }
コード例 #24
0
ファイル: ImportUtil.cs プロジェクト: jonbride/strengthreport
        private static bool PerformImport(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                          IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                          bool bForceSave)
        {
            if (fmtImp.TryBeginImport() == false)
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            StatusLoggerForm slf = new StatusLoggerForm();

            slf.InitEx(false);
            slf.Show();

            if (bSynchronize)
            {
                slf.StartLogging(KPRes.Synchronize, false);
            }
            else
            {
                slf.StartLogging(KPRes.ImportingStatusMsg, false);
            }

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, slf); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                slf.EndLogging(); slf.Close();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }

                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn.GetDisplayName(), false);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                slf.SetText((bSynchronize ? KPRes.Synchronizing : KPRes.ImportingStatusMsg) +
                            " " + iocIn.GetDisplayName(), LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, slf); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize)
                    {
                        strMsgEx += MessageService.NewParagraph +
                                    KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            slf.EndLogging(); slf.Close();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (pwDatabase.IOConnectionInfo.IsLocalFile())
                            {
                                if ((pwDatabase.IOConnectionInfo.Path != ioc.Path) &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                            }
                            else
                            {
                                pwDatabase.SaveAs(ioc, false, null);
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }
            else if (bSynchronize)            // Synchronized but not successfully imported
            {
                MessageService.ShowWarning(KPRes.SyncFailed,
                                           pwDatabase.IOConnectionInfo.GetDisplayName());

                bAllSuccess = false;
            }

            return(bAllSuccess);
        }
コード例 #25
0
        public static CompositeKey GetMasterKey(CommandLineArgs args,
                                                string strPrefix, IOConnectionInfo ioc)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            string strPre = (strPrefix ?? string.Empty);

            if (args[strPre + ParamGuiKey] != null)
            {
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc, false, false);
                if (kpf.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }

                return(kpf.CompositeKey);
            }

            if (args[strPre + ParamConsoleKey] != null)
            {
                CompositeKey cmpKey = new CompositeKey();

                Console.WriteLine(KSRes.NoKeyPartHint);
                Console.WriteLine();
                Console.WriteLine(KSRes.KeyPrompt);

                Console.Write(KSRes.PasswordPrompt + " ");
                string strPw = Console.ReadLine().Trim();
                if ((strPw != null) && (strPw.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpPassword(strPw));
                }

                Console.Write(KSRes.KeyFilePrompt + " ");
                string strFile = Console.ReadLine().Trim();
                if ((strFile != null) && (strFile.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpKeyFile(strFile));
                }

                Console.Write(KSRes.UserAccountPrompt + " ");
                string strUA = Console.ReadLine().Trim();
                if (strUA != null)
                {
                    string strUal = strUA.ToLower();
                    if ((strUal == "y") || (strUal == "j") ||
                        (strUal == "o") || (strUal == "a") ||
                        (strUal == "u"))
                    {
                        cmpKey.AddUserKey(new KcpUserAccount());
                    }
                }

                return(cmpKey);
            }

            return(KpsUtil.KeyFromCommandLine(args, strPre));
        }
コード例 #26
0
        public void OnKeyPrompt(KeyPromptForm keyPromptForm, MainForm mainWindow)
        {
            if (!Settings.Instance.Enabled)
            {
                return;
            }

            if (SystemInformation.TerminalServerSession) // RDP
            {
                if (!_notifiedAboutRdp)
                {
                    MessageBox.Show(AuthProviderUIContext.Current,
                                    "Windows Hello is not available for a remote session. Unfortunately, you are forced to enter database using default authorization.\n" +
                                    "The key will be kept in case you prompt to enter without using RDP. The usual key retention settings are being applied.",
                                    Settings.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    _notifiedAboutRdp = true;
                }
                return;
            }
            else
            {
                _notifiedAboutRdp = false;
            }

            string dbPath = GetDbPath(keyPromptForm);

            if (keyPromptForm.SecureDesktopMode)
            {
                if (IsKeyForDataBaseExist(dbPath))
                {
                    if (_cancellationTokenSource == null)
                    {
                        _cancellationTokenSource = new CancellationTokenSource();
                    }

                    Task.Factory.StartNew(() => MonitorWarning(_cancellationTokenSource.Token), _cancellationTokenSource.Token);

                    try
                    {
                        int masterKeyTries = KeePass.Program.Config.Security.MasterKeyTries;
                        Interlocked.Exchange(ref _masterKeyTries, masterKeyTries);
                        KeePass.Program.Config.Security.MasterKeyTries           = ++masterKeyTries;
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = false;
                        SetCompositeKey(keyPromptForm, new CompositeKey());
                        CloseFormWithResult(keyPromptForm, DialogResult.OK);
                    }
                    catch
                    {
                        StopMonitorWarning();
                        throw;
                    }
                }
            }
            else
            {
                StopMonitorWarning();

                int oldTriesValue = Interlocked.Exchange(ref _masterKeyTries, NoChanges);
                if (oldTriesValue != NoChanges)
                {
                    KeePass.Program.Config.Security.MasterKeyTries           = oldTriesValue;
                    KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                }

                Unlock(keyPromptForm, dbPath);
            }
        }
コード例 #27
0
ファイル: UWPLibrary.cs プロジェクト: mikalv/WinHelloUnlock
        /// <summary>
        /// Performs the actual unlock of the database
        /// </summary>
        /// <param name="ioInfo">IOConnectionInfo that represents the Database.</param>
        internal static async Task UnlockDatabase(IOConnectionInfo ioInfo, KeyPromptForm keyPromptForm)
        {
            string dbPath = Library.CharChange(ioInfo.Path);

            KeyCredentialRetrievalResult retrievalResult = await OpenCredential(dbPath);

            if (retrievalResult.Status == KeyCredentialStatus.Success) // If credential is successfully retrieved
            {
                KeyList keyList = await RetrieveKeys(dbPath, retrievalResult);

                CompositeKey compositeKey = Library.ConvertToComposite(keyList);

                // Composite Key is retrieved so the number of tries is augmented
                ++WinHelloUnlockExt.tries;

                if (compositeKey != null)                             // If there is actually a composite key
                {
                    if (Library.CheckMasterKey(ioInfo, compositeKey)) // If the composite key actually unlocks the database
                    {
                        // Unlock the database
                        Unlock(keyPromptForm, compositeKey);

                        // Check if the database was actually opened
                        string openedDBPath = WinHelloUnlockExt.Host.MainWindow.ActiveDatabase.IOConnectionInfo.Path;
                        if (openedDBPath != ioInfo.Path &&                  // If opened DB is not the same we are trying to open
                            WinHelloUnlockExt.updateCheckForm != null)      // and UpdateCheckForm is opened then the database was not opened because of that
                        {
                            // Using a global Composite key to test for changes
                            ck = compositeKey;

                            // Register an event handler to be able to unlock the database after updateCheckForm is closed
                            WinHelloUnlockExt.updateCheckForm.FormClosed += (object sender, FormClosedEventArgs e) =>
                                                                            UpdateFormClosedEventHandler(ioInfo);
                        }

                        if (WinHelloUnlockExt.isAutoTyping && WinHelloUnlockExt.LockAfterAutoType)
                        {
                            var _ = Task.Factory.StartNew(() => LockAfterAutoType());
                            //MessageService.ShowInfo("autotyping");
                        }
                    }
                    else // If composite key did not unlock the database prompt the user to delete the credentials
                    {
                        await Library.HandleMasterKeyChange(ioInfo, dbPath, true);
                    }
                }
                else // If compositeKey is null, open regular unlock prompt to unlock the database
                {
                    if (WinHelloUnlockExt.secureChaged)
                    {
                        KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                        WinHelloUnlockExt.secureChaged = false;
                        Library.CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
                        var _ = Task.Factory.StartNew(() => KeePass.Program.MainForm.OpenDatabase(ioInfo, null, true));
                    }
                    else
                    {
                        keyPromptForm.Visible = true;
                        keyPromptForm.Opacity = 1;
                    }
                }

                // Delete composite key data
                compositeKey = null;

                // Delete KeyList object
                keyList = new KeyList(null, null);
            }
            else
            {
                // If credentials were not successfully retrieved inform the user and open regular unlock prompt
                WinHelloErrors(retrievalResult.Status, "Error unlocking database: ");
                if (WinHelloUnlockExt.secureChaged)
                {
                    KeePass.Program.Config.Security.MasterKeyOnSecureDesktop = true;
                    WinHelloUnlockExt.secureChaged = false;
                    Library.CloseFormWithResult(keyPromptForm, DialogResult.Cancel);
                    var _ = Task.Factory.StartNew(() => KeePass.Program.MainForm.OpenDatabase(ioInfo, null, true));
                }
                else
                {
                    keyPromptForm.Visible = true;
                    keyPromptForm.Opacity = 1;
                }
            }
        }
コード例 #28
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    // Transacted-file operations can leave behind intact *.kdbx.tmp files when
                    // the file rename doesn't get completed (can happen easily with slow/unreliable
                    // remote collections. We check if that's the case here and fix the situation if
                    // an kdbx file does *not* exist (to avoid possibly overwriting good data with bad
                    // data (i.e. an interrupted kdbx.tmp write).

                    // Make a copy of the IOC like FileTransactionEx.cs:Initialize does
                    IOConnectionInfo iocTemp = iocIn.CloneDeep();
                    iocTemp.Path += FileTransactionEx.StrTempSuffix;

                    if (IOConnection.FileExists(iocTemp) && !IOConnection.FileExists(iocIn))
                    {
                        // Try and rename iocTemp to ioc.Path, then retry file opening.
                        IOConnection.RenameFile(iocTemp, iocIn);
                        try {
                            s = IOConnection.OpenRead(iocIn);
                        } catch (Exception nexFile) {
                            MessageService.ShowWarning(iocIn.GetDisplayName(), nexFile);
                            bAllSuccess = false;
                            continue;
                        }
                    }
                    else
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                        bAllSuccess = false;
                        continue;
                    }
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (UIUtil.ShowDialogNotValue(imf, DialogResult.OK))
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                                  KPRes.SavingDatabase + ")", LogStatusType.Info);

                MainForm mf = Program.MainForm;                 // Null for KPScript
                if (mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            string strSource = pwDatabase.IOConnectionInfo.Path;
                            if (ioc.Path != strSource)
                            {
                                bool bSaveAs = true;

                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    // Do not try to copy an encrypted file;
                                    // https://sourceforge.net/p/keepass/discussion/329220/thread/9c9eb989/
                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx
                                    if ((long)(File.GetAttributes(strSource) &
                                               FileAttributes.Encrypted) == 0)
                                    {
                                        File.Copy(strSource, ioc.Path, true);
                                        bSaveAs = false;
                                    }
                                }

                                if (bSaveAs)
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            // else { } // No assert (sync on save)

                            if (mf != null)
                            {
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                                       ioc.CloneDeep());
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return(bAllSuccess);
        }
コード例 #29
0
            private void SetKeyPromptFormTitle(KeyPromptForm kpf)
            {
                string title = string.Format(PluginTranslate.OTP_OpenDB, string.IsNullOrEmpty(DB.Name) ? UrlUtil.GetFileName(DB.IOConnectionInfo.Path) : DB.Name);

                kpf.InitEx(OTPDB.IOConnectionInfo, false, false, title);
            }
コード例 #30
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    // slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            dlgStatus.EndLogging();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (ioc.Path != pwDatabase.IOConnectionInfo.Path)
                            {
                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                                else
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            else
                            {
                            }                                    // No assert (sync on save)

                            Program.MainForm.FileMruList.AddItem(ioc.GetDisplayName(),
                                                                 ioc.CloneDeep(), true);
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            return(bAllSuccess);
        }