コード例 #1
0
ファイル: ClipboardUtil.cs プロジェクト: ComradeP/KeePass-2.x
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			Debug.Assert(psToCopy != null);
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");

			if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
				return false;

			string strData = SprEngine.Compile(psToCopy.ReadString(), false,
				peEntryInfo, pwReferenceSource, false, false);

			try
			{
				ClipboardUtil.Clear();

				DataObject doData = CreateProtectedDataObject(strData);
				Clipboard.SetDataObject(doData);

				m_pbDataHash32 = HashClipboard();
				m_strFormat = null;

				RaiseCopyEvent(bIsEntryInfo, strData);
			}
			catch(Exception) { Debug.Assert(false); return false; }

			if(peEntryInfo != null) peEntryInfo.Touch(false);

			// SprEngine.Compile might have modified the database
			Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

			return true;
		}
コード例 #2
0
        /// <summary>
        /// Save the current configuration
        /// </summary>
        private bool SaveConfiguration()
        {
            m_host.CustomConfig.SetString(Defs.ConfigAutoSync, m_autoSync.ToString());

            // remove old uuid config (may be removed in later versions)
            if (m_host.CustomConfig.GetString(Defs.ConfigUUID) != null)
            {
                m_host.CustomConfig.SetString(Defs.ConfigUUID, null);
            }

            if (!m_host.Database.IsOpen)
            {
                return(false);
            }

            // disable all currently active accounts but the selected (if any)
            PwObjectList <PwEntry> accounts = FindActiveAccounts();

            foreach (PwEntry entry in accounts)
            {
                if (!entry.Equals(m_entry) && entry.Strings.Exists(Defs.ConfigActiveAccount))
                {
                    entry.Strings.Set(Defs.ConfigActiveAccount, new ProtectedString(false, Defs.ConfigActiveAccountFalse));
                    entry.Touch(true);
                }
            }

            if (m_entry == null)
            {
                return(true);
            }

            m_entry.Strings.Set(Defs.ConfigActiveAccount, new ProtectedString(false, Defs.ConfigActiveAccountTrue));

            if (m_clientId == DefaultClientId || String.IsNullOrEmpty(m_clientId))
            {
                m_entry.Strings.Remove(Defs.ConfigClientId);
                m_entry.Strings.Remove(Defs.ConfigClientSecret);
            }
            else
            {
                m_entry.Strings.Set(Defs.ConfigClientId, new ProtectedString(false, m_clientId));
                if (m_clientSecret != null)
                {
                    m_entry.Strings.Set(Defs.ConfigClientSecret, m_clientSecret);
                }
            }
            if (m_refreshToken != null)
            {
                m_entry.Strings.Set(Defs.ConfigRefreshToken, m_refreshToken);
            }

            // mark entry as modified (important)
            m_entry.Touch(true);
            m_host.Database.Save(new NullStatusLogger());

            return(true);
        }
コード例 #3
0
        internal void SetEntryConfig(PwEntry e, EntryConfig c)
        {
            var serializer = NewJsonSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, c);
            e.CustomData.Set(SettingKey, writer.ToString());
            e.Touch(true);
            UpdateUI(e.ParentGroup);
        }
コード例 #4
0
        internal void SetEntryConfig(PwEntry e, EntryConfig c)
        {
            var serializer = NewJsonSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, c);
            e.Strings.Set(KeePassNatMsgName, new ProtectedString(false, writer.ToString()));
            e.Touch(true);
            UpdateUI(e.ParentGroup);
        }
コード例 #5
0
        private void SetEntryConfig(PwEntry e, KeePassHttpEntryConfig c)
        {
            var serializer = NewJsonSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, c);
            e.Strings.Set(KEEPASSHTTP_NAME, new ProtectedString(false, writer.ToString()));
            e.Touch(true);
            UpdateUI(e.ParentGroup);
        }
コード例 #6
0
ファイル: PxDatabase.cs プロジェクト: passxyz/KPCLib
        /// <summary>
        /// Delete an entry.
        /// </summary>
        /// <param name="pe">The entry to be deleted. Must not be <c>null</c>.</param>
        /// <param name="permanent">Permanent delete or move to recycle bin</param>
        public void DeleteEntry(PwEntry pe, bool permanent = false)
        {
            if (pe == null)
            {
                throw new ArgumentNullException("pe");
            }

            PwGroup pgRecycleBin = RootGroup.FindGroup(RecycleBinUuid, true);

            PwGroup pgParent = pe.ParentGroup;

            if (pgParent == null)
            {
                return;                               // Can't remove
            }
            pgParent.Entries.Remove(pe);

            bool bPermanent = false;

            if (RecycleBinEnabled == false)
            {
                bPermanent = true;
            }
            else if (permanent)
            {
                bPermanent = true;
            }
            else if (pgRecycleBin == null)
            {
            }                                              // if we cannot find it, we will create it later
            else if (pgParent == pgRecycleBin)
            {
                bPermanent = true;
            }
            else if (pgParent.IsContainedIn(pgRecycleBin))
            {
                bPermanent = true;
            }

            DateTime dtNow = DateTime.UtcNow;

            if (bPermanent)
            {
                PwDeletedObject pdo = new PwDeletedObject(pe.Uuid, dtNow);
                DeletedObjects.Add(pdo);
            }
            else             // Recycle
            {
                EnsureRecycleBin(ref pgRecycleBin);

                pgRecycleBin.AddEntry(pe, true, true);
                pe.Touch(false);
            }
        }
