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)); }
private void SyncLocal(PwDatabase pwDatabase, SafeVaultWebClient webClient, string databaseUuid, SafeVaultConf vaultConf) { SetStatusText("Check changes..."); var value = GetRemoteLastModified(webClient, databaseUuid); if (value == null) { SetStatusText("Database not found on SafeVault. Nothing to sync"); return; } var lastModified = value.Value; if (vaultConf.SyncRemoteLastModified == lastModified.ToString("u")) { SetStatusText("No changes"); return; } SetStatusText("Downloading..."); var dbData = Async.Invoke(() => DownloadFile(webClient, databaseUuid, vaultConf)); SetStatusText("Sync..."); SyncDatabase(pwDatabase, dbData, false); SetStatusText("Successfull Sync Local <= Remote"); vaultConf.SyncRemoteLastModified = lastModified.ToString("u"); vaultConf.Save(); pwDatabase.Save(new NullStatusLogger()); }
/// <summary> /// Exports all entries with the given tag to a new database at the given path. /// </summary> /// <param name="sourceDb">The source database.</param> /// <param name="settings">The settings for this job.</param> private static void SyncToDb(PwDatabase sourceDb, Settings settings) { // Create a key for the target database CompositeKey key = null; if (inSlave) { key = MasterKey; } else { key = CreateCompositeKey(settings.Password, settings.KeyFilePath); } // Create or open the target database PwDatabase targetDatabase = OpenTargetDatabase(settings.TargetFilePath, key); // Assign the properties of the source root group to the target root group HandleCustomIcon(targetDatabase, sourceDb, sourceDb.RootGroup); // Find all entries matching the tag and/or group PwObjectList <PwEntry> entries = GetMatching(sourceDb, settings); // Copy all entries to the new database CopyEntriesAndGroups(sourceDb, settings, entries, targetDatabase); //Delete slave entries that match Master settings (But not in master) PwObjectList <PwEntry> targetList = GetMatching(targetDatabase, settings); SelectEntriesAndDelete(entries, targetList, targetDatabase); // Save all changes to the DB sourceDb.Save(new NullStatusLogger()); targetDatabase.Save(new NullStatusLogger()); }
private static void SaveTargetDatabase(Settings settings, PwDatabase targetDatabase) { if (!settings.OverrideTargetDatabase && File.Exists(settings.TargetFilePath)) { // Save changes to existing target database targetDatabase.Save(new NullStatusLogger()); } else { // Create target folder (if not exist) string targetFolder = Path.GetDirectoryName(settings.TargetFilePath); if (targetFolder == null) { throw new ArgumentException("Can't get target folder."); } Directory.CreateDirectory(targetFolder); // Save the new database under the target path KdbxFile kdbx = new KdbxFile(targetDatabase); using (FileStream outputStream = new FileStream(settings.TargetFilePath, FileMode.Create)) { kdbx.Save(outputStream, null, KdbxFormat.Default, new NullStatusLogger()); } } }
public async Task <byte[]> SaveDatabase() { return(await Task.Run(() => { _pwDatabase.Save(new NullStatusLogger()); return _pwDatabase.IOConnectionInfo.Bytes; })); }
public void AddEntry(KeePassEntry entry) { var addEntry = new PwEntry(true, true); addEntry.Strings.Set("Title", new KeePassLib.Security.ProtectedString(true, entry.Title)); addEntry.Strings.Set("UserName", new KeePassLib.Security.ProtectedString(true, entry.Username)); addEntry.Strings.Set("Password", new KeePassLib.Security.ProtectedString(true, entry.Password)); if (!string.IsNullOrEmpty(entry.URL)) { addEntry.Strings.Set("URL", new KeePassLib.Security.ProtectedString(true, entry.URL)); } if (!string.IsNullOrEmpty(entry.Notes)) { addEntry.Strings.Set("Notes", new KeePassLib.Security.ProtectedString(true, entry.Notes)); } var group = _db.RootGroup.FindCreateGroup(entry.Group, true); group.AddEntry(addEntry, true); _db.Save(null); }
public bool UIFileSave(bool bForceSave) { if (m_db == null) { return(true); } try { m_db.Save(null); } catch (Exception) { return(false); } return(true); }
private void SaveCustomData() { string serializedProviders = string.Empty; foreach (OpenIdProvider provider in providers) { serializedProviders += string.Format("{0}|", JsonConvert.SerializeObject(provider)); } dbPwDatabase.CustomData.Set("OpenIdProviders", serializedProviders); dbPwDatabase.Save(null); }
public void SaveDatabase() { if (db == null) { return; } if (!db.IsOpen) { return; } db.Save(new DefaultKeePassLogger()); }
/// <summary> /// Called everytime a database is opened. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void FileOpenedHandler(object sender, FileOpenedEventArgs e) { database = e.Database; var ioInfo = database.IOConnectionInfo; // Global settings to be used in the Options Panel dbName = Library.CharChange(ioInfo.Path); UWPLibrary.ck = database.MasterKey; enablePlugin = database.CustomData.Get(ProductName) == "true" || database.CustomData.Get(ProductName) == null; LockAfterAutoType = database.CustomData.Get(ProductName + "AT") == "true"; if (!enablePlugin) // if plugin is explicitely disabled for the database { return; // Don't do anything else } if (await UWPLibrary.IsHelloAvailable() && await UWPLibrary.FirstTime(dbName)) // If the database has no credentials saved { // Ask the user if he/she wants to configure the plugin bool yesOrNo = MessageService.AskYesNo("Do You want to set " + WinHelloUnlockExt.ProductName + " for " + dbName + " now?", WinHelloUnlockExt.ShortProductName, true); // In case he/she wants, create the credentials if (yesOrNo) { await UWPLibrary.CreateHelloData(dbName); // Create CustomData to save global setting to enable the plugin database.CustomData.Set(ProductName, "true"); } else { // Create CustomData to save global setting to disable the plugin database.CustomData.Set(ProductName, "false"); enablePlugin = false; } database.Modified = true; // Try to save the database try { database.Save(null); } catch { } } // Set global settings back to default tries = 0; opened = true; }
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")); }
private void SyncDownload(PwDatabase pwDatabase, YandexWebDavClient webClient, string filename, YandexDiscSyncConf storageConf) { var lastModified = GetRemoteLastModified(filename, webClient); if (lastModified != null) { SetStatusText("Downloading..."); var dbData = Async.Invoke(() => DownloadFile(filename, webClient)); ReplaceDatabase(pwDatabase, dbData); SetStatusText("Download Done."); storageConf.ChangeDatabase(_host.Database); storageConf.SyncRemoteLastModified = lastModified.Value.ToString("u"); storageConf.Save(); pwDatabase.Save(new NullStatusLogger()); } else { SetStatusText("Database not found. Nothing to sync"); } }
private void SyncRemote(PwDatabase pwDatabase, SafeVaultWebClient webClient, string databaseUuid, SafeVaultConf vaultConf) { SetStatusText("Check changes..."); var localLastModified = GetLastModified(pwDatabase); var lastModified = GetRemoteLastModified(webClient, databaseUuid); if (lastModified != null && lastModified == localLastModified) { SetStatusText("No changes."); return; } if (lastModified != null && lastModified.Value.ToString("u") != vaultConf.SyncRemoteLastModified) { SetStatusText("Downloading..."); var dbData = Async.Invoke(() => DownloadFile(webClient, databaseUuid, vaultConf)); if (dbData != null) { SetStatusText("Sync..."); SyncDatabase(pwDatabase, dbData, true); _host.MainWindow.Enabled = false; localLastModified = GetLastModified(pwDatabase); } } SetStatusText("Saving to SafeVault..."); Async.Invoke(() => { webClient.DbxUpload( databaseUuid, File.ReadAllBytes(pwDatabase.IOConnectionInfo.Path), localLastModified); }); SetStatusText("Successfull Sync Local <=> Remote"); vaultConf.SyncRemoteLastModified = localLastModified.ToString("u"); vaultConf.Save(); pwDatabase.Save(new NullStatusLogger()); }
/// <summary> /// Sync YandexDisc with currently open Database file /// </summary> /// <returns>Return status of the update</returns> private void SyncDatabase(PwDatabase pwDatabase, byte[] dbData, bool forceSave) { CreateBackup(pwDatabase); var location = pwDatabase.IOConnectionInfo.Path; var tmpFile = location + ".sync.tmp"; try { System.IO.File.WriteAllBytes(tmpFile, dbData); IOConnectionInfo connection = IOConnectionInfo.FromPath(tmpFile); bool?success = ImportUtil.Synchronize(pwDatabase, _host.MainWindow, connection, false, _host.MainWindow); if (!success.HasValue) { throw new SynchronizeException( "Synchronization failed.\n\nYou do not have permission to import. Adjust your KeePass configuration."); } if (!(bool)success) { throw new SynchronizeException("Synchronization failed.\n\n" + "If the error was that master keys (passwords) do not match, use Upload / Download commands instead of Sync " + "or change the local master key to match that of the remote database."); } pwDatabase.Save(new NullStatusLogger()); var mostRecentUsed = _host.MainWindow.FileMruList; mostRecentUsed.RemoveItem(tmpFile); } finally { if (System.IO.File.Exists(tmpFile)) { System.IO.File.Delete(tmpFile); } } }
private void SyncRemote(PwDatabase pwDatabase, YandexWebDavClient webClient, string filename, YandexDiscSyncConf vaultConf) { SetStatusText("Check changes..."); var localLastModified = GetLastModified(pwDatabase); var lastModified = GetRemoteLastModified(filename, webClient); if (lastModified != null && lastModified == localLastModified) { SetStatusText("No changes."); return; } if (lastModified != null) { SetStatusText("Downloading..."); var dbData = Async.Invoke(() => DownloadFile(filename, webClient)); if (dbData != null) { SetStatusText("Sync..."); SyncDatabase(pwDatabase, dbData, true); _host.MainWindow.Enabled = false; localLastModified = GetLastModified(pwDatabase); } } SetStatusText("Saving to YandexDisc..."); Async.Invoke(() => { webClient.PutFile( filename, File.ReadAllBytes(pwDatabase.IOConnectionInfo.Path), localLastModified, progress => { SetStatusText($"Saving to YandexDisc ({Math.Floor(progress)}%)"); }); }); SetStatusText("Successfull Sync Local <=> Remote"); vaultConf.SyncRemoteLastModified = localLastModified.ToString("u"); vaultConf.Save(); pwDatabase.Save(new NullStatusLogger()); }
private void SyncDownload(PwDatabase pwDatabase, SafeVaultWebClient webClient, string databaseUuid, SafeVaultConf vaultConf) { var lastModified = GetRemoteLastModified(webClient, databaseUuid); if (lastModified != null) { SetStatusText("Downloading..."); var dbData = Async.Invoke(() => DownloadFile(webClient, databaseUuid, vaultConf)); ReplaceDatabase(pwDatabase, dbData); SetStatusText("Download Done."); vaultConf.ChangeDatabase(_host.Database); vaultConf.SyncRemoteLastModified = lastModified.Value.ToString("u"); vaultConf.Save(); pwDatabase.Save(new NullStatusLogger()); } else { SetStatusText("Database not found. Nothing to sync"); } }
public KeePassApi(IConfiguration config) { var dbpath = config.GetValue <string>("KeePassFile"); var masterpw = config.GetValue <string>("KeePassword"); var ioConnInfo = new IOConnectionInfo { Path = dbpath }; var compKey = new CompositeKey(); compKey.AddUserKey(new KcpPassword(masterpw)); if (!File.Exists(dbpath)) { var newDb = new PwDatabase(); newDb.New(ioConnInfo, compKey); newDb.Save(null); newDb.Close(); } _db = new PwDatabase(); _db.Open(ioConnInfo, compKey, null); }
public void Save(PwDatabase kpDatabase, Stream stream) { kpDatabase.Save(stream, null); }
/// <summary> /// Called when [file new]. /// </summary> /// <remarks>Review whenever private KeePass.MainForm.OnFileNew method changes. Last reviewed 20180416</remarks> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> internal void CreateNewDatabase() { if (!AppPolicy.Try(AppPolicyId.SaveFile)) { return; } DialogResult dr; string strPath; using (SaveFileDialog sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase, KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter( AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1, AppDefs.FileExtension.FileExt, false)) { GlobalWindowManager.AddDialog(sfd); dr = sfd.ShowDialog(_host.MainWindow); GlobalWindowManager.RemoveDialog(sfd); strPath = sfd.FileName; } if (dr != DialogResult.OK) { return; } KeePassLib.Keys.CompositeKey key = null; bool showUsualKeePassKeyCreationDialog = false; using (KeyCreationSimpleForm kcsf = new KeyCreationSimpleForm()) { // Don't show the simple key creation form if the user has set // security policies that restrict the allowable composite key sources if (KeePass.Program.Config.UI.KeyCreationFlags == 0) { kcsf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true); dr = kcsf.ShowDialog(_host.MainWindow); if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort)) { return; } if (dr == DialogResult.No) { showUsualKeePassKeyCreationDialog = true; } else { key = kcsf.CompositeKey; } } else { showUsualKeePassKeyCreationDialog = true; } if (showUsualKeePassKeyCreationDialog) { using (KeyCreationForm kcf = new KeyCreationForm()) { kcf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true); dr = kcf.ShowDialog(_host.MainWindow); if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort)) { return; } key = kcf.CompositeKey; } } PwDocument dsPrevActive = _host.MainWindow.DocumentManager.ActiveDocument; PwDatabase pd = _host.MainWindow.DocumentManager.CreateNewDocument(true).Database; pd.New(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), key); if (!string.IsNullOrEmpty(kcsf.DatabaseName)) { pd.Name = kcsf.DatabaseName; pd.NameChanged = DateTime.Now; } InsertStandardKeePassData(pd); var conf = pd.GetKPRPCConfig(); pd.SetKPRPCConfig(conf); // save the new database & update UI appearance pd.Save(_host.MainWindow.CreateStatusBarLogger()); } _host.MainWindow.UpdateUI(true, null, true, null, true, null, false); }
private static void RunScriptLine(CommandLineArgs args) { string strCommand = args[ParamCommand]; if (strCommand == null) { throw new InvalidOperationException(KSRes.NoCommand); } if (args.FileName == null) { RunSingleCommand(strCommand.ToLower()); return; } IOConnectionInfo ioc = new IOConnectionInfo(); ioc.Url = args.FileName; ioc.CredSaveMode = IOCredSaveMode.NoSave; CompositeKey cmpKey = null; if (args[ParamGuiKey] != null) { EnsureGuiInitialized(); KeyPromptForm kpf = new KeyPromptForm(); kpf.InitEx(ioc.GetDisplayName(), false); if (kpf.ShowDialog() != DialogResult.OK) { return; } cmpKey = kpf.CompositeKey; } else if (args[ParamConsoleKey] != null) { cmpKey = new CompositeKey(); Console.WriteLine(KSRes.NoKeyPartHint); Console.WriteLine(); Console.WriteLine(KSRes.KeyPrompt); Console.Write(KSRes.PasswordPrompt + " "); string strPw = Console.ReadLine().Trim(); if ((strPw != null) && (strPw.Length > 0)) { cmpKey.AddUserKey(new KcpPassword(strPw)); } Console.Write(KSRes.KeyFilePrompt + " "); string strFile = Console.ReadLine().Trim(); if ((strFile != null) && (strFile.Length > 0)) { cmpKey.AddUserKey(new KcpKeyFile(strFile)); } Console.Write(KSRes.UserAccountPrompt + " "); string strUA = Console.ReadLine().Trim(); if (strUA != null) { string strUal = strUA.ToLower(); if ((strUal == "y") || (strUal == "j") || (strUal == "o") || (strUal == "a") || (strUal == "u")) { cmpKey.AddUserKey(new KcpUserAccount()); } } } else { cmpKey = KeyFromCmdLine(args); } PwDatabase pwDb = new PwDatabase(); pwDb.Open(ioc, cmpKey, null); bool bNeedsSave; RunFileCommand(strCommand.ToLower(), args, pwDb, out bNeedsSave); if (bNeedsSave) { pwDb.Save(null); } pwDb.Close(); }
private static IDictionary <string, ProtectedString> OpenKeePassDB(SecureString Password) { PwDatabase PwDB = new PwDatabase(); IOConnectionInfo mioInfo = new IOConnectionInfo { Path = pathToKeePassDb }; CompositeKey compositeKey = new CompositeKey(); compositeKey.AddUserKey(new KcpPassword(Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(Password)))); IStatusLogger statusLogger = new NullStatusLogger(); Dictionary <string, ProtectedString> dict = new Dictionary <string, ProtectedString>(); try { PwDB.Open(mioInfo, compositeKey, statusLogger); PwObjectList <PwGroup> groups = PwDB.RootGroup.GetGroups(true); if (workingMode == WorkingModes.Prepare) { // Check whether the requested group already exists if (!groups.Any(x => x.Name.Equals(groupName))) { PwDB.RootGroup.AddGroup(new PwGroup() { Name = groupName }, true); Trace.TraceInformation($"The Group {groupName} has been added to KeePass DB"); } PwGroup grp = PwDB.RootGroup.GetGroups(true).Where(x => x.Name.Equals(groupName)).First(); // Check if the required entry doesn't exist in the group if (!grp.GetEntries(false).Any(x => x.Strings.ReadSafe("Title").Equals(entryName))) { //Need to have a local variable for Protected dic //otherwise the clause becomes too complecated for reading ProtectedStringDictionary d = new ProtectedStringDictionary(); d.Set("Title", new ProtectedString(true, entryName)); #pragma warning disable CS0618 // Type or member is obsolete //They tell it is obsolete and recommend to use any other constructor, //but, actually, there's no other to be used. grp.AddEntry(new PwEntry(grp, true, true) { Strings = d }, true); #pragma warning restore CS0618 // Type or member is obsolete Trace.TraceInformation($"The Entry {entryName} has been added to KeePass DB"); } PwEntry ent = grp.GetEntries(false).Where(x => x.Strings.ReadSafe("Title").Equals(entryName)).First(); //Create a value for password ProtectedString aesPwd = new ProtectedString(); PwGenerator.Generate(out aesPwd, new PwProfile() { Length = 16, CharSet = new PwCharSet(PwCharSet.LowerCase + PwCharSet.UpperCase + PwCharSet.Digits + PwCharSet.PrintableAsciiSpecial) }, UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(16)), new CustomPwGeneratorPool()); //Create a vlaue for Salt ProtectedString salt = new ProtectedString(); PwGenerator.Generate(out salt, new PwProfile() { Length = 26, CharSet = new PwCharSet(PwCharSet.LowerCase + PwCharSet.UpperCase + PwCharSet.Digits + PwCharSet.PrintableAsciiSpecial) }, UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(28)), new CustomPwGeneratorPool()); ent.Strings.Set("AESpassword", new ProtectedString(true, aesPwd.ReadString())); Trace.TraceInformation($"The value of the AESPass in the Entry {entryName} has been added to KeePass DB"); ent.Strings.Set("Salt", new ProtectedString(true, salt.ReadString())); Trace.TraceInformation($"The value of the Salt in the Entry {entryName} has been added to KeePass DB"); // Create IV SymmetricAlgorithm cipher = SymmetricAlgorithm.Create("AesManaged"); cipher.Mode = CipherMode.CBC; cipher.Padding = PaddingMode.PKCS7; ent.Strings.Set("IV", new ProtectedString(true, Convert.ToBase64String(cipher.IV))); Trace.TraceInformation($"The value of the IV in the Entry {entryName} has been added to KeePass DB"); PwDB.Save(statusLogger); // Add dummy values to the dictionary to pass the check in the end of the method dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt"))); dict.Add("Password", new ProtectedString(true, "dummy")); dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword"))); dict.Add("UserName", new ProtectedString(true, "dummy")); dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV"))); dict.Add("SecurityToken", new ProtectedString(true, "dummy")); } else { foreach (PwGroup grp in groups) { if (grp.Name.Equals(groupName)) { PwObjectList <PwEntry> entries = grp.GetEntries(false); foreach (PwEntry ent in entries) { if (ent.Strings.ReadSafe("Title").Equals(entryName)) { dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt"))); dict.Add("Password", new ProtectedString(true, ent.Strings.ReadSafe("Password"))); dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword"))); dict.Add("UserName", new ProtectedString(true, ent.Strings.ReadSafe("UserName"))); dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV"))); dict.Add("SecurityToken", new ProtectedString(true, ent.Strings.ReadSafe("SecurityToken"))); } } } } } } catch (Exception ex) { Trace.TraceError($"Failed to open KeePassDb \n{ex.Message}"); } finally { PwDB.Close(); } //Delete key-value pairs where values are empty dict.Where(d => d.Value.IsEmpty).ToList().ForEach(t => dict.Remove(t.Key)); return(dict); }