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));
        }
Example #2
0
        public static void Import(PwGroup pgStorage, Stream s, GxiProfile p,
            PwDatabase pdContext, IStatusLogger sl)
        {
            if(pgStorage == null) throw new ArgumentNullException("pgStorage");
            if(s == null) throw new ArgumentNullException("s");
            if(p == null) throw new ArgumentNullException("p");
            if(pdContext == null) throw new ArgumentNullException("pdContext");
            // sl may be null

            // Import into virtual group first, in order to realize
            // an all-or-nothing import
            PwGroup pgVirt = new PwGroup(true, true);

            try { ImportPriv(pgVirt, s, p, pdContext, sl); }
            finally { s.Close(); }

            foreach(PwGroup pg in pgVirt.Groups)
                pgStorage.AddGroup(pg, true);
            foreach(PwEntry pe in pgVirt.Entries)
                pgStorage.AddEntry(pe, true);
        }
Example #3
0
        public void Import(List <BaseRecord> baseRecords, PwDatabase storage, IStatusLogger status, bool createSubfolders = false)
        {
            var loginRecords      = new List <BaseRecord>();
            var walletRecords     = new List <BaseRecord>();
            var accountsRecords   = new List <BaseRecord>();
            var softwareRecords   = new List <BaseRecord>();
            var secureNoteRecords = new List <BaseRecord>();
            var identityRecords   = new List <BaseRecord>();
            var RecordsList       = new List <subfolder>();

            var records        = new List <BaseRecord>();
            var trashedRecords = new List <BaseRecord>();

            if (createSubfolders)
            {
                RecordsList.Add(new subfolder {
                    folderName = "Logins", folderIcon = PwIcon.World, recordList = loginRecords
                });
                RecordsList.Add(new subfolder {
                    folderName = "Wallet", folderIcon = PwIcon.Money, recordList = walletRecords
                });
                RecordsList.Add(new subfolder {
                    folderName = "Accounts", folderIcon = PwIcon.NetworkServer, recordList = accountsRecords
                });
                RecordsList.Add(new subfolder {
                    folderName = "Software", folderIcon = PwIcon.MultiKeys, recordList = softwareRecords
                });
                RecordsList.Add(new subfolder {
                    folderName = "Secure Notes", folderIcon = PwIcon.Notepad, recordList = secureNoteRecords
                });
                RecordsList.Add(new subfolder {
                    folderName = "identites", folderIcon = PwIcon.Identity, recordList = identityRecords
                });
            }

            baseRecords.ForEach(record =>
            {
                if (record.trashed)
                {
                    trashedRecords.Add(record);
                }
                else
                {
                    if (!createSubfolders)
                    {
                        records.Add(record);
                    }
                    else
                    {
                        if (record.GetType() == typeof(WebFormRecord))
                        {
                            loginRecords.Add(record);
                        }
                        else if (record.GetType() == typeof(BankAccountRecord) ||
                                 record.GetType() == typeof(CreditCardRecord) ||
                                 record.GetType() == typeof(MembershipRecord) ||
                                 record.GetType() == typeof(SocialSecurityNumberRecord))
                        {
                            walletRecords.Add(record);
                        }
                        else if (record.GetType() == typeof(DatabaseConnectionRecord) ||
                                 record.GetType() == typeof(EmailAccountRecord) ||
                                 record.GetType() == typeof(FtpAccountRecord) ||
                                 record.GetType() == typeof(GenericAccountRecord) ||
                                 record.GetType() == typeof(UnixServerRecord) ||
                                 record.GetType() == typeof(RouterRecord))
                        {
                            accountsRecords.Add(record);
                        }
                        else if (record.GetType() == typeof(ComputerLicenseRecord))
                        {
                            softwareRecords.Add(record);
                        }
                        else if (record.GetType() == typeof(SecureNoteRecord))
                        {
                            secureNoteRecords.Add(record);
                        }
                        else if (record.GetType() == typeof(IndentityRecord))
                        {
                            identityRecords.Add(record);
                        }
                    }
                }
            });

            status.SetText("Importing records..", LogStatusType.Info);
            PwGroup root = new PwGroup(true, true);

            root.Name = "1Password Import on " + DateTime.Now.ToString();

            if (createSubfolders)
            {
                foreach (var category in RecordsList)
                {
                    PwGroup categoryGroup = new PwGroup(true, true);
                    categoryGroup.Name   = category.folderName;
                    categoryGroup.IconId = category.folderIcon;

                    var tree = BuildTree(category.recordList);
                    foreach (var node in tree)
                    {
                        ImportRecord(node, categoryGroup, storage);
                    }
                    root.AddGroup(categoryGroup, true);
                }
            }
            else
            {
                var tree = BuildTree(records);
                foreach (var node in tree)
                {
                    ImportRecord(node, root, storage);
                }
            }

            if (trashedRecords.Count > 0)
            {
                PwGroup trash = new PwGroup(true, true)
                {
                    Name = "Trash", IconId = PwIcon.TrashBin
                };

                foreach (var trecord in trashedRecords)
                {
                    var wfrecord = trecord as WebFormRecord;
                    if (wfrecord != null)
                    {
                        PwEntry entry = wfrecord.CreatePwEntry(storage);

                        if (entry != null)
                        {
                            trash.AddEntry(entry, true);
                        }
                    }
                }
                root.AddGroup(trash, true);
            }

            storage.RootGroup.AddGroup(root, true);
        }
Example #4
0
        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);

                    XmlNode xnTags = xmlChild.Attributes.GetNamedItem("TAGS");
                    if((xnTags != null) && (xnTags.Value != null))
                    {
                        string[] vTags = xnTags.Value.Split(',');
                        foreach(string strTag in vTags)
                        {
                            if(string.IsNullOrEmpty(strTag)) continue;
                            pe.AddTag(strTag);
                        }
                    }
                }
                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); }
            }
        }
        private static void AddObject(PwGroup pgStorage, JsonObject jObject,
            PwDatabase pwContext, bool bCreateSubGroups)
        {
            if(jObject.Items.ContainsKey(m_strGroup))
            {
                JsonArray jArray = jObject.Items[m_strGroup].Value as JsonArray;
                if(jArray == null) { Debug.Assert(false); return; }

                PwGroup pgNew;
                if(bCreateSubGroups)
                {
                    pgNew = new PwGroup(true, true);
                    pgStorage.AddGroup(pgNew, true);

                    if(jObject.Items.ContainsKey("title"))
                        pgNew.Name = ((jObject.Items["title"].Value != null) ?
                            jObject.Items["title"].Value.ToString() : string.Empty);
                }
                else pgNew = pgStorage;

                foreach(JsonValue jValue in jArray.Values)
                {
                    JsonObject objSub = jValue.Value as JsonObject;
                    if(objSub != null) AddObject(pgNew, objSub, pwContext, true);
                    else { Debug.Assert(false); }
                }

                return;
            }

            PwEntry pe = new PwEntry(true, true);

            SetString(pe, "Index", false, jObject, "index");
            SetString(pe, PwDefs.TitleField, pwContext.MemoryProtection.ProtectTitle,
                jObject, "title");
            SetString(pe, "ID", false, jObject, "id");
            SetString(pe, PwDefs.UrlField, pwContext.MemoryProtection.ProtectUrl,
                jObject, "uri");
            SetString(pe, "CharSet", false, jObject, "charset");

            if((pe.Strings.ReadSafe(PwDefs.TitleField).Length > 0) ||
                (pe.Strings.ReadSafe(PwDefs.UrlField).Length > 0))
                pgStorage.AddEntry(pe, true);
        }
Example #6
0
		internal PwGroup GetCurrentEntries()
		{
			PwGroup pg = new PwGroup(true, true);
			pg.IsVirtual = true;

			if(!m_lvEntries.ShowGroups)
			{
				foreach(ListViewItem lvi in m_lvEntries.Items)
					pg.AddEntry(((PwListItem)lvi.Tag).Entry, false);
			}
			else // Groups
			{
				foreach(ListViewGroup lvg in m_lvEntries.Groups)
				{
					foreach(ListViewItem lvi in lvg.Items)
						pg.AddEntry(((PwListItem)lvi.Tag).Entry, false);
				}
			}

			return pg;
		}
Example #7
0
        private PwGroup ConvertGroup(PwGroupV3 groupV3)
        {
            PwGroup pwGroup = new PwGroup(true, false);
            pwGroup.Uuid = CreateUuidFromGroupId(groupV3.Id.Id);

            //check if we have group data for this group already (from loading in a previous pass).
            //then use the same UUID (important for merging)
            var gdForGroup = _groupData.Where(g => g.Value.Id == groupV3.Id.Id).ToList();
            if (gdForGroup.Count == 1)
            {
                pwGroup.Uuid = gdForGroup.Single().Key;
            }

            pwGroup.Name = groupV3.Name;
            Android.Util.Log.Debug("KP2A", "load kdb: group " + groupV3.Name);
            pwGroup.CreationTime = ConvertTime(groupV3.TCreation);
            pwGroup.LastAccessTime = ConvertTime(groupV3.TLastAccess);
            pwGroup.LastModificationTime = ConvertTime(groupV3.TLastMod);
            pwGroup.ExpiryTime = ConvertTime(groupV3.TExpire);
            pwGroup.Expires = !(Math.Abs((pwGroup.ExpiryTime - _expireNever).TotalMilliseconds) < 500); ;

            if (groupV3.Icon != null)
                pwGroup.IconId = (PwIcon) groupV3.Icon.IconId;
            _groupData[pwGroup.Uuid] = new AdditionalGroupData
                {
                    Flags = groupV3.Flags,
                    Id = groupV3.Id.Id
                };

            for (int i = 0; i < groupV3.ChildGroups.Count;i++)
            {
                pwGroup.AddGroup(ConvertGroup(groupV3.GetGroupAt(i)), true);
            }
            for (int i = 0; i < groupV3.ChildEntries.Count; i++)
            {
                var entry = groupV3.GetEntryAt(i);
                if (entry.IsMetaStream)
                {
                    _metaStreams.Add(entry);
                    continue;
                }

                pwGroup.AddEntry(ConvertEntry(entry), true);
            }

            return pwGroup;
        }
Example #8
0
        private static void AddEntryIfValid(PwGroup pgContainer, PwEntry pe)
        {
            if(pe == null) return;

            if((pe.Strings.ReadSafe(PwDefs.TitleField).Length == 0) &&
                (pe.Strings.ReadSafe(PwDefs.UserNameField).Length == 0))
            {
                return;
            }

            pgContainer.AddEntry(pe, true);
        }
Example #9
0
        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.CloneDeep();

            pe.SetUuid(new PwUuid(true), true);
            pe.CreationTime = pe.LastModificationTime = pe.LastAccessTime = DateTime.Now;

            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);
            }
        }
Example #10
0
        private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent,
                                      PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);

            pgParent.AddEntry(pe, true);

            DateTime?ndt;

            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 == 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 == ElemEntryLastModTime)
                {
                    ndt = ReadTime(xmlChild);
                    if (ndt.HasValue)
                    {
                        pe.LastModificationTime = ndt.Value;
                    }
                }
                else if (xmlChild.Name == ElemEntryExpireTime)
                {
                    ndt = ReadTime(xmlChild);
                    if (ndt.HasValue)
                    {
                        pe.ExpiryTime = ndt.Value;
                        pe.Expires    = true;
                    }
                }
                else if (xmlChild.Name == ElemEntryCreatedTime)
                {
                    ndt = ReadTime(xmlChild);
                    if (ndt.HasValue)
                    {
                        pe.CreationTime = ndt.Value;
                    }
                }
                else if (xmlChild.Name == ElemEntryLastAccTime)
                {
                    ndt = ReadTime(xmlChild);
                    if (ndt.HasValue)
                    {
                        pe.LastAccessTime = ndt.Value;
                    }
                }
                else if (xmlChild.Name == ElemEntryUsageCount)
                {
                    ulong uUsageCount;
                    if (ulong.TryParse(XmlUtil.SafeInnerText(xmlChild), out uUsageCount))
                    {
                        pe.UsageCount = uUsageCount;
                    }
                }
                else if (xmlChild.Name == ElemEntryAutoType)
                {
                    pe.AutoType.DefaultSequence = MapAutoType(
                        XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemEntryCustom)
                {
                    ReadCustomContainer(xmlChild, pe);
                }
                else if (xmlChild.Name == ElemImageIndex)
                {
                    pe.IconId = MapIcon(XmlUtil.SafeInnerText(xmlChild), true);
                }
                else if (Array.IndexOf <string>(ElemEntryUnsupportedItems,
                                                xmlChild.Name) >= 0)
                {
                }
                else
                {
                    Debug.Assert(false, xmlChild.Name);
                }
            }

            string strInfoText = pe.Strings.ReadSafe(FieldInfoText);

            if ((pe.Strings.ReadSafe(PwDefs.NotesField).Length == 0) &&
                (strInfoText.Length > 0))
            {
                pe.Strings.Remove(FieldInfoText);
                pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectNotes, strInfoText));
            }
        }
Example #11
0
        private static void ImportEntry(string strData, PwGroup pg, PwDatabase pd,
                                        bool bForceNotes)
        {
            PwEntry pe = new PwEntry(true, true);

            pg.AddEntry(pe, true);

            string[] v = strData.Split('\n');

            if (v.Length == 0)
            {
                Debug.Assert(false); return;
            }
            ImportUtil.AppendToField(pe, PwDefs.TitleField, v[0].Trim(), pd);

            int n = v.Length;

            for (int j = n - 1; j >= 0; --j)
            {
                if (v[j].Length > 0)
                {
                    break;
                }
                --n;
            }

            bool bInNotes = bForceNotes;

            for (int i = 1; i < n; ++i)
            {
                string str = v[i];

                int iSep = str.IndexOf(':');
                if (iSep <= 0)
                {
                    bInNotes = true;
                }

                if (bInNotes)
                {
                    if (str.Length == 0)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.NotesField,
                                                 MessageService.NewLine, pd, string.Empty, false);
                    }
                    else
                    {
                        ImportUtil.AppendToField(pe, PwDefs.NotesField, str, pd);
                    }
                }
                else
                {
                    string strRawKey = str.Substring(0, iSep);
                    string strValue  = str.Substring(iSep + 1).Trim();

                    string strKey = ImportUtil.MapNameToStandardField(strRawKey, false);
                    if (string.IsNullOrEmpty(strKey))
                    {
                        strKey = strRawKey;
                    }

                    ImportUtil.AppendToField(pe, strKey, strValue, pd);
                }
            }
        }