コード例 #7
0
ファイル: Migration.cs プロジェクト: numbnet/KeePassOTP
        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);
        }
コード例 #8
0
        private void TouchEntry(PwEntry pe)
        {
            if (currentStatus == null ||
                currentStatus != Status && currentStatus != PluginOptions.ExcludedText)
            {
                pe.Touched -= PwdTouchedHandler;
                pe.Touched += PwdTouchedHandler;

                pe.Touch(true);
            }

            ResetState();
        }
コード例 #9
0
 /// <summary>
 /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
 /// </summary>
 /// <param name="pe">Password Entry.</param>
 private void TotpCopyToClipboard(PwEntry pe)
 {
     if (SettingsCheck(pe) && SeedCheck(pe))
     {
         bool ValidInterval; bool ValidLength; bool ValidUrl;
         if (SettingsValidate(pe, out ValidInterval, out ValidLength, out ValidUrl))
         {
             bool     NoTimeCorrection = false;
             string[] Settings         = SettingsGet(pe);
             var      TotpGenerator    = new Totp_Provider(Convert.ToInt16(Settings[0]), Convert.ToInt16(Settings[1]));
             if (ValidUrl)
             {
                 var CurrentTimeCorrection = TimeCorrections[Settings[2]];
                 if (CurrentTimeCorrection != null)
                 {
                     TotpGenerator.TimeCorrection = CurrentTimeCorrection.TimeCorrection;
                 }
                 else
                 {
                     TotpGenerator.TimeCorrection = TimeSpan.Zero;
                     NoTimeCorrection             = true;
                 }
             }
             string InvalidCharacters;
             if (SeedValidate(pe, out InvalidCharacters))
             {
                 pe.Touch(false);
                 ClipboardUtil.CopyAndMinimize(TotpGenerator.Generate(Base32.Decode(SeedGet(pe).ReadString().ExtWithoutSpaces())), true, m_host.MainWindow, pe, m_host.MainWindow.ActiveDatabase);
                 m_host.MainWindow.StartClipboardCountdown();
             }
             else
             {
                 MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadSeed + InvalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
             }
             if (NoTimeCorrection)
             {
                 MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadUrl);
             }
         }
         else
         {
             MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadSet);
         }
     }
     else
     {
         MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningNotSet);
     }
 }
コード例 #10
0
ファイル: EntryUtil.cs プロジェクト: ComradeP/KeePass-2.x
        public static void ExpireTanEntry(PwEntry pe)
        {
            if (pe == null)
            {
                throw new ArgumentNullException("pe");
            }
            Debug.Assert(PwDefs.IsTanEntry(pe));

            if (Program.Config.Defaults.TanExpiresOnUse)
            {
                pe.ExpiryTime = DateTime.Now;
                pe.Expires    = true;
                pe.Touch(true);
            }
        }
コード例 #11
0
        public static void increaseHotpCounter(IPluginHost host, OtpAuthData data, PwEntry entry)
        {
            data.Counter = data.Counter + 1;
            if (data.KeeOtp1Mode)
            {
                migrateToKeeOtp1String(data, entry);
            }
            else
            {
                migrateToBuiltInOtp(data, entry);
            }

            entry.Touch(true);
            host.MainWindow.ActiveDatabase.Modified = true;
            host.MainWindow.UpdateUI(false, null, false, null, false, null, true);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
            public int MigrateOTP2DB()
            {
                if (!Valid || !OTPDB_Exists || !OTPDB_Opened)
                {
                    return(-1);
                }
                int moved = 0;
                //process all entries having OTP settings
                PwEntry peBackup     = m_pe;
                PwEntry pe_OTPBackup = m_peOTP;

                foreach (PwEntry pe in DB.RootGroup.GetEntries(true).Where(x => x.Strings.Exists(Config.OTPFIELD)))
                {
                    m_pe = pe;
                    ProtectedString otpfield       = m_pe.Strings.GetSafe(Config.OTPFIELD);
                    ProtectedString timecorrection = m_pe.Strings.GetSafe(Config.TIMECORRECTION);
                    if (otpfield.IsEmpty)
                    {
                        continue;
                    }
                    bool bCreated = false;
                    GetOTPEntry(true, out bCreated);
                    m_peOTP.Strings.Set(Config.OTPFIELD, otpfield);
                    if (!timecorrection.IsEmpty)
                    {
                        m_peOTP.Strings.Set(Config.TIMECORRECTION, timecorrection);
                    }
                    else
                    {
                        m_peOTP.Strings.Remove(Config.TIMECORRECTION);
                    }
                    //Seed has been added to OTP db, increase moved-counter
                    moved++;
                    m_pe.Strings.Remove(Config.OTPFIELD);
                    m_pe.Strings.Remove(Config.TIMECORRECTION);
                    m_pe.Strings.Set(DBNAME, new ProtectedString(false, StrUtil.BoolToString(true)));
                    m_pe.Touch(true);
                    FlagChanged(false);
                }
                m_pe    = peBackup;
                m_peOTP = pe_OTPBackup;
                if (moved > 0)
                {
                    OTPDB_Save();
                }
                return(moved);
            }
コード例 #14
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
            }
