Esempio n. 1
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();

                    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");
                }
                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)
                    {
                        var localfullPath = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile);

                        WriteVerbose("Downloading " + _remotefile);
                        WriteVerbose("Saving as " + localfullPath);
                        var fil = new FileInfo(@localfullPath);

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

                        client.Disconnect();
                    }
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
                    WriteError(erec);
                }
            }
        } // End process record
Esempio 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
Esempio n. 3
0
        protected BaseClient CreateConnection(string computer)
        {
            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.Request.Contains("PASSCODE") || prompt.Request.Contains("password"))
                        {
                            prompt.Response = Credential.GetNetworkCredential().Password;
                        }
                    }
                };
                break;

            case "Key":
                WriteVerbose("Using SSH Key authentication for connection (file).");
                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;
            }


            //Create instance of SSH Client with connection info
            BaseClient client;

            switch (Protocol)
            {
            case PoshSessionType.SFTP:
                client = new SftpClient(connectInfo);
                break;

            case PoshSessionType.SCP:
                client = new ScpClient(connectInfo);
                break;

            default:
                client = new SshClient(connectInfo);
                break;
            }

            // Handle host key
            if (Force)
            {
                WriteWarning("Host key is not being verified since Force switch is used.");
            }
            else
            {
                var savedHostKey = KnownHost.GetKey(computer);
                // filter out unsupported hostkeynames
                if (savedHostKey != default && !string.IsNullOrEmpty(savedHostKey.HostKeyName))
                {
                    foreach (var keyName in connectInfo.HostKeyAlgorithms.Keys.ToArray())
                    {
                        if (keyName != savedHostKey.HostKeyName)
                        {
                            connectInfo.HostKeyAlgorithms.Remove(keyName);
                        }
                    }
                }
                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(e.HostKeyName + " Fingerprint for " + computer1 + ": " + fingerPrint);
                    }

                    if (savedHostKey != default)
                    {
                        e.CanTrust = savedHostKey.Fingerprint == fingerPrint && (savedHostKey.HostKeyName == e.HostKeyName || savedHostKey.HostKeyName == string.Empty);
                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint " + (e.CanTrust ? "" : "not ") + "matched trusted " + savedHostKey.HostKeyName + " 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 // User specified he would accept the key so we can just add it to our list.
                            {
                                e.CanTrust = true;
                            }
                            if (e.CanTrust)
                            {
                                if (!KnownHost.SetKey(computer1, e.HostKeyName, fingerPrint))
                                {
                                    Host.UI.WriteWarningLine("Host key is not saved to store.");
                                }
                            }
                        }
                    }
                };
            }
            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();

                return(client);
            }
            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);
            }
            return(default);
Esempio n. 4
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 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();

                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;
                        }
                    }
                };

                var localfullPath = Path.GetFullPath(_localfolder);
                WriteVerbose("Downloading " + _remotefolder);
                var dirinfo = new DirectoryInfo(@localfullPath);
                client.Download(_remotefolder, dirinfo);
                client.Disconnect();
                WriteVerbose("Finished downloading.");
            }
        } // 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
Esempio n. 6
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 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)
                        {
                            //this.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);

                // Connect to host using Connection info
                client.Connect();
                client.BufferSize = 1024;

                // Print progess of upload.
                client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    var progressRecord = new ProgressRecord(1, "Uploading " + e.Filename, String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size))
                    {
                        PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size)
                    };

                    Host.UI.WriteProgress(1, progressRecord);
                };

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

                //var localfullPath = Path.GetFullPath(_localfolder);
                if (Directory.Exists(localfullPath))
                {
                    WriteVerbose("Uploading " + _remotefolder);
                    var dirinfo = new DirectoryInfo(@localfullPath);
                    client.Upload(dirinfo, _remotefolder);
                }
                else
                {
                    throw new DirectoryNotFoundException("Directory " + localfullPath + " was not found.");
                }
                client.Disconnect();
            }
        } // End process record