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>()); } }
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); }
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(); }