コード例 #15
0
            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);
                }
            }
コード例 #16
0
ファイル: AWM.cs プロジェクト: Rookiestyle/AlternateAutoType
 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);
 }
コード例 #17
0
ファイル: Extensions.cs プロジェクト: Rookiestyle/PEDCalc
        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);
        }
コード例 #18
0
        private void TouchEntry(PwEntry pe)
        {
            string currentStatus = null;

            var protectedStatus = pe.Strings.Get(PluginOptions.ColumnName);

            if (protectedStatus != null)
            {
                currentStatus = pe.Strings.Get(PluginOptions.ColumnName).ReadString();
            }

            if (currentStatus == null || currentStatus != Status)
            {
                pe.Touched -= PwdTouchedHandler;
                pe.Touched += PwdTouchedHandler;

                pe.Touch(true);
            }
        }
コード例 #19
0
            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);
            }
コード例 #20
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;
        }
コード例 #21
0
ファイル: EntryActivity.cs プロジェクト: ypid/keepass2android
        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();
        }
コード例 #22
0
        /// <summary>
        /// Test whether an entry is a TAN entry and if so, expire it, provided
        /// that the option for expiring TANs on use is enabled.
        /// </summary>
        /// <param name="pe">Entry.</param>
        /// <returns>If the entry has been modified, the return value is
        /// <c>true</c>, otherwise <c>false</c>.</returns>
        public static bool ExpireTanEntryIfOption(PwEntry pe)
        {
            if (pe == null)
            {
                throw new ArgumentNullException("pe");
            }
            if (!PwDefs.IsTanEntry(pe))
            {
                return(false);                                   // No assert
            }
            if (Program.Config.Defaults.TanExpiresOnUse)
            {
                pe.ExpiryTime = DateTime.Now;
                pe.Expires    = true;
                pe.Touch(true);
                return(true);
            }

            return(false);
        }
コード例 #23
0
        public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
                                PwEntry peEntryInfo, PwDatabase pwReferenceSource)
        {
            Debug.Assert(psToCopy != null);
            if (psToCopy == null)
            {
                throw new ArgumentNullException("psToCopy");
            }

            if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
            {
                return(false);
            }

            string strData = SprEngine.Compile(psToCopy.ReadString(), false,
                                               peEntryInfo, pwReferenceSource, false, false);

            try
            {
                ClipboardUtil.Clear();

                DataObject doData = CreateProtectedDataObject(strData);
                Clipboard.SetDataObject(doData);

                m_pbDataHash32 = HashClipboard();
                m_strFormat    = null;

                RaiseCopyEvent(bIsEntryInfo, strData);
            }
            catch (Exception) { Debug.Assert(false); return(false); }

            if (peEntryInfo != null)
            {
                peEntryInfo.Touch(false);
            }

            // SprEngine.Compile might have modified the database
            Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

            return(true);
        }
コード例 #24
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);
        }
