Example #1
0
        private static void ImportGroup(XmlNode xn, PwGroup pgParent, PwDatabase pd,
                                        bool bIsRecycleBin)
        {
            PwGroup pg;

            if (!bIsRecycleBin)
            {
                pg = new PwGroup(true, true);
                pgParent.AddGroup(pg, true);
            }
            else
            {
                pg = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);

                if (pg == null)
                {
                    pg = new PwGroup(true, true, KPRes.RecycleBin, PwIcon.TrashBin);
                    pgParent.AddGroup(pg, true);

                    pd.RecycleBinUuid    = pg.Uuid;
                    pd.RecycleBinChanged = DateTime.UtcNow;
                }
            }

            foreach (XmlNode xmlChild in xn.ChildNodes)
            {
                if (xmlChild.Name == ElemName)
                {
                    pg.Name = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemIcon)
                {
                    pg.IconId = GetIcon(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemGroup)
                {
                    ImportGroup(xmlChild, pg, pd, false);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ImportEntry(xmlChild, pg, pd);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
        private static void AddGroup(XmlNode xnGrp, PwGroup pgParent, PwDatabase pd)
        {
            PwGroup pg = new PwGroup(true, true);

            pgParent.AddGroup(pg, true);

            XmlNode xnName  = xnGrp.Attributes.GetNamedItem(AttribCaption);
            string  strName = ((xnName != null) ? xnName.Value : null);

            if (string.IsNullOrEmpty(strName))
            {
                Debug.Assert(false); strName = KPRes.Group;
            }
            pg.Name = strName;

            foreach (XmlNode xn in xnGrp)
            {
                if (Array.IndexOf <string>(ElemsGroup, xn.Name) >= 0)
                {
                    AddGroup(xn, pg, pd);
                }
                else if (Array.IndexOf <string>(ElemsEntry, xn.Name) >= 0)
                {
                    AddEntry(xn, pg, pd);
                }
                else if (Array.IndexOf <string>(ElemsWebEntry, xn.Name) >= 0)
                {
                    AddWebEntry(xn, pg, pd);
                }
                else
                {
                    Debug.Assert(false);
                }                                             // Unknown node
            }
        }
Example #3
0
        public bool AddGroup(KPGroup group)
        {
            lock (databaseLock)
            {
                using (var connection = Open())
                {
                    PwGroup parent = GetGroup(group.ParentID, connection.Database);
                    if (parent == null)
                    {
                        return(false);
                    }

                    PwGroup newGroup = new PwGroup(true, true);
                    newGroup.Name            = group.Name;
                    newGroup.EnableAutoType  = false;
                    newGroup.EnableSearching = false;

                    parent.AddGroup(newGroup, true);
                    connection.Database.Save(null);

                    group.ID = newGroup.Uuid.ToHexString();

                    groupCache = null;

                    return(true);
                }
            }
        }
Example #4
0
        public void MoveUserHomeToGarbageShoulRemoveAllUserProxies()
        {
            m_treeManager.Initialize(m_database);
            m_treeManager.CreateNewUser("mrX");
            m_treeManager.CreateNewUser("mrY");
            PwGroup grp1  = new PwGroup(true, true, "testgrp", PwIcon.Archive);
            PwUuid  grpId = grp1.Uuid;

            m_database.RootGroup.AddGroup(grp1, true);

            Assert.AreEqual(4, m_database.RootGroup.Groups.UCount);

            //move home to a normal PwGroup
            PwGroup homeX   = TestHelper.GetUserHomeNodeByNameFor(m_database, "mrX");
            PwUuid  homeXid = homeX.Uuid;
            //move home to the trash
            PwGroup trash = m_database.RootGroup.FindGroup(m_database.RecycleBinUuid, true);

            homeX.ParentGroup.Groups.Remove(homeX);
            trash.AddGroup(homeX, true);
            // TODO CK: Find out if the user should be deleted already at this place or later
            m_treeManager.CorrectStructure();

            trash = m_database.RootGroup.FindGroup(m_database.RecycleBinUuid, true);
            Assert.AreEqual(1, trash.Groups.UCount);
            homeX = m_database.RootGroup.FindGroup(homeXid, true);
            Assert.AreEqual(trash, homeX.ParentGroup);
            //empty trash..
            trash.DeleteAllObjects(m_database);
            //update should delete all references to the non existing user
            m_treeManager.CorrectStructure();

            Assert.AreEqual(2, NumberOfEntriesIn(m_database));
            Assert.NotNull(TestHelper.GetUserRootNodeByNameFor(m_database, "mrY"));
        }
Example #5
0
        public void MoveUserHomeShouldCreateAProxyInTheTarget()
        {
            m_treeManager.Initialize(m_database);
            m_treeManager.CreateNewUser("mrX");
            m_treeManager.CreateNewUser("mrY");
            PwGroup grp1  = new PwGroup(true, true, "testgrp", PwIcon.Archive);
            PwUuid  grpId = grp1.Uuid;

            m_database.RootGroup.AddGroup(grp1, true);

            Assert.AreEqual(4, m_database.RootGroup.Groups.UCount);

            //move home to a normal PwGroup
            PwGroup homeX   = TestHelper.GetUserHomeNodeByNameFor(m_database, "mrX");
            PwUuid  homeXid = homeX.Uuid;

            homeX.ParentGroup.Groups.Remove(homeX);
            grp1.AddGroup(homeX, true);
            m_treeManager.CorrectStructure();

            grp1  = TestHelper.GetGroupByUuidFor(m_database, grpId);
            homeX = TestHelper.GetGroupByUuidFor(m_database, homeXid);
            Assert.AreEqual(TestHelper.GetUsersGroupFor(m_database), homeX.ParentGroup);
            //a new proxy has to be set where we have moved he home before
            Assert.AreEqual(0, grp1.Groups.UCount);
            Assert.AreEqual(1, grp1.Entries.UCount);
            Assert.IsTrue(grp1.Entries.GetAt(0).IsProxyNode());
            string proxyLink = grp1.Entries.GetAt(0).Strings.ReadSafe(KeeShare.KeeShare.UuidLinkField);
            string rootUid   = homeX.Entries.GetAt(0).Uuid.ToHexString();

            Assert.AreEqual(proxyLink, rootUid);
            Assert.AreEqual(5, NumberOfEntriesIn(m_database));
        }
        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);
            }
        }
        private static void ImportGroup(PwDatabase pd, PwGroup pgParent, XmlNode xmlNode)
        {
            PwGroup pg = new PwGroup(true, true);

            foreach (XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if (xmlChild.Name == "name")
                {
                    pg.Name = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == "description")
                {
                    pg.Notes = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == "entry")
                {
                }
                else if (xmlChild.Name == "updated")
                {
                    pg.LastModificationTime = ImportTime(xmlChild);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            pgParent.AddGroup(pg, true);

            ProcessEntries(pd, pg, xmlNode.ChildNodes);
        }
Example #8
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);
            }
        }
