public static CompositeKey KeyFromCommandLine(CommandLineArgs args) { if(args == null) throw new ArgumentNullException("args"); CompositeKey cmpKey = new CompositeKey(); string strPassword = args[AppDefs.CommandLineOptions.Password]; string strKeyFile = args[AppDefs.CommandLineOptions.KeyFile]; string strUserAcc = args[AppDefs.CommandLineOptions.UserAccount]; if(strPassword != null) cmpKey.AddUserKey(new KcpPassword(strPassword)); if(strKeyFile != null) { try { cmpKey.AddUserKey(new KcpKeyFile(strKeyFile)); } catch(Exception exKey) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKey); return null; } } if(strUserAcc != null) { try { cmpKey.AddUserKey(new KcpUserAccount()); } catch(Exception exUA) { MessageService.ShowWarning(exUA); return null; } } return ((cmpKey.UserKeyCount > 0) ? cmpKey : null); }
public static void Main(string[] args) { CompositeKey key = new CompositeKey(); KcpPassword pw = new KcpPassword("12345"); key.AddUserKey(pw); byte[] pwdata = pw.KeyData.ReadData(); Console.WriteLine("PW data:"); Console.WriteLine(string.Join(",", pwdata.Select(x => "0x" + x.ToString("x")))); byte[] keydata = key.GenerateKey32(pwdata, 6000).ReadData(); Console.WriteLine("Key data:"); Console.WriteLine(string.Join(",", keydata.Select(x => "0x" + x.ToString("x")))); PwDatabase db = new PwDatabase(); db.MasterKey = key; KdbxFile kdbx = new KdbxFile(db); kdbx.Load(@"..\resources\test.kdbx", KdbxFormat.Default, null); var groups = db.RootGroup.GetGroups(true); Console.WriteLine("Group count: " + groups.UCount); var entries = db.RootGroup.GetEntries(true); Console.WriteLine("Entry count: " + entries.UCount); CompositeKey key2 = new CompositeKey(); key2.AddUserKey(pw); KcpKeyFile keyfile = new KcpKeyFile(@"..\resources\keyfile.key"); key2.AddUserKey(keyfile); byte[] keyfiledata = keyfile.KeyData.ReadData(); Console.WriteLine("Key file data:"); Console.WriteLine(string.Join(",", keyfiledata.Select(x => "0x" + x.ToString("x")))); Console.WriteLine("Composite Key data:"); byte[] key2data = key2.GenerateKey32(keyfiledata, 6000).ReadData(); Console.WriteLine(string.Join(",", key2data.Select(x => "0x" + x.ToString("x")))); }
protected static CompositeKey CreateKey(string password, string keyfile) { CompositeKey key = new CompositeKey(); key.AddUserKey(new KcpPassword(password)); if (!String.IsNullOrEmpty(keyfile)) key.AddUserKey(new KcpKeyFile(keyfile)); return key; }
public CreateDb(IKp2aApp app, Context ctx, IOConnectionInfo ioc, OnFinish finish, bool dontSave, CompositeKey key) : base(finish) { _ctx = ctx; _ioc = ioc; _dontSave = dontSave; _app = app; _key = key; }
public LoadDb(IKp2aApp app, IOConnectionInfo ioc, Task<MemoryStream> databaseData, CompositeKey compositeKey, String keyfileOrProvider, OnFinish finish) : base(finish) { _app = app; _ioc = ioc; _databaseData = databaseData; _compositeKey = compositeKey; _keyfileOrProvider = keyfileOrProvider; _rememberKeyfile = app.GetBooleanPreference(PreferenceKey.remember_keyfile); }
public bool EqualsValue(CompositeKey ckOther) { if (ckOther == null) { throw new ArgumentNullException("ckOther"); } byte[] pbThis = CreateRawCompositeKey32(); byte[] pbOther = ckOther.CreateRawCompositeKey32(); bool bResult = MemUtil.ArraysEqual(pbThis, pbOther); MemUtil.ZeroByteArray(pbOther); MemUtil.ZeroByteArray(pbThis); return(bResult); }
public bool EqualsValue(CompositeKey ckOther) { if (ckOther == null) { throw new ArgumentNullException("ckOther"); } bool bEqual; byte[] pbThis = CreateRawCompositeKey32(); try { byte[] pbOther = ckOther.CreateRawCompositeKey32(); bEqual = MemUtil.ArraysEqual(pbThis, pbOther); MemUtil.ZeroByteArray(pbOther); } finally { MemUtil.ZeroByteArray(pbThis); } return(bEqual); }
public static PwDatabase CreateKeePassDatabase(string databasePath, CompositeKey compositeKey) { if (!databasePath.EndsWith(".kdbx")) throw new FileNotFoundException("The database file must end with .kdbx"); var directoryName = Path.GetDirectoryName(databasePath); var fileName = Path.GetFileName(databasePath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); var ioc = new IOConnectionInfo(); ioc.Path = fileName; ioc.CredSaveMode = IOCredSaveMode.NoSave; var database = new PwDatabase(); database.New(ioc, compositeKey); database.Save(null); return database; }
public static CompositeKey CreateCompositeKey(string keyPassword = null, string keyFile = null, bool userAccount = false) { var emptyPassword = string.IsNullOrWhiteSpace(keyPassword); var emptyKeyFile = string.IsNullOrWhiteSpace(keyFile); if(emptyPassword && emptyKeyFile && !userAccount) throw new ArgumentException("KeyPass requires at least one form of authentication: Password, KeyFile, or UserAccount"); var key = new CompositeKey(); if (!emptyPassword) key.AddUserKey(new KcpPassword(keyPassword)); if (!emptyKeyFile) key.AddUserKey(new KcpKeyFile(keyFile)); if (userAccount) key.AddUserKey(new KcpUserAccount()); return key; }
public override void Run() { StatusLogger.UpdateMessage(UiStringKey.progress_create); Database db = _app.CreateNewDatabase(); db.KpDatabase = new KeePassLib.PwDatabase(); if (_key == null) { _key = new CompositeKey(); //use a temporary key which should be changed after creation } db.KpDatabase.New(_ioc, _key); db.KpDatabase.KeyEncryptionRounds = DefaultEncryptionRounds; db.KpDatabase.Name = "Keepass2Android Password Database"; //re-set the name of the root group because the PwDatabase uses UrlUtil which is not appropriate for all file storages: db.KpDatabase.RootGroup.Name = _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc); // Set Database state db.Root = db.KpDatabase.RootGroup; db.Loaded = true; db.SearchHelper = new SearchDbHelper(_app); // Add a couple default groups AddGroup internet = AddGroup.GetInstance(_ctx, _app, "Internet", 1, db.KpDatabase.RootGroup, null, true); internet.Run(); AddGroup email = AddGroup.GetInstance(_ctx, _app, "eMail", 19, db.KpDatabase.RootGroup, null, true); email.Run(); // Commit changes SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, _dontSave); save.SetStatusLogger(StatusLogger); _onFinishToRun = null; save.Run(); }
private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc, CompositeKey cmpKey, out bool bAbort) { bAbort = false; PerformSelfTest(); ShowWarningsLogger swLogger = CreateShowWarningsLogger(); swLogger.StartLogging(KPRes.OpeningDatabase, true); PwDocument ds = null; string strPathNrm = ioc.Path.Trim().ToLower(); for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan) { if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm) ds = m_docMgr.Documents[iScan]; else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm) ds = m_docMgr.Documents[iScan]; } PwDatabase pwDb; if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database; else pwDb = ds.Database; Exception ex = null; try { pwDb.Open(ioc, cmpKey, swLogger); #if DEBUG byte[] pbDiskDirect = WinUtil.HashFile(ioc); Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk)); #endif } catch(Exception exLoad) { ex = exLoad; pwDb = null; } swLogger.EndLogging(); if(pwDb == null) { if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase); } if(ex != null) { string strMsg = MessageService.GetLoadWarningMessage( ioc.GetDisplayName(), ex, (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)); bool bShowStd = true; if(!ioc.IsLocalFile()) { VistaTaskDialog vtd = new VistaTaskDialog(); vtd.CommandLinks = false; vtd.Content = strMsg; vtd.DefaultButtonID = (int)DialogResult.Cancel; // vtd.VerificationText = KPRes.CredSpecifyDifferent; vtd.WindowTitle = PwDefs.ShortProductName; vtd.SetIcon(VtdIcon.Warning); vtd.AddButton((int)DialogResult.Cancel, KPRes.Ok, null); vtd.AddButton((int)DialogResult.Retry, KPRes.CredSpecifyDifferent, null); if(vtd.ShowDialog(this)) { bShowStd = false; // if(vtd.ResultVerificationChecked) if(vtd.Result == (int)DialogResult.Retry) { IOConnectionInfo iocNew = ioc.CloneDeep(); // iocNew.ClearCredentials(false); iocNew.CredSaveMode = IOCredSaveMode.NoSave; iocNew.IsComplete = false; // iocNew.Password = string.Empty; OpenDatabase(iocNew, null, false); bAbort = true; } } } if(bShowStd) MessageService.ShowWarning(strMsg); // MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex, // (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)); } return pwDb; }
/// <summary> /// Open a database. This function opens the specified database and updates /// the user interface. /// </summary> public void OpenDatabase(IOConnectionInfo ioConnection, CompositeKey cmpKey, bool bOpenLocal) { if(!m_bFormLoaded && Program.Config.Application.Start.MinimizedAndLocked && (ioConnection != null) && (ioConnection.Path.Length > 0)) { PwDocument ds = m_docMgr.CreateNewDocument(true); ds.LockedIoc = ioConnection.CloneDeep(); UpdateUI(true, ds, true, null, true, null, false); return; } SaveWindowState(); // KPF 1093 IOConnectionInfo ioc; if(ioConnection == null) { if(bOpenLocal) { OpenFileDialogEx ofdDb = UIUtil.CreateOpenFileDialog(KPRes.OpenDatabaseFile, UIUtil.CreateFileTypeFilter(AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1, null, false, AppDefs.FileDialogContext.Database); GlobalWindowManager.AddDialog(ofdDb.FileDialog); DialogResult dr = ofdDb.ShowDialog(); GlobalWindowManager.RemoveDialog(ofdDb.FileDialog); if(dr != DialogResult.OK) return; ioc = IOConnectionInfo.FromPath(ofdDb.FileName); } else { ioc = CompleteConnectionInfo(new IOConnectionInfo(), false, true, true, true); if(ioc == null) return; } } else // ioConnection != null { ioc = CompleteConnectionInfo(ioConnection, false, true, true, false); if(ioc == null) return; } if(!ioc.CanProbablyAccess()) { MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileNotFoundError); return; } if(OpenDatabaseRestoreIfOpened(ioc)) return; PwDatabase pwOpenedDb = null; bool bAbort; if(cmpKey == null) { for(int iTry = 0; iTry < 3; ++iTry) { OdKpfConstructParams kpfParams = new OdKpfConstructParams(); kpfParams.IOConnectionInfo = ioc; kpfParams.CanExit = IsFileLocked(null); DialogResult dr; OdKpfResult kpfResult; if(Program.Config.Security.MasterKeyOnSecureDesktop && WinUtil.IsAtLeastWindows2000 && !KeePassLib.Native.NativeLib.IsUnix()) { kpfParams.SecureDesktopMode = true; ProtectedDialog dlg = new ProtectedDialog(OdKpfConstruct, OdKpfBuildResult); object objResult; dr = dlg.ShowDialog(out objResult, kpfParams); if(dr == DialogResult.None) { Debug.Assert(false); dr = DialogResult.Cancel; } kpfResult = (objResult as OdKpfResult); if(kpfResult == null) { Debug.Assert(false); continue; } if(kpfResult.ShowHelpAfterClose) AppHelp.ShowHelp(AppDefs.HelpTopics.KeySources, null); } else // Show dialog on normal desktop { Form dlg = OdKpfConstruct(kpfParams); dr = dlg.ShowDialog(); kpfResult = (OdKpfBuildResult(dlg) as OdKpfResult); UIUtil.DestroyForm(dlg); if(kpfResult == null) { Debug.Assert(false); continue; } } if(dr == DialogResult.Cancel) break; else if(kpfResult.HasClosedWithExit) { Debug.Assert(dr == DialogResult.Abort); OnFileExit(null, null); return; } pwOpenedDb = OpenDatabaseInternal(ioc, kpfResult.Key, out bAbort); if((pwOpenedDb != null) || bAbort) break; } } else // cmpKey != null { pwOpenedDb = OpenDatabaseInternal(ioc, cmpKey, out bAbort); } if((pwOpenedDb == null) || !pwOpenedDb.IsOpen) { UpdateUIState(false); // Reset status bar text return; } string strName = pwOpenedDb.IOConnectionInfo.GetDisplayName(); m_mruList.AddItem(strName, pwOpenedDb.IOConnectionInfo.CloneDeep()); PwDocument dsExisting = m_docMgr.FindDocument(pwOpenedDb); if(dsExisting != null) m_docMgr.ActiveDocument = dsExisting; bool bCorrectDbActive = (m_docMgr.ActiveDocument.Database == pwOpenedDb); Debug.Assert(bCorrectDbActive); // AutoEnableVisualHiding(); // SetLastUsedFile(pwOpenedDb.IOConnectionInfo); RememberKeySources(pwOpenedDb); PwGroup pgRestoreSelect = null; if(bCorrectDbActive) { m_docMgr.ActiveDocument.LockedIoc = new IOConnectionInfo(); // Clear pgRestoreSelect = pwOpenedDb.RootGroup.FindGroup( pwOpenedDb.LastSelectedGroup, true); } UpdateUI(true, null, true, pgRestoreSelect, true, null, false); if(bCorrectDbActive) { SetTopVisibleGroup(pwOpenedDb.LastTopVisibleGroup); if(pgRestoreSelect != null) SetTopVisibleEntry(pgRestoreSelect.LastTopVisibleEntry); } UpdateColumnSortingIcons(); if((pwOpenedDb.MasterKeyChangeForce >= 0) && ((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >= pwOpenedDb.MasterKeyChangeForce)) { while(true) { MessageService.ShowInfo(pwOpenedDb.IOConnectionInfo.GetDisplayName() + MessageService.NewParagraph + KPRes.MasterKeyChangeForce + MessageService.NewParagraph + KPRes.MasterKeyChangeInfo); if(ChangeMasterKey(pwOpenedDb)) { UpdateUIState(true); break; } if(!AppPolicy.Current.ChangeMasterKey) break; // Prevent endless loop } } else if((pwOpenedDb.MasterKeyChangeRec >= 0) && ((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >= pwOpenedDb.MasterKeyChangeRec)) { if(MessageService.AskYesNo(pwOpenedDb.IOConnectionInfo.GetDisplayName() + MessageService.NewParagraph + KPRes.MasterKeyChangeRec + MessageService.NewParagraph + KPRes.MasterKeyChangeQ)) UpdateUIState(ChangeMasterKey(pwOpenedDb)); } if(FixDuplicateUuids(pwOpenedDb, pwOpenedDb.IOConnectionInfo)) UpdateUIState(false); // Already marked as modified if(this.FileOpened != null) { FileOpenedEventArgs ea = new FileOpenedEventArgs(pwOpenedDb); this.FileOpened(this, ea); } Program.TriggerSystem.RaiseEvent(EcasEventIDs.OpenedDatabaseFile, EcasProperty.Database, pwOpenedDb); if(bCorrectDbActive && pwOpenedDb.IsOpen) { ShowExpiredEntries(true, Program.Config.Application.FileOpening.ShowExpiredEntries, Program.Config.Application.FileOpening.ShowSoonToExpireEntries); // Avoid view being destroyed by the unlocking routine pwOpenedDb.LastSelectedGroup = PwUuid.Zero; } if(Program.Config.MainWindow.MinimizeAfterOpeningDatabase) UIUtil.SetWindowState(this, FormWindowState.Minimized); ResetDefaultFocus(null); }
public static CompositeKey CreateKeyFor(string password) { CompositeKey key = new CompositeKey(); key.AddUserKey(new KcpPassword(password)); return key; }
private void CreateDatabase() { var keyfileCheckbox = FindViewById<CheckBox>(Resource.Id.use_keyfile); string password; if (!TryGetPassword(out password)) return; // Verify that a password or keyfile is set if (password.Length == 0 && !keyfileCheckbox.Checked) { Toast.MakeText(this, Resource.String.error_nopass, ToastLength.Long).Show(); return; } //create the key CompositeKey newKey = new CompositeKey(); if (String.IsNullOrEmpty(password) == false) { newKey.AddUserKey(new KcpPassword(password)); } if (String.IsNullOrEmpty(_keyfileFilename) == false) { try { newKey.AddUserKey(new KcpKeyFile(_keyfileFilename)); } catch (Exception) { Toast.MakeText(this, Resource.String.error_adding_keyfile, ToastLength.Long).Show(); return; } } // Create the new database CreateDb create = new CreateDb(App.Kp2a, this, _ioc, new LaunchGroupActivity(_ioc, this), false, newKey); ProgressTask createTask = new ProgressTask( App.Kp2a, this, create); createTask.Run(); }
public void LoadDatabase(IOConnectionInfo ioConnectionInfo, MemoryStream memoryStream, CompositeKey compKey, ProgressDialogStatusLogger statusLogger, IDatabaseFormat databaseFormat) { _db.LoadData(this, ioConnectionInfo, memoryStream, compKey, statusLogger, databaseFormat); }
private static KdbErrorCode SetDatabaseKey(KdbManager mgr, CompositeKey pwKey) { KdbErrorCode e; bool bPassword = pwKey.ContainsType(typeof(KcpPassword)); bool bKeyFile = pwKey.ContainsType(typeof(KcpKeyFile)); string strPassword = (bPassword ? (pwKey.GetUserKey( typeof(KcpPassword)) as KcpPassword).Password.ReadString() : string.Empty); string strKeyFile = (bKeyFile ? (pwKey.GetUserKey( typeof(KcpKeyFile)) as KcpKeyFile).Path : string.Empty); if(bPassword && bKeyFile) e = mgr.SetMasterKey(strKeyFile, true, strPassword, IntPtr.Zero, false); else if(bPassword && !bKeyFile) e = mgr.SetMasterKey(strPassword, false, null, IntPtr.Zero, false); else if(!bPassword && bKeyFile) e = mgr.SetMasterKey(strKeyFile, true, null, IntPtr.Zero, false); else if(pwKey.ContainsType(typeof(KcpUserAccount))) throw new Exception(KPRes.KdbWUA); else throw new Exception(KLRes.InvalidCompositeKey); return e; }
private bool CreateCompositeKey() { m_pKey = new CompositeKey(); if(m_cbPassword.Checked) // Use a password { byte[] pb = m_secPassword.ToUtf8(); m_pKey.AddUserKey(new KcpPassword(pb)); MemUtil.ZeroByteArray(pb); } string strKeyFile = m_cmbKeyFile.Text; Debug.Assert(strKeyFile != null); if(strKeyFile == null) strKeyFile = string.Empty; bool bIsProvKey = Program.KeyProviderPool.IsKeyProvider(strKeyFile); if(m_cbKeyFile.Checked && !strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta) && !bIsProvKey) { if(!ValidateKeyFile()) return false; try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile)); } catch(Exception) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError); return false; } } else if(m_cbKeyFile.Checked && !strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta) && bIsProvKey) { KeyProvider kp = Program.KeyProviderPool.Get(strKeyFile); if((kp != null) && m_bSecureDesktop) { if(!kp.SecureDesktopCompatible) { MessageService.ShowWarning(KPRes.KeyProvIncmpWithSD, KPRes.KeyProvIncmpWithSDHint); return false; } } KeyProviderQueryContext ctxKP = new KeyProviderQueryContext( m_ioInfo, false, m_bSecureDesktop); bool bPerformHash; byte[] pbProvKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP, out bPerformHash); if((pbProvKey != null) && (pbProvKey.Length > 0)) { try { m_pKey.AddUserKey(new KcpCustomKey(strKeyFile, pbProvKey, bPerformHash)); } catch(Exception exCKP) { MessageService.ShowWarning(exCKP); return false; } MemUtil.ZeroByteArray(pbProvKey); } else return false; // Provider has shown error message } if(m_cbUserAccount.Checked) { try { m_pKey.AddUserKey(new KcpUserAccount()); } catch(Exception exUA) { MessageService.ShowWarning(exUA); return false; } } return true; }
private bool CreateCompositeKey() { m_pKey = new CompositeKey(); if(m_cbPassword.Checked) // Use a password { if(!m_icgPassword.ValidateData(true)) return false; uint uPwLen = m_icgPassword.PasswordLength; if(uPwLen == 0) { if(!MessageService.AskYesNo(KPRes.EmptyMasterPw + MessageService.NewParagraph + KPRes.EmptyMasterPwHint + MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion, null, false)) { return false; } } uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength; if(uPwLen < uMinLen) { string strML = KPRes.MasterPasswordMinLengthFailed; strML = strML.Replace(@"{PARAM}", uMinLen.ToString()); MessageService.ShowWarning(strML); return false; } byte[] pb = m_icgPassword.GetPasswordUtf8(); uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality; if(QualityEstimation.EstimatePasswordBits(pb) < uMinQual) { string strMQ = KPRes.MasterPasswordMinQualityFailed; strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString()); MessageService.ShowWarning(strMQ); Array.Clear(pb, 0, pb.Length); return false; } string strValRes = Program.KeyValidatorPool.Validate(pb, KeyValidationType.MasterPassword); if(strValRes != null) { MessageService.ShowWarning(strValRes); Array.Clear(pb, 0, pb.Length); return false; } m_pKey.AddUserKey(new KcpPassword(pb)); Array.Clear(pb, 0, pb.Length); } string strKeyFile = m_cmbKeyFile.Text; bool bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(strKeyFile); if(m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) && !bIsKeyProv) { try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile, true)); } catch(InvalidDataException exID) // Selected database file { MessageService.ShowWarning(strKeyFile, exID); return false; } catch(Exception exKF) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKF); return false; } } else if(m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) && bIsKeyProv) { KeyProviderQueryContext ctxKP = new KeyProviderQueryContext( m_ioInfo, true, false); bool bPerformHash; byte[] pbCustomKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP, out bPerformHash); if((pbCustomKey != null) && (pbCustomKey.Length > 0)) { try { m_pKey.AddUserKey(new KcpCustomKey(strKeyFile, pbCustomKey, bPerformHash)); } catch(Exception exCKP) { MessageService.ShowWarning(exCKP); return false; } Array.Clear(pbCustomKey, 0, pbCustomKey.Length); } else return false; // Provider has shown error message } if(m_cbUserAccount.Checked) { try { m_pKey.AddUserKey(new KcpUserAccount()); } catch(Exception exUA) { MessageService.ShowWarning(exUA); return false; } } return true; }
public bool EqualsValue(CompositeKey ckOther) { if(ckOther == null) throw new ArgumentNullException("ckOther"); byte[] pbThis = CreateRawCompositeKey32(); byte[] pbOther = ckOther.CreateRawCompositeKey32(); bool bResult = MemUtil.ArraysEqual(pbThis, pbOther); Array.Clear(pbOther, 0, pbOther.Length); Array.Clear(pbThis, 0, pbThis.Length); return bResult; }
private bool CreateCompositeKey() { m_pKey = new CompositeKey(); if(m_cbPassword.Checked) // Use a password { byte[] pb = m_secPassword.ToUtf8(); m_pKey.AddUserKey(new KcpPassword(pb)); Array.Clear(pb, 0, pb.Length); } string strKeyFile = m_cmbKeyFile.Text; Debug.Assert(strKeyFile != null); if(strKeyFile == null) strKeyFile = string.Empty; bool bIsProvKey = Program.KeyProviderPool.IsKeyProvider(strKeyFile); if(m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) && (bIsProvKey == false)) { if(ValidateKeyFileLocation() == false) { m_pKey = null; return false; } try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile)); } catch(Exception) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError); m_pKey = null; return false; } } else if(m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) && (bIsProvKey == true)) { byte[] pbProvKey = Program.KeyProviderPool.GetKey(strKeyFile); try { m_pKey.AddUserKey(new KcpCustomKey(pbProvKey)); } catch(Exception exCKP) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exCKP); m_pKey = null; return false; } if((pbProvKey != null) && (pbProvKey.Length > 0)) Array.Clear(pbProvKey, 0, pbProvKey.Length); } if(m_cbUserAccount.Checked) { try { m_pKey.AddUserKey(new KcpUserAccount()); } catch(Exception exUA) { MessageService.ShowWarning(exUA); return false; } } return true; }
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; }
private CompositeKey CreateCompositeKey(string masterKey) { CompositeKey m_pKey = new CompositeKey (); SecureEdit se = new SecureEdit (masterKey); byte[] pb = se.ToUtf8 (); m_pKey.AddUserKey (new KcpPassword (pb)); Array.Clear (pb, 0, pb.Length); return m_pKey; }
/// <summary> /// Open a database. This function opens the specified database and updates /// the user interface. /// </summary> public void OpenDatabase(IOConnectionInfo ioc, CompositeKey cmpKey) { // Close active db CloseDatabase (); if (db != null && db.IsOpen) return; //IOConnectionInfo ioc = IOConnectionInfo.FromPath(ConfigurationManager.AppSettings["dbPath"]); //if (ioConnection == null) //{ // if (bOpenLocal) // { // OpenFileDialog ofdDb = UIUtil.CreateOpenFileDialog(KPRes.OpenDatabaseFile, // UIUtil.CreateFileTypeFilter(AppDefs.FileExtension.FileExt, // KPRes.KdbxFiles, true), 1, null, false, false); // //GlobalWindowManager.AddDialog(ofdDb); // //DialogResult dr = ofdDb.ShowDialog(); // //GlobalWindowManager.RemoveDialog(ofdDb); // //if (dr != DialogResult.OK) return; // ioc = IOConnectionInfo.FromPath(ofdDb.FileName); // } // else // { // ioc = CompleteConnectionInfo(new IOConnectionInfo(), false, // true, true, true); // if (ioc == null) return; // } //} //else // ioConnection != null //{ // ioc = CompleteConnectionInfo(ioConnection, false, true, true, false); // if (ioc == null) return; //} if (!ioc.CanProbablyAccess ()) { // TODO //MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileNotFoundError); //return; } //if (OpenDatabaseRestoreIfOpened(ioc)) return; PwDatabase pwOpenedDb = null; if (cmpKey == null) { // get the master key CompositeKey key = CreateCompositeKey (System.Configuration.ConfigurationManager.AppSettings ["dbKey"]); pwOpenedDb = OpenDatabaseInternal (ioc, key); } else { // cmpKey != null pwOpenedDb = OpenDatabaseInternal (ioc, cmpKey); } //string strName = pwOpenedDb.IOConnectionInfo.GetDisplayName(); //this.Text = strName; //m_mruList.AddItem(strName, pwOpenedDb.IOConnectionInfo.CloneDeep(), true); db = pwOpenedDb; }
public static CompositeKey KeyFromCommandLine(CommandLineArgs args) { if(args == null) throw new ArgumentNullException("args"); CompositeKey cmpKey = new CompositeKey(); string strPassword = args[AppDefs.CommandLineOptions.Password]; string strPasswordEnc = args[AppDefs.CommandLineOptions.PasswordEncrypted]; string strPasswordStdIn = args[AppDefs.CommandLineOptions.PasswordStdIn]; string strKeyFile = args[AppDefs.CommandLineOptions.KeyFile]; string strUserAcc = args[AppDefs.CommandLineOptions.UserAccount]; if(strPassword != null) cmpKey.AddUserKey(new KcpPassword(strPassword)); else if(strPasswordEnc != null) cmpKey.AddUserKey(new KcpPassword(StrUtil.DecryptString(strPasswordEnc))); else if(strPasswordStdIn != null) { KcpPassword kcpPw = ReadPasswordStdIn(true); if(kcpPw != null) cmpKey.AddUserKey(kcpPw); } if(strKeyFile != null) { if(Program.KeyProviderPool.IsKeyProvider(strKeyFile)) { KeyProviderQueryContext ctxKP = new KeyProviderQueryContext( IOConnectionInfo.FromPath(args.FileName), false, false); bool bPerformHash; byte[] pbProvKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP, out bPerformHash); if((pbProvKey != null) && (pbProvKey.Length > 0)) { try { cmpKey.AddUserKey(new KcpCustomKey(strKeyFile, pbProvKey, bPerformHash)); } catch(Exception exCKP) { MessageService.ShowWarning(exCKP); return null; } Array.Clear(pbProvKey, 0, pbProvKey.Length); } else return null; // Provider has shown error message } else // Key file { try { cmpKey.AddUserKey(new KcpKeyFile(strKeyFile)); } catch(Exception exKey) { MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKey); return null; } } } if(strUserAcc != null) { try { cmpKey.AddUserKey(new KcpUserAccount()); } catch(Exception exUA) { MessageService.ShowWarning(exUA); return null; } } if(cmpKey.UserKeyCount > 0) { ClearKeyOptions(args, true); return cmpKey; } return null; }
public static PwDatabase OpenKeePassDatabase(string databasePath, CompositeKey compositeKey) { if (!File.Exists(databasePath)) throw new FileNotFoundException(databasePath); var database = new PwDatabase(); var ioc = new IOConnectionInfo() { Path = databasePath }; database.Open(ioc, compositeKey, null); return database; }
private void Clear() { m_pgRootGroup = null; m_vDeletedObjects = new PwObjectList<PwDeletedObject>(); m_uuidDataCipher = StandardAesEngine.AesUuid; m_caCompression = PwCompressionAlgorithm.GZip; m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; m_pwUserKey = null; m_memProtConfig = new MemoryProtectionConfig(); m_vCustomIcons = new List<PwCustomIcon>(); m_strName = string.Empty; m_strDesc = string.Empty; m_strDefaultUserName = string.Empty; m_bUINeedsIconUpdate = true; m_ioSource = new IOConnectionInfo(); m_bDatabaseOpened = false; m_bModified = false; m_pwLastSelectedGroup = PwUuid.Zero; m_pwLastTopVisibleGroup = PwUuid.Zero; m_pbHashOfFileOnDisk = null; m_pbHashOfLastIO = null; }
public static bool? Import(PwDatabase pd, FileFormatProvider fmtImp, IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey) { if(pd == null) { Debug.Assert(false); return false; } if(fmtImp == null) { Debug.Assert(false); return false; } if(iocImp == null) { Debug.Assert(false); return false; } if(cmpKey == null) cmpKey = new CompositeKey(); if(!AppPolicy.Try(AppPolicyId.Import)) return false; if(!fmtImp.TryBeginImport()) return false; PwDatabase pdImp = new PwDatabase(); pdImp.New(new IOConnectionInfo(), cmpKey); pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep(); Stream s = IOConnection.OpenRead(iocImp); if(s == null) throw new FileNotFoundException(iocImp.GetDisplayName() + MessageService.NewLine + KPRes.FileNotFoundError); try { fmtImp.Import(pdImp, s, null); } finally { s.Close(); } pd.MergeIn(pdImp, mm); return true; }
private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc, CompositeKey cmpKey) { PerformSelfTest(); ShowWarningsLogger swLogger = CreateShowWarningsLogger(); swLogger.StartLogging(KPRes.OpeningDatabase, true); PwDocument ds = null; string strPathNrm = ioc.Path.Trim().ToLower(); for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan) { if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm) ds = m_docMgr.Documents[iScan]; else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm) ds = m_docMgr.Documents[iScan]; } PwDatabase pwDb; if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database; else pwDb = ds.Database; try { pwDb.Open(ioc, cmpKey, swLogger); #if DEBUG byte[] pbDiskDirect = WinUtil.HashFile(ioc); Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk)); #endif } catch(Exception ex) { MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex); pwDb = null; } swLogger.EndLogging(); if(pwDb == null) { if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase); } return pwDb; }
public void SetKeySources(IOConnectionInfo iocDb, CompositeKey cmpKey) { string strID = GetKeyAssocID(iocDb); int idx = GetKeyAssocIndex(strID); if((cmpKey == null) || !m_bRememberKeySources) { if(idx >= 0) m_vKeySources.RemoveAt(idx); return; } AceKeyAssoc a = new AceKeyAssoc(); a.DatabasePath = strID; IUserKey kcpFile = cmpKey.GetUserKey(typeof(KcpKeyFile)); if(kcpFile != null) { string strKeyFile = ((KcpKeyFile)kcpFile).Path; if(!string.IsNullOrEmpty(strKeyFile) && !StrUtil.IsDataUri(strKeyFile)) { if(!UrlUtil.IsAbsolutePath(strKeyFile)) strKeyFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strKeyFile); a.KeyFilePath = strKeyFile; } } IUserKey kcpCustom = cmpKey.GetUserKey(typeof(KcpCustomKey)); if(kcpCustom != null) a.KeyProvider = ((KcpCustomKey)kcpCustom).Name; IUserKey kcpUser = cmpKey.GetUserKey(typeof(KcpUserAccount)); a.UserAccount = (kcpUser != null); bool bAtLeastOne = ((a.KeyFilePath.Length > 0) || (a.KeyProvider.Length > 0) || a.UserAccount); if(bAtLeastOne) { if(idx >= 0) m_vKeySources[idx] = a; else m_vKeySources.Add(a); } else if(idx >= 0) m_vKeySources.RemoveAt(idx); }
/// <summary> /// Initialize the class for managing a new database. Previously loaded /// data is deleted. /// </summary> /// <param name="ioConnection">IO connection of the new database.</param> /// <param name="pwKey">Key to open the database.</param> public void New(IOConnectionInfo ioConnection, CompositeKey pwKey) { Debug.Assert(ioConnection != null); if(ioConnection == null) throw new ArgumentNullException("ioConnection"); Debug.Assert(pwKey != null); if(pwKey == null) throw new ArgumentNullException("pwKey"); this.Close(); m_ioSource = ioConnection; m_pwUserKey = pwKey; m_bDatabaseOpened = true; m_bModified = true; m_pgRootGroup = new PwGroup(true, true, UrlUtil.StripExtension(UrlUtil.GetFileName(ioConnection.Path)), PwIcon.FolderOpen); m_pgRootGroup.IsExpanded = true; }
private void OnBtnCancel(object sender, EventArgs e) { m_pKey = null; }
/// <summary> /// Open a database. The URL may point to any supported data source. /// </summary> /// <param name="ioSource">IO connection to load the database from.</param> /// <param name="pwKey">Key used to open the specified database.</param> /// <param name="slLogger">Logger, which gets all status messages.</param> public void Open(IOConnectionInfo ioSource, CompositeKey pwKey, IStatusLogger slLogger) { Debug.Assert(ioSource != null); if(ioSource == null) throw new ArgumentNullException("ioSource"); Debug.Assert(pwKey != null); if(pwKey == null) throw new ArgumentNullException("pwKey"); this.Close(); try { m_pgRootGroup = new PwGroup(true, true, UrlUtil.StripExtension( UrlUtil.GetFileName(ioSource.Path)), PwIcon.FolderOpen); m_pgRootGroup.IsExpanded = true; m_pwUserKey = pwKey; m_bModified = false; Kdb4File kdb4 = new Kdb4File(this); Stream s = IOConnection.OpenRead(ioSource); kdb4.Load(s, Kdb4Format.Default, slLogger); s.Close(); m_pbHashOfLastIO = kdb4.HashOfFileOnDisk; m_pbHashOfFileOnDisk = kdb4.HashOfFileOnDisk; Debug.Assert(m_pbHashOfFileOnDisk != null); m_bDatabaseOpened = true; m_ioSource = ioSource; } catch(Exception) { this.Clear(); throw; } }