Beispiel #1
0
            public override void SaveOTP(KPOTP myOTP, PwEntry pe)
            {
                if (!SetEntry(pe, true))
                {
                    return;
                }

                //string otpSettings = myOTP.Settings;
                KPOTP prev = GetOTP(pe);
                bool  OnlyCounterChanged = false;

                if (!SettingsChanged(pe, prev, myOTP, out OnlyCounterChanged))
                {
                    return;
                }

                PluginDebug.AddInfo("Update OTP data",
                                    "Entry uuid: " + pe.Uuid.ToHexString(),
                                    "Only change of HOTP counter: " + OnlyCounterChanged.ToString());

                bool bCreated = false;

                GetOTPEntry(true, out bCreated);
                if (!OnlyCounterChanged)
                {
                    //Create backup if something else than only the HOTP counter was changed
                    if (!bCreated)
                    {
                        m_peOTP.CreateBackup(OTPDB);
                    }
                }
                m_peOTP.Strings.Set(Config.OTPFIELD, myOTP.OTPAuthString);
                if (myOTP.TimeCorrectionUrlOwn)
                {
                    m_peOTP.Strings.Set(Config.TIMECORRECTION, new ProtectedString(false, "OWNURL"));
                }
                else if (string.IsNullOrEmpty(myOTP.TimeCorrectionUrl) || (myOTP.TimeCorrectionUrl == "OFF"))
                {
                    m_peOTP.Strings.Remove(Config.TIMECORRECTION);
                }
                else
                {
                    m_peOTP.Strings.Set(Config.TIMECORRECTION, new ProtectedString(false, myOTP.TimeCorrectionUrl));
                }

                Touch(m_peOTP);
                if (myOTP.OTPSeed.IsEmpty)
                {
                    m_pe.Strings.Remove(DBNAME);
                }
                else
                {
                    m_pe.Strings.Set(DBNAME, new ProtectedString(false, StrUtil.BoolToString(true)));
                }
                FlagChanged(false);
                FlagChanged(true);

                m_pe.Touch(true);
            }
Beispiel #2
0
        public bool MigratePlaceholder(string from, string to, PwEntry pe, out bool bChanged)
        {
            bChanged = false;
            if (pe == null)
            {
                return(true);
            }
            bool bBackupRequired = true;

            foreach (var a in pe.AutoType.Associations)
            {
                if (a.Sequence.Contains(from))
                {
                    if (bBackupRequired)
                    {
                        bBackupRequired = false;
                        pe.CreateBackup(m_db);
                    }
                    a.Sequence = a.Sequence.Replace(from, to);
                    bChanged   = true;
                }
            }
            if (pe.AutoType.DefaultSequence.Contains(from))
            {
                if (bBackupRequired)
                {
                    bBackupRequired = false;
                    pe.CreateBackup(m_db);
                }
                pe.AutoType.DefaultSequence = pe.AutoType.DefaultSequence.Replace(from, to);
                bChanged = true;
            }
            foreach (var s in pe.Strings.GetKeys())
            {
                ProtectedString ps = pe.Strings.Get(s);
                if (!ps.Contains(from))
                {
                    continue;
                }
                if (bBackupRequired)
                {
                    bBackupRequired = false;
                    pe.CreateBackup(m_db);
                }
                ps = ps.Replace(from, to);
                pe.Strings.Set(s, ps);
                bChanged = true;
            }
            if (bChanged)
            {
                pe.Touch(true, false);
            }
            return(bChanged);
        }
Beispiel #3
0
        public void RenameOfUserRootShouldRenameItsHomeAndAllProxies()
        {
            m_treeManager.Initialize(m_database);
            m_treeManager.CreateNewUser("mrX");
            PwEntry userRootNode        = TestHelper.GetUserRootNodeFor(m_database, 0);
            PwEntry userHomeProxyNode   = TestHelper.GetUserRootProxyFor(m_database, 0);
            PwEntry userExternProxyNode = userRootNode.CreateProxyNode();
            PwGroup userHome            = TestHelper.GetUserHomeNodeFor(m_database, 0);

            m_database.RootGroup.AddEntry(userExternProxyNode, true);
            userRootNode.CreateBackup(m_database);

            userRootNode.Strings.Set(KeeShare.KeeShare.TitleField, new ProtectedString(false, "mrNew"));
            TestHelper.SimulateTouch(userRootNode);

            m_treeManager.CorrectStructure();
            //refresh all references after update
            userRootNode        = TestHelper.GetUserRootNodeFor(m_database, 0);
            userHomeProxyNode   = TestHelper.GetUserRootNodeFor(m_database, 0);
            userExternProxyNode = m_database.RootGroup.Entries.GetAt(0);
            userHome            = TestHelper.GetUserHomeNodeFor(m_database, 0);

            //after that update all proxyNodes schould have become the same name as the rootNode_X
            Assert.AreEqual("mrNew", userHomeProxyNode.Strings.ReadSafe(KeeShare.KeeShare.TitleField));
            Assert.AreEqual("mrNew", userExternProxyNode.Strings.ReadSafe(KeeShare.KeeShare.TitleField));
            //even the home of the user should have the new name
            Assert.AreEqual("mrNew", userHome.Name);
            //everytime the UsersGroups should be sane!
            IsUsersGroupSane(m_database, 1);
        }
Beispiel #4
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
                                                            PwEntry pe, PwDatabase pd, SprContentFlags cf)
        {
            if ((pe == null) || (pd == null))
            {
                return(strText);
            }

            string str = strText;

            const string strNewPwPlh = @"{NEWPASSWORD}";

            if (str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                ProtectedString psAutoGen = new ProtectedString(
                    pd.MemoryProtection.ProtectPassword);
                PwgError e = PwGenerator.Generate(psAutoGen,
                                                  Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
                                                  null, Program.PwGeneratorPool);

                if (e == PwgError.Success)
                {
                    pe.CreateBackup();
                    pe.Strings.Set(PwDefs.PasswordField, psAutoGen);
                    pd.Modified = true;

                    string strIns = SprEngine.TransformContent(psAutoGen.ReadString(), cf);
                    str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
                }
            }

            return(str);
        }
Beispiel #5
0
        public void AttachFiles()
        {
            // Copied from PwEntryForm.OnCtxBinImport (PwEntryForm.cs)
            var ofd = UIUtil.CreateOpenFileDialog(KPRes.AttachFiles,
                                                  UIUtil.CreateFileTypeFilter(null, null, true), 1, null, true,
                                                  KeePass.App.AppDefs.FileDialogContext.Attachments);

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Entry.CreateBackup(Database);

                BinImportFiles(ofd.FileNames);

                RefreshObjectsFromEntry();
                OnEntryModified(EventArgs.Empty);
            }
        }
Beispiel #6
0
        /// <summary>
        /// The function checks if thelast made change has to be propageted to
        /// some referenced PwEntries
        /// </summary>
        /// <returns>True if the function has made changes to the database.</returns>
        private Changes CheckReferences()
        {
            PwEntry lastModifiedEntry = GetLastModifiedEntry();

            //if there are no changes, then we have nothing to do
            if (lastModifiedEntry == null)
            {
                return(Changes.None);
            }
            //was it a proxy or not?
            Changes changeFlag = Changes.None;

            if (lastModifiedEntry.IsProxyNode())
            {
                //lets update the root so we later can update all proxies
                PwEntry root = m_database.GetProxyTargetFor(lastModifiedEntry);
                //check if there are real changes! if not we are done here
                if (lastModifiedEntry.IsSimilarTo(root, true))
                {
                    return(Changes.None);
                }
                PwGroup parent = root.ParentGroup;

                root.CreateBackup(m_database); //rootNode_X should save all modifications in history
                parent.Entries.Remove(root);

                PwEntry updatedRoot = lastModifiedEntry.CloneDeep();
                updatedRoot.Uuid = root.Uuid;
                updatedRoot.SetParent(parent);
                //special handling for userRootNodes because they have a homefolder
                if (root.IsUserRootNode())
                {
                    //maybe the oldUserName has changed to => the homefolder should have the new name also
                    //we also want to have the same icons everywhere
                    parent.Name   = updatedRoot.GetTitle();
                    parent.IconId = updatedRoot.IconId;
                }
                else
                {
                    updatedRoot.Strings.Remove(KeeShare.UuidLinkField);
                }
                changeFlag |= UpdateProxyInformation(updatedRoot);
                changeFlag |= Changes.GroupDeleted;
            }
            else
            {
                changeFlag |= UpdateProxyInformation(lastModifiedEntry);
            }
            pe_lastModedEntry = GetLastModifiedEntry();
            return(changeFlag);
        }
        private static void TouchSaveEntry(PwDatabase m_pwDatabase, PwEntry m_pwEntry, bool is_new, bool update_parents)
        {
            //Save procedure taken from

            PwObjectList <PwEntry> m_vHistory = m_pwEntry.History.CloneDeep();
            PwEntry peTarget = m_pwEntry;

            peTarget.History = m_vHistory;             // Must be called before CreateBackup()
            if (!is_new)
            {
                peTarget.CreateBackup(null);
            }
            peTarget.Touch(true, update_parents);             // Touch *after* backup
            StrUtil.NormalizeNewLines(peTarget.Strings, true);
            peTarget.MaintainBackups(m_pwDatabase);
        }
            private bool SaveEntryStatus(ListViewItem Item, PwIcon icon, string text)
            {
                PwListItem pli = (((ListViewItem)Item).Tag as PwListItem);

                if (pli == null)
                {
                    Debug.Assert(false); return(false);
                }
                PwEntry pe = pli.Entry;

                pe = m_host.Database.RootGroup.FindEntry(pe.Uuid, true);

                var protString = pe.Strings.Get(PwDefs.PasswordField);

                if (protString != null && !protString.IsEmpty)
                {
                    return(false);
                }

                PwEntry peInit = pe.CloneDeep();

                pe.CreateBackup(null);
                pe.Touch(true, false); // Touch *after* backup


                pe.IconId       = icon;
                Item.ImageIndex = (int)icon;

                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(false, text));
                Item.SubItems[getSubitemOfField(KeePass.App.Configuration.AceColumnType.UserName)].Text = text;

                PwCompareOptions cmpOpt = (PwCompareOptions.IgnoreLastMod | PwCompareOptions.IgnoreLastAccess | PwCompareOptions.IgnoreLastBackup);

                if (pe.EqualsEntry(peInit, cmpOpt, MemProtCmpMode.None))
                {
                    pe.LastModificationTime = peInit.LastModificationTime;

                    pe.History.Remove(pe.History.GetAt(pe.History.UCount - 1)); // Undo backup

                    return(false);
                }
                else
                {
                    return(true);
                }
            }