Example #9
0
        private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
        {
            PwGroup pg = new PwGroup(true, true);

            pgParent.AddGroup(pg, true);

            try
            {
                XmlAttributeCollection xac = xmlNode.Attributes;
                pg.Name = xac.GetNamedItem(AttribGroupName).Value;
            }
            catch (Exception) { }

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    ReadGroup(xmlChild, pg, pwStorage);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ReadEntry(xmlChild, pg, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Example #10
0
        private static PwGroup FilterCloneGroup(PwGroup pg, Dictionary <PwUuid, bool> dUuids)
        {
            PwGroup pgNew = new PwGroup();

            pgNew.Uuid = pg.Uuid;
            pgNew.AssignProperties(pg, false, true);
            Debug.Assert(pgNew.EqualsGroup(pg, (PwCompareOptions.IgnoreParentGroup |
                                                PwCompareOptions.PropertiesOnly), MemProtCmpMode.Full));

            foreach (PwEntry pe in pg.Entries)
            {
                if (dUuids.ContainsKey(pe.Uuid))
                {
                    pgNew.AddEntry(pe.CloneDeep(), true, false);
                }
            }

            foreach (PwGroup pgSub in pg.Groups)
            {
                if (dUuids.ContainsKey(pgSub.Uuid))
                {
                    pgNew.AddGroup(FilterCloneGroup(pgSub, dUuids), true, false);
                }
            }

            return(pgNew);
        }
Example #11
0
        private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
        {
            PwGroup pg = new PwGroup(true, true);

            pgParent.AddGroup(pg, true);

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemGroupName)
                {
                    pg.Name = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemGroup)
                {
                    ReadGroup(xmlChild, pg, pwStorage);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ReadEntry(xmlChild, pg, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Example #12
0
        private static void ImportCategory(XmlNode xmlNode, PwGroup pgContainer,
                                           PwDatabase pwStorage)
        {
            string strName = ReadNameAttrib(xmlNode);

            if (string.IsNullOrEmpty(strName))
            {
                strName = KPRes.Group;
            }

            PwGroup pg = new PwGroup(true, true, strName, PwIcon.Folder);

            pgContainer.AddGroup(pg, true);

            foreach (XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if (xmlChild.Name.Equals(ElemEntry, StrUtil.CaseIgnoreCmp))
                {
                    ImportEntry(xmlChild, pg, pwStorage);
                }
                else if (xmlChild.Name.Equals(ElemCategory, StrUtil.CaseIgnoreCmp))
                {
                    ImportCategory(xmlChild, pg, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Example #13
0
        private void AddFolder(XElement xelFolder, PwGroup objParent)
        {
            if (xelFolder == null)
            {
                throw new ArgumentNullException("xelFolder");
            }

            string sName = GetString(xelFolder, "Name");

            var objGroup = new PwGroup(true, true, string.IsNullOrEmpty(sName) ? "Unknown" : sName, PwIcon.Folder)
            {
                Notes = GetString(xelFolder, "Comment", true)
            };

            objParent.AddGroup(objGroup, true);

            foreach (XElement xelSubFolder in xelFolder.XPathSelectElements("Folder"))
            {
                AddFolder(xelSubFolder, objGroup);
            }

            foreach (XElement xelRecord in xelFolder.XPathSelectElements("Record"))
            {
                AddRecord(xelRecord, objGroup);
            }
        }
        /// <summary>
        /// Creates (recursively) a group from a downloaded folder
        /// </summary>
        /// <param name="groupName">The group name of the created group.</param>
        /// <param name="secrets">The downloaded secret folder.</param>
        /// <param name="icon">The icon</param>
        /// <returns>The created keepass group</returns>
        private PwGroup CreateGroup(string groupName, SecretFolder secrets, PwIcon icon)
        {
            var group = new PwGroup(true, true, groupName, icon);

            group.CreationTime = DateTime.Now;

            // Create subfolder to recreate tree structure
            foreach (var subFolder in secrets.Folders)
            {
                // Create a subfolder only if there's something in it
                // Avoids having a lot of empty folders we don't have access to in Vault
                if (subFolder.Folders.Count() > 0 || subFolder.Secrets.Count() > 0)
                {
                    this.syncStatus.AddLog(string.Format("Create group {0} in {1}", subFolder.Name, groupName));
                    var subGroup = this.CreateGroup(subFolder.Name, subFolder, icon);
                    group.AddGroup(subGroup, true);
                }
            }

            // Create entries at this level
            foreach (var secret in secrets.Secrets)
            {
                this.syncStatus.AddLog(string.Format("Create entry {0} in {1}", secret.Name, groupName));
                var entry = this.CreateEntry(secret);
                group.AddEntry(entry, true);
            }

            return(group);
        }
        private static PwGroup AddPwGroup(PwGroup containingPwGroup, string newGroupnam)
        {
            PwGroup group = new PwGroup(true, true, newGroupnam, PwIcon.Archive);

            containingPwGroup.AddGroup(group, true);
            RefreshUiGroup(containingPwGroup);
            return(group);
        }
Example #16
0
        public void Import(List <BaseRecord> baseRecords, PwDatabase storage, IStatusLogger status)
        {
            var records        = new List <BaseRecord>();
            var trashedRecords = new List <BaseRecord>();

            baseRecords.ForEach(record =>
            {
                if (record.trashed)
                {
                    trashedRecords.Add(record);
                }
                else
                {
                    records.Add(record);
                }
            });


            var tree = BuildTree(records);

            status.SetText("Importing records..", LogStatusType.Info);

            PwGroup root = new PwGroup(true, true);

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


            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 #17
0
        private static PwGroup CreateFolder(PwGroup groupAddTo, FolderRecord folderRecord)
        {
            PwGroup folder = new PwGroup(true, true);

            folder.Name                 = StringExt.GetValueOrEmpty(folderRecord.title);
            folder.CreationTime         = DateTimeExt.FromUnixTimeStamp(folderRecord.createdAt);
            folder.LastModificationTime = DateTimeExt.FromUnixTimeStamp(folderRecord.updatedAt);
            groupAddTo.AddGroup(folder, true);
            return(folder);
        }
Example #18
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default, true);
            string       strData = sr.ReadToEnd();

            sr.Close();

            strData = StrUtil.NormalizeNewLines(strData, false);

            const string strInitGroup    = "\n\nOrdner:";
            const string strInitTemplate = "\n\nVorlage:";
            const string strInitEntry    = "\n\nEintrag:";
            const string strInitNote     = "\n\nNotiz:";

            string[] vSeps = new string[] { strInitGroup, strInitTemplate,
                                            strInitEntry, strInitNote };

            List <string> lData = StrUtil.SplitWithSep(strData, vSeps, true);

            Debug.Assert((lData.Count & 1) == 1);

            PwGroup pgRoot = pwStorage.RootGroup;

            PwGroup pgTemplates = new PwGroup(true, true, "Vorlagen",
                                              PwIcon.MarkedDirectory);

            pgRoot.AddGroup(pgTemplates, true);

            for (int i = 1; (i + 1) < lData.Count; i += 2)
            {
                string strInit = lData[i];
                string strPart = lData[i + 1];

                if (strInit == strInitGroup)
                {
                }
                else if (strInit == strInitTemplate)
                {
                    ImportEntry(strPart, pgTemplates, pwStorage, false);
                }
                else if (strInit == strInitEntry)
                {
                    ImportEntry(strPart, pgRoot, pwStorage, false);
                }
                else if (strInit == strInitNote)
                {
                    ImportEntry(strPart, pgRoot, pwStorage, true);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
        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 #20
0
        protected TestKp2aApp SetupAppWithDatabase(string filename)
        {
            TestKp2aApp app = CreateTestKp2aApp();

            IOConnectionInfo ioc = new IOConnectionInfo {
                Path = filename
            };
            Database db = app.CreateNewDatabase();

            if (filename.EndsWith(".kdb"))
            {
                db.DatabaseFormat = new KdbDatabaseFormat(app);
            }

            db.KpDatabase = new PwDatabase();

            CompositeKey compositeKey = new CompositeKey();

            compositeKey.AddUserKey(new KcpPassword(DefaultPassword));
            if (!String.IsNullOrEmpty(DefaultKeyfile))
            {
                compositeKey.AddUserKey(new KcpKeyFile(DefaultKeyfile));
            }
            db.KpDatabase.New(ioc, compositeKey);


            db.KpDatabase.KeyEncryptionRounds = 3;
            db.KpDatabase.Name = "Keepass2Android Testing Password Database";


            // Set Database state
            db.Root         = db.KpDatabase.RootGroup;
            db.Loaded       = true;
            db.SearchHelper = new SearchDbHelper(app);

            // Add a couple default groups
            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "Internet", PwIcon.Key), true);

            mailGroup = new PwGroup(true, true, "eMail", PwIcon.UserCommunication);
            db.KpDatabase.RootGroup.AddGroup(mailGroup, true);

            mailGroup.AddGroup(new PwGroup(true, true, "business", PwIcon.BlackBerry), true);

            mailEntry = new PwEntry(true, true);
            mailEntry.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                      true, "*****@*****.**"));
            mailEntry.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                      true, "[email protected] Entry"));
            mailGroup.AddEntry(mailEntry, true);

            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "eMail2", PwIcon.UserCommunication), true);

            return(app);
        }
Example #21
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 #22
0
		private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
		{
			PwGroup pg = new PwGroup(true, true);
			pgParent.AddGroup(pg, true);

			foreach(XmlNode xmlChild in xmlNode)
			{
				if(xmlChild.Name == ElemGroupName)
					pg.Name = XmlUtil.SafeInnerText(xmlChild);
				else if(xmlChild.Name == ElemGroup)
					ReadGroup(xmlChild, pg, pwStorage);
				else if(xmlChild.Name == ElemEntry)
					ReadEntry(xmlChild, pg, pwStorage);
				else { Debug.Assert(false); }
			}
		}
            public IKeePassGroup CreateGroup(string name)
            {
                var pwGroup = new PwGroup(true, true)
                {
                    Name = name
                };

                _group.AddGroup(pwGroup, true, true);

                var wrapped = new KbdxGroup(pwGroup, Parent, Database);

                Groups.Add(wrapped);
                Database.Modified = true;

                return(wrapped);
            }
Example #24
0
        /// <summary>
        /// Get or create the target group of an entry in the target database (including hierarchy).
        /// </summary>
        /// <param name="entry">An entry wich is located in the folder with the target structure.</param>
        /// <param name="targetDatabase">The target database in which the folder structure should be created.</param>
        /// <param name="sourceDatabase">The source database from which the folder properties should be taken.</param>
        /// <returns>The target folder in the target database.</returns>
        private static PwGroup CreateTargetGroupInDatebase(PwEntry entry, PwDatabase targetDatabase, PwDatabase sourceDatabase)
        {
            // Collect all group names from the entry up to the root group
            PwGroup       group = entry.ParentGroup;
            List <PwUuid> list  = new List <PwUuid>();

            while (group != null)
            {
                list.Add(group.Uuid);
                group = group.ParentGroup;
            }

            // Remove root group (we already changed the root group name)
            list.RemoveAt(list.Count - 1);
            // groups are in a bottom-up oder -> reverse to get top-down
            list.Reverse();

            // Create group structure for the new entry (copying group properties)
            PwGroup lastGroup = targetDatabase.RootGroup;

            foreach (PwUuid id in list)
            {
                // Does the target group already exist?
                PwGroup newGroup = lastGroup.FindGroup(id, false);
                if (newGroup != null)
                {
                    lastGroup = newGroup;
                    continue;
                }

                // Get the source group
                PwGroup sourceGroup = sourceDatabase.RootGroup.FindGroup(id, true);

                // Create a new group and asign all properties from the source group
                newGroup = new PwGroup();
                newGroup.AssignProperties(sourceGroup, false, true);
                HandleCustomIcon(targetDatabase, sourceDatabase, sourceGroup);

                // Add the new group at the right position in the target database
                lastGroup.AddGroup(newGroup, true);

                lastGroup = newGroup;
            }

            // Return the target folder (leaf folder)
            return(lastGroup);
        }
Example #25
0
        protected bool DoDeleteGroup(PwGroup pg, List <PwGroup> touchedGroups, List <PwGroup> permanentlyDeletedGroups)
        {
            PwGroup pgParent = pg.ParentGroup;

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

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

            if (pg.Uuid.Equals(pd.EntryTemplatesGroup))
            {
                pd.EntryTemplatesGroup        = PwUuid.Zero;
                pd.EntryTemplatesGroupChanged = DateTime.Now;
            }

            pgParent.Groups.Remove(pg);
            touchedGroups.Add(pgParent);
            if ((DeletePermanently) || (!CanRecycle))
            {
                pg.DeleteAllObjects(pd);

                PwDeletedObject pdo = new PwDeletedObject(pg.Uuid, DateTime.Now);
                pd.DeletedObjects.Add(pdo);


                permanentlyDeletedGroups.Add(pg);
            }
            else             // Recycle
            {
                bool groupListUpdateRequired = false;
                EnsureRecycleBinExists(ref pgRecycleBin, ref groupListUpdateRequired);

                pgRecycleBin.AddGroup(pg, true, true);
                pg.Touch(false);
                // Mark new parent (Recycle bin) touched
                touchedGroups.Add(pg.ParentGroup);
                // mark root touched if recycle bin was created
                if (groupListUpdateRequired)
                {
                    touchedGroups.Add(Db.Root);
                }
            }
            return(true);
        }
		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 #27
0
		public void Import(List<BaseRecord> baseRecords, PwDatabase storage, IStatusLogger status)
		{
			var records = new List<BaseRecord>();
			var trashedRecords = new List<BaseRecord>();

			baseRecords.ForEach(record =>
			{
				if (record.trashed)
					trashedRecords.Add(record);
				else
					records.Add(record);
			});


			var tree = BuildTree(records);

			status.SetText("Importing records..", LogStatusType.Info);
			
			PwGroup root = new PwGroup(true, true);
			root.Name = "1Password Import on " + DateTime.Now.ToString();


			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)
						CreateWebForm(trash, storage, wfrecord);
				}
				root.AddGroup(trash, true);
			}

			storage.RootGroup.AddGroup(root, true);
		}
