private static void ImportRecord(Node<BaseRecord> currentNode, PwGroup groupAddTo, PwDatabase pwStorage) { BaseRecord record = currentNode.AssociatedObject; if (record.GetType() == typeof(FolderRecord)) { FolderRecord folderRecord = (FolderRecord)record; var folder = CreateFolder(groupAddTo, folderRecord); foreach (var node in currentNode.Nodes) { ImportRecord(node, folder, pwStorage); } } else if (record.GetType() == typeof(WebFormRecord)) { WebFormRecord webForm = (WebFormRecord)record; CreateWebForm(groupAddTo, pwStorage, webForm); } else if (record.GetType() == typeof(BaseRecord)) { //Trace.WriteLine(String.Format("Error. Can't import unknown record type: {0}", record.RawJson)); } else if (record.GetType() == typeof(UnknownRecord)) { //CreateUnknown(groupAddTo, pwStorage, record as UnknownRecord); } }
public void InitEx(PwGroup pgDataSource, bool bPrintMode) { Debug.Assert(pgDataSource != null); if(pgDataSource == null) throw new ArgumentNullException("pgDataSource"); m_pgDataSource = pgDataSource; m_bPrintMode = bPrintMode; }
public void InitEx(PwGroup pgEntrySource, ImageList ilClientIcons, string strDefaultRef) { m_pgEntrySource = pgEntrySource; m_ilIcons = ilClientIcons; m_strDefaultRef = (strDefaultRef ?? string.Empty); }
public GxiContext ModifyWith(PwGroup pg) { GxiContext c = (GxiContext)MemberwiseClone(); Debug.Assert(object.ReferenceEquals(c.m_dStringKeyRepl, m_dStringKeyRepl)); c.m_pg = pg; return c; }
public MoveElement(IStructureItem elementToMove, PwGroup targetGroup, Context ctx, IKp2aApp app, OnFinish finish) : base(finish) { _elementToMove = elementToMove; _targetGroup = targetGroup; _ctx = ctx; _app = app; }
public static string CreateSummaryList(PwGroup pgItems, bool bStartWithNewPar) { List<PwEntry> l = pgItems.GetEntries(true).CloneShallowToList(); string str = CreateSummaryList(pgItems, l.ToArray()); if((str.Length == 0) || !bStartWithNewPar) return str; return (MessageService.NewParagraph + str); }
public void InitEx(PwGroup pgDataSource, bool bPrintMode, int nDefaultSortColumn) { Debug.Assert(pgDataSource != null); if(pgDataSource == null) throw new ArgumentNullException("pgDataSource"); m_pgDataSource = pgDataSource; m_bPrintMode = bPrintMode; m_nDefaultSortColumn = nDefaultSortColumn; }
public void InitEx(PwGroup pg, bool bCreatingNew, ImageList ilClientIcons, PwDatabase pwDatabase) { m_pwGroup = pg; m_bCreatingNew = bCreatingNew; m_ilClientIcons = ilClientIcons; m_pwDatabase = pwDatabase; }
// public void Save(string strFile, PwGroup pgDataSource, KdbxFormat format, // IStatusLogger slLogger) // { // bool bMadeUnhidden = UrlUtil.UnhideFile(strFile); // // IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); // this.Save(IOConnection.OpenWrite(ioc), pgDataSource, format, slLogger); // // if(bMadeUnhidden) UrlUtil.HideFile(strFile, true); // Hide again // } /// <summary> /// Save the contents of the current <c>PwDatabase</c> to a KDBX file. /// </summary> /// <param name="sSaveTo">Stream to write the KDBX file into.</param> /// <param name="pgDataSource">Group containing all groups and /// entries to write. If <c>null</c>, the complete database will /// be written.</param> /// <param name="format">Format of the file to create.</param> /// <param name="slLogger">Logger that recieves status information.</param> public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat format, IStatusLogger slLogger) { Debug.Assert(sSaveTo != null); if(sSaveTo == null) throw new ArgumentNullException("sSaveTo"); m_format = format; m_slLogger = slLogger; HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo, true, null); UTF8Encoding encNoBom = StrUtil.Utf8; CryptoRandom cr = CryptoRandom.Instance; try { m_pbMasterSeed = cr.GetRandomBytes(32); m_pbTransformSeed = cr.GetRandomBytes(32); m_pbEncryptionIV = cr.GetRandomBytes(16); m_pbProtectedStreamKey = cr.GetRandomBytes(32); m_craInnerRandomStream = CrsAlgorithm.Salsa20; m_randomStream = new CryptoRandomStream(m_craInnerRandomStream, m_pbProtectedStreamKey); m_pbStreamStartBytes = cr.GetRandomBytes(32); Stream writerStream; if(m_format == KdbxFormat.Default) { WriteHeader(hashedStream); // Also flushes the stream Stream sEncrypted = AttachStreamEncryptor(hashedStream); if((sEncrypted == null) || (sEncrypted == hashedStream)) throw new SecurityException(KLRes.CryptoStreamFailed); sEncrypted.Write(m_pbStreamStartBytes, 0, m_pbStreamStartBytes.Length); Stream sHashed = new HashedBlockStream(sEncrypted, true); if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip) writerStream = new GZipStream(sHashed, CompressionMode.Compress); else writerStream = sHashed; } else if(m_format == KdbxFormat.PlainXml) writerStream = hashedStream; else { Debug.Assert(false); throw new FormatException("KdbFormat"); } m_xmlWriter = new XmlTextWriter(writerStream, encNoBom); WriteDocument(pgDataSource); m_xmlWriter.Flush(); m_xmlWriter.Close(); writerStream.Close(); } finally { CommonCleanUpWrite(sSaveTo, hashedStream); } }
public static void Launch(Activity act, PwGroup parentGroup) { Intent i = new Intent(act, typeof(GroupEditActivity)); PwGroup parent = parentGroup; i.PutExtra(KeyParent, parent.Uuid.ToHexString()); act.StartActivityForResult(i, 0); }
public static string GetGroupPath(PwGroup group) { string path = GetGroupPathRec(group); if (path.Length > 0) { return path; } else { return "(Root)"; } }
private void AddProduct(PwDatabase database, PwGroup group, Product product) { var productGroup = group.FindCreateGroup(product.Name, true); foreach (var key in product.Keys) { if(!GroupContainsKeyAsPassword(productGroup,key)) AddKey(database, productGroup, key); } }
private void AddKey(PwDatabase database, PwGroup group, Key key) { var entry = new PwEntry(true, true); group.AddEntry(entry, true); entry.Strings.Set(PwDefs.TitleField, new ProtectedString(database.MemoryProtection.ProtectTitle, key.Type)); entry.Strings.Set(PwDefs.PasswordField, new ProtectedString(database.MemoryProtection.ProtectPassword, key.Value)); entry.Strings.Set(PwDefs.NotesField, new ProtectedString(database.MemoryProtection.ProtectNotes, key.Description)); }
protected AddEntry(Context ctx, IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnFinish finish) : base(finish) { _ctx = ctx; _parentGroup = parentGroup; _app = app; _entry = entry; _onFinishToRun = new AfterAdd(app.GetDb(), entry, OnFinishToRun); }
private static string GetGroupPathRec(PwGroup group) { if (group.ParentGroup != null) { string parent = GetGroupPathRec(group.ParentGroup); return parent + (parent.Length > 0 ? "/" : "") + group.Name; } else { // Empty, because we don't need the name of DB in path, which is the root. return ""; } }
public Search(PwGroup rootGroup) { this.rootGroup = rootGroup; this.SearchInTitle = Settings.Default.SearchInTitle; this.SearchInUrl = Settings.Default.SearchInUrl; this.SearchInUserName = Settings.Default.SearchInUserName; this.SearchInNotes = Settings.Default.SearchInNotes; this.SearchInPassword = Settings.Default.SearchInPassword; this.searchInOther = Settings.Default.SearchInOther; }
private void ConstructEx(PwGroup pgDataSource, PwDatabase pwContextInfo, bool? bExportDeleted) { if(pgDataSource == null) throw new ArgumentNullException("pgDataSource"); // pwContextInfo may be null m_pg = pgDataSource; m_pd = pwContextInfo; if(bExportDeleted.HasValue) m_bExpDel = bExportDeleted.Value; }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { StreamReader sr = new StreamReader(sInput, Encoding.Default); string strData = sr.ReadToEnd(); sr.Close(); strData = strData.Replace("\r", string.Empty); string[] vLines = strData.Split(new char[] { '\n' }); PwGroup pg = pwStorage.RootGroup; Dictionary<string, string> dItems = new Dictionary<string, string>(); bool bInNotes = false; foreach(string strLine in vLines) { if(strLine.StartsWith(StrGroupStart) && strLine.EndsWith(StrGroupEnd)) { AddEntry(pg, dItems, ref bInNotes); dItems.Clear(); pg = new PwGroup(true, true); pg.Name = strLine.Substring(StrGroupStart.Length, strLine.Length - StrGroupStart.Length - StrGroupEnd.Length); pwStorage.RootGroup.AddGroup(pg, true); } else if(strLine.StartsWith(StrEntryStart) && strLine.EndsWith(StrEntryEnd)) { AddEntry(pg, dItems, ref bInNotes); dItems.Clear(); } else if(strLine == StrNotesBegin) bInNotes = true; else if(bInNotes) { if(dItems.ContainsKey(PwDefs.NotesField)) dItems[PwDefs.NotesField] += MessageService.NewLine + strLine; else dItems[PwDefs.NotesField] = strLine; } else { int nSplitPos = strLine.IndexOf(StrFieldSplit); if(nSplitPos < 0) { Debug.Assert(false); } else { AddField(dItems, strLine.Substring(0, nSplitPos), strLine.Substring(nSplitPos + StrFieldSplit.Length)); } } } AddEntry(pg, dItems, ref bInNotes); }
public override void AttachToGroupDialog(KeePassRPCExt plugin, PwGroup group, TabControl mainTabControl) { KeeFoxGroupUserControl groupControl = new KeeFoxGroupUserControl(plugin, group); TabPage keefoxTabPage = new TabPage("KeeFox"); groupControl.Dock = DockStyle.Fill; keefoxTabPage.Controls.Add(groupControl); if (mainTabControl.ImageList == null) mainTabControl.ImageList = new ImageList(); int imageIndex = mainTabControl.ImageList.Images.Add(global::KeePassRPC.Properties.Resources.KeeFox16, Color.Transparent); keefoxTabPage.ImageIndex = imageIndex; mainTabControl.TabPages.Add(keefoxTabPage); }
private AddGroup(Context ctx, IKp2aApp app, String name, int iconid, PwGroup parent, OnFinish finish, bool dontSave) : base(finish) { _ctx = ctx; _name = name; _iconId = iconid; Parent = parent; DontSave = dontSave; _app = app; _onFinishToRun = new AfterAdd(this, OnFinishToRun); }
public override void Run() { StatusLogger.UpdateMessage(UiStringKey.AddingGroup); // Generate new group Group = new PwGroup(true, true, _name, (PwIcon)_iconId); Parent.AddGroup(Group, true); // Commit to disk SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, DontSave); save.SetStatusLogger(StatusLogger); save.Run(); }
public GxiContext(GxiProfile p, PwDatabase pd, PwGroup pg, PwEntry pe) { m_pd = pd; m_pg = pg; m_pe = pe; m_dStringKeyRepl = GxiImporter.ParseRepl(p.StringKeyRepl); m_dStringValueRepl = GxiImporter.ParseRepl(p.StringValueRepl); m_dStringKeyRepl2 = GxiImporter.ParseRepl(p.StringKeyRepl2); m_dStringValueRepl2 = GxiImporter.ParseRepl(p.StringValueRepl2); m_dBinaryKeyRepl = GxiImporter.ParseRepl(p.BinaryKeyRepl); }
private void add_sub_groups(PwGroup group, int level, string cur_item_uuid) { PwObjectList<PwGroup> groups = group.GetGroups(false); foreach (PwGroup sub_group in groups) { StartGroupDropdown item = new StartGroupDropdown(sub_group.Uuid.ToHexString(), sub_group.Name, level + 1); if (sub_group.Uuid.ToHexString() == cur_item_uuid) drop_cur_item = item; drop_items.Add(item); add_sub_groups(sub_group, level + 1, cur_item_uuid); } }
public EditGroup(Context ctx, IKp2aApp app, String name, PwIcon iconid, PwUuid customIconId, PwGroup group, OnFinish finish) : base(finish) { _ctx = ctx; _name = name; _iconId = iconid; Group = group; _customIconId = customIconId; _app = app; _onFinishToRun = new AfterEdit(this, OnFinishToRun); }
public static PwDatabase CreateDatabase(string recyclerName = "") { var database = new PwDatabase(); database.RootGroup = new PwGroup(true, true); database.RootGroup.Name = "RootGroup"; if( recyclerName != "") { var trash = new PwGroup(true, true, recyclerName, PwIcon.TrashBin); database.RootGroup.AddGroup(trash, true); database.RecycleBinUuid = trash.Uuid; } return database; }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { string str = PwMemory2008Xml104.Preprocess(sInput); MemoryStream ms = new MemoryStream(StrUtil.Utf8.GetBytes(str), false); XmlSerializer xs = new XmlSerializer(typeof(Priv_PwMem2008XmlFile)); Priv_PwMem2008XmlFile f = (Priv_PwMem2008XmlFile)xs.Deserialize(ms); ms.Close(); if((f == null) || (f.Cells == null)) return; Dictionary<string, PwGroup> vGroups = new Dictionary<string, PwGroup>(); for(int iLine = 2; iLine < f.Cells.Length; ++iLine) { string[] vCells = f.Cells[iLine]; if((vCells == null) || (vCells.Length != 6)) continue; if((vCells[1] == null) || (vCells[2] == null) || (vCells[3] == null) || (vCells[4] == null)) continue; string strGroup = vCells[4]; PwGroup pg; if(strGroup == ".") pg = pwStorage.RootGroup; else if(vGroups.ContainsKey(strGroup)) pg = vGroups[strGroup]; else { pg = new PwGroup(true, true); pg.Name = strGroup; pwStorage.RootGroup.AddGroup(pg, true); vGroups[strGroup] = pg; } PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); if(vCells[1] != ".") pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, vCells[1])); if(vCells[2] != ".") pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, vCells[2])); if(vCells[3] != ".") pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, vCells[3])); } }
/// <summary> /// recursuve search for a group /// </summary> /// <param name="group"></param> /// <param name="groupName"></param> /// <returns></returns> public static PwGroup FindGroup(PwGroup group, string groupName) { if (group.Name == groupName) return group; // Check each child group using recursion foreach (PwGroup subGroup in group.Groups) { PwGroup subSubGroup = FindGroup(subGroup, groupName); if (subSubGroup != null) return subSubGroup; } return null; }
private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage) { PwGroup pg = new PwGroup(true, true); pgParent.AddGroup(pg, true); foreach(XmlNode xmlChild in xmlNode) { if(xmlChild.Name == ElemGroupName) pg.Name = XmlUtil.SafeInnerText(xmlChild); else if(xmlChild.Name == ElemGroup) ReadGroup(xmlChild, pg, pwStorage); else if(xmlChild.Name == ElemEntry) ReadEntry(xmlChild, pg, pwStorage); else { Debug.Assert(false); } } }
public PwGroup Search(Database database, SearchParameters sp, IDictionary<PwUuid, KeyValuePair<string, string>> resultContexts) { if(sp.RegularExpression) // Validate regular expression { new Regex(sp.SearchString); } string strGroupName = _app.GetResourceString(UiStringKey.search_results) + " (\"" + sp.SearchString + "\")"; PwGroup pgResults = new PwGroup(true, true, strGroupName, PwIcon.EMailSearch) {IsVirtual = true}; PwObjectList<PwEntry> listResults = pgResults.Entries; database.Root.SearchEntries(sp, listResults, resultContexts, new NullStatusLogger()); return pgResults; }
public void performSearch(PwGroup pwGroup, BackgroundWorker worker) { Debug.WriteLine("Starting a new Search in Group"); Stopwatch sw = Stopwatch.StartNew(); if (pwGroup != null) { searchInList(pwGroup.Entries, worker); foreach (PwGroup group in pwGroup.Groups) { this.performSearch(group, worker); } } Debug.WriteLine("End of Search in Group. Worker cancelled: " + worker.CancellationPending + ". elapsed Ticks: " + sw.ElapsedTicks.ToString() + " elapsed ms: " + sw.ElapsedMilliseconds); }
private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage) { PwEntry pe = new PwEntry(true, true); pgParent.AddEntry(pe, true); DateTime dt; foreach (XmlNode xmlChild in xmlNode) { if (xmlChild.Name == ElemEntryName) { pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, XmlUtil.SafeInnerText(xmlChild))); } else if (xmlChild.Name == ElemEntryType) { pe.IconId = ((XmlUtil.SafeInnerText(xmlChild) != "1") ? PwIcon.Key : PwIcon.PaperNew); } else if (xmlChild.Name == ElemEntryUser) { pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, XmlUtil.SafeInnerText(xmlChild))); } else if (xmlChild.Name == ElemEntryPassword) { pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, XmlUtil.SafeInnerText(xmlChild))); } else if (xmlChild.Name == ElemEntryURL) { pe.Strings.Set(PwDefs.UrlField, new ProtectedString( pwStorage.MemoryProtection.ProtectUrl, XmlUtil.SafeInnerText(xmlChild))); } else if (xmlChild.Name == ElemEntryNotes) { pe.Strings.Set(PwDefs.NotesField, new ProtectedString( pwStorage.MemoryProtection.ProtectNotes, XmlUtil.SafeInnerText(xmlChild))); } else if (xmlChild.Name == ElemEntryCreationTime) { if (ParseDate(xmlChild, out dt)) { pe.CreationTime = dt; } } else if (xmlChild.Name == ElemEntryLastModTime) { if (ParseDate(xmlChild, out dt)) { pe.LastModificationTime = dt; } } else if (xmlChild.Name == ElemEntryExpireTime) { if (ParseDate(xmlChild, out dt)) { pe.ExpiryTime = dt; pe.Expires = true; } } else { Debug.Assert(false); } } }
public static bool WriteEntries(Stream msOutput, PwDatabase pdContext, PwEntry[] vEntries) { if (msOutput == null) { Debug.Assert(false); return(false); } // pdContext may be null if (vEntries == null) { Debug.Assert(false); return(false); } /* KdbxFile f = new KdbxFile(pwDatabase); * f.m_format = KdbxFormat.PlainXml; * * XmlTextWriter xtw = null; * try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); } * catch(Exception) { Debug.Assert(false); return false; } * if(xtw == null) { Debug.Assert(false); return false; } * * f.m_xmlWriter = xtw; * * xtw.Formatting = Formatting.Indented; * xtw.IndentChar = '\t'; * xtw.Indentation = 1; * * xtw.WriteStartDocument(true); * xtw.WriteStartElement(ElemRoot); * * foreach(PwEntry pe in vEntries) * f.WriteEntry(pe, false); * * xtw.WriteEndElement(); * xtw.WriteEndDocument(); * * xtw.Flush(); * xtw.Close(); * return true; */ PwDatabase pd = new PwDatabase(); pd.New(new IOConnectionInfo(), new CompositeKey()); PwGroup pg = pd.RootGroup; if (pg == null) { Debug.Assert(false); return(false); } foreach (PwEntry pe in vEntries) { PwUuid pu = pe.CustomIconUuid; if (!pu.Equals(PwUuid.Zero) && (pd.GetCustomIconIndex(pu) < 0)) { int i = -1; if (pdContext != null) { i = pdContext.GetCustomIconIndex(pu); } if (i >= 0) { PwCustomIcon ci = pdContext.CustomIcons[i]; pd.CustomIcons.Add(ci); } else { Debug.Assert(pdContext == null); } } PwEntry peCopy = pe.CloneDeep(); pg.AddEntry(peCopy, true); } KdbxFile f = new KdbxFile(pd); f.Save(msOutput, null, KdbxFormat.PlainXml, null); return(true); }
private string GenerateHtmlDocument(bool bTemporary) { PwGroup pgDataSource = m_pgDataSource.CloneDeep(); // Sorting, ... int nSortEntries = m_cmbSortEntries.SelectedIndex; string strSortFieldName = null; if (nSortEntries == 0) { } // No sort else if (nSortEntries == 1) { strSortFieldName = PwDefs.TitleField; } else if (nSortEntries == 2) { strSortFieldName = PwDefs.UserNameField; } else if (nSortEntries == 3) { strSortFieldName = PwDefs.PasswordField; } else if (nSortEntries == 4) { strSortFieldName = PwDefs.UrlField; } else if (nSortEntries == 5) { strSortFieldName = PwDefs.NotesField; } else { Debug.Assert(false); } if (strSortFieldName != null) { SortGroupEntriesRecursive(pgDataSource, strSortFieldName); } bool bGroup = m_cbGroups.Checked; bool bTitle = m_cbTitle.Checked, bUserName = m_cbUser.Checked; bool bPassword = m_cbPassword.Checked, bUrl = m_cbUrl.Checked; bool bNotes = m_cbNotes.Checked; bool bCreation = m_cbCreation.Checked, bLastMod = m_cbLastMod.Checked; // bool bLastAcc = m_cbLastAccess.Checked; bool bExpire = m_cbExpire.Checked; bool bAutoType = m_cbAutoType.Checked; bool bTags = m_cbTags.Checked; bool bCustomStrings = m_cbCustomStrings.Checked; bool bUuid = m_cbUuid.Checked; PfOptions p = new PfOptions(); p.MonoPasswords = m_cbMonospaceForPasswords.Checked; if (m_rbMonospace.Checked) { p.MonoPasswords = false; // Monospace anyway } p.SmallMono = m_cbSmallMono.Checked; p.SprMode = m_cmbSpr.SelectedIndex; p.Rtl = (this.RightToLeft == RightToLeft.Yes); p.Database = m_pdContext; if (m_cbIcon.Checked) { p.ClientIcons = m_ilClientIcons; } if (m_rbSerif.Checked) { p.FontInit = "<span class=\"fserif\">"; p.FontExit = "</span>"; } else if (m_rbSansSerif.Checked) { p.FontInit = string.Empty; p.FontExit = string.Empty; } else if (m_rbMonospace.Checked) { p.FontInit = (p.SmallMono ? "<code><small>" : "<code>"); p.FontExit = (p.SmallMono ? "</small></code>" : "</code>"); } else { Debug.Assert(false); } GFunc <string, string> h = new GFunc <string, string>(StrUtil.StringToHtml); GFunc <string, string> c = delegate(string strRaw) { return(CompileText(strRaw, p, true, false)); }; GFunc <string, string> cs = delegate(string strRaw) { return(CompileText(strRaw, p, true, true)); }; StringBuilder sb = new StringBuilder(); sb.AppendLine("<!DOCTYPE html>"); sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\""); string strLang = Program.Translation.Properties.Iso6391Code; if (string.IsNullOrEmpty(strLang)) { strLang = "en"; } strLang = h(strLang); sb.Append(" xml:lang=\"" + strLang + "\" lang=\"" + strLang + "\""); if (p.Rtl) { sb.Append(" dir=\"rtl\""); } sb.AppendLine(">"); sb.AppendLine("<head>"); sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); sb.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />"); sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />"); sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />"); sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />"); sb.Append("<title>"); sb.Append(h(pgDataSource.Name)); sb.AppendLine("</title>"); sb.AppendLine("<style type=\"text/css\">"); sb.AppendLine("/* <![CDATA[ */"); sb.AppendLine("body {"); sb.AppendLine("\tcolor: #000000;"); sb.AppendLine("\tbackground-color: #FFFFFF;"); sb.AppendLine("\tfont-family: \"Tahoma\", \"MS Sans Serif\", \"Sans Serif\", \"Verdana\", sans-serif;"); sb.AppendLine("\tfont-size: 10pt;"); sb.AppendLine("}"); sb.AppendLine("h2 {"); sb.AppendLine("\tcolor: #000000;"); sb.AppendLine("\tbackground-color: #D0D0D0;"); sb.AppendLine("\tpadding-left: 2pt;"); sb.AppendLine("\tpadding-right: 2pt;"); // RTL support sb.AppendLine("}"); sb.AppendLine("h3 {"); sb.AppendLine("\tcolor: #000000;"); sb.AppendLine("\tbackground-color: #D0D0D0;"); sb.AppendLine("\tpadding-left: 2pt;"); sb.AppendLine("\tpadding-right: 2pt;"); // RTL support sb.AppendLine("}"); sb.AppendLine("table, th, td {"); sb.AppendLine("\tborder: 0px none;"); sb.AppendLine("\tborder-collapse: collapse;"); sb.AppendLine("}"); sb.AppendLine("table {"); sb.AppendLine("\twidth: 100%;"); sb.AppendLine("\ttable-layout: fixed;"); sb.AppendLine("\tempty-cells: show;"); sb.AppendLine("}"); sb.AppendLine("th, td {"); sb.AppendLine("\ttext-align: " + (p.Rtl ? "right;" : "left;")); sb.AppendLine("\tvertical-align: top;"); sb.AppendLine("}"); sb.AppendLine("th {"); sb.AppendLine("\tfont-weight: bold;"); sb.AppendLine("}"); sb.AppendLine("a {"); sb.AppendLine("\tcolor: #0000DD;"); sb.AppendLine("\ttext-decoration: none;"); sb.AppendLine("}"); sb.AppendLine("a:hover, a:active {"); sb.AppendLine("\tcolor: #6699FF;"); sb.AppendLine("\ttext-decoration: underline;"); sb.AppendLine("}"); sb.AppendLine(".field_name {"); sb.AppendLine("\t-webkit-hyphens: auto;"); sb.AppendLine("\t-moz-hyphens: auto;"); sb.AppendLine("\t-ms-hyphens: auto;"); sb.AppendLine("\thyphens: auto;"); sb.AppendLine("}"); sb.AppendLine(".field_data {"); // sb.AppendLine("\tword-break: break-all;"); sb.AppendLine("\toverflow-wrap: break-word;"); sb.AppendLine("\tword-wrap: break-word;"); sb.AppendLine("}"); sb.AppendLine(".fserif {"); sb.AppendLine("\tfont-family: \"Times New Roman\", serif;"); sb.AppendLine("}"); sb.AppendLine(".icon_cli {"); sb.AppendLine("\tdisplay: inline-block;"); sb.AppendLine("\tmargin: 0px 0px 0px 0px;"); sb.AppendLine("\tpadding: 0px 0px 0px 0px;"); sb.AppendLine("\tborder: 0px none;"); sb.AppendLine("\twidth: 1.1em;"); sb.AppendLine("\theight: 1.1em;"); sb.AppendLine("\tvertical-align: top;"); sb.AppendLine("}"); if (bTemporary) { // Add the temporary content identifier sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {"); sb.AppendLine("\tfont-size: 10pt;"); sb.AppendLine("}"); } sb.AppendLine("/* ]]> */"); sb.AppendLine("</style>"); sb.AppendLine("</head><body>"); sb.AppendLine("<h2>" + h(pgDataSource.Name) + "</h2>"); WriteGroupNotes(sb, pgDataSource); EntryHandler ehInit = delegate(PwEntry pe) { p.Entry = pe; if (p.SprMode != 0) { p.SprContext = new SprContext(pe, p.Database, SprCompileFlags.NonActive, false, false); } else { Debug.Assert(p.SprContext == null); } Application.DoEvents(); return(true); }; EntryHandler eh = null; string strTableInit = "<table>"; PwGroup pgLast = null; if (m_rbTabular.Checked) { int nEquiCols = 0; if (bGroup) { ++nEquiCols; } if (bTitle) { ++nEquiCols; } if (bUserName) { ++nEquiCols; } if (bPassword) { ++nEquiCols; } if (bUrl) { ++nEquiCols; } if (bNotes) { nEquiCols += 2; } if (bCreation) { ++nEquiCols; } // if(bLastAcc) ++nEquiCols; if (bLastMod) { ++nEquiCols; } if (bExpire) { ++nEquiCols; } if (bTags) { ++nEquiCols; } if (bUuid) { ++nEquiCols; } if (nEquiCols == 0) { nEquiCols = 1; } string strColWidth = (100.0f / (float)nEquiCols).ToString( "F2", NumberFormatInfo.InvariantInfo); string strColWidth2 = (200.0f / (float)nEquiCols).ToString( "F2", NumberFormatInfo.InvariantInfo); string strHTdInit = "<th class=\"field_name\" style=\"width: " + strColWidth + "%;\">"; string strHTdInit2 = "<th class=\"field_name\" style=\"width: " + strColWidth2 + "%;\">"; string strHTdExit = "</th>"; string strDataTdInit = "<td class=\"field_data\">"; string strDataTdExit = "</td>"; p.CellInit = strDataTdInit + p.FontInit; p.CellExit = p.FontExit + strDataTdExit; StringBuilder sbH = new StringBuilder(); sbH.AppendLine(); sbH.Append("<tr>"); if (bGroup) { sbH.AppendLine(strHTdInit + h(KPRes.Group) + strHTdExit); } if (bTitle) { sbH.AppendLine(strHTdInit + h(KPRes.Title) + strHTdExit); } if (bUserName) { sbH.AppendLine(strHTdInit + h(KPRes.UserName) + strHTdExit); } if (bPassword) { sbH.AppendLine(strHTdInit + h(KPRes.Password) + strHTdExit); } if (bUrl) { sbH.AppendLine(strHTdInit + h(KPRes.Url) + strHTdExit); } if (bNotes) { sbH.AppendLine(strHTdInit2 + h(KPRes.Notes) + strHTdExit); } if (bCreation) { sbH.AppendLine(strHTdInit + h(KPRes.CreationTime) + strHTdExit); } // if(bLastAcc) sbH.AppendLine(strHTdInit + h(KPRes.LastAccessTime) + strHTdExit); if (bLastMod) { sbH.AppendLine(strHTdInit + h(KPRes.LastModificationTime) + strHTdExit); } if (bExpire) { sbH.AppendLine(strHTdInit + h(KPRes.ExpiryTime) + strHTdExit); } if (bTags) { sbH.AppendLine(strHTdInit + h(KPRes.Tags) + strHTdExit); } if (bUuid) { sbH.AppendLine(strHTdInit + h(KPRes.Uuid) + strHTdExit); } sbH.Append("</tr>"); // No terminating \r\n strTableInit += sbH.ToString(); sb.AppendLine(strTableInit); eh = delegate(PwEntry pe) { ehInit(pe); sb.AppendLine("<tr>"); WriteTabularIf(bGroup, sb, c(pe.ParentGroup.Name), p); WriteTabularIf(bTitle, sb, pe, PwDefs.TitleField, p); WriteTabularIf(bUserName, sb, pe, PwDefs.UserNameField, p); if (bPassword) { if (p.MonoPasswords) { sb.Append(strDataTdInit + (p.SmallMono ? "<code><small>" : "<code>")); } else { sb.Append(p.CellInit); } string strInner = cs(pe.Strings.ReadSafe(PwDefs.PasswordField)); if (strInner.Length == 0) { strInner = " "; } sb.Append(strInner); if (p.MonoPasswords) { sb.AppendLine((p.SmallMono ? "</small></code>" : "</code>") + strDataTdExit); } else { sb.AppendLine(p.CellExit); } } // WriteTabularIf(bUrl, sb, pe, PwDefs.UrlField, p); WriteTabularIf(bUrl, sb, MakeUrlLink(pe.Strings.ReadSafe( PwDefs.UrlField), p), p); WriteTabularIf(bNotes, sb, pe, PwDefs.NotesField, p); WriteTabularIf(bCreation, sb, h(TimeUtil.ToDisplayString( pe.CreationTime)), p); // WriteTabularIf(bLastAcc, sb, h(TimeUtil.ToDisplayString( // pe.LastAccessTime)), p); WriteTabularIf(bLastMod, sb, h(TimeUtil.ToDisplayString( pe.LastModificationTime)), p); WriteTabularIf(bExpire, sb, h(pe.Expires ? TimeUtil.ToDisplayString( pe.ExpiryTime) : KPRes.NeverExpires), p); WriteTabularIf(bTags, sb, h(StrUtil.TagsToString(pe.Tags, true)), p); WriteTabularIf(bUuid, sb, pe.Uuid.ToHexString(), p); sb.AppendLine("</tr>"); return(true); }; } else if (m_rbDetails.Checked) { sb.AppendLine(strTableInit); if (pgDataSource.Entries.UCount == 0) { sb.AppendLine(@"<tr><td> </td></tr>"); } eh = delegate(PwEntry pe) { ehInit(pe); if ((pgLast != null) && (pgLast == pe.ParentGroup)) { sb.AppendLine("<tr><td colspan=\"2\"><hr /></td></tr>"); } if (bGroup) { WriteDetailsLine(sb, KPRes.Group, pe.ParentGroup.Name, p); } if (bTitle) { PfOptions pSub = p.CloneShallow(); pSub.FontInit = MakeIconImg(pe.IconId, pe.CustomIconUuid, pe, p) + pSub.FontInit + "<b>"; pSub.FontExit = "</b>" + pSub.FontExit; WriteDetailsLine(sb, KPRes.Title, pe.Strings.ReadSafe( PwDefs.TitleField), pSub); } if (bUserName) { WriteDetailsLine(sb, KPRes.UserName, pe.Strings.ReadSafe( PwDefs.UserNameField), p); } if (bPassword) { WriteDetailsLine(sb, KPRes.Password, pe.Strings.ReadSafe( PwDefs.PasswordField), p); } if (bUrl) { WriteDetailsLine(sb, KPRes.Url, pe.Strings.ReadSafe( PwDefs.UrlField), p); } if (bNotes) { WriteDetailsLine(sb, KPRes.Notes, pe.Strings.ReadSafe( PwDefs.NotesField), p); } if (bCreation) { WriteDetailsLine(sb, KPRes.CreationTime, TimeUtil.ToDisplayString( pe.CreationTime), p); } // if(bLastAcc) WriteDetailsLine(sb, KPRes.LastAccessTime, TimeUtil.ToDisplayString( // pe.LastAccessTime), p); if (bLastMod) { WriteDetailsLine(sb, KPRes.LastModificationTime, TimeUtil.ToDisplayString( pe.LastModificationTime), p); } if (bExpire) { WriteDetailsLine(sb, KPRes.ExpiryTime, (pe.Expires ? TimeUtil.ToDisplayString( pe.ExpiryTime) : KPRes.NeverExpires), p); } if (bAutoType) { foreach (AutoTypeAssociation a in pe.AutoType.Associations) { WriteDetailsLine(sb, KPRes.AutoType, a.WindowName + ": " + a.Sequence, p); } } if (bTags) { WriteDetailsLine(sb, KPRes.Tags, StrUtil.TagsToString( pe.Tags, true), p); } if (bUuid) { WriteDetailsLine(sb, KPRes.Uuid, pe.Uuid.ToHexString(), p); } foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings) { if (bCustomStrings && !PwDefs.IsStandardField(kvp.Key)) { WriteDetailsLine(sb, kvp, p); } } pgLast = pe.ParentGroup; return(true); }; } else { Debug.Assert(false); } GroupHandler gh = delegate(PwGroup pg) { if (pg.Entries.UCount == 0) { return(true); } sb.Append("</table><br /><h3>"); // "</table><br /><hr /><h3>" // sb.Append(MakeIconImg(pg.IconId, pg.CustomIconUuid, pg, p)); sb.Append(h(pg.GetFullPath(" - ", false))); sb.AppendLine("</h3>"); WriteGroupNotes(sb, pg); sb.AppendLine(strTableInit); return(true); }; pgDataSource.TraverseTree(TraversalMethod.PreOrder, gh, eh); if (m_rbTabular.Checked) { sb.AppendLine("</table>"); } else if (m_rbDetails.Checked) { sb.AppendLine("</table><br />"); } sb.AppendLine("</body></html>"); string strDoc = sb.ToString(); #if DEBUG XmlUtilEx.ValidateXml(strDoc, true); #endif return(strDoc); }
public PwGroupEntryListBuffer(PwGroup group) : base(group.Entries) { mGroup = group; }
private static void AddEntry(string[] vLine, PwDatabase pd) { Debug.Assert((vLine.Length == 0) || (vLine.Length == 7)); if (vLine.Length < 5) { return; } // Skip header line if ((vLine[1] == "username") && (vLine[2] == "password") && (vLine[3] == "extra") && (vLine[4] == "name")) { return; } PwEntry pe = new PwEntry(true, true); PwGroup pg = pd.RootGroup; if (vLine.Length >= 6) { string strGroup = vLine[5]; if (strGroup.Length > 0) { pg = pg.FindCreateSubTree(strGroup, new string[1] { "\\" }, true); } } pg.AddEntry(pe, true); ImportUtil.AppendToField(pe, PwDefs.TitleField, vLine[4], pd); ImportUtil.AppendToField(pe, PwDefs.UserNameField, vLine[1], pd); ImportUtil.AppendToField(pe, PwDefs.PasswordField, vLine[2], pd); string strNotes = vLine[3]; bool bIsSecNote = vLine[0].Equals("http://sn", StrUtil.CaseIgnoreCmp); if (bIsSecNote) { if (strNotes.StartsWith("NoteType:", StrUtil.CaseIgnoreCmp)) { AddNoteFields(pe, strNotes, pd); } else { ImportUtil.AppendToField(pe, PwDefs.NotesField, strNotes, pd); } } else // Standard entry, no secure note { ImportUtil.AppendToField(pe, PwDefs.UrlField, vLine[0], pd); Debug.Assert(!strNotes.StartsWith("NoteType:")); ImportUtil.AppendToField(pe, PwDefs.NotesField, strNotes, pd); } if (vLine.Length >= 7) { if (StrUtil.StringToBool(vLine[6])) { pe.AddTag("Favorite"); } } }
public PwGroupBuffer(PwGroup group) { mGroup = group; mEntries = new PwGroupEntryListBuffer(mGroup); mGroups = new PwGroupGroupListBuffer(mGroup); }
private bool compG(PwGroup pw1, PwGroup pw2) { return(prgc.Compare(pw1, pw2) > 0); }
private void WriteEntries(KdbManager mgr, Dictionary <PwGroup, uint> dictGroups, PwGroup pgRoot) { bool bWarnedOnce = false; uint uGroupCount, uEntryCount, uEntriesSaved = 0; pgRoot.GetCounts(true, out uGroupCount, out uEntryCount); DateTime dtNeverExpire = KdbManager.GetNeverExpireTime(); EntryHandler eh = delegate(PwEntry pe) { KdbEntry e = new KdbEntry(); e.Uuid.Set(pe.Uuid.UuidBytes); if (pe.ParentGroup != pgRoot) { e.GroupId = dictGroups[pe.ParentGroup]; } else { e.GroupId = 1; if ((m_slLogger != null) && !bWarnedOnce) { m_slLogger.SetText(KdbPrefix + KPRes.FormatNoRootEntries, LogStatusType.Warning); bWarnedOnce = true; } if (dictGroups.Count == 0) { throw new Exception(KPRes.FormatNoSubGroupsInRoot); } } e.ImageId = (uint)pe.IconId; e.Title = pe.Strings.ReadSafe(PwDefs.TitleField); e.UserName = pe.Strings.ReadSafe(PwDefs.UserNameField); e.Password = pe.Strings.ReadSafe(PwDefs.PasswordField); e.Url = pe.Strings.ReadSafe(PwDefs.UrlField); string strNotes = pe.Strings.ReadSafe(PwDefs.NotesField); ExportCustomStrings(pe, ref strNotes); ExportAutoType(pe, ref strNotes); ExportUrlOverride(pe, ref strNotes); e.Additional = strNotes; e.PasswordLength = (uint)e.Password.Length; Debug.Assert(TimeUtil.PwTimeLength == 7); e.CreationTime.Set(pe.CreationTime); e.LastModificationTime.Set(pe.LastModificationTime); e.LastAccessTime.Set(pe.LastAccessTime); if (pe.Expires) { e.ExpirationTime.Set(pe.ExpiryTime); } else { e.ExpirationTime.Set(dtNeverExpire); } IntPtr hBinaryData = IntPtr.Zero; if (pe.Binaries.UCount >= 1) { foreach (KeyValuePair <string, ProtectedBinary> kvp in pe.Binaries) { e.BinaryDescription = kvp.Key; byte[] pbAttached = kvp.Value.ReadData(); e.BinaryDataLength = (uint)pbAttached.Length; if (e.BinaryDataLength > 0) { hBinaryData = Marshal.AllocHGlobal((int)e.BinaryDataLength); Marshal.Copy(pbAttached, 0, hBinaryData, (int)e.BinaryDataLength); e.BinaryData = hBinaryData; } break; } if ((pe.Binaries.UCount > 1) && (m_slLogger != null)) { m_slLogger.SetText(KdbPrefix + KPRes.FormatOnlyOneAttachment + "\r\n\r\n" + KPRes.Entry + ":\r\n" + KPRes.Title + ": " + e.Title + "\r\n" + KPRes.UserName + ": " + e.UserName, LogStatusType.Warning); } } bool bResult = mgr.AddEntry(ref e); Marshal.FreeHGlobal(hBinaryData); hBinaryData = IntPtr.Zero; if (!bResult) { Debug.Assert(false); throw new InvalidOperationException(); } ++uEntriesSaved; if (m_slLogger != null) { if (!m_slLogger.SetProgress((100 * uEntriesSaved) / uEntryCount)) { return(false); } } return(true); }; if (!pgRoot.TraverseTree(TraversalMethod.PreOrder, null, eh)) { throw new InvalidOperationException(); } }
/// <summary> /// Save the contents of the current <c>PwDatabase</c> to a KDB file. /// </summary> /// <param name="strSaveToFile">Location to save the KDB file to.</param> public void Save(string strSaveToFile, PwGroup pgDataSource) { Debug.Assert(strSaveToFile != null); if (strSaveToFile == null) { throw new ArgumentNullException("strSaveToFile"); } using (KdbManager mgr = new KdbManager()) { KdbErrorCode e = KdbFile.SetDatabaseKey(mgr, m_pwDatabase.MasterKey); if (e != KdbErrorCode.Success) { Debug.Assert(false); throw new Exception(KLRes.InvalidCompositeKey); } if (m_slLogger != null) { if (m_pwDatabase.MasterKey.ContainsType(typeof(KcpUserAccount))) { m_slLogger.SetText(KPRes.KdbWUA, LogStatusType.Warning); } if (m_pwDatabase.Name.Length != 0) { m_slLogger.SetText(KdbPrefix + KPRes.FormatNoDatabaseName, LogStatusType.Warning); } if (m_pwDatabase.Description.Length != 0) { m_slLogger.SetText(KdbPrefix + KPRes.FormatNoDatabaseDesc, LogStatusType.Warning); } } // Set properties AesKdf kdf = new AesKdf(); if (!kdf.Uuid.Equals(m_pwDatabase.KdfParameters.KdfUuid)) { mgr.KeyTransformationRounds = (uint)PwDefs.DefaultKeyEncryptionRounds; } else { ulong uRounds = m_pwDatabase.KdfParameters.GetUInt64( AesKdf.ParamRounds, PwDefs.DefaultKeyEncryptionRounds); uRounds = Math.Min(uRounds, 0xFFFFFFFEUL); mgr.KeyTransformationRounds = (uint)uRounds; } PwGroup pgRoot = (pgDataSource ?? m_pwDatabase.RootGroup); // Write groups and entries Dictionary <PwGroup, UInt32> dictGroups = WriteGroups(mgr, pgRoot); WriteEntries(mgr, dictGroups, pgRoot); e = mgr.SaveDatabase(strSaveToFile); if (e != KdbErrorCode.Success) { throw new Exception(KLRes.FileSaveFailed); } } }
private static void ImportGroup(XmlNode xmlNode, PwDatabase pwStorage, PwGroup pg) { PwGroup pgSub = pg; PwEntry pe = null; foreach (XmlNode xmlChild in xmlNode) { if (xmlChild.Name == "A") { pe = new PwEntry(true, true); pg.AddEntry(pe, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, XmlUtil.SafeInnerText(xmlChild))); XmlNode xnUrl = xmlChild.Attributes.GetNamedItem("HREF"); if ((xnUrl != null) && (xnUrl.Value != null)) { pe.Strings.Set(PwDefs.UrlField, new ProtectedString( pwStorage.MemoryProtection.ProtectUrl, xnUrl.Value)); } else { Debug.Assert(false); } // pe.Strings.Set("RDF_ID", new ProtectedString( // false, xmlChild.Attributes.GetNamedItem("ID").Value)); ImportIcon(xmlChild, pe, pwStorage); } else if (xmlChild.Name == "DD") { if (pe != null) { ImportUtil.AppendToField(pe, PwDefs.NotesField, XmlUtil.SafeInnerText(xmlChild).Trim(), pwStorage, "\r\n", false); } else { Debug.Assert(false); } } else if (xmlChild.Name == "H3") { string strGroup = XmlUtil.SafeInnerText(xmlChild); if (strGroup.Length == 0) { Debug.Assert(false); pgSub = pg; } else { pgSub = new PwGroup(true, true, strGroup, PwIcon.Folder); pg.AddGroup(pgSub, true); } } else if (xmlChild.Name == "DL") { ImportGroup(xmlChild, pwStorage, pgSub); } else { Debug.Assert(false); } } }
public static string TryGetPassword(string url, string username) { if (group != null) { return(InternalGetPassword(url, username)); } if (failed) { return(null); } context = AzusaContext.GetInstance(); DirectoryInfo di = new DirectoryInfo("."); FileInfo dbFileInfo = di.GetFiles("*.kdbx").FirstOrDefault(x => x.Extension.ToLower().Equals(".kdbx")); if (dbFileInfo == null) { dbFileInfo = di.Parent.GetFiles("*.kdbx").FirstOrDefault(x => x.Extension.ToLower().Equals(".kdbx")); } if (dbFileInfo == null) { failed = true; return(null); } string pw = null; context.Splash.Invoke((MethodInvoker) delegate { pw = TextInputForm.PromptPassword(String.Format("Passwort für {0}?", dbFileInfo.Name), context.Splash); }); if (string.IsNullOrEmpty(pw)) { failed = true; return(null); } IOConnectionInfo connectionInfo = IOConnectionInfo.FromPath(dbFileInfo.FullName); KcpPassword kcpPassword = new KcpPassword(pw); CompositeKey compositeKey = new CompositeKey(); compositeKey.AddUserKey(kcpPassword); database = new PwDatabase(); try { database.Open(connectionInfo, compositeKey, null); group = FindPwGroup(database.RootGroup); if (group == null) { failed = true; return(null); } return(InternalGetPassword(url, username)); } catch (InvalidCompositeKeyException) { failed = true; return(null); } }
public DeleteGroup(Context ctx, IKp2aApp app, PwGroup group, OnFinish finish) : base(finish, app) { SetMembers(ctx, app, group, false); }
public void InitEx(bool bExport, PwDatabase pd, PwGroup pg) { m_bExport = bExport; m_pd = pd; m_pg = pg; }
/// <summary> /// A PwDatabase extension method that creates a website entry. /// </summary> /// <param name="pd">The database to act on</param> /// <param name="group">The group to insert new entries into</param> /// <param name="host">The host</param> /// <param name="username">The username</param> /// <param name="password">The password</param> /// <param name="creationSettings">Settings used while creating the entry</param> /// <param name="logger">The logger</param> public static void CreateWebsiteEntry(this PwDatabase pd, PwGroup group, EntryInfo entry, CreationSettings creationSettings, IStatusLogger logger) { Contract.Requires(group != null); Contract.Requires(entry != null); Contract.Requires(creationSettings != null); Contract.Requires(logger != null); logger.SetText(string.Format("{0} - {1}", entry.Username, entry.Hostname), LogStatusType.Info); var pe = new PwEntry(true, true); group.AddEntry(pe, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, entry.Hostname)); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName, entry.Username)); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword, entry.Password)); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl, entry.Hostname)); if (creationSettings.UseDates) { pe.CreationTime = entry.Created; pe.LastModificationTime = entry.Modified; } if (!string.IsNullOrEmpty(entry.Hostname) && (creationSettings.ExtractIcon || creationSettings.ExtractTitle)) { try { string content; using (var client = new WebClientEx()) { content = client.DownloadStringAwareOfEncoding(entry.Hostname); var document = new HtmlDocument(); document.LoadHtml(content); if (creationSettings.ExtractTitle) { var title = document.DocumentNode.SelectSingleNode("/html/head/title"); if (title != null) { pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, HttpUtility.HtmlDecode(title.InnerText.Trim()))); } } if (creationSettings.ExtractIcon) { string iconUrl = null; foreach (var prio in new string[] { "shortcut icon", "apple-touch-icon", "icon" }) { //iconUrl = document.DocumentNode.SelectNodes("/html/head/link").Where(l => prio == l.Attributes["rel"]?.Value).LastOrDefault()?.Attributes["href"]?.Value; var node = document.DocumentNode.SelectNodes("/html/head/link").Where(l => l.GetAttributeValue("rel", string.Empty) == prio).LastOrDefault(); if (node != null) { iconUrl = node.GetAttributeValue("href", string.Empty); } if (!string.IsNullOrEmpty(iconUrl)) { break; } } if (!string.IsNullOrEmpty(iconUrl)) { if (!iconUrl.StartsWith("http://") && !iconUrl.StartsWith("https://")) { iconUrl = entry.Hostname.TrimEnd('/') + '/' + iconUrl.TrimStart('/'); } using (var s = client.OpenRead(iconUrl)) { var icon = Image.FromStream(s); if (icon.Width > 16 || icon.Height > 16) { icon = icon.GetThumbnailImage(16, 16, null, IntPtr.Zero); } using (var ms = new MemoryStream()) { icon.Save(ms, ImageFormat.Png); var data = ms.ToArray(); var createNewIcon = true; foreach (var item in pd.CustomIcons) { if (KeePassLib.Utility.MemUtil.ArraysEqual(data, item.ImageDataPng)) { pe.CustomIconUuid = item.Uuid; createNewIcon = false; break; } } if (createNewIcon) { var pwci = new PwCustomIcon(new PwUuid(true), data); pd.CustomIcons.Add(pwci); pe.CustomIconUuid = pwci.Uuid; } } } pd.UINeedsIconUpdate = true; } } } } catch { } } }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { StreamReader sr = new StreamReader(sInput, Encoding.Default); string strData = sr.ReadToEnd(); sr.Close(); CsvOptions opt = new CsvOptions(); opt.BackslashIsEscape = false; opt.TextQualifier = char.MaxValue; // No text qualifier CsvStreamReaderEx csv = new CsvStreamReaderEx(strData, opt); PwGroup pg = pwStorage.RootGroup; char[] vGroupSplit = new char[] { '\\' }; while (true) { string[] v = csv.ReadLine(); if (v == null) { break; } if (v.Length < 1) { continue; } for (int i = 0; i < v.Length; ++i) { v[i] = ParseString(v[i]); } if (v[0].StartsWith("\\")) // Group { string strGroup = v[0].Trim(vGroupSplit); // Also from end if (strGroup.Length > 0) { pg = pwStorage.RootGroup.FindCreateSubTree(strGroup, vGroupSplit); if (v.Length >= 6) { pg.Notes = v[5].Trim(); } if ((v.Length >= 5) && (v[4].Trim().Length > 0)) { if (pg.Notes.Length > 0) { pg.Notes += Environment.NewLine + Environment.NewLine; } pg.Notes += v[4].Trim(); } } } else // Entry { PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); List <string> l = new List <string>(v); while (l.Count < 8) { Debug.Assert(false); l.Add(string.Empty); } ImportUtil.AppendToField(pe, PwDefs.TitleField, l[0], pwStorage); ImportUtil.AppendToField(pe, PwDefs.UserNameField, l[1], pwStorage); ImportUtil.AppendToField(pe, PwDefs.PasswordField, l[2], pwStorage); ImportUtil.AppendToField(pe, PwDefs.UrlField, l[3], pwStorage); ImportUtil.AppendToField(pe, PwDefs.NotesField, l[4], pwStorage); if (l[5].Length > 0) { ImportUtil.AppendToField(pe, "Custom 1", l[5], pwStorage); } if (l[6].Length > 0) { ImportUtil.AppendToField(pe, "Custom 2", l[6], pwStorage); } if (l[7].Length > 0) { ImportUtil.AppendToField(pe, "Custom 3", l[7], pwStorage); } } } }
// public void Save(string strFile, PwGroup pgDataSource, KdbxFormat fmt, // IStatusLogger slLogger) // { // bool bMadeUnhidden = UrlUtil.UnhideFile(strFile); // // IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); // this.Save(IOConnection.OpenWrite(ioc), pgDataSource, format, slLogger); // // if(bMadeUnhidden) UrlUtil.HideFile(strFile, true); // Hide again // } /// <summary> /// Save the contents of the current <c>PwDatabase</c> to a KDBX file. /// </summary> /// <param name="sSaveTo">Stream to write the KDBX file into.</param> /// <param name="pgDataSource">Group containing all groups and /// entries to write. If <c>null</c>, the complete database will /// be written.</param> /// <param name="fmt">Format of the file to create.</param> /// <param name="slLogger">Logger that recieves status information.</param> public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat fmt, IStatusLogger slLogger) { Debug.Assert(sSaveTo != null); if (sSaveTo == null) { throw new ArgumentNullException("sSaveTo"); } if (m_bUsedOnce) { throw new InvalidOperationException("Do not reuse KdbxFile objects!"); } m_bUsedOnce = true; m_format = fmt; m_slLogger = slLogger; m_xmlWriter = null; PwGroup pgRoot = (pgDataSource ?? m_pwDatabase.RootGroup); UTF8Encoding encNoBom = StrUtil.Utf8; CryptoRandom cr = CryptoRandom.Instance; byte[] pbCipherKey = null; byte[] pbHmacKey64 = null; m_pbsBinaries.Clear(); m_pbsBinaries.AddFrom(pgRoot); List <Stream> lStreams = new List <Stream>(); lStreams.Add(sSaveTo); HashingStreamEx sHashing = new HashingStreamEx(sSaveTo, true, null); lStreams.Add(sHashing); try { m_uFileVersion = GetMinKdbxVersion(); int cbEncKey, cbEncIV; ICipherEngine iCipher = GetCipher(out cbEncKey, out cbEncIV); m_pbMasterSeed = cr.GetRandomBytes(32); m_pbEncryptionIV = cr.GetRandomBytes((uint)cbEncIV); // m_pbTransformSeed = cr.GetRandomBytes(32); PwUuid puKdf = m_pwDatabase.KdfParameters.KdfUuid; KdfEngine kdf = KdfPool.Get(puKdf); if (kdf == null) { throw new Exception(KLRes.UnknownKdf + MessageService.NewParagraph + // KLRes.FileNewVerOrPlgReq + MessageService.NewParagraph + "UUID: " + puKdf.ToHexString() + "."); } kdf.Randomize(m_pwDatabase.KdfParameters); if (m_format == KdbxFormat.Default) { if (m_uFileVersion < FileVersion32_4) { m_craInnerRandomStream = CrsAlgorithm.Salsa20; m_pbInnerRandomStreamKey = cr.GetRandomBytes(32); } else // KDBX >= 4 { m_craInnerRandomStream = CrsAlgorithm.ChaCha20; m_pbInnerRandomStreamKey = cr.GetRandomBytes(64); } m_randomStream = new CryptoRandomStream(m_craInnerRandomStream, m_pbInnerRandomStreamKey); } if (m_uFileVersion < FileVersion32_4) { m_pbStreamStartBytes = cr.GetRandomBytes(32); } Stream sXml; if (m_format == KdbxFormat.Default) { byte[] pbHeader = GenerateHeader(); m_pbHashOfHeader = CryptoUtil.HashSha256(pbHeader); MemUtil.Write(sHashing, pbHeader); sHashing.Flush(); ComputeKeys(out pbCipherKey, cbEncKey, out pbHmacKey64); Stream sPlain; if (m_uFileVersion < FileVersion32_4) { Stream sEncrypted = EncryptStream(sHashing, iCipher, pbCipherKey, cbEncIV, true); if ((sEncrypted == null) || (sEncrypted == sHashing)) { throw new SecurityException(KLRes.CryptoStreamFailed); } lStreams.Add(sEncrypted); MemUtil.Write(sEncrypted, m_pbStreamStartBytes); sPlain = new HashedBlockStream(sEncrypted, true); } else // KDBX >= 4 { // For integrity checking (without knowing the master key) MemUtil.Write(sHashing, m_pbHashOfHeader); byte[] pbHeaderHmac = ComputeHeaderHmac(pbHeader, pbHmacKey64); MemUtil.Write(sHashing, pbHeaderHmac); Stream sBlocks = new HmacBlockStream(sHashing, true, true, pbHmacKey64); lStreams.Add(sBlocks); sPlain = EncryptStream(sBlocks, iCipher, pbCipherKey, cbEncIV, true); if ((sPlain == null) || (sPlain == sBlocks)) { throw new SecurityException(KLRes.CryptoStreamFailed); } } lStreams.Add(sPlain); if (m_pwDatabase.Compression == PwCompressionAlgorithm.GZip) { sXml = new GZipStream(sPlain, CompressionMode.Compress); lStreams.Add(sXml); } else { sXml = sPlain; } if (m_uFileVersion >= FileVersion32_4) { WriteInnerHeader(sXml); // Binary header before XML } } else if (m_format == KdbxFormat.PlainXml) { sXml = sHashing; } else { Debug.Assert(false); throw new ArgumentOutOfRangeException("fmt"); } m_xmlWriter = XmlUtilEx.CreateXmlWriter(sXml); WriteDocument(pgRoot); m_xmlWriter.Flush(); } finally { CommonCleanUpWrite(lStreams, sHashing); if (pbCipherKey != null) { MemUtil.ZeroByteArray(pbCipherKey); } if (pbHmacKey64 != null) { MemUtil.ZeroByteArray(pbHmacKey64); } } }
public abstract Task <List <BreachedEntry> > CheckGroup(PwGroup group, bool expireEntries, bool oldEntriesOnly, bool ignoreDeleted, bool ignoreExpired, IProgress <ProgressItem> progressIndicator);
public static PwGroupView GetInstance(GroupBaseActivity act, PwGroup pw) { return(new PwGroupView(act, pw)); }
public void EditGroup(PwGroup pwGroup) { GroupEditActivity.Launch(this, pwGroup.ParentGroup, pwGroup); }
private void WriteDocument(PwGroup pgRoot) { Debug.Assert(m_xmlWriter != null); if (m_xmlWriter == null) { throw new InvalidOperationException(); } uint uNumGroups, uNumEntries, uCurEntry = 0; pgRoot.GetCounts(true, out uNumGroups, out uNumEntries); m_xmlWriter.WriteStartDocument(true); m_xmlWriter.WriteStartElement(ElemDocNode); WriteMeta(); m_xmlWriter.WriteStartElement(ElemRoot); StartGroup(pgRoot); Stack <PwGroup> groupStack = new Stack <PwGroup>(); groupStack.Push(pgRoot); GroupHandler gh = delegate(PwGroup pg) { Debug.Assert(pg != null); if (pg == null) { throw new ArgumentNullException("pg"); } while (true) { if (pg.ParentGroup == groupStack.Peek()) { groupStack.Push(pg); StartGroup(pg); break; } else { groupStack.Pop(); if (groupStack.Count <= 0) { return(false); } EndGroup(); } } return(true); }; EntryHandler eh = delegate(PwEntry pe) { Debug.Assert(pe != null); WriteEntry(pe, false); ++uCurEntry; if (m_slLogger != null) { if (!m_slLogger.SetProgress((100 * uCurEntry) / uNumEntries)) { return(false); } } return(true); }; if (!pgRoot.TraverseTree(TraversalMethod.PreOrder, gh, eh)) { throw new OperationCanceledException(); } while (groupStack.Count > 1) { m_xmlWriter.WriteEndElement(); groupStack.Pop(); } EndGroup(); WriteList(ElemDeletedObjects, m_pwDatabase.DeletedObjects); m_xmlWriter.WriteEndElement(); // Root m_xmlWriter.WriteEndElement(); // ElemDocNode m_xmlWriter.WriteEndDocument(); }
private static void AddObject(PwGroup pgStorage, JsonObject jo, PwDatabase pwContext, bool bCreateSubGroups, Dictionary <string, List <string> > dTags, List <PwEntry> lCreatedEntries) { string strRoot = jo.GetValue <string>("root"); if (string.Equals(strRoot, "tagsFolder", StrUtil.CaseIgnoreCmp)) { ImportTags(jo, dTags); return; } JsonObject[] v = jo.GetValueArray <JsonObject>("children"); if (v != null) { PwGroup pgNew; if (bCreateSubGroups) { pgNew = new PwGroup(true, true); pgNew.Name = (jo.GetValue <string>("title") ?? string.Empty); pgStorage.AddGroup(pgNew, true); } else { pgNew = pgStorage; } foreach (JsonObject joSub in v) { if (joSub == null) { Debug.Assert(false); continue; } AddObject(pgNew, joSub, pwContext, true, dTags, lCreatedEntries); } return; } PwEntry pe = new PwEntry(true, true); // SetString(pe, "Index", false, jo, "index"); SetString(pe, PwDefs.TitleField, pwContext.MemoryProtection.ProtectTitle, jo, "title"); // SetString(pe, "ID", false, jo, "id"); SetString(pe, PwDefs.UrlField, pwContext.MemoryProtection.ProtectUrl, jo, "uri"); // SetString(pe, "CharSet", false, jo, "charset"); v = jo.GetValueArray <JsonObject>("annos"); if (v != null) { foreach (JsonObject joAnno in v) { if (joAnno == null) { Debug.Assert(false); continue; } string strName = joAnno.GetValue <string>("name"); string strValue = joAnno.GetValue <string>("value"); if ((strName == "bookmarkProperties/description") && !string.IsNullOrEmpty(strValue)) { pe.Strings.Set(PwDefs.NotesField, new ProtectedString( pwContext.MemoryProtection.ProtectNotes, strValue)); } } } // Tags support (new versions) string strTags = jo.GetValue <string>("tags"); if (!string.IsNullOrEmpty(strTags)) { string[] vTags = strTags.Split(','); foreach (string strTag in vTags) { string str = strTag.Trim(); if (str.Length != 0) { pe.AddTag(str); } } } string strKeyword = jo.GetValue <string>("keyword"); if (!string.IsNullOrEmpty(strKeyword)) { ImportUtil.AppendToField(pe, "Keyword", strKeyword, pwContext); } if ((pe.Strings.ReadSafe(PwDefs.TitleField).Length != 0) || (pe.Strings.ReadSafe(PwDefs.UrlField).Length != 0)) { pgStorage.AddEntry(pe, true); lCreatedEntries.Add(pe); } }
private static void ProcessCsvLine(string strLine, PwDatabase pwStorage, Dictionary <string, PwGroup> dictGroups) { if (strLine == "\"Bezeichnung\"\t\"User/ID\"\t\"1.Passwort\"\t\"Url/Programm\"\t\"Geändert am\"\t\"Bemerkung\"\t\"2.Passwort\"\t\"Läuft ab\"\t\"Kategorie\"\t\"Eigene Felder\"") { return; } string str = strLine; if (str.StartsWith("\"") && str.EndsWith("\"")) { str = str.Substring(1, str.Length - 2); } else { Debug.Assert(false); } string[] list = str.Split(new string[] { "\"\t\"" }, StringSplitOptions.None); int iOffset; if (list.Length == 11) { iOffset = 0; // 1Password Pro 5.99 } else if (list.Length == 10) { iOffset = -1; // 1PW 6.15 } else if (list.Length > 11) { iOffset = 0; // Unknown extension } else { return; } string strGroup = list[9 + iOffset]; PwGroup pg; if (dictGroups.ContainsKey(strGroup)) { pg = dictGroups[strGroup]; } else { pg = new PwGroup(true, true, strGroup, PwIcon.Folder); pwStorage.RootGroup.AddGroup(pg, true); dictGroups[strGroup] = pg; } PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, ParseCsvWord(list[1 + iOffset]))); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, ParseCsvWord(list[2 + iOffset]))); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, ParseCsvWord(list[3 + iOffset]))); pe.Strings.Set(PwDefs.UrlField, new ProtectedString( pwStorage.MemoryProtection.ProtectUrl, ParseCsvWord(list[4 + iOffset]))); pe.Strings.Set(PwDefs.NotesField, new ProtectedString( pwStorage.MemoryProtection.ProtectNotes, ParseCsvWord(list[6 + iOffset]))); pe.Strings.Set(PwDefs.PasswordField + " 2", new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, ParseCsvWord(list[7 + iOffset]))); // 1Password Pro only: // Debug.Assert(list[9] == list[0]); // Very mysterious format... DateTime dt; if (ParseDateTime(list[5 + iOffset], out dt)) { pe.CreationTime = pe.LastAccessTime = pe.LastModificationTime = dt; } else { Debug.Assert(false); } if (ParseDateTime(list[8 + iOffset], out dt)) { pe.Expires = true; pe.ExpiryTime = dt; } AddCustomFields(pe, list[10 + iOffset]); }
public PwGroupBuffer() { mGroup = new PwGroup(false, false); mEntries = new PwGroupEntryListBuffer(mGroup); mGroups = new PwGroupGroupListBuffer(mGroup); }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { StreamReader sr = new StreamReader(sInput, StrUtil.Utf8, true); string strData = sr.ReadToEnd(); sr.Close(); const string strKvpSep = " : "; PwGroup pg = pwStorage.RootGroup; strData = StrUtil.NormalizeNewLines(strData, false); strData += ("\n\nTitle" + strKvpSep); string[] vLines = strData.Split('\n'); bool bLastWasEmpty = true; string strName = PwDefs.TitleField; PwEntry pe = null; string strNotes = string.Empty; // Do not trim spaces, because these are part of the // key-value separator char[] vTrimLine = new char[] { '\t', '\r', '\n' }; foreach (string strLine in vLines) { if (strLine == null) { Debug.Assert(false); continue; } string str = strLine.Trim(vTrimLine); string strValue = str; int iKvpSep = str.IndexOf(strKvpSep); if (iKvpSep >= 0) { string strOrgName = str.Substring(0, iKvpSep).Trim(); strValue = str.Substring(iKvpSep + strKvpSep.Length).Trim(); // If an entry doesn't have any notes, the next entry // may start without an empty line; in this case we // detect the new entry by the field name "Title" // (which apparently is not translated by Enpass) if (bLastWasEmpty || (strOrgName == "Title")) { if (pe != null) { strNotes = strNotes.Trim(); pe.Strings.Set(PwDefs.NotesField, new ProtectedString( pwStorage.MemoryProtection.ProtectNotes, strNotes)); strNotes = string.Empty; pg.AddEntry(pe, true); } pe = new PwEntry(true, true); } strName = ImportUtil.MapNameToStandardField(strOrgName, true); if (string.IsNullOrEmpty(strName)) { strName = strOrgName; if (string.IsNullOrEmpty(strName)) { Debug.Assert(false); strName = PwDefs.NotesField; } } } if (strName == PwDefs.NotesField) { if (strNotes.Length > 0) { strNotes += MessageService.NewLine; } strNotes += strValue; } else { ImportUtil.AppendToField(pe, strName, strValue, pwStorage); } bLastWasEmpty = (str.Length == 0); } }
/// <summary> /// The main routine, called when import is selected /// </summary> /// <param name="pwStorage"></param> /// <param name="sInput"></param> /// <param name="slLogger"></param> public override void Import(PwDatabase pwStorage, System.IO.Stream sInput, KeePassLib.Interfaces.IStatusLogger slLogger) { try { FormXml form = new FormXml(); form.Initialise(pwStorage); // form.GroupName = pwStorage.RootGroup.Name; //if (pwStorage.LastSelectedGroup != null) //{ // form.GroupName = pwStorage.RootGroup.FindGroup(pwStorage.LastSelectedGroup, true).Name; //} if (form.ShowDialog() == DialogResult.OK) { bool overwritePassword = form.Overwrite; bool searchWeb = form.GetTitles; bool checkMatches = form.Merge; bool addAutoType = form.AddAutoType; PwIcon iconId = (PwIcon)Enum.Parse(typeof(PwIcon), form.IconName); PwGroup group = form.Group; if (group == null) { group = pwStorage.RootGroup; } try { InternetAccessor internetAccessor = new InternetAccessor(); slLogger.StartLogging("Importing Firefox File", false); slLogger.SetText("Reading File", LogStatusType.Info); // Load in the supplied xml document XmlDocument fireFoxDocument = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; settings.ValidationType = ValidationType.None; XmlReader reader = XmlTextReader.Create(sInput, settings); try { fireFoxDocument.Load(reader); } catch (Exception ex) { throw new Exception("Failed to load the password file. " + Environment.NewLine + "This may be due to the presence of foreign characters in the data. " + Environment.NewLine + "Please check the website for help" + Environment.NewLine + Environment.NewLine + ex.Message, ex); } finally { reader.Close(); } // Get a collection of nodes that represent each password XmlNodeList fireFoxEntryNodes = fireFoxDocument.SelectNodes("xml/entries/entry"); int count = fireFoxEntryNodes.Count; int pos = 0; // Loop each entry and add it to KeePass foreach (XmlElement fireFoxEntryElement in fireFoxEntryNodes) { if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user { break; } // keep the user informed of progress pos++; slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count))); // gather the data to import string title = fireFoxEntryElement.SelectSingleNode("@host").InnerText; slLogger.SetText(title, LogStatusType.Info); string notes = String.Empty; if (form.IncludeImportNotes) { notes += "Imported from FireFox by the Web Site Advantage FireFox to KeePass Importer" + Environment.NewLine; } string url = fireFoxEntryElement.SelectSingleNode("@host").InnerText; string formSubmitURL = fireFoxEntryElement.SelectSingleNode("@formSubmitURL").InnerText; if (!String.IsNullOrEmpty(formSubmitURL)) { url = formSubmitURL; } string host = url; try { Uri uri = new Uri(url); host = uri.Host; } catch { } string username = fireFoxEntryElement.SelectSingleNode("@user").InnerText; bool newEntry = true; PwEntry pe = null; if (checkMatches) { pe = KeePassHelper.FindMatchingEntry(pwStorage.RootGroup, url, username); } if (pe == null) { // create a new entry pe = new PwEntry(true, true); group.AddEntry(pe, true); slLogger.SetText("Created new entry", LogStatusType.AdditionalInfo); } else { newEntry = false; slLogger.SetText("Found matching entry", LogStatusType.AdditionalInfo); } if (newEntry || overwritePassword) { // set the password pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, fireFoxEntryElement.SelectSingleNode("@password").InnerText)); } if (newEntry) { // set all fields pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, title)); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, username)); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, url)); if (!String.IsNullOrEmpty(notes)) { pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, notes)); } pe.Expires = false; pe.IconId = iconId; // Gatter any extra information... if (fireFoxEntryElement.HasAttribute("userFieldName") && fireFoxEntryElement.GetAttribute("userFieldName").Length > 0) { pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("userFieldName"))); } if (fireFoxEntryElement.HasAttribute("usernameField") && fireFoxEntryElement.GetAttribute("usernameField").Length > 0) { pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("usernameField"))); } if (fireFoxEntryElement.HasAttribute("passFieldName") && fireFoxEntryElement.GetAttribute("passFieldName").Length > 0) { pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passFieldName"))); } if (fireFoxEntryElement.HasAttribute("passwordField") && fireFoxEntryElement.GetAttribute("passwordField").Length > 0) { pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passwordField"))); } if (fireFoxEntryElement.HasAttribute("httpRealm") && fireFoxEntryElement.GetAttribute("httpRealm").Length > 0) { pe.Strings.Set("HttpRealm", new ProtectedString(false, fireFoxEntryElement.GetAttribute("httpRealm"))); } if (fireFoxEntryElement.HasAttribute("formSubmitURL") && fireFoxEntryElement.GetAttribute("formSubmitURL").Length > 0) { pe.Strings.Set("LoginFormDomain", new ProtectedString(false, fireFoxEntryElement.GetAttribute("formSubmitURL"))); } } string webTitle = null; // if new or the title is the same as the url then we should try and get the title if (searchWeb) { // test if new or entry has url as title if ((newEntry || pe.Strings.Get(PwDefs.TitleField).ReadString() == pe.Strings.Get(PwDefs.UrlField).ReadString())) { // get the pages title slLogger.SetText("Accessing website for title", LogStatusType.AdditionalInfo); webTitle = internetAccessor.ScrapeTitle(url); if (!String.IsNullOrEmpty(webTitle)) { slLogger.SetText("Title set from internet to " + webTitle, LogStatusType.AdditionalInfo); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, webTitle)); } } } if (addAutoType) { KeePassHelper.InsertAutoType(pe, "*" + host + "*", KeePassUtilities.AutoTypeSequence()); } if (webTitle != null && addAutoType) { KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence()); } } } finally { slLogger.EndLogging(); } } } catch (Exception ex) { ErrorMessage.ShowErrorMessage("Importer Xml", "Import Failed", ex); } }
/// <summary> /// Initialize the form. Must be called before the dialog is displayed. /// </summary> /// <param name="pwRoot">Data source group. This group will be searched.</param> public void InitEx(PwDatabase pdContext, PwGroup pwRoot) { m_pdContext = pdContext; m_pgRoot = pwRoot; }
protected override void OnCreate(Bundle savedInstanceState) { _design.ApplyDialogTheme(); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.group_edit); ImageButton iconButton = (ImageButton)FindViewById(Resource.Id.icon_button); iconButton.Click += (sender, e) => { IconPickerActivity.Launch(this); }; _selectedIconId = (int)PwIcon.FolderOpen; iconButton.SetImageDrawable(App.Kp2a.GetDb().DrawableFactory.GetIconDrawable(this, App.Kp2a.GetDb().KpDatabase, (PwIcon)_selectedIconId, null, true)); Button okButton = (Button)FindViewById(Resource.Id.ok); okButton.Click += (sender, e) => { TextView nameField = (TextView)FindViewById(Resource.Id.group_name); String name = nameField.Text; if (name.Length > 0) { Intent intent = new Intent(); intent.PutExtra(KeyName, name); intent.PutExtra(KeyIconId, _selectedIconId); if (_selectedCustomIconId != null) { intent.PutExtra(KeyCustomIconId, MemUtil.ByteArrayToHexString(_selectedCustomIconId.UuidBytes)); } if (_groupToEdit != null) { intent.PutExtra(KeyGroupUuid, MemUtil.ByteArrayToHexString(_groupToEdit.Uuid.UuidBytes)); } SetResult(Result.Ok, intent); Finish(); } else { Toast.MakeText(this, Resource.String.error_no_name, ToastLength.Long).Show(); } }; if (Intent.HasExtra(KeyGroupUuid)) { string groupUuid = Intent.Extras.GetString(KeyGroupUuid); _groupToEdit = App.Kp2a.GetDb().Groups[new PwUuid(MemUtil.HexStringToByteArray(groupUuid))]; _selectedIconId = (int)_groupToEdit.IconId; _selectedCustomIconId = _groupToEdit.CustomIconUuid; TextView nameField = (TextView)FindViewById(Resource.Id.group_name); nameField.Text = _groupToEdit.Name; App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iconButton, this, App.Kp2a.GetDb().KpDatabase, _groupToEdit.IconId, _groupToEdit.CustomIconUuid, false); SetTitle(Resource.String.edit_group_title); } else { SetTitle(Resource.String.add_group_title); } Button cancel = (Button)FindViewById(Resource.Id.cancel); cancel.Click += (sender, e) => { Intent intent = new Intent(); SetResult(Result.Canceled, intent); Finish(); }; }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { string str = PwMemory2008Xml104.Preprocess(sInput); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str), false); XmlSerializer xs = new XmlSerializer(typeof(Priv_PwMem2008XmlFile)); Priv_PwMem2008XmlFile f = (Priv_PwMem2008XmlFile)xs.Deserialize(ms); if ((f == null) || (f.Cells == null)) { return; } Dictionary <string, PwGroup> vGroups = new Dictionary <string, PwGroup>(); for (int iLine = 2; iLine < f.Cells.Length; ++iLine) { string[] vCells = f.Cells[iLine]; if ((vCells == null) || (vCells.Length != 6)) { continue; } if ((vCells[1] == null) || (vCells[2] == null) || (vCells[3] == null) || (vCells[4] == null)) { continue; } string strGroup = vCells[4]; PwGroup pg; if (strGroup == ".") { pg = pwStorage.RootGroup; } else if (vGroups.ContainsKey(strGroup)) { pg = vGroups[strGroup]; } else { pg = new PwGroup(true, true); pg.Name = strGroup; pwStorage.RootGroup.AddGroup(pg, true); vGroups[strGroup] = pg; } PwEntry pe = new PwEntry(true, true); pg.AddEntry(pe, true); if (vCells[1] != ".") { pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, vCells[1])); } if (vCells[2] != ".") { pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, vCells[2])); } if (vCells[3] != ".") { pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, vCells[3])); } } }
public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { StreamReader sr = new StreamReader(sInput, Encoding.Default); string strData = sr.ReadToEnd(); sr.Close(); sInput.Close(); Dictionary <string, PwGroup> dGroups = new Dictionary <string, PwGroup>(); dGroups[string.Empty] = pwStorage.RootGroup; CsvOptions opt = new CsvOptions(); opt.BackslashIsEscape = false; CsvStreamReaderEx csv = new CsvStreamReaderEx(strData, opt); while (true) { string[] v = csv.ReadLine(); if (v == null) { break; } if (v.Length == 0) { continue; } if (v[0].StartsWith("TurboPasswords CSV Export File")) { continue; } if (v.Length < 24) { Debug.Assert(false); continue; } if ((v[0] == "Category") && (v[1] == "Type")) { continue; } PwEntry pe = new PwEntry(true, true); PwGroup pg; string strGroup = v[0]; if (!dGroups.TryGetValue(strGroup, out pg)) { pg = new PwGroup(true, true, strGroup, PwIcon.Folder); dGroups[string.Empty].AddGroup(pg, true); dGroups[strGroup] = pg; } pg.AddEntry(pe, true); string strType = v[1]; for (int f = 0; f < 6; ++f) { string strKey = v[2 + (2 * f)]; string strValue = v[2 + (2 * f) + 1]; if (strKey.Length == 0) { strKey = PwDefs.NotesField; } if (strValue.Length == 0) { continue; } if (strKey == "Description") { strKey = PwDefs.TitleField; } else if (((strType == "Contact") || (strType == "Personal Info")) && (strKey == "Name")) { strKey = PwDefs.TitleField; } else if (((strType == "Membership") || (strType == "Insurance")) && (strKey == "Company")) { strKey = PwDefs.TitleField; } else if (strKey == "SSN") { strKey = PwDefs.UserNameField; } else { string strMapped = ImportUtil.MapNameToStandardField(strKey, false); if (!string.IsNullOrEmpty(strMapped)) { strKey = strMapped; } } ImportUtil.AppendToField(pe, strKey, strValue, pwStorage, ((strKey == PwDefs.NotesField) ? "\r\n" : ", "), false); } ImportUtil.AppendToField(pe, PwDefs.NotesField, v[20], pwStorage, "\r\n\r\n", false); if (v[21].Length > 0) { ImportUtil.AppendToField(pe, "Login URL", v[21], pwStorage, null, true); } } }
public void ConvertView(PwGroup pw) { PopulateView(this, pw); }