Example #12
0
        private KdbContext ReadXmlElement(KdbContext ctx, XmlReader xr)
        {
            Debug.Assert(xr.NodeType == XmlNodeType.Element);

            switch (ctx)
            {
            case KdbContext.Null:
                if (xr.Name == ElemDocNode)
                {
                    return(SwitchContext(ctx, KdbContext.KeePassFile, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.KeePassFile:
                if (xr.Name == ElemMeta)
                {
                    return(SwitchContext(ctx, KdbContext.Meta, xr));
                }
                else if (xr.Name == ElemRoot)
                {
                    return(SwitchContext(ctx, KdbContext.Root, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Meta:
                if (xr.Name == ElemGenerator)
                {
                    ReadString(xr);                             // Ignore
                }
                else if (xr.Name == ElemDbName)
                {
                    m_pwDatabase.Name = ReadString(xr);
                }
                else if (xr.Name == ElemDbDesc)
                {
                    m_pwDatabase.Description = ReadString(xr);
                }
                else if (xr.Name == ElemDbDefaultUser)
                {
                    m_pwDatabase.DefaultUserName = ReadString(xr);
                }
                else if (xr.Name == ElemDbMntncHistoryDays)
                {
                    m_pwDatabase.MaintenanceHistoryDays = ReadUInt(xr, 365);
                }
                else if (xr.Name == ElemMemoryProt)
                {
                    return(SwitchContext(ctx, KdbContext.MemoryProtection, xr));
                }
                else if (xr.Name == ElemCustomIcons)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcons, xr));
                }
                else if (xr.Name == ElemLastSelectedGroup)
                {
                    m_pwDatabase.LastSelectedGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemLastTopVisibleGroup)
                {
                    m_pwDatabase.LastTopVisibleGroup = ReadUuid(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.MemoryProtection:
                if (xr.Name == ElemProtTitle)
                {
                    m_pwDatabase.MemoryProtection.ProtectNotes = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtUserName)
                {
                    m_pwDatabase.MemoryProtection.ProtectUserName = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtPassword)
                {
                    m_pwDatabase.MemoryProtection.ProtectPassword = ReadBool(xr, true);
                }
                else if (xr.Name == ElemProtURL)
                {
                    m_pwDatabase.MemoryProtection.ProtectUrl = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtNotes)
                {
                    m_pwDatabase.MemoryProtection.ProtectNotes = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtAutoHide)
                {
                    m_pwDatabase.MemoryProtection.AutoEnableVisualHiding = ReadBool(xr, true);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcons:
                if (xr.Name == ElemCustomIconItem)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcon, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcon:
                if (xr.Name == ElemCustomIconItemID)
                {
                    m_uuidCustomIconID = ReadUuid(xr);
                }
                else if (xr.Name == ElemCustomIconItemData)
                {
                    string strData = ReadString(xr);
                    if ((strData != null) && (strData.Length > 0))
                    {
                        m_pbCustomIconData = Convert.FromBase64String(strData);
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Root:
                if (xr.Name == ElemGroup)
                {
                    Debug.Assert(m_ctxGroups.Count == 0);
                    if (m_ctxGroups.Count != 0)
                    {
                        throw new FormatException();
                    }

                    m_pwDatabase.RootGroup = new PwGroup(false, false);
                    m_ctxGroups.Push(m_pwDatabase.RootGroup);
                    m_ctxGroup = m_ctxGroups.Peek();

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemDeletedObjects)
                {
                    return(SwitchContext(ctx, KdbContext.RootDeletedObjects, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Group:
                if (xr.Name == ElemUuid)
                {
                    m_ctxGroup.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemName)
                {
                    m_ctxGroup.Name = ReadString(xr);
                }
                else if (xr.Name == ElemNotes)
                {
                    m_ctxGroup.Notes = ReadString(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxGroup.IconId = (PwIcon)ReadUInt(xr, (uint)PwIcon.Folder);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxGroup.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.GroupTimes, xr));
                }
                else if (xr.Name == ElemIsExpanded)
                {
                    m_ctxGroup.IsExpanded = ReadBool(xr, true);
                }
                else if (xr.Name == ElemGroupDefaultAutoTypeSeq)
                {
                    m_ctxGroup.DefaultAutoTypeSequence = ReadString(xr);
                }
                else if (xr.Name == ElemLastTopVisibleEntry)
                {
                    m_ctxGroup.LastTopVisibleEntry = ReadUuid(xr);
                }
                else if (xr.Name == ElemGroup)
                {
                    m_ctxGroup = new PwGroup(false, false);
                    m_ctxGroups.Peek().AddGroup(m_ctxGroup, true);

                    m_ctxGroups.Push(m_ctxGroup);

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxGroup.AddEntry(m_ctxEntry, true);

                    m_bEntryInHistory = false;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Entry:
                if (xr.Name == ElemUuid)
                {
                    m_ctxEntry.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxEntry.IconId = (PwIcon)ReadUInt(xr, (uint)PwIcon.Key);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxEntry.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemFgColor)
                {
                    string strColor = ReadString(xr);
                    if ((strColor != null) && (strColor.Length > 0))
                    {
                        m_ctxEntry.ForegroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemBgColor)
                {
                    string strColor = ReadString(xr);
                    if ((strColor != null) && (strColor.Length > 0))
                    {
                        m_ctxEntry.BackgroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemOverrideUrl)
                {
                    m_ctxEntry.OverrideUrl = ReadString(xr);
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.EntryTimes, xr));
                }
                else if (xr.Name == ElemString)
                {
                    return(SwitchContext(ctx, KdbContext.EntryString, xr));
                }
                else if (xr.Name == ElemBinary)
                {
                    return(SwitchContext(ctx, KdbContext.EntryBinary, xr));
                }
                else if (xr.Name == ElemAutoType)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoType, xr));
                }
                else if (xr.Name == ElemHistory)
                {
                    Debug.Assert(m_bEntryInHistory == false);

                    if (m_bEntryInHistory == false)
                    {
                        m_ctxHistoryBase = m_ctxEntry;
                        return(SwitchContext(ctx, KdbContext.EntryHistory, xr));
                    }
                    else
                    {
                        ReadUnknown(xr);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.GroupTimes:
            case KdbContext.EntryTimes:
                ITimeLogger tl = ((ctx == KdbContext.GroupTimes) ?
                                  (ITimeLogger)m_ctxGroup : (ITimeLogger)m_ctxEntry);
                Debug.Assert(tl != null);

                if (xr.Name == ElemLastModTime)
                {
                    tl.LastModificationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemCreationTime)
                {
                    tl.CreationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemLastAccessTime)
                {
                    tl.LastAccessTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpiryTime)
                {
                    tl.ExpiryTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpires)
                {
                    tl.Expires = ReadBool(xr, false);
                }
                else if (xr.Name == ElemUsageCount)
                {
                    tl.UsageCount = ReadULong(xr, 0);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryString:
                if (xr.Name == ElemKey)
                {
                    m_ctxStringName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxStringValue = ReadProtectedString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryBinary:
                if (xr.Name == ElemKey)
                {
                    m_ctxBinaryName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxBinaryValue = ReadProtectedBinary(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoType:
                if (xr.Name == ElemAutoTypeEnabled)
                {
                    m_ctxEntry.AutoType.Enabled = ReadBool(xr, true);
                }
                else if (xr.Name == ElemAutoTypeObfuscation)
                {
                    m_ctxEntry.AutoType.ObfuscationOptions =
                        (AutoTypeObfuscationOptions)ReadUInt(xr, 0);
                }
                else if (xr.Name == ElemAutoTypeDefaultSeq)
                {
                    m_ctxEntry.AutoType.DefaultSequence = ReadString(xr);
                }
                else if (xr.Name == ElemAutoTypeItem)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoTypeItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoTypeItem:
                if (xr.Name == ElemWindow)
                {
                    m_ctxATName = ReadString(xr);
                }
                else if (xr.Name == ElemKeystrokeSequence)
                {
                    m_ctxATSeq = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryHistory:
                if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxHistoryBase.History.Add(m_ctxEntry);

                    m_bEntryInHistory = true;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.RootDeletedObjects:
                if (xr.Name == ElemDeletedObject)
                {
                    m_ctxDeletedObject = new PwDeletedObject();
                    m_pwDatabase.DeletedObjects.Add(m_ctxDeletedObject);

                    return(SwitchContext(ctx, KdbContext.DeletedObject, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.DeletedObject:
                if (xr.Name == ElemUuid)
                {
                    m_ctxDeletedObject.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemDeletionTime)
                {
                    m_ctxDeletedObject.DeletionTime = ReadTime(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            default:
                ReadUnknown(xr);
                break;
            }

            return(ctx);
        }
        private void PerformImport(PwGroup pgStorage, bool bCreatePreview)
        {
            List <CsvFieldInfo> lFields = GetCsvFieldInfos();

            if (bCreatePreview)
            {
                int dx = m_lvImportPreview.ClientRectangle.Width;                 // Before clearing

                m_lvImportPreview.Items.Clear();
                m_lvImportPreview.Columns.Clear();

                foreach (CsvFieldInfo cfi in lFields)
                {
                    string strCol = CsvFieldToString(cfi.Type);
                    if (cfi.Type == CsvFieldType.CustomString)
                    {
                        strCol = (cfi.Name ?? string.Empty);
                    }
                    m_lvImportPreview.Columns.Add(strCol, dx / lFields.Count);
                }
            }

            CsvOptions opt = GetCsvOptions();

            if (opt == null)
            {
                Debug.Assert(bCreatePreview); return;
            }

            string            strData = GetDecodedText();
            CsvStreamReaderEx csr     = new CsvStreamReaderEx(strData, opt);

            Dictionary <string, PwGroup> dGroups = new Dictionary <string, PwGroup>();

            dGroups[string.Empty] = pgStorage;

            if (bCreatePreview)
            {
                m_lvImportPreview.BeginUpdate();
            }

            DateTime dtNow           = DateTime.UtcNow;
            DateTime dtNoExpire      = KdbTime.NeverExpireTime.ToDateTime();
            bool     bIgnoreFirstRow = m_cbIgnoreFirst.Checked;
            bool     bIsFirstRow     = true;
            bool     bMergeGroups    = m_cbMergeGroups.Checked;

            while (true)
            {
                string[] v = csr.ReadLine();
                if (v == null)
                {
                    break;
                }
                if (v.Length == 0)
                {
                    continue;
                }
                if ((v.Length == 1) && (v[0].Length == 0))
                {
                    continue;
                }

                if (bIsFirstRow && bIgnoreFirstRow)
                {
                    bIsFirstRow = false;
                    continue;
                }
                bIsFirstRow = false;

                PwGroup pg = pgStorage;
                PwEntry pe = new PwEntry(true, true);

                ListViewItem lvi = null;
                for (int i = 0; i < Math.Min(v.Length, lFields.Count); ++i)
                {
                    string       strField = v[i];
                    CsvFieldInfo cfi      = lFields[i];

                    if (cfi.Type == CsvFieldType.Ignore)
                    {
                    }
                    else if (cfi.Type == CsvFieldType.Group)
                    {
                        pg = FindCreateGroup(strField, pgStorage, dGroups,
                                             cfi.Format, opt, bMergeGroups);
                    }
                    else if (cfi.Type == CsvFieldType.Title)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.TitleField,
                                                 strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.UserName)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.UserNameField,
                                                 strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.Password)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.PasswordField,
                                                 strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.Url)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.UrlField,
                                                 strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.Notes)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.NotesField,
                                                 strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.CustomString)
                    {
                        ImportUtil.AppendToField(pe, (string.IsNullOrEmpty(cfi.Name) ?
                                                      PwDefs.NotesField : cfi.Name), strField, m_pwDatabase);
                    }
                    else if (cfi.Type == CsvFieldType.CreationTime)
                    {
                        pe.CreationTime = ParseDateTime(ref strField, cfi, dtNow);
                    }
                    // else if(cfi.Type == CsvFieldType.LastAccessTime)
                    //	pe.LastAccessTime = ParseDateTime(ref strField, cfi, dtNow);
                    else if (cfi.Type == CsvFieldType.LastModTime)
                    {
                        pe.LastModificationTime = ParseDateTime(ref strField, cfi, dtNow);
                    }
                    else if (cfi.Type == CsvFieldType.ExpiryTime)
                    {
                        bool bParseSuccess;
                        pe.ExpiryTime = ParseDateTime(ref strField, cfi, dtNow,
                                                      out bParseSuccess);
                        pe.Expires = (bParseSuccess && (pe.ExpiryTime != dtNoExpire));
                    }
                    else if (cfi.Type == CsvFieldType.Tags)
                    {
                        List <string> lTags = StrUtil.StringToTags(strField);
                        foreach (string strTag in lTags)
                        {
                            pe.AddTag(strTag);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }

                    if (bCreatePreview)
                    {
                        strField = StrUtil.MultiToSingleLine(strField);

                        if (lvi != null)
                        {
                            lvi.SubItems.Add(strField);
                        }
                        else
                        {
                            lvi = m_lvImportPreview.Items.Add(strField);
                        }
                    }
                }

                if (bCreatePreview)
                {
                    // Create remaining subitems
                    for (int r = v.Length; r < lFields.Count; ++r)
                    {
                        if (lvi != null)
                        {
                            lvi.SubItems.Add(string.Empty);
                        }
                        else
                        {
                            lvi = m_lvImportPreview.Items.Add(string.Empty);
                        }
                    }
                }

                pg.AddEntry(pe, true);
            }

            if (bCreatePreview)
            {
                m_lvImportPreview.EndUpdate();
                ProcessResize();
            }
        }
Example #14
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr          = new StreamReader(sInput, Encoding.Default);
            string       strDocument = sr.ReadToEnd();

            sr.Close();

            PwGroup pg = pwStorage.RootGroup;

            CharStream cs = new CharStream(strDocument);

            string[] vFields            = new string[7];
            char[]   vDateFieldSplitter = new char[] { '/' };
            char[]   vDateZeroTrim      = new char[] { '0' };

            bool bFirst = true;

            while (true)
            {
                bool bSubZero = false;
                for (int iField = 0; iField < vFields.Length; ++iField)
                {
                    vFields[iField] = ReadCsvField(cs);

                    if ((iField > 0) && (vFields[iField] == null))
                    {
                        bSubZero = true;
                    }
                }
                if (vFields[0] == null)
                {
                    break;                                    // Import successful
                }
                else if (bSubZero)
                {
                    throw new FormatException();
                }

                if (bFirst)
                {
                    bFirst = false;                     // Check first line once only

                    if ((vFields[0] != "ServiceName") || (vFields[1] != "UserName") ||
                        (vFields[2] != "Password") || (vFields[3] != "Memo") ||
                        (vFields[4] != "Expire") || (vFields[5] != "StartDate") ||
                        (vFields[6] != "DaysToLive"))
                    {
                        Debug.Assert(false);
                        throw new FormatException();
                    }
                    else
                    {
                        continue;
                    }
                }

                PwEntry pe = new PwEntry(true, true);
                pg.AddEntry(pe, true);

                pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectTitle, vFields[0]));
                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectUserName, vFields[1]));
                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectPassword, vFields[2]));
                pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectNotes, vFields[3]));

                pe.Expires = (vFields[4] == "true");

                try
                {
                    string[] vDateParts = vFields[5].Split(vDateFieldSplitter);
                    DateTime dt         = (new DateTime(
                                               int.Parse(vDateParts[2].TrimStart(vDateZeroTrim)),
                                               int.Parse(vDateParts[0].TrimStart(vDateZeroTrim)),
                                               int.Parse(vDateParts[1].TrimStart(vDateZeroTrim)),
                                               0, 0, 0, DateTimeKind.Local)).ToUniversalTime();
                    pe.LastModificationTime = dt;
                    pe.LastAccessTime       = dt;
                    pe.ExpiryTime           = dt.AddDays(double.Parse(vFields[6]));
                }
                catch (Exception) { Debug.Assert(false); }

                pe.Strings.Set("Days To Live", new ProtectedString(false,
                                                                   vFields[6]));
            }
        }
Example #15
0
        public void Import(List <Records.BaseRecord> records, PwDatabase pwDatabase, IStatusLogger statusLogger, UserPrefs userPrefs)
        {
            List <Records.ItemRecord> trashedRecords = null;

            records.RemoveAll(record => record is Records.SavedSearchRecord);

            // Copy trashed items to another collection
            if (userPrefs.KeepTrashedItems)
            {
                trashedRecords = records.FindAll(record => (record is Records.ItemRecord) && (record as Records.ItemRecord).trashed).ConvertAll <Records.ItemRecord>(record => record as Records.ItemRecord);
            }

            // Filter out trashed items from main set
            records.RemoveAll(record => (record is Records.ItemRecord) && (record as Records.ItemRecord).trashed);

            if (userPrefs.FolderLayout == FolderLayout.Category)
            {
                // Since they're not being used, filter out user-defined folders from main set
                records = records.FindAll(record => record is Records.ItemRecord);

                // Assign parent folder to items according to their category
                foreach (Records.ItemRecord itemRecord in records.ConvertAll(record => record as Records.ItemRecord))
                {
                    ItemCategory itemCategory = ItemCategory.Unknown;

                    if (!categoriesByRecordType.TryGetValue(itemRecord.typeName, out itemCategory))
                    {
                        itemCategory = ItemCategory.Unknown;
                    }

                    Records.RegularFolderRecord categoryFolder = Records.RegularFolderRecord.FolderRecordForCategory(itemCategory);

                    if (!records.Contains(categoryFolder))
                    {
                        records.Add(categoryFolder);
                    }

                    itemRecord.folderUuid = categoryFolder.uuid;
                }
            }
            else if (userPrefs.FolderLayout == FolderLayout.UserDefined)
            {
                Records.RegularFolderRecord unassignedFolder = null;

                // Assign orphan items the "Unassigned" folder as parent
                foreach (Records.ItemRecord itemRecord in records.FindAll(record => (record is Records.ItemRecord) && Guid.Empty.Equals((record as Records.ItemRecord).folderUuid)))
                {
                    if (unassignedFolder == null)
                    {
                        unassignedFolder = Records.RegularFolderRecord.UnassignedFolderRecord;
                        records.Add(unassignedFolder);
                    }

                    itemRecord.folderUuid = Records.RegularFolderRecord.UnassignedFolderRecord.uuid;
                }
            }

            IEnumerable <TreeNode <Records.BaseRecord> > tree = buildTree(records);

            PwGroup rootGroup = null;

            if (userPrefs.CreateParentFolder)
            {
                rootGroup = new PwGroup(true, true)
                {
                    Name = "1Password Import on " + DateTimeFormatter.FormatDateTime(DateTime.Now, userPrefs.DateFormat)
                }
            }
            ;
            else
            {
                rootGroup = pwDatabase.RootGroup;
            }

            foreach (TreeNode <Records.BaseRecord> node in tree)
            {
                importRecord(node, rootGroup, pwDatabase, userPrefs);
            }

            if (trashedRecords != null && trashedRecords.Count > 0)
            {
                PwGroup trashGroup = Records.RegularFolderRecord.TrashFolderRecord.CreatePwGroup();

                foreach (Records.ItemRecord trashedRecord in trashedRecords)
                {
                    PwEntry entry = trashedRecord.CreatePwEntry(pwDatabase, userPrefs);
                    trashGroup.AddEntry(entry, true);
                }

                rootGroup.AddGroup(trashGroup, true);
            }

            if (userPrefs.CreateParentFolder)
            {
                pwDatabase.RootGroup.AddGroup(rootGroup, true);
            }
        }
Example #16
0
		private void OnFileNew(object sender, EventArgs e)
		{
			if(!AppPolicy.Try(AppPolicyId.NewFile)) return;
			if(!AppPolicy.Try(AppPolicyId.SaveFile)) return;

			SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase,
				KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter(
				AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1,
				AppDefs.FileExtension.FileExt, AppDefs.FileDialogContext.Database);

			GlobalWindowManager.AddDialog(sfd.FileDialog);
			DialogResult dr = sfd.ShowDialog();
			GlobalWindowManager.RemoveDialog(sfd.FileDialog);

			string strPath = sfd.FileName;

			if(dr != DialogResult.OK) return;

			KeyCreationForm kcf = new KeyCreationForm();
			kcf.InitEx(IOConnectionInfo.FromPath(strPath), true);
			dr = kcf.ShowDialog();
			if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
			{
				UIUtil.DestroyForm(kcf);
				return;
			}

			PwDocument dsPrevActive = m_docMgr.ActiveDocument;
			PwDatabase pd = m_docMgr.CreateNewDocument(true).Database;
			pd.New(IOConnectionInfo.FromPath(strPath), kcf.CompositeKey);

			UIUtil.DestroyForm(kcf);

			DatabaseSettingsForm dsf = new DatabaseSettingsForm();
			dsf.InitEx(true, pd);
			dr = dsf.ShowDialog();
			if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
			{
				m_docMgr.CloseDatabase(pd);
				try { m_docMgr.ActiveDocument = dsPrevActive; }
				catch(Exception) { } // Fails if no database is open now
				UpdateUI(false, null, true, null, true, null, false);
				UIUtil.DestroyForm(dsf);
				return;
			}
			UIUtil.DestroyForm(dsf);

			// AutoEnableVisualHiding();

			PwGroup pg = new PwGroup(true, true, KPRes.General, PwIcon.Folder);
			// for(int i = 0; i < 30; ++i) pg.CustomData.Set("Test" + i.ToString("D2"), "12345");
			pd.RootGroup.AddGroup(pg, true);

			pg = new PwGroup(true, true, KPRes.WindowsOS, PwIcon.DriveWindows);
			pd.RootGroup.AddGroup(pg, true);

			pg = new PwGroup(true, true, KPRes.Network, PwIcon.NetworkServer);
			pd.RootGroup.AddGroup(pg, true);

			pg = new PwGroup(true, true, KPRes.Internet, PwIcon.World);
			// pg.CustomData.Set("GroupTestItem", "TestValue");
			pd.RootGroup.AddGroup(pg, true);

			pg = new PwGroup(true, true, KPRes.EMail, PwIcon.EMail);
			pd.RootGroup.AddGroup(pg, true);

			pg = new PwGroup(true, true, KPRes.Homebanking, PwIcon.Homebanking);
			pd.RootGroup.AddGroup(pg, true);

			PwEntry pe = new PwEntry(true, true);
			pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
				KPRes.SampleEntry));
			pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
				KPRes.UserName));
			pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
				PwDefs.HomepageUrl));
			pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
				KPRes.Password));
			pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes,
				KPRes.Notes));
			pe.AutoType.Add(new AutoTypeAssociation(KPRes.TargetWindow,
				@"{USERNAME}{TAB}{PASSWORD}{TAB}{ENTER}"));
			// for(int i = 0; i < 30; ++i) pe.CustomData.Set("Test" + i.ToString("D2"), "12345");
			pd.RootGroup.AddEntry(pe, true);

			pe = new PwEntry(true, true);
			pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
				KPRes.SampleEntry + " #2"));
			pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
				"Michael321"));
			pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
				@"http://keepass.info/help/kb/testform.html"));
			pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
				"12345"));
			pe.AutoType.Add(new AutoTypeAssociation("*Test Form - KeePass*", string.Empty));
			pd.RootGroup.AddEntry(pe, true);