Beispiel #9
0
            private void txtNotes_TextChanged(object sender, EventArgs e)
            {
                PwDatabase pwStorage = m_host.Database;
                PwEntry    pe        = m_host.MainWindow.GetSelectedEntry(true);

                if (txtNotes.Tag == null)
                {
                    // Text has just started changing, backup the original entry and save it in Tag property, which we'll use later do determine whether the entry is modified or not
                    pe.CreateBackup(null);
                    pe.Touch(true, false);                     // Touch *after* backup

                    txtNotes.Tag = pe.CloneDeep();
                }

                pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, txtNotes.Text));
                Util.UpdateSaveState();                 // Make save icon enabled
            }
Beispiel #10
0
 private bool AddToAutotype(PwEntry pe, string s, ref AWMDuplicateHandling dup)
 {
     if (pe.AutoType.Associations.FirstOrDefault(x => string.Compare(x.WindowName, s, true) == 0) != null)
     {
         if (dup == AWMDuplicateHandling.Undefined)
         {
             dup = GetDuplicateHandling(s);
         }
         if (dup != AWMDuplicateHandling.Add)
         {
             return(false);
         }
     }
     pe.CreateBackup(KeePass.Program.MainForm.DocumentManager.SafeFindContainerOf(pe));
     pe.AutoType.Add(new KeePassLib.Collections.AutoTypeAssociation(s, string.Empty));
     pe.Touch(true, false);
     return(true);
 }
Beispiel #11
0
        internal static void Expire(this PwEntry pe, bool bExpireAll)
        {
            if (!pe.Expires && !bExpireAll)
            {
                return;
            }
            if (pe.Expires && (pe.ExpiryTime < DateTime.UtcNow))
            {
                return;
            }

            Configuration.SkipRecalc = true;
            PluginDebug.AddInfo("Expire entry", pe.Uuid.ToString());
            pe.CreateBackup(KeePass.Program.MainForm.ActiveDatabase);
            pe.Expires    = true;
            pe.ExpiryTime = PEDCalcValue.UnixStart;
            pe.Touch(true, false);
        }
            public override void SaveOTP(KPOTP myOTP, PwEntry pe)
            {
                KPOTP prev = GetOTP(pe);
                bool  OnlyCounterChanged = false;

                if (!SettingsChanged(pe, prev, myOTP, out OnlyCounterChanged))
                {
                    return;
                }

                PluginDebug.AddInfo("Update OTP data",
                                    "Entry uuid: " + pe.Uuid.ToString(),
                                    "Only change of HOTP counter: " + OnlyCounterChanged.ToString());
                if (!OnlyCounterChanged)
                {
                    //Create backup if something else than only the HOTP counter was changed
                    pe.CreateBackup(pe.GetDB());
                }
                if (myOTP.OTPSeed.IsEmpty)
                {
                    pe.Strings.Remove(Config.OTPFIELD);
                    pe.Strings.Remove(Config.TIMECORRECTION);
                }
                else
                {
                    //pe.Strings.Set(Config.SETTINGS, new ProtectedString(false, otpSettings));
                    //pe.Strings.Set(Config.SEED, myOTP.OTPSeed);
                    pe.Strings.Set(Config.OTPFIELD, myOTP.OTPAuthString);
                    if (myOTP.TimeCorrectionUrlOwn)
                    {
                        pe.Strings.Set(Config.TIMECORRECTION, new ProtectedString(false, "OWNURL"));
                    }
                    else if (string.IsNullOrEmpty(myOTP.TimeCorrectionUrl) || (myOTP.TimeCorrectionUrl == "OFF"))
                    {
                        pe.Strings.Remove(Config.TIMECORRECTION);
                    }
                    else
                    {
                        pe.Strings.Set(Config.TIMECORRECTION, new ProtectedString(false, myOTP.TimeCorrectionUrl));
                    }
                }
                pe.Touch(true);
            }
Beispiel #13
0
        internal void AddUrlToEntry(string url, Action finishAction)
        {
            PwEntry initialEntry = Entry.CloneDeep();

            PwEntry newEntry = Entry;

            newEntry.History = newEntry.History.CloneDeep();
            newEntry.CreateBackup(null);

            newEntry.Touch(true, false);             // Touch *after* backup

            //if there is no URL in the entry, set that field. If it's already in use, use an additional (not existing) field
            if (String.IsNullOrEmpty(newEntry.Strings.ReadSafe(PwDefs.UrlField)))
            {
                newEntry.Strings.Set(PwDefs.UrlField, new ProtectedString(false, url));
            }
            else
            {
                int c = 1;
                while (newEntry.Strings.Get("KP2A_URL_" + c) != null)
                {
                    c++;
                }

                newEntry.Strings.Set("KP2A_URL_" + c, new ProtectedString(false, url));
            }

            //save the entry:

            ActionOnFinish closeOrShowError = new ActionOnFinish((success, message) =>
            {
                OnFinish.DisplayMessage(this, message);
                finishAction();
            });


            RunnableOnFinish runnable = new UpdateEntry(this, App.Kp2a, initialEntry, newEntry, closeOrShowError);

            ProgressTask pt = new ProgressTask(App.Kp2a, this, runnable);

            pt.Run();
        }
Beispiel #14
0
        private void OnShowPCAForm(object sender, EventArgs e)
        {
            if (!SaveOldPassword())
            {
                return;
            }
            m_pcaForm = new PCADialog();
            PCAInitData pcadata = new PCAInitData(SelectedEntry);

            DerefStrings(pcadata, SelectedEntry);
            m_pcaForm.Init(pcadata, ProfilesOpening);
            if (m_pcaForm.ShowDialog(m_host.MainWindow) == DialogResult.OK)
            {
                SelectedEntry.CreateBackup(Program.MainForm.ActiveDatabase);
                SelectedEntry.Strings.Set(PwDefs.PasswordField, m_pcaForm.NewPassword);
                SelectedEntry.Expires = m_pcaForm.EntryExpiry.Checked;
                if (SelectedEntry.Expires)
                {
                    SelectedEntry.ExpiryTime = m_pcaForm.EntryExpiry.Value.ToUniversalTime();
                }
                if (string.IsNullOrEmpty(m_pcaForm.Sequence))
                {
                    SelectedEntry.Strings.Remove(Config.PCASequence);
                }
                else
                {
                    SelectedEntry.Strings.Set(Config.PCASequence, new ProtectedString(false, m_pcaForm.Sequence));
                }
                if (string.IsNullOrEmpty(m_pcaForm.URL2))
                {
                    SelectedEntry.Strings.Remove(Config.PCAURLField);
                }
                else
                {
                    SelectedEntry.Strings.Set(Config.PCAURLField, new ProtectedString(false, m_pcaForm.URL2));
                }
                SelectedEntry.Touch(true);
                Tools.RefreshEntriesList(true);
            }
            m_pcaForm.CleanupEx();
            m_pcaForm = null;
        }
