Exemplo n.º 1
0
        public void New_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile file = testData.CreateFileAsync("1.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword("0"));
            var db = new PwDatabase();

            db.New(ci, key);
            var initialEnitiesCount = db.RootGroup.GetEntriesCount(true);

            Assert.AreNotEqual(0, initialEnitiesCount);
            db.Save(null);
            db.Close();
            Assert.IsNull(db.RootGroup);
            db = new PwDatabase();
            db.Open(ci, key, null);
            Assert.AreEqual(initialEnitiesCount,
                            db.RootGroup.GetEntriesCount(true));
        }
Exemplo n.º 2
0
        /// <summary>
        /// The function tries to merge possible updates from the deltaDB into
        /// the actual database. If there was made changes to the actualDB, then
        /// the function fires a event, which cause the KeePass UI to update and
        /// show the "save"-button.
        /// </summary>
        public void Import(object sender, SyncSource source)
        {
            Debug.Assert(source.DestinationDB != null && source.DestinationDB.RootGroup != null);
            //merge all updates in
            PwDatabase deltaDB = new PwDatabase();

            try {
                deltaDB.Open(IOConnectionInfo.FromPath(source.Location), source.Key, null);
            }
            catch (InvalidCompositeKeyException e) {
                Debug.WriteLine("Wrong key! exception was: " + e.Message);
                //brand this entry as a false one => red bg-color and "X" as group icon
                ShowErrorHighlight(source.DestinationDB, source.Uuid);
                if (Imported != null)
                {
                    Imported.Invoke(this, source.DestinationDB.RootGroup);
                }
                return;
            }
            catch (Exception e) {
                Debug.WriteLine("Standard exception was thrown during deltaDB.Open(): " + e.Message);
                //maybe the process has not finished writing to our file, but the filewtcher fires our event
                //sourceEntryUuid we have to ignore it and wait for the next one.
                return;
            }
            HideErrorHighlight(source.DestinationDB, source.Uuid);
            MergeIn(source.DestinationDB, deltaDB);
            deltaDB.Close();
        }
Exemplo n.º 3
0
 void Syncronize(PwDatabase database)
 {
     try
     {
         var filename = database.IOConnectionInfo.Path;
         var isSame   = Api.IsDatabaseSame(filename);
         if (!isSame)
         {
             var tempFilename = Path.GetTempPath() + String.Concat(Guid.NewGuid().ToString(), ".temp");
             var tempFile     = Api.DownloadDatabase(filename, tempFilename);
             if (tempFile != null)
             {
                 var serialinfo = new IOConnectionInfo {
                     Path = tempFile.FullName
                 };
                 var db  = new PwDatabase();
                 var log = new Log();
                 db.Open(serialinfo, database.MasterKey, log);
                 database.MergeIn(db, PwMergeMethod.Synchronize);
                 db.Close();
                 tempFile.Delete();
             }
             Api.UploadDatabase(filename);
             Api.CompactDatabase(filename);
         }
     }
     catch (Exception ex)
     {
         ShowNotification(ex.Message);
     }
 }
Exemplo n.º 4
0
        public static PwDatabase OpenDatabase(this IOConnectionInfo connectionInfo, CompositeKey key)
        {
            var database = new PwDatabase();

            database.Open(connectionInfo, key, new NullStatusLogger()); // TODO Check if Powershell output logger instead of NullLogger makes any sense
            return(database);
        }
Exemplo n.º 5
0
 public void Sync()
 {
     this.fileSystemWatcher.EnableRaisingEvents = false;
     System.Threading.Thread.Sleep(500 + randomizer.Next(500, 1000) + randomizer.Next(500, 1500));
     try {
         var db = new PwDatabase();
         db.Open(this.database.IOConnectionInfo, this.database.MasterKey, new NullStatusLogger());
         this.database.MergeIn(db, PwMergeMethod.Synchronize);
         db.Close();
         AutoSyncExt.host.MainWindow.RefreshEntriesList();
     } catch (Exception e) {
         this.database.Modified = true;
         var notification = new System.Windows.Forms.NotifyIcon()
         {
             Visible         = true,
             Icon            = System.Drawing.SystemIcons.Information,
             BalloonTipIcon  = System.Windows.Forms.ToolTipIcon.Warning,
             BalloonTipTitle = "KeePass.AutoSync",
             BalloonTipText  = "Database: " + this.database.IOConnectionInfo.Path + Environment.NewLine + Environment.NewLine + e.Message,
         };
         notification.ShowBalloonTip(5000);
         Thread.Sleep(10000);
         notification.Dispose();
     }
     this.fileSystemWatcher.EnableRaisingEvents = true;
 }