コード例 #25
0
ファイル: CreateEditForm.cs プロジェクト: aXe1/KeeYaOtp
        private void CreateEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult != DialogResult.OK)
            {
                return;
            }

            if (OtpDataUtils.TryCreateOtpData(textSecret.Text, textPin.Text, out var dataString))
            {
                if (!_entry.Strings.Exists(OtpDataUtils.Key) || _entry.Strings.Get(OtpDataUtils.Key).ReadString() != dataString)
                {
                    _entry.Strings.Set(OtpDataUtils.Key, new ProtectedString(true, dataString));
                    _entry.Touch(true);
                    _host.MainWindow.UpdateUI(false, null, true, _host.Database.RootGroup, true, null, true);
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
コード例 #26
0
ファイル: DeleteRunnable.cs プロジェクト: 77rusa/README
        protected void DoDeleteEntry(PwEntry pe, List <PwGroup> touchedGroups)
        {
            PwDatabase pd = Db.KpDatabase;

            PwGroup pgRecycleBin = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);

            bool     bUpdateGroupList = false;
            DateTime dtNow            = DateTime.Now;

            PwGroup pgParent = pe.ParentGroup;

            if (pgParent != null)
            {
                pgParent.Entries.Remove(pe);
                //TODO check if RecycleBin is deleted
                //TODO no recycle bin in KDB

                if ((DeletePermanently) || (!CanRecycle))
                {
                    PwDeletedObject pdo = new PwDeletedObject(pe.Uuid, dtNow);
                    pd.DeletedObjects.Add(pdo);
                    touchedGroups.Add(pgParent);
                    Db.EntriesById.Remove(pe.Uuid);
                    Db.Elements.Remove(pe);
                }
                else                 // Recycle
                {
                    EnsureRecycleBinExists(ref pgRecycleBin, ref bUpdateGroupList);

                    pgRecycleBin.AddEntry(pe, true, true);
                    pe.Touch(false);

                    touchedGroups.Add(pgParent);
                    // Mark new parent dirty
                    touchedGroups.Add(pgRecycleBin);
                    // mark root dirty if recycle bin was created
                    touchedGroups.Add(Db.Root);
                }
            }
        }
コード例 #27
0
        /// <summary>
        /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
        /// </summary>
        /// <param name="pe">Password Entry.</param>
        private void TOTPCopyToClipboard(PwEntry pe)
        {
            if (SettingsCheck(pe) && SeedCheck(pe))
            {
                bool ValidInterval; bool ValidLength; bool ValidUrl;
                if (SettingsValidate(pe, out ValidInterval, out ValidLength, out ValidUrl))
                {
                    string[] Settings = SettingsGet(pe);

                    TOTPProvider TOTPGenerator = new TOTPProvider(Settings, ref this.TimeCorrections);

                    string InvalidCharacters;
                    if (SeedValidate(pe, out InvalidCharacters))
                    {
                        pe.Touch(false);

                        string totp = TOTPGenerator.Generate(SeedGet(pe).ReadString().ExtWithoutSpaces());

                        ClipboardUtil.CopyAndMinimize(totp, true, m_host.MainWindow, pe, m_host.MainWindow.ActiveDatabase);
                        m_host.MainWindow.StartClipboardCountdown();
                    }
                    else
                    {
                        MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadSeed + InvalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
                    }
                    if (TOTPGenerator.TimeCorrectionError)
                    {
                        MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadUrl);
                    }
                }
                else
                {
                    MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadSet);
                }
            }
            else
            {
                MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningNotSet);
            }
        }
コード例 #28
0
        /// <summary>
        /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
        /// </summary>
        /// <param name="pe">Password Entry.</param>
        internal void TOTPCopyToClipboard(PwEntry pe)
        {
            if (TOTPEntryValidator.HasSeed(pe))
            {
                if (TOTPEntryValidator.SettingsValidate(pe))
                {
                    string[] settings = TOTPEntryValidator.SettingsGet(pe);

                    TOTPProvider totpGenerator = new TOTPProvider(settings, this.TimeCorrections);

                    string invalidCharacters;
                    if (TOTPEntryValidator.SeedValidate(pe, out invalidCharacters))
                    {
                        pe.Touch(false);

                        string totp = totpGenerator.Generate(TOTPEntryValidator.SeedGet(pe).ReadString().ExtWithoutSpaces());

                        ClipboardUtil.CopyAndMinimize(totp, true, PluginHost.MainWindow, pe, PluginHost.MainWindow.ActiveDatabase);
                        PluginHost.MainWindow.StartClipboardCountdown();
                    }
                    else
                    {
                        MessageService.ShowWarning(Localization.Strings.ErrorBadSeed + invalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
                    }
                    if (totpGenerator.TimeCorrectionError)
                    {
                        MessageService.ShowWarning(Localization.Strings.WarningBadURL);
                    }
                }
                else
                {
                    MessageService.ShowWarning(Localization.Strings.ErrorBadSettings);
                }
            }
            else
            {
                MessageService.ShowWarning(Localization.Strings.ErrorNoSeed);
            }
        }
コード例 #29
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
                                                            SprContext ctx)
        {
            PwEntry    pe = ctx.Entry;
            PwDatabase pd = ctx.Database;

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

            string str = strText;

            const string strNewPwPlh = @"{NEWPASSWORD}";

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

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

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

            return(str);
        }
コード例 #30
0
        /// <summary>
        /// Displays the character selection form for the protected string referenced by the
        /// clicked <see cref="ProtectedStringMenuItem" />.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnEntryMenuItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem is ProtectedStringMenuItem)
            {
                ProtectedStringMenuItem item = (ProtectedStringMenuItem)e.ClickedItem;

                PwEntry entry = this.host.Database.RootGroup.FindEntry(item.EntryUuid, true);
                if (entry != null)
                {
                    if (entry.Strings.Exists(item.ProtectedStringKey))
                    {
                        ProtectedString procString = entry.Strings.Get(item.ProtectedStringKey);

                        // Display character selector form for the protected string
                        using (CharacterSelectorForm selectorForm = new CharacterSelectorForm(this.host, procString))
                        {
                            selectorForm.ShowDialog(this.host.MainWindow);
                        }

                        entry.Touch(false);
                    }
                }
            }
        }