Example #28
0
        private void importRecord(TreeNode <Records.BaseRecord> currentNode, PwGroup pwGroupAddTo, PwDatabase pwDatabase, UserPrefs userPrefs)
        {
            Records.BaseRecord record = currentNode.AssociatedObject;

            if (record is Records.RegularFolderRecord)
            {
                PwGroup folder = (record as Records.RegularFolderRecord).CreatePwGroup();

                if (folder != null)
                {
                    pwGroupAddTo.AddGroup(folder, true);

                    foreach (TreeNode <Records.BaseRecord> child in currentNode.Children)
                    {
                        importRecord(child, folder, pwDatabase, userPrefs);
                    }
                }
            }
            else
            {
                Records.ItemRecord itemRecord = record as Records.ItemRecord;

                PwEntry entry = itemRecord.CreatePwEntry(pwDatabase, userPrefs);

                if (entry != null)
                {
                    PwCustomIcon customIcon = itemRecord.GetPwCustomIcon();

                    if (customIcon != null)
                    {
                        if (!pwDatabase.CustomIcons.Exists(icon => icon.Uuid.Equals(customIcon.Uuid)))
                        {
                            pwDatabase.CustomIcons.Add(customIcon);
                        }

                        pwDatabase.UINeedsIconUpdate = true;
                    }

                    pwGroupAddTo.AddEntry(entry, true);
                }
            }
        }