Exemplo n.º 6
0
        protected virtual void PopulateDatabaseFromStream(PwDatabase pwDatabase, Stream s, IOConnectionInfo iocInfo, CompositeKey compositeKey, ProgressDialogStatusLogger status, IDatabaseFormat databaseFormat)
        {
            IFileStorage fileStorage = _app.GetFileStorage(iocInfo);
            var          filename    = fileStorage.GetFilenameWithoutPathAndExt(iocInfo);

            pwDatabase.Open(s, filename, iocInfo, compositeKey, status, databaseFormat);
        }
Exemplo n.º 7
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var ioConnectionInfo = new IOConnectionInfo()
            {
                Path = databasePath
            };

            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword(databasePassword));

            var pwDatabase = new PwDatabase();

            pwDatabase.Open(ioConnectionInfo, key, null);

            var fieldMapper = new InMemoryFieldMapper()
            {
                HostAddress      = "IP Address",
                ConnectionMethod = "OS"
            };

            IPasswordChangerTreeNode treeNode = PasswordChangerTreeNode.Build(pwDatabase, fieldMapper);

            var pwChangerServiceFactory = new PasswordChangerServiceFactory(
                new PasswordDatabase(pwDatabase),
                new FakePasswordChangerExFactoryThatThrowsException()
                );

            var formBatchPasswordChanger = new FormBatchPasswordChanger(treeNode, pwChangerServiceFactory);

            Application.Run(formBatchPasswordChanger);
        }
Exemplo n.º 8
0
        private static PwDatabase CreateTargetDatabase(PwDatabase sourceDb, Settings settings, CompositeKey key)
        {
            // Default to same folder as sourceDb for target if no directory is specified
            if (!Path.IsPathRooted(settings.TargetFilePath))
            {
                string sourceDbPath = Path.GetDirectoryName(sourceDb.IOConnectionInfo.Path);
                if (sourceDbPath != null)
                {
                    settings.TargetFilePath = Path.Combine(sourceDbPath, settings.TargetFilePath);
                }
            }

            // Create a new database
            PwDatabase targetDatabase = new PwDatabase();

            if (!settings.OverrideTargetDatabase && File.Exists(settings.TargetFilePath))
            {
                // Connect the database object to the existing database
                targetDatabase.Open(new IOConnectionInfo()
                {
                    Path = settings.TargetFilePath
                }, key, new NullStatusLogger());
            }
            else
            {
                // Apply the created key to the new database
                targetDatabase.New(new IOConnectionInfo(), key);
            }

            return(targetDatabase);
        }
Exemplo n.º 9
0
        private static void ResaveKdbx(string kdbx2ExportPath, string kdbx2ExportPassword)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var pwbDatabase = new PwDatabase();

            var cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(kdbx2ExportPassword));

            var ioc = IOConnectionInfo.FromPath(kdbx2ExportPath);

            pwbDatabase.Open(ioc, cmpKey, null);

            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"{elapsed.TotalSeconds}s to load [{kdbx2ExportPath}]");

            stopwatch.Reset();

            var duplicate = new KdbxFile(pwbDatabase);
            var dupPath   = Path.GetDirectoryName(kdbx2ExportPath)
                            + Path.DirectorySeparatorChar
                            + Path.GetFileNameWithoutExtension(kdbx2ExportPath)
                            + ".dup"
                            + Path.GetExtension(kdbx2ExportPath);
            var fileStream = new FileStream(dupPath, FileMode.Create);

            duplicate.Save(fileStream, null, KdbxFormat.Default, null);

            Console.WriteLine($"{elapsed.TotalSeconds}s to save [{kdbx2ExportPath}] to [{dupPath}]");
        }