コード例 #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);
        }
コード例 #32
0
ファイル: EntryUtil.cs プロジェクト: rdealexb/keepass
        /// <summary>
        /// Test whether an entry is a TAN entry and if so, expire it, provided
        /// that the option for expiring TANs on use is enabled.
        /// </summary>
        /// <param name="pe">Entry.</param>
        /// <returns>If the entry has been modified, the return value is
        /// <c>true</c>, otherwise <c>false</c>.</returns>
        public static bool ExpireTanEntryIfOption(PwEntry pe, PwDatabase pdContext)
        {
            if(pe == null) throw new ArgumentNullException("pe");
            // pdContext may be null
            if(!PwDefs.IsTanEntry(pe)) return false; // No assert

            if(Program.Config.Defaults.TanExpiresOnUse)
            {
                pe.ExpiryTime = DateTime.Now;
                pe.Expires = true;
                pe.Touch(true);
                if(pdContext != null) pdContext.Modified = true;
                return true;
            }

            return false;
        }
コード例 #33
0
        /// <summary>
        /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
        /// </summary>
        /// <param name="pe">Password Entry.</param>
        private void TOTPCopyToClipboard(PwEntry pe)
        {
            if (SettingsCheck(pe) && SeedCheck(pe))
            {
                bool ValidInterval; bool ValidLength; bool ValidUrl;
                if (SettingsValidate(pe, out ValidInterval, out ValidLength, out ValidUrl))
                {
                    string[] Settings = SettingsGet(pe);

                    TOTPProvider TOTPGenerator = new TOTPProvider(Settings, ref this.TimeCorrections);

                    string InvalidCharacters;
                    if (SeedValidate(pe, out InvalidCharacters))
                    {
                        pe.Touch(false);

                        string totp = TOTPGenerator.Generate(SeedGet(pe).ReadString().ExtWithoutSpaces());

                        ClipboardUtil.CopyAndMinimize(totp, true, m_host.MainWindow, pe, m_host.MainWindow.ActiveDatabase);
                        m_host.MainWindow.StartClipboardCountdown();
                    }
                    else
                    {
                        MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadSeed + InvalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
                    }
                    if (TOTPGenerator.TimeCorrectionError) MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadUrl);
                }
                else
                {
                    MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningBadSet);
                }
            }
            else
            {
                MessageService.ShowWarning(TrayTOTP_Plugin_Localization.strWarningNotSet);
            }
        }
コード例 #34
0
ファイル: EntryActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            long usageCount = prefs.GetLong(GetString(Resource.String.UsageCount_key), 0);

            ISharedPreferencesEditor edit = prefs.Edit();
            edit.PutLong(GetString(Resource.String.UsageCount_key), usageCount + 1);
            edit.Commit();

            _showPassword =
                !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

            base.OnCreate(savedInstanceState);
            RequestWindowFeature(WindowFeatures.IndeterminateProgress);

            new ActivityDesign(this).ApplyTheme();

            SetEntryView();

            Database db = App.Kp2a.GetDb();
            // Likely the app has been killed exit the activity
            if (!db.Loaded || (App.Kp2a.QuickLocked))
            {
                Finish();
                return;
            }

            SetResult(KeePass.ExitNormal);

            Intent i = Intent;
            PwUuid uuid = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyEntry)));
            _pos = i.GetIntExtra(KeyRefreshPos, -1);

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            Entry = db.Entries[uuid];
            Android.Util.Log.Debug("KP2A", "Notes: " + Entry.Strings.ReadSafe(PwDefs.NotesField));

            // Refresh Menu contents in case onCreateMenuOptions was called before Entry was set
            ActivityCompat.InvalidateOptionsMenu(this);

            // Update last access time.
            Entry.Touch(false);

            if (PwDefs.IsTanEntry(Entry) && prefs.GetBoolean(GetString(Resource.String.TanExpiresOnUse_key), Resources.GetBoolean(Resource.Boolean.TanExpiresOnUse_default)) && ((Entry.Expires == false) || Entry.ExpiryTime > DateTime.Now))
            {
                PwEntry backupEntry = Entry.CloneDeep();
                Entry.ExpiryTime = DateTime.Now;
                Entry.Expires = true;
                Entry.Touch(true);
                RequiresRefresh();
                UpdateEntry update = new UpdateEntry(this, App.Kp2a, backupEntry, Entry, null);
                ProgressTask pt = new ProgressTask(App.Kp2a, this, update);
                pt.Run();
            }
            FillData();

            SetupEditButtons();
            SetupMoveButtons ();

            App.Kp2a.GetDb().LastOpenedEntry = new PwEntryOutput(Entry, App.Kp2a.GetDb().KpDatabase);

            _pluginActionReceiver = new PluginActionReceiver(this);
            RegisterReceiver(_pluginActionReceiver, new IntentFilter(Strings.ActionAddEntryAction));
            _pluginFieldReceiver = new PluginFieldReceiver(this);
            RegisterReceiver(_pluginFieldReceiver, new IntentFilter(Strings.ActionSetEntryField));

            new Thread(NotifyPluginsOnOpen).Start();

            //the rest of the things to do depends on the current app task:
            _appTask.CompleteOnCreateEntryActivity(this);
        }