Beispiel #15
0
        private Changes EnsureMatchingNamingAndIcons(PwEntry userNode, PwGroup userHome, PwGroup usersGroup)
        {
            string userName = userNode.Strings.ReadSafe(KeeShare.TitleField);

            //we are located in our home => check for new names.. and icons
            if (userNode.ParentGroup.Name == userNode.Strings.ReadSafe(KeeShare.TitleField) && userNode.IconId == userNode.ParentGroup.IconId)
            {
                return(Changes.None);
            }
            if (userNode.LastModificationTime.Ticks >= userNode.ParentGroup.LastModificationTime.Ticks)
            {
                //if last change was in the rootNode the group has to become the new name
                PwObjectList <PwEntry> history = userNode.History;
                Changes changeFlags            = Changes.None;
                string  lastName = null;
                if (history.UCount > 0)
                {
                    lastName = history.GetAt(history.UCount - 1u).Strings.ReadSafe(KeeShare.TitleField);
                }
                if (lastName != userName && lastName == userNode.ParentGroup.Name)
                {
                    userNode.ParentGroup.Name = userName;
                    changeFlags |= Changes.GroupChanged;
                }
                if (userNode.IconId != userNode.ParentGroup.IconId)
                {
                    userNode.ParentGroup.IconId = userNode.IconId;
                    changeFlags |= Changes.GroupChanged;
                }
                return(changeFlags);
            }

            //otherwise the name of the group was the actual name
            userName = userNode.ParentGroup.Name;
            userNode.CreateBackup(m_database);
            userNode.Strings.Set(KeeShare.TitleField, new ProtectedString(false, userName));
            //icons should also be the same!
            userNode.IconId = userNode.ParentGroup.IconId;
            userNode.Touch(true, false);
            return(Changes.GroupChanged);
        }
Beispiel #16
0
        void SaveEntry()
        {
            Database          db  = App.Kp2a.GetDb();
            EntryEditActivity act = this;

            if (!ValidateBeforeSaving())
            {
                return;
            }

            PwEntry initialEntry = State.EntryInDatabase.CloneDeep();

            PwEntry newEntry = State.EntryInDatabase;

            //Clone history and re-assign:
            newEntry.History = newEntry.History.CloneDeep();

            //Based on KeePass Desktop
            bool bCreateBackup = (!State.IsNew);

            if (bCreateBackup)
            {
                newEntry.CreateBackup(null);
            }

            if (State.SelectedIcon)
            {
                newEntry.IconId         = State.SelectedIconId;
                newEntry.CustomIconUuid = State.SelectedCustomIconId;
            }             //else the State.EntryInDatabase.Icon

            /* KPDesktop
             *      if(m_cbCustomForegroundColor.Checked)
             *              newEntry.ForegroundColor = m_clrForeground;
             *      else newEntry.ForegroundColor = Color.Empty;
             *      if(m_cbCustomBackgroundColor.Checked)
             *              newEntry.BackgroundColor = m_clrBackground;
             *      else newEntry.BackgroundColor = Color.Empty;
             *
             */

            UpdateEntryFromUi(newEntry);
            newEntry.Binaries = State.Entry.Binaries;
            newEntry.Expires  = State.Entry.Expires;
            if (newEntry.Expires)
            {
                newEntry.ExpiryTime = State.Entry.ExpiryTime;
            }


            newEntry.Touch(true, false);             // Touch *after* backup

            StrUtil.NormalizeNewLines(newEntry.Strings, true);

            bool             bUndoBackup = false;
            PwCompareOptions cmpOpt      = (PwCompareOptions.NullEmptyEquivStd |
                                            PwCompareOptions.IgnoreTimes);

            if (bCreateBackup)
            {
                cmpOpt |= PwCompareOptions.IgnoreLastBackup;
            }
            if (newEntry.EqualsEntry(initialEntry, cmpOpt, MemProtCmpMode.CustomOnly))
            {
                // No modifications at all => restore last mod time and undo backup
                newEntry.LastModificationTime = initialEntry.LastModificationTime;
                bUndoBackup = bCreateBackup;
            }
            else if (bCreateBackup)
            {
                // If only history items have been modified (deleted) => undo
                // backup, but without restoring the last mod time
                PwCompareOptions cmpOptNh = (cmpOpt | PwCompareOptions.IgnoreHistory);
                if (newEntry.EqualsEntry(initialEntry, cmpOptNh, MemProtCmpMode.CustomOnly))
                {
                    bUndoBackup = true;
                }
            }
            if (bUndoBackup)
            {
                newEntry.History.RemoveAt(newEntry.History.UCount - 1);
            }

            newEntry.MaintainBackups(db.KpDatabase);

            //if ( newEntry.Strings.ReadSafe (PwDefs.TitleField).Equals(State.Entry.Strings.ReadSafe (PwDefs.TitleField)) ) {
            //	SetResult(KeePass.EXIT_REFRESH);
            //} else {
            //it's safer to always update the title as we might add further information in the title like expiry etc.
            SetResult(KeePass.ExitRefreshTitle);
            //}

            RunnableOnFinish runnable;

            ActionOnFinish closeOrShowError = new ActionOnFinish((success, message) => {
                if (success)
                {
                    Finish();
                }
                else
                {
                    OnFinish.DisplayMessage(this, message);
                }
            });

            ActionOnFinish afterAddEntry = new ActionOnFinish((success, message) =>
            {
                if (success)
                {
                    _appTask.AfterAddNewEntry(this, newEntry);
                }
            }, closeOrShowError);

            if (State.IsNew)
            {
                runnable = AddEntry.GetInstance(this, App.Kp2a, newEntry, State.ParentGroup, afterAddEntry);
            }
            else
            {
                runnable = new UpdateEntry(this, App.Kp2a, initialEntry, newEntry, closeOrShowError);
            }
            ProgressTask pt = new ProgressTask(App.Kp2a, act, runnable);

            pt.Run();
        }
Beispiel #17
0
        private bool SaveEntry(PwEntry peTarget, bool bValidate)
        {
            if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return true;

            if(bValidate && !m_icgPassword.ValidateData(true)) return false;

            if(this.EntrySaving != null)
            {
                CancellableOperationEventArgs eaCancel = new CancellableOperationEventArgs();
                this.EntrySaving(this, eaCancel);
                if(eaCancel.Cancel) return false;
            }

            peTarget.History = m_vHistory; // Must be called before CreateBackup()
            bool bCreateBackup = (m_pwEditMode != PwEditMode.AddNewEntry);
            if(bCreateBackup) peTarget.CreateBackup(null);

            peTarget.IconId = m_pwEntryIcon;
            peTarget.CustomIconUuid = m_pwCustomIconID;

            if(m_cbCustomForegroundColor.Checked)
                peTarget.ForegroundColor = m_clrForeground;
            else peTarget.ForegroundColor = Color.Empty;
            if(m_cbCustomBackgroundColor.Checked)
                peTarget.BackgroundColor = m_clrBackground;
            else peTarget.BackgroundColor = Color.Empty;

            peTarget.OverrideUrl = m_cmbOverrideUrl.Text;

            List<string> vNewTags = StrUtil.StringToTags(m_tbTags.Text);
            peTarget.Tags.Clear();
            foreach(string strTag in vNewTags) peTarget.AddTag(strTag);

            peTarget.Expires = m_cgExpiry.Checked;
            if(peTarget.Expires) peTarget.ExpiryTime = m_cgExpiry.Value;

            UpdateEntryStrings(true, false, false);

            peTarget.Strings = m_vStrings;
            peTarget.Binaries = m_vBinaries;

            m_atConfig.Enabled = m_cbAutoTypeEnabled.Checked;
            m_atConfig.ObfuscationOptions = (m_cbAutoTypeObfuscation.Checked ?
                AutoTypeObfuscationOptions.UseClipboard :
                AutoTypeObfuscationOptions.None);

            SaveDefaultSeq();

            peTarget.AutoType = m_atConfig;

            peTarget.Touch(true, false); // Touch *after* backup
            if(object.ReferenceEquals(peTarget, m_pwEntry)) m_bTouchedOnce = true;

            StrUtil.NormalizeNewLines(peTarget.Strings, true);

            bool bUndoBackup = false;
            PwCompareOptions cmpOpt = m_cmpOpt;
            if(bCreateBackup) cmpOpt |= PwCompareOptions.IgnoreLastBackup;
            if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOpt, MemProtCmpMode.CustomOnly))
            {
                // No modifications at all => restore last mod time and undo backup
                peTarget.LastModificationTime = m_pwInitialEntry.LastModificationTime;
                bUndoBackup = bCreateBackup;
            }
            else if(bCreateBackup)
            {
                // If only history items have been modified (deleted) => undo
                // backup, but without restoring the last mod time
                PwCompareOptions cmpOptNH = (m_cmpOpt | PwCompareOptions.IgnoreHistory);
                if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOptNH, MemProtCmpMode.CustomOnly))
                    bUndoBackup = true;
            }
            if(bUndoBackup) peTarget.History.RemoveAt(peTarget.History.UCount - 1);

            peTarget.MaintainBackups(m_pwDatabase);

            if(this.EntrySaved != null) this.EntrySaved(this, EventArgs.Empty);

            return true;
        }