Exemplo n.º 10
0
        private static void ExportKdbx2Xml(string kdbx2ExportPath, string kdbx2ExportPassword)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var pwbDatabase = new PwDatabase();

            var cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(kdbx2ExportPassword));

            var ioc = IOConnectionInfo.FromPath(kdbx2ExportPath);

            pwbDatabase.Open(ioc, cmpKey, null);

            var xmlExportFile = new KdbxFile(pwbDatabase);
            var xmlPath       = Path.GetDirectoryName(kdbx2ExportPath) + Path.DirectorySeparatorChar
                                + Path.GetFileNameWithoutExtension(kdbx2ExportPath) + ".xml";
            var fileStream = new FileStream(xmlPath, FileMode.Create);

            xmlExportFile.Save(fileStream, null, KdbxFormat.PlainXml, null);
            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"{elapsed.TotalSeconds}s to export [{kdbx2ExportPath}] to [{xmlPath}]");
        }
Exemplo n.º 11
0
        public void ShouldExportAfterChangedContent()
        {
            PwEntry mrX = TestHelper.GetUserRootNodeFor(m_database, 0);

            //the first autoExport only checks if there is a delta container allready and if not it will export one
            //in our case there should be no existing container so a new one will be created.
            string  exportPath  = GetTestPath();
            PwGroup exportGroup = new PwGroup(true, true, exportPath, PwIcon.Apple);

            m_database.GetExportGroup().AddGroup(exportGroup, true);
            exportGroup.AddEntry(mrX.CreateProxyNode(), true);

            string exportFile = exportPath + SyncSource.FileNameFor(mrX) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            m_syncManager.RefeshSourcesList();
            m_syncManager.Export();

            mrX = TestHelper.GetUserRootNodeFor(m_database, 0);
            Assert.AreEqual("mrX", mrX.GetTitle());

            Assert.IsTrue(File.Exists(exportFile));

            //now we will change a password that is shared to mrX and then trigger the AutoExport method
            //like it will happen on any OnChangeEvent. After that again we validate the data in the export container.
            PwEntry entry1 = m_database.RootGroup.FindEntry(Uuid1, true);

            entry1.SetTitle("new title");
            //due to the fact that the UnitTest is way faster than userIneraction we have to manipulate the lastModTimestamp
            //because if we don't do that the um.Update() method will maybe use another value to update all references and
            //then we will have the old title in the stringField
            TestHelper.SimulateTouch(entry1);
            //now we run the update methods that will be triggered on every UiChangeEvent
            m_treeManager.CorrectStructure();
            m_syncManager.RefeshSourcesList();
            //the autoexport method was triggered by in import or OnSaveEvent only so we have to trigger it manually here

            m_syncManager.Export();

            PwDatabase deltaDB = new PwDatabase();

            Assert.DoesNotThrow(delegate {
                deltaDB.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            });
            //as before we want to have the same content except that entry1 should now have a new title!
            Assert.AreEqual(5, deltaDB.RootGroup.GetEntries(true).UCount);
            Assert.AreEqual(3, deltaDB.RootGroup.Entries.UCount);
            Assert.AreEqual("grp1", deltaDB.RootGroup.Groups.GetAt(0).Name);
            Assert.AreEqual(2, deltaDB.RootGroup.Groups.GetAt(0).Entries.UCount);
            //now we will test in detail if there are only the expected entries in the created delta container
            Assert.AreEqual(Uuid1, deltaDB.RootGroup.Entries.GetAt(0).Uuid);
            Assert.AreEqual(Uuid3, deltaDB.RootGroup.Entries.GetAt(2).Uuid);
            Assert.AreEqual(Uuid6, deltaDB.RootGroup.Entries.GetAt(1).Uuid);
            Assert.AreEqual(Uuid4, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(0).Uuid);
            Assert.AreEqual(Uuid5, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(1).Uuid);
            Assert.AreEqual("new title", deltaDB.RootGroup.Entries.GetAt(0).GetTitle());
            deltaDB.Close();
        }