#if DEBUG
			Random r = Program.GlobalRandom;
			long lTimeMin = (new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).ToBinary();
			long lTimeMax = (new DateTime(2030, 11, 25, 11, 58, 58, DateTimeKind.Utc)).ToBinary();
			Debug.Assert(lTimeMin < lTimeMax);
			PwProfile prf = new PwProfile();
			prf.CharSet = new PwCharSet(PwCharSet.UpperCase + PwCharSet.LowerCase +
				PwCharSet.Digits + PwCharSet.PrintableAsciiSpecial);
			prf.GeneratorType = PasswordGeneratorType.CharSet;
			for(uint iSamples = 0; iSamples < 1500; ++iSamples)
			{
				pg = pd.RootGroup.Groups.GetAt(iSamples % 5);

				pe = new PwEntry(true, true);

				ProtectedString ps;
				PwGenerator.Generate(out ps, prf, null, null);
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
					ps.ReadString()));
				PwGenerator.Generate(out ps, prf, null, null);
				pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
					ps.ReadString()));
				PwGenerator.Generate(out ps, prf, null, null);
				pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
					ps.ReadString()));
				PwGenerator.Generate(out ps, prf, null, null);
				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
					ps.ReadString()));
				PwGenerator.Generate(out ps, prf, null, null);
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes,
					ps.ReadString()));

				pe.CreationTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() *
					(lTimeMax - lTimeMin)));
				pe.LastModificationTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() *
					(lTimeMax - lTimeMin)));
				pe.LastAccessTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() *
					(lTimeMax - lTimeMin)));
				pe.ExpiryTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() *
					(lTimeMax - lTimeMin)));
				pe.LocationChanged = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() *
					(lTimeMax - lTimeMin)));

				pe.IconId = (PwIcon)r.Next(0, (int)PwIcon.Count);

				pg.AddEntry(pe, true);
			}

			pd.CustomData.Set("Sample Custom Data 1", "0123456789");
			pd.CustomData.Set("Sample Custom Data 2", "\u00B5y data");

			// pd.PublicCustomData.SetString("Sample Custom Data", "Sample Value");
#endif

			UpdateUI(true, null, true, null, true, null, true);

			if(this.FileCreated != null)
			{
				FileCreatedEventArgs ea = new FileCreatedEventArgs(pd);
				this.FileCreated(this, ea);
			}
		}
		private static void AddEntry(PwGroup pg, Dictionary<string, string> dItems,
			ref bool bInNotes)
		{
			if(dItems.Count == 0) return;

			PwEntry pe = new PwEntry(true, true);
			pg.AddEntry(pe, true);

			foreach(KeyValuePair<string, string> kvp in dItems)
				pe.Strings.Set(kvp.Key, new ProtectedString(false, kvp.Value));

			bInNotes = false;
		}
Example #18
0
        private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage,
                                        string strLineBreak)
        {
            Debug.Assert(xmlNode != null); if (xmlNode == null)
            {
                return;
            }

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

            List <DatePasswordPair> listHistory = null;

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

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

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

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

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

            PwGroup pgContainer = pwStorage.RootGroup;

            if (strGroupName.Length != 0)
            {
                pgContainer = pwStorage.RootGroup.FindCreateSubTree(strGroupName,
                                                                    new string[1] {
                    "."
                }, true);
            }
            pgContainer.AddEntry(pe, true);
            pgContainer.IsExpanded = true;
        }
