Supports RSA and DSA private key in both OpenSSH and ssh.com format.
OpenSSH
ssh.com
The following encryption algorithms are supported: DES-EDE3-CBC DES-EDE3-CFB DES-CBC AES-128-CBC AES-192-CBC AES-256-CBC
public SftpUploader(AppConfig conf) { this.config = conf; if (config.sftpEnabled) { AuthenticationMethod[] auths = new AuthenticationMethod[1]; if (String.IsNullOrWhiteSpace(config.sftpPrivateKeyPath)) { auths[0] = new PasswordAuthenticationMethod(config.sftpUsername, Utils.GetBytes(config.sftpPassword)); } else { try { PrivateKeyFile pkf = null; if (string.IsNullOrEmpty(config.sftpPassword)) { pkf = new PrivateKeyFile(config.sftpPrivateKeyPath); } else { pkf = new PrivateKeyFile(config.sftpPrivateKeyPath, config.sftpPassword); } auths[0] = new PrivateKeyAuthenticationMethod(config.sftpUsername, pkf); } catch (IOException) { Log.Error("Unable to read private key file: " + config.sftpPrivateKeyPath); return; } } connInfo = new ConnectionInfo(config.sftpRemoteServer, config.sftpUsername, auths); } }
public void Connect(ConnectionSettings settings, int terminalCols, int terminalRows) { Settings = settings; if (dataThread != null) throw new InvalidOperationException("Already connecting to a server."); dataThread = new Thread(() => { #if USE_LIBSSHNET var connection = new LibSshNetConnection(serverAddress, username, (authentications.First() as PasswordAuthentication).Password); stream = connection.GetStream(); #else try { var authentications = new List<AuthenticationMethod>(); if (!string.IsNullOrEmpty(settings.KeyFilePath)) { var privateKeyFile = new PrivateKeyFile(settings.KeyFilePath, settings.KeyFilePassphrase); authentications.Add(new PrivateKeyAuthenticationMethod(settings.Username, privateKeyFile)); } authentications.Add(new PasswordAuthenticationMethod(settings.Username, settings.Password)); ConnectionInfo connectionInfo = new ConnectionInfo(settings.ServerAddress, settings.ServerPort, settings.Username, authentications.ToArray()); Client = new SshClient(connectionInfo); Client.Connect(); Client.KeepAliveInterval = TimeSpan.FromSeconds(20); Stream = Client.CreateShellStream("xterm-256color", (uint) terminalCols, (uint) terminalRows, 0, 0, 1000); if (Connected != null) Connected(this, EventArgs.Empty); } catch (Exception ex) { ConnectionFailedEventArgs args = null; if (ex is Renci.SshNet.Common.SshPassPhraseNullOrEmptyException || ex is InvalidOperationException) args = new ConnectionFailedEventArgs(ConnectionError.PassphraseIncorrect, ex.Message); else if (ex is SocketException) args = new ConnectionFailedEventArgs(ConnectionError.NetError, ex.Message); else if (ex is Renci.SshNet.Common.SshAuthenticationException) args = new ConnectionFailedEventArgs(ConnectionError.AuthenticationError, ex.Message); else throw; if (Failed != null) Failed(this, args); } #endif }); dataThread.Name = "Data Thread"; dataThread.IsBackground = true; dataThread.Start(); }
public MainWindow() { InitializeComponent(); // Updates UI elements with possible changes in Branch or Server lists UpdateServerLists(); //Prepares for loading private key and shows window var loadKeyWindow = new LoadKey(); loadKeyWindow.ShowDialog(); try { var keyFile = new PrivateKeyFile(loadKeyWindow.KeyFilePath, loadKeyWindow.Password); _dansSsh = new SshClient("dans-app", loadKeyWindow.UserName, keyFile); } catch { MessageBox.Show("Invalid credentials"); Close(); } }
protected override void ProcessRecord() { if (keyfile.Equals("")) { //########################################### //### Connect using Username and Password ### //########################################### ConnectionInfo connectInfo; var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName); foreach (var computer in computername) { if (proxyserver != "") { // Set the proper proxy type var ptype = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, port, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, proxycredential.GetNetworkCredential().UserName, proxycredential.GetNetworkCredential().Password, KIconnectInfo, PassconnectInfo); } else { WriteVerbose("Using Username and Password authentication for connection."); // Connection info for Keyboard Interactive var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName, PassconnectInfo, KIconnectInfo); //} // End foroeach computer } // 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; } }; try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectInfo); // Handle host key 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); //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm); //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint); if (SSHHostKeys.ContainsKey(computer)) { if (SSHHostKeys[computer] == FingerPrint) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer); } } else { int choice; if (acceptkey) { choice = 0; } else { Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>(); choices.Add(new ChoiceDescription("Y")); choices.Add(new ChoiceDescription("N")); choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyMng(); //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer); keymng.SetKey(computer, 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(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } } else { //########################## //### Connect using Keys ### //########################## 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 = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } 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); if (proxycredential.UserName == "") { connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, 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); } } try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectionInfo); // Handle host key 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); //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm); //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint); if (SSHHostKeys.ContainsKey(computer)) { if (SSHHostKeys[computer] == FingerPrint) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer); } } else { int choice; if (acceptkey) { choice = 0; } else { Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>(); choices.Add(new ChoiceDescription("Y")); choices.Add(new ChoiceDescription("N")); choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyMng(); //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer); keymng.SetKey(computer, 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(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } // for each computer } // file exists else { throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found."); } } }
public void ConnectionTests(int count, int pause) { var regex = new Regex(@"^\d+\s[\d\w:]+\s[\d\.]+\s.+?\s.+?$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline); Renci.SshNet.SshClient client; { var path = Concrete.Client.FixPath(_config.PathToPrivateKey !); using var keyFile = new Renci.SshNet.PrivateKeyFile(path); client = new Renci.SshNet.SshClient(_config.Host, _config.Port, _config.Username, keyFile); } client.Connect(); while (count-- > 0) { string output; { using var command = client.CreateCommand("cat /tmp/dhcp.leases", Encoding.UTF8); command.CommandTimeout = TimeSpan.FromSeconds(1); output = command.Execute(); } Assert.NotNull(output); Assert.NotEmpty(output); Assert.Matches(regex, output); Thread.Sleep(pause); } client.Disconnect(); client.Dispose(); }
public MySqlSshDatabaseConnection(string host, int port, string username, string privateKeyPath, string privateKeyPassPhrase, string mySqlHost, int mySqlPort, string mySqlUsername, string mySqlPassword, string mySqlDatabase) { _mySqlHost = mySqlHost; _mySqlPort = mySqlPort; var privateKeyFile = new PrivateKeyFile(privateKeyPath, privateKeyPassPhrase); _client = new SshClient(host, port, username, privateKeyFile); var databaseConnectionString = BuildConnectionString(LocalHost, LocalPort, mySqlUsername, mySqlPassword, mySqlDatabase); _connection = new MySqlConnection(databaseConnectionString); }
/// <summary> /// Initializes a new instance of the <see cref="SftpUploader"/> class /// with the specified <see cref="SftpClient"/>. /// </summary> /// <param name="info">An object containing the connection info.</param> /// <param name="timeout"> /// The time in milliseconds to wait for a response from the server. /// </param> public SftpUploader(ConnectionInfo info, int timeout = 30000) { try { var keyFile = new PrivateKeyFile(info.PrivateKeyPath); client = new SftpClient(info.Host, info.Port, info.UserName, keyFile); } catch (Exception ex) { Trace.WriteLine(ex); } if (client == null) { client = new SftpClient(info.Host, info.Port, info.UserName, info.Password); } client.ConnectionInfo.Timeout = TimeSpan.FromMilliseconds(timeout); }
public Client(IOptions <Config> options) { var config = Guard.Argument(options).NotNull().Wrap(o => o.Value).NotNull().Value; if (!string.IsNullOrWhiteSpace(config.Password)) { _sshClient = new(config.Host, config.Port, config.Username, config.Password); } else if (!string.IsNullOrWhiteSpace(config.PathToPrivateKey)) { var path = FixPath(config.PathToPrivateKey); var privateKeyFileInfo = new FileInfo(path); using var stream = privateKeyFileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read); using var privateKeyFile = new Renci.SshNet.PrivateKeyFile(stream); _sshClient = new(config.Host, config.Port, config.Username, privateKeyFile); } else { _sshClient = new(config.Host, config.Port, config.Username); } }
/// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this._disposed) { // Note disposing has been done. _disposed = true; // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { if (_privateKeyFile != null) { _privateKeyFile.Dispose(); } } // Call the appropriate methods to clean up // unmanaged resources here. _privateKeyFile = null; } }
/// <summary> /// An event handler called when connecting to the SSH server. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="e">The event arguments.</param> private void OnConnect(object sender, EventArgs e) { // If the username is empty, show a message and return. if (string.IsNullOrWhiteSpace(this.textBoxUsername.Text)) { MessageBox.Show("The user name cannot be empty.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // The connection info. ConnectionInfo connectionInfo = null; try { // Create a new connection info. if (this.radioPasswordAuthentication.Checked) { // Create a password connection info. connectionInfo = new PasswordConnectionInfo(this.textBoxServer.Text, this.textBoxUsername.Text, this.secureTextBoxPassword.SecureText.ConvertToUnsecureString()); } else if (this.radioKeyAuthentication.Checked) { // If the private key is null, show a message and return. if (null == this.sshKey) { MessageBox.Show("The key cannot be empty for the selected authentication method.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Create a memory stream with the key data. using (MemoryStream memoryStream = new MemoryStream(this.sshKey)) { // Create the private key file. using (PrivateKeyFile keyFile = new PrivateKeyFile(memoryStream)) { // Create a key connection info. connectionInfo = new PrivateKeyConnectionInfo(this.textBoxServer.Text, this.textBoxUsername.Text, keyFile); } } } else { // If no authentication type is selected, do nothing. MessageBox.Show("You must select a method of authentication.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } catch (Exception exception) { // Show an error dialog if an exception is thrown. MessageBox.Show("Cannot connect to the SSH server. {0}".FormatWith(exception.Message), "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { // Connect to the SSH server. this.Connect(connectionInfo); } catch (SshException exception) { // Show an error dialog if an exception is thrown. MessageBox.Show("Cannot connect to the SSH server. {0}".FormatWith(exception.Message), "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }
/// <summary> /// Represents private key information. /// </summary> /// <param name="privateKey">The private key file used for authentication.</param> /// <param name="privateKeyFilePassword">The private key file password.</param> internal PrivateKeyFile(string privateKey, string privateKeyFilePassword) { _privateKey = privateKey; _privateKeyPassword = privateKeyFilePassword; _privateKeyFile = new Renci.SshNet.PrivateKeyFile(privateKey, privateKeyFilePassword); }
protected override void ProcessRecord() { if (keyfile.Equals("")) { //########################################### //### Connect using Username and Password ### //########################################### if (proxyserver != "") { // Set the proper proxy type var ptype = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName); var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); foreach (var computer in computername) { WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); var connectInfo = new ConnectionInfo(computer, port, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, proxycredential.GetNetworkCredential().UserName, proxycredential.GetNetworkCredential().Password, KIconnectInfo, PassconnectInfo); // 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; } }; try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectInfo); // Connect to host using Connection info Client.Connect(); WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } // End foroeac computer } else { WriteVerbose("Using Username and Password authentication for connection."); // Connection info for Keyboard Interactive var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName); var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); foreach (var computer in computername) { WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); var connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName, 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; } }; try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectInfo); // Connect to host using Connection info Client.Connect(); WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } // End foroeach computer } } else { //########################## //### Connect using Keys ### //########################## WriteVerbose("Using SSH Key authentication for connection."); var fullPath = Path.GetFullPath(keyfile); if (proxyserver != "") { // Set the proper proxy type var ptype = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } if (File.Exists(fullPath)) { foreach (var computer in computername) { PrivateKeyConnectionInfo connectionInfo; 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); if (proxycredential.UserName == "") { connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, proxycredential.GetNetworkCredential().UserName, proxycredential.GetNetworkCredential().Password, sshkey); } } try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectionInfo); // Connect to host using Connection info Client.Connect(); WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } } } else { WriteVerbose("Using SSH Key authentication for connection."); if (File.Exists(fullPath)) { foreach (var computer in computername) { PrivateKeyConnectionInfo connectionInfo; 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); } try { //Ceate instance of SSH Client with connection info var Client = new SshClient(connectionInfo); // Connect to host using Connection info Client.Connect(); WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true); } catch (Exception ex) { throw ex; } } } } } }
/// <summary> /// GetSshClient /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="ppkFilename"></param> /// <returns></returns> public static SshClient GetSshClient(string host, string username, string password, string ppkFilename) { var ppkFile = new PrivateKeyFile(ppkFilename); var client = new SshClient(host, username, ppkFile); return client; }
static Keys() { string basePath = Path.Combine(Path.GetDirectoryName(new Uri(typeof(Keys).Assembly.CodeBase).LocalPath), "TestData"); PublicKeys = SshRsaModule.loadPublicKeys(Path.Combine(basePath, "authorized_keys")); PrivateKey = new PrivateKeyFile(Path.Combine(basePath, "test_rsa"), "test"); }
private void Start() { iProxyServer.Start(this); XElement body = new XElement("getaddress"); body.Add(new XElement("uidnode", iDeviceUdn)); XElement tree = CallWebService("getaddress", body.ToString()); if (tree == null) return; XElement error = tree.Element("error"); if (error != null) { Logger.ErrorFormat("Remote access method {0} failed with error {1}.", "getaddress", error.Value); return; } XElement successElement = tree.Element("success"); XElement sshServerElement = successElement.Element("sshserver"); iSshServerHost = sshServerElement.Element("address").Value; iSshServerPort = Convert.ToInt32(sshServerElement.Element("port").Value); XElement portForwardElement = successElement.Element("portforward"); iPortForwardAddress = portForwardElement.Element("address").Value; iPortForwardPort = (uint)Convert.ToInt32(portForwardElement.Element("port").Value); if (Environment.OSVersion.Platform.ToString() == "Unix") { iSshClientNative = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Hidden, FileName = "ssh", Arguments = String.Format( "-i {0} -p {1} -R {2}:{3}:{4}:{5} -N {6}@{7} -o StrictHostKeyChecking=no", FileFullName(kFilePrivateKey), iSshServerPort, iPortForwardAddress, iPortForwardPort, iNetworkAdapter, iProxyServer.Port, kSshServerUserName, iSshServerHost) }; iSshClientNative.StartInfo = startInfo; iSshClientNative.Start(); } else { PrivateKeyFile pkf = new PrivateKeyFile(FileFullName(kFilePrivateKey)); iSshClient = new SshClient(iSshServerHost, iSshServerPort, kSshServerUserName, pkf); iSshClient.Connect(); Logger.InfoFormat("Connected to ssh server at {0}:{1}", iSshServerHost, iSshServerPort); iForwardedPortRemote = new ForwardedPortRemote(iPortForwardAddress, iPortForwardPort, iNetworkAdapter, iProxyServer.Port); iSshClient.AddForwardedPort(iForwardedPortRemote); iForwardedPortRemote.Start(); } Logger.InfoFormat("Forwarded remote port {0}:{1} to {2}:{3}", iPortForwardAddress, iPortForwardPort, iNetworkAdapter, iProxyServer.Port); iConnectionCheckTimer.Enabled = true; }
private void connectButton_Click(object sender, EventArgs e) { AuthenticationMethod am = null; if (noAuthRadioButton.Checked) { am = new KeyboardInteractiveAuthenticationMethod(userNameTextBox.Text); } if (passwordRadioButton.Checked) { am = new PasswordAuthenticationMethod( userNameTextBox.Text, passwordTextBox.Text); } if (keyRadioButton.Checked) { PrivateKeyFile pkf; if (passphraseTextBox.Text == "") { pkf = new PrivateKeyFile(fileNameLabel.Text); } else { pkf = new PrivateKeyFile(fileNameLabel.Text, passphraseTextBox.Text); } am = new PrivateKeyAuthenticationMethod( userNameTextBox.Text, new PrivateKeyFile[] {pkf}); } // set connection info this.connectionInfo = new ConnectionInfo( serverTextBox.Text, Int32.Parse(portTextBox.Text), userNameTextBox.Text, new AuthenticationMethod[] {am}); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); }
/// <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> /// Occurs when an item in the list of available keys is clicked. /// </summary> /// <param name="sender">The object where the event handler is attached.</param> /// <param name="e">The event data.</param> private async void Keys_ItemClick(object sender, ItemClickEventArgs e) { PrivateKeyData privateKeyData = e.ClickedItem as PrivateKeyData; if (e.ClickedItem == null) { return; } MessageDialog dlg = null; try { PrivateKeyFile privateKey; using (var privateKeyStream = new MemoryStream(privateKeyData.Data)) { privateKey = new PrivateKeyFile(privateKeyStream); } var addedAgentKey = PrivateKeyAgentManager.PrivateKeyAgent.AddSsh2(privateKey.HostKey, privateKeyData.FileName); if (addedAgentKey != null) { this.AgentKeys.Add(addedAgentKey); } else { dlg = new MessageDialog("This private key is already loaded into the agent.", "Error loading private key"); } this.SetEmptyHintVisibilities(); } catch (SshPassPhraseNullOrEmptyException) { var clickedItem = ((ListViewBase)sender).ContainerFromItem(e.ClickedItem); this.loadKeyPasswordErrorTextBlock.Visibility = Visibility.Collapsed; this.loadKeyPasswordBox.Tag = e.ClickedItem; Flyout.GetAttachedFlyout((ListViewBase)this.keysGridView).ShowAt((FrameworkElement)clickedItem); this.loadKeyPasswordBox.Focus(FocusState.Programmatic); } catch (SshException ex) { dlg = new MessageDialog(ex.Message, "Error loading private key"); } if (dlg != null) { await dlg.ShowAsync(); } }
public bool Connect() { if (client == null) { if (!string.IsNullOrEmpty(Account.Keypath) && File.Exists(Account.Keypath)) { PrivateKeyFile keyFile; if (string.IsNullOrEmpty(Account.Passphrase)) { keyFile = new PrivateKeyFile(Account.Keypath); } else { keyFile = new PrivateKeyFile(Account.Keypath, Account.Passphrase); } client = new SftpClient(Account.Host, Account.Port, Account.Username, keyFile); } else if (!string.IsNullOrEmpty(Account.Password)) { client = new SftpClient(Account.Host, Account.Port, Account.Username, Account.Password); } if (client != null) { client.BufferSize = (uint)BufferSize; } } if (client != null && !client.IsConnected) { client.Connect(); } return IsConnected; }
/// <summary> /// Runs the commands on the PlanetLab node at the specified index. /// </summary> /// <param name="state">The state.</param> /// <param name="index">The node state index.</param> private void OnRunNode(PlManagerState state, int index) { lock (state.Sync) { // If the operation has been canceled, return. if (state.IsStopped) return; // Get the node state. PlManagerNodeState nodeState = state.GetNode(index); // Execute the secure shell connection on the thread pool. ThreadPool.QueueUserWorkItem((object threadState) => { // Raise a node started event. if (null != this.NodeStarted) this.NodeStarted(this, new PlManagerNodeEventArgs(state, nodeState.Node)); try { // Create the private key connection information. ConnectionInfo connectionInfo; // Create a memory stream with the key data. using (MemoryStream memoryStream = new MemoryStream(state.Slice.Key)) { // Create the private key file. using (PrivateKeyFile keyFile = new PrivateKeyFile(memoryStream)) { // Create a key connection info. connectionInfo = new PrivateKeyConnectionInfo(nodeState.Node.Hostname, state.Slice.Name, keyFile); } } // Open an SSH client to the PlanetLab node. using (SshClient sshClient = new SshClient(connectionInfo)) { // Connect the client. sshClient.Connect(); // For all the slice commands. foreach (PlCommand command in state.Slice.Commands) { // If the command has parameters. if (command.HasParameters) { // Format the command with all parameter sets. for (int indexSet = 0; indexSet < command.SetsCount; indexSet++) { // If the operation has been paused, wait for resume. if (state.IsPaused) { state.WaitPause(); } // If the operation has been canceled, return. if (state.IsStopped) { // Remove the node from the running list. state.UpdateNodeRunningToSkipped(index); // Cancel all nodes in the pending list. state.CancelPendingNodes(); // Raise the canceled event. if (null != this.NodeCanceled) this.NodeCanceled(this, new PlManagerNodeEventArgs(state, nodeState.Node)); // Return. return; } // Run the command with the current parameters set. this.OnRunCommand(state, nodeState, command, indexSet, sshClient); } } else { // Run the command without parameters. this.OnRunCommand(state, nodeState, command, -1, sshClient); } } // Disconnect the client. sshClient.Disconnect(); } // Remove the node from the running list. state.UpdateNodeRunningToCompleted(index); // Raise the success event. if (null != this.NodeFinishedSuccess) this.NodeFinishedSuccess(this, new PlManagerNodeEventArgs(state, nodeState.Node)); } catch (Exception exception) { // Remove the node from the running list. state.UpdateNodeRunningToSkipped(index); // Raise the fail event. if (null != this.NodeFinishedFail) this.NodeFinishedFail(this, new PlManagerNodeEventArgs(state, nodeState.Node, exception)); } finally { lock (state.Sync) { // If the operation has not been canceled. if (!state.IsStopped) { // If the list of pending nodes and running nodes is empty, stop. if ((0 == state.PendingCount) && (0 == state.RunningCount)) { this.Stop(state); } // Get a cached copy of all the pending PlanetLab nodes. int[] pendingCache = state.PendingNodes.ToArray(); // Find the next pending node to execute commands. foreach (int newIndex in pendingCache) { // Get the node state corresponding to the pending node. PlManagerNodeState newNode = state.GetNode(newIndex); // If the slice configuration only allows one node per site. if (state.Slice.OnlyRunOneNodePerSite) { // If the node site is completed. if (state.IsSiteCompleted(newNode.Node.SiteId.Value)) { // Change the node from the pending to the skipped state. state.UpdateNodePendingToSkipped(newIndex); // Raise an event indicating that the node has been skipped. if (null != this.NodeSkipped) this.NodeSkipped(this, new PlManagerNodeEventArgs(state, newNode.Node)); // Skip the loop to the next node. continue; } // If the node site is running. if (state.IsSiteRunning(newNode.Node.SiteId.Value)) { // Postpone the node for later, and skip the loop to the next node. continue; } } // Change the node from the pending to the running state. state.UpdateNodePendingToRunning(newIndex); // Execute the commands on specified node. this.OnRunNode(state, newIndex); // Exit the loop. break; } } } } }); } }
/// <summary> /// GetSshClient /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="ppkFilename"></param> /// <returns></returns> public static SshClient GetSshClient(string host, string username, string password, string ppkFilename) { PrivateKeyFile ppkFile = new PrivateKeyFile(ppkFilename); SshClient client = new SshClient(host, username, new PrivateKeyFile[] { ppkFile }); return client; }
/// <summary> /// Represents private key information. /// </summary> /// <param name="privateKey">The private key file used for authentication.</param> internal PrivateKeyFile(string privateKey) { _privateKey = privateKey; _privateKeyFile = new Renci.SshNet.PrivateKeyFile(privateKey); }
/// <summary> /// Represents private key information. /// </summary> /// <param name="privateKey">The private key stream used for authentication.</param> internal PrivateKeyFile(Stream privateKey) { _privateKeyFile = new Renci.SshNet.PrivateKeyFile(privateKey); }
/// <summary> /// Occurs when the load key button is clicked. /// </summary> /// <param name="sender">The object where the event handler is attached.</param> /// <param name="e">The event data.</param> private async void keyLoadButton_Click(object sender, RoutedEventArgs e) { PrivateKeyData privateKeyData = this.loadKeyPasswordBox.Tag as PrivateKeyData; if (privateKeyData == null) { return; } try { PrivateKeyFile privateKey; using (var privateKeyStream = new MemoryStream(privateKeyData.Data)) { privateKey = new PrivateKeyFile(privateKeyStream, loadKeyPasswordBox.Password); } var addedAgentKey = PrivateKeyAgentManager.PrivateKeyAgent.AddSsh2(privateKey.HostKey, privateKeyData.FileName); if (addedAgentKey != null) { this.AgentKeys.Add(addedAgentKey); } else { MessageDialog dlg = new MessageDialog("This private key is already loaded into the private key agent.", "Error loading private key"); await dlg.ShowAsync(); } Flyout.GetAttachedFlyout(this.keysGridView).Hide(); this.SetEmptyHintVisibilities(); } catch (Exception) { this.loadKeyPasswordErrorTextBlock.Text = "Wrong password."; this.loadKeyPasswordErrorTextBlock.Visibility = Visibility.Visible; this.loadKeyPasswordBox.Focus(FocusState.Programmatic); } this.loadKeyPasswordBox.Password = string.Empty; }
protected override void ProcessRecord() { if (_keyfile.Equals("")) { //########################################### //### Connect using Username and Password ### //########################################### var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName); 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(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, kIconnectInfo, passconnectInfo); } else { WriteVerbose("Using Username and Password authentication for connection."); // Connection info for Keyboard Interactive var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, 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 SFTP Client with connection info var client = new SftpClient(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); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { 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 TrustedKeyMng(); 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(SshModHelper.AddToSftpSessionCollection(client, SessionState), true); } } else { //########################## //### Connect using Keys ### //########################## 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, _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 SftpClient(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) { //this.Host.UI.WriteVerboseLine("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 TrustedKeyMng(); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Connect to host using Connection info client.Connect(); WriteObject(SshModHelper.AddToSftpSessionCollection(client, SessionState), true); } // for each computer } // file exists else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } } // End process record }
/// <summary> /// Represents private key information. /// </summary> /// <param name="privateKey">The private key stream used for authentication.</param> /// <param name="privateKeyFilePassword">The private key file password.</param> internal PrivateKeyFile(Stream privateKey, string privateKeyFilePassword) { _privateKeyFile = new Renci.SshNet.PrivateKeyFile(privateKey, privateKeyFilePassword); }
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> /// SFTP procedure to upload or download files /// </summary> /// <param name="blShuttingDown"></param> public void SFTP(ref bool blShuttingDown) { SftpClient sftp = null; try { string upassword = ""; AES256 aes = new AES256(ep); if (_password.Length > 0) { upassword = aes.Decrypt(_password); } if (string.IsNullOrEmpty(KeyFileDirectory)) { sftp = new SftpClient(Host, Port, Username, upassword); } else { KeyFiles = Common.WalkDirectory(KeyFileDirectory, ref blShuttingDown); List<PrivateKeyFile> PKeyFiles = new List<PrivateKeyFile>(); foreach (FileInfo kfile in KeyFiles) { PrivateKeyFile p; if (UsePassPhrase) { p = new PrivateKeyFile(kfile.FullName, upassword); } else { p = new PrivateKeyFile(kfile.FullName); } PKeyFiles.Add(p); } sftp = new SftpClient(Host, Port, Username, PKeyFiles.ToArray()); } BackupFolder = BackupFolder.Replace("\\\\", "\\"); UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter); sftp.Connect(); upassword = ""; _evt.WriteEntry("Remote Sync SFTP: Connected successfully to Host: " + Host, System.Diagnostics.EventLogEntryType.Information,1005, 10); switch (TransferDirection) { case TransferDirectionOptions.Upload: List<DirectoryInfo> Dirs = null; Stream ureader = null; try { string strRemotePath = ""; strRemotePath = Common.FixNullstring(RemoteDirectory); if (RemoteDirectory != "") { strRemotePath = RemoteDirectory + "/"; } strRemotePath = Common.RemotePathClean(Common.FixNullstring(strRemotePath)); BackupFolder = Common.WindowsPathClean(Common.FixNullstring(BackupFolder)); if (!string.IsNullOrEmpty(strRemotePath)) { if (!sftp.Exists(strRemotePath)) { sftp.CreateDirectory(strRemotePath); } sftp.ChangeDirectory(strRemotePath); } //Create Directories Dirs = Common.GetAllDirectories(BackupFolder); foreach (DirectoryInfo dir in Dirs) { if (blShuttingDown) { throw new Exception("Shutting Down"); } try { strRemotePath = dir.FullName; strRemotePath = Common.RemotePathCombine(RemoteDirectory, strRemotePath, BackupFolder); if (blShuttingDown) { _evt.WriteEntry("Remote Sync: Shutting Down, about to Create a Folder: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1040, 10); return; } } catch (Exception) { _evt.WriteEntry("Remote Sync: Folder Path Text Formatting Error: " + strRemotePath, System.Diagnostics.EventLogEntryType.Error, 1040, 10); } try { sftp.CreateDirectory(strRemotePath); _evt.WriteEntry("Remote Sync: Folder Created on " + Host + ": " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1040, 10); } catch (Exception) { } } //Upload every file found and place in the correct directory UploadFiles = Common.WalkDirectory(BackupFolder, ref blShuttingDown, FileNameFilter); foreach (FileInfo ufile in UploadFiles) { try { bool blFileFound = false; bool blOverwriteFile = false; if (blShuttingDown) { throw new Exception("Shutting Down"); } strRemotePath = ufile.DirectoryName; strRemotePath = Common.RemotePathCombine(Common.FixNullstring(RemoteDirectory),strRemotePath,Common.FixNullstring(BackupFolder)); if (!string.IsNullOrEmpty(strRemotePath)) { sftp.ChangeDirectory(strRemotePath); } strRemotePath = Common.RemotePathCombine(strRemotePath, ufile.Name); if (sftp.Exists(strRemotePath)) { blFileFound = true; //if (!((ufile.LastWriteTimeUtc == sftp.GetLastWriteTimeUtc(strRemotePath)))) SftpFile mupload = sftp.Get(strRemotePath); if (ufile.Length != mupload.Length) { blOverwriteFile = true; } } if (sftp.Exists(strRemotePath + ".7z")) { blFileFound = true; SftpFile mupload = sftp.Get(strRemotePath + ".7z"); //File Size can't be used to compare and last write time cannot be modified so can't compare blOverwriteFile = true; //Overwrite Options can be specified by the user /*if (!((ufile.LastWriteTimeUtc == mupload.LastWriteTimeUtc))) { blOverwriteFile = true; }*/ } if (blShuttingDown) { _evt.WriteEntry("Remote Sync: Shutting Down, about to possibly upload a file: " + ufile.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1010, 10); return; } if ((blFileFound == false || blOverwriteFile || (Overwrite == OverwriteOptions.ForceOverwrite && blFileFound)) && !(Overwrite == OverwriteOptions.NoOverwrite && blFileFound == true)) { /*if (sftp.Exists(ufile.FullName)) { SftpFileAttributes fa=sftp.GetAttributes(ufile.FullName); fa.OwnerCanWrite = true; fa.OthersCanWrite = true; fa.GroupCanWrite = true; sftp.SetAttributes(ufile.FullName,fa); sftp.DeleteFile(ufile.FullName); }*/ ureader = new FileStream(ufile.FullName, FileMode.Open); //sftp.UploadFile(File.OpenRead(ufile.FullName), strRemotePath); sftp.UploadFile(ureader, strRemotePath); _evt.WriteEntry("Remote Sync SFTP: File Uploaded: " + ufile.FullName + " Host: " + Host + " To: " + strRemotePath, System.Diagnostics.EventLogEntryType.Information, 1010, 10); ureader.Close(); ureader = null; //sftp.SetLastWriteTime(ufile.Name, ufile.LastWriteTimeUtc); //not implemented yet } } catch (Exception ex) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + "Upload of FileName: " + ufile.FullName + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } } } catch (Exception exsftup) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + exsftup.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (Dirs != null) { Dirs.Clear(); } Dirs = null; if (ureader != null) { ureader.Close(); ureader = null; } if (UploadFiles != null) { UploadFiles.Clear(); } UploadFiles = null; } break; case TransferDirectionOptions.Download: List<RemoteFile> RemoteFiles=null; try { if (!string.IsNullOrEmpty(RemoteDirectory)) { sftp.ChangeDirectory(RemoteDirectory); } RemoteFiles = Common.GetRemoteDirectories(RemoteDirectory, sftp, ""); //Creates Folder Locally in the BackupFolder Common.CreateLocalFolderStructure(RemoteFiles, BackupFolder); //Downloads Files in each directory foreach (RemoteFile ftpfile in RemoteFiles) { string DownloadPath = ""; string strLocalFilePath = ""; string strRemoteFilePath = ""; if (blShuttingDown) { throw new Exception("Shutting Down"); } try { DownloadPath = Common.RemotePathCombine(RemoteDirectory,ftpfile.ParentDirectory); if (!ftpfile.IsDirectory) { strLocalFilePath = Common.WindowsPathCombine(BackupFolder, ftpfile.ParentDirectory); strLocalFilePath = Common.WindowsPathCombine(strLocalFilePath, ftpfile.Name); strRemoteFilePath = Common.RemotePathCombine(DownloadPath, ftpfile.Name); if (blShuttingDown) { if (sftp != null) { if (sftp.IsConnected) { sftp.Disconnect(); } sftp.Dispose(); } _evt.WriteEntry("Remote Sync: Shutting Down, about to possibly download a Host: " + Host + " file: " + DownloadPath + "/" + ftpfile.Name + " From: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); return; } if (Common.DownloadFile(strLocalFilePath, strRemoteFilePath, ftpfile, Overwrite)) { if (Common.FixNullstring(FileNameFilter) != "" && Common.VerifyPattern(FileNameFilter)) { if (Common.FileNameMatchesPattern(FileNameFilter, ftpfile.Name)) { if (File.Exists(strLocalFilePath)) { File.SetAttributes(strLocalFilePath, FileAttributes.Normal); File.Delete(strLocalFilePath); } using (FileStream fs = new FileStream(strLocalFilePath, FileMode.Create)) { sftp.DownloadFile(strRemoteFilePath, fs); _evt.WriteEntry("Remote Sync SFTP: File Downloaded: " + strRemoteFilePath + " Host: " + Host + " To: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); fs.Close(); } } } else { if (File.Exists(strLocalFilePath)) { File.SetAttributes(strLocalFilePath, FileAttributes.Normal); File.Delete(strLocalFilePath); } using (FileStream fs = new FileStream(strLocalFilePath, FileMode.Create)) { sftp.DownloadFile(strRemoteFilePath, fs); _evt.WriteEntry("Remote Sync SFTP: File Downloaded: " + strRemoteFilePath + " Host: " + Host + " To: " + strLocalFilePath, System.Diagnostics.EventLogEntryType.Information, 1020, 10); fs.Close(); } } } } } catch (Exception exintry) { _evt.WriteEntry("Remote Sync SFTP: File Download Error: " + DownloadPath + "/" + ftpfile.Name + " Host: " + Host + " To: " + strLocalFilePath + " Error: " + exintry.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } } /* //Example Simple Usage RemoteFiles = sftp.ListDirectory("."); foreach (Renci.SshNet.Sftp.SftpFile ftpfile in RemoteFiles) { using (FileStream fs = new FileStream(BackupFolder + "\\" + ftpfile.Name, FileMode.Create)) { sftp.DownloadFile(ftpfile.FullName, fs); } } */ } catch (Exception excon) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + excon.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (RemoteFiles != null) { RemoteFiles.Clear(); } RemoteFiles = null; } break; } } catch (Exception ex) { _evt.WriteEntry("Remote Sync SFTP: Host: " + Host + " Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 1000, 10); } finally { if (sftp != null) { if (sftp.IsConnected) { sftp.Disconnect(); } sftp.Dispose(); } sftp = null; } }
protected override void ProcessRecord() { if (keyfile.Equals("")) { foreach (var computer in computername) { #region AuthUserPass //########################################### //### Connect using Username and Password ### //########################################### ConnectionInfo connectInfo; KeyboardInteractiveAuthenticationMethod KIconnectInfo; if (proxyserver != "") { #region Proxy // Set the proper proxy type var ptype = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName); var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, port, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, proxycredential.GetNetworkCredential().UserName, proxycredential.GetNetworkCredential().Password, KIconnectInfo, PassconnectInfo); #endregion } // Proxy Server else { #region No Proxy WriteVerbose("Using Username and Password authentication for connection."); // Connection info for Keyboard Interactive KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName); var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName); connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName, PassconnectInfo, KIconnectInfo); #endregion }// No Proxy // 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; } }; try { //Ceate instance of SCP Client with connection info var Client = new ScpClient(connectInfo); // Handle host key 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); //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm); //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint); if (SSHHostKeys.ContainsKey(computer)) { if (SSHHostKeys[computer] == FingerPrint) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer); } } else { Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>(); choices.Add(new ChoiceDescription("Y")); choices.Add(new ChoiceDescription("N")); int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1); if (choice == 0) { var keymng = new TrustedKeyMng(); //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer); keymng.SetKey(computer, FingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout); // Set the Operation Timeout Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout); // Connect to host using Connection info Client.Connect(); Client.BufferSize = 1024; // Print progess of download. Client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size); this.Host.UI.WriteProgress(1, progressRecord); } }; var localfullPath = Path.GetFullPath(localfolder); WriteVerbose("Downloading " + remotefolder); DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath); Client.Download(remotefolder, dirinfo); Client.Disconnect(); } catch (Exception ex) { throw ex; } } //end foreach computer #endregion } //Use/Password Auth else { //########################## //### Connect using Keys ### //########################## 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 = Renci.SshNet.ProxyTypes.Http; WriteVerbose("A Proxy Server has been specified"); switch (proxytype) { case "HTTP": ptype = Renci.SshNet.ProxyTypes.Http; break; case "Socks4": ptype = Renci.SshNet.ProxyTypes.Socks4; break; case "Socks5": ptype = Renci.SshNet.ProxyTypes.Socks5; break; } 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); if (proxycredential.UserName == "") { connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, ptype, proxyserver, proxyport, proxycredential.GetNetworkCredential().UserName, proxycredential.GetNetworkCredential().Password, sshkey); } } } else { 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); } } try { //Ceate instance of SCP Client with connection info var Client = new ScpClient(connectionInfo); // Handle host key 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); //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm); //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint); if (SSHHostKeys.ContainsKey(computer)) { if (SSHHostKeys[computer] == FingerPrint) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer); } } else { Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>(); choices.Add(new ChoiceDescription("Y")); choices.Add(new ChoiceDescription("N")); int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1); if (choice == 0) { var keymng = new TrustedKeyMng(); //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer); keymng.SetKey(computer, FingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout); // Set the Operation Timeout Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout); // Connect to host using Connection info Client.Connect(); Client.BufferSize = 1024; // Print progess of download. Client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size); this.Host.UI.WriteProgress(1, progressRecord); } }; var localfullPath = Path.GetFullPath(localfolder); WriteVerbose("Downloading " + remotefolder); DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath); Client.Download(remotefolder, dirinfo); Client.Disconnect(); } catch (Exception ex) { throw ex; } } }// file exist else { throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found."); } } }
protected override void ProcessRecord() { if (_keyfile.Equals("")) { foreach (var computer in _computername) { #region AuthUserPass //########################################### //### Connect using Username and Password ### //########################################### ConnectionInfo connectInfo; KeyboardInteractiveAuthenticationMethod kIconnectInfo; if (_proxyserver != "") { #region Proxy // 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; } kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName); var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, kIconnectInfo, passconnectInfo); #endregion } // Proxy Server else { #region No Proxy WriteVerbose("Using Username and Password authentication for connection."); // Connection info for Keyboard Interactive kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName); var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, passconnectInfo, kIconnectInfo); #endregion }// No Proxy // 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 SCP Client with connection info var client = new ScpClient(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); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } else { var choices = new Collection<ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); if (choice == 0) { var keymng = new TrustedKeyMng(); //this.Host.UI.WriteVerboseLine("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 the Operation Timeout client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout); // Connect to host using Connection info client.Connect(); client.BufferSize = 1024; // Print progess of download. client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size); Host.UI.WriteProgress(1, progressRecord); } }; WriteVerbose("Connection succesfull"); var localfullPath = Path.GetFullPath(_localfile); WriteVerbose("Downloading " + _remotefile); var fil = new FileInfo(@localfullPath); // Download the file client.Download(_remotefile, fil); client.Disconnect(); } //end foreach computer #endregion } //Use/Password Auth else { //########################## //### Connect using Keys ### //########################## 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 { 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); connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, sshkey); } } //Ceate instance of SCP Client with connection info var client = new ScpClient(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) { //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } else { var choices = new Collection<ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); if (choice == 0) { var keymng = new TrustedKeyMng(); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Set the Operation Timeout client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout); // Connect to host using Connection info client.Connect(); client.BufferSize = 1024; // Print progess of download. client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size); Host.UI.WriteProgress(1, progressRecord); } }; WriteVerbose("Connection succesfull"); var localfullPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile); WriteVerbose("Downloading " + _remotefile); var fil = new FileInfo(@localfullPath); // Download the file client.Download(_remotefile, fil); client.Disconnect(); } }// file exist else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } } } // End process record
/// <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); }
// Public methods. /// <summary> /// Connects the console to the current SSH server. /// </summary> public void Connect() { // If the private key is null, show a message and return. if (null == this.config.Key) { // Show a message. MessageBox.Show("The private key for the selected PlanetLab slice is not set.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning); // Raise the connect failed event. if (this.ConnectFailed != null) this.ConnectFailed(this, new PlExceptionEventArgs<PlNode>(this.node, new Exception("The private key for the selected PlanetLab slice is not set."))); return; } try { // The connection info. ConnectionInfo connectionInfo = null; // Create a memory stream with the key data. using (MemoryStream memoryStream = new MemoryStream(this.config.Key)) { // Create the private key file. using (PrivateKeyFile keyFile = new PrivateKeyFile(memoryStream)) { // Create a key connection info. connectionInfo = new PrivateKeyConnectionInfo(this.node.Hostname, this.config.Name, keyFile); } } // Connect to the PlanetLab node. base.Connect(connectionInfo); } catch (Exception exception) { // Show an error dialog if an exception is thrown. MessageBox.Show("Cannot connect to the PlanetLab node. {0}".FormatWith(exception.Message), "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error); // Log this.log.Add(this.crawler.Log.Add( LogEventLevel.Verbose, LogEventType.Information, ControlSession.logSource, "Connecting to the PlanetLab node \'{0}\' failed. {1}", new object[] { this.node.Hostname, exception.Message }, exception)); // Raise the connect failed event. if (this.ConnectFailed != null) this.ConnectFailed(this, new PlExceptionEventArgs<PlNode>(this.node, exception)); } }