Exemplo n.º 12
0
        public KeePassFixture()
        {
            Logger = new KPCLibLogger();
            PwDb   = new PwDatabase();
            IOConnectionInfo ioc    = IOConnectionInfo.FromPath(TEST_DB);
            CompositeKey     cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(TEST_DB_KEY));
            PwDb.Open(ioc, cmpKey, Logger);
        }
Exemplo n.º 13
0
        public void ShouldExportImportedNodes()
        {
            var importDatabase = TestHelper.CreateDatabase();
            var importedEntry  = new PwEntry(true, true);

            importedEntry.SetTitle("ImportedEntry");
            var importedGroup = new PwGroup(true, true);

            importedGroup.Name = "ImportedGroup";
            importedGroup.AddEntry(importedEntry, true);
            importDatabase.RootGroup.AddGroup(importedGroup, true);

            var exportPath = GetTestPath();

            m_syncManager.AddExportPath(exportPath);
            var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX");

            m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrX.CreateProxyNode(), true);

            m_database.RootGroup.AddEntry(userMrX.CreateProxyNode(), true);
            var existingEntry = new PwEntry(true, true);

            existingEntry.SetTitle("ExistingEntry");
            m_database.RootGroup.AddEntry(existingEntry, true);
            m_treeManager.CorrectStructure();

            string exportFile = exportPath + SyncSource.FileNameFor(userMrX) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            Assert.AreEqual(0, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "ImportedEntry"));
            Assert.AreEqual(0, m_database.RootGroup.GetGroups(true).Count(g => g.Name == "ImportedGroup"));

            m_syncManager.Export();

            Assert.IsTrue(File.Exists(exportFile));

            var importer = new SyncImporterAccessor();

            importer.MergeInAccessor(m_database, importDatabase);

            Assert.AreEqual(1, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "ImportedEntry"));
            Assert.AreEqual(1, m_database.RootGroup.GetGroups(true).Count(g => g.Name == "ImportedGroup"));

            m_syncManager.Export();

            Assert.IsTrue(File.Exists(exportFile));

            var deltaDBUpdated = new PwDatabase();

            deltaDBUpdated.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            Assert.AreEqual(1, deltaDBUpdated.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "ImportedEntry"));
            Assert.AreEqual(1, deltaDBUpdated.RootGroup.GetGroups(true).Count(g => g.Name == "ImportedGroup"));
            deltaDBUpdated.Close();
        }
Exemplo n.º 14
0
        private void SyncDatabase(string databaseFilename)
        {
            var db = new PwDatabase();

            db.Open(IOConnectionInfo.FromPath(databaseFilename), this.host.Database.MasterKey, new NullStatusLogger());

            this.host.Database.MergeIn(db, PwMergeMethod.Synchronize);
            this.host.MainWindow.RefreshEntriesList();

            db.Close();
        }
        public static KeyValuePair <string, string> GetEntry(string entry, string databasefile, string keyfile)
        {
            /*
             * Assembly assembly = Assembly.LoadFrom(assemblyPath);
             * Type T = assembly.GetType("Company.Project.Classname");
             * Company.Project.Classname instance = (Company.Project.Classname)Activator.CreateInstance(T);
             */

            //Read string databasefile,string keyfile from config
            KeyValuePair <string, string> keyval = new KeyValuePair <string, string>("Username", null);

            DpiUtil.ConfigureProcess();        //needed?

            if (!KeePass.Program.CommonInit()) //check if in same dir as KeePass??
            {
                KeePass.Program.CommonTerminate();
                return(keyval);
            }

            IOConnectionInfo ioc = new IOConnectionInfo();

            ioc.Path         = databasefile;
            ioc.CredSaveMode = IOCredSaveMode.NoSave;

            CompositeKey cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpKeyFile(keyfile));

            if ((cmpKey == null) || (cmpKey.UserKeyCount == 0))
            {
                return(keyval);
            }

            PwDatabase pwDb = new PwDatabase();

            pwDb.Open(ioc, cmpKey, null);

            string password;

            //bool bNeedsSave;
            if (ReportingMod.GetEntryString(pwDb, entry, out password))
            {
                keyval = new KeyValuePair <string, string>("Username", password);
            }
            // if (bNeedsSave) pwDb.Save(null);


            pwDb.Close();


            return(keyval);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Checks whether the provided master key actually unlocks the database
        /// </summary>
        /// <param name="ioInfo">IOConnectionInfo that represents the database.</param>
        /// <param name="key">Master Key to check.</param>
        internal static bool CheckMasterKey(IOConnectionInfo ioinfo, CompositeKey key)
        {
            PwDatabase db = new PwDatabase();

            try
            {
                db.Open(ioinfo, key, null);
                bool isopen = db.IsOpen;
                db.Close();
                return(isopen);
            }
            catch (Exception) { return(false); }
        }