Example #19
0
        private void SetGrouping(AceListGrouping lgPrimary)
        {
            Debug.Assert(((int)lgPrimary & ~(int)AceListGrouping.Primary) == 0);
            if((int)lgPrimary == (Program.Config.MainWindow.ListGrouping &
                (int)AceListGrouping.Primary))
                return;

            Program.Config.MainWindow.ListGrouping &= ~(int)AceListGrouping.Primary;
            Program.Config.MainWindow.ListGrouping |= (int)lgPrimary;
            Debug.Assert((Program.Config.MainWindow.ListGrouping &
                (int)AceListGrouping.Primary) == (int)lgPrimary);
            UpdateUI();

            if(m_mf == null) { Debug.Assert(false); return; }

            PwDatabase pd = m_mf.ActiveDatabase;
            PwGroup pg = m_mf.GetCurrentEntries();
            if((pd == null) || !pd.IsOpen || (pg == null)) return; // No assert

            PwObjectList<PwEntry> pwl = pg.GetEntries(true);
            if((pwl.UCount > 0) && EntryUtil.EntriesHaveSameParent(pwl))
                m_mf.UpdateUI(false, null, true, pwl.GetAt(0).ParentGroup,
                    true, null, false);
            else
            {
                EntryUtil.ReorderEntriesAsInDatabase(pwl, pd); // Requires open DB

                pg = new PwGroup(true, true);
                pg.IsVirtual = true;
                foreach(PwEntry pe in pwl) pg.AddEntry(pe, false);

                m_mf.UpdateUI(false, null, false, null, true, pg, false);
            }
        }
Example #20
0
        private static void ReadEntry(XmlNode xmlNode, PwDatabase pwStorage,
                                      Dictionary <string, PwGroup> dictGroups)
        {
            PwEntry pe = new PwEntry(true, true);
            PwGroup pg = pwStorage.RootGroup;

            string strAttachDesc = null, strAttachment = null;

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    string strPreTree = null;
                    try
                    {
                        XmlNode xmlTree = xmlChild.Attributes.GetNamedItem(AttribGroupTree);
                        strPreTree = xmlTree.Value;
                    }
                    catch (Exception) { }

                    string strLast  = XmlUtil.SafeInnerText(xmlChild);
                    string strGroup = ((!string.IsNullOrEmpty(strPreTree)) ?
                                       strPreTree + "\\" + strLast : strLast);

                    pg = pwStorage.RootGroup.FindCreateSubTree(strGroup,
                                                               new char[] { '\\' });
                }
                else if (xmlChild.Name == ElemTitle)
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUserName)
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUrl)
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUuid)
                {
                    pe.Uuid = new PwUuid(MemUtil.HexStringToByteArray(
                                             XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemImage)
                {
                    uint uImage;
                    if (uint.TryParse(XmlUtil.SafeInnerText(xmlChild), out uImage))
                    {
                        if (uImage < (uint)PwIcon.Count)
                        {
                            pe.IconId = (PwIcon)uImage;
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else if (xmlChild.Name == ElemCreationTime)
                {
                    pe.CreationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastModTime)
                {
                    pe.LastModificationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastAccessTime)
                {
                    pe.LastAccessTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemExpiryTime)
                {
                    try
                    {
                        XmlNode xmlExpires = xmlChild.Attributes.GetNamedItem(AttribExpires);
                        if (StrUtil.StringToBool(xmlExpires.Value))
                        {
                            pe.Expires    = true;
                            pe.ExpiryTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                        }
                        else
                        {
                            Debug.Assert(ParseTime(XmlUtil.SafeInnerText(xmlChild)).Year == 2999);
                        }
                    }
                    catch (Exception) { Debug.Assert(false); }
                }
                else if (xmlChild.Name == ElemAttachDesc)
                {
                    strAttachDesc = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemAttachment)
                {
                    strAttachment = XmlUtil.SafeInnerText(xmlChild);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if (!string.IsNullOrEmpty(strAttachDesc) && (strAttachment != null))
            {
                byte[]          pbData = Convert.FromBase64String(strAttachment);
                ProtectedBinary pb     = new ProtectedBinary(false, pbData);
                pe.Binaries.Set(strAttachDesc, pb);
            }

            pg.AddEntry(pe, true);
        }
Example #21
0
		private static void AddEntryIfValid(PwGroup pgContainer, ref PwEntry pe)
		{
			try
			{
				if(pe == null) return;
				if(pe.Strings.ReadSafe(PwDefs.TitleField).Length == 0) return;

				pgContainer.AddEntry(pe, true);
			}
			finally { pe = new PwEntry(true, true); }
		}
Example #22
0
        private static void ImportPriv(PwDatabase pd, HtmlElement hBody)
        {
#if DEBUG
            bool bHasSpanCaptions = (GetElements(hBody, "SPAN", "class",
                                                 "caption").Count > 0);
#endif

            foreach (HtmlElement hTable in hBody.GetElementsByTagName("TABLE"))
            {
                Debug.Assert(XmlUtil.SafeAttribute(hTable, "width") == "100%");
                string strRules = XmlUtil.SafeAttribute(hTable, "rules");
                string strFrame = XmlUtil.SafeAttribute(hTable, "frame");
                if (strRules.Equals("cols", StrUtil.CaseIgnoreCmp) &&
                    strFrame.Equals("void", StrUtil.CaseIgnoreCmp))
                {
                    continue;
                }

                PwEntry pe = new PwEntry(true, true);
                PwGroup pg = null;
                bool    bNotesHeaderFound = false;

                foreach (HtmlElement hTr in hTable.GetElementsByTagName("TR"))
                {
                    // 7.9.1.1+
                    List <HtmlElement> lCaption = GetElements(hTr, "SPAN",
                                                              "class", "caption");
                    if (lCaption.Count == 0)
                    {
                        lCaption = GetElements(hTr, "DIV", "class", "caption");
                    }
                    if (lCaption.Count > 0)
                    {
                        string strTitle = ParseTitle(XmlUtil.SafeInnerText(
                                                         lCaption[0]), pd, out pg);
                        ImportUtil.AppendToField(pe, PwDefs.TitleField, strTitle, pd);
                        continue;                         // Data is in next TR
                    }

                    // 7.9.1.1+
                    if (hTr.GetElementsByTagName("TABLE").Count > 0)
                    {
                        continue;
                    }

                    HtmlElementCollection lTd = hTr.GetElementsByTagName("TD");
                    if (lTd.Count == 1)
                    {
                        HtmlElement e        = lTd[0];
                        string      strText  = XmlUtil.SafeInnerText(e);
                        string      strClass = XmlUtil.SafeAttribute(e, "class");

                        if (strClass.Equals("caption", StrUtil.CaseIgnoreCmp))
                        {
                            Debug.Assert(pg == null);
                            strText = ParseTitle(strText, pd, out pg);
                            ImportUtil.AppendToField(pe, PwDefs.TitleField, strText, pd);
                        }
                        else if (strClass.Equals("subcaption", StrUtil.CaseIgnoreCmp))
                        {
                            ImportUtil.AppendToField(pe, PwDefs.UrlField,
                                                     ImportUtil.FixUrl(strText), pd);
                        }
                        else if (strClass.Equals("field", StrUtil.CaseIgnoreCmp))
                        {
                            // 7.9.2.5+
                            if (strText.EndsWith(":") && !bNotesHeaderFound)
                            {
                                bNotesHeaderFound = true;
                            }
                            else
                            {
                                ImportUtil.AppendToField(pe, PwDefs.NotesField,
                                                         strText.Trim(), pd);
                            }
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else if ((lTd.Count == 2) || (lTd.Count == 3))
                    {
                        string strKey   = XmlUtil.SafeInnerText(lTd[0]);
                        string strValue = XmlUtil.SafeInnerText(lTd[lTd.Count - 1]);
                        if (lTd.Count == 3)
                        {
                            Debug.Assert(string.IsNullOrEmpty(lTd[1].InnerText));
                        }

                        if (strKey.EndsWith(":"))                        // 7.9.1.1+
                        {
                            strKey = strKey.Substring(0, strKey.Length - 1);
                        }

                        if (strKey.Length > 0)
                        {
                            ImportUtil.AppendToField(pe, MapKey(strKey), strValue, pd);
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }

                if (pg != null)
                {
                    pg.AddEntry(pe, true);
                }
#if DEBUG
                else
                {
                    Debug.Assert(bHasSpanCaptions);
                }
#endif
            }
        }
Example #23
0
        private void OnFileNew(object sender, EventArgs e)
        {
            if(!AppPolicy.Try(AppPolicyId.NewFile)) return;
            if(!AppPolicy.Try(AppPolicyId.SaveFile)) return;

            SaveFileDialog sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase,
                KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter(
                AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1,
                AppDefs.FileExtension.FileExt, false, true);

            GlobalWindowManager.AddDialog(sfd);
            DialogResult dr = sfd.ShowDialog();
            GlobalWindowManager.RemoveDialog(sfd);

            string strPath = sfd.FileName;

            if(dr != DialogResult.OK) return;

            KeyCreationForm kcf = new KeyCreationForm();
            kcf.InitEx(IOConnectionInfo.FromPath(strPath), true);
            dr = kcf.ShowDialog();
            if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
            {
                UIUtil.DestroyForm(kcf);
                return;
            }

            PwDocument dsPrevActive = m_docMgr.ActiveDocument;
            PwDatabase pd = m_docMgr.CreateNewDocument(true).Database;
            pd.New(IOConnectionInfo.FromPath(strPath), kcf.CompositeKey);

            UIUtil.DestroyForm(kcf);

            DatabaseSettingsForm dsf = new DatabaseSettingsForm();
            dsf.InitEx(true, pd);
            dr = dsf.ShowDialog();
            if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
            {
                m_docMgr.CloseDatabase(pd);
                try { m_docMgr.ActiveDocument = dsPrevActive; }
                catch(Exception) { } // Fails if no database is open now
                UpdateUI(false, null, true, null, true, null, false);
                UIUtil.DestroyForm(dsf);
                return;
            }
            UIUtil.DestroyForm(dsf);

            // AutoEnableVisualHiding();

            PwGroup pg = new PwGroup(true, true, KPRes.General, PwIcon.Folder);
            pd.RootGroup.AddGroup(pg, true);

            pg = new PwGroup(true, true, KPRes.WindowsOS, PwIcon.DriveWindows);
            pd.RootGroup.AddGroup(pg, true);

            pg = new PwGroup(true, true, KPRes.Network, PwIcon.NetworkServer);
            pd.RootGroup.AddGroup(pg, true);

            pg = new PwGroup(true, true, KPRes.Internet, PwIcon.World);
            pd.RootGroup.AddGroup(pg, true);

            pg = new PwGroup(true, true, KPRes.EMail, PwIcon.EMail);
            pd.RootGroup.AddGroup(pg, true);

            pg = new PwGroup(true, true, KPRes.Homebanking, PwIcon.Homebanking);
            pd.RootGroup.AddGroup(pg, true);

            PwEntry pe = new PwEntry(true, true);
            pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
                KPRes.SampleEntry));
            pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
                KPRes.UserName));
            pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
                @"http://www.somesite.com/"));
            pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
                KPRes.Password));
            pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes,
                KPRes.Notes));
            pe.AutoType.Add(new AutoTypeAssociation(KPRes.TargetWindow,
                @"{USERNAME}{TAB}{PASSWORD}{TAB}{ENTER}"));
            pd.RootGroup.AddEntry(pe, true);

            pe = new PwEntry(true, true);
            pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
                KPRes.SampleEntry + " #2"));
            pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
                "Michael321"));
            pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
                @"http://keepass.info/help/kb/kb090406_testform.html"));
            pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
                "12345"));
            pe.AutoType.Add(new AutoTypeAssociation("Test Form - KeePass*", string.Empty));
            pd.RootGroup.AddEntry(pe, true);

            #if DEBUG
            Random r = Program.GlobalRandom;
            for(uint iSamples = 0; iSamples < 1500; ++iSamples)
            {
                pg = pd.RootGroup.Groups.GetAt(iSamples % 5);

                pe = new PwEntry(true, true);

                pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle,
                    Guid.NewGuid().ToString()));
                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName,
                    Guid.NewGuid().ToString()));
                pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl,
                    Guid.NewGuid().ToString()));
                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword,
                    Guid.NewGuid().ToString()));
                pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes,
                    Guid.NewGuid().ToString()));

                pe.IconId = (PwIcon)r.Next(0, (int)PwIcon.Count);

                pg.AddEntry(pe, true);
            }

            pd.CustomData.Set("Sample Custom Data 1", "0123456789");
            pd.CustomData.Set("Sample Custom Data 2", @"µy data");
            #endif

            UpdateUI(true, null, true, null, true, null, true);

            if(this.FileCreated != null)
            {
                FileCreatedEventArgs ea = new FileCreatedEventArgs(pd);
                this.FileCreated(this, ea);
            }
        }