Example #29
0
        private static void AddFolder(PwGroup pgParent, HspFolder hspFolder,
                                      bool bNewGroup)
        {
            if (hspFolder == null)
            {
                Debug.Assert(false); return;
            }

            PwGroup pg;

            if (bNewGroup)
            {
                pg = new PwGroup(true, true);
                pgParent.AddGroup(pg, true);

                if (!string.IsNullOrEmpty(hspFolder.Name))
                {
                    pg.Name = hspFolder.Name;
                }
            }
            else
            {
                pg = pgParent;
            }

            if (hspFolder.Folders != null)
            {
                foreach (HspFolder fld in hspFolder.Folders)
                {
                    AddFolder(pg, fld, true);
                }
            }

            if (hspFolder.Cards != null)
            {
                foreach (HspCard crd in hspFolder.Cards)
                {
                    AddCard(pg, crd);
                }
            }
        }
Example #30
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 #31
0
        private static void ReadGroup(XmlNode xmlNode, Stack <PwGroup> vGroups,
                                      PwDatabase pwStorage)
        {
            if (vGroups.Count == 0)
            {
                Debug.Assert(false); return;
            }
            PwGroup pgParent = vGroups.Peek();

            PwGroup pg = new PwGroup(true, true);

            pgParent.AddGroup(pg, true);
            vGroups.Push(pg);

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemTitle)
                {
                    pg.Name = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemIcon)
                {
                    pg.IconId = ReadIcon(xmlChild, pg.IconId);
                }
                else if (xmlChild.Name == ElemGroup)
                {
                    ReadGroup(xmlChild, vGroups, pwStorage);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ReadEntry(xmlChild, pg, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            vGroups.Pop();
        }
Example #32
0
        private void AddGroup(XElement xelGroup, PwGroup objRoot)
        {
            if (xelGroup == null)
            {
                throw new ArgumentNullException("xelGroup");
            }

            string sName = GetString(xelGroup, "Name");

            var objGroup = new PwGroup(true, true, string.IsNullOrEmpty(sName) ? "Unknown" : sName, PwIcon.FolderPackage)
            {
                Notes = GetString(xelGroup, "Comment", true)
            };

            DateTime dtValid;

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

            string aAutoType = GetString(xelGroup, "AutoType");

            if (!string.IsNullOrEmpty(aAutoType))
            {
                objGroup.DefaultAutoTypeSequence = ConvertAutoType(aAutoType, xelGroup);
            }
            objRoot.AddGroup(objGroup, true);

            foreach (XElement xelFolder in xelGroup.XPathSelectElements("Folder"))
            {
                AddFolder(xelFolder, objGroup);
            }

            foreach (XElement xelRecord in xelGroup.XPathSelectElements("Record"))
            {
                AddRecord(xelRecord, objGroup);
            }
        }
Example #33
0
        private static PwGroup FindCreateGroup(string strSpec, PwGroup pgStorage,
                                               Dictionary <string, PwGroup> dRootGroups, string strSep, CsvOptions opt,
                                               bool bMergeGroups)
        {
            List <string> l = SplitGroupPath(strSpec, strSep, opt);

            if (bMergeGroups)
            {
                char   chSep   = StrUtil.GetUnusedChar(strSpec);
                string strPath = AssembleGroupPath(l, 0, chSep);

                return(pgStorage.FindCreateSubTree(strPath, new char[1] {
                    chSep
                }));
            }

            string strRootSub = l[0];

            if (!dRootGroups.ContainsKey(strRootSub))
            {
                PwGroup pgNew = new PwGroup(true, true);
                pgNew.Name = strRootSub;
                pgStorage.AddGroup(pgNew, true);
                dRootGroups[strRootSub] = pgNew;
            }
            PwGroup pg = dRootGroups[strRootSub];

            if (l.Count > 1)
            {
                char   chSep      = StrUtil.GetUnusedChar(strSpec);
                string strSubPath = AssembleGroupPath(l, 1, chSep);

                pg = pg.FindCreateSubTree(strSubPath, new char[1] {
                    chSep
                });
            }

            return(pg);
        }
Example #34
0
        private void AddEntry(PwDatabase pwStorage, PwGroup group, Entry entry)
        {
            var pwModel = entry.ToPw(pwStorage);

            // Add group
            var pwGroup = pwModel as PwGroup;

            if (pwGroup != null)
            {
                group.AddGroup(pwGroup, true);
                return;
            }

            // Add entry
            var pwEntry = pwModel as PwEntry;

            if (pwEntry != null)
            {
                group.AddEntry(pwEntry, true);
                return;
            }
        }
Example #35
0
        private static PwGroup FindCreateGroup(string strSpec, PwGroup pgStorage,
			Dictionary<string, PwGroup> dRootGroups, string strSep, CsvOptions opt)
        {
            List<string> l = new List<string>();
            if(string.IsNullOrEmpty(strSep)) l.Add(strSpec);
            else
            {
                string[] vChain = strSpec.Split(new string[1] { strSep },
                    StringSplitOptions.RemoveEmptyEntries);
                for(int i = 0; i < vChain.Length; ++i)
                {
                    string strGrp = vChain[i];
                    if(opt.TrimFields) strGrp = strGrp.Trim();
                    if(strGrp.Length > 0) l.Add(strGrp);
                }
                if(l.Count == 0) l.Add(strSpec);
            }

            string strRootSub = l[0];
            if(!dRootGroups.ContainsKey(strRootSub))
            {
                PwGroup pgNew = new PwGroup(true, true);
                pgNew.Name = strRootSub;
                pgStorage.AddGroup(pgNew, true);
                dRootGroups[strRootSub] = pgNew;
            }
            PwGroup pg = dRootGroups[strRootSub];

            if(l.Count > 1)
            {
                char chSep = StrUtil.GetUnusedChar(strSpec);
                StringBuilder sb = new StringBuilder();
                for(int i = 1; i < l.Count; ++i)
                {
                    if(i > 1) sb.Append(chSep);
                    sb.Append(l[i]);
                }

                pg = pg.FindCreateSubTree(sb.ToString(), new char[1]{ chSep });
            }

            return pg;
        }
Example #36
0
		private static void ImportGroup(XmlNode xn, PwGroup pgParent, PwDatabase pd,
			bool bIsRecycleBin)
		{
			PwGroup pg;
			if(!bIsRecycleBin)
			{
				pg = new PwGroup(true, true);
				pgParent.AddGroup(pg, true);
			}
			else
			{
				pg = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);

				if(pg == null)
				{
					pg = new PwGroup(true, true, KPRes.RecycleBin, PwIcon.TrashBin);
					pgParent.AddGroup(pg, true);

					pd.RecycleBinUuid = pg.Uuid;
					pd.RecycleBinChanged = DateTime.UtcNow;
				}
			}

			foreach(XmlNode xmlChild in xn.ChildNodes)
			{
				if(xmlChild.Name == ElemName)
					pg.Name = XmlUtil.SafeInnerText(xmlChild);
				else if(xmlChild.Name == ElemIcon)
					pg.IconId = GetIcon(XmlUtil.SafeInnerText(xmlChild));
				else if(xmlChild.Name == ElemGroup)
					ImportGroup(xmlChild, pg, pd, false);
				else if(xmlChild.Name == ElemEntry)
					ImportEntry(xmlChild, pg, pd);
				else { Debug.Assert(false); }
			}
		}