Exemplo n.º 17
0
        private static PwDatabase OpenTargetDatabase(string targetFilePath, CompositeKey key)
        {
            // Create a new database
            PwDatabase targetDatabase = new PwDatabase();

            // Connect the database object to the existing database
            targetDatabase.Open(new IOConnectionInfo()
            {
                Path = targetFilePath
            }, key, null);

            return(targetDatabase);
        }
Exemplo n.º 18
0
        public void ShouldExportToTargets()
        {
            //we change the password which is used to encrypt the delta container so we can later access the delta container
            //more easily.
            PwEntry mrX = TestHelper.GetUserRootNodeFor(m_database, 0);
            //the first autoExport only checks if there is a delta container allready and if not it will export one
            //in our case there should be no existing container so a new one will be created.
            var exportFolder = m_database.GetExportGroup();

            Assert.IsTrue(0 == exportFolder.Groups.UCount);
            string exportPath = GetTestPath();

            m_syncManager.AddExportPath(exportPath);
            var exportGroup = exportFolder.Groups.GetAt(0);

            exportGroup.AddEntry(mrX.CreateProxyNode(), true);

            string exportFile = exportPath + SyncSource.FileNameFor(mrX) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            m_syncManager.RefeshSourcesList();
            m_syncManager.Export();

            mrX = TestHelper.GetUserRootNodeFor(m_database, 0);
            Assert.AreEqual("mrX", mrX.Strings.ReadSafe(KeeShare.KeeShare.TitleField));

            Assert.IsTrue(File.Exists(exportFile));

            //now we open the creted delta container and verify the contend
            PwDatabase deltaDB = new PwDatabase();

            Assert.DoesNotThrow(delegate {
                deltaDB.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            });

            Assert.AreEqual(5, deltaDB.RootGroup.GetEntries(true).UCount);
            Assert.AreEqual(3, deltaDB.RootGroup.Entries.UCount);
            Assert.AreEqual("grp1", deltaDB.RootGroup.Groups.GetAt(0).Name);
            Assert.AreEqual(2, deltaDB.RootGroup.Groups.GetAt(0).Entries.UCount);
            //now we will test in detail if there are only the expected entries in the created delta container
            Assert.AreEqual(Uuid1, deltaDB.RootGroup.Entries.GetAt(0).Uuid);
            Assert.AreEqual(Uuid3, deltaDB.RootGroup.Entries.GetAt(2).Uuid);
            Assert.AreEqual(Uuid6, deltaDB.RootGroup.Entries.GetAt(1).Uuid);
            Assert.AreEqual(Uuid4, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(0).Uuid);
            Assert.AreEqual(Uuid5, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(1).Uuid);
            Assert.AreEqual("normalEntry1", deltaDB.RootGroup.Entries.GetAt(0).GetTitle());
            deltaDB.Close();
        }
Exemplo n.º 19
0
        public IKeePassService Open()
        {
            //TODO add support for composite database keys
            if (KeePassPasswordProvider.RetrievePassword() == null)
            {
                throw new ArgumentNullException("password", "Password provided by IKeePassPasswordValueProvider is not set. Please register Password before calling Open().");
            }

            var io           = IOConnectionInfo.FromPath(Configuration.Path);
            var masterpass   = new KcpPassword(KeePassPasswordProvider.RetrievePassword().ConvertToUnsecureString());
            var compositeKey = new CompositeKey();

            compositeKey.AddUserKey(masterpass);
            _database = new PwDatabase();
            _database.Open(io, compositeKey, new NullStatusLogger());
            return(this);
        }