Beispiel #18
0
            /*
             * // Get all user defined strings
             * internal static Dictionary<string, string> GetDictEntriesUserStrings(PwGroup pwg)
             * {
             *  Dictionary<string, string> strd = new Dictionary<string, string>();
             *  //SortedDictionary<string, string> strd = new SortedDictionary<string, string>();
             *
             *  // Add all known pwentry strings
             *  foreach (PwEntry pe in pwg.GetEntries(true))
             *  {
             *      foreach (KeyValuePair<string, ProtectedString> pstr in pe.Strings)
             *      {
             *          if (!strd.ContainsKey(pstr.Key))
             *          {
             *              if (!PwDefs.IsStandardField(pstr.Key))
             *              {
             *                  strd.Add(pstr.Key, pstr.Value.ReadString());
             *              }
             *          }
             *      }
             *  }
             *
             *  return strd;
             * }*/

            // Ported from KeePass Entry Dialog SaveEntry() and UpdateEntryStrings(...)
            internal static bool SaveEntry(PwDatabase pwStorage, ListViewItem Item, int SubItem, string Text)
            {
                PwListItem pli = (((ListViewItem)Item).Tag as PwListItem);

                if (pli == null)
                {
                    Debug.Assert(false); return(false);
                }
                PwEntry pe = pli.Entry;

                pe = pwStorage.RootGroup.FindEntry(pe.Uuid, true);

                PwEntry peInit = pe.CloneDeep();

                pe.CreateBackup(null);
                pe.Touch(true, false); // Touch *after* backup

                int           colID   = SubItem;
                AceColumn     col     = GetAceColumn(colID);
                AceColumnType colType = col.Type;

                switch (colType)
                {
                case AceColumnType.Title:
                    //if(PwDefs.IsTanEntry(pe))
                    //TODO tan list	 TanTitle ???		    pe.Strings.Set(PwDefs.TanTitle, new ProtectedString(false, Text));
                    //else
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, Text));
                    break;

                case AceColumnType.UserName:
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, Text));
                    break;

                case AceColumnType.Password:
                    //byte[] pb = Text.ToUtf8();
                    //pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, pb));
                    //MemUtil.ZeroByteArray(pb);
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, Text));
                    break;

                case AceColumnType.Url:
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, Text));
                    break;

                case AceColumnType.Notes:
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, Text));
                    break;

                case AceColumnType.OverrideUrl:
                    pe.OverrideUrl = Text;
                    break;

                case AceColumnType.Tags:
                    List <string> vNewTags = StrUtil.StringToTags(Text);
                    pe.Tags.Clear();
                    foreach (string strTag in vNewTags)
                    {
                        pe.AddTag(strTag);
                    }
                    break;

                case AceColumnType.CustomString:
                    pe.Strings.Set(col.CustomName, new ProtectedString(pe.Strings.GetSafe(col.CustomName).IsProtected, Text));
                    break;

                default:
                    // Nothing todo
                    break;
                }

                PwCompareOptions cmpOpt = (PwCompareOptions.IgnoreLastMod | PwCompareOptions.IgnoreLastAccess | PwCompareOptions.IgnoreLastBackup);

                if (pe.EqualsEntry(peInit, cmpOpt, MemProtCmpMode.None))
                {
                    pe.LastModificationTime = peInit.LastModificationTime;

                    pe.History.Remove(pe.History.GetAt(pe.History.UCount - 1)); // Undo backup

                    return(false);
                }
                else
                {
                    return(true);
                }
            }
Beispiel #19
0
        private void MergeEntries(PwEntry destination, PwEntry source, int urlMergeMode, PwDatabase db)
        {
            EntryConfig destConfig;
            string destJSON = KeePassRPCPlugin.GetPwEntryString(destination, "KPRPC JSON", db);
            if (string.IsNullOrEmpty(destJSON))
            {
                destConfig = new EntryConfig();
            }
            else
            {
                try
                {
                    destConfig = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), destJSON);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + destination.Strings.ReadSafe("URL") + " and the full configuration data is: " + destJSON, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            EntryConfig sourceConfig;
            string sourceJSON = KeePassRPCPlugin.GetPwEntryString(source, "KPRPC JSON", db);
            if (string.IsNullOrEmpty(sourceJSON))
            {
                sourceConfig = new EntryConfig();
            }
            else
            {
                try
                {
                    sourceConfig = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), sourceJSON);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + source.Strings.ReadSafe("URL") + " and the full configuration data is: " + sourceJSON, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            destination.CreateBackup(db);

            destConfig.HTTPRealm = sourceConfig.HTTPRealm;
            destination.IconId = source.IconId;
            destination.CustomIconUuid = source.CustomIconUuid;
            destination.Strings.Set("UserName", new ProtectedString(
                host.Database.MemoryProtection.ProtectUserName, source.Strings.ReadSafe("UserName")));
            destination.Strings.Set("Password", new ProtectedString(
                host.Database.MemoryProtection.ProtectPassword, source.Strings.ReadSafe("Password")));
            destConfig.FormFieldList = sourceConfig.FormFieldList;

            // This algorithm could probably be made more efficient (lots of O(n) operations
            // but we're dealing with pretty small n so I've gone with the conceptually
            // easiest approach for now).

            List<string> destURLs = new List<string>();
            destURLs.Add(destination.Strings.ReadSafe("URL"));
            if (destConfig.AltURLs != null)
                destURLs.AddRange(destConfig.AltURLs);

            List<string> sourceURLs = new List<string>();
            sourceURLs.Add(source.Strings.ReadSafe("URL"));
            if (sourceConfig.AltURLs != null)
                sourceURLs.AddRange(sourceConfig.AltURLs);

            switch (urlMergeMode)
            {
                case 1:
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 2:
                    destURLs.RemoveAt(0);
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 3:
                    if (sourceURLs.Count > 0)
                    {
                        foreach (string sourceUrl in sourceURLs)
                            if (!destURLs.Contains(sourceUrl))
                                destURLs.Add(sourceUrl);
                    }
                    break;
                case 4:
                default:
                    // No changes to URLs
                    break;
            }

            // These might not have changed but meh
            destination.Strings.Set("URL", new ProtectedString(host.Database.MemoryProtection.ProtectUrl, destURLs[0]));
            destConfig.AltURLs = new string[0];
            if (destURLs.Count > 1)
                destConfig.AltURLs = destURLs.GetRange(1,destURLs.Count-1).ToArray();

            destination.Strings.Set("KPRPC JSON", new ProtectedString(true, Jayrock.Json.Conversion.JsonConvert.ExportToString(destConfig)));
            destination.Touch(true);
        }