Example #37
0
        private static void ImportGroup(PwDatabase pd, PwGroup pgParent, XmlNode xmlNode)
        {
            PwGroup pg = new PwGroup(true, true);

            foreach(XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if(xmlChild.Name == "name")
                    pg.Name = XmlUtil.SafeInnerText(xmlChild);
                else if(xmlChild.Name == "description")
                    pg.Notes = XmlUtil.SafeInnerText(xmlChild);
                else if(xmlChild.Name == "entry") { }
                else if(xmlChild.Name == "updated")
                    pg.LastModificationTime = ImportTime(xmlChild);
                else { Debug.Assert(false); }
            }

            pgParent.AddGroup(pg, true);

            ProcessEntries(pd, pg, xmlNode.ChildNodes);
        }
        public void MoveUserHomeShouldCreateAProxyInTheTarget()
        {
            m_treeManager.Initialize(m_database);
            m_treeManager.CreateNewUser("mrX");
            m_treeManager.CreateNewUser("mrY");
            PwGroup grp1 = new PwGroup(true, true, "testgrp", PwIcon.Archive);
            PwUuid grpId = grp1.Uuid;
            m_database.RootGroup.AddGroup(grp1, true);

            Assert.AreEqual(4, m_database.RootGroup.Groups.UCount);

            //move home to a normal PwGroup
            PwGroup homeX = TestHelper.GetUserHomeNodeByNameFor(m_database, "mrX");
            PwUuid homeXid = homeX.Uuid;
            homeX.ParentGroup.Groups.Remove(homeX);
            grp1.AddGroup(homeX, true);
            m_treeManager.CorrectStructure();

            grp1 = TestHelper.GetGroupByUuidFor( m_database, grpId);
            homeX = TestHelper.GetGroupByUuidFor(m_database, homeXid);
            Assert.AreEqual(TestHelper.GetUsersGroupFor(m_database), homeX.ParentGroup);
            //a new proxy has to be set where we have moved he home before
            Assert.AreEqual(0, grp1.Groups.UCount);
            Assert.AreEqual(1, grp1.Entries.UCount);
            Assert.IsTrue(grp1.Entries.GetAt(0).IsProxyNode());
            string proxyLink = grp1.Entries.GetAt(0).Strings.ReadSafe(KeeShare.KeeShare.UuidLinkField);
            string rootUid = homeX.Entries.GetAt(0).Uuid.ToHexString();
            Assert.AreEqual(proxyLink, rootUid);
            Assert.AreEqual(5, NumberOfEntriesIn(m_database));
        }
        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 #40
