public static bool PerformGlobal(List<PwDatabase> vSources, ImageList ilIcons) { Debug.Assert(vSources != null); if(vSources == null) return false; IntPtr hWnd; string strWindow; try { hWnd = NativeMethods.GetForegroundWindow(); strWindow = NativeMethods.GetWindowText(hWnd); } catch(Exception) { Debug.Assert(false); hWnd = IntPtr.Zero; strWindow = null; } if((strWindow == null) || (strWindow.Length == 0)) return false; PwObjectList<PwEntry> m_vList = new PwObjectList<PwEntry>(); DateTime dtNow = DateTime.Now; EntryHandler eh = delegate(PwEntry pe) { // Ignore expired entries if(pe.Expires && (pe.ExpiryTime < dtNow)) return true; if(GetSequenceForWindow(pe, strWindow, true) != null) m_vList.Add(pe); return true; }; foreach(PwDatabase pwSource in vSources) { if(pwSource.IsOpen == false) continue; pwSource.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh); } if(m_vList.UCount == 1) AutoType.PerformInternal(m_vList.GetAt(0), strWindow); else if(m_vList.UCount > 1) { EntryListForm elf = new EntryListForm(); elf.InitEx(KPRes.AutoTypeEntrySelection, KPRes.AutoTypeEntrySelectionDescShort, KPRes.AutoTypeEntrySelectionDescLong, Properties.Resources.B48x48_KGPG_Key2, ilIcons, m_vList); elf.EnsureForeground = true; if(elf.ShowDialog() == DialogResult.OK) { try { NativeMethods.EnsureForegroundWindow(hWnd); } catch(Exception) { Debug.Assert(false); } if(elf.SelectedEntry != null) AutoType.PerformInternal(elf.SelectedEntry, strWindow); } } return true; }
private IEnumerable<PwEntry> FindMatchingEntries(Request r, Aes aes) { string submithost = null; string realm = null; var list = new PwObjectList<PwEntry>(); string formhost, searchHost; formhost = searchHost = GetHost(CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT)); if (r.SubmitUrl != null) { submithost = GetHost(CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT)); } if (r.Realm != null) realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT); var origSearchHost = searchHost; var parms = MakeSearchParameters(); var root = host.Database.RootGroup; while (list.UCount == 0 && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1)) { parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost); root.SearchEntries(parms, list); searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); if (searchHost == origSearchHost) break; } Func<PwEntry, bool> filter = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = GetEntryConfig(e); if (c != null) { if (c.Allow.Contains(formhost) && (submithost == null || c.Allow.Contains(submithost))) return true; if (c.Deny.Contains(formhost) || (submithost != null && c.Deny.Contains(submithost))) return false; if (realm != null && c.Realm != realm) return false; } if (title.StartsWith("http://") || title.StartsWith("https://")) { var u = new Uri(title); if (formhost.Contains(u.Host)) return true; } if (entryUrl != null && entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://")) { var u = new Uri(entryUrl); if (formhost.Contains(u.Host)) return true; } return formhost.Contains(title) || (entryUrl != null && formhost.Contains(entryUrl)); }; return from e in list where filter(e) select e; }
public void InitEx(string strTitle, string strDescShort, string strDescLong, Image imgIcon, ImageList ilIcons, PwObjectList<PwEntry> vEntries) { m_strTitle = strTitle; m_strDescShort = strDescShort; m_strDescLong = strDescLong; m_imgIcon = imgIcon; m_ilIcons = UIUtil.CloneImageList(ilIcons, true); m_vEntries = vEntries; }
private IEnumerable <PwEntryDatabase> FindMatchingEntries(string url, string realm) { var listResult = new List <PwEntryDatabase>(); var hostUri = new Uri(url); var formHost = hostUri.Host; var searchHost = hostUri.Host; var origSearchHost = hostUri.Host; var parms = MakeSearchParameters(); List <PwDatabase> listDatabases = new List <PwDatabase>(); var configOpt = new ConfigOpt(_host.CustomConfig); if (configOpt.SearchInAllOpenedDatabases) { foreach (PwDocument doc in _host.MainWindow.DocumentManager.Documents) { if (doc.Database.IsOpen) { listDatabases.Add(doc.Database); } } } else { listDatabases.Add(_host.Database); } int listCount = 0; foreach (PwDatabase db in listDatabases) { searchHost = origSearchHost; //get all possible entries for given host-name while (listResult.Count == listCount && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1)) { parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost); var listEntries = new PwObjectList <PwEntry>(); db.RootGroup.SearchEntries(parms, listEntries); foreach (var le in listEntries) { listResult.Add(new PwEntryDatabase(le, db)); } searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); //searchHost contains no dot --> prevent possible infinite loop if (searchHost == origSearchHost) { break; } } listCount = listResult.Count; } var searchUrls = configOpt.SearchUrls; bool filter(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = _ext.GetEntryConfig(e); if (c != null) { if (c.Allow.Contains(formHost)) { return(true); } if (c.Deny.Contains(formHost)) { return(false); } if (!string.IsNullOrEmpty(realm) && c.Realm != realm) { return(false); } } if (IsValidUrl(entryUrl, formHost)) { return(true); } if (IsValidUrl(title, formHost)) { return(true); } if (searchUrls) { foreach (var sf in e.Strings.Where(s => s.Key.StartsWith("URL", StringComparison.InvariantCultureIgnoreCase))) { var sfv = e.Strings.ReadSafe(sf.Key); if (sf.Key.IndexOf("regex", StringComparison.OrdinalIgnoreCase) >= 0 && System.Text.RegularExpressions.Regex.IsMatch(formHost, sfv)) { return(true); } if (IsValidUrl(sfv, formHost)) { return(true); } } } return(formHost.Contains(title) || (!string.IsNullOrEmpty(entryUrl) && formHost.Contains(entryUrl))); } bool filterSchemes(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); if (entryUrl != null && Uri.TryCreate(entryUrl, UriKind.Absolute, out var entryUri) && entryUri.Scheme == hostUri.Scheme) { return(true); } if (Uri.TryCreate(title, UriKind.Absolute, out var titleUri) && titleUri.Scheme == hostUri.Scheme) { return(true); } return(false); } var result = listResult.Where(e => filter(e.entry)); if (configOpt.MatchSchemes) { result = result.Where(e => filterSchemes(e.entry)); } if (configOpt.HideExpired) { result = result.Where(x => !(x.entry.Expires && x.entry.ExpiryTime <= DateTime.UtcNow)); } return(result); }
public static PwEntry FindRefTarget(string strFullRef, SprContext ctx, out char chScan, out char chWanted) { chScan = char.MinValue; chWanted = char.MinValue; if (strFullRef == null) { Debug.Assert(false); return(null); } if (!strFullRef.StartsWith(StrRefStart, SprEngine.ScMethod) || !strFullRef.EndsWith(StrRefEnd, SprEngine.ScMethod)) { return(null); } if ((ctx == null) || (ctx.Database == null)) { Debug.Assert(false); return(null); } string strRef = strFullRef.Substring(StrRefStart.Length, strFullRef.Length - StrRefStart.Length - StrRefEnd.Length); if (strRef.Length <= 4) { return(null); } if (strRef[1] != '@') { return(null); } if (strRef[3] != ':') { return(null); } chScan = char.ToUpper(strRef[2]); chWanted = char.ToUpper(strRef[0]); SearchParameters sp = SearchParameters.None; sp.SearchString = strRef.Substring(4); sp.RespectEntrySearchingDisabled = false; if (chScan == 'T') { sp.SearchInTitles = true; } else if (chScan == 'U') { sp.SearchInUserNames = true; } else if (chScan == 'A') { sp.SearchInUrls = true; } else if (chScan == 'P') { sp.SearchInPasswords = true; } else if (chScan == 'N') { sp.SearchInNotes = true; } else if (chScan == 'I') { sp.SearchInUuids = true; } else if (chScan == 'O') { sp.SearchInOther = true; } else { return(null); } PwObjectList <PwEntry> lFound = new PwObjectList <PwEntry>(); ctx.Database.RootGroup.SearchEntries(sp, lFound); return((lFound.UCount > 0) ? lFound.GetAt(0) : null); }
internal void ShowEntriesByTag(string strTag) { if(strTag == null) { Debug.Assert(false); return; } if(strTag.Length == 0) return; // No assert PwDatabase pd = m_docMgr.ActiveDatabase; if((pd == null) || !pd.IsOpen) return; // No assert (call from trigger) PwObjectList<PwEntry> vEntries = new PwObjectList<PwEntry>(); pd.RootGroup.FindEntriesByTag(strTag, vEntries, true); PwGroup pgResults = new PwGroup(true, true); pgResults.IsVirtual = true; foreach(PwEntry pe in vEntries) pgResults.AddEntry(pe, false); UpdateUI(false, null, false, null, true, pgResults, false); }
public static bool EntriesHaveSameParent(PwObjectList<PwEntry> v) { if(v == null) { Debug.Assert(false); return true; } if(v.UCount == 0) return true; PwGroup pg = v.GetAt(0).ParentGroup; foreach(PwEntry pe in v) { if(pe.ParentGroup != pg) return false; } return true; }
private void OnEntryDuplicate(object sender, EventArgs e) { PwDatabase pd = m_docMgr.ActiveDatabase; PwGroup pgSelected = GetSelectedGroup(); PwEntry[] vSelected = GetSelectedEntries(); if((vSelected == null) || (vSelected.Length == 0)) return; DuplicationForm dlg = new DuplicationForm(); if(UIUtil.ShowDialogAndDestroy(dlg) != DialogResult.OK) return; PwObjectList<PwEntry> vNewEntries = new PwObjectList<PwEntry>(); foreach(PwEntry pe in vSelected) { PwEntry peNew = pe.CloneDeep(); peNew.SetUuid(new PwUuid(true), true); // Create new UUID dlg.ApplyTo(peNew, pe, pd); Debug.Assert(pe.ParentGroup == peNew.ParentGroup); PwGroup pg = (pe.ParentGroup ?? pgSelected); if((pg == null) && (pd != null)) pg = pd.RootGroup; if(pg == null) continue; pg.AddEntry(peNew, true, true); vNewEntries.Add(peNew); } AddEntriesToList(vNewEntries); SelectEntries(vNewEntries, true, true); // if(!m_lvEntries.ShowGroups && (m_lvEntries.Items.Count >= 1)) // m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1); // else EnsureVisibleSelected(true); EnsureVisibleSelected(true); // Show all copies if possible EnsureVisibleSelected(false); // Ensure showing the first UpdateUIState(true, m_lvEntries); }
private void OnEntryDuplicate(object sender, EventArgs e) { PwDatabase pd = m_docMgr.ActiveDatabase; PwGroup pgSelected = GetSelectedGroup(); PwEntry[] vSelected = GetSelectedEntries(); if((vSelected == null) || (vSelected.Length == 0)) return; DuplicationForm dlg = new DuplicationForm(); if(UIUtil.ShowDialogAndDestroy(dlg) != DialogResult.OK) return; PwObjectList<PwEntry> vNewEntries = new PwObjectList<PwEntry>(); foreach(PwEntry pe in vSelected) { PwEntry peNew = pe.CloneDeep(); peNew.SetUuid(new PwUuid(true), true); // Create new UUID if(dlg.AppendCopyToTitles && (pd != null)) { string strTitle = peNew.Strings.ReadSafe(PwDefs.TitleField); peNew.Strings.Set(PwDefs.TitleField, new ProtectedString( pd.MemoryProtection.ProtectTitle, strTitle + " - " + KPRes.CopyOfItem)); } if(dlg.ReplaceDataByFieldRefs && (pd != null)) { string strUser = @"{REF:U@I:" + pe.Uuid.ToHexString() + @"}"; peNew.Strings.Set(PwDefs.UserNameField, new ProtectedString( pd.MemoryProtection.ProtectUserName, strUser)); string strPw = @"{REF:P@I:" + pe.Uuid.ToHexString() + @"}"; peNew.Strings.Set(PwDefs.PasswordField, new ProtectedString( pd.MemoryProtection.ProtectPassword, strPw)); } Debug.Assert(pe.ParentGroup == peNew.ParentGroup); PwGroup pg = (pe.ParentGroup ?? pgSelected); if((pg == null) && (pd != null)) pg = pd.RootGroup; if(pg == null) continue; pg.AddEntry(peNew, true, true); vNewEntries.Add(peNew); } AddEntriesToList(vNewEntries); SelectEntries(vNewEntries, true, false); if(!m_lvEntries.ShowGroups && (m_lvEntries.Items.Count >= 1)) m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1); else EnsureVisibleSelected(true); UpdateUIState(true, m_lvEntries); }
private void removePermissionsButton_Click(object sender, EventArgs e) { if (KeePass.Program.MainForm.DocumentManager.ActiveDatabase.IsOpen) { PwDatabase db = KeePass.Program.MainForm.DocumentManager.ActiveDatabase; uint counter = 0; var entries = db.RootGroup.GetEntries(true); if (entries.Count() > 999) { MessageBox.Show( String.Format("{0} entries detected!\nSearching and removing permissions could take some while.\n\nWe will inform you when the process has been finished.", entries.Count().ToString()), String.Format("{0} entries detected", entries.Count().ToString()), MessageBoxButtons.OK, MessageBoxIcon.Information ); } foreach (var entry in entries) { foreach (var str in entry.Strings) { if (str.Key == KeePassHttpExt.KEEPASSHTTP_NAME) { PwObjectList <PwEntry> m_vHistory = entry.History.CloneDeep(); entry.History = m_vHistory; entry.CreateBackup(null); entry.Strings.Remove(str.Key); entry.Touch(true); counter += 1; break; } } } if (counter > 0) { KeePass.Program.MainForm.UpdateUI(false, null, true, db.RootGroup, true, null, true); MessageBox.Show( String.Format("Successfully removed permissions from {0} entr{1}.", counter.ToString(), counter == 1 ? "y" : "ies"), String.Format("Removed permissions from {0} entr{1}", counter.ToString(), counter == 1 ? "y" : "ies"), MessageBoxButtons.OK, MessageBoxIcon.Information ); } else { MessageBox.Show( "The active database does not contain an entry with permissions.", "No entry with permissions found!", MessageBoxButtons.OK, MessageBoxIcon.Information ); } } else { MessageBox.Show("The active database is locked!\nPlease unlock the selected database or choose another one which is unlocked.", "Database locked!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static string FillRefPlaceholders(string strSeq, PwDatabase pwDatabase, SprContentFlags cf, uint uRecursionLevel, SprRefsCache vRefsCache) { if (pwDatabase == null) { return(strSeq); } string str = strSeq; const string strStart = @"{REF:"; const string strEnd = @"}"; int nOffset = 0; for (int iLoop = 0; iLoop < 20; ++iLoop) { str = SprEngine.FillRefsUsingCache(str, vRefsCache); int nStart = str.IndexOf(strStart, nOffset, SprEngine.ScMethod); if (nStart < 0) { break; } int nEnd = str.IndexOf(strEnd, nStart, SprEngine.ScMethod); if (nEnd < 0) { break; } string strFullRef = str.Substring(nStart, nEnd - nStart + 1); string strRef = str.Substring(nStart + strStart.Length, nEnd - nStart - strStart.Length); if (strRef.Length <= 4) { nOffset = nStart + 1; continue; } if (strRef[1] != '@') { nOffset = nStart + 1; continue; } if (strRef[3] != ':') { nOffset = nStart + 1; continue; } char chScan = char.ToUpper(strRef[2]); char chWanted = char.ToUpper(strRef[0]); SearchParameters sp = SearchParameters.None; sp.SearchString = strRef.Substring(4); if (chScan == 'T') { sp.SearchInTitles = true; } else if (chScan == 'U') { sp.SearchInUserNames = true; } else if (chScan == 'A') { sp.SearchInUrls = true; } else if (chScan == 'P') { sp.SearchInPasswords = true; } else if (chScan == 'N') { sp.SearchInNotes = true; } else if (chScan == 'I') { sp.SearchInUuids = true; } else if (chScan == 'O') { sp.SearchInOther = true; } else { nOffset = nStart + 1; continue; } PwObjectList <PwEntry> lFound = new PwObjectList <PwEntry>(); pwDatabase.RootGroup.SearchEntries(sp, lFound, true); if (lFound.UCount > 0) { PwEntry peFound = lFound.GetAt(0); string strInsData; if (chWanted == 'T') { strInsData = peFound.Strings.ReadSafe(PwDefs.TitleField); } else if (chWanted == 'U') { strInsData = peFound.Strings.ReadSafe(PwDefs.UserNameField); } else if (chWanted == 'A') { strInsData = peFound.Strings.ReadSafe(PwDefs.UrlField); } else if (chWanted == 'P') { strInsData = peFound.Strings.ReadSafe(PwDefs.PasswordField); } else if (chWanted == 'N') { strInsData = peFound.Strings.ReadSafe(PwDefs.NotesField); } else if (chWanted == 'I') { strInsData = peFound.Uuid.ToHexString(); } else { nOffset = nStart + 1; continue; } string strInnerContent = SprEngine.CompileInternal(strInsData, peFound, pwDatabase, null, uRecursionLevel + 1, vRefsCache); strInnerContent = SprEngine.TransformContent(strInnerContent, cf); // str = str.Substring(0, nStart) + strInnerContent + str.Substring(nEnd + 1); SprEngine.AddRefToCache(strFullRef, strInnerContent, vRefsCache); str = SprEngine.FillRefsUsingCache(str, vRefsCache); } else { nOffset = nStart + 1; continue; } } return(str); }
/// <summary> /// Search this group and all groups in the current one for entries. /// </summary> /// <param name="searchParams">Specifies the search method.</param> /// <param name="listStorage">Entry list in which the search results will /// be stored.</param> public void SearchEntries(SearchParameters searchParams, PwObjectList <PwEntry> listStorage) { Debug.Assert(searchParams != null); if (searchParams == null) { throw new ArgumentNullException("searchParams"); } Debug.Assert(listStorage != null); if (listStorage == null) { throw new ArgumentNullException("listStorage"); } string strSearch = searchParams.SearchString; Debug.Assert(strSearch != null); if (strSearch == null) { throw new ArgumentException(); } StringComparison scType = searchParams.ComparisonMode; Regex rx = null; EntryHandler eh = null; bool bTitle = searchParams.SearchInTitles; bool bUserName = searchParams.SearchInUserNames; bool bPassword = searchParams.SearchInPasswords; bool bUrl = searchParams.SearchInUrls; bool bNotes = searchParams.SearchInNotes; bool bOther = searchParams.SearchInOther; bool bUuids = searchParams.SearchInUuids; bool bExcludeExpired = searchParams.ExcludeExpired; DateTime dtNow = DateTime.Now; if (searchParams.RegularExpression) { RegexOptions ro = RegexOptions.Compiled; if ((scType == StringComparison.CurrentCultureIgnoreCase) || (scType == StringComparison.InvariantCultureIgnoreCase) || (scType == StringComparison.OrdinalIgnoreCase)) { ro |= RegexOptions.IgnoreCase; } rx = new Regex(strSearch, ro); } if (strSearch.Length <= 0) // Report all { eh = delegate(PwEntry pe) { if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) { return(true); // Skip } listStorage.Add(pe); return(true); }; } else { eh = delegate(PwEntry pe) { if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) { return(true); // Skip } uint uInitialResults = listStorage.UCount; foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings) { string strKey = kvp.Key; if (strKey == PwDefs.TitleField) { SearchEvalAdd(bTitle, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } else if (strKey == PwDefs.UserNameField) { SearchEvalAdd(bUserName, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } else if (strKey == PwDefs.PasswordField) { SearchEvalAdd(bPassword, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } else if (strKey == PwDefs.UrlField) { SearchEvalAdd(bUrl, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } else if (strKey == PwDefs.NotesField) { SearchEvalAdd(bNotes, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } else if (bOther) { SearchEvalAdd(true, strSearch, kvp.Value.ReadString(), scType, rx, pe, listStorage); } // An entry can match only once => break if we have added it if (listStorage.UCount > uInitialResults) { break; } } if ((listStorage.UCount == uInitialResults) && bUuids) { SearchEvalAdd(true, strSearch, pe.Uuid.ToHexString(), scType, rx, pe, listStorage); } return(true); }; } PreOrderTraverseTree(null, eh); }
private static void SearchEvalAdd(bool bIf, string strSearch, string strDataField, StringComparison scType, Regex rx, PwEntry pe, PwObjectList <PwEntry> lResults) { if (bIf == false) { return; } if (rx == null) { if (strDataField.IndexOf(strSearch, scType) >= 0) { lResults.Add(pe); } } else // Regular expression { if (rx.IsMatch(strDataField)) { lResults.Add(pe); } } }
private Changes FixHomeFolders() { //==================================== //maybe we have some emptyFolders => new homefolders! //we can use the same loop to test for illegal shares of //foreign homes. that means, a foreign proxy is located //in a users homefolder. PwGroup usersGroup = m_database.GetUsersGroup(); PwObjectList <PwGroup> allHomes = usersGroup.GetGroups(false); PwObjectList <PwGroup> foreignHomes = new PwObjectList <PwGroup>(); PwObjectList <PwGroup> emptyHomes = new PwObjectList <PwGroup>(); foreach (PwGroup home in allHomes) { //we remember the empty folders, so we can later make them new users if (home.Entries.UCount == 0) { emptyHomes.Add(home); } //if we have more than 1 entry in a homegroup we have to check for //possible foreign shares if (home.Entries.UCount > 1) { List <PwEntry> entries = home.GetEntries(false).CloneShallowToList(); foreach (PwEntry entry in entries) { //is it a userPorxy or a pwdProxy? //the first we have to remove but the second one //is a note that we want to share a pwd with this user, //so we don't touch it! if (m_database.IsUserProxy(entry)) { entry.DeleteFrom(home, m_database); } } } //and maybe we have a foreign home in our homefolder (to share it..) //so we have to fix that too. foreach (PwGroup foreignHome in home.GetGroups(true)) { if (foreignHome.IsHome()) { foreignHomes.Add(foreignHome); } } } Changes changeFlag = Changes.None; foreach (PwGroup home in emptyHomes) { string userName = home.Name; try { changeFlag |= CreateNewUser(userName, home); } catch (Exception) { // WTF: Why? //should throw the exception and later inform the user... } } foreach (PwGroup home in foreignHomes) { home.MoveToParent(m_database.GetUsersGroup()); changeFlag |= Changes.GroupMoved; } return(changeFlag); }
private IEnumerable <PwEntry> FindMatchingEntries(Request r, Aes aes) { string submithost = null; string realm = null; var list = new PwObjectList <PwEntry>(); string formhost, searchHost; formhost = searchHost = GetHost(CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT)); if (r.SubmitUrl != null) { submithost = GetHost(CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT)); } if (r.Realm != null) { realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT); } var origSearchHost = searchHost; var parms = MakeSearchParameters(); var root = host.Database.RootGroup; while (list.UCount == 0 && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1)) { parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost); root.SearchEntries(parms, list); searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); if (searchHost == origSearchHost) { break; } } Func <PwEntry, bool> filter = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = GetEntryConfig(e); if (c != null) { if (c.Allow.Contains(formhost) && (submithost == null || c.Allow.Contains(submithost))) { return(true); } if (c.Deny.Contains(formhost) || (submithost != null && c.Deny.Contains(submithost))) { return(false); } if (realm != null && c.Realm != realm) { return(false); } } if (title.StartsWith("http://") || title.StartsWith("https://")) { var u = new Uri(title); if (formhost.Contains(u.Host)) { return(true); } } if (entryUrl != null && entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://")) { var u = new Uri(entryUrl); if (formhost.Contains(u.Host)) { return(true); } } return(formhost.Contains(title) || (entryUrl != null && formhost.Contains(entryUrl))); }; return(from e in list where filter(e) select e); }
private static void CopyEntriesAndGroups(PwDatabase sourceDb, Settings settings, PwObjectList <PwEntry> entries, PwDatabase targetDatabase) { foreach (PwEntry entry in entries) { // Get or create the target group in the target database (including hierarchy) PwGroup targetGroup = settings.FlatExport ? targetDatabase.RootGroup : CreateTargetGroupInDatebase(entry, targetDatabase, sourceDb); PwEntry peNew = null; if (!settings.OverrideTargetDatabase) { peNew = targetGroup.FindEntry(entry.Uuid, bSearchRecursive: false); // Check if the target entry is newer than the source entry if (settings.OverrideEntryOnlyNewer && peNew != null && peNew.LastModificationTime > entry.LastModificationTime) { // Yes -> skip this entry continue; } } // Was no existing entry in the target database found? if (peNew == null) { // Create a new entry peNew = new PwEntry(false, false); peNew.Uuid = entry.Uuid; // Add entry to the target group in the new database targetGroup.AddEntry(peNew, true); } // Clone entry properties peNew.AssignProperties(entry, false, true, true); // Handle custom icon HandleCustomIcon(targetDatabase, sourceDb, entry); } }
private bool IdMatchesMultipleTimes(string strSearch, char tchField) { if(m_pgEntrySource == null) { Debug.Assert(false); return false; } SearchParameters sp = SearchParameters.None; sp.SearchString = strSearch; sp.RespectEntrySearchingDisabled = false; if(tchField == 'T') sp.SearchInTitles = true; else if(tchField == 'U') sp.SearchInUserNames = true; else if(tchField == 'P') sp.SearchInPasswords = true; else if(tchField == 'A') sp.SearchInUrls = true; else if(tchField == 'N') sp.SearchInNotes = true; else if(tchField == 'I') sp.SearchInUuids = true; else { Debug.Assert(false); return true; } PwObjectList<PwEntry> l = new PwObjectList<PwEntry>(); m_pgEntrySource.SearchEntries(sp, l); if(l.UCount == 0) { Debug.Assert(false); return false; } else if(l.UCount == 1) return false; return true; }
private void OnTrayOpening(object sender, EventArgs e) { PluginDebug.AddInfo("Tray setup: Start", 0); m_TrayMenu.DropDownItems.Clear(); List <PwDatabase> lDB = m_host.MainWindow.DocumentManager.GetOpenDatabases(); SearchParameters sp = new SearchParameters(); sp.ExcludeExpired = !Program.Config.Integration.AutoTypeExpiredCanMatch; //exclude expired entries only if they can not match sp.SearchInStringNames = true; Dictionary <string, PwObjectList <PwEntry> > dEntries = new Dictionary <string, PwObjectList <PwEntry> >(); foreach (PwDatabase db in lDB) { string dbName = UrlUtil.GetFileName(db.IOConnectionInfo.Path); if (!string.IsNullOrEmpty(db.Name)) { dbName = db.Name + " (" + dbName + ")"; } PwObjectList <PwEntry> entries = new PwObjectList <PwEntry>(); if (Config.UseDBForOTPSeeds(db)) { sp.SearchString = OTPDAO.OTPHandler_DB.DBNAME; } else { sp.SearchString = Config.OTPFIELD; // Config.SEED + " " + Config.SETTINGS; } db.RootGroup.SearchEntries(sp, entries); PluginDebug.AddInfo("Tray setup: Check database", 0, "DB: " + dbName, "Entries: " + entries.UCount.ToString()); if ((entries == null) || (entries.UCount == 0)) { continue; } //Ignore deleted entries PwGroup pgRecycle = db.RecycleBinEnabled ? db.RootGroup.FindGroup(db.RecycleBinUuid, true) : null; if (pgRecycle != null) { for (int i = (int)entries.UCount - 1; i >= 0; i--) { PwEntry pe = entries.GetAt((uint)i); if (pe.IsContainedIn(pgRecycle)) { entries.Remove(pe); } } } entries.Sort(SortEntries); dEntries.Add(dbName, entries); } foreach (var kvp in dEntries) { ToolStripMenuItem parent = null; //If entries of only one DB are found don't include the DB as additional menu level if (dEntries.Count == 1) { parent = m_TrayMenu; } else { parent = new ToolStripMenuItem(kvp.Key); m_TrayMenu.DropDownItems.Add(parent); } foreach (PwEntry pe in kvp.Value) { ToolStripMenuItem entry = new ToolStripMenuItem(); string[] text = GetTrayText(pe); PluginDebug.AddInfo("Tray setup: Add entry", 0, "Uuid: " + text[2]); // Do NOT add username and entry title to debugfile if (text[0] == string.Empty) { entry.Text = StrUtil.EncodeMenuText(string.Format(PluginTranslate.User, text[1])); } else if (text[1] == string.Empty) { entry.Text = StrUtil.EncodeMenuText(text[0]); } else { entry.Text = StrUtil.EncodeMenuText(text[0] + " (" + text[1] + ")"); } entry.Name = "KPOTP_" + pe.Uuid.ToString(); entry.Click += OnOTPTray; entry.Tag = pe; parent.DropDownItems.Add(entry); } } m_TrayMenu.Enabled = dEntries.Count > 0; m_TrayMenu.Text = m_TrayMenu.Enabled ? PluginTranslate.OTPCopyTrayEntries : PluginTranslate.OTPCopyTrayNoEntries; }
/// <summary> /// Apply a list of deleted objects. /// </summary> /// <param name="listDelObjects">List of deleted objects.</param> private void ApplyDeletions(PwObjectList<PwDeletedObject> listDelObjects, bool bCopyDeletionInfoToLocal) { Debug.Assert(listDelObjects != null); if(listDelObjects == null) throw new ArgumentNullException("listDelObjects"); LinkedList<PwGroup> listGroupsToDelete = new LinkedList<PwGroup>(); LinkedList<PwEntry> listEntriesToDelete = new LinkedList<PwEntry>(); GroupHandler gh = delegate(PwGroup pg) { if(pg == m_pgRootGroup) return true; foreach(PwDeletedObject pdo in listDelObjects) { if(pg.Uuid.EqualsValue(pdo.Uuid)) if(pg.LastModificationTime < pdo.DeletionTime) listGroupsToDelete.AddLast(pg); } return true; }; EntryHandler eh = delegate(PwEntry pe) { foreach(PwDeletedObject pdo in listDelObjects) { if(pe.Uuid.EqualsValue(pdo.Uuid)) if(pe.LastModificationTime < pdo.DeletionTime) listEntriesToDelete.AddLast(pe); } return true; }; m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh); foreach(PwGroup pg in listGroupsToDelete) pg.ParentGroup.Groups.Remove(pg); foreach(PwEntry pe in listEntriesToDelete) pe.ParentGroup.Entries.Remove(pe); if(bCopyDeletionInfoToLocal) { foreach(PwDeletedObject pdoNew in listDelObjects) { bool bCopy = true; foreach(PwDeletedObject pdoLocal in m_vDeletedObjects) { if(pdoNew.Uuid.EqualsValue(pdoLocal.Uuid)) { bCopy = false; if(pdoNew.DeletionTime > pdoLocal.DeletionTime) pdoLocal.DeletionTime = pdoNew.DeletionTime; break; } } if(bCopy) m_vDeletedObjects.Add(pdoNew); } } }
private PwGroup SrxpFilterCloneSelf(SearchParameters sp) { PwGroup pgNew = CloneDeep(); pgNew.ParentGroup = null; DateTime dtNow = DateTime.UtcNow; GroupHandler gh = delegate(PwGroup pg) { if (!sp.SearchInGroupNames) { pg.Name = string.Empty; } if (!sp.SearchInTags) { pg.Tags.Clear(); } PwObjectList <PwEntry> l = pg.Entries; for (int i = (int)l.UCount - 1; i >= 0; --i) { PwEntry pe = l.GetAt((uint)i); if (sp.ExcludeExpired && pe.Expires && (pe.ExpiryTime <= dtNow)) { } else if (sp.RespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) { } else { continue; } l.RemoveAt((uint)i); } return(true); }; EntryHandler eh = delegate(PwEntry pe) { SrxpClearString(!sp.SearchInTitles, pe, PwDefs.TitleField); SrxpClearString(!sp.SearchInUserNames, pe, PwDefs.UserNameField); SrxpClearString(!sp.SearchInPasswords, pe, PwDefs.PasswordField); SrxpClearString(!sp.SearchInUrls, pe, PwDefs.UrlField); SrxpClearString(!sp.SearchInNotes, pe, PwDefs.NotesField); if (!sp.SearchInOther) { List <string> lKeys = pe.Strings.GetKeys(); foreach (string strKey in lKeys) { SrxpClearString(!PwDefs.IsStandardField(strKey), pe, strKey); } } if (!sp.SearchInTags) { pe.Tags.Clear(); } if (!sp.SearchInHistory) { pe.History.Clear(); } return(true); }; gh(pgNew); pgNew.TraverseTree(TraversalMethod.PreOrder, gh, eh); return(pgNew); }
private void SrsmSearch(SearchParameters sp, PwObjectList <PwEntry> lResults, IStatusLogger sl) { PwObjectList <PwEntry> lAll = GetEntries(true); DateTime dtNow = DateTime.UtcNow; List <PwEntry> l = new List <PwEntry>(); foreach (PwEntry pe in lAll) { if (sp.ExcludeExpired && pe.Expires && (pe.ExpiryTime <= dtNow)) { continue; } if (sp.RespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) { continue; } l.Add(pe); } List <string> lTerms; if (sp.SearchMode == PwSearchMode.Simple) { lTerms = StrUtil.SplitSearchTerms(sp.SearchString); } else { lTerms = new List <string>(); lTerms.Add(sp.SearchString); } // Search longer strings first (for improved performance) lTerms.Sort(StrUtil.CompareLengthGt); SearchParameters spSub = sp.Clone(); for (int iTerm = 0; iTerm < lTerms.Count; ++iTerm) { string strTerm = lTerms[iTerm]; // No trim if (string.IsNullOrEmpty(strTerm)) { continue; } bool bNegate = false; if ((sp.SearchMode == PwSearchMode.Simple) && (strTerm.Length >= 2) && (strTerm[0] == '-')) { strTerm = strTerm.Substring(1); bNegate = true; } spSub.SearchString = strTerm; ulong uStEntriesDone = (ulong)iTerm * (ulong)l.Count; ulong uStEntriesMax = (ulong)lTerms.Count * (ulong)l.Count; List <PwEntry> lOut; if (!SrsmSearchSingle(spSub, l, out lOut, sl, uStEntriesDone, uStEntriesMax)) { l.Clear(); // Do not return non-matching entries break; } if (bNegate) { List <PwEntry> lNew = new List <PwEntry>(); int iNeg = 0; foreach (PwEntry pe in l) { if ((iNeg < lOut.Count) && object.ReferenceEquals(lOut[iNeg], pe)) { ++iNeg; } else { Debug.Assert(!lOut.Contains(pe)); lNew.Add(pe); } } Debug.Assert(lNew.Count == (l.Count - lOut.Count)); l = lNew; } else { l = lOut; } } lResults.Add(l); }
private void OnEntryDuplicate(object sender, EventArgs e) { PwGroup pgSelected = GetSelectedGroup(); PwEntry[] vSelected = GetSelectedEntries(); if((vSelected == null) || (vSelected.Length == 0)) return; PwObjectList<PwEntry> vNewEntries = new PwObjectList<PwEntry>(); foreach(PwEntry pe in vSelected) { PwEntry peNew = pe.CloneDeep(); peNew.Uuid = new PwUuid(true); // Create new UUID ProtectedString psTitle = peNew.Strings.Get(PwDefs.TitleField); if(psTitle != null) peNew.Strings.Set(PwDefs.TitleField, new ProtectedString( psTitle.IsProtected, psTitle.ReadString() + " - " + KPRes.CopyOfItem)); Debug.Assert(pe.ParentGroup == peNew.ParentGroup); PwGroup pg = (pe.ParentGroup ?? pgSelected); if((pg == null) && (m_docMgr.ActiveDocument != null)) pg = m_docMgr.ActiveDatabase.RootGroup; if(pg == null) continue; pg.AddEntry(peNew, true, true); vNewEntries.Add(peNew); } AddEntriesToList(vNewEntries); SelectEntries(vNewEntries, true); if((m_lvEntries.ShowGroups == false) && (m_lvEntries.Items.Count >= 1)) m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1); else EnsureVisibleSelected(true); UpdateUIState(true); }
private IEnumerable<PwEntryDatabase> FindMatchingEntries(Request r, Aes aes) { string submithost = null; string realm = null; var listResult = new List<PwEntryDatabase>(); string formhost, searchHost; formhost = searchHost = GetHost(CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT)); if (r.SubmitUrl != null) { submithost = GetHost(CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT)); } if (r.Realm != null) realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT); var origSearchHost = searchHost; var parms = MakeSearchParameters(); List<PwDatabase> listDatabases = new List<PwDatabase>(); var configOpt = new ConfigOpt(this.host.CustomConfig); if (configOpt.SearchInAllOpenedDatabases) { foreach (PwDocument doc in host.MainWindow.DocumentManager.Documents) { if (doc.Database.IsOpen) { listDatabases.Add(doc.Database); } } } else { listDatabases.Add(host.Database); } int listCount = 0; foreach (PwDatabase db in listDatabases) { searchHost = origSearchHost; //get all possible entries for given host-name while (listResult.Count == listCount && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1)) { parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost); var listEntries = new PwObjectList<PwEntry>(); db.RootGroup.SearchEntries(parms, listEntries); foreach (var le in listEntries) { listResult.Add(new PwEntryDatabase(le, db)); } searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); //searchHost contains no dot --> prevent possible infinite loop if (searchHost == origSearchHost) break; } listCount = listResult.Count; } Func<PwEntry, bool> filter = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = GetEntryConfig(e); if (c != null) { if (c.Allow.Contains(formhost) && (submithost == null || c.Allow.Contains(submithost))) return true; if (c.Deny.Contains(formhost) || (submithost != null && c.Deny.Contains(submithost))) return false; if (realm != null && c.Realm != realm) return false; } if (title.StartsWith("http://") || title.StartsWith("https://")) { var u = new Uri(title); if (formhost.Contains(u.Host)) return true; } if (entryUrl != null && entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://")) { var u = new Uri(entryUrl); if (formhost.Contains(u.Host)) return true; } return formhost.Contains(title) || (entryUrl != null && formhost.Contains(entryUrl)); }; return from e in listResult where filter(e.entry) select e; }
private static void CreateEntry(PwEntry peTemplate) { if (peTemplate == null) { Debug.Assert(false); return; } PwDatabase pd = Program.MainForm.ActiveDatabase; if (pd == null) { Debug.Assert(false); return; } if (pd.IsOpen == false) { Debug.Assert(false); return; } PwGroup pgContainer = Program.MainForm.GetSelectedGroup(); if (pgContainer == null) { pgContainer = pd.RootGroup; } PwEntry pe = peTemplate.Duplicate(); pe.History.Clear(); if (EntryTemplates.EntryCreating != null) { EntryTemplates.EntryCreating(null, new TemplateEntryEventArgs( peTemplate.CloneDeep(), pe)); } PwEntryForm pef = new PwEntryForm(); pef.InitEx(pe, PwEditMode.AddNewEntry, pd, Program.MainForm.ClientIcons, false, true); if (UIUtil.ShowDialogAndDestroy(pef) == DialogResult.OK) { pgContainer.AddEntry(pe, true, true); MainForm mf = Program.MainForm; if (mf != null) { mf.UpdateUI(false, null, pd.UINeedsIconUpdate, null, true, null, true); PwObjectList <PwEntry> lSelect = new PwObjectList <PwEntry>(); lSelect.Add(pe); mf.SelectEntries(lSelect, true, true); mf.EnsureVisibleSelected(false); mf.UpdateUI(false, null, false, null, false, null, false); if (Program.Config.Application.AutoSaveAfterEntryEdit) { mf.SaveDatabase(pd, null); } } else { Debug.Assert(false); } if (EntryTemplates.EntryCreated != null) { EntryTemplates.EntryCreated(null, new TemplateEntryEventArgs( peTemplate.CloneDeep(), pe)); } } else { Program.MainForm.UpdateUI(false, null, pd.UINeedsIconUpdate, null, pd.UINeedsIconUpdate, null, false); } }
internal void SelectEntries(PwObjectList<PwEntry> lEntries, bool bDeselectOthers, bool bFocusFirst) { ++m_uBlockEntrySelectionEvent; bool bFirst = true; for(int i = 0; i < m_lvEntries.Items.Count; ++i) { PwEntry pe = ((PwListItem)m_lvEntries.Items[i].Tag).Entry; if(pe == null) { Debug.Assert(false); continue; } bool bFound = false; foreach(PwEntry peFocus in lEntries) { if(pe == peFocus) { m_lvEntries.Items[i].Selected = true; if(bFirst && bFocusFirst) { UIUtil.SetFocusedItem(m_lvEntries, m_lvEntries.Items[i], false); bFirst = false; } bFound = true; break; } } if(bDeselectOthers && !bFound) m_lvEntries.Items[i].Selected = false; } --m_uBlockEntrySelectionEvent; }
private void runCheckButton_Click(object sender, EventArgs e) { var checkDups = checkDuplicates.Checked; var checkLen = checkLength.Checked; var lenToCheck = Convert.ToInt32(lengthToCheckInput.Value); var checkComp = checkComplexity.Checked; var comp = (PasswordScore)complexitySlider.Value; if (!checkDups && !checkLen && !checkComp) { MessageBox.Show("You must select at least one criteria to check.", "Error"); return; } runCheckButton.Enabled = false; checkDuplicates.Enabled = false; checkLength.Enabled = false; lengthToCheckInput.Enabled = false; checkComplexity.Enabled = false; complexitySlider.Enabled = false; try { this.statusLabel.Text = "Starting Check..."; PwDatabase pwdb = m_host.Database; if (!pwdb.IsOpen) { statusLabel.Text = "Please open database first..."; return; } PwObjectList <PwEntry> entries = pwdb.RootGroup.GetEntries(true); if (entries != null) { statusLabel.Text = "Database opened, " + entries.UCount + " entries to check..."; } else { statusLabel.Text = "No entries in Database."; return; } //Used to check for Duplicate Passwords Dictionary <string, List <string> > results = new Dictionary <string, List <string> >(entries.Count <PwEntry>()); //Used to check password length List <string> shortPasses = new List <string>(); //Used to check password complexity List <string> simplePasses = new List <string>(); foreach (var entry in entries) { string pass = entry.Strings.Get(PwDefs.PasswordField).ReadString(); if (pass.Equals("")) { continue; } if (checkDups) { if (results.ContainsKey(pass)) { results[pass].Add(entry.Strings.Get(PwDefs.TitleField).ReadString()); } else { List <string> list = new List <string>(); var xx = entry.Strings.Get(PwDefs.TitleField); if (xx != null) { list.Add(xx.ReadString()); } else { var urlxx = entry.Strings.Get(PwDefs.UrlField); if (urlxx != null) { list.Add(urlxx.ReadString()); } else { list.Add(entry.ToString()); } } results.Add(pass, list); } } if (checkLen) { if (pass.Length < lenToCheck) { shortPasses.Add(entry.Strings.Get(PwDefs.TitleField).ReadString() + " (" + pass.Length + ")"); } } if (checkComp) { var tcomp = PasswordAdvisor.CheckStrength(pass); if (tcomp < comp) { simplePasses.Add(entry.Strings.Get(PwDefs.TitleField).ReadString() + " (" + Enum.GetName(typeof(PasswordScore), tcomp) + ")"); } } } checkResultsView.BeginUpdate(); TreeNodeCollection nodes = checkResultsView.Nodes; checkResultsView.Nodes.Clear(); if (checkDups) { int dupPass = 1; foreach (KeyValuePair <string, List <string> > result in results) { if (result.Value.Count > 1) { List <TreeNode> children = new List <TreeNode>(); foreach (var title in result.Value) { children.Add(new TreeNode(title)); } TreeNode node = new TreeNode(string.Format("Duplicated Password [{0}] ({1})", result.Key, children.Count), children.ToArray()); nodes.Add(node); dupPass++; } } } if (checkLen) { if (shortPasses.Count > 0) { List <TreeNode> children = new List <TreeNode>(); foreach (var title in shortPasses) { children.Add(new TreeNode(title)); } TreeNode node = new TreeNode("Short Passwords", children.ToArray()); nodes.Add(node); } } if (checkComp) { if (simplePasses.Count > 0) { List <TreeNode> children = new List <TreeNode>(); foreach (var title in simplePasses) { children.Add(new TreeNode(title)); } TreeNode node = new TreeNode("Simple Passwords", children.ToArray()); nodes.Add(node); } } checkResultsView.EndUpdate(); statusLabel.Text = "Check complete."; } catch (NullReferenceException nre) { MessageBox.Show(string.Format("I tried to read a null value.\n{0}", nre.StackTrace)); throw; } runCheckButton.Enabled = true; checkDuplicates.Enabled = true; checkLength.Enabled = true; lengthToCheckInput.Enabled = true; checkComplexity.Enabled = true; complexitySlider.Enabled = true; }
/* private void ReadDeletedObjects(XmlNode xmlNode, PwObjectList<PwDeletedObject> list) { ProcessNode(xmlNode); foreach(XmlNode xmlChild in xmlNode.ChildNodes) { if(xmlChild.Name == ElemDeletedObject) list.Add(ReadDeletedObject(xmlChild)); else ReadUnknown(xmlChild); } } private PwDeletedObject ReadDeletedObject(XmlNode xmlNode) { ProcessNode(xmlNode); PwDeletedObject pdo = new PwDeletedObject(); foreach(XmlNode xmlChild in xmlNode.ChildNodes) { if(xmlChild.Name == ElemUuid) pdo.Uuid = ReadUuid(xmlChild); else if(xmlChild.Name == ElemDeletionTime) pdo.DeletionTime = ReadTime(xmlChild); else ReadUnknown(xmlChild); } return pdo; } */ private void ReadHistory(XmlNode xmlNode, PwObjectList<PwEntry> plStorage) { ProcessNode(xmlNode); foreach(XmlNode xmlChild in xmlNode.ChildNodes) { if(xmlChild.Name == ElemEntry) { plStorage.Add(ReadEntry(xmlChild)); } else ReadUnknown(xmlChild); } }
private void OnShowEntriesByTag(object sender, DynamicMenuEventArgs e) { string strTag = (e.Tag as string); if(strTag == null) { Debug.Assert(false); return; } if(strTag.Length == 0) return; // No assert PwDatabase pd = m_docMgr.ActiveDatabase; if((pd == null) || !pd.IsOpen) { Debug.Assert(false); return; } PwObjectList<PwEntry> vEntries = new PwObjectList<PwEntry>(); pd.RootGroup.FindEntriesByTag(strTag, vEntries, true); PwGroup pgResults = new PwGroup(true, true); pgResults.IsVirtual = true; foreach(PwEntry pe in vEntries) pgResults.AddEntry(pe, false); UpdateUI(false, null, false, null, true, pgResults, false); }
public static PwEntry FindRefTarget(string strFullRef, SprContext ctx, out char chScan, out char chWanted) { chScan = char.MinValue; chWanted = char.MinValue; if(strFullRef == null) { Debug.Assert(false); return null; } if(!strFullRef.StartsWith(StrRefStart, SprEngine.ScMethod) || !strFullRef.EndsWith(StrRefEnd, SprEngine.ScMethod)) return null; if((ctx == null) || (ctx.Database == null)) { Debug.Assert(false); return null; } string strRef = strFullRef.Substring(StrRefStart.Length, strFullRef.Length - StrRefStart.Length - StrRefEnd.Length); if(strRef.Length <= 4) return null; if(strRef[1] != '@') return null; if(strRef[3] != ':') return null; chScan = char.ToUpper(strRef[2]); chWanted = char.ToUpper(strRef[0]); SearchParameters sp = SearchParameters.None; sp.SearchString = strRef.Substring(4); sp.RespectEntrySearchingDisabled = false; if(chScan == 'T') sp.SearchInTitles = true; else if(chScan == 'U') sp.SearchInUserNames = true; else if(chScan == 'A') sp.SearchInUrls = true; else if(chScan == 'P') sp.SearchInPasswords = true; else if(chScan == 'N') sp.SearchInNotes = true; else if(chScan == 'I') sp.SearchInUuids = true; else if(chScan == 'O') sp.SearchInOther = true; else return null; PwObjectList<PwEntry> lFound = new PwObjectList<PwEntry>(); ctx.Database.RootGroup.SearchEntries(sp, lFound); return ((lFound.UCount > 0) ? lFound.GetAt(0) : null); }
private void SelectEntries(PwObjectList<PwEntry> lEntries, bool bDeselectOthers) { m_bBlockEntrySelectionEvent = true; for(int i = 0; i < m_lvEntries.Items.Count; ++i) { PwEntry pe = (m_lvEntries.Items[i].Tag as PwEntry); if(pe == null) { Debug.Assert(false); continue; } bool bFound = false; foreach(PwEntry peFocus in lEntries) { if(pe == peFocus) { m_lvEntries.Items[i].Selected = true; bFound = true; break; } } if(bDeselectOthers && !bFound) m_lvEntries.Items[i].Selected = false; } m_bBlockEntrySelectionEvent = false; }
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); }
public PwDeletedObjectListBuffer(PwObjectList <PwDeletedObject> objectList) : base(objectList) { }
private static void ExportDatabaseFile(EcasAction a, EcasContext ctx) { string strPath = EcasUtil.GetParamString(a.Parameters, 0, true); // if(string.IsNullOrEmpty(strPath)) return; // Allow no-file exports string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true); if (string.IsNullOrEmpty(strFormat)) { return; } string strGroup = EcasUtil.GetParamString(a.Parameters, 2, true); string strTag = EcasUtil.GetParamString(a.Parameters, 3, true); PwDatabase pd = Program.MainForm.ActiveDatabase; if ((pd == null) || !pd.IsOpen) { return; } PwGroup pg = pd.RootGroup; if (!string.IsNullOrEmpty(strGroup)) { char chSep = strGroup[0]; PwGroup pgSub = pg.FindCreateSubTree(strGroup.Substring(1), new char[] { chSep }, false); pg = (pgSub ?? (new PwGroup(true, true, KPRes.Group, PwIcon.Folder))); } if (!string.IsNullOrEmpty(strTag)) { // Do not use pg.Duplicate, because this method // creates new UUIDs pg = pg.CloneDeep(); pg.TakeOwnership(true, true, true); GroupHandler gh = delegate(PwGroup pgSub) { PwObjectList <PwEntry> l = pgSub.Entries; long n = (long)l.UCount; for (long i = n - 1; i >= 0; --i) { if (!l.GetAt((uint)i).HasTag(strTag)) { l.RemoveAt((uint)i); } } return(true); }; gh(pg); pg.TraverseTree(TraversalMethod.PreOrder, gh, null); } PwExportInfo pei = new PwExportInfo(pg, pd, true); IOConnectionInfo ioc = (!string.IsNullOrEmpty(strPath) ? IOConnectionInfo.FromPath(strPath) : null); ExportUtil.Export(pei, strFormat, ioc); }
protected PwObjectListBufferBase(PwObjectList <TData> objectList) { mObjectList = objectList; }
private void OnFilterKeyDown(object sender, KeyEventArgs e) { if((e.KeyCode == Keys.Return) || (e.KeyCode == Keys.Enter)) { e.SuppressKeyPress = true; SearchParameters sp = new SearchParameters(); sp.SearchString = m_tbFilter.Text; sp.SearchInPasswords = true; PwObjectList<PwEntry> lResults = new PwObjectList<PwEntry>(); m_pgEntrySource.SearchEntries(sp, lResults); UIUtil.CreateEntryList(m_lvEntries, lResults, m_vColumns, m_ilIcons); } }
public static PwObjectList<PwEntry> GetPossibleTemplates(IPluginHost m_host) { PwObjectList<PwEntry> entries = new PwObjectList<PwEntry>(); PwGroup group = template_group(m_host); if (group == null) return entries; PwObjectList<PwEntry> all_entries = group.GetEntries(true); foreach (PwEntry entry in all_entries) { if (entry.Strings.Exists("_etm_template")) entries.Add(entry); } return entries; }
private void Clear() { m_pgRootGroup = null; m_vDeletedObjects = new PwObjectList<PwDeletedObject>(); m_uuidDataCipher = StandardAesEngine.AesUuid; m_caCompression = PwCompressionAlgorithm.GZip; m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; m_pwUserKey = null; m_memProtConfig = new MemoryProtectionConfig(); m_vCustomIcons = new List<PwCustomIcon>(); m_strName = string.Empty; m_strDesc = string.Empty; m_strDefaultUserName = string.Empty; m_bUINeedsIconUpdate = true; m_ioSource = new IOConnectionInfo(); m_bDatabaseOpened = false; m_bModified = false; m_pwLastSelectedGroup = PwUuid.Zero; m_pwLastTopVisibleGroup = PwUuid.Zero; m_pbHashOfFileOnDisk = null; m_pbHashOfLastIO = null; }
private void OnToolsGeneratePasswordList(object sender, EventArgs e) { PwDatabase pwDb = m_docMgr.ActiveDatabase; if(!pwDb.IsOpen) return; PwGeneratorForm pgf = new PwGeneratorForm(); pgf.InitEx(null, true, IsTrayed()); if(pgf.ShowDialog() == DialogResult.OK) { PwGroup pg = GetSelectedGroup(); if(pg == null) pg = pwDb.RootGroup; SingleLineEditForm dlgCount = new SingleLineEditForm(); dlgCount.InitEx(KPRes.GenerateCount, KPRes.GenerateCountDesc, KPRes.GenerateCountLongDesc, Properties.Resources.B48x48_KGPG_Gen, string.Empty, null); if(dlgCount.ShowDialog() == DialogResult.OK) { uint uCount; if(!uint.TryParse(dlgCount.ResultString, out uCount)) uCount = 1; byte[] pbAdditionalEntropy = EntropyForm.CollectEntropyIfEnabled( pgf.SelectedProfile); PwObjectList<PwEntry> l = new PwObjectList<PwEntry>(); for(uint i = 0; i < uCount; ++i) { PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); ProtectedString psNew; PwGenerator.Generate(out psNew, pgf.SelectedProfile, pbAdditionalEntropy, Program.PwGeneratorPool); psNew = psNew.WithProtection(pwDb.MemoryProtection.ProtectPassword); pe.Strings.Set(PwDefs.PasswordField, psNew); l.Add(pe); } UpdateUI(false, null, false, null, true, null, true, m_lvEntries); SelectEntries(l, true, true); EnsureVisibleSelected(false); } UIUtil.DestroyForm(dlgCount); } UIUtil.DestroyForm(pgf); }
protected PwObjectListBufferBase() { mObjectList = new PwObjectList <TData>(); }
/// <summary> /// Search this group and all subgroups for entries. /// </summary> /// <param name="sp">Specifies the search parameters.</param> /// <param name="lResults">Entry list in which the search results /// will be stored.</param> public void SearchEntries(SearchParameters sp, PwObjectList <PwEntry> lResults) { SearchEntries(sp, lResults, null); }
public void InitEx(PwEntry pwEntry, PwEditMode pwMode, PwDatabase pwDatabase, ImageList ilIcons, bool bShowAdvancedByDefault, bool bSelectFullTitle) { Debug.Assert(pwEntry != null); if(pwEntry == null) throw new ArgumentNullException("pwEntry"); Debug.Assert(pwMode != PwEditMode.Invalid); if(pwMode == PwEditMode.Invalid) throw new ArgumentException(); Debug.Assert(ilIcons != null); if(ilIcons == null) throw new ArgumentNullException("ilIcons"); m_pwEntry = pwEntry; m_pwEditMode = pwMode; m_pwDatabase = pwDatabase; m_ilIcons = ilIcons; m_bShowAdvancedByDefault = bShowAdvancedByDefault; m_bSelectFullTitle = bSelectFullTitle; m_vStrings = m_pwEntry.Strings.CloneDeep(); m_vBinaries = m_pwEntry.Binaries.CloneDeep(); m_atConfig = m_pwEntry.AutoType.CloneDeep(); m_vHistory = m_pwEntry.History.CloneDeep(); }
public PwEntryListBuffer(PwObjectList <PwEntry> entryList) : base(entryList) { }
private void OnToolsPwGenerator(object sender, EventArgs e) { PwDatabase pwDb = m_docMgr.ActiveDatabase; PwGeneratorForm pgf = new PwGeneratorForm(); pgf.InitEx(null, pwDb.IsOpen, IsTrayed()); if(pgf.ShowDialog() == DialogResult.OK) { if(pwDb.IsOpen) { PwGroup pg = GetSelectedGroup(); if(pg == null) pg = pwDb.RootGroup; PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); byte[] pbAdditionalEntropy = EntropyForm.CollectEntropyIfEnabled( pgf.SelectedProfile); ProtectedString psNew; PwGenerator.Generate(out psNew, pgf.SelectedProfile, pbAdditionalEntropy, Program.PwGeneratorPool); psNew = psNew.WithProtection(pwDb.MemoryProtection.ProtectPassword); pe.Strings.Set(PwDefs.PasswordField, psNew); UpdateUI(false, null, false, null, true, null, true, m_lvEntries); PwObjectList<PwEntry> l = new PwObjectList<PwEntry>(); l.Add(pe); SelectEntries(l, true, true); EnsureVisibleSelected(false); } } UIUtil.DestroyForm(pgf); }
private bool SearchEntriesSingle(SearchParameters spIn, PwObjectList <PwEntry> listStorage, IDictionary <PwUuid, KeyValuePair <string, string> > resultContexts, IStatusLogger slStatus, ref ulong uCurEntries, ulong uTotalEntries) { SearchParameters sp = spIn.Clone(); if (sp.SearchString == null) { Debug.Assert(false); return(true); } sp.SearchString = sp.SearchString.Trim(); bool bTitle = sp.SearchInTitles; bool bUserName = sp.SearchInUserNames; bool bPassword = sp.SearchInPasswords; bool bUrl = sp.SearchInUrls; bool bNotes = sp.SearchInNotes; bool bOther = sp.SearchInOther; bool bUuids = sp.SearchInUuids; bool bGroupName = sp.SearchInGroupNames; bool bTags = sp.SearchInTags; bool bExcludeExpired = sp.ExcludeExpired; bool bRespectEntrySearchingDisabled = sp.RespectEntrySearchingDisabled; DateTime dtNow = DateTime.Now; Regex rx = null; if (sp.RegularExpression) { RegexOptions ro = RegexOptions.None; // RegexOptions.Compiled if ((sp.ComparisonMode == StringComparison.CurrentCultureIgnoreCase) || #if !KeePassUAP (sp.ComparisonMode == StringComparison.InvariantCultureIgnoreCase) || #endif (sp.ComparisonMode == StringComparison.OrdinalIgnoreCase)) { ro |= RegexOptions.IgnoreCase; } rx = new Regex(sp.SearchString, ro); } ulong uLocalCurEntries = uCurEntries; EntryHandler eh = null; if (sp.SearchString.Length <= 0) // Report all { eh = delegate(PwEntry pe) { if (slStatus != null) { if (!slStatus.SetProgress((uint)((uLocalCurEntries * 100UL) / uTotalEntries))) { return(false); } ++uLocalCurEntries; } if (bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) { return(true); // Skip } if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) { return(true); // Skip } listStorage.Add(pe); return(true); }; } else { eh = delegate(PwEntry pe) { if (slStatus != null) { if (!slStatus.SetProgress((uint)((uLocalCurEntries * 100UL) / uTotalEntries))) { return(false); } ++uLocalCurEntries; } if (bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) { return(true); // Skip } if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) { return(true); // Skip } uint uInitialResults = listStorage.UCount; foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings) { string strKey = kvp.Key; if (strKey == PwDefs.TitleField) { if (bTitle) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } } else if (strKey == PwDefs.UserNameField) { if (bUserName) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } } else if (strKey == PwDefs.PasswordField) { if (bPassword) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } } else if (strKey == PwDefs.UrlField) { if (bUrl) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } } else if (strKey == PwDefs.NotesField) { if (bNotes) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } } else if (bOther) { SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); } // An entry can match only once => break if we have added it if (listStorage.UCount > uInitialResults) { break; } } if (bUuids && (listStorage.UCount == uInitialResults)) { SearchEvalAdd(sp, pe.Uuid.ToHexString(), rx, pe, listStorage, resultContexts, SearchContextTags); } if (bGroupName && (listStorage.UCount == uInitialResults) && (pe.ParentGroup != null)) { SearchEvalAdd(sp, pe.ParentGroup.Name, rx, pe, listStorage, resultContexts, SearchContextParentGroup); } if (bTags) { foreach (string strTag in pe.Tags) { if (listStorage.UCount != uInitialResults) { break; // Match } SearchEvalAdd(sp, strTag, rx, pe, listStorage, resultContexts, SearchContextTags); } } return(true); }; } if (!PreOrderTraverseTree(null, eh)) { return(false); } uCurEntries = uLocalCurEntries; return(true); }
private void GetAllLoginsHandler(Request r, Response resp, Aes aes) { if (!VerifyRequest(r, aes)) return; var list = new PwObjectList<PwEntry>(); var root = host.Database.RootGroup; var parms = MakeSearchParameters(); parms.SearchString = @"^[A-Za-z0-9:/-]+\.[A-Za-z0-9:/-]+$"; // match anything looking like a domain or url root.SearchEntries(parms, list); foreach (var entry in list) { var name = entry.Strings.ReadSafe(PwDefs.TitleField); var login = GetUserPass(entry)[0]; var uuid = entry.Uuid.ToHexString(); var e = new ResponseEntry(name, login, null, uuid); resp.Entries.Add(e); } resp.Success = true; resp.Id = r.Id; SetResponseVerifier(resp, aes); foreach (var entry in resp.Entries) { entry.Name = CryptoTransform(entry.Name, false, true, aes, CMode.ENCRYPT); entry.Login = CryptoTransform(entry.Login, false, true, aes, CMode.ENCRYPT); entry.Uuid = CryptoTransform(entry.Uuid, false, true, aes, CMode.ENCRYPT); } }
private static void SearchEvalAdd(SearchParameters sp, string strDataField, Regex rx, PwEntry pe, PwObjectList <PwEntry> lResults, IDictionary <PwUuid, KeyValuePair <string, string> > resultContexts, string contextFieldName) { bool bMatch = false; int matchPos; if (rx == null) { matchPos = strDataField.IndexOf(sp.SearchString, sp.ComparisonMode); bMatch = matchPos >= 0; } else { var match = rx.Match(strDataField); bMatch = match.Success; matchPos = match.Index; } if (!bMatch && (sp.DataTransformationFn != null)) { string strCmp = sp.DataTransformationFn(strDataField, pe); if (!object.ReferenceEquals(strCmp, strDataField)) { if (rx == null) { matchPos = strCmp.IndexOf(sp.SearchString, sp.ComparisonMode); bMatch = matchPos >= 0; } else { var match = rx.Match(strCmp); bMatch = match.Success; matchPos = match.Index; } } } if (bMatch) { lResults.Add(pe); if (resultContexts != null) { // Trim the value if necessary var contextString = strDataField; if (contextString.Length > SearchContextStringMaxLength) { // Start 10% before actual data, and don't run over var startPos = Math.Max(0, Math.Min(matchPos - (SearchContextStringMaxLength / 10), contextString.Length - SearchContextStringMaxLength)); contextString = "… " + contextString.Substring(startPos, SearchContextStringMaxLength) + ((startPos + SearchContextStringMaxLength < contextString.Length) ? " …" : null); } resultContexts[pe.Uuid] = new KeyValuePair <string, string>(contextFieldName, contextString); } } }
private void OnEntryAdd(object sender, EventArgs e) { PwGroup pg = GetSelectedGroup(); Debug.Assert(pg != null); if(pg == null) return; if(pg.IsVirtual) { MessageService.ShowWarning(KPRes.GroupCannotStoreEntries, KPRes.SelectDifferentGroup); return; } PwDatabase pwDb = m_docMgr.ActiveDatabase; PwEntry pwe = new PwEntry(true, true); pwe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwDb.MemoryProtection.ProtectUserName, pwDb.DefaultUserName)); ProtectedString psAutoGen = new ProtectedString( pwDb.MemoryProtection.ProtectPassword); PwGenerator.Generate(psAutoGen, Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile, null, Program.PwGeneratorPool); pwe.Strings.Set(PwDefs.PasswordField, psAutoGen); int nExpireDays = Program.Config.Defaults.NewEntryExpiresInDays; if(nExpireDays >= 0) { pwe.Expires = true; pwe.ExpiryTime = DateTime.Now.AddDays(nExpireDays); } if((pg.IconId != PwIcon.Folder) && (pg.IconId != PwIcon.FolderOpen) && (pg.IconId != PwIcon.FolderPackage)) { pwe.IconId = pg.IconId; // Inherit icon from group } pwe.CustomIconUuid = pg.CustomIconUuid; // Temporarily assume that the entry is in pg; required for retrieving // the default auto-type sequence pwe.ParentGroup = pg; PwEntryForm pForm = new PwEntryForm(); pForm.InitEx(pwe, PwEditMode.AddNewEntry, pwDb, m_ilCurrentIcons, false, false); if(UIUtil.ShowDialogAndDestroy(pForm) == DialogResult.OK) { pg.AddEntry(pwe, true); UpdateUI(false, null, pwDb.UINeedsIconUpdate, null, true, null, true, m_lvEntries); PwObjectList<PwEntry> vSelect = new PwObjectList<PwEntry>(); vSelect.Add(pwe); SelectEntries(vSelect, true, true); EnsureVisibleEntry(pwe.Uuid); } else UpdateUI(false, null, pwDb.UINeedsIconUpdate, null, pwDb.UINeedsIconUpdate, null, false); }
/// <summary> /// Search this group and all subgroups for entries. /// </summary> /// <param name="sp">Specifies the search method.</param> /// <param name="listStorage">Entry list in which the search results will /// be stored.</param> public void SearchEntries(SearchParameters sp, PwObjectList <PwEntry> listStorage) { SearchEntries(sp, listStorage, null); }
private void OnEntryViewLinkClicked(object sender, LinkClickedEventArgs e) { string strLink = e.LinkText; if(string.IsNullOrEmpty(strLink)) { Debug.Assert(false); return; } PwEntry pe = GetSelectedEntry(false); ProtectedBinary pb = ((pe != null) ? pe.Binaries.Get(strLink) : null); string strEntryUrl = string.Empty; if(pe != null) strEntryUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), GetEntryListSprContext(pe, m_docMgr.SafeFindContainerOf(pe))); if((pe != null) && (pe.ParentGroup != null) && (pe.ParentGroup.Name == strLink)) { UpdateUI(false, null, true, pe.ParentGroup, true, null, false); EnsureVisibleSelected(false); ResetDefaultFocus(m_lvEntries); } else if(strEntryUrl == strLink) PerformDefaultUrlAction(null, false); else if(pb != null) ExecuteBinaryEditView(strLink, pb); else if(strLink.StartsWith(SprEngine.StrRefStart, StrUtil.CaseIgnoreCmp) && strLink.EndsWith(SprEngine.StrRefEnd, StrUtil.CaseIgnoreCmp)) { // If multiple references are amalgamated, only use first one string strFirstRef = strLink; int iEnd = strLink.IndexOf(SprEngine.StrRefEnd, StrUtil.CaseIgnoreCmp); if(iEnd != (strLink.Length - SprEngine.StrRefEnd.Length)) strFirstRef = strLink.Substring(0, iEnd + 1); char chScan, chWanted; PwEntry peRef = SprEngine.FindRefTarget(strFirstRef, GetEntryListSprContext( pe, m_docMgr.SafeFindContainerOf(pe)), out chScan, out chWanted); if(peRef != null) { UpdateUI(false, null, true, peRef.ParentGroup, true, null, false, m_lvEntries); PwObjectList<PwEntry> lSel = new PwObjectList<PwEntry>(); lSel.Add(peRef); SelectEntries(lSel, true, true); EnsureVisibleSelected(false); ShowEntryDetails(peRef); } } else WinUtil.OpenUrl(strLink, pe); }
/// <summary> /// Search this group and all subgroups for entries. /// </summary> /// <param name="sp">Specifies the search method.</param> /// <param name="listStorage">Entry list in which the search results will /// be stored.</param> /// <param name="slStatus">Optional status reporting object.</param> public void SearchEntries(SearchParameters sp, PwObjectList <PwEntry> listStorage, IStatusLogger slStatus) { SearchEntries(sp, listStorage, null, slStatus); }
private static bool ListContainsOnlyTans(PwObjectList<PwEntry> vEntries) { if(vEntries == null) { Debug.Assert(false); return true; } foreach(PwEntry pe in vEntries) { if(!PwDefs.IsTanEntry(pe)) return false; } return true; }
/// <summary> /// Search this group and all subgroups for entries. /// </summary> /// <param name="sp">Specifies the search method.</param> /// <param name="listStorage">Entry list in which the search results will /// be stored.</param> /// <param name="resultContexts">Dictionary that will be populated with text fragments indicating the context of why each entry (keyed by Uuid) was returned</param> public void SearchEntries(SearchParameters sp, PwObjectList <PwEntry> listStorage, IDictionary <PwUuid, KeyValuePair <string, string> > resultContexts, IStatusLogger slStatus) { if (sp == null) { Debug.Assert(false); return; } if (listStorage == null) { Debug.Assert(false); return; } ulong uCurEntries = 0, uTotalEntries = 0; List <string> lTerms = StrUtil.SplitSearchTerms(sp.SearchString); if ((lTerms.Count <= 1) || sp.RegularExpression) { if (slStatus != null) { uTotalEntries = GetEntriesCount(true); } SearchEntriesSingle(sp, listStorage, resultContexts, slStatus, ref uCurEntries, uTotalEntries); return; } // Search longer strings first (for improved performance) lTerms.Sort(StrUtil.CompareLengthGt); string strFullSearch = sp.SearchString; // Backup PwGroup pg = this; for (int iTerm = 0; iTerm < lTerms.Count; ++iTerm) { // Update counters for a better state guess if (slStatus != null) { ulong uRemRounds = (ulong)(lTerms.Count - iTerm); uTotalEntries = uCurEntries + (uRemRounds * pg.GetEntriesCount(true)); } PwGroup pgNew = new PwGroup(); sp.SearchString = lTerms[iTerm]; bool bNegate = false; if (sp.SearchString.StartsWith("-")) { sp.SearchString = sp.SearchString.Substring(1); bNegate = (sp.SearchString.Length > 0); } if (!pg.SearchEntriesSingle(sp, pgNew.Entries, resultContexts, slStatus, ref uCurEntries, uTotalEntries)) { pg = null; break; } if (bNegate) { PwObjectList <PwEntry> lCand = pg.GetEntries(true); pg = new PwGroup(); foreach (PwEntry peCand in lCand) { if (pgNew.Entries.IndexOf(peCand) < 0) { pg.Entries.Add(peCand); } } } else { pg = pgNew; } } if (pg != null) { listStorage.Add(pg.Entries); } sp.SearchString = strFullSearch; // Restore }
private void AddEntriesToList(PwObjectList<PwEntry> vEntries) { if(vEntries == null) { Debug.Assert(false); return; } m_bEntryGrouping = m_lvEntries.ShowGroups; ListViewStateEx lvseCachedState = new ListViewStateEx(m_lvEntries); foreach(PwEntry pe in vEntries) { if(pe == null) { Debug.Assert(false); continue; } if(m_bEntryGrouping) { PwGroup pg = pe.ParentGroup; foreach(ListViewGroup lvg in m_lvEntries.Groups) { PwGroup pgList = (lvg.Tag as PwGroup); Debug.Assert(pgList != null); if((pgList != null) && (pg == pgList)) { m_lvgLastEntryGroup = lvg; break; } } } SetListEntry(pe, null); } Debug.Assert(lvseCachedState.CompareTo(m_lvEntries)); UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor, Program.Config.MainWindow.EntryListAlternatingBgColors); }
private IEnumerable <PwEntryDatabase> FindMatchingEntries(Request r, Aes aes) { string submitHost = null; string realm = null; var listResult = new List <PwEntryDatabase>(); var url = CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT); string formHost, searchHost; formHost = searchHost = GetHost(url); string hostScheme = GetScheme(url); if (r.SubmitUrl != null) { submitHost = GetHost(CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT)); } if (r.Realm != null) { realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT); } var origSearchHost = searchHost; var parms = MakeSearchParameters(); List <PwDatabase> listDatabases = new List <PwDatabase>(); var configOpt = new ConfigOpt(this.host.CustomConfig); if (configOpt.SearchInAllOpenedDatabases) { foreach (PwDocument doc in host.MainWindow.DocumentManager.Documents) { if (doc.Database.IsOpen) { listDatabases.Add(doc.Database); } } } else { listDatabases.Add(host.Database); } int listCount = 0; foreach (PwDatabase db in listDatabases) { searchHost = origSearchHost; //get all possible entries for given host-name while (listResult.Count == listCount && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1)) { parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost); var listEntries = new PwObjectList <PwEntry>(); db.RootGroup.SearchEntries(parms, listEntries); foreach (var le in listEntries) { listResult.Add(new PwEntryDatabase(le, db)); } searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); //searchHost contains no dot --> prevent possible infinite loop if (searchHost == origSearchHost) { break; } } listCount = listResult.Count; } Func <PwEntry, bool> filter = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = GetEntryConfig(e); if (c != null) { if (c.Allow.Contains(formHost) && (submitHost == null || c.Allow.Contains(submitHost))) { return(true); } if (c.Deny.Contains(formHost) || (submitHost != null && c.Deny.Contains(submitHost))) { return(false); } if (realm != null && c.Realm != realm) { return(false); } } if (entryUrl != null && (entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://") || title.StartsWith("ftp://") || title.StartsWith("sftp://"))) { var uHost = GetHost(entryUrl); if (formHost.EndsWith(uHost)) { return(true); } } if (title.StartsWith("http://") || title.StartsWith("https://") || title.StartsWith("ftp://") || title.StartsWith("sftp://")) { var uHost = GetHost(title); if (formHost.EndsWith(uHost)) { return(true); } } return(formHost.Contains(title) || (entryUrl != null && formHost.Contains(entryUrl))); }; Func <PwEntry, bool> filterSchemes = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); if (entryUrl != null) { var entryScheme = GetScheme(entryUrl); if (entryScheme == hostScheme) { return(true); } } var titleScheme = GetScheme(title); if (titleScheme == hostScheme) { return(true); } return(false); }; var result = from e in listResult where filter(e.entry) select e; if (configOpt.MatchSchemes) { result = from e in result where filterSchemes(e.entry) select e; } return(result); }
private static string FillRefPlaceholders(string strSeq, PwDatabase pwDatabase, SprContentFlags cf, uint uRecursionLevel, SprRefsCache vRefsCache) { if(pwDatabase == null) return strSeq; string str = strSeq; const string strStart = @"{REF:"; const string strEnd = @"}"; int nOffset = 0; for(int iLoop = 0; iLoop < 20; ++iLoop) { str = SprEngine.FillRefsUsingCache(str, vRefsCache); int nStart = str.IndexOf(strStart, nOffset, SprEngine.ScMethod); if(nStart < 0) break; int nEnd = str.IndexOf(strEnd, nStart, SprEngine.ScMethod); if(nEnd < 0) break; string strFullRef = str.Substring(nStart, nEnd - nStart + 1); string strRef = str.Substring(nStart + strStart.Length, nEnd - nStart - strStart.Length); if(strRef.Length <= 4) { nOffset = nStart + 1; continue; } if(strRef[1] != '@') { nOffset = nStart + 1; continue; } if(strRef[3] != ':') { nOffset = nStart + 1; continue; } char chScan = char.ToUpper(strRef[2]); char chWanted = char.ToUpper(strRef[0]); SearchParameters sp = SearchParameters.None; sp.SearchString = strRef.Substring(4); if(chScan == 'T') sp.SearchInTitles = true; else if(chScan == 'U') sp.SearchInUserNames = true; else if(chScan == 'A') sp.SearchInUrls = true; else if(chScan == 'P') sp.SearchInPasswords = true; else if(chScan == 'N') sp.SearchInNotes = true; else if(chScan == 'I') sp.SearchInUuids = true; else if(chScan == 'O') sp.SearchInOther = true; else { nOffset = nStart + 1; continue; } PwObjectList<PwEntry> lFound = new PwObjectList<PwEntry>(); pwDatabase.RootGroup.SearchEntries(sp, lFound, true); if(lFound.UCount > 0) { PwEntry peFound = lFound.GetAt(0); string strInsData; if(chWanted == 'T') strInsData = peFound.Strings.ReadSafe(PwDefs.TitleField); else if(chWanted == 'U') strInsData = peFound.Strings.ReadSafe(PwDefs.UserNameField); else if(chWanted == 'A') strInsData = peFound.Strings.ReadSafe(PwDefs.UrlField); else if(chWanted == 'P') strInsData = peFound.Strings.ReadSafe(PwDefs.PasswordField); else if(chWanted == 'N') strInsData = peFound.Strings.ReadSafe(PwDefs.NotesField); else if(chWanted == 'I') strInsData = peFound.Uuid.ToHexString(); else { nOffset = nStart + 1; continue; } string strInnerContent = SprEngine.CompileInternal(strInsData, peFound, pwDatabase, null, uRecursionLevel + 1, vRefsCache); strInnerContent = SprEngine.TransformContent(strInnerContent, cf); // str = str.Substring(0, nStart) + strInnerContent + str.Substring(nEnd + 1); SprEngine.AddRefToCache(strFullRef, strInnerContent, vRefsCache); str = SprEngine.FillRefsUsingCache(str, vRefsCache); } else { nOffset = nStart + 1; continue; } } return str; }
// Ported from KeePass Mainform_functions SetListEntry internal static ListViewItem InsertListEntryOLD(PwEntry pe, int iIndex) { // Adapted variables DateTime m_dtCachedNow = DateTime.Now; Font m_fontExpired = FontUtil.CreateFont(m_lvEntries.Font, FontStyle.Strikeout); bool m_bEntryGrouping = m_lvEntries.ShowGroups; bool m_bShowTanIndices = Program.Config.MainWindow.TanView.ShowIndices; bool bSubEntries = Program.Config.MainWindow.ShowEntriesOfSubGroups; ListViewGroup m_lvgLastEntryGroup = null; foreach (ListViewGroup lvg in m_lvEntries.Groups) { if ((lvg.Tag as PwGroup) == pe.ParentGroup) { m_lvgLastEntryGroup = lvg; } } PwGroup pg = (Program.MainForm.GetSelectedGroup()); PwObjectList <PwEntry> pwlSource = ((pg != null) ? pg.GetEntries(bSubEntries) : new PwObjectList <PwEntry>()); bool m_bOnlyTans = ListContainsOnlyTans(pwlSource); ListViewItem lviTarget = null; Color m_clrAlternateItemBgColor = UIUtil.GetAlternateColor(m_lvEntries.BackColor); if (pe == null) { Debug.Assert(false); return(null); } ListViewItem lvi = (lviTarget ?? new ListViewItem()); PwListItem pli = new PwListItem(pe); lvi.Tag = pli; //lvi.BeginUpdate(); if (pe.Expires && (pe.ExpiryTime <= m_dtCachedNow)) { lvi.ImageIndex = (int)PwIcon.Expired; if (m_fontExpired != null) { lvi.Font = m_fontExpired; } } else // Not expired { // Reset font, if item was expired previously (i.e. has expired font) if ((lviTarget != null) && (lvi.ImageIndex == (int)PwIcon.Expired)) { lvi.Font = m_lvEntries.Font; } if (pe.CustomIconUuid.EqualsValue(PwUuid.Zero)) { lvi.ImageIndex = (int)pe.IconId; } else { lvi.ImageIndex = (int)PwIcon.Count + m_host.MainWindow.DocumentManager.ActiveDatabase.GetCustomIconIndex(pe.CustomIconUuid); } } if (m_bEntryGrouping && (lviTarget == null)) { PwGroup pgContainer = pe.ParentGroup; PwGroup pgLast = ((m_lvgLastEntryGroup != null) ? (PwGroup)m_lvgLastEntryGroup.Tag : null); Debug.Assert(pgContainer != null); if (pgContainer != null) { if (pgContainer != pgLast) { m_lvgLastEntryGroup = new ListViewGroup( pgContainer.GetFullPath()); m_lvgLastEntryGroup.Tag = pgContainer; m_lvEntries.Groups.Add(m_lvgLastEntryGroup); } lvi.Group = m_lvgLastEntryGroup; } } if (!pe.ForegroundColor.IsEmpty) { lvi.ForeColor = pe.ForegroundColor; } else if (lviTarget != null) { lvi.ForeColor = m_lvEntries.ForeColor; } else { Debug.Assert(UIUtil.ColorsEqual(lvi.ForeColor, m_lvEntries.ForeColor)); } if (!pe.BackgroundColor.IsEmpty) { lvi.BackColor = pe.BackgroundColor; } // else if(Program.Config.MainWindow.EntryListAlternatingBgColors && // ((m_lvEntries.Items.Count & 1) == 1)) // lvi.BackColor = m_clrAlternateItemBgColor; else if (lviTarget != null) { lvi.BackColor = m_lvEntries.BackColor; } else { Debug.Assert(UIUtil.ColorsEqual(lvi.BackColor, m_lvEntries.BackColor)); } // m_bOnlyTans &= PwDefs.IsTanEntry(pe); if (m_bShowTanIndices && m_bOnlyTans) { string strIndex = pe.Strings.ReadSafe(PwDefs.TanIndexField); if (strIndex.Length > 0) { lvi.Text = strIndex; } else { lvi.Text = PwDefs.TanTitle; } } else { lvi.Text = GetEntryFieldEx(pe, 0, true); } int nColumns = m_lvEntries.Columns.Count; if (lviTarget == null) { for (int iColumn = 1; iColumn < nColumns; ++iColumn) { lvi.SubItems.Add(GetEntryFieldEx(pe, iColumn, true)); } } else { int nSubItems = lvi.SubItems.Count; for (int iColumn = 1; iColumn < nColumns; ++iColumn) { string strSub = GetEntryFieldEx(pe, iColumn, true); if (iColumn < nSubItems) { lvi.SubItems[iColumn].Text = strSub; } else { lvi.SubItems.Add(strSub); } } Debug.Assert(lvi.SubItems.Count == nColumns); } //if (lviTarget == null) m_lvEntries.Items.Add(lvi); if (lviTarget == null) { m_lvEntries.Items.Insert(iIndex, lvi); } UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor, Program.Config.MainWindow.EntryListAlternatingBgColors); //lvi.EndUpdate(); return(lvi); }
public static void ReorderEntriesAsInDatabase(PwObjectList<PwEntry> v, PwDatabase pd) { if((v == null) || (pd == null)) { Debug.Assert(false); return; } if(pd.RootGroup == null) { Debug.Assert(false); return; } // DB must be open PwObjectList<PwEntry> vRem = v.CloneShallow(); v.Clear(); EntryHandler eh = delegate(PwEntry pe) { int p = vRem.IndexOf(pe); if(p >= 0) { v.Add(pe); vRem.RemoveAt((uint)p); } return true; }; pd.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh); foreach(PwEntry peRem in vRem) v.Add(peRem); // Entries not found }
public static string CreateSummaryList(PwGroup pgSubGroups, PwEntry[] vEntries) { int nMaxEntries = 10; string strSummary = string.Empty; if (pgSubGroups != null) { PwObjectList <PwGroup> vGroups = pgSubGroups.GetGroups(true); if (vGroups.UCount > 0) { StringBuilder sbGroups = new StringBuilder(); sbGroups.Append("- "); uint uToList = Math.Min(3U, vGroups.UCount); for (uint u = 0; u < uToList; ++u) { if (sbGroups.Length > 2) { sbGroups.Append(", "); } sbGroups.Append(vGroups.GetAt(u).Name); } if (uToList < vGroups.UCount) { sbGroups.Append(", ..."); } strSummary += sbGroups.ToString(); // New line below nMaxEntries -= 2; } } int nSummaryShow = Math.Min(nMaxEntries, vEntries.Length); if (nSummaryShow == (vEntries.Length - 1)) { --nSummaryShow; // Plural msg } for (int iSumEnum = 0; iSumEnum < nSummaryShow; ++iSumEnum) { if (strSummary.Length > 0) { strSummary += MessageService.NewLine; } PwEntry pe = vEntries[iSumEnum]; strSummary += ("- " + StrUtil.CompactString3Dots( pe.Strings.ReadSafe(PwDefs.TitleField), 39)); if (PwDefs.IsTanEntry(pe)) { string strTanIdx = pe.Strings.ReadSafe(PwDefs.UserNameField); if (!string.IsNullOrEmpty(strTanIdx)) { strSummary += (@" (#" + strTanIdx + @")"); } } } if (nSummaryShow != vEntries.Length) { strSummary += (MessageService.NewLine + "- " + KPRes.MoreEntries.Replace(@"{PARAM}", (vEntries.Length - nSummaryShow).ToString())); } return(strSummary); }
private static void CreateEntry(PwEntry peTemplate) { if(peTemplate == null) { Debug.Assert(false); return; } PwDatabase pd = Program.MainForm.ActiveDatabase; if(pd == null) { Debug.Assert(false); return; } if(pd.IsOpen == false) { Debug.Assert(false); return; } PwGroup pgContainer = Program.MainForm.GetSelectedGroup(); if(pgContainer == null) pgContainer = pd.RootGroup; PwEntry pe = peTemplate.Duplicate(); if(EntryTemplates.EntryCreating != null) EntryTemplates.EntryCreating(null, new TemplateEntryEventArgs( peTemplate.CloneDeep(), pe)); PwEntryForm pef = new PwEntryForm(); pef.InitEx(pe, PwEditMode.AddNewEntry, pd, Program.MainForm.ClientIcons, false, true); if(UIUtil.ShowDialogAndDestroy(pef) == DialogResult.OK) { pgContainer.AddEntry(pe, true, true); MainForm mf = Program.MainForm; if(mf != null) { mf.UpdateUI(false, null, pd.UINeedsIconUpdate, null, true, null, true); PwObjectList<PwEntry> vSelect = new PwObjectList<PwEntry>(); vSelect.Add(pe); mf.SelectEntries(vSelect, true, true); mf.EnsureVisibleEntry(pe.Uuid); mf.UpdateUI(false, null, false, null, false, null, false); } else { Debug.Assert(false); } if(EntryTemplates.EntryCreated != null) EntryTemplates.EntryCreated(null, new TemplateEntryEventArgs( peTemplate.CloneDeep(), pe)); } else Program.MainForm.UpdateUI(false, null, pd.UINeedsIconUpdate, null, pd.UINeedsIconUpdate, null, false); }
private IEnumerable <PwEntryDatabase> FindMatchingEntries(Request r, Aes aes) { string submitHost = null; string realm = null; var listResult = new List <PwEntryDatabase>(); var url = CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT); string formHost, searchHost, submitUrl; formHost = searchHost = GetHost(url); string hostScheme = GetScheme(url); if (r.SubmitUrl != null) { submitUrl = CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT); submitHost = GetHost(submitUrl); } else { submitUrl = url; } if (r.Realm != null) { realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT); } var origSearchHost = searchHost; var parms = MakeSearchParameters(); List <PwDatabase> listDatabases = new List <PwDatabase>(); var configOpt = new ConfigOpt(this.host.CustomConfig); if (configOpt.SearchInAllOpenedDatabases) { foreach (PwDocument doc in host.MainWindow.DocumentManager.Documents) { if (doc.Database.IsOpen) { listDatabases.Add(doc.Database); } } } else { listDatabases.Add(host.Database); } int listCount = 0; foreach (PwDatabase db in listDatabases) { parms.SearchString = ".*"; var listEntries = new PwObjectList <PwEntry>(); db.RootGroup.SearchEntries(parms, listEntries); foreach (var le in listEntries) { listResult.Add(new PwEntryDatabase(le, db)); } listCount = listResult.Count; } searchHost = origSearchHost; List <string> hostNameRegExps = new List <string>(); do { hostNameRegExps.Add(String.Format("^{0}$|/{0}/?", searchHost)); searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1); } while (searchHost.IndexOf(".") != -1); Func <PwEntry, bool> filter = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); var c = GetEntryConfig(e); if (c != null && c.RegExp != null) { try { return(Regex.IsMatch(submitUrl, c.RegExp)); } catch (Exception) { //ignore invalid pattern } } else { bool found = false; foreach (string hostNameRegExp in hostNameRegExps) { if (Regex.IsMatch(e.Strings.ReadSafe("URL"), hostNameRegExp) || Regex.IsMatch(e.Strings.ReadSafe("Title"), hostNameRegExp) || Regex.IsMatch(e.Strings.ReadSafe("Notes"), hostNameRegExp)) { found = true; break; } } if (!found) { return(false); } } if (c != null) { if (c.Allow.Contains(formHost) && (submitHost == null || c.Allow.Contains(submitHost))) { return(true); } if (c.Deny.Contains(formHost) || (submitHost != null && c.Deny.Contains(submitHost))) { return(false); } if (realm != null && c.Realm != realm) { return(false); } } if (entryUrl != null && (entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://") || title.StartsWith("ftp://") || title.StartsWith("sftp://"))) { var uHost = GetHost(entryUrl); if (formHost.EndsWith(uHost)) { return(true); } } if (title.StartsWith("http://") || title.StartsWith("https://") || title.StartsWith("ftp://") || title.StartsWith("sftp://")) { var uHost = GetHost(title); if (formHost.EndsWith(uHost)) { return(true); } } return(formHost.Contains(title) || (entryUrl != null && entryUrl != "" && formHost.Contains(entryUrl))); }; Func <PwEntry, bool> filterSchemes = delegate(PwEntry e) { var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); if (entryUrl != null) { var entryScheme = GetScheme(entryUrl); if (entryScheme == hostScheme) { return(true); } } var titleScheme = GetScheme(title); if (titleScheme == hostScheme) { return(true); } return(false); }; var result = from e in listResult where filter(e.entry) select e; if (configOpt.MatchSchemes) { result = from e in result where filterSchemes(e.entry) select e; } Func <PwEntry, bool> hideExpired = delegate(PwEntry e) { DateTime dtNow = DateTime.UtcNow; if (e.Expires && (e.ExpiryTime <= dtNow)) { return(false); } return(true); }; if (configOpt.HideExpired) { result = from e in result where hideExpired(e.entry) select e; } return(result); }