Beispiel #20
0
        private bool UpdateEntry(PwUuid uuid, string username, string password, string formHost, string requestId, string groupName, string name)
        {
            PwEntry entry = null;

            var configOpt = new ConfigOpt(this.host.CustomConfig);

            if (configOpt.SearchInAllOpenedDatabases)
            {
                foreach (PwDocument doc in host.MainWindow.DocumentManager.Documents)
                {
                    if (doc.Database.IsOpen)
                    {
                        entry = doc.Database.RootGroup.FindEntry(uuid, true);
                        if (entry != null)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                entry = host.Database.RootGroup.FindEntry(uuid, true);
            }

            if (entry == null)
            {
                return(false);
            }

            string[] up           = GetUserPass(entry);
            var      u            = up[0];
            var      p            = up[1];
            var      t            = up[2];
            var      currentGroup = entry.ParentGroup.GetFullPath("/", true);
            // prepend the passed group w/ the root group name so it matches the GetFullPath
            var fullGroupName = host.Database.RootGroup.Name + "/" + groupName;

            if (u != username || p != password || (groupName != null && currentGroup != fullGroupName) || (name != null && t != name))
            {
                bool allowUpdate = configOpt.AlwaysAllowUpdates;

                if (!allowUpdate)
                {
                    host.MainWindow.Activate();

                    DialogResult result;
                    if (host.MainWindow.IsTrayed())
                    {
                        result = MessageBox.Show(
                            String.Format("Do you want to update the information in {0} - {1}?", formHost, u),
                            "Update Entry", MessageBoxButtons.YesNo,
                            MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
                    else
                    {
                        result = MessageBox.Show(
                            host.MainWindow,
                            String.Format("Do you want to update the information in {0} - {1}?", formHost, u),
                            "Update Entry", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }


                    if (result == DialogResult.Yes)
                    {
                        allowUpdate = true;
                    }
                }

                if (allowUpdate)
                {
                    if (groupName != null)
                    {
                        PwGroup newGroup;

                        if (groupName == "/")
                        {
                            newGroup = host.Database.RootGroup;
                        }
                        else
                        {
                            newGroup = host.Database.RootGroup.FindCreateSubTree(groupName, KEEPASSHTTP_GROUP_SEPERATOR);
                        }

                        if (entry.ParentGroup != newGroup)
                        {
                            var oldGroup = entry.ParentGroup;
                            newGroup.AddEntry(entry, true);
                            oldGroup.Entries.Remove(entry);
                        }
                    }


                    PwObjectList <PwEntry> m_vHistory = entry.History.CloneDeep();
                    entry.History = m_vHistory;
                    entry.CreateBackup(null);

                    if (name != null)
                    {
                        entry.Strings.Set(PwDefs.TitleField, new ProtectedString(false, name));
                    }

                    entry.Strings.Set(PwDefs.UserNameField, new ProtectedString(false, username));
                    entry.Strings.Set(PwDefs.PasswordField, new ProtectedString(true, password));
                    entry.Touch(true, false);
                    UpdateUI(entry.ParentGroup);

                    return(true);
                }
            }

            return(false);
        }
Beispiel #21
0
        public bool SaveEntry(EntryModel edited, PwEntry m_pwInitialEntry /*, bool bValidate*/)
        {
            const PwCompareOptions m_cmpOpt = (PwCompareOptions.NullEmptyEquivStd | PwCompareOptions.IgnoreTimes);

            PwEntry originalEntry = edited.Entry;
            //peTarget.History = m_vHistory; // Must be called before CreateBackup()

            bool bCreateBackup = !edited.IsNew;

            if (bCreateBackup)
            {
                originalEntry.CreateBackup(null);
            }

//         peTarget.IconId = m_pwEntryIcon;
//         peTarget.CustomIconUuid = m_pwCustomIconID;
//
//         if(m_cbCustomForegroundColor.Checked)
//            peTarget.ForegroundColor = m_clrForeground;
//         else peTarget.ForegroundColor = Color.Empty;
//         if(m_cbCustomBackgroundColor.Checked)
//            peTarget.BackgroundColor = m_clrBackground;
//         else peTarget.BackgroundColor = Color.Empty;

            //peTarget.OverrideUrl = m_tbOverrideUrl.Text;

//         List<string> vNewTags = StrUtil.StringToTags(m_tbTags.Text);
//         peTarget.Tags.Clear();
//         foreach(string strTag in vNewTags) peTarget.AddTag(strTag);

            originalEntry.Expires = edited.Expires;

            if (originalEntry.Expires)
            {
                originalEntry.ExpiryTime = edited.ExpireDate;
            }

            UpdateEntryStrings(edited, originalEntry.Strings);

//         peTarget.Strings = m_vStrings;
//         peTarget.Binaries = m_vBinaries;

//         m_atConfig.Enabled = m_cbAutoTypeEnabled.Checked;
//         m_atConfig.ObfuscationOptions = (m_cbAutoTypeObfuscation.Checked ?
//            AutoTypeObfuscationOptions.UseClipboard :
//            AutoTypeObfuscationOptions.None);
//
//         SaveDefaultSeq();

//         peTarget.AutoType = m_atConfig;

            originalEntry.Touch(true, false); // Touch *after* backup

//         if(object.ReferenceEquals(peTarget, m_pwEntry))
//            m_bTouchedOnce = true;

            StrUtil.NormalizeNewLines(originalEntry.Strings, true);

            bool             bUndoBackup = false;
            PwCompareOptions cmpOpt      = m_cmpOpt;

            if (bCreateBackup)
            {
                cmpOpt |= PwCompareOptions.IgnoreLastBackup;
            }

            if (originalEntry.EqualsEntry(m_pwInitialEntry, cmpOpt, MemProtCmpMode.CustomOnly))
            {
                // No modifications at all => restore last mod time and undo backup
                originalEntry.LastModificationTime = m_pwInitialEntry.LastModificationTime;
                bUndoBackup = bCreateBackup;
            }
            else if (bCreateBackup)
            {
                // If only history items have been modified (deleted) => undo
                // backup, but without restoring the last mod time
                PwCompareOptions cmpOptNH = (m_cmpOpt | PwCompareOptions.IgnoreHistory);
                if (originalEntry.EqualsEntry(m_pwInitialEntry, cmpOptNH, MemProtCmpMode.CustomOnly))
                {
                    bUndoBackup = true;
                }
            }

            if (bUndoBackup)
            {
                originalEntry.History.RemoveAt(originalEntry.History.UCount - 1);
            }

            originalEntry.MaintainBackups(db);

            return(true);
        }
Beispiel #22
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
                                                            SprContext ctx, uint uRecursionLevel)
        {
            PwEntry    pe = ctx.Entry;
            PwDatabase pd = ctx.Database;

            if ((pe == null) || (pd == null))
            {
                return(strText);
            }

            string str = strText;

            const string strNewPwStart = @"{NEWPASSWORD";

            if (str.IndexOf(strNewPwStart, StrUtil.CaseIgnoreCmp) < 0)
            {
                return(str);
            }

            string strGen = null;

            int           iStart;
            List <string> lParams;

            while (SprEngine.ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                                         strNewPwStart + ":", out iStart, out lParams, true))
            {
                if (strGen == null)
                {
                    strGen = GeneratePassword((((lParams != null) &&
                                                (lParams.Count > 0)) ? lParams[0] : string.Empty), ctx);
                }

                string strIns = SprEngine.TransformContent(strGen, ctx);
                str = str.Insert(iStart, strIns);
            }

            const string strNewPwPlh = strNewPwStart + @"}";

            if (str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                if (strGen == null)
                {
                    strGen = GeneratePassword(null, ctx);
                }

                string strIns = SprEngine.TransformContent(strGen, ctx);
                str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
            }

            if (strGen != null)
            {
                pe.CreateBackup(pd);

                ProtectedString psGen = new ProtectedString(
                    pd.MemoryProtection.ProtectPassword, strGen);
                pe.Strings.Set(PwDefs.PasswordField, psGen);

                pe.Touch(true, false);
                pd.Modified = true;
            }
            else
            {
                Debug.Assert(false);
            }

            return(str);
        }
Beispiel #23
0
        private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage,
                                        string strLineBreak)
        {
            Debug.Assert(xmlNode != null); if (xmlNode == null)
            {
                return;
            }

            PwEntry pe           = new PwEntry(true, true);
            string  strGroupName = string.Empty;

            List <DatePasswordPair> listHistory = null;

            foreach (XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    strGroupName = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemTitle)
                {
                    pe.Strings.Set(PwDefs.TitleField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectTitle,
                                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUserName)
                {
                    pe.Strings.Set(PwDefs.UserNameField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectUserName,
                                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectPassword,
                                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemURL)
                {
                    pe.Strings.Set(PwDefs.UrlField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectUrl,
                                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectNotes,
                                                       XmlUtil.SafeInnerText(xmlChild, strLineBreak)));
                }
                else if (xmlChild.Name == ElemEMail)
                {
                    pe.Strings.Set("E-Mail", new ProtectedString(false,
                                                                 XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemCreationTime)
                {
                    pe.CreationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemLastAccessTime)
                {
                    pe.LastAccessTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemExpireTime)
                {
                    pe.ExpiryTime = ReadDateTime(xmlChild);
                    pe.Expires    = true;
                }
                else if (xmlChild.Name == ElemLastModTime)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemRecordModTime)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemCreationTimeX)
                {
                    pe.CreationTime = ReadDateTimeX(xmlChild);
                }
                else if (xmlChild.Name == ElemLastAccessTimeX)
                {
                    pe.LastAccessTime = ReadDateTimeX(xmlChild);
                }
                else if (xmlChild.Name == ElemExpireTimeX)
                {
                    pe.ExpiryTime = ReadDateTimeX(xmlChild);
                    pe.Expires    = true;
                }
                else if (xmlChild.Name == ElemLastModTimeX)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTimeX(xmlChild);
                }
                else if (xmlChild.Name == ElemRecordModTimeX)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTimeX(xmlChild);
                }
                else if (xmlChild.Name == ElemAutoType)
                {
                    pe.AutoType.DefaultSequence = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemRunCommand)
                {
                    pe.OverrideUrl = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemEntryHistory)
                {
                    listHistory = ReadEntryHistory(xmlChild);
                }
            }

            if (listHistory != null)
            {
                string   strPassword = pe.Strings.ReadSafe(PwDefs.PasswordField);
                DateTime dtLastMod   = pe.LastModificationTime;

                foreach (DatePasswordPair dpp in listHistory)
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       dpp.Password));
                    pe.LastModificationTime = dpp.Time;

                    pe.CreateBackup(null);
                }
                // Maintain backups manually now (backups from the imported file
                // might have been out of order)
                pe.MaintainBackups(pwStorage);

                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectPassword,
                                   strPassword));
                pe.LastModificationTime = dtLastMod;
            }

            PwGroup pgContainer = pwStorage.RootGroup;

            if (strGroupName.Length != 0)
            {
                pgContainer = pwStorage.RootGroup.FindCreateSubTree(strGroupName,
                                                                    new string[1] {
                    "."
                }, true);
            }
            pgContainer.AddEntry(pe, true);
            pgContainer.IsExpanded = true;
        }