0
		private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
		{
			PwGroup pg = new PwGroup(true, true);
			pgParent.AddGroup(pg, true);

			try
			{
				XmlAttributeCollection xac = xmlNode.Attributes;
				pg.Name = xac.GetNamedItem(AttribGroupName).Value;
			}
			catch(Exception) { }

			foreach(XmlNode xmlChild in xmlNode)
			{
				if(xmlChild.Name == ElemGroup)
					ReadGroup(xmlChild, pg, pwStorage);
				else if(xmlChild.Name == ElemEntry)
					ReadEntry(xmlChild, pg, pwStorage);
				else { Debug.Assert(false); }
			}
		}
        private static void AddObject(PwGroup pgStorage, JsonObject jObject,
			PwDatabase pwContext, bool bCreateSubGroups,
			Dictionary<string, List<string>> dTags, List<PwEntry> lCreatedEntries)
        {
            JsonValue jvRoot;
            jObject.Items.TryGetValue("root", out jvRoot);
            string strRoot = (((jvRoot != null) ? jvRoot.ToString() : null) ?? string.Empty);
            if(strRoot.Equals("tagsFolder", StrUtil.CaseIgnoreCmp))
            {
                ImportTags(jObject, dTags);
                return;
            }

            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, dTags, lCreatedEntries);
                    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(jObject.Items.ContainsKey("annos"))
            {
                JsonArray vAnnos = (jObject.Items["annos"].Value as JsonArray);
                if(vAnnos != null)
                {
                    foreach(JsonValue jv in vAnnos.Values)
                    {
                        if(jv == null) { Debug.Assert(false); continue; }
                        JsonObject jo = (jv.Value as JsonObject);
                        if(jo == null) { Debug.Assert(false); continue; }

                        JsonValue jvAnnoName, jvAnnoValue;
                        jo.Items.TryGetValue("name", out jvAnnoName);
                        jo.Items.TryGetValue("value", out jvAnnoValue);
                        if((jvAnnoName == null) || (jvAnnoValue == null)) continue;

                        string strAnnoName = jvAnnoName.ToString();
                        string strAnnoValue = jvAnnoValue.ToString();
                        if((strAnnoName == null) || (strAnnoValue == null)) continue;

                        if(strAnnoName == "bookmarkProperties/description")
                            pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                pwContext.MemoryProtection.ProtectNotes, strAnnoValue));
                    }
                }
            }

            if((pe.Strings.ReadSafe(PwDefs.TitleField).Length > 0) ||
                (pe.Strings.ReadSafe(PwDefs.UrlField).Length > 0))
            {
                pgStorage.AddEntry(pe, true);
                lCreatedEntries.Add(pe);
            }
        }
