Provides connection information when private key authentication method is used
Inheritance: ConnectionInfo, IDisposable
Esempio n. 1
1
        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.");
                }
            }
        }
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
        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.");
                }
            }
        }
Esempio n. 4
0
        /// <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();
        }
        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;
        }
Esempio n. 6
0
        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
        }
Esempio n. 7
0
        /// <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;
                                    }
                                }
                            }
                        }
                    });
            }
        }
Esempio n. 8
0
        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;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        /// <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();

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
Esempio n. 10
0
        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
Esempio n. 11
0
        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();
        }
Esempio n. 12
0
        /// <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>
        /// 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;
            }
        }
Esempio n. 14
0
        // 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));
            }
        }