Exemplo n.º 20
0
        public void CreateAndSaveLocal()
        {
            IKp2aApp         app = new TestKp2aApp();
            IOConnectionInfo ioc = new IOConnectionInfo {
                Path = DefaultFilename
            };

            File outputDir = new File(DefaultDirectory);

            outputDir.Mkdirs();
            File targetFile = new File(ioc.Path);

            if (targetFile.Exists())
            {
                targetFile.Delete();
            }

            bool createSuccesful = false;
            //create the task:
            CreateDb createDb = new CreateDb(app, Application.Context, ioc, new ActionOnFinish((success, message) =>
                                                                                               { createSuccesful = success;
                                                                                                 if (!success)
                                                                                                 {
                                                                                                     Android.Util.Log.Debug("KP2A_Test", message);
                                                                                                 }
                                                                                               }), false);

            //run it:

            createDb.Run();
            //check expectations:
            Assert.IsTrue(createSuccesful);
            Assert.IsNotNull(app.GetDb());
            Assert.IsNotNull(app.GetDb().KpDatabase);
            //the create task should create two groups:
            Assert.AreEqual(2, app.GetDb().KpDatabase.RootGroup.Groups.Count());

            //ensure the the database can be loaded from file:
            PwDatabase loadedDb = new PwDatabase();

            loadedDb.Open(ioc, new CompositeKey(), null, new KdbxDatabaseFormat(KdbxFormat.Default));

            //Check whether the databases are equal
            AssertDatabasesAreEqual(loadedDb, app.GetDb().KpDatabase);
        }
Exemplo n.º 21
0
        public void New_Test()
        {
            var db = CreateTestDatabase(out IOConnectionInfo ci,
                                        out CompositeKey key, out IFile file);
            var initialEnitiesCount = db.RootGroup.GetEntriesCount(true);

            Assert.AreNotEqual(0, initialEnitiesCount);
            db.Save(null);
            db.Close();

            Assert.IsNull(db.RootGroup);
            db = new PwDatabase();
            db.Open(ci, key, null);
            Assert.AreEqual(initialEnitiesCount,
                            db.RootGroup.GetEntriesCount(true));
            db.Close();
            file.DeleteAsync().Wait();
        }
Exemplo n.º 22
0
        public void Open_With_KeyFile_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile keyFile = testData.CreateFileAsync("1.key",
                                                     CreationCollisionOption.ReplaceExisting).Result;
            var fileStream = keyFile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
            var assembly   = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
            var stream     = assembly.GetManifestResourceStream(
                "KeePass2PCL.Test.UWP.TestData.1.key");

            using (var reader = new BinaryReader(stream))
                using (var fileWriter = new BinaryWriter(fileStream))
                {
                    fileWriter.Write(reader.ReadBytes((int)stream.Length));
                }

            IFile file = testData.CreateFileAsync("1key.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;

            fileStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
            assembly   = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
            stream     = assembly.GetManifestResourceStream(
                "KeePass2PCL.Test.UWP.TestData.1key.kdbx");
            using (var reader = new BinaryReader(stream))
                using (var fileWriter = new BinaryWriter(fileStream))
                {
                    fileWriter.Write(reader.ReadBytes((int)stream.Length));
                }

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpKeyFile(keyFile.Path));
            var db = new PwDatabase();

            db.Open(ci, key, null);
            keyFile.DeleteAsync().Wait();
            file.DeleteAsync().Wait();
            testData.DeleteAsync().Wait();
        }