Example #24
0
        private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);

            pgParent.AddEntry(pe, true);

            DateTime?odtExpiry = null;

            foreach (XmlNode xmlChild in xmlNode)
            {
                string strValue = XmlUtil.SafeInnerText(xmlChild);

                if (xmlChild.NodeType == XmlNodeType.Text)
                {
                    ImportUtil.AppendToField(pe, PwDefs.TitleField, (xmlChild.Value ??
                                                                     string.Empty).Trim(), pwStorage, " ", false);
                }
                else if (xmlChild.Name == ElemEntryUser)
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName, strValue));
                }
                else if (xmlChild.Name == ElemEntryPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword, strValue));
                }
                else if (xmlChild.Name == ElemEntryPassword2)
                {
                    if (strValue.Length > 0)                    // Prevent empty item
                    {
                        pe.Strings.Set(Password2Key, new ProtectedString(
                                           pwStorage.MemoryProtection.ProtectPassword, strValue));
                    }
                }
                else if (xmlChild.Name == ElemEntryUrl)
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl, strValue));
                }
                else if (xmlChild.Name == ElemEntryNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes, strValue));
                }
                else if (xmlChild.Name == ElemTags)
                {
                    string        strTags = strValue.Replace(' ', ';');
                    List <string> vTags   = StrUtil.StringToTags(strTags);
                    foreach (string strTag in vTags)
                    {
                        pe.AddTag(strTag);
                    }
                }
                else if (xmlChild.Name == ElemEntryExpires)
                {
                    pe.Expires = StrUtil.StringToBool(strValue);
                }
                else if (xmlChild.Name == ElemEntryExpiryTime)
                {
                    DateTime dt = TimeUtil.FromDisplayString(strValue);
                    if (dt != DateTime.Now)
                    {
                        odtExpiry = dt;
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else if (xmlChild.Name == ElemAutoType)
                {
                    ReadAutoType(xmlChild, pe);
                }
                else if (xmlChild.Name == ElemEntryUnsupp0)
                {
                }
                else if (xmlChild.Name == ElemEntryUnsupp1)
                {
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if (odtExpiry.HasValue)
            {
                pe.ExpiryTime = odtExpiry.Value;
            }
            else
            {
                pe.Expires = false;
            }
        }
Example #25
0
		private void MoveOrCopySelectedEntries(PwGroup pgTo, DragDropEffects e)
		{
			PwEntry[] vSelected = GetSelectedEntries();
			if((vSelected == null) || (vSelected.Length == 0)) return;

			PwGroup pgSafeView = (m_pgActiveAtDragStart ?? new PwGroup());
			bool bFullUpdateView = false;
			List<PwEntry> vNowInvisible = new List<PwEntry>();

			if(e == DragDropEffects.Move)
			{
				foreach(PwEntry pe in vSelected)
				{
					PwGroup pgParent = pe.ParentGroup;
					if(pgParent == pgTo) continue;

					if(pgParent != null) // Remove from parent
					{
						if(!pgParent.Entries.Remove(pe)) { Debug.Assert(false); }
					}

					pgTo.AddEntry(pe, true, true);

					if(pe.IsContainedIn(pgSafeView)) bFullUpdateView = true;
					else vNowInvisible.Add(pe);
				}
			}
			else if(e == DragDropEffects.Copy)
			{
				foreach(PwEntry pe in vSelected)
				{
					PwEntry peCopy = pe.Duplicate();

					pgTo.AddEntry(peCopy, true, true);

					if(peCopy.IsContainedIn(pgSafeView)) bFullUpdateView = true;
				}
			}
			else { Debug.Assert(false); }

			if(!bFullUpdateView)
			{
				RemoveEntriesFromList(vNowInvisible, true);
				UpdateUI(false, null, true, m_pgActiveAtDragStart, false, null, true);
			}
			else UpdateUI(false, null, true, m_pgActiveAtDragStart, true, null, true);

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

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

            List <DatePasswordPair> listHistory = null;

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

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

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

                    pe.CreateBackup();
                }

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

            PwGroup pgContainer = pwStorage.RootGroup;

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

            pgContainer.AddEntry(pe, true);

            pgContainer.IsExpanded = true;
        }
        public void GetAllUserRootNodesReturnsOnlyValidRootNodes()
        {
            m_treeManager.Initialize(m_database);
            PwEntry root1 = new PwEntry( true, true );
            PwEntry root2 = new PwEntry( true, true );
            PwEntry root3 = new PwEntry( true, true );

            PwEntry normalEntry1 = new PwEntry( true, true );
            PwEntry normalEntry2 = new PwEntry( true, true );
            PwGroup level1 = new PwGroup();

            //initial data
            root1.Strings.Set(KeeShare.KeeShare.UuidLinkField, new ProtectedString( false, root1.Uuid.ToHexString() ) );
            root2.Strings.Set(KeeShare.KeeShare.UuidLinkField, new ProtectedString( false, root2.Uuid.ToHexString() ) );
            root3.Strings.Set(KeeShare.KeeShare.UuidLinkField, new ProtectedString( false, root3.Uuid.ToHexString() ) );

            m_database.RootGroup.AddEntry( root1, true );
            m_database.RootGroup.AddEntry( root2, true );
            m_database.RootGroup.AddEntry( normalEntry1, true );
            m_database.RootGroup.AddGroup( level1, true );
            level1.AddEntry( normalEntry2, true );
            level1.AddEntry( root3, true );

            PwObjectList<PwEntry> rootNodes = m_database.GetAllUserNodes();
            Assert.AreEqual( 3, rootNodes.UCount );

            Assert.AreEqual( root1, rootNodes.GetAt( 0 ) );
            Assert.AreEqual( root2, rootNodes.GetAt( 1 ) );
            Assert.AreEqual( root3, rootNodes.GetAt( 2 ) );
        }
Example #28
0
        private static void ImportRecords(JsonObject[] v, PwDatabase pd)
        {
            if (v == null)
            {
                Debug.Assert(false); return;
            }

            Dictionary <string, PwGroup> dGroups = new Dictionary <string, PwGroup>();
            string strGroupSep   = MemUtil.ByteArrayToHexString(Guid.NewGuid().ToByteArray());
            string strBackspCode = MemUtil.ByteArrayToHexString(Guid.NewGuid().ToByteArray());

            foreach (JsonObject jo in v)
            {
                if (jo == null)
                {
                    Debug.Assert(false); continue;
                }

                PwEntry pe = new PwEntry(true, true);

                ImportUtil.AppendToField(pe, PwDefs.TitleField,
                                         jo.GetValue <string>("title"), pd);
                ImportUtil.AppendToField(pe, PwDefs.UserNameField,
                                         jo.GetValue <string>("login"), pd);
                ImportUtil.AppendToField(pe, PwDefs.PasswordField,
                                         jo.GetValue <string>("password"), pd);
                ImportUtil.AppendToField(pe, PwDefs.UrlField,
                                         jo.GetValue <string>("login_url"), pd);
                ImportUtil.AppendToField(pe, PwDefs.NotesField,
                                         jo.GetValue <string>("notes"), pd);

                JsonObject joCustom = jo.GetValue <JsonObject>("custom_fields");
                if (joCustom != null)
                {
                    foreach (KeyValuePair <string, object> kvp in joCustom.Items)
                    {
                        string strValue = (kvp.Value as string);
                        if (strValue == null)
                        {
                            Debug.Assert(false); continue;
                        }

                        if (kvp.Key == "TFC:Keeper")
                        {
                            EntryUtil.ImportOtpAuth(pe, strValue, pd);
                        }
                        else
                        {
                            ImportUtil.AppendToField(pe, kvp.Key, strValue, pd);
                        }
                    }
                }

                PwGroup      pg       = null;
                JsonObject[] vFolders = jo.GetValueArray <JsonObject>("folders");
                if ((vFolders != null) && (vFolders.Length >= 1))
                {
                    JsonObject joFolder = vFolders[0];
                    if (joFolder != null)
                    {
                        string strGroup = joFolder.GetValue <string>("folder");
                        if (!string.IsNullOrEmpty(strGroup))
                        {
                            strGroup = strGroup.Replace("\\\\", strBackspCode);
                            strGroup = strGroup.Replace("\\", strGroupSep);
                            strGroup = strGroup.Replace(strBackspCode, "\\");

                            if (!dGroups.TryGetValue(strGroup, out pg))
                            {
                                pg = pd.RootGroup.FindCreateSubTree(strGroup,
                                                                    new string[] { strGroupSep }, true);
                                dGroups[strGroup] = pg;
                            }
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                if (pg == null)
                {
                    pg = pd.RootGroup;
                }

                pg.AddEntry(pe, true);
            }
        }
Example #29
0
        private static void PasteEntriesFromClipboardPriv(PwDatabase pwDatabase,
            PwGroup pgStorage)
        {
            if(!ClipboardUtil.ContainsData(ClipFormatEntries)) return;

            byte[] pbEnc = ClipboardUtil.GetEncodedData(ClipFormatEntries, IntPtr.Zero);
            if(pbEnc == null) { Debug.Assert(false); return; }

            byte[] pbPlain;
            if(WinUtil.IsWindows9x) pbPlain = pbEnc;
            else pbPlain = ProtectedData.Unprotect(pbEnc, AdditionalEntropy,
                DataProtectionScope.CurrentUser);

            MemoryStream ms = new MemoryStream(pbPlain, false);
            GZipStream gz = new GZipStream(ms, CompressionMode.Decompress);

            List<PwEntry> vEntries = KdbxFile.ReadEntries(gz);

            // Adjust protection settings and add entries
            foreach(PwEntry pe in vEntries)
            {
                pe.Strings.EnableProtection(PwDefs.TitleField,
                    pwDatabase.MemoryProtection.ProtectTitle);
                pe.Strings.EnableProtection(PwDefs.UserNameField,
                    pwDatabase.MemoryProtection.ProtectUserName);
                pe.Strings.EnableProtection(PwDefs.PasswordField,
                    pwDatabase.MemoryProtection.ProtectPassword);
                pe.Strings.EnableProtection(PwDefs.UrlField,
                    pwDatabase.MemoryProtection.ProtectUrl);
                pe.Strings.EnableProtection(PwDefs.NotesField,
                    pwDatabase.MemoryProtection.ProtectNotes);

                pgStorage.AddEntry(pe, true, true);
            }

            gz.Close(); ms.Close();
        }
        private KdbContext ReadXmlElement(KdbContext ctx, XmlReader xr)
        {
            Debug.Assert(xr.NodeType == XmlNodeType.Element);

            switch (ctx)
            {
            case KdbContext.Null:
                if (xr.Name == ElemDocNode)
                {
                    return(SwitchContext(ctx, KdbContext.KeePassFile, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.KeePassFile:
                if (xr.Name == ElemMeta)
                {
                    return(SwitchContext(ctx, KdbContext.Meta, xr));
                }
                else if (xr.Name == ElemRoot)
                {
                    return(SwitchContext(ctx, KdbContext.Root, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Meta:
                if (xr.Name == ElemGenerator)
                {
                    ReadString(xr);                             // Ignore
                }
                else if (xr.Name == ElemHeaderHash)
                {
                    string strHash = ReadString(xr);
                    if (!string.IsNullOrEmpty(strHash) && (m_pbHashOfHeader != null) &&
                        !m_bRepairMode)
                    {
                        byte[] pbHash = Convert.FromBase64String(strHash);
                        if (!MemUtil.ArraysEqual(pbHash, m_pbHashOfHeader))
                        {
                            throw new IOException(KLRes.FileCorrupted);
                        }
                    }
                }
                else if (xr.Name == ElemDbName)
                {
                    m_pwDatabase.Name = ReadString(xr);
                }
                else if (xr.Name == ElemDbNameChanged)
                {
                    m_pwDatabase.NameChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbDesc)
                {
                    m_pwDatabase.Description = ReadString(xr);
                }
                else if (xr.Name == ElemDbDescChanged)
                {
                    m_pwDatabase.DescriptionChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbDefaultUser)
                {
                    m_pwDatabase.DefaultUserName = ReadString(xr);
                }
                else if (xr.Name == ElemDbDefaultUserChanged)
                {
                    m_pwDatabase.DefaultUserNameChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbMntncHistoryDays)
                {
                    m_pwDatabase.MaintenanceHistoryDays = ReadUInt(xr, 365);
                }
                else if (xr.Name == ElemDbColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_pwDatabase.Color = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemDbKeyChanged)
                {
                    m_pwDatabase.MasterKeyChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbKeyChangeRec)
                {
                    m_pwDatabase.MasterKeyChangeRec = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemDbKeyChangeForce)
                {
                    m_pwDatabase.MasterKeyChangeForce = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemMemoryProt)
                {
                    return(SwitchContext(ctx, KdbContext.MemoryProtection, xr));
                }
                else if (xr.Name == ElemCustomIcons)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcons, xr));
                }
                else if (xr.Name == ElemRecycleBinEnabled)
                {
                    m_pwDatabase.RecycleBinEnabled = ReadBool(xr, true);
                }
                else if (xr.Name == ElemRecycleBinUuid)
                {
                    m_pwDatabase.RecycleBinUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemRecycleBinChanged)
                {
                    m_pwDatabase.RecycleBinChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemEntryTemplatesGroup)
                {
                    m_pwDatabase.EntryTemplatesGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemEntryTemplatesGroupChanged)
                {
                    m_pwDatabase.EntryTemplatesGroupChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemHistoryMaxItems)
                {
                    m_pwDatabase.HistoryMaxItems = ReadInt(xr, -1);
                }
                else if (xr.Name == ElemHistoryMaxSize)
                {
                    m_pwDatabase.HistoryMaxSize = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemLastSelectedGroup)
                {
                    m_pwDatabase.LastSelectedGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemLastTopVisibleGroup)
                {
                    m_pwDatabase.LastTopVisibleGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemBinaries)
                {
                    return(SwitchContext(ctx, KdbContext.Binaries, xr));
                }
                else if (xr.Name == ElemCustomData)
                {
                    return(SwitchContext(ctx, KdbContext.CustomData, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.MemoryProtection:
                if (xr.Name == ElemProtTitle)
                {
                    m_pwDatabase.MemoryProtection.ProtectTitle = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtUserName)
                {
                    m_pwDatabase.MemoryProtection.ProtectUserName = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtPassword)
                {
                    m_pwDatabase.MemoryProtection.ProtectPassword = ReadBool(xr, true);
                }
                else if (xr.Name == ElemProtUrl)
                {
                    m_pwDatabase.MemoryProtection.ProtectUrl = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtNotes)
                {
                    m_pwDatabase.MemoryProtection.ProtectNotes = ReadBool(xr, false);
                }
                // else if(xr.Name == ElemProtAutoHide)
                //	m_pwDatabase.MemoryProtection.AutoEnableVisualHiding = ReadBool(xr, true);
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcons:
                if (xr.Name == ElemCustomIconItem)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcon, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcon:
                if (xr.Name == ElemCustomIconItemID)
                {
                    m_uuidCustomIconID = ReadUuid(xr);
                }
                else if (xr.Name == ElemCustomIconItemData)
                {
                    string strData = ReadString(xr);
                    if (!string.IsNullOrEmpty(strData))
                    {
                        m_pbCustomIconData = Convert.FromBase64String(strData);
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Binaries:
                if (xr.Name == ElemBinary)
                {
                    if (xr.MoveToAttribute(AttrId))
                    {
                        string          strKey = xr.Value;
                        ProtectedBinary pbData = ReadProtectedBinary(xr);

                        m_dictBinPool[strKey ?? string.Empty] = pbData;
                    }
                    else
                    {
                        ReadUnknown(xr);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomData:
                if (xr.Name == ElemStringDictExItem)
                {
                    return(SwitchContext(ctx, KdbContext.CustomDataItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomDataItem:
                if (xr.Name == ElemKey)
                {
                    m_strCustomDataKey = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_strCustomDataValue = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Root:
                if (xr.Name == ElemGroup)
                {
                    Debug.Assert(m_ctxGroups.Count == 0);
                    if (m_ctxGroups.Count != 0)
                    {
                        throw new FormatException();
                    }

                    m_pwDatabase.RootGroup = new PwGroup(false, false);
                    m_ctxGroups.Push(m_pwDatabase.RootGroup);
                    m_ctxGroup = m_ctxGroups.Peek();

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemDeletedObjects)
                {
                    return(SwitchContext(ctx, KdbContext.RootDeletedObjects, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Group:
                if (xr.Name == ElemUuid)
                {
                    m_ctxGroup.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemName)
                {
                    m_ctxGroup.Name = ReadString(xr);
                }
                else if (xr.Name == ElemNotes)
                {
                    m_ctxGroup.Notes = ReadString(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxGroup.IconId = (PwIcon)ReadInt(xr, (int)PwIcon.Folder);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxGroup.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.GroupTimes, xr));
                }
                else if (xr.Name == ElemIsExpanded)
                {
                    m_ctxGroup.IsExpanded = ReadBool(xr, true);
                }
                else if (xr.Name == ElemGroupDefaultAutoTypeSeq)
                {
                    m_ctxGroup.DefaultAutoTypeSequence = ReadString(xr);
                }
                else if (xr.Name == ElemEnableAutoType)
                {
                    m_ctxGroup.EnableAutoType = StrUtil.StringToBoolEx(ReadString(xr));
                }
                else if (xr.Name == ElemEnableSearching)
                {
                    m_ctxGroup.EnableSearching = StrUtil.StringToBoolEx(ReadString(xr));
                }
                else if (xr.Name == ElemLastTopVisibleEntry)
                {
                    m_ctxGroup.LastTopVisibleEntry = ReadUuid(xr);
                }
                else if (xr.Name == ElemGroup)
                {
                    m_ctxGroup = new PwGroup(false, false);
                    m_ctxGroups.Peek().AddGroup(m_ctxGroup, true);

                    m_ctxGroups.Push(m_ctxGroup);

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxGroup.AddEntry(m_ctxEntry, true);

                    m_bEntryInHistory = false;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Entry:
                if (xr.Name == ElemUuid)
                {
                    m_ctxEntry.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxEntry.IconId = (PwIcon)ReadInt(xr, (int)PwIcon.Key);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxEntry.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemFgColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_ctxEntry.ForegroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemBgColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_ctxEntry.BackgroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemOverrideUrl)
                {
                    m_ctxEntry.OverrideUrl = ReadString(xr);
                }
                else if (xr.Name == ElemTags)
                {
                    m_ctxEntry.Tags = StrUtil.StringToTags(ReadString(xr));
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.EntryTimes, xr));
                }
                else if (xr.Name == ElemString)
                {
                    return(SwitchContext(ctx, KdbContext.EntryString, xr));
                }
                else if (xr.Name == ElemBinary)
                {
                    return(SwitchContext(ctx, KdbContext.EntryBinary, xr));
                }
                else if (xr.Name == ElemAutoType)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoType, xr));
                }
                else if (xr.Name == ElemHistory)
                {
                    Debug.Assert(m_bEntryInHistory == false);

                    if (m_bEntryInHistory == false)
                    {
                        m_ctxHistoryBase = m_ctxEntry;
                        return(SwitchContext(ctx, KdbContext.EntryHistory, xr));
                    }
                    else
                    {
                        ReadUnknown(xr);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.GroupTimes:
            case KdbContext.EntryTimes:
                ITimeLogger tl = ((ctx == KdbContext.GroupTimes) ?
                                  (ITimeLogger)m_ctxGroup : (ITimeLogger)m_ctxEntry);
                Debug.Assert(tl != null);

                if (xr.Name == ElemCreationTime)
                {
                    tl.CreationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemLastModTime)
                {
                    tl.LastModificationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemLastAccessTime)
                {
                    tl.LastAccessTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpiryTime)
                {
                    tl.ExpiryTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpires)
                {
                    tl.Expires = ReadBool(xr, false);
                }
                else if (xr.Name == ElemUsageCount)
                {
                    tl.UsageCount = ReadULong(xr, 0);
                }
                else if (xr.Name == ElemLocationChanged)
                {
                    tl.LocationChanged = ReadTime(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryString:
                if (xr.Name == ElemKey)
                {
                    m_ctxStringName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxStringValue = ReadProtectedString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryBinary:
                if (xr.Name == ElemKey)
                {
                    m_ctxBinaryName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxBinaryValue = ReadProtectedBinary(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoType:
                if (xr.Name == ElemAutoTypeEnabled)
                {
                    m_ctxEntry.AutoType.Enabled = ReadBool(xr, true);
                }
                else if (xr.Name == ElemAutoTypeObfuscation)
                {
                    m_ctxEntry.AutoType.ObfuscationOptions =
                        (AutoTypeObfuscationOptions)ReadInt(xr, 0);
                }
                else if (xr.Name == ElemAutoTypeDefaultSeq)
                {
                    m_ctxEntry.AutoType.DefaultSequence = ReadString(xr);
                }
                else if (xr.Name == ElemAutoTypeItem)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoTypeItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoTypeItem:
                if (xr.Name == ElemWindow)
                {
                    m_ctxATName = ReadString(xr);
                }
                else if (xr.Name == ElemKeystrokeSequence)
                {
                    m_ctxATSeq = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryHistory:
                if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxHistoryBase.History.Add(m_ctxEntry);

                    m_bEntryInHistory = true;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.RootDeletedObjects:
                if (xr.Name == ElemDeletedObject)
                {
                    m_ctxDeletedObject = new PwDeletedObject();
                    m_pwDatabase.DeletedObjects.Add(m_ctxDeletedObject);

                    return(SwitchContext(ctx, KdbContext.DeletedObject, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.DeletedObject:
                if (xr.Name == ElemUuid)
                {
                    m_ctxDeletedObject.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemDeletionTime)
                {
                    m_ctxDeletedObject.DeletionTime = ReadTime(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            default:
                ReadUnknown(xr);
                break;
            }

            return(ctx);
        }
        public void IsParentTest()
        {
            PwDatabase db = new PwDatabase();
            db.RootGroup = new PwGroup();
            TreeManager um = new TreeManager();
            userManager.Initialize( db );
            rootGroup = db.RootGroup;

            //groups are named like g<# of group>_<level in tree> level 0 is the copyRootGroup
            PwGroup g1_1 = new PwGroup( true, true, "g1_1", PwIcon.Apple );
            PwGroup g2_1 = new PwGroup( true, true, "g2_1", PwIcon.Apple );
            PwGroup g3_2 = new PwGroup( true, true, "g3_2", PwIcon.Apple );
            PwGroup g4_3 = new PwGroup( true, true, "g4_3", PwIcon.Apple );

            rootGroup.AddGroup( g1_1, true );
            rootGroup.AddGroup( g2_1, true );
            g2_1.AddGroup( g3_2, true );
            g3_2.AddGroup( g4_3, true );

            PwEntry pe1_0 = new PwEntry( true, true );
            PwEntry pe2_1 = new PwEntry( true, true );
            PwEntry pe3_2 = new PwEntry( true, true );
            PwEntry pe4_3 = new PwEntry( true, true );

            rootGroup.AddEntry( pe1_0, true );
            g2_1.AddEntry( pe2_1, true );
            g3_2.AddEntry( pe3_2, true );
            g4_3.AddEntry( pe4_3, true );

            Assert.IsTrue( pe1_0.IsInsideParent( rootGroup ) );
            Assert.IsTrue( pe4_3.IsInsideParent( rootGroup ) );
            Assert.IsTrue( pe4_3.IsInsideParent( g2_1 ) );
            Assert.IsTrue( g4_3.IsInsideParent( g2_1 ) );
            Assert.IsTrue( g4_3.IsInsideParent( rootGroup ) );

            Assert.IsFalse( pe1_0.IsInsideParent( g2_1 ) );
            Assert.IsFalse( pe4_3.IsInsideParent( g1_1 ) );
            Assert.IsFalse( pe2_1.IsInsideParent( g3_2 ) );
            Assert.IsFalse( g2_1.IsInsideParent( g4_3 ) );
        }
Example #32
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Unicode);
            string       strData = sr.ReadToEnd();

            sr.Close();

            strData = strData.Replace(@"<WBR>", string.Empty);

            int nOffset = 0;

            while (true)
            {
                PwEntry pe = new PwEntry(true, true);

                int nTitleTD = strData.IndexOf(m_strTitleTD, nOffset);
                if (nTitleTD < 0)
                {
                    break;
                }
                nOffset = nTitleTD + 1;

                string strTitle = StrUtil.XmlToString(StrUtil.GetStringBetween(
                                                          strData, nTitleTD, @">", @"</TD>"));

                PwGroup pg = pwStorage.RootGroup;
                if (strTitle.IndexOf('\\') > 0)
                {
                    int    nLast   = strTitle.LastIndexOf('\\');
                    string strTree = strTitle.Substring(0, nLast);
                    pg = pwStorage.RootGroup.FindCreateSubTree(strTree,
                                                               new char[] { '\\' });

                    strTitle = strTitle.Substring(nLast + 1);
                }

                pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectTitle, strTitle));

                pg.AddEntry(pe, true);

                int nNextTitleTD = strData.IndexOf(m_strTitleTD, nOffset);
                if (nNextTitleTD < 0)
                {
                    nNextTitleTD = strData.Length + 1;
                }

                int nUrlTD = strData.IndexOf(m_strUrlTD, nOffset);
                if ((nUrlTD >= 0) && (nUrlTD < nNextTitleTD))
                {
                    string strUrl = StrUtil.XmlToString(StrUtil.GetStringBetween(
                                                            strData, nUrlTD, @">", @"</TD>"));

                    if (!string.IsNullOrEmpty(strUrl) && (strUrl.IndexOf(':') < 0) &&
                        (strUrl.IndexOf('@') < 0))
                    {
                        strUrl = @"http://" + strUrl;
                    }

                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl, strUrl));
                }

                while (true)
                {
                    int nKeyTD = strData.IndexOf(m_strKeyTD, nOffset);
                    if ((nKeyTD < 0) || (nKeyTD > nNextTitleTD))
                    {
                        break;
                    }

                    int nValueTD = strData.IndexOf(m_strValueTD, nOffset);
                    if ((nValueTD < 0) || (nValueTD > nNextTitleTD))
                    {
                        break;
                    }

                    string strKey = StrUtil.XmlToString(StrUtil.GetStringBetween(
                                                            strData, nKeyTD, @">", @"</TD>")).TrimEnd(new char[] { '$' });
                    string strValueRaw = StrUtil.GetStringBetween(strData,
                                                                  nValueTD, @">", @"</TD>");
                    strValueRaw = strValueRaw.Replace(@"<BR>", Environment.NewLine);
                    string strValue = StrUtil.XmlToString(strValueRaw);

                    string strKeyMapped = ImportUtil.MapNameToStandardField(strKey, true);
                    if ((strKeyMapped == PwDefs.TitleField) ||
                        (strKeyMapped == PwDefs.UrlField) ||
                        (strKeyMapped.Length == 0))
                    {
                        strKeyMapped = strKey;
                    }

                    // pe.Strings.Set(strKeyMapped, new ProtectedString(
                    //	pwStorage.MemoryProtection.GetProtection(strKeyMapped),
                    //	strValue));
                    ImportUtil.AppendToField(pe, strKeyMapped, strValue, pwStorage);

                    nOffset = nValueTD + 1;
                }
            }
        }
Example #33
0
		private static void AddCard(PwGroup pgParent, HspCard hspCard)
		{
			if(hspCard == null) { Debug.Assert(false); return; }

			PwEntry pe = new PwEntry(true, true);
			pgParent.AddEntry(pe, true);

			if(!string.IsNullOrEmpty(hspCard.Name))
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(false, hspCard.Name));

			if(!string.IsNullOrEmpty(hspCard.Note))
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(false, hspCard.Note));

			if(hspCard.Fields == null) return;
			foreach(HspField fld in hspCard.Fields)
			{
				if(fld == null) { Debug.Assert(false); continue; }
				if(string.IsNullOrEmpty(fld.Name) || string.IsNullOrEmpty(fld.Value)) continue;

				string strKey = ImportUtil.MapNameToStandardField(fld.Name, true);
				if(string.IsNullOrEmpty(strKey)) strKey = fld.Name;

				string strValue = pe.Strings.ReadSafe(strKey);
				if(strValue.Length > 0) strValue += ", ";
				strValue += fld.Value;
				pe.Strings.Set(strKey, new ProtectedString(false, strValue));
			}
		}
        /// <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
            {
                Form1 form = new Form1();

                form.Initialise(pwStorage);

                if (form.ShowDialog() == DialogResult.OK)
                {
                    // return;
                    bool   overwritePassword = form.Overwrite;
                    bool   searchWeb         = form.GetTitles;
                    bool   checkMatches      = form.Merge;
                    string masterPassword    = form.Password;

                    bool   addAutoType = form.AddAutoType;
                    PwIcon iconId      = (PwIcon)Enum.Parse(typeof(PwIcon), form.IconName);

                    string profilePath = form.ProfilePath;

                    if (String.IsNullOrEmpty(profilePath))
                    {
                        MessageBox.Show("No Profile Selected. Use Load More Profiles", "Profile Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Import(pwStorage, sInput, slLogger); // bit of a hack!
                        return;
                    }

                    PwGroup group = form.Group;

                    if (group == null)
                    {
                        group = pwStorage.RootGroup;
                    }

                    //     return;

                    try
                    {
                        InternetAccessor internetAccessor = new InternetAccessor();

                        slLogger.StartLogging("Importing Firefox Passwords", false);

                        slLogger.SetText("Logging In", LogStatusType.Info);

                        FirefoxProfile profile = new FirefoxProfile(profilePath);

                        profile.Login(masterPassword);

                        slLogger.SetText("Reading Signon file", LogStatusType.Info);


                        FirefoxSignonsFile signonsFile = profile.GetSignonsFile(masterPassword);


                        slLogger.SetText("Processing Passwords", LogStatusType.Info);

                        int count = signonsFile.SignonSites.Count;
                        int pos   = 0;

                        //  return;

                        // Loop each entry and add it to KeePass
                        foreach (FirefoxSignonSite signonSite in signonsFile.SignonSites)
                        {
                            // keep the user informed of progress
                            pos++;

                            foreach (FirefoxSignon signon in signonSite.Signons)
                            {
                                if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user
                                {
                                    break;
                                }


                                slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count)));


                                string notes = String.Empty;

                                if (form.IncludeImportNotes)
                                {
                                    notes += "Imported from FireFox by the Web Site Advantage FireFox to KeePass Importer" + Environment.NewLine;
                                }

                                // gather the data to import

                                string title = signonSite.Site;
                                string url   = signonSite.Site;

                                if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                {
                                    title = signon.LoginFormDomain;
                                    url   = signon.LoginFormDomain;
                                }

                                string host = url;
                                try
                                {
                                    Uri uri = new Uri(url);
                                    host = uri.Host;
                                }
                                catch { }

                                slLogger.SetText(title, LogStatusType.Info);


                                string username = signon.UserName;

                                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, signon.Password));
                                }

                                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 (!String.IsNullOrEmpty(signon.UserNameField))
                                    {
                                        pe.Strings.Set("UserNameField", new ProtectedString(false, signon.UserNameField));
                                    }

                                    if (!String.IsNullOrEmpty(signon.PasswordField))
                                    {
                                        pe.Strings.Set("PasswordField", new ProtectedString(false, signon.PasswordField));
                                    }

                                    if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                    {
                                        pe.Strings.Set("LoginFormDomain", new ProtectedString(false, signon.LoginFormDomain));
                                    }
                                }

                                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));
                                        }
                                    }
                                    //else
                                    //{
                                    //    // Entry has a good title, keep it incase there are other ones for this site
                                    //    title = pe.Strings.Get(PwDefs.TitleField).ReadString();
                                    //}
                                }
                                // return;


                                if (addAutoType)
                                {
                                    KeePassHelper.InsertAutoType(pe, "*" + host + "*", KeePassUtilities.AutoTypeSequence());
                                }

                                // return;

                                if (webTitle != null && addAutoType)
                                {
                                    KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence());
                                }
                            }
                        }
                    }
                    finally
                    {
                        slLogger.EndLogging();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage.ShowErrorMessage("Importer", "Import Failed", ex);
            }
        }
Example #35
0
		private static void AddEntry(PwGroup pg, Dictionary<string, string> dItems,
			ref bool bInNotes, ref DateTime? dtExpire)
		{
			if(dItems.Count > 0)
			{
				PwEntry pe = new PwEntry(true, true);
				pg.AddEntry(pe, true);

				foreach(KeyValuePair<string, string> kvp in dItems)
					pe.Strings.Set(kvp.Key, new ProtectedString(false, kvp.Value));

				if(dtExpire.HasValue)
				{
					pe.Expires = true;
					pe.ExpiryTime = dtExpire.Value;
				}
			}

			bInNotes = false;
			dtExpire = null;
		}
Example #36
0
        private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent,
                                      PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);

            pgParent.AddEntry(pe, true);

            string strAttachDesc = null, strAttachment = null;

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemTitle)
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUserName)
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUrl)
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       FilterSpecial(XmlUtil.SafeInnerXml(xmlChild))));
                }
                else if (xmlChild.Name == ElemIcon)
                {
                    pe.IconId = ReadIcon(xmlChild, pe.IconId);
                }
                else if (xmlChild.Name == ElemCreationTime)
                {
                    pe.CreationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastModTime)
                {
                    pe.LastModificationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastAccessTime)
                {
                    pe.LastAccessTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemExpiryTime)
                {
                    string strDate = XmlUtil.SafeInnerText(xmlChild);
                    pe.Expires = (strDate != ValueNever);
                    if (pe.Expires)
                    {
                        pe.ExpiryTime = ParseTime(strDate);
                    }
                }
                else if (xmlChild.Name == ElemAttachDesc)
                {
                    strAttachDesc = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemAttachment)
                {
                    strAttachment = XmlUtil.SafeInnerText(xmlChild);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if (!string.IsNullOrEmpty(strAttachDesc) && (strAttachment != null))
            {
                byte[]          pbData = Convert.FromBase64String(strAttachment);
                ProtectedBinary pb     = new ProtectedBinary(false, pbData);
                pe.Binaries.Set(strAttachDesc, pb);
            }
        }
Example #37
0
        private static void ImportEntry(string strData, PwGroup pg, PwDatabase pd,
			bool bForceNotes)
        {
            PwEntry pe = new PwEntry(true, true);
            pg.AddEntry(pe, true);

            string[] v = strData.Split('\n');

            if(v.Length == 0) { Debug.Assert(false); return; }
            ImportUtil.AppendToField(pe, PwDefs.TitleField, v[0].Trim(), pd);

            int n = v.Length;
            for(int j = n - 1; j >= 0; --j)
            {
                if(v[j].Length > 0) break;
                --n;
            }

            bool bInNotes = bForceNotes;
            for(int i = 1; i < n; ++i)
            {
                string str = v[i];

                int iSep = str.IndexOf(':');
                if(iSep <= 0) bInNotes = true;

                if(bInNotes)
                {
                    if(str.Length == 0)
                        ImportUtil.AppendToField(pe, PwDefs.NotesField,
                            Environment.NewLine, pd, string.Empty, false);
                    else
                        ImportUtil.AppendToField(pe, PwDefs.NotesField,
                            str, pd, Environment.NewLine, false);
                }
                else
                {
                    string strRawKey = str.Substring(0, iSep);
                    string strValue = str.Substring(iSep + 1).Trim();

                    string strKey = ImportUtil.MapNameToStandardField(strRawKey, false);
                    if(string.IsNullOrEmpty(strKey)) strKey = strRawKey;

                    bool bMultiLine = ((strKey == PwDefs.NotesField) ||
                        !PwDefs.IsStandardField(strKey));
                    ImportUtil.AppendToField(pe, strKey, strValue, pd,
                        (bMultiLine ? Environment.NewLine : ", "), false);
                }
            }
        }
Example #38
0
        public override void Run()
        {
            //check if we will run into problems. Then finish with error before we start doing anything.
            foreach (var _elementToMove in _elementsToMove)
            {
                PwGroup pgParent = _elementToMove.ParentGroup;
                if (pgParent != _targetGroup)
                {
                    if (pgParent != null)
                    {
                        PwGroup group = _elementToMove as PwGroup;
                        if (group != null)
                        {
                            if ((_targetGroup == group) || (_targetGroup.IsContainedIn(group)))
                            {
                                Finish(false, _app.GetResourceString(UiStringKey.CannotMoveGroupHere));
                                return;
                            }
                        }
                    }
                }
            }

            HashSet <Database> removeDatabases = new HashSet <Database>();
            Database           addDatabase     = _app.FindDatabaseForElement(_targetGroup);

            if (addDatabase == null)
            {
                Finish(false, "Did not find target database. Did you lock it?");
                return;
            }

            foreach (var elementToMove in _elementsToMove)
            {
                _app.DirtyGroups.Add(elementToMove.ParentGroup);


                PwGroup pgParent = elementToMove.ParentGroup;
                if (pgParent != _targetGroup)
                {
                    if (pgParent != null) // Remove from parent
                    {
                        PwEntry entry = elementToMove as PwEntry;
                        if (entry != null)
                        {
                            var dbRem = _app.FindDatabaseForElement(entry);
                            removeDatabases.Add(dbRem);
                            dbRem.EntriesById.Remove(entry.Uuid);
                            dbRem.Elements.Remove(entry);
                            pgParent.Entries.Remove(entry);
                            _targetGroup.AddEntry(entry, true, true);
                            addDatabase.EntriesById.Add(entry.Uuid, entry);
                            addDatabase.Elements.Add(entry);
                        }
                        else
                        {
                            PwGroup group = (PwGroup)elementToMove;
                            if ((_targetGroup == group) || (_targetGroup.IsContainedIn(group)))
                            {
                                Finish(false, _app.GetResourceString(UiStringKey.CannotMoveGroupHere));
                                return;
                            }

                            var dbRem = _app.FindDatabaseForElement(@group);
                            if (dbRem == null)
                            {
                                Finish(false, "Did not find source database. Did you lock it?");
                                return;
                            }

                            dbRem.GroupsById.Remove(group.Uuid);
                            dbRem.Elements.Remove(group);
                            removeDatabases.Add(dbRem);
                            pgParent.Groups.Remove(group);
                            _targetGroup.AddGroup(group, true, true);
                            addDatabase.GroupsById.Add(group.Uuid, group);
                            addDatabase.Elements.Add(group);
                        }
                    }
                }
            }



            //first save the database where we added the elements
            var allDatabasesToSave = new List <Database> {
                addDatabase
            };

            //then all databases where we removed elements:
            removeDatabases.RemoveWhere(db => db == addDatabase);
            allDatabasesToSave.AddRange(removeDatabases);

            int  indexToSave     = 0;
            bool allSavesSuccess = true;

            void ContinueSave(bool success, string message, Activity activeActivity)
            {
                allSavesSuccess &= success;
                indexToSave++;
                if (indexToSave == allDatabasesToSave.Count)
                {
                    OnFinishToRun.SetResult(allSavesSuccess);
                    OnFinishToRun.Run();
                    return;
                }
                SaveDb saveDb = new SaveDb(_ctx, _app, allDatabasesToSave[indexToSave], new ActionOnFinish(activeActivity, ContinueSave), false);

                saveDb.SetStatusLogger(StatusLogger);
                saveDb.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
                saveDb.Run();
            }

            SaveDb save = new SaveDb(_ctx, _app, allDatabasesToSave[0], new ActionOnFinish(ActiveActivity, ContinueSave), false);

            save.SetStatusLogger(StatusLogger);
            save.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
            save.Run();
        }
        private void AddRecord( XElement xelRecord, PwGroup objParent )
        {
            if ( xelRecord == null )
            {
                throw new ArgumentNullException( "xelRecord" );
            }

            var objEntry = new PwEntry( true, true );

            objEntry.Strings.Set( PwDefs.TitleField, new ProtectedString( false, GetString( xelRecord, "Name" ) ) );
            objEntry.Strings.Set( PwDefs.NotesField, new ProtectedString( false, GetString( xelRecord, "Comment", true ) ) );

            foreach( var xelValue in xelRecord.XPathSelectElements( "Values/Value" ) )
            {
                var eType = (PasscommFieldType) int.Parse( GetString( xelValue, "@Type" ) );

                switch ( eType )
                {
                case PasscommFieldType.Login:
                    {
                        objEntry.Strings.Set( PwDefs.UserNameField, new ProtectedString( false, xelValue.Value ) );
                    }
                    break;
                case PasscommFieldType.Password:
                    {
                        objEntry.Strings.Set( PwDefs.PasswordField, new ProtectedString( true, xelValue.Value ) );
                    }
                    break;
                case PasscommFieldType.URL:
                    {
                        objEntry.Strings.Set( PwDefs.UrlField, new ProtectedString( false, xelValue.Value ) );
                    }
                    break;
                case PasscommFieldType.CMD:
                case PasscommFieldType.Email:
                case PasscommFieldType.Text:
                case PasscommFieldType.IP:
                    {
                        objEntry.Strings.Set( GetString( xelValue, "@Name" ), new ProtectedString( false, xelValue.Value ) );
                    }
                    break;
                case PasscommFieldType.AdditionalPassword:
                    {
                        objEntry.Strings.Set( GetString( xelValue, "@Name" ), new ProtectedString( true, xelValue.Value ) );
                    }
                    break;
                case PasscommFieldType.File:
                    {
                        if ( !string.IsNullOrEmpty( xelValue.Value ) )
                        {
                            string[] arrFile = xelValue.Value.Split( '|' );

                            Debug.Assert( xelRecord.Document != null, "xelRecord.Document != null" );

                            objEntry.Binaries.Set( arrFile[0],
                                new ProtectedBinary( true,
                                    Convert.FromBase64String(
                                        GetString(
                                            xelRecord.Document.Root,
                                            string.Format( "Files/File[@Key='{0}']", arrFile[1] )
                                            )
                                        )
                                    ) );
                        }
                    }
                    break;
                }
            }

            var xelGroup = xelRecord;
            while ( xelGroup.Name.LocalName != "Group" && xelGroup.Parent != null )
            {
                xelGroup = xelGroup.Parent;
            }

            bool bEnableAutoType = false;

            if ( xelGroup.Name.LocalName == "Group" )
            {
                foreach ( var xRule in xelRecord.XPathSelectElements( "AutoType/Rule" ) )
                {
                    int iType = int.Parse( GetString( xRule, "@Type" ) );
                    if ( iType != 0 )
                    {
                        string sMatch = GetString( xRule, "Match" );
                        string sSequence = GetString( xRule, "Sequence" );

                        if ( iType != 1 )
                        {
                            sMatch = "??:URL:" + sMatch;
                        }

                        if ( !string.IsNullOrEmpty( sMatch ) && !string.IsNullOrEmpty( sSequence ) )
                        {
                            sSequence = ConvertAutoType( sSequence, xelGroup );
                            if (!string.IsNullOrEmpty( sSequence ))
                            {
                                bEnableAutoType = true;
                                objEntry.AutoType.Add( new AutoTypeAssociation( sMatch, sSequence ) );
                            }
                        }
                    }
                }
            }

            objEntry.AutoType.Enabled = bEnableAutoType;

            DateTime dtValid;
            if ( DateTime.TryParse( GetString( xelGroup, "ValidTill" ), out dtValid ) )
            {
                objEntry.Expires = true;
                objEntry.ExpiryTime = dtValid;
            }

            objParent.AddEntry( objEntry, true );
        }
Example #40
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);
            }
        }
