[Ignore] // placeholder for actual test
 public void DisposeTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
 [Ignore] // placeholder for actual test
 public void NameTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Name;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
 [Ignore] // placeholder for actual test
 public void AuthenticateTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
     Session session = null; // TODO: Initialize to an appropriate value
     AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
     AuthenticationResult actual;
     actual = target.Authenticate(session);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
 [Ignore] // placeholder for actual test
 public void KeyboardInteractiveAuthenticationMethodConstructorTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Exemplo n.º 5
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    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;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                default:
                    break;
                }

                //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
Exemplo n.º 6
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    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;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(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 (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;
                            }
                            else
                            {
                                var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                                ThrowTerminatingError(new ErrorRecord(
                                                          ex,
                                                          "SSH fingerprint mismatch for host " + computer1,
                                                          ErrorCategory.SecurityError,
                                                          computer1));
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                            }

                            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
                try
                {
                    client.Connect();

                    var counter = 0;
                    // Print progess of download.
                    if (!_noProgress)
                    {
                        client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            if (e.Size != 0)
                            {
                                counter++;
                                if (counter > 900)
                                {
                                    var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                    if (percent == 100)
                                    {
                                        return;
                                    }

                                    var progressRecord = new ProgressRecord(1,
                                                                            "Downloading " + e.Filename,
                                                                            String.Format("{0} Bytes Downloaded of {1}",
                                                                                          e.Downloaded,
                                                                                          e.Size))
                                    {
                                        PercentComplete = percent
                                    };

                                    Host.UI.WriteProgress(1, progressRecord);
                                    counter = 0;
                                }
                            }
                        };
                    }
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.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);
                }

                if (client.IsConnected)
                {
                    try
                    {
                        var localfullPath = Path.GetFullPath(_localfolder);
                        WriteVerbose("Downloading " + _remotefolder);
                        var dirinfo = new DirectoryInfo(@localfullPath);
                        client.Download(_remotefolder, dirinfo);
                        WriteVerbose("Finished downloading.");
                    }
                    catch (Exception e)
                    {
                        ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                        WriteError(erec);
                    }
                    client.Disconnect();
                }
            }
        } // End process record
