/// Calculate time offset for all relevant entries /// Do NOT use Task.Run as this requires .NET 4.5 which will cause issues on Mono /// Mono reports .NET 4.0.3 being installed despite higher versions can be used /// This results in KeePass refusing to compile the plgx public static /*async*/ void GetTimingsAsync(KeePassLib.PwDatabase db) { //Don't use TraverseTree as db content might change during processing //and this will result in an exception since TraverseTree uses 'foreach' //Don't use Task at all (https://github.com/Rookiestyle/KeePassOTP/issues/31) KeePassLib.Delegates.GAction <object> act = new KeePassLib.Delegates.GAction <object>((object o) => { DateTime dtStart = DateTime.Now; IEnumerable <string> lURL = db.RootGroup.GetEntries(true). Where(e => OTPDAO.OTPDefined(e) != OTPDAO.OTPDefinition.None). //We're not interested in sites without OTP being set up Select(e => e.Strings.ReadSafe(KeePassLib.PwDefs.UrlField)).Distinct(); //We're not interested in duplicate URLs foreach (string url in lURL) { if (m_timeCorrectionUrls.ContainsKey(url)) { continue; } GetTimeCorrection(url); System.Threading.Thread.Sleep(100); } ; DateTime dtEnd = DateTime.Now; PluginDebug.AddInfo("Calculated OTP time corrections", 0, "Start: " + dtStart.ToLongTimeString(), "End: " + dtEnd.ToLongTimeString()); }); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(act)); }
/// Calculate time offset for all relevant entries /// Do NOT use Task.Run as this requires .NET 4.5 which will cause issues on Mono /// Mono reports .NET 4.0.3 being installed despite higher versions can be used /// This results in KeePass refusing to compile the plgx public static /*async*/ void GetTimingsAsync(KeePassLib.PwDatabase db) { //Don't use TraverseTree as db content might change during processing //and this will result in an exception since TraverseTree uses 'foreach' //await - Don't use, see comment above method definition System.Threading.Tasks.Task.Factory.StartNew(() => //System.Threading.Tasks.Task.Run(() => { DateTime dtStart = DateTime.Now; IEnumerable <string> lURL = db.RootGroup.GetEntries(true). Where(e => OTPDAO.OTPDefined(e) != OTPDAO.OTPDefinition.None). //We're not interested in sites without OTP being set up Select(e => e.Strings.ReadSafe(KeePassLib.PwDefs.UrlField)).Distinct(); //We're not interested in duplicate URLs foreach (string url in lURL) { if (m_timeCorrectionUrls.ContainsKey(url)) { continue; } GetTimeCorrection(url); System.Threading.Thread.Sleep(100); } ; DateTime dtEnd = DateTime.Now; PluginDebug.AddInfo("Calculated OTP time corrections", 0, "Start: " + dtStart.ToLongTimeString(), "End: " + dtEnd.ToLongTimeString()); } ); }
private static Exception CheckArgument(KeePassLib.PwDatabase database, Uri filePath, KeePassLib.Security.ProtectedString password) { if (ReferenceEquals(database, null)) { return(new ArgumentNullException("database")); } if (ReferenceEquals(filePath, null)) { return(new ArgumentNullException("filePath")); } if (!filePath.IsFile) { return(new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Path [{0}] is not a file", filePath.LocalPath), "filePath")); } if (!Path.GetExtension(filePath.LocalPath).Equals(KeePassDatabaseExtension, StringComparison.InvariantCultureIgnoreCase)) { return(new ArgumentException(string.Format(CultureInfo.InvariantCulture, "File [{0}] must be a KeePass database (*.{1})", filePath.LocalPath, KeePassDatabaseExtension), "filePath")); } if (ReferenceEquals(password, null) || password.IsEmpty) { return(new ArgumentNullException("password")); } return(null); }
public KeePassLib.PwGroup getGroup(string name) { KeePassLib.PwGroup group = new KeePassLib.PwGroup(); var ioconninfo = new KeePassLib.Serialization.IOConnectionInfo(); if (!(string.IsNullOrEmpty(KeepassDBFilePath))) { ioconninfo.Path = base64Decode(KeepassDBFilePath); KeePassLib.Keys.CompositeKey compkey = new KeePassLib.Keys.CompositeKey(); if (string.IsNullOrEmpty(KeepassKeyFilePath) && string.IsNullOrEmpty(KeepassMasterPassword)) { throw new Exception("A Key file or Master Password has not been set!"); } else { if (!(string.IsNullOrEmpty(KeepassKeyFilePath))) { compkey.AddUserKey(new KeePassLib.Keys.KcpKeyFile(base64Decode(KeepassKeyFilePath))); } if (!(string.IsNullOrEmpty(KeepassMasterPassword))) { compkey.AddUserKey(new KeePassLib.Keys.KcpPassword(base64Decode(KeepassMasterPassword))); } var db = new KeePassLib.PwDatabase(); try { db.Open(ioconninfo, compkey, null); KeePassLib.Collections.PwObjectList <KeePassLib.PwGroup> groups = db.RootGroup.GetGroups(true); group = groups.First(i => i.Name == name); } catch { throw; } finally { if (db.IsOpen) { db.Close(); db = null; } } } } else { throw new Exception("Keepass DB Path has not been set!"); } return(group); }
public ICollection <SecretEntryModel> ReadDatabase(string databasePath, string masterPassword) { _stringValidator.IsNullOrWhitespace(databasePath, nameof(databasePath)); _stringValidator.IsNullOrWhitespace(masterPassword, nameof(masterPassword)); _fileValidator.IsExist(databasePath); //How to read KeePass database taken from https://stackoverflow.com/a/9028433 var result = default(ICollection <SecretEntryModel>); var connection = new IOConnectionInfo { Path = databasePath }; var compositeKey = new CompositeKey(); var password = new KcpPassword(masterPassword); compositeKey.AddUserKey(password); var database = new KeePassLib.PwDatabase(); try { database.Open(connection, compositeKey, null); var readData = from entry in database.RootGroup.GetEntries(true) select new { Group = entry.ParentGroup.Name, Title = entry.Strings.ReadSafe("Title"), UserName = entry.Strings.ReadSafe("UserName"), Password = entry.Strings.ReadSafe("Password"), URL = entry.Strings.ReadSafe("URL"), Notes = entry.Strings.ReadSafe("Notes") }; result = readData.Select(data => new SecretEntryModel { Title = data.Title, UserName = data.UserName, Password = data.Password, }).ToList(); } catch (Exception exception) { Log.Logger.Error(exception, $"During reading KeePass database {databasePath} an error has been occured"); } finally { if (database.IsOpen) { database.Close(); } } return(result); }
private static List <CredentialSet> LoadKeePass() { try { var ioConnInfo = new KeePassLib.Serialization.IOConnectionInfo { Path = Main.Settings.Settings.KeePassPath }; var compKey = new KeePassLib.Keys.CompositeKey(); compKey.AddUserKey(new KeePassLib.Keys.KcpPassword(Main.Settings.Settings.KeePassPassword)); var db = new KeePassLib.PwDatabase(); db.Open(ioConnInfo, compKey, null); var entries = db.RootGroup.GetEntries(true); List <CredentialSet> list = new List <CredentialSet>(); foreach (var entry in entries) { string title = entry.Strings.ReadSafe("Title"); string userName = entry.Strings.ReadSafe("UserName"); string domain = entry.Strings.ReadSafe("Domain"); if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(userName)) { CredentialSet credentialSet = new CredentialSet { Name = title, Username = string.IsNullOrEmpty(domain) && userName.Contains("\\") ? userName.Split(new string[] { "\\" }, StringSplitOptions.None)[1] : userName, Domain = string.IsNullOrEmpty(domain) && userName.Contains("\\") ? userName.Split(new string[] { "\\" }, StringSplitOptions.None)[0] : domain, Password = entry.Strings.ReadSafe("Password") }; list.Add(credentialSet); string id = entry.Uuid.ToHexString(); if (!keyPassCredentialsById.ContainsKey(id)) { keyPassCredentialsById.Add(id, credentialSet); } } } db.Close(); return(list); } catch (Exception ex) { Log.Error("Error loading KeePass-File due to the following reason: " + ex.Message, ex); return(new List <CredentialSet>()); } }
public static string GetDBName(KeePassLib.PwEntry pe) { if (pe == null) { return(string.Empty); } KeePassLib.PwDatabase db = KeePass.Program.MainForm.DocumentManager.FindContainerOf(pe); if (db == null) { return(string.Empty); } if (!string.IsNullOrEmpty(db.Name)) { return(db.Name); } return(KeePassLib.Utility.UrlUtil.GetFileName(db.IOConnectionInfo.Path)); }
internal static List <object> FindWrapper(KeePassLib.PwDatabase db, IStatusLogger sl, out Action <ListView> fInit, FindInfo fi) { if (fi.Name == SearchExpired) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, true, 0, 0)); } else if (fi.Name == SearchExpired_1D) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 1, 0)); } else if (fi.Name == SearchExpired_2D) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 2, 0)); } else if (fi.Name == SearchExpired_3D) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 3, 0)); } else if (fi.Name == SearchExpired_7D) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 7, 0)); } else if (fi.Name == SearchExpired_14D) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 14, 0)); } else if (fi.Name == SearchExpired_1M) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 0, 1)); } else if (fi.Name == SearchExpired_2M) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, 0, 2)); } else if (fi.Name == SearchExpired_F) { return(SpecialSearches.SearchExpired.FindExpired(db, sl, out fInit, false, int.MaxValue, 0)); } List <object> l = null; fInit = null; return(l); }
public override void Import(KeePassLib.PwDatabase pwStorage, System.IO.Stream sInput, IStatusLogger slLogger) { if (pwStorage == null) { throw new ArgumentNullException("CardFileFormatProvider.Import(): null PwDatabase argument received"); } if (!pwStorage.IsOpen) { MessageBox.Show("You first need to open a database!", "CardFileFormatProvider"); return; } if (sInput == null) { throw new ArgumentNullException("CardFileFormatProvider.Import(): null Stream argument received"); } if (slLogger == null) { throw new ArgumentNullException("CardFileFormatProvider.Import(): null IStatusLogger argument received"); } if (!(sInput.CanRead)) { throw new ArgumentException("Input stream not readable"); } try { KPWriter kpWriter = new KPWriter(pwStorage); // The plugin's Keepass Writer CardFile crdfile = new CardFile(false, String.Empty, kpWriter); // The plugin's Importer, false = no logging slLogger.SetText("Importing Cardfile ...", LogStatusType.Info); crdfile.process(sInput); // read the cardfile & write to keepass m_Host.MainWindow.UpdateUI(false, null, true, m_Host.Database.RootGroup, true, null, true); slLogger.SetText("Importing Cardfile completed", LogStatusType.Info); } catch (ExnCardFileRdr ex) { reportError(ex.Message, "Warning", slLogger, LogStatusType.Warning); } catch (FileNotFoundException ex) { reportError(ex.Message, "Warning", slLogger, LogStatusType.Warning); } catch (DirectoryNotFoundException ex) { reportError(ex.Message, "Warning", slLogger, LogStatusType.Warning); } catch (Exception ex) { reportError(ex.ToString(), "Error", slLogger, LogStatusType.Error); } //try }
private static bool Export(KeePassLib.PwDatabase database, Uri filePath, KeePassLib.Security.ProtectedString password, KeePassLib.Interfaces.IStatusLogger logger) { Exception argumentError = CheckArgument(database, filePath, password); if (!ReferenceEquals(argumentError, null)) { throw argumentError; } if (string.Equals(database.IOConnectionInfo.Path, filePath.LocalPath, StringComparison.InvariantCultureIgnoreCase)) { return(false); //Don't export myself } //Create new database in temporary file KeePassLib.PwDatabase exportedDatabase = new KeePassLib.PwDatabase(); exportedDatabase.Compression = KeePassLib.PwCompressionAlgorithm.GZip; KeePassLib.Serialization.IOConnectionInfo connectionInfo = new KeePassLib.Serialization.IOConnectionInfo(); string storageDirectory = Path.GetDirectoryName(filePath.LocalPath); string tmpPath = Path.Combine(storageDirectory, string.Format("{0}{1}", Guid.NewGuid(), KeePassDatabaseExtension)); connectionInfo.Path = tmpPath; connectionInfo.CredSaveMode = KeePassLib.Serialization.IOCredSaveMode.SaveCred; KeePassLib.Keys.CompositeKey exportedKey = new KeePassLib.Keys.CompositeKey(); exportedKey.AddUserKey(new KeePassLib.Keys.KcpPassword(password.ReadString())); exportedDatabase.New(connectionInfo, exportedKey); exportedDatabase.RootGroup.Name = database.RootGroup.Name; //Merge current database in temporary file exportedDatabase.MergeIn(database, KeePassLib.PwMergeMethod.OverwriteExisting, logger); exportedDatabase.Save(logger); exportedDatabase.Close(); //Move temporary file into target backup path if (File.Exists(filePath.LocalPath)) { File.Delete(filePath.LocalPath); } File.Move(tmpPath, filePath.LocalPath); return(true); }
public static async void GetTimingsAsync(KeePassLib.PwDatabase db) { //Don't use TraverseTree as db content might change during processing //and this will result in an exception since TraverseTree uses 'foreach' await System.Threading.Tasks.Task.Run(() => { IEnumerable <string> lURL = db.RootGroup.GetEntries(true). Where(e => OTPDAO.OTPDefined(e) != OTPDAO.OTPDefinition.None). //We're not interested in sites without OTP being set up Select(e => e.Strings.ReadSafe(KeePassLib.PwDefs.UrlField)).Distinct(); //We're not interested in duplicate URLs foreach (string url in lURL) { if (m_timeCorrectionUrls.ContainsKey(url)) { continue; } GetTimeCorrection(url); System.Threading.Thread.Sleep(100); } ; } ); }
/// <summary> /// Retrieves a OneDrive Refresh Token from the provided KeePass database /// </summary> /// <param name="keePassDatabase">KeePass database instance to get the Refresh Token from</param> /// <returns>OneDrive Refresh Token if available or NULL if no Refresh Token found for the provided database</returns> public static string GetRefreshTokenFromKeePassDatabase(KeePassLib.PwDatabase keePassDatabase) { var refreshToken = keePassDatabase.CustomData.Get("KoenZomers.KeePass.OneDriveSync.RefreshToken"); return(refreshToken); }
/// <summary> /// Saves the provided OneDrive Refresh Token in the provided KeePass database /// </summary> /// <param name="keePassDatabase">KeePass database instance to store the Refresh Token in</param> /// <param name="refreshToken">The OneDrive Refresh Token to store securely in the KeePass database</param> public static void SaveRefreshTokenInKeePassDatabase(KeePassLib.PwDatabase keePassDatabase, string refreshToken) { keePassDatabase.CustomData.Set("KoenZomers.KeePass.OneDriveSync.RefreshToken", refreshToken); }
private static List<CredentialSet> LoadKeePass() { try { var ioConnInfo = new KeePassLib.Serialization.IOConnectionInfo { Path = Main.Settings.Settings.KeePassPath }; var compKey = new KeePassLib.Keys.CompositeKey(); compKey.AddUserKey(new KeePassLib.Keys.KcpPassword(Main.Settings.Settings.KeePassPassword)); var db = new KeePassLib.PwDatabase(); db.Open(ioConnInfo, compKey, null); var entries = db.RootGroup.GetEntries(true); List<CredentialSet> list = new List<CredentialSet>(); foreach (var entry in entries) { string title = entry.Strings.ReadSafe("Title"); string userName = entry.Strings.ReadSafe("UserName"); string domain = entry.Strings.ReadSafe("Domain"); if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(userName)) { list.Add(new CredentialSet { Name = title, Username = string.IsNullOrEmpty(domain) && userName.Contains("\\") ? userName.Split(new string[] {"\\"}, StringSplitOptions.None)[1] : userName, Domain = string.IsNullOrEmpty(domain) && userName.Contains("\\") ? userName.Split(new string[] {"\\"}, StringSplitOptions.None)[0] : domain, Password = entry.Strings.ReadSafe("Password") }); } } db.Close(); return list; } catch (Exception ex) { Log.Error("Error loading KeePass-File due to the following reason: " + ex.Message, ex); return new List<CredentialSet>(); } }
public string getData(string value, string kpColumn2Search = "Title", string kpColumn2Return = "Password") { string returnValue = string.Empty; var ioconninfo = new KeePassLib.Serialization.IOConnectionInfo(); if (!(string.IsNullOrEmpty(KeepassDBFilePath))) { ioconninfo.Path = base64Decode(KeepassDBFilePath); KeePassLib.Keys.CompositeKey compkey = new KeePassLib.Keys.CompositeKey(); if (string.IsNullOrEmpty(KeepassKeyFilePath) && string.IsNullOrEmpty(KeepassMasterPassword)) { throw new Exception("A Key file or Master Password has not been set!"); } else { if (!(string.IsNullOrEmpty(KeepassKeyFilePath))) { compkey.AddUserKey(new KeePassLib.Keys.KcpKeyFile(base64Decode(KeepassKeyFilePath))); } if (!(string.IsNullOrEmpty(KeepassMasterPassword))) { compkey.AddUserKey(new KeePassLib.Keys.KcpPassword(base64Decode(KeepassMasterPassword))); } var db = new KeePassLib.PwDatabase(); try { db.Open(ioconninfo, compkey, null); KeePassLib.Collections.PwObjectList <KeePassLib.PwEntry> entries = db.RootGroup.GetEntries(true); //var data = from entry in db.rootgroup.getentries(true) where entry.strings.readsafe("title") == "tyler-u-client-id" select entry; KeePassLib.PwEntry pw = entries.FirstOrDefault(i => i.Strings.ReadSafe(kpColumn2Search) == value); if (pw != null) { returnValue = pw.Strings.ReadSafe(kpColumn2Return); } else { returnValue = string.Empty; } pw = null; } catch { throw; } finally { if (db.IsOpen) { db.Close(); db = null; } } } } else { throw new Exception("Keepass DB Path has not been set!"); } return(returnValue); }
static void Main(string[] args) { /*Variables to track (in respective order) IP address, * location of the password db, location of Winbox, * and registry value to lookup*/ String address; string kpLocation; string wbLocation; string valueName = "KeePass Location"; var masterpw = ""; String username = ""; String password = ""; //Grab the file paths for password db and winbox RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\WinboxHelper"); kpLocation = (string)rk.GetValue(valueName); valueName = "Winbox Location"; wbLocation = (string)rk.GetValue(valueName); //If no args passed, program will exit if (args.Length < 1) { address = ""; Console.WriteLine("Args less than one."); Console.Read(); Environment.Exit(0); } else { //IP address must be the first argument passed. Everything else is ignored. address = args[0]; } //String manipulation for using web links if (address.ToLower().Contains("winboxhelper")) { address = address.Substring(13); } //Make new KeePass pwdb object and point it to the specified db var db = new KeePassLib.PwDatabase(); var dbpath = @kpLocation; //Retrieve master password from user and mask input while (true) { Console.Write("Enter Master PW: "); ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { masterpw += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && masterpw.Length > 0) { masterpw = masterpw.Substring(0, (masterpw.Length - 1)); Console.Write("\b \b"); } } } // Stops Receving Keys Once Enter is Pressed while (key.Key != ConsoleKey.Enter); Console.WriteLine(); //Connect to pwdb var ioConnInfo = new IOConnectionInfo { Path = dbpath }; var compKey = new CompositeKey(); compKey.AddUserKey(new KcpPassword(masterpw)); Console.WriteLine(); //IP address or gtfo if (address.Equals("") || address.Equals(null)) { Console.WriteLine("Must specify an IP address. Terminating."); Console.Read(); Environment.Exit(0); } //Pass composite key to db and try to open. If not, gently tell user they have the wrong password or have probably been fired. try { db.Open(ioConnInfo, compKey, new CoutLogger()); break; } catch (Exception) { Console.WriteLine("Invalid password or could not load the database. Please try again."); } } //Retrieve the KeePass entries. var kpdata = from entry in db.RootGroup.GetEntries(true) select new { //Grab all the KeePass entries Group = entry.ParentGroup.Name, Title = entry.Strings.ReadSafe("Title"), Username = entry.Strings.ReadSafe("UserName"), Password = entry.Strings.ReadSafe("Password"), URL = entry.Strings.ReadSafe("URL"), Notes = entry.Strings.ReadSafe("Notes") }; //Search the KeePass entries for the IP address foreach (Object anon in kpdata) { String[] s; s = anon.ToString().Split(new Char[] { ',' }); for (int i = 0; i < s.Length; i++) { if (s[i].Contains(address)) { /*Username is the 3rd element of the KeePass entry returned * and has some leading text that we're not interested in.*/ username = s[2].Substring(12); /*Password is the 4th element of the KeePass entry returned * and also has some leading text that we're not interested in.*/ password = s[3].Substring(12); } } } //If no matching entry was found, exit the program. if (password.Equals("") || password.Equals(null)) { Console.WriteLine("No matching record found. Terminating."); Console.ReadLine(); db.Close(); Environment.Exit(0); } //Otherwise, open Winbox with the discovered parameters ProcessStartInfo start = new ProcessStartInfo(); String winbox; //Enter in the command line arguments winbox = address + " " + username + " " + password; start.Arguments = winbox; //Enter the executable to run start.FileName = wbLocation; start.WindowStyle = ProcessWindowStyle.Hidden; start.CreateNoWindow = true; //Run the external process & wait for it to finish using (Process proc = Process.Start(start)) { /*Insert hide window here if you don't want to stare * at a command prompt while you're working in winbox.*/ proc.WaitForExit(); } // Make sure to release the file db.Close(); }