Exemplo n.º 23
0
        public void ShouldHandleCyclesOfNodesInImportAndExport()
        {
            var exportPath = GetTestPath();

            m_syncManager.AddExportPath(exportPath);

            var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX");

            m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrX.CreateProxyNode(), true);

            var existingEntry = new PwEntry(true, true);

            existingEntry.SetTitle("Entry Version 1");
            m_database.RootGroup.AddEntry(existingEntry, true);
            m_database.RootGroup.AddEntry(userMrX.CreateProxyNode(), true);

            m_treeManager.CorrectStructure();

            string exportFile = exportPath + SyncSource.FileNameFor(userMrX) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            m_syncManager.Export();

            var deltaDBInitial = new PwDatabase();

            deltaDBInitial.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            Assert.AreEqual(1, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1"));
            foreach (var entry in deltaDBInitial.RootGroup.GetEntries(true))
            {
                entry.SetTitle("Changed");
            }
            deltaDBInitial.Save(null);
            deltaDBInitial.Close();

            m_syncManager.AddImportPath(exportFile);
            m_database.GetImportGroup().Groups.GetAt(0).Entries.GetAt(0).SetPassword(userMrX.Strings.ReadSafe(KeeShare.KeeShare.PasswordField));

            m_syncManager.RefeshSourcesList();
            // Node normalEntry6 is within the user home and is relocated on export which changes the parent node - during import, the parents of
            // not "officially" relocated nodes is checked and an assertion is thrown
            Assert.AreEqual(0, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Changed"));
        }
Exemplo n.º 24
0
        public async Task Open(byte[] file, Credentials credentials)
        {
            try
            {
                await Task.Run(() =>
                {
                    var compositeKey = CreateCompositeKey(credentials);
                    var ioConnection = IOConnectionInfo.FromByteArray(file);

                    _pwDatabase.Open(ioConnection, compositeKey, new NullStatusLogger());

                    _credentials = credentials;
                });
            }
            catch (InvalidCompositeKeyException ex)
            {
                throw new ArgumentException(ex.Message, ex);
            }
        }
        /// <summary>
        /// Loads configuration values from the source represented by this <see cref="T:Microsoft.Extensions.Configuration.IConfigurationProvider" />.
        /// </summary>
        public override void Load()
        {
            var database = new PwDatabase();

            database.Open(_configurationSource.Connection, _configurationSource.CompositeKey, null);

            var entries = _configurationSource.FilterEntries != null
                ? _configurationSource.FilterEntries(database)
                : database.RootGroup.GetEntries(true);

            var resolveKey = _configurationSource.ResolveKey ?? ((entry) =>
            {
                var keyPath = entry.ParentGroup.GetFullPath(":", true);
                var title = entry.Strings.ReadSafe("Title");
                var userName = entry.Strings.ReadSafe("UserName");
                return($"{keyPath}:{title}:{userName}");
            });

            var resolveValue = _configurationSource.ResolveValue ?? ((key, entry) =>
            {
                var value = entry.Strings.ReadSafe("Password");
                return(value == "Password" ? null : value);
            });

            foreach (var entry in entries)
            {
                var key   = resolveKey(entry);
                var value = resolveValue(key, entry);

                if (!Data.TryAdd(key, value))
                {
                    for (var i = 1; i < int.MaxValue; i++)
                    {
                        var incrementKey = $"{key}`{i}";
                        if (Data.TryAdd(incrementKey, value))
                        {
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 26
0
        public void ShouldNotImportDatabasesWithDifferentUsers()
        {
            var exportPath = GetTestPath();

            m_syncManager.AddExportPath(exportPath);

            var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX");
            var userMrY = TestHelper.GetUserRootNodeByNameFor(m_database, "mrY");

            m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrY.CreateProxyNode(), true);

            var existingEntry = new PwEntry(true, true);

            existingEntry.SetTitle("Entry Version 1");
            m_database.RootGroup.AddEntry(existingEntry, true);
            m_database.RootGroup.AddEntry(userMrY.CreateProxyNode(), true);

            m_treeManager.CorrectStructure();

            string exportFile = exportPath + SyncSource.FileNameFor(userMrY) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            m_syncManager.Export();

            existingEntry.SetTitle("Entry Version 2");

            var deltaDBInitial = new PwDatabase();

            deltaDBInitial.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            Assert.AreEqual(0, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 2"));
            Assert.AreEqual(1, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1"));
            deltaDBInitial.Close();

            m_syncManager.AddImportPath(exportFile);
            m_database.GetImportGroup().Groups.GetAt(0).Entries.GetAt(0).SetPassword("InvalidPassword");

            m_syncManager.RefeshSourcesList();

            Assert.AreEqual(1, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 2"));
            Assert.AreEqual(0, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1"));
        }
Exemplo n.º 27
0
        public void ShouldNotExportKeeShareNodes()
        {
            m_treeManager.Initialize(m_database);
            var exportPath = GetTestPath();

            m_syncManager.AddExportPath(exportPath);
            var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX");
            var userMrY = TestHelper.GetUserRootNodeByNameFor(m_database, "mrY");

            userMrY.SetPassword(STANDARD_PASSWORD);

            m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrY.CreateProxyNode(), true);

            m_database.RootGroup.AddEntry(userMrX.CreateProxyNode(), true);

            m_treeManager.CorrectStructure();

            m_database.GetUserHomeFor(userMrY).AddEntry(userMrX.CreateProxyNode(), true);
            m_database.GetUserHomeFor(userMrX).AddEntry(userMrY.CreateProxyNode(), true);

            string exportFile = exportPath + SyncSource.FileNameFor(userMrY) + SyncExporter.FileExtension;

            Assert.IsFalse(File.Exists(exportFile));

            m_syncManager.Export();

            TestHelper.DelayAction();

            Assert.IsTrue(File.Exists(exportFile));

            var deltaDBAdamReexport = new PwDatabase();

            deltaDBAdamReexport.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null);
            foreach (var entry in deltaDBAdamReexport.RootGroup.GetEntries(true))
            {
                Assert.AreNotEqual(userMrX.GetTitle(), entry.GetTitle());
            }
            foreach (var group in deltaDBAdamReexport.RootGroup.GetGroups(true))
            {
                Assert.AreNotEqual(userMrX.GetTitle(), group.Name);
            }
        }
Exemplo n.º 28
0
        private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc, CompositeKey cmpKey)
        {
            PerformSelfTest();

            //string strPathNrm = ioc.Path.Trim().ToLower();

            PwDatabase pwDb = new PwDatabase();

            try {
                pwDb.Open(ioc, cmpKey, null);
            }
            catch (Exception ex) {
                //MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex,
                //   (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));
                pwDb = null;
                throw;
            }

            return(pwDb);
        }
Exemplo n.º 29
0
        public void Open_With_Wrong_Password_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile file = testData.CreateFileAsync("1.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;
            var fileStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
            var assembly   = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
            var stream     = assembly.GetManifestResourceStream(
                "KeePass2PCL.Test.UWP.TestData.1.kdbx");

            using (var reader = new BinaryReader(stream))
                using (var fileWriter = new BinaryWriter(fileStream))
                {
                    fileWriter.Write(reader.ReadBytes((int)stream.Length));
                }

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword("0"));
            var  db           = new PwDatabase();
            bool wasException = false;

            try
            {
                db.Open(ci, key, null);
            }
            catch (InvalidCompositeKeyException)
            {
                wasException = true;
            }
            Assert.IsTrue(wasException);
            file.DeleteAsync().Wait();
            testData.DeleteAsync().Wait();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Opens a database.
        /// </summary>
        /// <param name="path">Path to the datebase.</param>
        /// <param name="password">Password of the database (optional).</param>
        /// <param name="keyPath">Keyfile for the database (optional).</param>
        /// <returns></returns>
        internal static PwDatabase OpenDatabase(string path, string password = null, string keyPath = null)
        {
            IOConnectionInfo ioConnInfo = new IOConnectionInfo {
                Path = path
            };
            CompositeKey compositeKey = new CompositeKey();

            if (password != null)
            {
                KeyHelper.AddPasswordToKey(password, compositeKey);
            }

            if (keyPath != null)
            {
                KeyHelper.AddKeyfileToKey(keyPath, compositeKey, ioConnInfo);
            }

            PwDatabase db = new PwDatabase();

            db.Open(ioConnInfo, compositeKey, new NullStatusLogger());
            return(db);
        }