Beispiel #24
0
        /// <summary>
        /// Button that moves forward in the setup steps.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonFinish_Click(object sender, EventArgs e)
        {
            string invalidBase32Chars;

            // TOTP Seed field
            if (TextBoxSeedSetup.Text == string.Empty) //If no TOTP Seed
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, Localization.Strings.SetupSeedCantBeEmpty);
            }
            else if (Base32.HasInvalidPadding(TextBoxSeedSetup.Text.ExtWithoutSpaces()))
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, Localization.Strings.SetupInvalidPadding);
            }
            else if (!TextBoxSeedSetup.Text.ExtWithoutSpaces().IsBase32(out invalidBase32Chars))
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, Localization.Strings.SetupInvalidCharacter + "(" + invalidBase32Chars + ")");
            }
            else
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, string.Empty);
            }

            // Interval field
            if ((NumericIntervalSetup.Value < 1) || (NumericIntervalSetup.Value > 180))
            {
                ErrorProviderSetup.SetError(NumericIntervalSetup, string.Format(Localization.Strings.SetupInterval, Environment.NewLine));
            }
            else
            {
                ErrorProviderSetup.SetError(NumericIntervalSetup, string.Empty);
            }

            // Format/Interval radios
            if (!RadioButtonLength6Setup.Checked && !RadioButtonLength7Setup.Checked && !RadioButtonLength8Setup.Checked && !RadioButtonSteamFormatSetup.Checked)
            {
                ErrorProviderSetup.SetError(RadioButtonLength8Setup, Localization.Strings.SetupLengthMandatory);
            }
            else
            {
                ErrorProviderSetup.SetError(RadioButtonLength8Setup, string.Empty);
            }

            // Time Correction Field
            if (ComboBoxTimeCorrectionSetup.Text != string.Empty)
            {
                string uriName = ComboBoxTimeCorrectionSetup.Text;

                Uri  uriResult;
                bool validUrl = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                if (!validUrl)
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, Localization.Strings.SetupInvalidUrl);
                }
                else
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, string.Empty);
                }
            }

            if (ErrorProviderSetup.GetError(TextBoxSeedSetup) != string.Empty ||
                ErrorProviderSetup.GetError(NumericIntervalSetup) != string.Empty ||
                ErrorProviderSetup.GetError(ComboBoxTimeCorrectionSetup) != string.Empty ||
                ErrorProviderSetup.GetError(ComboBoxTimeCorrectionSetup) != string.Empty)
            {
                return;
            }

            try
            {
                _entry.CreateBackup(_plugin.PluginHost.MainWindow.ActiveDatabase);

                _entry.Strings.Set(_plugin.Settings.TOTPSeedStringName, new ProtectedString(true, TextBoxSeedSetup.Text));

                string format = "";

                if (RadioButtonLength6Setup.Checked)
                {
                    format = "6";
                }
                else if (RadioButtonLength7Setup.Checked)
                {
                    format = "7";
                }
                else if (RadioButtonLength8Setup.Checked)
                {
                    format = "8";
                }
                else if (RadioButtonSteamFormatSetup.Checked)
                {
                    format = "S";
                }

                var settings = new ProtectedString(false, NumericIntervalSetup.Value.ToString() + ";" + format + (ComboBoxTimeCorrectionSetup.Text != string.Empty ? ";" : string.Empty) + ComboBoxTimeCorrectionSetup.Text);
                _entry.Strings.Set(_plugin.Settings.TOTPSettingsStringName, settings);

                _entry.Touch(true);

                _plugin.PluginHost.MainWindow.ActiveDatabase.Modified = true;
                _plugin.ResetLastSelectedGroup();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            DialogResult = DialogResult.OK;
            Close();
        }
Beispiel #25
0
		private static string ReplaceNewPasswordPlaceholder(string strText,
			PwEntry pe, PwDatabase pd, SprContentFlags cf)
		{
			if((pe == null) || (pd == null)) return strText;

			string str = strText;

			const string strNewPwPlh = @"{NEWPASSWORD}";
			if(str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
			{
				ProtectedString psAutoGen = new ProtectedString(
					pd.MemoryProtection.ProtectPassword);
				PwgError e = PwGenerator.Generate(psAutoGen,
					Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
					null, Program.PwGeneratorPool);

				if(e == PwgError.Success)
				{
					pe.CreateBackup();
					pe.Strings.Set(PwDefs.PasswordField, psAutoGen);
					pd.Modified = true;

					string strIns = SprEngine.TransformContent(psAutoGen.ReadString(), cf);
					str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
				}
			}

			return str;
		}
Beispiel #26
0
        private void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage)
        {
            Debug.Assert(xmlNode != null); if (xmlNode == null)
            {
                return;
            }

            PwEntry pe           = new PwEntry(true, true);
            string  strGroupName = string.Empty;

            List <DatePasswordPair> listHistory = null;

            foreach (XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    strGroupName = ImportUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemTitle)
                {
                    pe.Strings.Set(PwDefs.TitleField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectTitle,
                                                       ImportUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUserName)
                {
                    pe.Strings.Set(PwDefs.UserNameField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectUserName,
                                                       ImportUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectPassword,
                                                       ImportUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemURL)
                {
                    pe.Strings.Set(PwDefs.UrlField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectUrl,
                                                       ImportUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField,
                                   new ProtectedString(pwStorage.MemoryProtection.ProtectNotes,
                                                       ImportUtil.SafeInnerText(xmlChild, m_strLineBreak)));
                }
                else if (xmlChild.Name == ElemCreationTime)
                {
                    pe.CreationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemLastAccessTime)
                {
                    pe.LastAccessTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemExpireTime)
                {
                    pe.ExpiryTime = ReadDateTime(xmlChild);
                    pe.Expires    = true;
                }
                else if (xmlChild.Name == ElemLastModTime)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemRecordModTime)                // = last mod
                {
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                }
                else if (xmlChild.Name == ElemAutoType)
                {
                    pe.AutoType.DefaultSequence = ImportUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemEntryHistory)
                {
                    listHistory = ReadEntryHistory(xmlChild);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if (listHistory != null)
            {
                string strPassword = pe.Strings.ReadSafe(PwDefs.PasswordField);

                foreach (DatePasswordPair dpp in listHistory)
                {
                    pe.LastAccessTime = dpp.Time;
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       dpp.Password));

                    pe.CreateBackup();
                }

                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectPassword,
                                   strPassword));
            }

            PwGroup pgContainer = pwStorage.RootGroup;

            if (strGroupName.Length != 0)
            {
                pgContainer = pwStorage.RootGroup.FindCreateSubTree(strGroupName,
                                                                    new char[] { '.' });
            }

            pgContainer.AddEntry(pe, true);

            pgContainer.IsExpanded = true;
        }
Beispiel #27
0
        /// <summary>
        /// Button that moves forward in the setup steps.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonFinish_Click(object sender, EventArgs e)
        {
            string InvalidBase32Chars;

            // TOTP Seed field
            if (TextBoxSeedSetup.Text == string.Empty) //If no TOTP Seed
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, SetupTOTP_Localization.SetupSeedCantBeEmpty);
            }
            else if (!TextBoxSeedSetup.Text.ExtWithoutSpaces().ExtIsBase32(out InvalidBase32Chars)) // TODO: Add support to other known formats
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, SetupTOTP_Localization.SetupInvalidCharacter + "(" + InvalidBase32Chars + ")!");
            }
            else
            {
                ErrorProviderSetup.SetError(TextBoxSeedSetup, string.Empty);
            }

            // Interval field
            if ((NumericIntervalSetup.Value < 1) || (NumericIntervalSetup.Value > 60))
            {
                ErrorProviderSetup.SetError(NumericIntervalSetup, string.Format(SetupTOTP_Localization.SetupInterval1to60, Environment.NewLine));
            }
            else
            {
                ErrorProviderSetup.SetError(NumericIntervalSetup, string.Empty);
            }

            // Format/Interval radios
            if (!RadioButtonLength6Setup.Checked && !RadioButtonLength7Setup.Checked && !RadioButtonLength8Setup.Checked && !RadioButtonSteamFormatSetup.Checked)
            {
                ErrorProviderSetup.SetError(RadioButtonLength8Setup, SetupTOTP_Localization.SetupLengthMandatory);
            }
            else
            {
                ErrorProviderSetup.SetError(RadioButtonLength8Setup, string.Empty);
            }

            // Time Correction Field
            if (ComboBoxTimeCorrectionSetup.Text != string.Empty)
            {
                string uriName = ComboBoxTimeCorrectionSetup.Text;

                Uri  uriResult;
                bool validURL = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) &&
                                (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                if (!validURL)
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, SetupTOTP_Localization.SetupInvalidUrl);
                }
                else
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, string.Empty);
                }
            }

            /* ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, SetupTOTP_Localization.SetupUrlMustContainHttp);
             * if (ComboBoxTimeCorrectionSetup.Text.Contains(";"))
             *  ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, SetupTOTP_Localization.SetupInvalidCharacter + " (;)");
             */

            if (ErrorProviderSetup.GetError(TextBoxSeedSetup) != string.Empty ||
                ErrorProviderSetup.GetError(NumericIntervalSetup) != string.Empty ||
                ErrorProviderSetup.GetError(ComboBoxTimeCorrectionSetup) != string.Empty ||
                ErrorProviderSetup.GetError(ComboBoxTimeCorrectionSetup) != string.Empty)
            {
                return;
            }



            try
            {
                entry.CreateBackup(_plugin.m_host.MainWindow.ActiveDatabase);

                entry.Strings.Set(_plugin.m_host.CustomConfig.GetString(KeeTrayTOTPExt.setname_string_TOTPSeed_StringName,
                                                                        TrayTOTP_Plugin_Localization.setdef_string_TOTPSeed_StringName),
                                  new ProtectedString(true, TextBoxSeedSetup.Text)
                                  );

                string format = "";

                if (RadioButtonLength6Setup.Checked)
                {
                    format = "6";
                }
                else if (RadioButtonLength7Setup.Checked)
                {
                    format = "7";
                }
                else if (RadioButtonLength8Setup.Checked)
                {
                    format = "8";
                }
                else if (RadioButtonSteamFormatSetup.Checked)
                {
                    format = "S";
                }

                entry.Strings.Set(_plugin.m_host.CustomConfig.GetString(KeeTrayTOTPExt.setname_string_TOTPSettings_StringName,
                                                                        TrayTOTP_Plugin_Localization.setdef_string_TOTPSettings_StringName),
                                  new ProtectedString(false,
                                                      NumericIntervalSetup.Value.ToString() + ";" + format +
                                                      (ComboBoxTimeCorrectionSetup.Text != string.Empty ? ";" : string.Empty) + ComboBoxTimeCorrectionSetup.Text)
                                  );

                entry.Touch(true);

                _plugin.m_host.MainWindow.ActiveDatabase.Modified = true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
                return;
            }

            DialogResult = DialogResult.OK;
            Close();
        }