Example #42
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);
        }
Example #43
0
		private static void AddGroup(XmlNode xnGrp, PwGroup pgParent, PwDatabase pd)
		{
			XmlNode xnName = xnGrp.Attributes.GetNamedItem(AttribCaption);
			string strName = ((xnName != null) ? xnName.Value : null);
			if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); strName = KPRes.Group; }

			PwGroup pg = new PwGroup(true, true);
			pg.Name = strName;

			pgParent.AddGroup(pg, true);

			foreach(XmlNode xn in xnGrp)
			{
				if(Array.IndexOf<string>(ElemsGroup, xn.Name) >= 0)
					AddGroup(xn, pg, pd);
				else if(Array.IndexOf<string>(ElemsEntry, xn.Name) >= 0)
					AddEntry(xn, pg, pd);
				else if(Array.IndexOf<string>(ElemsWebEntry, xn.Name) >= 0)
					AddWebEntry(xn, pg, pd);
				else { Debug.Assert(false); } // Unknown node
			}
		}
Example #44
0
        private static void ReadGroup(XmlNode xmlNode, PwGroup pgParent, PwDatabase pwStorage)
        {
            PwGroup pg = new PwGroup(true, true);
            pgParent.AddGroup(pg, true);

            foreach(XmlNode xmlChild in xmlNode)
            {
                if(xmlChild.NodeType == XmlNodeType.Text)
                {
                    string strValue = (xmlChild.Value ?? string.Empty).Trim();
                    if(strValue.Length > 0)
                    {
                        if(pg.Name.Length > 0) pg.Name += " ";
                        pg.Name += strValue;
                    }
                }
                else if(xmlChild.Name == ElemGroup)
                    ReadGroup(xmlChild, pg, pwStorage);
                else if(xmlChild.Name == ElemEntry)
                    ReadEntry(xmlChild, pg, pwStorage);
                else if(xmlChild.Name == ElemTags) { }
                else { Debug.Assert(false); }
            }
        }
Example #45
0
        private void PerformImport(PwGroup pgStorage, bool bCreatePreview)
        {
            List<CsvFieldInfo> lFields = new List<CsvFieldInfo>();
            for(int i = 0; i < m_lvFields.Items.Count; ++i)
            {
                CsvFieldInfo cfi = (m_lvFields.Items[i].Tag as CsvFieldInfo);
                if(cfi == null) { Debug.Assert(false); continue; }
                lFields.Add(cfi);
            }

            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.Now;
            DateTime dtNoExpire = KdbTime.NeverExpireTime.ToDateTime();
            bool bIgnoreFirstRow = m_cbIgnoreFirst.Checked;
            bool bIsFirstRow = true;

            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 pgParent = 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.GroupName)
                    {
                        if(!dGroups.ContainsKey(strField))
                        {
                            PwGroup pgNew = new PwGroup(true, true);
                            pgNew.Name = strField;
                            pgStorage.AddGroup(pgNew, true);
                            dGroups[strField] = pgNew;
                        }

                        pgParent = dGroups[strField];
                    }
                    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 { 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);
                    }
                }

                pgParent.AddEntry(pe, true);
            }

            if(bCreatePreview)
            {
                m_lvImportPreview.EndUpdate();
                ProcessResize();
            }
        }
Example #46
0
        private static void ImportCategory(XmlNode xmlNode, PwGroup pgContainer,
			PwDatabase pwStorage)
        {
            string strName = ReadNameAttrib(xmlNode);
            if(string.IsNullOrEmpty(strName)) strName = KPRes.Group;

            PwGroup pg = new PwGroup(true, true, strName, PwIcon.Folder);
            pgContainer.AddGroup(pg, true);

            foreach(XmlNode xmlChild in xmlNode.ChildNodes)
            {
                if(xmlChild.Name.Equals(ElemEntry, StrUtil.CaseIgnoreCmp))
                    ImportEntry(xmlChild, pg, pwStorage);
                else if(xmlChild.Name.Equals(ElemCategory, StrUtil.CaseIgnoreCmp))
                    ImportCategory(xmlChild, pg, pwStorage);
                else { Debug.Assert(false); }
            }
        }
Example #47
0
        private static PwGroup FindCreateGroup(string strSpec, PwGroup pgStorage,
			Dictionary<string, PwGroup> dRootGroups, string strSep, CsvOptions opt,
			bool bMergeGroups)
        {
            List<string> l = SplitGroupPath(strSpec, strSep, opt);

            if(bMergeGroups)
            {
                char chSep = StrUtil.GetUnusedChar(strSpec);
                string strPath = AssembleGroupPath(l, 0, chSep);

                return pgStorage.FindCreateSubTree(strPath, new char[1] { chSep });
            }

            string strRootSub = l[0];
            if(!dRootGroups.ContainsKey(strRootSub))
            {
                PwGroup pgNew = new PwGroup(true, true);
                pgNew.Name = strRootSub;
                pgStorage.AddGroup(pgNew, true);
                dRootGroups[strRootSub] = pgNew;
            }
            PwGroup pg = dRootGroups[strRootSub];

            if(l.Count > 1)
            {
                char chSep = StrUtil.GetUnusedChar(strSpec);
                string strSubPath = AssembleGroupPath(l, 1, chSep);

                pg = pg.FindCreateSubTree(strSubPath, new char[1] { chSep });
            }

            return pg;
        }