コード例 #35
0
ファイル: AutoType.cs プロジェクト: elitak/keepass
        private static bool Execute(string strSeq, PwEntry pweData)
        {
            Debug.Assert(strSeq != null); if(strSeq == null) return false;
            Debug.Assert(pweData != null); if(pweData == null) return false;

            if(!pweData.GetAutoTypeEnabled()) return false;
            if(!AppPolicy.Try(AppPolicyId.AutoType)) return false;

            if(KeePassLib.Native.NativeLib.IsUnix())
            {
                if(!NativeMethods.TryXDoTool())
                {
                    MessageService.ShowWarning(KPRes.AutoTypeXDoToolRequired,
                        KPRes.PackageInstallHint);
                    return false;
                }
            }

            PwDatabase pwDatabase = null;
            try { pwDatabase = Program.MainForm.PluginHost.Database; }
            catch(Exception) { }

            bool bObfuscate = (pweData.AutoType.ObfuscationOptions !=
                AutoTypeObfuscationOptions.None);
            AutoTypeEventArgs args = new AutoTypeEventArgs(strSeq, bObfuscate, pweData);

            if(AutoType.FilterCompilePre != null) AutoType.FilterCompilePre(null, args);

            args.Sequence = SprEngine.Compile(args.Sequence, true, pweData,
                pwDatabase, true, false);

            string strError = ValidateAutoTypeSequence(args.Sequence);
            if(strError != null)
            {
                MessageService.ShowWarning(strError);
                return false;
            }

            Application.DoEvents();

            if(AutoType.FilterSendPre != null) AutoType.FilterSendPre(null, args);
            if(AutoType.FilterSend != null) AutoType.FilterSend(null, args);

            if(args.Sequence.Length > 0)
            {
                try { SendInputEx.SendKeysWait(args.Sequence, args.SendObfuscated); }
                catch(Exception excpAT)
                {
                    MessageService.ShowWarning(excpAT);
                }
            }

            pweData.Touch(false);
            if(EntryUtil.ExpireTanEntryIfOption(pweData))
                Program.MainForm.RefreshEntriesList();

            // SprEngine.Compile might have modified the database;
            // pd.Modified is set by SprEngine
            Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

            return true;
        }
コード例 #36
0
 /// <summary>
 /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
 /// </summary>
 /// <param name="pe">Password Entry.</param>
 private void TotpCopyToClipboard(PwEntry pe)
 {
     if (SettingsCheck(pe) && SeedCheck(pe))
     {
         bool ValidInterval; bool ValidLength; bool ValidUrl;
         if (SettingsValidate(pe, out ValidInterval, out ValidLength, out ValidUrl))
         {
             bool NoTimeCorrection = false;
             string[] Settings = SettingsGet(pe);
             var TotpGenerator = new Totp_Provider(Convert.ToInt16(Settings[0]), Convert.ToInt16(Settings[1]));
             if (ValidUrl)
             {
                 var CurrentTimeCorrection = TimeCorrections[Settings[2]];
                 if (CurrentTimeCorrection != null)
                 {
                     TotpGenerator.TimeCorrection = CurrentTimeCorrection.TimeCorrection;
                 }
                 else
                 {
                     TotpGenerator.TimeCorrection = TimeSpan.Zero;
                     NoTimeCorrection = true;
                 }
             }
             string InvalidCharacters;
             if (SeedValidate(pe, out InvalidCharacters))
             {
                 pe.Touch(false);
                 ClipboardUtil.CopyAndMinimize(TotpGenerator.Generate(Base32.Decode(SeedGet(pe).ReadString().ExtWithoutSpaces())), true, m_host.MainWindow, pe, m_host.MainWindow.ActiveDatabase);
                 m_host.MainWindow.StartClipboardCountdown();
             }
             else
             {
                 MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadSeed + InvalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
             }
             if (NoTimeCorrection) MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadUrl);
         }
         else
         {
             MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningBadSet);
         }
     }
     else
     {
         MessageService.ShowWarning(TrayTotp_Plugin_Localization.strWarningNotSet);
     }
 }
