/// <summary> /// Reads file and loads key into agent /// </summary> /// <param name="aAgent">the agent</param> /// <param name="aFileName">pathname of file to read</param> /// <param name="aGetPassPhraseCallback">method that returns passphrase</param> /// <param name="aConstraints">additional constraints</param> /// <exception cref="AgentFailureException"> /// Agent returned SSH_AGENT_FAILURE /// </exception> /// <exception cref="KeyFormatterException"> /// File format was not recognized /// </exception> /// <exception cref="UnauthorizedAccessException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="PathTooLongException"></exception> /// <exception cref="DirectoryNotFoundException"></exception> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="NotSupportedException"></exception> /// <returns>The ssh key that was read from the file</returns> public static ISshKey AddKeyFromFile(this IAgent aAgent, string aFileName, KeyFormatter.GetPassphraseCallback aGetPassPhraseCallback, ICollection <Agent.KeyConstraint> aConstraints = null) { string firstLine; using (var fileReader = File.OpenText(aFileName)) { firstLine = fileReader.ReadLine(); } var formatter = KeyFormatter.GetFormatter(firstLine); formatter.GetPassphraseCallbackMethod = aGetPassPhraseCallback; var key = formatter.DeserializeFile(aFileName); if (aConstraints != null) { foreach (var constraint in aConstraints) { key.AddConstraint(constraint); } } // prevent error in Pageant by attempting to remove key before adding it // this makes behavior more consistent with OpenSSH if (aAgent is PageantClient) { try { aAgent.RemoveKey(key); } catch (Exception) { /* error will occur if key is not loaded */ } } aAgent.AddKey(key); return(key); }
public static ISshKey GetSshKey(this EntrySettings settings, ProtectedStringDictionary strings, ProtectedBinaryDictionary binaries, SprContext sprContext) { if (!settings.AllowUseOfSshKey) { return(null); } KeyFormatter.GetPassphraseCallback getPassphraseCallback = delegate(string comment) { var securePassphrase = new SecureString(); var passphrase = SprEngine.Compile(strings.ReadSafe( PwDefs.PasswordField), sprContext); foreach (var c in passphrase) { securePassphrase.AppendChar(c); } return(securePassphrase); }; Func <Stream> getPrivateKeyStream; Func <Stream> getPublicKeyStream = null; switch (settings.Location.SelectedType) { case EntrySettings.LocationType.Attachment: if (string.IsNullOrWhiteSpace(settings.Location.AttachmentName)) { throw new NoAttachmentException(); } var privateKeyData = binaries.Get(settings.Location.AttachmentName); var publicKeyData = binaries.Get(settings.Location.AttachmentName + ".pub"); getPrivateKeyStream = () => new MemoryStream(privateKeyData.ReadData()); if (publicKeyData != null) { getPublicKeyStream = () => new MemoryStream(publicKeyData.ReadData()); } return(GetSshKey(getPrivateKeyStream, getPublicKeyStream, settings.Location.AttachmentName, getPassphraseCallback)); case EntrySettings.LocationType.File: var filename = settings.Location.FileName.ExpandEnvironmentVariables(); getPrivateKeyStream = () => File.OpenRead(filename); var publicKeyFile = filename + ".pub"; if (File.Exists(publicKeyFile)) { getPublicKeyStream = () => File.OpenRead(publicKeyFile); } return(GetSshKey(getPrivateKeyStream, getPublicKeyStream, settings.Location.AttachmentName, getPassphraseCallback)); default: return(null); } }
public static ISshKey AddKeyFromFile(this IAgent agent, string fileName, ICollection <Agent.KeyConstraint> constraints, KeyFormatter.GetPassphraseCallback getPassword = null) { if (getPassword == null) { getPassword = PasswordCallbackFactory( string.Format(Strings.msgEnterPassphrase, Path.GetFileName(fileName))); } return(agent.AddKeyFromFile(fileName, getPassword, constraints)); }
/// <summary> /// Auto-detect data format, read data and create key object /// </summary> /// <param name="aStream"></param> /// <returns></returns> public static ISshKey ReadSshKey(this Stream aStream, KeyFormatter.GetPassphraseCallback aGetPassphraseCallback = null) { using (var reader = new StreamReader(aStream)) { var firstLine = reader.ReadLine(); var formatter = KeyFormatter.GetFormatter(firstLine); formatter.GetPassphraseCallbackMethod = aGetPassphraseCallback; aStream.Position = 0; return(formatter.Deserialize(aStream) as ISshKey); } }
public void SetupFixture() { passphraseCallback = delegate(string comment) { SecureString passphrase = new SecureString(); foreach (char c in Resources.pw.Trim()) { passphrase.AppendChar(c); } return passphrase; }; }
public OpensshPrivateKeyFormatterTest() { passphraseCallback = delegate(string comment) { SecureString passphrase = new SecureString(); foreach (char c in Resources.pw.Trim()) { passphrase.AppendChar(c); } return(passphrase); }; }
public static void AddKeysFromFiles(this IAgent agent, string[] fileNames, ICollection <Agent.KeyConstraint> constraints = null) { KeyFormatter.GetPassphraseCallback getPassword = null; foreach (var fileName in fileNames) { try { try { // try using the previous passphrase if (getPassword == null) { throw new Exception("No previous passphrase."); } agent.AddKeyFromFile(fileName, constraints, getPassword); } catch { // if the previous passphrase does not work, ask for a new passphrase getPassword = PasswordCallbackFactory( string.Format(Strings.msgEnterPassphrase, Path.GetFileName(fileName))); agent.AddKeyFromFile(fileName, constraints, getPassword); } } catch (PpkFormatterException) { MessageBox.Show(string.Format( "Error opening file '{0}'\n" + "Possible causes:\n" + "\n" + "- Passphrase was entered incorrectly\n" + "- File is corrupt", fileName), Util.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (AgentNotRunningException) { MessageBox.Show("Could not add key because no SSH agent was found." + " Please make sure your SSH agent program is running (e.g. Pageant).", Util.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(string.Format(Strings.errFileOpenFailed, fileName, ex.Message), Util.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } // TODO may want to return ICollection<ISshKey> with added keys // to be more like other Add* methods } }
static ISshKey GetSshKey(Func <Stream> getPrivateKeyStream, Func <Stream> getPublicKeyStream, string fallbackComment, KeyFormatter.GetPassphraseCallback getPassphrase) { ISshKey key; using (var privateKeyStream = getPrivateKeyStream()) key = privateKeyStream.ReadSshKey(getPassphrase); if (string.IsNullOrWhiteSpace(key.Comment) && getPublicKeyStream != null) { using (var stream = getPublicKeyStream()) key.Comment = KeyFormatter.GetComment(stream.ReadAllLines(Encoding.UTF8)); } if (string.IsNullOrWhiteSpace(key.Comment)) { key.Comment = fallbackComment; } return(key); }
public void TestIOProtocolExt() { using (KeePassAppDomain testDomain1 = new KeePassAppDomain()) { testDomain1.StartKeePass(true, false, 1, true); testDomain1.DoCallBack(delegate() { KeePass.Program.MainForm.Invoke((MethodInvoker) delegate() { /* initialize plugins */ KeeAgentExt td1KeeAgentExt = new KeeAgentExt(); IOProtocolExtExt td1IOProtocolExt = new IOProtocolExtExt(); IPluginHost td1PluginHost = KeePass.Program.MainForm.PluginHost; td1KeeAgentExt.Initialize(td1PluginHost); td1IOProtocolExt.Initialize(td1PluginHost); KeePass.Program.MainForm.FormClosing += delegate( Object source, FormClosingEventArgs args) { td1KeeAgentExt.Terminate(); td1IOProtocolExt.Terminate(); }; var extType = td1KeeAgentExt.GetType(); var mAgentField = extType.GetField("mAgent", BindingFlags.Instance | BindingFlags.NonPublic); var agent = mAgentField.GetValue(td1KeeAgentExt) as IAgent; // test not valid in client mode Assert.That(agent, Is.AssignableTo <Agent>()); // override confirm callback so we don't have to click OK (agent as Agent).ConfirmUserPermissionCallback = delegate(ISshKey aKey) { return(true); }; /* load ssh key */ var keyFileDir = Path.GetFullPath(Path.Combine( "..", "..", "..", "SshAgentLib", "SshAgentLibTests", "Resources")); var keyFilePath = Path.Combine(keyFileDir, "rsa_with_passphrase"); Assert.That(File.Exists(keyFilePath), "Cannot locate key file: " + keyFilePath); KeyFormatter.GetPassphraseCallback getPassphraseCallback = delegate() { var passphrase = "passphrase"; var securePassphrase = new SecureString(); foreach (char c in passphrase) { securePassphrase.AppendChar(c); } return(securePassphrase); }; var constraints = new List <Agent.KeyConstraint>(); constraints.addConfirmConstraint(); agent.AddKeyFromFile(keyFilePath, getPassphraseCallback, constraints); /* run test */ IOConnectionInfo ioConnectionInfo = new IOConnectionInfo(); ioConnectionInfo.Path = "sftp://satest/test.kdbx"; ioConnectionInfo.UserName = "******"; bool fileExists = IOConnection.FileExists(ioConnectionInfo); Assert.IsTrue(fileExists, "Is satest VM running?"); /* the problem we are checking for is that IOConnection.FileExists * does not lock up. Originally, in KeeAgent, WinPagent ran on main * thread and caused lock-up here. So, we are looking to see if the * test times out or not. */ }); }); } }
private void mAddButton_Clicked() { // TODO - persist start directory (and possibly viewMode) using (var dialog = new KeyFileDialog()) { dialog.SetDirectory(Environment.GetFolderPath( Environment.SpecialFolder.Personal)); dialog.Exec(); if (dialog.Result == (int)QDialog.DialogCode.Accepted) { var constraints = dialog.GetConstraints(); foreach (var file in dialog.SelectedFiles) { try { KeyFormatter.GetPassphraseCallback passphraseCallback = () => { var passphraseDialog = new PassphraseDialog(); passphraseDialog.Exec(); if (passphraseDialog.Result == (int)QDialog.DialogCode.Rejected) { return(null); } using (var passphrase = new PinnedArray <byte>(passphraseDialog.GetPassphrase())) { var securePassphrase = new SecureString(); foreach (var b in passphrase.Data) { securePassphrase.AppendChar((char)b); } return(securePassphrase); } }; mAgent.AddKeyFromFile(file, passphraseCallback, constraints); } catch (AgentFailureException) { QMessageBox.Critical(this, Tr("Agent Failure"), Tr("Possible causes:") + "<ul>" + "</li>" + "<li>" + Tr("Agent is locked") + "</li>" + "<li>" + Tr("Agent does not support this key type") + "</ul>"); } catch (KeyFormatterException) { QMessageBox.Critical(this, Tr("File format error"), Tr("This file not a recognized private key file") + "<br><br>" + file); } catch (Exception ex) { Debug.Fail(ex.ToString()); } } } } if (mAgent is Agent) { UpdateUIState(); } else { ReloadData(); } }
/// <summary> /// Auto-detect data format, read data and create key object /// </summary> /// <param name="aStream"></param> /// <returns></returns> public static ISshKey ReadSshKey(this byte[] aData, KeyFormatter.GetPassphraseCallback aGetPassphraseCallback = null) { using (var stream = new MemoryStream(aData)) { return(stream.ReadSshKey(aGetPassphraseCallback)); } }