Exemplo n.º 1
0
        /// <summary>
        /// Replace the current database file with a new file and open it
        /// </summary>
        /// <param name="downloadFilePath">Full path of the new database file</param>
        /// <returns>Status of the replacement</returns>
        private string replaceDatabase(string currentFilePath, string downloadFilePath)
        {
            string status       = string.Empty;
            string tempFilePath = currentFilePath + ".gsyncbak";

            KeePassLib.Keys.CompositeKey pwKey = m_host.Database.MasterKey;
            m_host.Database.Close();

            try
            {
                System.IO.File.Move(currentFilePath, tempFilePath);
                System.IO.File.Move(downloadFilePath, currentFilePath);
                System.IO.File.Delete(tempFilePath);
                status = "下载文件替换当前数据库 '" + System.IO.Path.GetFileName(currentFilePath) + "'";
            }
            catch (Exception)
            {
                status = "替换当前数据库失败,下载文件在 '" + System.IO.Path.GetFileName(downloadFilePath) + "'";
            }

            // try to open new (or old in case of error) db
            try
            {
                // try to open with current MasterKey ...
                m_host.Database.Open(IOConnectionInfo.FromPath(currentFilePath), pwKey, new NullStatusLogger());
            }
            catch (KeePassLib.Keys.InvalidCompositeKeyException)
            {
                // ... MasterKey is different, let user enter the MasterKey
                m_host.MainWindow.OpenDatabase(IOConnectionInfo.FromPath(currentFilePath), null, true);
            }

            return(status);
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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>());
            }
        }
Exemplo n.º 4
0
        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);
        }
Exemplo n.º 5
0
        /// <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);
        }
Exemplo n.º 6
0
        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>();
        	}
        }
Exemplo n.º 7
0
        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);
        }