コード例 #37
0
        public void RenamePwdProxyNodesTest()
        {
            m_treeManager.Initialize(m_database);
            PwEntry pwd1 = new PwEntry( true, true );
            pwd1.Strings.Set(KeeShare.KeeShare.TitleField, new ProtectedString( false, "pwd1" ) );
            m_database.RootGroup.AddEntry( pwd1, true );
            pwd1.Touch( true );

            DateTime lastTouch = pwd1.LastModificationTime;

            PwEntry pwdProxy = PwNode.CreateProxyNode( pwd1 );
            m_database.GetGroupsGroup().AddEntry( pwdProxy, true );

            pwdProxy.LastModificationTime = lastTouch.AddTicks( 10 );

            m_treeManager.CorrectStructure( );

            Assert.AreEqual( 2, NumberOfEntriesIn( m_database ) );
            string pwdId = m_database.RootGroup.Entries.GetAt( 0 ).Uuid.ToHexString();
            pwdProxy = m_database.GetGroupsGroup().Entries.GetAt(0);
            Assert.AreEqual( pwdId, pwdProxy.Strings.ReadSafe(KeeShare.KeeShare.UuidLinkField));

            pwdProxy.Strings.Set(KeeShare.KeeShare.TitleField, new ProtectedString( false, "new Title" ) );
            pwdProxy.LastModificationTime = lastTouch.AddTicks( 23 );

            m_treeManager.CorrectStructure(  );
            Assert.AreEqual( "new Title", m_database.RootGroup.Entries.GetAt( 0 ).Strings.ReadSafe(KeeShare.KeeShare.TitleField) );
        }
コード例 #38
0
ファイル: Handlers.cs プロジェクト: nelsonst47/keepasshttp
 private void SetEntryConfig(PwEntry e, KeePassHttpEntryConfig c)
 {
     var serializer = NewJsonSerializer();
     var writer = new StringWriter();
     serializer.Serialize(writer, c);
     e.Strings.Set(KEEPASSHTTP_NAME, new ProtectedString(false, writer.ToString()));
     e.Touch(true);
     UpdateUI(e.ParentGroup);
 }
        /// <summary>
        /// Downloads one favicon and attaches it to the entry
        /// </summary>
        /// <param name="pwe">The entry for which we want to download the favicon</param>
        private void downloadOneFavicon(PwEntry pwe, ref string message)
        {
            // TODO: create async jobs instead?

            string url = pwe.Strings.ReadSafe("URL");

            // If we have no URL, quit
            if (string.IsNullOrEmpty(url))
                return;

            // If we have a URL with specific scheme that is not http or https, quit
            if (!url.StartsWith("http://") && !url.StartsWith("https://")
                && url.Contains("://"))
                return;

            int dotIndex = url.IndexOf(".");
            if (dotIndex >= 0)
            {
                string protocol = "http";
                string fullURL = url;

                // trim any path data
                int slashDotIndex = url.IndexOf("/", dotIndex);
                if (slashDotIndex >= 0)
                    url = url.Substring(0, slashDotIndex);

                // If there is a protocol/scheme prepended to the URL, strip it off.
                int protocolEndIndex = url.LastIndexOf("/");
                if (protocolEndIndex >= 0)
                {
                    protocol = url.Substring(0,protocolEndIndex-2);
                    url = url.Substring(protocolEndIndex + 1);
                }

                MemoryStream ms = null;
                bool success = getFromFaviconExplicitLocation(url, protocol, fullURL, ref ms, ref message);

                if (!success)
                    success = getFromFaviconStandardLocation(url, protocol, ref ms, ref message);

                if (!success)
                    return;

                // If we found an icon then we don't care whether one particular download method failed.
                message = "";

                byte[] msByteArray = ms.ToArray();

                foreach (PwCustomIcon item in m_host.Database.CustomIcons)
                {
                    // re-use existing custom icon if it's already in the database
                    // (This will probably fail if database is used on
                    // both 32 bit and 64 bit machines - not sure why...)
                    if (KeePassLib.Utility.MemUtil.ArraysEqual(msByteArray, item.ImageDataPng))
                    {
                        pwe.CustomIconUuid = item.Uuid;
                        pwe.Touch(true);
                        m_host.Database.UINeedsIconUpdate = true;
                        return;
                    }
                }

                // Create a new custom icon for use with this entry
                PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true),
                    ms.ToArray());
                m_host.Database.CustomIcons.Add(pwci);
                pwe.CustomIconUuid = pwci.Uuid;
                pwe.Touch(true);
                m_host.Database.UINeedsIconUpdate = true;
            }
        }
コード例 #40
0
        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);
        }
コード例 #41
0
 public static void SimulateTouch(PwEntry entry)
 {
     DelayAction();
     entry.Touch(true, false);
     //entry.LastModificationTime = entry.LastModificationTime.AddMilliseconds(23);
 }
コード例 #42
0
ファイル: KeePassRPCService.cs プロジェクト: kkchia/KeeFox
        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);
        }
