public SftpStorage(string user, string password, string keyPath, string host, int?port = null, string rootPath = "", bool createRoot = false) { _rootPath = rootPath; _user = user; _password = password; _keyPath = keyPath; _host = host; _port = port ?? DefaultPort; ConnectionInfo connectionInfo = null; if (keyPath != null) { connectionInfo = new PrivateKeyConnectionInfo(host, _port, _user, new PrivateKeyFile(keyPath)); } else { connectionInfo = new PasswordConnectionInfo(host, _port, user, password); } _client = new SftpClient(connectionInfo); _client.Connect(); if (createRoot) { try { _client.CreateDirectory(_rootPath); } catch (Exception) { } } }
private ConnectionInfo PrepareConnectionInfo() { ConnectionInfo connectionInfo; if (_proxy != null) { var proxyType = ProxyTypes.None; switch (_proxy.ProxyType) { case Helpers.ProxyTypes.Http: proxyType = ProxyTypes.Http; break; case Helpers.ProxyTypes.Socks4: proxyType = ProxyTypes.Socks4; break; case Helpers.ProxyTypes.Socks5: proxyType = ProxyTypes.Socks5; break; } if (_proxy.ProxyAuthMethod == ProxyAuthMethod.Password) { connectionInfo = new PasswordConnectionInfo( _secureShell.HostName, _secureShell.HostUsername, _secureShell.HostPassword.GetString(), proxyType, _proxy.ProxyHostName, _proxy.ProxyPort, _proxy.ProxyUsername, _proxy.ProxyPasswd?.GetString() ); } else //if (_proxy.ProxyAuthMethod == ProxyAuthMethod.PrivateKey) { connectionInfo = new PrivateKeyConnectionInfo( _secureShell.HostName, _secureShell.HostPort, _secureShell.HostUsername, proxyType, _proxy.ProxyHostName, _proxy.ProxyPort, new PrivateKeyFile("") // ToDo: ); } } else { connectionInfo = new ConnectionInfo( _secureShell.HostName, _secureShell.HostPort, _secureShell.HostUsername, new PasswordAuthenticationMethod(_secureShell.HostUsername, _secureShell.HostPassword.GetString()) ); } return(connectionInfo); }
public static SftpClient CreateConnection(string server, string username, string privateKeyPath) { var privateKey = new PrivateKeyFile(privateKeyPath); var privateKeyConnection = new PrivateKeyConnectionInfo(server, username, privateKey); return(new SftpClient(privateKeyConnection)); }
[Ignore] // placeholder for actual test public void DisposeTest() { string host = string.Empty; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, keyFiles); // TODO: Initialize to an appropriate value target.Dispose(); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public static void Run() { var pfFile = new PrivateKeyFile(@"mykey.pem"); var connectionInfo = new PrivateKeyConnectionInfo("54.252.90.204", "ubuntu", pfFile); CopyScript(connectionInfo); //RunRefreshShell(connectionInfo); }
private static void RunRefreshShell(PrivateKeyConnectionInfo connectionInfo) { using (var ssh = new SshClient(connectionInfo)) { ssh.Connect(); var cmd = ssh.CreateCommand("sudo /home/ubuntu/se/shopping/script/refresh_sphinx.sh"); var str = cmd.Execute(); Console.WriteLine(str); } }
[Ignore] // placeholder for actual test public void PrivateKeyConnectionInfoConstructorTest7() { string host = string.Empty; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, keyFiles); Assert.Inconclusive("TODO: Implement code to verify target"); }
public void PrivateKeyConnectionInfoConstructorTest2() { string host = string.Empty; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value string proxyHost = string.Empty; // TODO: Initialize to an appropriate value int proxyPort = 0; // TODO: Initialize to an appropriate value string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername, keyFiles); Assert.Inconclusive("TODO: Implement code to verify target"); }
public static SftpClient CreateSftpClient(MayhemConfiguration config) { if (!File.Exists(config.Ssh.KeyAuth)) { throw new Exception("Key does not exists"); } PrivateKeyFile privateKeyStream = new PrivateKeyFile(config.Ssh.KeyAuth); var connectionInfo = new PrivateKeyConnectionInfo(config.Ssh.IP, config.Ssh.Username, privateKeyStream); return(new SftpClient(connectionInfo)); }
public static bool Authorize(SSHCredentials sshCredentials) { SshClient client = null; PrivateKeyConnectionInfo connectionInfo = new PrivateKeyConnectionInfo( sshCredentials.Host, sshCredentials.UserName, new PrivateKeyFile[] { new PrivateKeyFile(sshCredentials.KeyFile) }); client = new SshClient(connectionInfo); client.Connect(); client.Disconnect(); return(true); }
[Ignore] // placeholder for actual test public void PrivateKeyConnectionInfoConstructorTest4() { string host = string.Empty; // TODO: Initialize to an appropriate value int port = 0; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value string proxyHost = string.Empty; // TODO: Initialize to an appropriate value int proxyPort = 0; // TODO: Initialize to an appropriate value string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, keyFiles); Assert.Inconclusive("TODO: Implement code to verify target"); }
public override void SessionStarting() { if (KeyPath != null) { var ci = new PrivateKeyConnectionInfo(Host, Username, new PrivateKeyFile(KeyPath)); OpenClient(ci); } else { var auth_passwd = new PasswordAuthenticationMethod(Username, Password); var auth_kb = new KeyboardInteractiveAuthenticationMethod(Username); auth_kb.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(OnAuthPrompt); var ci = new ConnectionInfo(Host, Username, auth_kb, auth_passwd); OpenClient(ci); } }
public void Test_PrivateKeyConnectionInfo() { var host = Resources.HOST; var username = Resources.USERNAME; MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS)); #region Example PrivateKeyConnectionInfo PrivateKeyFile var connectionInfo = new PrivateKeyConnectionInfo(host, username, new PrivateKeyFile(keyFileStream)); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } #endregion Assert.AreEqual(connectionInfo.Host, Resources.HOST); Assert.AreEqual(connectionInfo.Username, Resources.USERNAME); }
public string RunCommand(string grid, string command, bool appendXML) { string strMethodName = (new StackTrace(true)).GetFrame(0).GetMethod().Name; if (boolCanRead) { string privateKey = HttpContext.Current.Server.MapPath("~/cv_avamar.pvt"); string user = oVariable.AvamarUsername(); string xml = ""; PrivateKeyFile key = new PrivateKeyFile(privateKey, oVariable.ADPassword()); var connectionInfo = new PrivateKeyConnectionInfo(grid, user, key); using (var client = new SshClient(connectionInfo)) { try { client.Connect(); SshCommand output = client.RunCommand(command + (appendXML ? " --xml" : "") + " | tee -a .avamar_cv_command_$(date +%Y%m).log"); if (String.IsNullOrEmpty(output.Error) == false) { xml = output.Error; } else { xml = output.Result; } client.Disconnect(); } catch (SshAuthenticationException ex) { xml = "Error Message: " + ex.Message + " on " + grid; } } return(xml); } else { oLog.WriteEntry(String.Format("\"" + WebMethodName + "\" Finished...Access Denied (" + strUser + ")"), EventLogEntryType.Information); return(strERRORPrefix + "Access Denied (" + strUser + ")"); } }
private SshClient CreateClient() { ConnectionInfo connInfo; if (string.IsNullOrEmpty(_pkey)) { connInfo = new PasswordConnectionInfo(_host, 22, _username, _password ?? string.Empty); } else if (!string.IsNullOrEmpty(_password)) { connInfo = new PrivateKeyConnectionInfo(_host, 22, _username, new PrivateKeyFile(_pkey, _password)); } else { connInfo = new PrivateKeyConnectionInfo(_host, 22, _username, new PrivateKeyFile(_pkey)); } connInfo.Timeout = TimeSpan.FromSeconds(_connectTimeout); return(new SshClient(connInfo)); }
static public bool EnsureTunnelExists(SqlDBCredentials credentials) { SSHCredentials sshCredentials = credentials.SSHCredentials; SshClient client = null; if (_clients.TryGetClient(sshCredentials, out client) == false) { PrivateKeyConnectionInfo connectionInfo = new PrivateKeyConnectionInfo( sshCredentials.Host, sshCredentials.UserName, new PrivateKeyFile[] { new PrivateKeyFile(sshCredentials.KeyFile) }); client = new SshClient(connectionInfo); client.KeepAliveInterval = TimeSpan.FromMinutes(1); client.ErrorOccurred += Client_ErrorOccurred; client.HostKeyReceived += Client_HostKeyReceived; client.Connect(); if (client.IsConnected) { ForwardedPortLocal port = new ForwardedPortLocal( IPAddress.Loopback.ToString(), sshCredentials.LocalTunnelPort, sshCredentials.TunnelHost, 3306); client.AddForwardedPort(port); port.Start(); if (port.IsStarted == false) { client.Disconnect(); client = null; throw new Exception("Could not forward port"); } _clients.Add(client); } } return(client != null); }
private SftpClient ConfigureSftp() { if (!_ftpConfigurationModel.Host.ToUpperInvariant().Contains("SFTP")) { throw new Exception($"Para utilizar o sftp é necessário definir HOST válido no appsettings"); } if (_ftpConfigurationModel.Port == null) { throw new Exception($"Para utilizar o sftp é necessário definir uma Porta válida"); } if (_ftpConfigurationModel.RsaFileName.isNullOrEmpty()) { throw new Exception($"Para utilizar o sftp é necessário definir um valor para a configuração RsaFileName, no appsettings"); } var privateKeyFileConfiguration = new PrivateKeyFile($"ConfigurationFiles\\HDI\\{_ftpConfigurationModel.RsaFileName}"); var connectionInfo = new PrivateKeyConnectionInfo(_ftpConfigurationModel.Host, _ftpConfigurationModel.Port.Value, _ftpConfigurationModel.Username, // ProxyTypes.Http, // "px1.ituran.sp", // 8080, privateKeyFileConfiguration); if (_ftpConfigurationModel.Timeout != null) { connectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, _ftpConfigurationModel.Timeout.Value); } return(new SftpClient(connectionInfo)); }
private void SetupFilesystem() { Debug.WriteLine("SetupFilesystem {0},{1},{2},{3}", Host, Port, Username, ConnectionType.ToString()); ProxyTypes pt = ProxyTypes.None; switch (ProxyType) { case 1: pt = ProxyTypes.Http; break; case 2: pt = ProxyTypes.Socks4; break; case 3: pt = ProxyTypes.Socks5; break; } int ProxyPort = 8080; var Proxy = ProxyHost; if (ProxyHost != null) { var s = ProxyHost.Split(':'); if (s.Length > 1) { Int32.TryParse(s[1], out ProxyPort); Proxy = s[0]; } } ConnectionInfo info; switch (ConnectionType) { case ConnectionType.Pageant: var agent = new PageantProtocol(); if (pt == ProxyTypes.None) { info = new AgentConnectionInfo(Host, Port, Username, agent); } else if (ProxyUser.Length > 0) { info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, agent); } else { info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, agent); } break; case ConnectionType.PrivateKey: if (pt == ProxyTypes.None) { info = new PrivateKeyConnectionInfo(Host, Port, Username, new PrivateKeyFile(PrivateKey, Passphrase)); } else if (ProxyUser.Length > 0) { info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, new PrivateKeyFile(PrivateKey, Passphrase)); } else { info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, new PrivateKeyFile(PrivateKey, Passphrase)); } break; default: if (pt == ProxyTypes.None) { info = new PasswordConnectionInfo(Host, Port, Username, Password); } else if (ProxyUser.Length > 0) { info = new PasswordConnectionInfo(Host, Username, Password, pt, Proxy, ProxyPort, ProxyUser, ProxyPass); } else { info = new PasswordConnectionInfo(Host, Port, Username, Password, pt, Proxy, ProxyPort); } break; } _connection = Settings.Default.UseNetworkDrive ? String.Format("\\\\{0}\\{1}\\{2}", info.Host, Root, info.Username) : Name; _filesystem = new SftpFilesystem(info, Root, _connection, Settings.Default.UseOfflineAttribute, false, (int)Settings.Default.AttributeCacheTimeout, (int)Settings.Default.DirContentCacheTimeout); Debug.WriteLine("Connecting..."); _filesystem.KeepAliveInterval = new TimeSpan(0, 0, 60); _filesystem.Connect(); }
/// <summary> /// Generate a ConnectionInfoObject using a SSH Key. /// </summary> /// <param name="computer"></param> /// <param name="port"></param> /// <param name="keyfile"></param> /// <param name="credential"></param> /// <param name="proxyserver"></param> /// <param name="proxytype"></param> /// <param name="proxyport"></param> /// <param name="proxycredential"></param> /// <returns></returns> public static PrivateKeyConnectionInfo GetKeyConnectionInfo(string computer, int port, string keyfile, PSCredential credential, string proxyserver, string proxytype, int proxyport, PSCredential proxycredential) { PrivateKeyConnectionInfo connectionInfo; var fullPath = Path.GetFullPath(keyfile); // Check if the file actually exists. if (File.Exists(fullPath)) { // Create the key object. PrivateKeyFile sshkey; if (credential.GetNetworkCredential().Password == "") { sshkey = new PrivateKeyFile(File.OpenRead(@fullPath)); } else { sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password); } if (proxyserver != "") { // Set the proper proxy type var ptype = ProxyTypes.Http; switch (proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } if (proxycredential.UserName != "") { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, ptype, proxyserver, proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, ptype, proxyserver, proxyport, proxycredential.UserName, proxycredential.GetNetworkCredential().Password, sshkey); } } else // Handle connection with no proxy server { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, sshkey); } } // file exists else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } return(connectionInfo); }
/// <summary> /// Connect to the remote servers, with the details from Profile /// </summary> /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param> public void Connect(bool reconnecting = false) { Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting); Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting"); if (FTP) { _ftpc = new FtpClient { Host = controller.Account.Host, Port = controller.Account.Port }; // Add accepted certificates _ftpc.ClientCertificates.AddRange(Certificates); if (controller.Account.Protocol == FtpProtocol.FTPS) { _ftpc.ValidateCertificate += (sender, x) => { var fingerPrint = new X509Certificate2(x.Certificate).Thumbprint; if (_ftpc.ClientCertificates.Count <= 0 && x.PolicyErrors != SslPolicyErrors.None) { Certificates.Add(x.Certificate); x.Accept = false; return; } // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint)) { Log.Write(l.Client, "Trusted: {0}", fingerPrint); x.Accept = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = fingerPrint, SerialNumber = x.Certificate.GetSerialNumberString(), Algorithm = x.Certificate.GetKeyAlgorithmParametersString(), ValidFrom = x.Certificate.GetEffectiveDateString(), ValidTo = x.Certificate.GetExpirationDateString(), Issuer = x.Certificate.Issuer }; // Prompt user to validate ValidateCertificate(null, e); x.Accept = e.IsTrusted; }; // Change Security Protocol if (controller.Account.FtpsMethod == FtpsMethod.Explicit) { _ftpc.EncryptionMode = FtpEncryptionMode.Explicit; } else if (controller.Account.FtpsMethod == FtpsMethod.Implicit) { _ftpc.EncryptionMode = FtpEncryptionMode.Implicit; } } _ftpc.Credentials = new NetworkCredential(controller.Account.Username, controller.Account.Password); try { _ftpc.Connect(); } catch (Exception exc) { // Since the ClientCertificates are added when accepted in ValidateCertificate, the first // attempt to connect will fail with an AuthenticationException. If this is the case, a // re-connect is attempted, this time with the certificates properly set. // This is a workaround to avoid storing Certificate files locally... if (exc is System.Security.Authentication.AuthenticationException && _ftpc.ClientCertificates.Count <= 0) { Connect(); } else { throw; } } } else // SFTP { ConnectionInfo connectionInfo; if (controller.isPrivateKeyValid) { connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password)); } else { connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password); } _sftpc = new SftpClient(connectionInfo); _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage); _sftpc.HostKeyReceived += (o, x) => { var fingerPrint = x.FingerPrint.GetCertificateData(); // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint)) { Log.Write(l.Client, "Trusted: {0}", fingerPrint); x.CanTrust = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = fingerPrint, Key = x.HostKeyName, KeySize = x.KeyLength.ToString() }; // Prompt user to validate ValidateCertificate(null, e); x.CanTrust = e.IsTrusted; }; _sftpc.Connect(); _sftpc.ErrorOccurred += (o, e) => { if (!isConnected) { Notifications.ChangeTrayText(MessageType.Nothing); } if (ConnectionClosed != null) { ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message }); } if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException) { Log.Write(l.Warning, "Permission denied error occured"); } if (e.Exception is Renci.SshNet.Common.SshConnectionException) { Reconnect(); } }; } controller.HomePath = WorkingDirectory; if (isConnected) { if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/")) { WorkingDirectory = controller.Paths.Remote; } } Log.Write(l.Debug, "Client connected sucessfully"); Notifications.ChangeTrayText(MessageType.Ready); if (Settings.IsDebugMode) { LogServerInfo(); } // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set SetKeepAlive(); }
protected override void ProcessRecord() { if (_keyfile.Equals("")) { //Username authentication //found a problem where domain name wasn't passed when using the format of {domain}\{username} //So, if the domain exists, prefix it properly //If using {username}@{domain}, this is not an issue string _UserNameMod = ""; if (_credential.GetNetworkCredential().Domain.Length > 0) { _UserNameMod = _credential.GetNetworkCredential().Domain + "\\" + _credential.GetNetworkCredential().UserName; } else { _UserNameMod = _credential.GetNetworkCredential().UserName; } var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_UserNameMod); foreach (var computer in _computername) { ConnectionInfo connectInfo; if (_proxyserver != "") { // Set the proper proxy type var ptype = ProxyTypes.Http; //WriteVerbose("A Proxy Server has been specified"); switch (_proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } var passconnectInfo = new PasswordAuthenticationMethod(_UserNameMod, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _UserNameMod); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, kIconnectInfo, passconnectInfo); } else { // Connection info for Keyboard Interactive var passconnectInfo = new PasswordAuthenticationMethod(_UserNameMod, _credential.GetNetworkCredential().Password); connectInfo = new ConnectionInfo(computer, _port, _UserNameMod, passconnectInfo, kIconnectInfo); } // Event Handler for interactive Authentication kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) { if (prompt.Request.Contains("Password")) { prompt.Response = _credential.GetNetworkCredential().Password; } } }; //Ceate instance of SSH Client with connection info var client = new SshClient(connectInfo); // Handle host key string computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); //WriteVerbose("Key algorithm of " + client.ConnectionInfo.CurrentHostKeyAlgorithm); //WriteVerbose("Key exchange alhorithm " + client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //WriteVerbose("Host key fingerprint: " + fingerPrint); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { //WriteVerbose("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } else { int choice; if (_acceptkey) { choice = 0; } else { var choices = new Collection <ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyManagement(); //WriteVerbose("Saving fingerprint " + fingerPrint + " for host " + computer); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Set Keepalive for connections client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval); // Connect to host using Connection info //WriteVerbose("Connecting to " + computer + " with user " + _UserNameMod); client.Connect(); WriteObject(SSHModuleHelper.AddToSSHSessionCollection(client, SessionState), true); } } else { //Use SSH Key for authentication WriteVerbose("Using SSH Key authentication for connection."); var fullPath = Path.GetFullPath(_keyfile); if (File.Exists(fullPath)) { foreach (var computer in _computername) { PrivateKeyConnectionInfo connectionInfo; if (_proxyserver != "") { // Set the proper proxy type var ptype = ProxyTypes.Http; //WriteVerbose("A Proxy Server has been specified"); switch (_proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } if (_credential.GetNetworkCredential().Password == "") { WriteVerbose("Using key with no passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath)); connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, sshkey); } else { WriteVerbose("Using key with passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password); if (_proxycredential.UserName == "") { connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, sshkey); } } } else { WriteVerbose("Using SSH Key authentication for connection."); if (_credential.GetNetworkCredential().Password == "") { WriteVerbose("Using key with no passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath)); connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey); } else { WriteVerbose("Using key with passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password); connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey); } } //Ceate instance of SSH Client with connection info var client = new SshClient(connectionInfo); // Handle host key string computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { //WriteVerbose("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } else { int choice; if (_acceptkey) { choice = 0; } else { var choices = new Collection <ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyManagement(); //WriteVerbose("Saving fingerprint " + fingerPrint + " for host " + computer); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Set Keepalive for connections client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval); // Connect to host using Connection info client.Connect(); WriteObject(SSHModuleHelper.AddToSSHSessionCollection(client, SessionState), true); } } else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } } }
static void Main(string[] args) { if (args.Length != 5) { ShowUsage(); } else { try { String Host = args[0]; String Port = args[1]; String Username = args[3]; String Password = null; String Keypath = null; if (args[2] == "plaintext") { Password = args[4]; var connectionInfo = new PasswordConnectionInfo(Host, Int32.Parse(Port), Username, Password); connectionInfo.Timeout = TimeSpan.FromSeconds(10); var ssh = new SshClient(connectionInfo); ssh.Connect(); Console.WriteLine("[+] Valid: " + Username + " " + Password); ssh.Disconnect(); ssh.Dispose(); } else if (args[2] == "keyfile") { Keypath = args[4]; FileStream keyFileStream = File.OpenRead(Keypath); byte[] byData = new byte[40]; keyFileStream.Read(byData, 0, 40); string keyData = System.Text.Encoding.Default.GetString(byData); if (keyData.Contains("OPENSSH")) { Console.WriteLine("[!] Bad format of key file. You should use puttygen to convert the format."); System.Environment.Exit(0); } keyFileStream.Seek(0, SeekOrigin.Begin); var connectionInfo = new PrivateKeyConnectionInfo(Host, Int32.Parse(Port), Username, new PrivateKeyFile(keyFileStream)); connectionInfo.Timeout = TimeSpan.FromSeconds(10); var ssh = new SshClient(connectionInfo); ssh.Connect(); Console.WriteLine("[+] Valid: " + Username + " " + Keypath); ssh.Disconnect(); ssh.Dispose(); } else { Console.WriteLine("[!] Wrong parameter"); System.Environment.Exit(0); } } catch (Renci.SshNet.Common.SshException ex) { Console.WriteLine("[!] " + ex.Message); } catch (Exception exception) { Console.WriteLine("[!] " + exception.Message); } } }
private static PrivateKeyConnectionInfo GetKeyConnectionInfo(string computer, int port, Stream keyFileStream, PSCredential credential, string proxyserver, string proxytype, int proxyport, PSCredential proxycredential) { PrivateKeyConnectionInfo connectionInfo; // Create the key object. PrivateKeyFile sshkey; if (credential.GetNetworkCredential().Password == String.Empty) { sshkey = new PrivateKeyFile(keyFileStream); } else { sshkey = new PrivateKeyFile(keyFileStream, credential.GetNetworkCredential().Password); } if (proxyserver != String.Empty) { // Set the proper proxy type var ptype = ProxyTypes.Http; switch (proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } if (proxycredential.UserName != String.Empty) { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, ptype, proxyserver, proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, ptype, proxyserver, proxyport, proxycredential.UserName, proxycredential.GetNetworkCredential().Password, sshkey); } } else // Handle connection with no proxy server { connectionInfo = new PrivateKeyConnectionInfo(computer, port, credential.UserName, sshkey); } return(connectionInfo); }
/// <summary> /// Connect to the remote servers, with the details from Profile /// </summary> /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param> public override void Connect(bool reconnecting = false) { Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting); Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting"); lock (ftpcLock) { ConnectionInfo connectionInfo; if (_controller.IsPrivateKeyValid) { connectionInfo = new PrivateKeyConnectionInfo(_controller.Account.Host, _controller.Account.Port, _controller.Account.Username, new PrivateKeyFile(_controller.Account.PrivateKeyFile, _controller.Account.Password)); } else { connectionInfo = new PasswordConnectionInfo(_controller.Account.Host, _controller.Account.Port, _controller.Account.Username, _controller.Account.Password); } _sftpc = new SftpClient(connectionInfo); _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage); _sftpc.HostKeyReceived += (o, x) => { var fingerPrint = x.FingerPrint.GetCertificateData(); // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint)) { Log.Write(l.Client, "Trusted: {0}", fingerPrint); x.CanTrust = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = fingerPrint, Key = x.HostKeyName, KeySize = x.KeyLength.ToString() }; // Prompt user to validate ValidateCertificate(null, e); x.CanTrust = e.IsTrusted; }; _sftpc.Connect(); _sftpc.ErrorOccurred += (o, e) => { if (!isConnected) { Notifications.ChangeTrayText(MessageType.Nothing); } if (ConnectionClosed != null) { ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message }); } if (e.Exception is SftpPermissionDeniedException) { Log.Write(l.Warning, "Permission denied error occured"); } if (e.Exception is SshConnectionException) { Reconnect(); } }; } _controller.HomePath = WorkingDirectory; if (isConnected) { if (!string.IsNullOrWhiteSpace(_controller.Paths.Remote) && !_controller.Paths.Remote.Equals("/")) { WorkingDirectory = _controller.Paths.Remote; } if (connectionState == null) { connectionState = new BackgroundWorker(); connectionState.DoWork += new DoWorkEventHandler((o, e) => { while (true) { if (!isConnected) { // RECONNECT //_controller.Client.Reconnect(); } Thread.Sleep(5000); } }); connectionState.RunWorkerAsync(); } } Log.Write(l.Debug, "Client connected sucessfully"); Notifications.ChangeTrayText(MessageType.Ready); if (Settings.IsDebugMode) { LogServerInfo(); } // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set SetKeepAlive(); }
public override WebResponse GetResponse() { NetworkCredential cred = (m_cred as NetworkCredential); string strUser = ((cred != null) ? cred.UserName : null); string strPassword = ((cred != null) ? cred.Password : null); BaseClient m_Client = null; int l_port = m_uri.Port == -1 ? 22 : m_uri.Port; Uri uriTo = null; if (m_strMethod == KeePassLib.Serialization.IOConnection.WrmMoveFile) { uriTo = new Uri(m_whcHeaders.Get( IOConnection.WrhMoveFileTo)); } MemoryStream reqStream = null; if (m_reqBody.Count > 0) { reqStream = new MemoryStream(m_reqBody.ToArray()); } ConnectionInfo n_con_info; if (File.Exists(m_props.Get("SSHKey"))) { using (FileStream keyStream = new FileStream(m_props.Get("SSHKey"), FileMode.Open)) { PrivateKeyFile v_keyauth; if (strPassword == null) { v_keyauth = new PrivateKeyFile(keyStream); } else { v_keyauth = new PrivateKeyFile(keyStream, strPassword); } n_con_info = new PrivateKeyConnectionInfo(m_uri.Host, l_port, strUser, v_keyauth); } } else if (!String.IsNullOrWhiteSpace(m_props.Get("SSHKey"))) { string keyString = m_props.Get("SSHKey").Replace("\\n", "\n"); using (MemoryStream keyStream = new MemoryStream(Encoding.ASCII.GetBytes(keyString))) { PrivateKeyFile v_keyauth; if (strPassword == null) { v_keyauth = new PrivateKeyFile(keyStream); } else { v_keyauth = new PrivateKeyFile(keyStream, strPassword); } n_con_info = new PrivateKeyConnectionInfo(m_uri.Host, l_port, strUser, v_keyauth); } } else if (String.IsNullOrWhiteSpace(m_props.Get("SSHKey")) && String.IsNullOrWhiteSpace(strPassword)) { // No password, no keyfile, try pageant PageantProtocol agent = new PageantProtocol(); n_con_info = new AgentConnectionInfo(m_uri.Host, l_port, strUser, agent); } else { KeyboardInteractiveAuthenticationMethod v_kauth = new KeyboardInteractiveAuthenticationMethod(strUser); v_kauth.AuthenticationPrompt += SftpWebRequest_AuthenticationPrompt; PasswordAuthenticationMethod v_pauth = new PasswordAuthenticationMethod(strUser, strPassword); n_con_info = new ConnectionInfo(m_uri.Host, l_port, strUser, v_pauth, v_kauth); } m_Client = new SftpClient(n_con_info); //Set timeout to reasonable setting of 30 seconds for default. int connectionTimeout = 30000; if (m_props.Get("SSHTimeout") != null) { int.TryParse(m_props.Get("SSHTimeout"), out connectionTimeout); } m_Client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, connectionTimeout); if (m_props.Get("HostKey") != null) { string[] v_ssh_dss_parts = m_props.Get("HostKey").Split(':'); if (v_ssh_dss_parts.Length != 16) { throw new Exception("Input incorrect host fingerprint. Check it. Must look like: 12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef"); } List <byte> v_ssh_dss_parts_b = new List <byte>(); foreach (string str in v_ssh_dss_parts) { try { v_ssh_dss_parts_b.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)); } catch (Exception) { throw new Exception("Input incorrect host fingerprint. Check it. Must look like: 12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef"); } } m_fingerprint = v_ssh_dss_parts_b.ToArray(); m_Client.HostKeyReceived += M_Client_HostKeyReceived; } return(new SftpWebResponse(m_Client, m_strMethod, m_uri, uriTo, reqStream)); }
public override async Task Connect(bool reconnecting = false) { Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting); Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting"); ConnectionInfo connectionInfo; if (Controller.IsPrivateKeyValid) { connectionInfo = new PrivateKeyConnectionInfo(Controller.Account.Host, Controller.Account.Port, Controller.Account.Username, new PrivateKeyFile(Controller.Account.PrivateKeyFile, Controller.Account.Password)); } else { connectionInfo = new PasswordConnectionInfo(Controller.Account.Host, Controller.Account.Port, Controller.Account.Username, Controller.Account.Password); } connectionInfo.Encoding = this.Charset; connectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage); _sftpc = new Renci.SshNet.SftpClient(connectionInfo); _sftpc.HostKeyReceived += (o, x) => { var fingerPrint = x.FingerPrint.GetCertificateData(); // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint)) { Log.Write(l.Client, "Trusted: {0}", fingerPrint); x.CanTrust = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = fingerPrint, Key = x.HostKeyName, KeySize = x.KeyLength.ToString() }; // Prompt user to validate ValidateCertificate?.Invoke(null, e); x.CanTrust = e.IsTrusted; }; var caughtException = default(Exception); await Task.Run(() => { try { _sftpc.Connect(); } catch (SshAuthenticationException ex) { ex.LogException(); caughtException = new AuthenticationException(ex.Message, ex.InnerException); } catch (SshConnectionException ex) { ex.LogException(); caughtException = new CertificateDeclinedException(ex.Message, ex.InnerException); } catch (Exception ex) { ex.LogException(); caughtException = ex; } }); if (caughtException != default(Exception)) { throw caughtException; } _sftpc.ErrorOccurred += async(o, e) => { if (!IsConnected) { Notifications.ChangeTrayText(MessageType.Nothing); } OnConnectionClosed(new ConnectionClosedEventArgs { Text = e.Exception.Message }); if (e.Exception is SftpPermissionDeniedException) { Log.Write(l.Warning, "Permission denied error occured"); } if (e.Exception is SshConnectionException) { await Reconnect(); } }; Controller.HomePath = WorkingDirectory; if (IsConnected) { if (!string.IsNullOrWhiteSpace(Controller.Paths.Remote) && !Controller.Paths.Remote.Equals("/")) { WorkingDirectory = Controller.Paths.Remote; } } Log.Write(l.Debug, "Client connected sucessfully"); Notifications.ChangeTrayText(MessageType.Ready); if (Settings.IsDebugMode) { LogServerInfo(); } }
/// <summary> /// Connect to the remote servers, with the details from Profile /// </summary> /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param> public void Connect(bool reconnecting = false) { Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting); Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting"); if (FTP) { _ftpc = new FtpClient(controller.Account.Host, controller.Account.Port); _ftpc.ConnectionClosed += (o, e) => { Notifications.ChangeTrayText(MessageType.Nothing); if (ConnectionClosed != null) { ConnectionClosed(null, new ConnectionClosedEventArgs { Text = _ftpc.LastResponse.Text }); } Reconnect(); }; if (controller.Account.Protocol == FtpProtocol.FTPS) { _ftpc.ValidateServerCertificate += (sender, x) => { // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(x.Certificate.Thumbprint)) { Log.Write(l.Client, "Trusted: {0}", x.Certificate.Thumbprint); x.IsCertificateValid = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = x.Certificate.Thumbprint, SerialNumber = x.Certificate.SerialNumber, Algorithm = x.Certificate.SignatureAlgorithm.FriendlyName, ValidFrom = x.Certificate.NotBefore.ToString("MM/dd/yy"), ValidTo = x.Certificate.NotAfter.ToString("MM/dd/yy"), Issuer = x.Certificate.IssuerName.Name }; ValidateCertificate(null, e); x.IsCertificateValid = e.IsTrusted; }; // Change Security Protocol if (controller.Account.FtpsMethod == FtpsMethod.Explicit) { _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit; } else if (controller.Account.FtpsMethod == FtpsMethod.Implicit) { _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit; } } try { _ftpc.Open(controller.Account.Username, controller.Account.Password); } catch (Exception) { if (controller.Account.FtpsMethod == FtpsMethod.None) { throw; } bool connected = false; // Try connecting with the other available Security Protocols foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol))) { if ((controller.Account.FtpsMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit")) || (controller.Account.FtpsMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit"))) { Log.Write(l.Debug, "Testing with {0}", p.ToString()); try { _ftpc.Close(); _ftpc.SecurityProtocol = p; _ftpc.Open(controller.Account.Username, controller.Account.Password); } catch (Exception exe) { Log.Write(l.Warning, "Unable to connect: {0}", exe.GetType().ToString()); continue; } connected = true; controller.Account.FtpSecurityProtocol = p; break; } } if (!connected) { Notifications.ChangeTrayText(MessageType.Nothing); throw; } } } else // SFTP { ConnectionInfo connectionInfo; if (controller.isPrivateKeyValid) { connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password)); } else { connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password); } _sftpc = new SftpClient(connectionInfo); _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage); _sftpc.HostKeyReceived += (o, x) => { var fingerPrint = x.FingerPrint.GetCertificateData(); // if ValidateCertificate handler isn't set, accept the certificate and move on if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint)) { Log.Write(l.Client, "Trusted: {0}", fingerPrint); x.CanTrust = true; return; } var e = new ValidateCertificateEventArgs { Fingerprint = fingerPrint, Key = x.HostKeyName, KeySize = x.KeyLength.ToString() }; ValidateCertificate(null, e); x.CanTrust = e.IsTrusted; }; _sftpc.Connect(); _sftpc.ErrorOccurred += (o, e) => { if (!isConnected) { Notifications.ChangeTrayText(MessageType.Nothing); } if (ConnectionClosed != null) { ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message }); } if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException) { Log.Write(l.Warning, "Permission denied error occured"); } if (e.Exception is Renci.SshNet.Common.SshConnectionException) { Reconnect(); } }; } controller.HomePath = WorkingDirectory; if (isConnected) { if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/")) { WorkingDirectory = controller.Paths.Remote; } } Log.Write(l.Debug, "Client connected sucessfully"); Notifications.ChangeTrayText(MessageType.Ready); if (Settings.IsDebugMode) { LogServerInfo(); } }
/// <summary> /// Establishes the connection to the server, using the specified <paramref name="terminal"/> for connection initialization (authentication, etc.). /// </summary> /// <param name="terminal">The terminal to use for connection initialization.</param> /// <returns>A value indicating whether the connection was successfully established.</returns> /// <exception cref="ObjectDisposedException">The connection object is already disposed.</exception> /// <exception cref="InvalidOperationException">The connection object is currently connected.</exception> public async Task <bool> ConnectAsync(IConnectionInitializingTerminal terminal) { this.CheckDisposed(); this.MustBeConnected(false); Lazy <string> username = new Lazy <string>(() => { if (string.IsNullOrEmpty(this.connectionData.Username)) { return(terminal.ReadLineAsync("Username: "******"Username: "******"Password: "******"Password expired for user " + e.Username); do { var readNewPassword1Task = terminal.ReadLineAsync("New password: "******"Repeat new password: "******"Performing keyboard-interactive authentication."); } if (!string.IsNullOrEmpty(e.Instruction)) { terminal.WriteLine(e.Instruction); } foreach (var prompt in e.Prompts) { var readLineTask = terminal.ReadLineAsync(prompt.Request, echo: prompt.IsEchoed); readLineTask.Wait(); prompt.Response = readLineTask.Result; } }; connectionInfo = keyboardInteractiveConnectionInfo; break; case Model.AuthenticationType.PrivateKey: if (this.privateKeyData == null) { throw new Exception("Private Key '" + connectionData.PrivateKeyName + "' not found. Please correct the authentication details of the connection."); } PrivateKeyFile privateKey; try { using (var privateKeyStream = new MemoryStream(privateKeyData.Data)) { privateKey = new PrivateKeyFile(privateKeyStream); } } catch (SshPassPhraseNullOrEmptyException) { privateKey = null; } // In the normal PrivateKey authentication there is only a connection-local PrivateKeyAgent. var localPprivateKeyAgent = new Lazy <PrivateKeyAgent>(() => { terminal.WriteLine("Performing authentication with Private Key '" + connectionData.PrivateKeyName + "'."); if (privateKey == null) { string privateKeyPassword = terminal.ReadLineAsync("Private Key password: "******"Wrong Private Key password, please try again.", ex); } } } var pka = new PrivateKeyAgent(); pka.AddSsh2(privateKey.HostKey, connectionData.PrivateKeyName); return(pka); }); var privateKeyConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, localPprivateKeyAgent); connectionInfo = privateKeyConnectionInfo; break; case AuthenticationType.PrivateKeyAgent: if (PrivateKeyAgentManager.PrivateKeyAgent.ListSsh2().Count == 0) { throw new SshAuthenticationException("The private key agent doesn't contain any private keys."); } var globalPrivateKeyAgent = new Lazy <PrivateKeyAgent>(() => { var pka = PrivateKeyAgentManager.PrivateKeyAgent; terminal.WriteLine("Performing private key agent authentication."); return(pka); }); var privateKeyAgentConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, globalPrivateKeyAgent); connectionInfo = privateKeyAgentConnectionInfo; if (connectionData.PrivateKeyAgentForwarding == true) { forwardedPrivateKeyAgent = globalPrivateKeyAgent; terminal.WriteLine("Agent forwarding is enabled."); } break; default: throw new NotImplementedException("Authentication method '" + this.connectionData.Authentication + "' not implemented."); } connectionInfo.AuthenticationBanner += (sender, e) => { terminal.WriteLine(e.BannerMessage.Replace("\n", "\r\n")); }; this.client = new SshClient(connectionInfo); this.client.HostKeyReceived += (s, e) => { string fingerprint = string.Join(":", e.FingerPrint.Select(b => b.ToString("x2"))); bool trustHostKey = true; bool storeHostKey = false; string newHostKey = string.Join(null, e.HostKey.Select(b => b.ToString("x2"))); if (oldHostKey == null) { terminal.WriteLine("Remote Terminal has not yet cached a host key for this server."); terminal.WriteLine("Host key's fingerprint: " + fingerprint); terminal.WriteLine("Please make sure the fingerprint matches the server's actual host key."); trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?"); if (trustHostKey) { storeHostKey = QueryYesNo(terminal, "Do you want to store this host key in the cache?"); } } else if (oldHostKey != newHostKey) { terminal.WriteLine("POSSIBLE SECURITY BREACH DETECTED!"); terminal.WriteLine("Remote Terminal has cached another host key for this server."); terminal.WriteLine("This could mean one of two things:"); terminal.WriteLine(" * the server's host key was changed by an administrator"); terminal.WriteLine(" * another computer is trying to intercept your connection"); terminal.WriteLine("Host key's new fingerprint: " + fingerprint); trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?"); if (trustHostKey) { storeHostKey = QueryYesNo(terminal, "Do you want to update the cache with the new host key?"); } } e.CanTrust = trustHostKey; if (trustHostKey) { oldHostKey = newHostKey; } if (storeHostKey) { HostKeysDataSource.AddOrUpdate(this.connectionData.Host, this.connectionData.Port, newHostKey); } }; this.client.ConnectionInfo.Timeout = new TimeSpan(0, 15, 0); await Task.Run(() => { this.client.Connect(); }); this.client.ConnectionInfo.Timeout = new TimeSpan(0, 1, 0); var terminalModes = new Dictionary <TerminalModes, uint>(); terminalModes[TerminalModes.TTY_OP_ISPEED] = 0x00009600; terminalModes[TerminalModes.TTY_OP_OSPEED] = 0x00009600; this.stream = this.client.CreateShellStream(terminal.TerminalName, (uint)terminal.Columns, (uint)terminal.Rows, 0, 0, 1024, forwardedPrivateKeyAgent.Value, terminalModes.ToArray()); this.reader = new StreamReader(this.stream); this.writer = new StreamWriter(this.stream); this.writer.AutoFlush = true; return(true); } catch (SshConnectionException ex) { terminal.WriteLine(ex.Message); retry = false; } catch (SshAuthenticationException ex) { terminal.WriteLine(ex.Message); if (connectionData.Authentication == AuthenticationType.PrivateKeyAgent) { terminal.WriteLine("Please load the necessary private key(s) into the private key agent."); retry = false; } else { retry = true; } } catch (Exception ex) { terminal.WriteLine(ex.Message); retry = false; } if (!retry || numRetries++ > 5) { return(false); } }while (true); }