Exemplo n.º 7
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    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;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               ProxyCredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               ProxyCredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key for " + computer + " 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))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            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;
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Connect to host using Connection info
                    client.Connect();
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.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);
                }

                try
                {
                    if (client.IsConnected)
                    {
                        if (String.Equals(_pathtype, "File", StringComparison.OrdinalIgnoreCase))
                        {
                            WriteVerbose("Item type selected: File");
                            var _progresspreference = (ActionPreference)this.SessionState.PSVariable.GetValue("ProgressPreference");

                            if (_noProgress == false)
                            {
                                var counter = 0;
                                // Print progess of download.

                                client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                                {
                                    if (e.Size != 0)
                                    {
                                        counter++;
                                        if (counter > 900)
                                        {
                                            var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);
                                            if (percent == 100)
                                            {
                                                return;
                                            }

                                            var progressRecord = new ProgressRecord(1,
                                                                                    "Downloading " + e.Filename,
                                                                                    String.Format("{0} Bytes Downloaded of {1}",
                                                                                                  e.Downloaded, e.Size))
                                            {
                                                PercentComplete = percent
                                            };

                                            Host.UI.WriteProgress(1, progressRecord);
                                            counter = 0;
                                        }
                                    }
                                };
                            }
                            WriteVerbose("Connection successful");

                            // Get file name for use when downloading the file.
                            var filename        = "";
                            var destinationpath = "";
                            var localfullPath   = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localpath);

                            if (String.IsNullOrEmpty(_newname))
                            {
                                filename = new DirectoryInfo(@_remotepath).Name;
                            }
                            else
                            {
                                filename = _newname;
                            }
                            destinationpath = (localfullPath.TrimEnd('/', '\\')) + System.IO.Path.DirectorySeparatorChar + filename;
                            WriteVerbose("Downloading " + _remotepath);
                            WriteVerbose("Saving as " + destinationpath);
                            var fil = new FileInfo(@destinationpath);

                            // Download the file
                            client.Download(_remotepath, fil);

                            client.Disconnect();
                        }
                        else
                        {
                            WriteVerbose("Item type selected: Directory");

                            var counter = 0;
                            // Print progess of download.
                            if (!_noProgress)
                            {
                                client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                                {
                                    if (e.Size != 0)
                                    {
                                        counter++;
                                        if (counter > 900)
                                        {
                                            var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                            if (percent == 100)
                                            {
                                                return;
                                            }

                                            var progressRecord = new ProgressRecord(1,
                                                                                    "Downloading " + e.Filename,
                                                                                    String.Format("{0} Bytes Downloaded of {1}",
                                                                                                  e.Downloaded,
                                                                                                  e.Size))
                                            {
                                                PercentComplete = percent
                                            };

                                            Host.UI.WriteProgress(1, progressRecord);
                                            counter = 0;
                                        }
                                    }
                                };
                            }

                            try
                            {
                                // Get directory name for use when downloading the file.
                                var dirname         = "";
                                var destinationpath = "";
                                var localfullPath   = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localpath);

                                if (String.IsNullOrEmpty(_newname))
                                {
                                    dirname = new DirectoryInfo(@_remotepath).Name;
                                }
                                else
                                {
                                    dirname = _newname;
                                }
                                destinationpath = (localfullPath.TrimEnd('/', '\\')) + System.IO.Path.DirectorySeparatorChar + dirname;

                                Directory.CreateDirectory(destinationpath);
                                WriteVerbose("Downloading: " + _remotepath);
                                WriteVerbose("Destination: " + destinationpath);
                                var dirinfo = new DirectoryInfo(@destinationpath);
                                client.Download(_remotepath, dirinfo);
                                WriteVerbose("Finished downloading.");
                            }
                            catch (Exception e)
                            {
                                ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                                WriteError(erec);
                            }
                            client.Disconnect();
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
                    WriteError(erec);
                }
            }
        } // End process record
        public override ProcessOutput ExecuteCcm(string args, bool throwOnProcessError = true)
        {
            var executable = GetExecutable(ref args);

            Trace.TraceInformation(executable + " " + args);

            var output = new ProcessOutput();

            if (_sshClient == null)
            {
                Trace.TraceInformation("Connecting ssh client...");
                var kauth = new KeyboardInteractiveAuthenticationMethod(_user);
                var pauth = new PasswordAuthenticationMethod(_user, _password);

                var connectionInfo = new ConnectionInfo(_ip, _port, _user, kauth, pauth);

                kauth.AuthenticationPrompt += (sender, e) =>
                {
                    foreach (var prompt in e.Prompts)
                    {
                        if (prompt.Request.ToLowerInvariant().StartsWith("password"))
                        {
                            prompt.Response = _password;
                        }
                    }
                };

                if (!string.IsNullOrEmpty(_privateKeyFilePath))
                {
                    var privateKeyAuth = new PrivateKeyAuthenticationMethod(_user, new PrivateKeyFile[]
                    {
                        new PrivateKeyFile(_privateKeyFilePath)
                    });
                    connectionInfo = new ConnectionInfo(_ip, _port, _user, privateKeyAuth);
                }

                _sshClient = new SshClient(connectionInfo);
            }
            if (!_sshClient.IsConnected)
            {
                _sshClient.Connect();
            }

            var result = _sshClient.RunCommand(string.Format(@"{0} {1}", executable, args));

            output.ExitCode = result.ExitStatus;
            if (result.Error != null)
            {
                output.OutputText.Append(result.Error);
            }
            else
            {
                output.OutputText.Append(result.Result);
            }

            if (throwOnProcessError)
            {
                ValidateOutput(output);
            }
            return(output);
        }