Beispiel #28
0
        /// <summary>
        /// Button that moves forward in the setup steps.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonNext_Click(object sender, EventArgs e)
        {
            switch (_CurrentStep)
            {
            case 1:
                //Welcome
                break;

            case 2:
                //Interval
                ErrorProviderSetup.SetError(NumericIntervalSetup, string.Empty);
                if ((NumericIntervalSetup.Value < 1) || (NumericIntervalSetup.Value > 60))
                {
                    ErrorProviderSetup.SetError(NumericIntervalSetup, string.Format(FormSetup_Localization.SetupInterval1to60, Environment.NewLine));
                }
                if (ErrorProviderSetup.GetError(NumericIntervalSetup) != string.Empty)
                {
                    return;
                }
                break;

            case 3:
                //Length
                ErrorProviderSetup.SetError(RadioButtonLength8Setup, string.Empty);
                if (!RadioButtonLength6Setup.Checked && !RadioButtonLength8Setup.Checked)
                {
                    ErrorProviderSetup.SetError(RadioButtonLength8Setup, FormSetup_Localization.SetupLengthMandatory);
                }
                if (ErrorProviderSetup.GetError(RadioButtonLength8Setup) != string.Empty)
                {
                    return;
                }
                break;

            case 4:
                //Seed
                ErrorProviderSetup.SetError(TextBoxSeedSetup, string.Empty);
                if (TextBoxSeedSetup.Text == string.Empty)
                {
                    ErrorProviderSetup.SetError(TextBoxSeedSetup, FormSetup_Localization.SetupSeedCantBeEmpty);
                }
                string InvalidBase32Chars;
                if (!TextBoxSeedSetup.Text.ExtWithoutSpaces().ExtIsBase32(out InvalidBase32Chars))
                {
                    ErrorProviderSetup.SetError(TextBoxSeedSetup, FormSetup_Localization.SetupInvalidCharacter + "(" + InvalidBase32Chars + ")!");
                }
                if (ErrorProviderSetup.GetError(TextBoxSeedSetup) != string.Empty)
                {
                    return;
                }
                break;

            case 5:
                //Time Correction
                ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, string.Empty);
                if (ComboBoxTimeCorrectionSetup.Text != string.Empty && !ComboBoxTimeCorrectionSetup.Text.StartsWith("http"))
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, FormSetup_Localization.SetupUrlMustContainHttp);
                }
                if (ComboBoxTimeCorrectionSetup.Text != string.Empty && !ComboBoxTimeCorrectionSetup.Text.Contains("://"))
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, FormSetup_Localization.SetupInvalidUrl);
                }
                if (ComboBoxTimeCorrectionSetup.Text.Contains(";"))
                {
                    ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, FormSetup_Localization.SetupInvalidCharacter + " (;)");
                }
                if (ErrorProviderSetup.GetError(ComboBoxTimeCorrectionSetup) != string.Empty)
                {
                    return;
                }
                break;

            case 6:
                //Proceed
                try
                {
                    entry.CreateBackup(_plugin.m_host.MainWindow.ActiveDatabase);
                    entry.Strings.Set(_plugin.m_host.CustomConfig.GetString(TrayTotpGTExt.setname_string_TotpSeed_StringName, TrayTotp_Plugin_Localization.setdef_string_TotpSeed_StringName), new ProtectedString(true, TextBoxSeedSetup.Text));
                    entry.Strings.Set(_plugin.m_host.CustomConfig.GetString(TrayTotpGTExt.setname_string_TotpSettings_StringName, TrayTotp_Plugin_Localization.setdef_string_TotpSettings_StringName), new ProtectedString(false, NumericIntervalSetup.Value.ToString() + ";" + (RadioButtonLength6Setup.Checked ? "6" : (RadioButtonLength8Setup.Checked ? "8" : "6")) + (ComboBoxTimeCorrectionSetup.Text != string.Empty ? ";" : string.Empty) + ComboBoxTimeCorrectionSetup.Text));
                    entry.Touch(true);
                    _plugin.m_host.MainWindow.ActiveDatabase.Modified = true;
                }
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                    return;
                }
                break;

            case 7:
                //Confirmation
                DialogResult = DialogResult.OK;
                Close();
                break;
            }
            CurrentStep++;
        }