Example #48
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 #49
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); }
            }
        }
Example #50
0
		private static PwGroup CreateFolder(PwGroup groupAddTo, FolderRecord folderRecord)
		{
			PwGroup folder = new PwGroup(true, true);
			folder.Name = StringExt.GetValueOrEmpty(folderRecord.title);
			folder.CreationTime = DateTimeExt.FromUnixTimeStamp(folderRecord.createdAt);
			folder.LastModificationTime = DateTimeExt.FromUnixTimeStamp(folderRecord.updatedAt);
			groupAddTo.AddGroup(folder, true);
			return folder;
		}
Example #51
0
        protected TestKp2aApp SetupAppWithDatabase(string filename)
        {
            TestKp2aApp app = CreateTestKp2aApp();

            IOConnectionInfo ioc = new IOConnectionInfo {Path = filename};
            Database db = app.CreateNewDatabase();
            if (filename.EndsWith(".kdb"))
            {
                db.DatabaseFormat = new KdbDatabaseFormat(app);
            }

            db.KpDatabase = new PwDatabase();

            CompositeKey compositeKey = new CompositeKey();
            compositeKey.AddUserKey(new KcpPassword(DefaultPassword));
            if (!String.IsNullOrEmpty(DefaultKeyfile))
                compositeKey.AddUserKey(new KcpKeyFile(DefaultKeyfile));
            db.KpDatabase.New(ioc, compositeKey);

            db.KpDatabase.KeyEncryptionRounds = 3;
            db.KpDatabase.Name = "Keepass2Android Testing Password Database";

            // Set Database state
            db.Root = db.KpDatabase.RootGroup;
            db.Loaded = true;
            db.SearchHelper = new SearchDbHelper(app);

            // Add a couple default groups
            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "Internet", PwIcon.Key), true);

            mailGroup = new PwGroup(true, true, "eMail", PwIcon.UserCommunication);
            db.KpDatabase.RootGroup.AddGroup(mailGroup, true);

            mailGroup.AddGroup(new PwGroup(true, true, "business", PwIcon.BlackBerry), true);

            mailEntry = new PwEntry(true, true);
            mailEntry.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                                            true, "*****@*****.**"));
            mailEntry.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                                         true, "[email protected] Entry"));
            mailGroup.AddEntry(mailEntry, true);

            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "eMail2", PwIcon.UserCommunication), true);

            return app;
        }
        private void AddFolder( XElement xelFolder, PwGroup objParent )
        {
            if ( xelFolder == null )
            {
                throw new ArgumentNullException( "xelFolder" );
            }

            string sName = GetString( xelFolder, "Name" );

            var objGroup = new PwGroup( true, true, string.IsNullOrEmpty( sName ) ? "Unknown" : sName, PwIcon.Folder )
                {
                    Notes = GetString( xelFolder, "Comment", true )
                };

            objParent.AddGroup( objGroup, true );

            foreach( XElement xelSubFolder in xelFolder.XPathSelectElements( "Folder" ) )
            {
                AddFolder( xelSubFolder, objGroup );
            }

            foreach( XElement xelRecord in xelFolder.XPathSelectElements( "Record" ) )
            {
                AddRecord( xelRecord, objGroup );
            }
        }
 public static void SetParent(this PwGroup group, PwGroup parent, bool bTakeOwnership = true)
 {
     parent.AddGroup(group, bTakeOwnership);
 }
        private void AddGroup( XElement xelGroup, PwGroup objRoot )
        {
            if ( xelGroup == null )
            {
                throw new ArgumentNullException( "xelGroup" );
            }

            string sName = GetString( xelGroup, "Name" );

            var objGroup = new PwGroup( true, true, string.IsNullOrEmpty( sName ) ? "Unknown" : sName, PwIcon.FolderPackage )
                {
                    Notes = GetString( xelGroup, "Comment", true )
                };

            DateTime dtValid;

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

            string aAutoType = GetString( xelGroup, "AutoType" );
            if( !string.IsNullOrEmpty( aAutoType ) )
            {
                objGroup.DefaultAutoTypeSequence = ConvertAutoType( aAutoType, xelGroup );
            }
            objRoot.AddGroup( objGroup, true );

            foreach( XElement xelFolder in xelGroup.XPathSelectElements( "Folder" ) )
            {
                AddFolder( xelFolder, objGroup );
            }

            foreach( XElement xelRecord in xelGroup.XPathSelectElements( "Record" ) )
            {
                AddRecord( xelRecord, objGroup );
            }
        }
        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 #56
0
		private static void AddFolder(PwGroup pgParent, HspFolder hspFolder,
			bool bNewGroup)
		{
			if(hspFolder == null) { Debug.Assert(false); return; }

			PwGroup pg;
			if(bNewGroup)
			{
				pg = new PwGroup(true, true);
				pgParent.AddGroup(pg, true);

				if(!string.IsNullOrEmpty(hspFolder.Name))
					pg.Name = hspFolder.Name;
			}
			else pg = pgParent;

			if(hspFolder.Folders != null)
			{
				foreach(HspFolder fld in hspFolder.Folders)
					AddFolder(pg, fld, true);
			}

			if(hspFolder.Cards != null)
			{
				foreach(HspCard crd in hspFolder.Cards)
					AddCard(pg, crd);
			}
		}