Exemplo n.º 1
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
        }
Exemplo n.º 2
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Length == 0)
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                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;
                            }
                        }
                    };
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    if (_keyfile.Length == 1)   // Filename
                    {
                        connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                                   _port,
                                                                                   _keyfile[0],
                                                                                   _credential,
                                                                                   _proxyserver,
                                                                                   _proxytype,
                                                                                   _proxyport,
                                                                                   _proxycredential);
                    }
                    else
                    {
                        connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                                   _port,
                                                                                   _keyfile,
                                                                                   _credential,
                                                                                   _proxyserver,
                                                                                   _proxytype,
                                                                                   _proxyport,
                                                                                   _proxycredential);
                    }
                }

                //Ceate instance of SSH Client with connection info
                BaseClient client;
                if (Protocol == "SSH")
                {
                    client = new SshClient(connectInfo);
                }
                else
                {
                    client = new SftpClient(connectInfo);
                }


                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            e.CanTrust = _sshHostKeys[computer1] == fingerPrint;
                            if (e.CanTrust && MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                if (!_acceptkey)
                                {
                                    var choices = new Collection <ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };
                                    e.CanTrust = 0 == Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                else
                                {
                                    e.CanTrust = true;
                                }
                                if (e.CanTrust)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                }
                            }
                        }
                    };
                }
                try
                {
                    // 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();

                    if (Protocol == "SSH")
                    {
                        WriteObject(SshModHelper.AddToSshSessionCollection(client as SshClient, SessionState), true);
                    }
                    else
                    {
                        WriteObject(SshModHelper.AddToSftpSessionCollection(client as SftpClient, SessionState), true);
                    }
                }
                catch (SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }

                // Renci.SshNet.Common.SshOperationTimeoutException when host is not alive or connection times out.
                // Renci.SshNet.Common.SshConnectionException when fingerprint mismatched
                // Renci.SshNet.Common.SshAuthenticationException Bad password
            }
        } // End process record
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                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;
                            }
                        }
                    };
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keyfile,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new SftpClient(connectInfo);


                // Handle host key
                var computer1 = computer;
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    var sb = new StringBuilder();
                    foreach (var b in e.FingerPrint)
                    {
                        sb.AppendFormat("{0:x}:", b);
                    }
                    var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                    if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                    {
                        Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                    }

                    if (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " +
                                                         computer);
                            }
                            e.CanTrust = true;
                        }
                        else
                        {
                            throw new System.Security.SecurityException("SSH fingerprint mismatch 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);
            }
        } // End process record