Exemplo n.º 9
0
        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.GetNetworkCredential().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
Exemplo n.º 10
0
        public SecureCopier(ResourceNode node)
        {
            Log.Info("SCP: Establishing connection to node " + node.ResourceName + "." + node.NodeName);

            var nodeAddress = node.NodeAddress; // todo : OR ExecutionUrl????!!!!!
            var addrParts   = node.NodeAddress.Split(':');

            int port = DEFAULT_SCP_PORT;

            if (addrParts.Length == 2)
            {
                int.TryParse(addrParts[1], out port);
                nodeAddress = addrParts[0];
            }

            // if resource asks us for password interactively:
            var interactiveAuthMethod = new KeyboardInteractiveAuthenticationMethod(node.Credentials.Username);

            interactiveAuthMethod.AuthenticationPrompt += delegate(object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
            {
                foreach (var prompt in e.Prompts)
                {
                    Log.Debug("Interactive request by resource node " + node.NodeName + ": '" + prompt.Request + "'");

                    if (prompt.Request.ToLowerInvariant().Contains("password"))
                    {
                        Log.Debug("Responding by password");
                        prompt.Response = node.Credentials.Password;
                    }
                }
            };

            ConnectionInfo connectionInfo;

            if (!String.IsNullOrWhiteSpace(node.Credentials.CertFile))
            {
                connectionInfo = new ConnectionInfo(nodeAddress, port, node.Credentials.Username,
                                                    new PrivateKeyAuthenticationMethod(
                                                        node.Credentials.Username,
                                                        new PrivateKeyFile(node.Credentials.CertFile, node.Credentials.Password)
                                                        )
                                                    );
            }
            else
            {
                connectionInfo = new ConnectionInfo(nodeAddress, port, node.Credentials.Username,
                                                    new PasswordAuthenticationMethod(node.Credentials.Username, node.Credentials.Password),
                                                    interactiveAuthMethod
                                                    );
            }

            try
            {
                _sftpClient = new SftpClient(connectionInfo);
                _sftpClient.Connect();

                _scp = null;
            }
            catch (Exception e)
            {
                Log.Warn("Unable to use sftp. Rolling bask to SCP for resource node " + node.ResourceName + "." + node.NodeName + ": " + e.ToString());
                _sftpClient = null;

                _scp = new Scp(nodeAddress, node.Credentials.Username, node.Credentials.Password);
                _scp.Connect(port);
            }
        }
Exemplo n.º 11
0
        public string RunShell(string command)
        {
            string result = string.Empty;

            try
            {
                using (var client = new SshClient(this.host, this.username, this.password))
                {
                    client.Connect();
                    IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>();
                    termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);

                    ShellStream shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);

                    StreamReader reader = new StreamReader(shellStream);
                    StreamWriter writer = new StreamWriter(shellStream);
                    writer.AutoFlush = true;

                    result += reader.ReadToEnd();
                    while (shellStream.Length == 0)
                    {
                        Thread.Sleep(500);
                    }

                    Thread.Sleep(500);
                    result += reader.ReadToEnd();

                    writer.WriteLine(command);
                    while (shellStream.Length == 0)
                    {
                        Thread.Sleep(500);
                    }

                    Thread.Sleep(1000);
                    result += reader.ReadToEnd();

                    shellStream.Dispose();
                    client.Disconnect();
                    client.Dispose();
                }
            }
            catch (Exception exc)
            {
                if (exc.ToString().Contains("No suitable authentication method found to complete authentication"))
                {
                    KeyboardInteractiveAuthenticationMethod keybAuth = new KeyboardInteractiveAuthenticationMethod(this.username);
                    keybAuth.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(HandleKeyEvent);
                    var connectionInfo = new ConnectionInfo(this.host, 22, this.username, keybAuth);
                    using (var client = new SshClient(connectionInfo))
                    {
                        client.Connect();
                        IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>();
                        termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);

                        ShellStream shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);

                        StreamReader reader = new StreamReader(shellStream);
                        StreamWriter writer = new StreamWriter(shellStream);
                        writer.AutoFlush = true;

                        result += reader.ReadToEnd();
                        while (shellStream.Length == 0)
                        {
                            Thread.Sleep(500);
                        }

                        Thread.Sleep(500);
                        result += reader.ReadToEnd();

                        writer.WriteLine(command);
                        while (shellStream.Length == 0)
                        {
                            Thread.Sleep(500);
                        }

                        Thread.Sleep(1000);
                        result += reader.ReadToEnd();

                        shellStream.Dispose();
                        client.Disconnect();
                        client.Dispose();
                    }
                }
            }
            return(result);
        }