Example #41
0
        private void AddSecLine(PwGroup pgContainer, SecLine line, bool bIsContainer,
			PwDatabase pwParent)
        {
            if(!bIsContainer)
            {
                if(line.SubLines.Count > 0)
                {
                    PwGroup pg = new PwGroup(true, true);
                    pg.Name = line.Text;

                    pgContainer.AddGroup(pg, true);

                    pgContainer = pg;
                }
                else
                {
                    PwEntry pe = new PwEntry(true, true);
                    pgContainer.AddEntry(pe, true);

                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                        pwParent.MemoryProtection.ProtectTitle, line.Text));
                }
            }

            foreach(SecLine subLine in line.SubLines)
                AddSecLine(pgContainer, subLine, false, pwParent);
        }
 public override void Add(PwEntryBuffer item)
 {
     mGroup.AddEntry(item.Entry, true);
 }
Example #43
0
        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); }
            }
        }
Example #44
0
        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);
                    }
                }
            }
        }
Example #45
0
        private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);
            pgParent.AddEntry(pe, true);

            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 == 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 { Debug.Assert(false); }
            }
        }
Example #46
0
        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);
                }
            }
        }
Example #47
0
		private void ShowExpiredEntries(bool bOnlyIfExists, bool bShowExpired,
			bool bShowSoonToExpire)
		{
			if(!bShowExpired && !bShowSoonToExpire) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			// https://sourceforge.net/p/keepass/bugs/1150/
			if(!pd.IsOpen || (pd.RootGroup == null)) return;

			PwGroup pg = new PwGroup(true, true, string.Empty, PwIcon.Expired);
			pg.IsVirtual = true;

			const int iSkipDays = 7;
			DateTime dtNow = DateTime.Now;
			DateTime dtLimit = dtNow.Add(new TimeSpan(iSkipDays, 0, 0, 0));

			EntryHandler eh = delegate(PwEntry pe)
			{
				if(!pe.Expires) return true;
				if(PwDefs.IsTanEntry(pe)) return true; // Exclude TANs

				if((bShowExpired && (pe.ExpiryTime <= dtNow)) ||
					(bShowSoonToExpire && (pe.ExpiryTime <= dtLimit) &&
					(pe.ExpiryTime > dtNow)))
					pg.AddEntry(pe, false);
				return true;
			};

			pd.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh);

			if((pg.Entries.UCount > 0) || !bOnlyIfExists)
			{
				UpdateEntryList(pg, false);
				UpdateUIState(false);
				ShowSearchResultsStatusMessage(null);
			}
		}