Beispiel #29
0
		private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage,
			string strLineBreak)
		{
			Debug.Assert(xmlNode != null); if(xmlNode == null) return;

			PwEntry pe = new PwEntry(true, true);
			string strGroupName = string.Empty;

			List<DatePasswordPair> listHistory = null;

			foreach(XmlNode xmlChild in xmlNode.ChildNodes)
			{
				if(xmlChild.Name == ElemGroup)
					strGroupName = XmlUtil.SafeInnerText(xmlChild);
				else if(xmlChild.Name == ElemTitle)
					pe.Strings.Set(PwDefs.TitleField,
						new ProtectedString(pwStorage.MemoryProtection.ProtectTitle,
						XmlUtil.SafeInnerText(xmlChild)));
				else if(xmlChild.Name == ElemUserName)
					pe.Strings.Set(PwDefs.UserNameField,
						new ProtectedString(pwStorage.MemoryProtection.ProtectUserName,
						XmlUtil.SafeInnerText(xmlChild)));
				else if(xmlChild.Name == ElemPassword)
					pe.Strings.Set(PwDefs.PasswordField,
						new ProtectedString(pwStorage.MemoryProtection.ProtectPassword,
						XmlUtil.SafeInnerText(xmlChild)));
				else if(xmlChild.Name == ElemURL)
					pe.Strings.Set(PwDefs.UrlField,
						new ProtectedString(pwStorage.MemoryProtection.ProtectUrl,
						XmlUtil.SafeInnerText(xmlChild)));
				else if(xmlChild.Name == ElemNotes)
					pe.Strings.Set(PwDefs.NotesField,
						new ProtectedString(pwStorage.MemoryProtection.ProtectNotes,
						XmlUtil.SafeInnerText(xmlChild, strLineBreak)));
				else if(xmlChild.Name == ElemEMail)
					pe.Strings.Set("E-Mail", new ProtectedString(false,
						XmlUtil.SafeInnerText(xmlChild)));
				else if(xmlChild.Name == ElemCreationTime)
					pe.CreationTime = ReadDateTime(xmlChild);
				else if(xmlChild.Name == ElemLastAccessTime)
					pe.LastAccessTime = ReadDateTime(xmlChild);
				else if(xmlChild.Name == ElemExpireTime)
				{
					pe.ExpiryTime = ReadDateTime(xmlChild);
					pe.Expires = true;
				}
				else if(xmlChild.Name == ElemLastModTime) // = last mod
					pe.LastModificationTime = ReadDateTime(xmlChild);
				else if(xmlChild.Name == ElemRecordModTime) // = last mod
					pe.LastModificationTime = ReadDateTime(xmlChild);
				else if(xmlChild.Name == ElemCreationTimeX)
					pe.CreationTime = ReadDateTimeX(xmlChild);
				else if(xmlChild.Name == ElemLastAccessTimeX)
					pe.LastAccessTime = ReadDateTimeX(xmlChild);
				else if(xmlChild.Name == ElemExpireTimeX)
				{
					pe.ExpiryTime = ReadDateTimeX(xmlChild);
					pe.Expires = true;
				}
				else if(xmlChild.Name == ElemLastModTimeX) // = last mod
					pe.LastModificationTime = ReadDateTimeX(xmlChild);
				else if(xmlChild.Name == ElemRecordModTimeX) // = last mod
					pe.LastModificationTime = ReadDateTimeX(xmlChild);
				else if(xmlChild.Name == ElemAutoType)
					pe.AutoType.DefaultSequence = XmlUtil.SafeInnerText(xmlChild);
				else if(xmlChild.Name == ElemRunCommand)
					pe.OverrideUrl = XmlUtil.SafeInnerText(xmlChild);
				else if(xmlChild.Name == ElemEntryHistory)
					listHistory = ReadEntryHistory(xmlChild);
			}

			if(listHistory != null)
			{
				string strPassword = pe.Strings.ReadSafe(PwDefs.PasswordField);
				DateTime dtLastMod = pe.LastModificationTime;

				foreach(DatePasswordPair dpp in listHistory)
				{
					pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectPassword,
						dpp.Password));
					pe.LastModificationTime = dpp.Time;

					pe.CreateBackup(null);
				}
				// Maintain backups manually now (backups from the imported file
				// might have been out of order)
				pe.MaintainBackups(pwStorage);

				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectPassword,
					strPassword));
				pe.LastModificationTime = dtLastMod;
			}

			PwGroup pgContainer = pwStorage.RootGroup;
			if(strGroupName.Length != 0)
				pgContainer = pwStorage.RootGroup.FindCreateSubTree(strGroupName,
					new string[1]{ "." }, true);
			pgContainer.AddEntry(pe, true);
			pgContainer.IsExpanded = true;
		}
        private void MergeEntries(PwEntry destination, PwEntry source, int urlMergeMode, PwDatabase db)
        {
            EntryConfig destConfig = destination.GetKPRPCConfig();
            if (destConfig == null)
                return;

            EntryConfig sourceConfig = source.GetKPRPCConfig();
            if (sourceConfig == null)
                return;

            destination.CreateBackup(db);

            destConfig.HTTPRealm = sourceConfig.HTTPRealm;
            destination.IconId = source.IconId;
            destination.CustomIconUuid = source.CustomIconUuid;
            destination.Strings.Set("UserName", new ProtectedString(
                host.Database.MemoryProtection.ProtectUserName, source.Strings.ReadSafe("UserName")));
            destination.Strings.Set("Password", new ProtectedString(
                host.Database.MemoryProtection.ProtectPassword, source.Strings.ReadSafe("Password")));
            destConfig.FormFieldList = sourceConfig.FormFieldList;

            // This algorithm could probably be made more efficient (lots of O(n) operations
            // but we're dealing with pretty small n so I've gone with the conceptually
            // easiest approach for now).

            List<string> destURLs = new List<string>();
            destURLs.Add(destination.Strings.ReadSafe("URL"));
            if (destConfig.AltURLs != null)
                destURLs.AddRange(destConfig.AltURLs);

            List<string> sourceURLs = new List<string>();
            sourceURLs.Add(source.Strings.ReadSafe("URL"));
            if (sourceConfig.AltURLs != null)
                sourceURLs.AddRange(sourceConfig.AltURLs);

            switch (urlMergeMode)
            {
                case 1:
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 2:
                    destURLs.RemoveAt(0);
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 3:
                    if (sourceURLs.Count > 0)
                    {
                        foreach (string sourceUrl in sourceURLs)
                            if (!destURLs.Contains(sourceUrl))
                                destURLs.Add(sourceUrl);
                    }
                    break;
                case 4:
                default:
                    // No changes to URLs
                    break;
            }

            // These might not have changed but meh
            destination.Strings.Set("URL", new ProtectedString(host.Database.MemoryProtection.ProtectUrl, destURLs[0]));
            destConfig.AltURLs = new string[0];
            if (destURLs.Count > 1)
                destConfig.AltURLs = destURLs.GetRange(1,destURLs.Count-1).ToArray();

            destination.SetKPRPCConfig(destConfig);
            destination.Touch(true);
        }
Beispiel #31
0
        private bool UpdateEntry(PwUuid uuid, string username, string password, string formHost, string requestId)
        {
            PwEntry entry = null;

            var configOpt = new ConfigOpt(this.host.CustomConfig);

            if (configOpt.SearchInAllOpenedDatabases)
            {
                foreach (PwDocument doc in host.MainWindow.DocumentManager.Documents)
                {
                    if (doc.Database.IsOpen)
                    {
                        entry = doc.Database.RootGroup.FindEntry(uuid, true);
                        if (entry != null)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                entry = host.Database.RootGroup.FindEntry(uuid, true);
            }

            if (entry == null)
            {
                return(false);
            }

            string[] up = GetUserPass(entry);
            var      u  = up[0];
            var      p  = up[1];

            if (u != username || p != password)
            {
                bool allowUpdate = configOpt.AlwaysAllowUpdates;

                if (!allowUpdate)
                {
                    host.MainWindow.Activate();

                    DialogResult result;
                    if (host.MainWindow.IsTrayed())
                    {
                        result = MessageBox.Show(
                            String.Format("Do you want to update the information in {0} - {1}?", formHost, u),
                            "Update Entry", MessageBoxButtons.YesNo,
                            MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
                    else
                    {
                        result = MessageBox.Show(
                            host.MainWindow,
                            String.Format("Do you want to update the information in {0} - {1}?", formHost, u),
                            "Update Entry", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }


                    if (result == DialogResult.Yes)
                    {
                        allowUpdate = true;
                    }
                }

                if (allowUpdate)
                {
                    PwObjectList <PwEntry> m_vHistory = entry.History.CloneDeep();
                    entry.History = m_vHistory;
                    entry.CreateBackup(null);

                    entry.Strings.Set(PwDefs.UserNameField, new ProtectedString(false, username));
                    entry.Strings.Set(PwDefs.PasswordField, new ProtectedString(true, password));
                    entry.Touch(true, false);
                    UpdateUI(entry.ParentGroup);

                    return(true);
                }
            }

            return(false);
        }
Beispiel #32
0
        private void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage)
        {
            Debug.Assert(xmlNode != null); if(xmlNode == null) return;

            PwEntry pe = new PwEntry(true, true);
            string strGroupName = string.Empty;

            List<DatePasswordPair> listHistory = null;

            foreach(XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if(xmlChild.Name == ElemGroup)
                    strGroupName = ImportUtil.SafeInnerText(xmlChild);
                else if(xmlChild.Name == ElemTitle)
                    pe.Strings.Set(PwDefs.TitleField,
                        new ProtectedString(pwStorage.MemoryProtection.ProtectTitle,
                        ImportUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemUserName)
                    pe.Strings.Set(PwDefs.UserNameField,
                        new ProtectedString(pwStorage.MemoryProtection.ProtectUserName,
                        ImportUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemPassword)
                    pe.Strings.Set(PwDefs.PasswordField,
                        new ProtectedString(pwStorage.MemoryProtection.ProtectPassword,
                        ImportUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemURL)
                    pe.Strings.Set(PwDefs.UrlField,
                        new ProtectedString(pwStorage.MemoryProtection.ProtectUrl,
                        ImportUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemNotes)
                    pe.Strings.Set(PwDefs.NotesField,
                        new ProtectedString(pwStorage.MemoryProtection.ProtectNotes,
                        ImportUtil.SafeInnerText(xmlChild, m_strLineBreak)));
                else if(xmlChild.Name == ElemCreationTime)
                    pe.CreationTime = ReadDateTime(xmlChild);
                else if(xmlChild.Name == ElemLastAccessTime)
                    pe.LastAccessTime = ReadDateTime(xmlChild);
                else if(xmlChild.Name == ElemExpireTime)
                {
                    pe.ExpiryTime = ReadDateTime(xmlChild);
                    pe.Expires = true;
                }
                else if(xmlChild.Name == ElemLastModTime) // = last mod
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                else if(xmlChild.Name == ElemRecordModTime) // = last mod
                    pe.LastModificationTime = ReadDateTime(xmlChild);
                else if(xmlChild.Name == ElemAutoType)
                    pe.AutoType.DefaultSequence = ImportUtil.SafeInnerText(xmlChild);
                else if(xmlChild.Name == ElemEntryHistory)
                    listHistory = ReadEntryHistory(xmlChild);
                else { Debug.Assert(false); }
            }

            if(listHistory != null)
            {
                string strPassword = pe.Strings.ReadSafe(PwDefs.PasswordField);

                foreach(DatePasswordPair dpp in listHistory)
                {
                    pe.LastAccessTime = dpp.Time;
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectPassword,
                        dpp.Password));

                    pe.CreateBackup();
                }

                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                    pwStorage.MemoryProtection.ProtectPassword,
                    strPassword));
            }

            PwGroup pgContainer = pwStorage.RootGroup;
            if(strGroupName.Length != 0)
                pgContainer = pwStorage.RootGroup.FindCreateSubTree(strGroupName,
                    new char[]{ '.' });

            pgContainer.AddEntry(pe, true);

            pgContainer.IsExpanded = true;
        }