Exemplo n.º 12
0
        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 ScpClient(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 (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                            e.CanTrust = true;
                        }
                        else
                        {
                            var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                            ThrowTerminatingError(new ErrorRecord(
                                                      ex,
                                                      "SSH fingerprint mismatch for host " + computer1,
                                                      ErrorCategory.SecurityError,
                                                      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();
                //client.BufferSize = 1024;

                var counter = 0;
                // Print progess of download.
                client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    if (e.Size != 0)
                    {
                        counter++;

                        if (counter > 900)
                        {
                            var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size);

                            if (percent == 100)
                            {
                                return;
                            }

                            var progressRecord = new ProgressRecord(1,
                                                                    "Uploading " + e.Filename,
                                                                    String.Format("{0} Bytes Uploaded of {1}",
                                                                                  e.Uploaded, e.Size))
                            {
                                PercentComplete = percent
                            };

                            Host.UI.WriteProgress(1, progressRecord);
                            counter = 0;
                        }
                    }
                };

                WriteVerbose("Connection successful");

                // Resolve the path even if a relative one is given.
                ProviderInfo provider;
                var          pathinfo      = GetResolvedProviderPathFromPSPath(_localfile, out provider);
                var          localfullPath = pathinfo[0];

                if (File.Exists(@localfullPath))
                {
                    WriteVerbose("Uploading " + localfullPath);
                    var fil            = new FileInfo(@localfullPath);
                    var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
                    client.Upload(fil, remoteFullpath);

                    client.Disconnect();
                }
                else
                {
                    var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found.");

                    ThrowTerminatingError(new ErrorRecord(
                                              ex,
                                              "File to upload " + localfullPath + " was not found.",
                                              ErrorCategory.InvalidArgument,
                                              localfullPath));
                }
            }
        } // End process record
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="computer"></param>
        /// <param name="port"></param>
        /// <param name="credential"></param>
        /// <param name="proxyserver"></param>
        /// <param name="proxytype"></param>
        /// <param name="proxyport"></param>
        /// <param name="proxycredential"></param>
        /// <param name="kIconnectInfo"></param>
        /// <returns></returns>
        public static ConnectionInfo GetCredConnectionInfo(string computer,
                                                           int port,
                                                           PSCredential credential,
                                                           string proxyserver,
                                                           string proxytype,
                                                           int proxyport,
                                                           PSCredential proxycredential,
                                                           KeyboardInteractiveAuthenticationMethod kIconnectInfo)
        {
            ConnectionInfo connectionInfo;
            var            passconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName,
                                                                              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.GetNetworkCredential().UserName != "")
                {
                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.GetNetworkCredential().UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        "",
                                                        "",
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
                else
                {
                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.GetNetworkCredential().UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        proxycredential.GetNetworkCredential().UserName,
                                                        proxycredential.GetNetworkCredential().Password,
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
            }
            else // Handle connection with no proxy server
            {
                connectionInfo = new ConnectionInfo(computer,
                                                    port,
                                                    credential.GetNetworkCredential().UserName,
                                                    passconnectInfo,
                                                    kIconnectInfo);
            }
            return(connectionInfo);
        }