Example #48
0
        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);
                }
            }
        }
Example #49
0
		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);
		}
Example #50
0
        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");
                }
            }
        }
Example #51
0
		public PwGroup GetSelectedEntriesAsGroup()
		{
			PwGroup pg = new PwGroup(true, true);

			// Copying group properties would confuse users
			// PwGroup pgSel = GetSelectedGroup();
			// if(pgSel != null)
			// {
			//	pg.Name = pgSel.Name;
			//	pg.IconId = pgSel.IconId;
			//	pg.CustomIconUuid = pgSel.CustomIconUuid;
			// }

			PwEntry[] vSel = GetSelectedEntries();
			if((vSel == null) || (vSel.Length == 0)) return pg;

			foreach(PwEntry pe in vSel) pg.AddEntry(pe, false);

			return pg;
		}
        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);
        }
        public void DeleteOneUserShouldRemoveObsoleteProxyNodes()
        {
            m_treeManager.Initialize(m_database);
            m_treeManager.CreateNewUser("mrX");
            m_treeManager.CreateNewUser("mrY");

            //a DeleteUser should also delete all proxies of this user!
            //so we create some and look if all proxies will be deleted...
            PwGroup testGroup1 = new PwGroup( true, false );
            PwGroup testGroup2 = new PwGroup( true, false );
            PwGroup testGroup3 = new PwGroup( true, false );

            m_database.RootGroup.AddGroup( testGroup1, true );
            m_database.RootGroup.AddGroup( testGroup2, true );

            testGroup2.AddGroup( testGroup3, true );

            PwEntry mrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX");
            PwEntry mrY = TestHelper.GetUserRootNodeByNameFor(m_database, "mrY");

            PwEntry mrXproxy1 = PwNode.CreateProxyNode( mrX );
            PwEntry mrXproxy2 = PwNode.CreateProxyNode( mrX );
            PwEntry mrXproxy3 = PwNode.CreateProxyNode( mrX );

            testGroup1.AddEntry( mrXproxy1, true );
            testGroup2.AddEntry( mrXproxy2, true );
            testGroup3.AddEntry( mrXproxy3, true );

            Assert.AreEqual( 7, NumberOfEntriesIn(m_database)); // 2 standard proxies each + 3 additional proxies for mrX

            m_treeManager.DeleteUser( mrX );

            Assert.AreEqual(2, NumberOfEntriesIn(m_database));
            foreach( PwEntry proxy in m_database.RootGroup.GetEntries( true ) )
            {
                Assert.AreEqual("mrY", proxy.Strings.ReadSafe(KeeShare.KeeShare.TitleField));
            }
            IsUsersGroupSane( m_database, 1 );
        }