コード例 #43
0
ファイル: EntryUtil.cs プロジェクト: ComradeP/KeePass-2.x
		public static void ExpireTanEntry(PwEntry pe)
		{
			if(pe == null) throw new ArgumentNullException("pe");
			Debug.Assert(PwDefs.IsTanEntry(pe));

			if(Program.Config.Defaults.TanExpiresOnUse)
			{
				pe.ExpiryTime = DateTime.Now;
				pe.Expires = true;
				pe.Touch(true);
			}
		}
コード例 #44
0
        /// <summary>
        /// Downloads one favicon and attaches it to the entry
        /// </summary>
        /// <param name="pwe">The entry for which we want to download the favicon</param>
        private void downloadOneFavicon(PwEntry pwe, ref string message)
        {
            // TODO: create async jobs instead?

            string url = pwe.Strings.ReadSafe("URL");

            if (string.IsNullOrEmpty(url))
                url = pwe.Strings.ReadSafe("Title");

            // If we still have no URL, quit
            if (string.IsNullOrEmpty(url))
                return;

            // If we have a URL with specific scheme that is not http or https, quit
            if (!url.StartsWith("http://") && !url.StartsWith("https://")
                && url.Contains("://"))
                return;

            int dotIndex = url.IndexOf(".");
            if (dotIndex >= 0)
            {
                Uri fullURI = null;
                try {
                    fullURI = new Uri((url.StartsWith("http://")||url.StartsWith("https://"))?url:"http://"+url,UriKind.Absolute);
                }
                catch (Exception ex)
                {
                    message += url + "\n" + ex.Message;
                    return;
                }

                MemoryStream ms = null;
                Uri lastURI = getFromFaviconExplicitLocation(fullURI, ref ms, ref message);
                bool success = (lastURI != null) && lastURI.OriginalString.Equals("http://success");

                if (!success)
                {
                    success = getFavicon(new Uri((lastURI==null)?fullURI:lastURI,"/favicon.ico"), ref ms, ref message);
                }

                if (!success)
                    return;

                // If we found an icon then we don't care whether one particular download method failed.
                message = "";

                byte[] msByteArray = ms.ToArray();

                foreach (PwCustomIcon item in m_host.Database.CustomIcons)
                {
                    // re-use existing custom icon if it's already in the database
                    // (This will probably fail if database is used on
                    // both 32 bit and 64 bit machines - not sure why...)
                    if (KeePassLib.Utility.MemUtil.ArraysEqual(msByteArray, item.ImageDataPng))
                    {
                        pwe.CustomIconUuid = item.Uuid;
                        pwe.Touch(true);
                        m_host.Database.UINeedsIconUpdate = true;
                        return;
                    }
                }

                // Create a new custom icon for use with this entry
                PwCustomIcon pwci = new PwCustomIcon(new PwUuid(true),
                    ms.ToArray());
                m_host.Database.CustomIcons.Add(pwci);
                pwe.CustomIconUuid = pwci.Uuid;
                pwe.Touch(true);
                m_host.Database.UINeedsIconUpdate = true;
            }
        }
コード例 #45
0
ファイル: PwEntryForm.cs プロジェクト: rdealexb/keepass
        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;
        }
コード例 #46
0
ファイル: ClipboardUtil.cs プロジェクト: saadware/kpn
        public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner)
        {
            if(strToCopy == null) throw new ArgumentNullException("strToCopy");

            if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
                return false;

            string strData = (bSprCompile ? SprEngine.Compile(strToCopy,
                new SprContext(peEntryInfo, pwReferenceSource,
                SprCompileFlags.All)) : strToCopy);

            try
            {
                if(!KeeNativeLib.NativeLib.IsUnix()) // Windows
                {
                    if(!OpenW(hOwner, true))
                        throw new InvalidOperationException();

                    bool bFailed = false;
                    if(!AttachIgnoreFormatW()) bFailed = true;
                    if(!SetDataW(null, strData, null)) bFailed = true;
                    CloseW();

                    if(bFailed) return false;
                }
                else if(KeeNativeLib.NativeLib.GetPlatformID() == PlatformID.MacOSX)
                    SetStringM(strData);
                else if(KeeNativeLib.NativeLib.IsUnix())
                    SetStringU(strData);
                // else // Managed
                // {
                //	Clear();
                //	DataObject doData = CreateProtectedDataObject(strData);
                //	Clipboard.SetDataObject(doData);
                // }
            }
            catch(Exception) { Debug.Assert(false); return false; }

            m_strFormat = null;

            byte[] pbUtf8 = StrUtil.Utf8.GetBytes(strData);
            SHA256Managed sha256 = new SHA256Managed();
            m_pbDataHash32 = sha256.ComputeHash(pbUtf8);

            RaiseCopyEvent(bIsEntryInfo, strData);

            if(peEntryInfo != null) peEntryInfo.Touch(false);

            // SprEngine.Compile might have modified the database
            Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

            return true;
        }