Example #54
0
        /// <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
                {
                }
            }
        }
Example #55
0
        private static void ImportEntry(PwDatabase pd, PwGroup pgParent, XmlNode xmlNode)
        {
            PwEntry pe = new PwEntry(true, true);
            pgParent.AddEntry(pe, true);

            foreach(XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if(xmlChild.Name == "name")
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                        pd.MemoryProtection.ProtectTitle, XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == "description")
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                        pd.MemoryProtection.ProtectNotes, XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == "updated")
                    pe.LastModificationTime = ImportTime(xmlChild);
                else if(xmlChild.Name == "field")
                {
                    XmlNode xnName = xmlChild.Attributes.GetNamedItem("id");
                    if(xnName == null) { Debug.Assert(false); }
                    else
                    {
                        KeyValuePair<string, bool> kvp = MapFieldName(xnName.Value, pd);
                        pe.Strings.Set(kvp.Key, new ProtectedString(kvp.Value,
                            XmlUtil.SafeInnerText(xmlChild)));
                    }
                }
                else { Debug.Assert(false); }
            }
        }
        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 ReadEntry(XmlNode xmlNode, PwGroup pgParent,
            PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);
            pgParent.AddEntry(pe, true);

            string strAttachDesc = null, strAttachment = null;

            foreach(XmlNode xmlChild in xmlNode)
            {
                if(xmlChild.Name == ElemTitle)
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectTitle,
                        XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemUserName)
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectUserName,
                        XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemUrl)
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectUrl,
                        XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemPassword)
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectPassword,
                        XmlUtil.SafeInnerText(xmlChild)));
                else if(xmlChild.Name == ElemNotes)
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                        pwStorage.MemoryProtection.ProtectNotes,
                        FilterSpecial(XmlUtil.SafeInnerXml(xmlChild))));
                else if(xmlChild.Name == ElemIcon)
                    pe.IconId = ReadIcon(xmlChild, pe.IconId);
                else if(xmlChild.Name == ElemCreationTime)
                    pe.CreationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                else if(xmlChild.Name == ElemLastModTime)
                    pe.LastModificationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                else if(xmlChild.Name == ElemLastAccessTime)
                    pe.LastAccessTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                else if(xmlChild.Name == ElemExpiryTime)
                {
                    string strDate = XmlUtil.SafeInnerText(xmlChild);
                    pe.Expires = (strDate != ValueNever);
                    if(pe.Expires) pe.ExpiryTime = ParseTime(strDate);
                }
                else if(xmlChild.Name == ElemAttachDesc)
                    strAttachDesc = XmlUtil.SafeInnerText(xmlChild);
                else if(xmlChild.Name == ElemAttachment)
                    strAttachment = XmlUtil.SafeInnerText(xmlChild);
                else { Debug.Assert(false); }
            }

            if(!string.IsNullOrEmpty(strAttachDesc) && (strAttachment != null))
            {
                byte[] pbData = Convert.FromBase64String(strAttachment);
                ProtectedBinary pb = new ProtectedBinary(false, pbData);
                pe.Binaries.Set(strAttachDesc, pb);
            }
        }
Example #58
0
        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);
            }
        }
Example #59
0
		private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent,
			PwDatabase pwStorage)
		{
			PwEntry pe = new PwEntry(true, true);
			pgParent.AddEntry(pe, true);

			DateTime? ndt;
			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 == 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 == ElemEntryLastModTime)
				{
					ndt = ReadTime(xmlChild);
					if(ndt.HasValue) pe.LastModificationTime = ndt.Value;
				}
				else if(xmlChild.Name == ElemEntryExpireTime)
				{
					ndt = ReadTime(xmlChild);
					if(ndt.HasValue)
					{
						pe.ExpiryTime = ndt.Value;
						pe.Expires = true;
					}
				}
				else if(xmlChild.Name == ElemEntryCreatedTime)
				{
					ndt = ReadTime(xmlChild);
					if(ndt.HasValue) pe.CreationTime = ndt.Value;
				}
				else if(xmlChild.Name == ElemEntryLastAccTime)
				{
					ndt = ReadTime(xmlChild);
					if(ndt.HasValue) pe.LastAccessTime = ndt.Value;
				}
				else if(xmlChild.Name == ElemEntryUsageCount)
				{
					ulong uUsageCount;
					if(ulong.TryParse(XmlUtil.SafeInnerText(xmlChild), out uUsageCount))
						pe.UsageCount = uUsageCount;
				}
				else if(xmlChild.Name == ElemEntryAutoType)
					pe.AutoType.DefaultSequence = MapAutoType(
						XmlUtil.SafeInnerText(xmlChild));
				else if(xmlChild.Name == ElemEntryCustom)
					ReadCustomContainer(xmlChild, pe);
				else if(xmlChild.Name == ElemImageIndex)
					pe.IconId = MapIcon(XmlUtil.SafeInnerText(xmlChild), true);
				else if(Array.IndexOf<string>(ElemEntryUnsupportedItems,
					xmlChild.Name) >= 0) { }
				else { Debug.Assert(false, xmlChild.Name); }
			}

			string strInfoText = pe.Strings.ReadSafe(FieldInfoText);
			if((pe.Strings.ReadSafe(PwDefs.NotesField).Length == 0) &&
				(strInfoText.Length > 0))
			{
				pe.Strings.Remove(FieldInfoText);
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes, strInfoText));
			}
		}
Example #60
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            string[] vLines = strData.Split(new char[] { '\r', '\n' });

            PwGroup pg = pwStorage.RootGroup;
            PwEntry pe = new PwEntry(true, true);

            foreach (string strLine in vLines)
            {
                if (strLine.StartsWith(InitGroup))
                {
                    string strGroup = strLine.Remove(0, InitGroup.Length);
                    if (strGroup.Length > InitGroup.Length)
                    {
                        strGroup = strGroup.Substring(0, strGroup.Length - InitGroup.Length);
                    }

                    pg = pwStorage.RootGroup.FindCreateGroup(strGroup, true);

                    pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);
                }
                else if (strLine.StartsWith(InitNewEntry))
                {
                    pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);
                }
                else if (strLine.StartsWith(InitTitle))
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle,
                                       strLine.Remove(0, InitTitle.Length)));
                }
                else if (strLine.StartsWith(InitUser))
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName,
                                       strLine.Remove(0, InitUser.Length)));
                }
                else if (strLine.StartsWith(InitPassword))
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       strLine.Remove(0, InitPassword.Length)));
                }
                else if (strLine.StartsWith(InitURL))
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl,
                                       strLine.Remove(0, InitURL.Length)));
                }
                else if (strLine.StartsWith(InitEMail))
                {
                    pe.Strings.Set("E-Mail", new ProtectedString(
                                       false,
                                       strLine.Remove(0, InitEMail.Length)));
                }
                else if (strLine.StartsWith(InitNotes))
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       strLine.Remove(0, InitNotes.Length)));
                }
                else if (strLine.StartsWith(ContinueNotes))
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       pe.Strings.ReadSafe(PwDefs.NotesField) + "\r\n" +
                                       strLine.Remove(0, ContinueNotes.Length)));
                }
            }
        }