Provides functionality to perform password authentication.
Inheritance: AuthenticationMethod, IDisposable
Example #1
24
 public SftpUploader(AppConfig conf)
 {
     this.config = conf;
     if (config.sftpEnabled)
     {
         AuthenticationMethod[] auths = new AuthenticationMethod[1];
         if (String.IsNullOrWhiteSpace(config.sftpPrivateKeyPath))
         {
             auths[0] = new PasswordAuthenticationMethod(config.sftpUsername, Utils.GetBytes(config.sftpPassword));
         }
         else
         {
             try
             {
                 PrivateKeyFile pkf = null;
                 if (string.IsNullOrEmpty(config.sftpPassword))
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath);
                 }
                 else
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath, config.sftpPassword);
                 }
                 auths[0] = new PrivateKeyAuthenticationMethod(config.sftpUsername, pkf);
             }
             catch (IOException)
             {
                 Log.Error("Unable to read private key file: " + config.sftpPrivateKeyPath);
                 return;
             }
         }
         connInfo = new ConnectionInfo(config.sftpRemoteServer, config.sftpUsername, auths);
     }
 }
        public override ProcessOutput ExecuteCcm(string args, int timeout = 90000, 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 += delegate(object sender, AuthenticationPromptEventArgs 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;
        }
Example #3
1
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                //###########################################
                //### Connect using Username and Password ###
                //###########################################
                ConnectionInfo connectInfo;
                var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                foreach (var computer in computername)
                {
                    if (proxyserver != "")
                    {
                        // Set the proper proxy type
                        var ptype = Renci.SshNet.ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (proxytype)
                        {
                            case "HTTP":
                                ptype = Renci.SshNet.ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = Renci.SshNet.ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = Renci.SshNet.ProxyTypes.Socks5;
                                break;
                        }

                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                            WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                            connectInfo = new ConnectionInfo(computer,
                                port,
                                credential.GetNetworkCredential().UserName,
                                ptype,
                                proxyserver,
                                proxyport,
                                proxycredential.GetNetworkCredential().UserName,
                                proxycredential.GetNetworkCredential().Password,
                                KIconnectInfo,
                                PassconnectInfo);

                    }
                    else
                    {
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive

                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);

                        //} // End foroeach computer
                    }

                    // Event Handler for interactive Authentication
                    KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = credential.GetNetworkCredential().Password;
                        }
                    };

                    try
                    {
                        //Ceate instance of SSH Client with connection info
                        var Client = new SshClient(connectInfo);

                        // Handle host key
                        Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                            //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                            if (SSHHostKeys.ContainsKey(computer))
                            {
                                if (SSHHostKeys[computer] == FingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                }
                            }
                            else
                            {
                                int choice;
                                if (acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                    choices.Add(new ChoiceDescription("Y"));
                                    choices.Add(new ChoiceDescription("N"));

                                    choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                    keymng.SetKey(computer, FingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };
                        // Set the connection timeout
                        Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                        // Set Keepalive for connections
                        Client.KeepAliveInterval = TimeSpan.FromSeconds(keepaliveinterval);

                        // Connect to  host using Connection info
                        Client.Connect();
                        WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);
                if (File.Exists(fullPath))
                {
                    foreach (var computer in computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = Renci.SshNet.ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (proxytype)
                            {
                                case "HTTP":
                                    ptype = Renci.SshNet.ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = Renci.SshNet.ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = Renci.SshNet.ProxyTypes.Socks5;
                                    break;
                            }

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {
                            WriteVerbose("Using SSH Key authentication for connection.");
                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }

                        }
                        try
                        {
                            //Ceate instance of SSH Client with connection info
                            var Client = new SshClient(connectionInfo);

                            // Handle host key
                            Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                            {
                                var sb = new StringBuilder();
                                foreach (var b in e.FingerPrint)
                                {
                                    sb.AppendFormat("{0:x}:", b);
                                }
                                string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                                //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                                if (SSHHostKeys.ContainsKey(computer))
                                {
                                    if (SSHHostKeys[computer] == FingerPrint)
                                    {
                                        //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                    }
                                }
                                else
                                {
                                    int choice;
                                    if (acceptkey)
                                    {
                                        choice = 0;
                                    }
                                    else
                                    {
                                        Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                        choices.Add(new ChoiceDescription("Y"));
                                        choices.Add(new ChoiceDescription("N"));

                                        choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);
                                    }
                                    if (choice == 0)
                                    {
                                        var keymng = new TrustedKeyMng();
                                        //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                        keymng.SetKey(computer, FingerPrint);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        e.CanTrust = false;
                                    }
                                }
                            };
                            // Set the connection timeout
                            Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                            // Set Keepalive for connections
                            Client.KeepAliveInterval = TimeSpan.FromSeconds(keepaliveinterval);

                            // Connect to  host using Connection info
                            Client.Connect();
                            WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);

                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    } // for each computer
                } // file exists
                else
                {
                    throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }
        }
        public void UploadFile(string fullSourcePath, string fileName)
        {
            var host = ConfigurationManager.AppSettings["Host"];
            var user = ConfigurationManager.AppSettings["User"];
            var port = ConfigurationManager.AppSettings["Port"];
            var pass = ConfigurationManager.AppSettings["Password"];
            var path = ConfigurationManager.AppSettings["Path"];
            var key = ConfigurationManager.AppSettings["PrivateKey"];

            int p = 22;
            if (!string.IsNullOrEmpty(port))
                p = int.Parse(port);

            Log.Info("Uploading '{0}' to {1}@{2}:{3}", fileName, user, host, p);

            AuthenticationMethod auth;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(user)) {
                Log.Info("Using public key authentication with key {0}", key);
                auth = new PrivateKeyAuthenticationMethod(user ,new PrivateKeyFile[]{ new PrivateKeyFile(key) });
            } else if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass)){
                Log.Info("Using password authentication");
                auth = new PasswordAuthenticationMethod(user,pass);
            } else {
                throw new Exception("Please ensure that username, and either PrivateKey or Password setting are defined in the configuration file.");
            }

            ConnectionInfo ConnNfo = new ConnectionInfo(host, p, user, new AuthenticationMethod[]{ auth } );

            string targetPath = fileName;
            if (!String.IsNullOrEmpty(path)) {
                // If the Path config setting specifies the file name,
                // then ignore the local file name and always upload to the same target
                if (!String.IsNullOrWhiteSpace(Path.GetFileName(path))) {
                    targetPath = path;
                } else {
                    targetPath = Path.Combine(path, targetPath);
                    // To avoid path guessing by .NET, we first combine the path, then force
                    // potential backslashes with linux slashes.
                    // This will obviously kill any space escaping in the path, so we need to bring those back
                    bool hadSpaceEscapes = targetPath.Contains("\\ ");
                    targetPath = targetPath.Replace('\\', '/');
                    if (hadSpaceEscapes)
                        targetPath = targetPath.Replace("/ ", "\\ ");
                }
            }

            using (var scp = new ScpClient(ConnNfo)) {
                scp.Connect();

                Log.Info("Connection opened, uploading file.");
                scp.Upload(new FileInfo(fullSourcePath), targetPath);
                Log.Info("File uploaded, closing connection.");
                scp.Disconnect();
            }
        }
Example #5
0
 private ConnectionInfo GenerateConnectionInfo(string host, string username, string password)
 {
     var auth1 = new PasswordAuthenticationMethod(username, password);
     var auth2 = new KeyboardInteractiveAuthenticationMethod(username);
     auth2.AuthenticationPrompt += delegate(object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
     {
         foreach (var prompt in e.Prompts)
         {
             if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
             {
                 prompt.Response = password;
             }
         }
     };
     ConnectionInfo ci = new ConnectionInfo(host, username, auth1, auth2);
     return ci;
 }
Example #6
0
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                foreach (var computer in computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod KIconnectInfo;
                    if (proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = Renci.SshNet.ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (proxytype)
                        {
                            case "HTTP":
                                ptype = Renci.SshNet.ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = Renci.SshNet.ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = Renci.SshNet.ProxyTypes.Socks5;
                                break;
                        }

                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            port,
                            credential.GetNetworkCredential().UserName,
                            ptype,
                            proxyserver,
                            proxyport,
                            proxycredential.GetNetworkCredential().UserName,
                            proxycredential.GetNetworkCredential().Password,
                            KIconnectInfo,
                            PassconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = credential.GetNetworkCredential().Password;
                        }
                    };
                    try
                    {
                        //Ceate instance of SCP Client with connection info
                        var Client = new ScpClient(connectInfo);

                        // Handle host key
                        Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                            //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                            if (SSHHostKeys.ContainsKey(computer))
                            {
                                if (SSHHostKeys[computer] == FingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                }
                            }
                            else
                            {
                                Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                choices.Add(new ChoiceDescription("Y"));
                                choices.Add(new ChoiceDescription("N"));

                                int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                    keymng.SetKey(computer, FingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                        // Set the Operation Timeout
                        Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

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

                        // Print progess of download.
                        Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

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

                        var localfullPath = Path.GetFullPath(localfolder);
                        WriteVerbose("Downloading " + remotefolder);
                        DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                        Client.Download(remotefolder, dirinfo);
                        Client.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = Renci.SshNet.ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (proxytype)
                            {
                                case "HTTP":
                                    ptype = Renci.SshNet.ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = Renci.SshNet.ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = Renci.SshNet.ProxyTypes.Socks5;
                                    break;
                            }

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                        }

                        try
                        {
                            //Ceate instance of SCP Client with connection info
                            var Client = new ScpClient(connectionInfo);

                            // Handle host key
                            Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                            {
                                var sb = new StringBuilder();
                                foreach (var b in e.FingerPrint)
                                {
                                    sb.AppendFormat("{0:x}:", b);
                                }
                                string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                                //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                                if (SSHHostKeys.ContainsKey(computer))
                                {
                                    if (SSHHostKeys[computer] == FingerPrint)
                                    {
                                        //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                    }
                                }
                                else
                                {
                                    Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                    choices.Add(new ChoiceDescription("Y"));
                                    choices.Add(new ChoiceDescription("N"));

                                    int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                    if (choice == 0)
                                    {
                                        var keymng = new TrustedKeyMng();
                                        //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                        keymng.SetKey(computer, FingerPrint);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        e.CanTrust = false;
                                    }
                                }
                            };

                            // Set the connection timeout
                            Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                            // Set the Operation Timeout
                            Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

                            // Connect to  host using Connection info
                            Client.Connect();

                            Client.BufferSize = 1024;

                            // Print progess of download.
                            Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                            {
                                var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                                if (e.Size != 0)
                                {
                                    progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

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

                            var localfullPath = Path.GetFullPath(localfolder);
                            WriteVerbose("Downloading " + remotefolder);
                            DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                            Client.Download(remotefolder, dirinfo);
                            Client.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }

                }// file exist
                else
                {
                    throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }
        }
Example #7
0
        /// <summary>
        /// Upload Files.
        /// </summary>
        /// <returns></returns>
        public Boolean Put()
        {
            Boolean ok = false;

            // Choose Authentication Method
            AuthenticationMethod authenticationMethod;
            if (PrivateKeyPath != null && PrivateKeyPath.Trim().Length > 0)
            {
                authenticationMethod = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(PrivateKeyPath, PassPhrase));
            }
            else
            {
                authenticationMethod = new PasswordAuthenticationMethod(UserName, Password);
            }

            // Get Connection Info
            ConnectionInfo connectionInfo;
            if (Port > 0)
	        {
                if (Proxy != null && Proxy.Host != null && Proxy.Host.Length > 0)
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        (ProxyTypes)Enum.Parse(typeof(ProxyTypes), Proxy.Type.ToString()),
                                                        Proxy.Host, Proxy.Port,
                                                        Proxy.UserName, Proxy.Password,
                                                        authenticationMethod);
                }
                else
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName, authenticationMethod);
                }
            }
            else
            {
                connectionInfo = new ConnectionInfo(Host, UserName, authenticationMethod);
            }

            // Uploads
            Boolean fail = false;
            using (SftpClient sftp = new SftpClient(connectionInfo))
            {
                // Connect
                try
                {
                    sftp.Connect();
                }
                catch (Exception xcp)
                {
                    Logger.Log($"SftpClient.Connect failed:{Environment.NewLine}{ToString()}", 
                                xcp, EventLogEntryType.Error);
                    fail = true;
                }
                // Check Connection
                if (!fail && sftp.IsConnected)
                {
                    // Change Directory
                    if (Directory.Length > 0)
                    {
                        sftp.ChangeDirectory(Directory);
                    }
                    
                    foreach (var filePath in FilePaths)
                    {
                        // Upload File
                        using (FileStream file = File.OpenRead(filePath))
                        {
                            try
                            {
                                String path = Directory.Length > 0 
                                            ? string.Format("{0}/{1}", 
                                                            Directory, Path.GetFileName(filePath)) 
                                            : "";

                                Action<UInt64> del = uploadFileCallback;
                                sftp.UploadFile(file, path, del);

                                //uploadFileResult

                                ok = true;

                            }
                            catch (System.ArgumentException xcp)
                            {
                                Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}",
                                            xcp, EventLogEntryType.Error);
                                throw;
                            }
                            catch (Exception xcp)
                            {
                                Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", 
                                            xcp, EventLogEntryType.Error);
                                throw;
                            }
                        }
                    }
                    // Disconnect
                    try
                    {
                        sftp.Disconnect();
                    }
                    catch (Exception xcp)
                    {
                        Logger.Log($"SftpClient.Disconnect failed:{Environment.NewLine}{ToString()}",
                                    xcp, EventLogEntryType.FailureAudit);
                    }
                }
            }

            return ok && !fail;
        }
        /// <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.UserName,
                                                                   credential.GetNetworkCredential().Password);
            if (proxyserver != String.Empty)
            {
                // Set the proper proxy type
                var ptype = ProxyTypes.Http;
                switch (proxytype)
                {
                    case "HTTP":
                        ptype = ProxyTypes.Http;
                        break;
                    case "Socks4":
                        ptype = ProxyTypes.Socks4;
                        break;
                    case "Socks5":
                        ptype = ProxyTypes.Socks5;
                        break;
                }

                if (proxycredential.UserName != String.Empty)
                {
                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        String.Empty,
                                                        String.Empty,
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
                else
                {

                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        proxycredential.UserName,
                                                        proxycredential.GetNetworkCredential().Password,
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
            }
            else // Handle connection with no proxy server
            {

                connectionInfo = new ConnectionInfo(computer,
                                                    port,
                                                    credential.UserName,
                                                    passconnectInfo,
                                                    kIconnectInfo);

            }
            return connectionInfo;
        }
Example #9
0
        protected override void ProcessRecord()
        {
            if (_keyfile.Equals(""))
            {
                //###########################################
                //### Connect using Username and Password ###
                //###########################################
                var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                foreach (var computer in _computername)
                {
                    ConnectionInfo connectInfo;
                    if (_proxyserver != "")
                    {
                        // Set the proper proxy type
                        var ptype = ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (_proxytype)
                        {
                            case "HTTP":
                                ptype = ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = ProxyTypes.Socks5;
                                break;
                        }

                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            ptype,
                            _proxyserver,
                            _proxyport,
                            _proxycredential.GetNetworkCredential().UserName,
                            _proxycredential.GetNetworkCredential().Password,
                            kIconnectInfo,
                            passconnectInfo);



                    }
                    else
                    {
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive

                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);


                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            passconnectInfo,
                            kIconnectInfo);
                    }

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };


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

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

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                e.CanTrust = true;
                            }
                            else
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                            }
                        }
                        else
                        {
                            int choice;
                            if (_acceptkey)
                            {
                                choice = 0;
                            }
                            else
                            {
                                var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                                choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                            }
                            if (choice == 0)
                            {
                                var keymng = new TrustedKeyMng();
                                keymng.SetKey(computer1, fingerPrint);
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                    };
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set Keepalive for connections
                    client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval);

                    // Connect to  host using Connection info
                    client.Connect();
                    WriteObject(SshModHelper.AddToSftpSessionCollection(client, SessionState), true);
                }
            }
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(_keyfile);
                if (File.Exists(fullPath))
                {
                    foreach (var computer in _computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (_proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (_proxytype)
                            {
                                case "HTTP":
                                    ptype = ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = ProxyTypes.Socks5;
                                    break;
                            }

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);

                                if (_proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        _proxycredential.GetNetworkCredential().UserName,
                                        _proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {
                            WriteVerbose("Using SSH Key authentication for connection.");
                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey);
                            }


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

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

                            if (_sshHostKeys.ContainsKey(computer1))
                            {
                                if (_sshHostKeys[computer1] == fingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                                }
                            }
                            else
                            {
                                int choice;
                                if (_acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    var choices = new Collection<ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };

                                    choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };
                        // Set the connection timeout
                        client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                        // Connect to  host using Connection info
                        client.Connect();
                        WriteObject(SshModHelper.AddToSftpSessionCollection(client, SessionState), true);
                    } // for each computer
                } // file exists
                else
                {
                    throw new FileNotFoundException("Key file " + fullPath + " was not found.");
                }

            } // End process record
        }
Example #10
0
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                //###########################################
                //### Connect using Username and Password ###
                //###########################################

                if (proxyserver != "")
                {
                    // Set the proper proxy type
                    var ptype = Renci.SshNet.ProxyTypes.Http;
                    WriteVerbose("A Proxy Server has been specified");
                    switch (proxytype)
                    {
                        case "HTTP":
                            ptype = Renci.SshNet.ProxyTypes.Http;
                            break;
                        case "Socks4":
                            ptype = Renci.SshNet.ProxyTypes.Socks4;
                            break;
                        case "Socks5":
                            ptype = Renci.SshNet.ProxyTypes.Socks5;
                            break;
                    }

                    var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                    var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);
                    foreach (var computer in computername)
                    {
                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        var connectInfo = new ConnectionInfo(computer,
                            port,
                            credential.GetNetworkCredential().UserName,
                            ptype,
                            proxyserver,
                            proxyport,
                            proxycredential.GetNetworkCredential().UserName,
                            proxycredential.GetNetworkCredential().Password,
                            KIconnectInfo,
                            PassconnectInfo);

                        // Event Handler for interactive Authentication
                        KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                        {
                            foreach (var prompt in e.Prompts)
                            {
                                if (prompt.Request.Contains("Password"))
                                    prompt.Response = credential.GetNetworkCredential().Password;
                            }
                        };
                        try
                        {
                            //Ceate instance of SSH Client with connection info
                            var Client = new SshClient(connectInfo);

                            // Connect to  host using Connection info
                            Client.Connect();
                            WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);

                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    } // End foroeac computer
                }
                else
                {
                    WriteVerbose("Using Username and Password authentication for connection.");
                    // Connection info for Keyboard Interactive
                    var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                    var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                    foreach (var computer in computername)
                    {
                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        var connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);

                        // Event Handler for interactive Authentication
                        KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                        {
                            foreach (var prompt in e.Prompts)
                            {
                                if (prompt.Request.Contains("Password"))
                                    prompt.Response = credential.GetNetworkCredential().Password;
                            }
                        };
                        try
                        {
                            //Ceate instance of SSH Client with connection info
                            var Client = new SshClient(connectInfo);

                            // Connect to  host using Connection info
                            Client.Connect();
                            WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    } // End foroeach computer
                }
            }
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);

                if (proxyserver != "")
                {
                    // Set the proper proxy type
                    var ptype = Renci.SshNet.ProxyTypes.Http;
                    WriteVerbose("A Proxy Server has been specified");
                    switch (proxytype)
                    {
                        case "HTTP":
                            ptype = Renci.SshNet.ProxyTypes.Http;
                            break;
                        case "Socks4":
                            ptype = Renci.SshNet.ProxyTypes.Socks4;
                            break;
                        case "Socks5":
                            ptype = Renci.SshNet.ProxyTypes.Socks5;
                            break;
                    }

                    if (File.Exists(fullPath))
                    {
                        foreach (var computer in computername)
                        {
                            PrivateKeyConnectionInfo connectionInfo;
                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                            try
                            {
                                //Ceate instance of SSH Client with connection info
                                var Client = new SshClient(connectionInfo);

                                // Connect to  host using Connection info
                                Client.Connect();
                                WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    }
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    if (File.Exists(fullPath))
                    {
                        foreach (var computer in computername)
                        {
                            PrivateKeyConnectionInfo connectionInfo;
                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            try
                            {
                                //Ceate instance of SSH Client with connection info
                                var Client = new SshClient(connectionInfo);

                                // Connect to  host using Connection info
                                Client.Connect();
                                WriteObject(SSHModHelper.AddToSSHSessionCollection(Client, this.SessionState), true);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    }
                }
            }
        }
        private static async Task<bool> GetWorkingConnectionInfo(string ip, TimeSpan timeout)
        {

            //User auth method
            KeyboardInteractiveAuthenticationMethod authMethod = new KeyboardInteractiveAuthenticationMethod("lvuser");
            PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod("lvuser", "");

            authMethod.AuthenticationPrompt += (sender, e) =>
            {
                foreach (
                    AuthenticationPrompt p in
                        e.Prompts.Where(
                            p => p.Request.IndexOf("Password:"******"";
                }
            };

            //Admin Auth Method
            KeyboardInteractiveAuthenticationMethod authMethodAdmin = new KeyboardInteractiveAuthenticationMethod("admin");
            PasswordAuthenticationMethod pauthAdmin = new PasswordAuthenticationMethod("admin", "");

            authMethodAdmin.AuthenticationPrompt += (sender, e) =>
            {
                foreach (
                    AuthenticationPrompt p in
                        e.Prompts.Where(
                            p => p.Request.IndexOf("Password:"******"";
                }
            };

            s_lvUserConnectionInfo = new ConnectionInfo(ip, "lvuser", pauth, authMethod) { Timeout = timeout };


            s_adminConnectionInfo = new ConnectionInfo(ip, "admin", pauthAdmin, authMethodAdmin) { Timeout = timeout };
            using (SshClient zeroConfClient = new SshClient(s_lvUserConnectionInfo))
            {
                try
                {
                    await Task.Run(() => zeroConfClient.Connect());
                    return true;
                }
                catch (SocketException)
                {
                    return false;
                }
                catch (SshOperationTimeoutException)
                {
                    return false;
                }
            }
        }
 private void connectButton_Click(object sender, EventArgs e)
 {
     AuthenticationMethod am = null;
     if (noAuthRadioButton.Checked) {
         am = new KeyboardInteractiveAuthenticationMethod(userNameTextBox.Text);
     }
     if (passwordRadioButton.Checked) {
         am = new PasswordAuthenticationMethod(
             userNameTextBox.Text, passwordTextBox.Text);
     }
     if (keyRadioButton.Checked) {
         PrivateKeyFile pkf;
         if (passphraseTextBox.Text == "") {
             pkf = new PrivateKeyFile(fileNameLabel.Text);
         } else {
             pkf = new PrivateKeyFile(fileNameLabel.Text, passphraseTextBox.Text);
         }
         am = new PrivateKeyAuthenticationMethod(
             userNameTextBox.Text,
             new PrivateKeyFile[] {pkf});
     }
     // set connection info
     this.connectionInfo = new ConnectionInfo(
         serverTextBox.Text,
         Int32.Parse(portTextBox.Text),
         userNameTextBox.Text,
         new AuthenticationMethod[] {am});
     this.DialogResult = System.Windows.Forms.DialogResult.OK;
     this.Close();
 }
Example #13
0
        protected override void ProcessRecord()
        {
            if (_keyfile.Equals(""))
            {
                foreach (var computer in _computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod kIconnectInfo;
                    if (_proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (_proxytype)
                        {
                            case "HTTP":
                                ptype = ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = ProxyTypes.Socks5;
                                break;
                        }

                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            ptype,
                            _proxyserver,
                            _proxyport,
                            _proxycredential.GetNetworkCredential().UserName,
                            _proxycredential.GetNetworkCredential().Password,
                            kIconnectInfo,
                            passconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            passconnectInfo,
                            kIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };
                    //Ceate instance of SCP Client with connection info
                    var client = new ScpClient(connectInfo);

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

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                e.CanTrust = true;
                            }
                            else
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                            }
                        }
                        else
                        {
                            var choices = new Collection<ChoiceDescription>
                            {
                                new ChoiceDescription("Y"),
                                new ChoiceDescription("N")
                            };

                            int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                            if (choice == 0)
                            {
                                var keymng = new TrustedKeyMng();
                                //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                keymng.SetKey(computer1, fingerPrint);
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                    };

                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set the Operation Timeout
                    client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

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

                    // Print progess of download.
                    client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                    {
                        var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                        if (e.Size != 0)
                        {
                            progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                            Host.UI.WriteProgress(1, progressRecord);
                        }
                    };
                    WriteVerbose("Connection succesfull");
                    var localfullPath = Path.GetFullPath(_localfile);

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

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

                    client.Disconnect();
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(_keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in _computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (_proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (_proxytype)
                            {
                                case "HTTP":
                                    ptype = ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = ProxyTypes.Socks5;
                                    break;
                            }

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);

                                if (_proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        _proxycredential.GetNetworkCredential().UserName,
                                        _proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                        }

                        //Ceate instance of SCP Client with connection info
                        var client = new ScpClient(connectionInfo);

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

                            if (_sshHostKeys.ContainsKey(computer1))
                            {
                                if (_sshHostKeys[computer1] == fingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                                }
                            }
                            else
                            {
                                var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                                int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();

                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                        // Set the Operation Timeout
                        client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

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

                        client.BufferSize = 1024;

                        // Print progess of download.
                        client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

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

                        WriteVerbose("Connection succesfull");
                        var localfullPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile);

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

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

                        client.Disconnect();
                    }

                }// file exist
                else
                {
                    throw new FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }

        } // End process record
        internal static SftpClient CreateSftpClient(this string connectionString)
        {
            if (connectionString == null) throw new ArgumentNullException("connectionString");

            // get parts of connection string
            var csb = new DbConnectionStringBuilder { ConnectionString = connectionString };
            var host = csb["host"] as string;
            var username = csb["username"] as string;
            var password = csb["password"] as string;
            var hostkey = csb["hostkey"] as string;
            var port = Attempt.Get(() => Convert.ToInt32(csb["port"]));

            // do this when connstring is bad
            Action<string> badConnString = detail =>
            {
                throw new FormatException(
                    string.Format(
                        "SFTP connection string invalid. {0} Example: username=USERNAME;password=PASSWORD;host=HOSTNAME;hostkey=ssh-dss 1024 3b:1c:20:aa:27:00:83:4f:7a:49:9c:9f:e7:67:ab:03",
                        detail ?? ""));
            };

            // check required conn string params
            if (new[] { host, username, password, hostkey }.Any(string.IsNullOrWhiteSpace))
                badConnString("Missing required parameter.");

            // check format of host key
            var hostKeyParts =
                hostkey.Split().Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim().ToLower()).ToArray();

            // host key needs 3 parts: name, length, fingerprint
            if (hostKeyParts.Length != 3)
                badConnString(string.Format("Host key '{0}' is incorrectly formatted.", hostkey));

            // length neeeds to be an int
            int hostKeyLength;
            if (!int.TryParse(hostKeyParts[1], out hostKeyLength))
                badConnString(string.Format("Host key length '{0}' is not an integer.", hostKeyParts[1]));

            // finter print needs to be a byte array as hex string
            var hostKeyPrint =
                Attempt.Get(() => SoapHexBinary.Parse(string.Concat(hostKeyParts[2].Where(char.IsLetterOrDigit))).Value);
            if (!hostKeyPrint.Succeeded)
                badConnString(string.Format("Invalid host key fingerprint '{0}'.", hostKeyParts[2]));

            // using only pw auth for time being
            var pwAuthMethod = new PasswordAuthenticationMethod(username, password);
            var connInfo = port.Succeeded
                ? new ConnectionInfo(host, port.Value, username, pwAuthMethod)
                : new ConnectionInfo(host, username, pwAuthMethod);

            var sftpClient = new SftpClient(connInfo);

            // validate host key
            sftpClient.HostKeyReceived += (s, e) =>
            {
                e.CanTrust = hostKeyParts[0].Equals(e.HostKeyName.Trim(), StringComparison.OrdinalIgnoreCase)
                             && hostKeyLength == e.KeyLength
                             && hostKeyPrint.Value.SequenceEqual(e.FingerPrint);
            };

            return sftpClient;
        }
        private void btnUnixDetect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var KeyboardInteractive = new Ssh.KeyboardInteractiveAuthenticationMethod(Host.Username);
                var Password            = new Ssh.PasswordAuthenticationMethod(Host.Username, AES.DecryptString(Host.Password));
                var encryptedPassword   = Host.Password;
                KeyboardInteractive.AuthenticationPrompt += delegate(object sender1, Ssh.Common.AuthenticationPromptEventArgs e1)
                {
                    foreach (var prompt in e1.Prompts)
                    {
                        if (prompt.Request.ToLower().Contains("password"))
                        {
                            prompt.Response = AES.DecryptString(encryptedPassword);
                        }
                    }
                };
                var conn = new Ssh.ConnectionInfo(Host.Value,
                                                  Host.Username,
                                                  Password,
                                                  KeyboardInteractive);
                using (Ssh.SshClient client = new Ssh.SshClient(conn))
                {
                    client.Connect();
                    var termdic = new Dictionary <Ssh.Common.TerminalModes, uint>();
                    termdic.Add(Ssh.Common.TerminalModes.ECHO, 0);

                    using (var shell = client.CreateShellStream("gogrid", 80, 24, 800, 600, 1024, termdic))
                    {
                        using (var output = new StreamReader(shell))
                            using (var input = new StreamWriter(shell))
                            {
                                input.AutoFlush = true;
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                //shell.WriteLine("stty raw -echo"); // disable echo
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                shell.Write("([ -d ~/oraInventory/ContentsXML/ ] && [ -e ~/oraInventory/ContentsXML/inventory.xml ])  && echo epmi1 || echo epmi0\n");
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                var resp = shell.ReadLine();
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                if (System.Text.RegularExpressions.Regex.IsMatch(resp, "epmi1$"))
                                {
                                    shell.Write("cat ~/oraInventory/ContentsXML/inventory.xml\n");
                                    while (shell.Length == 0)
                                    {
                                        Thread.Sleep(500);
                                    }
                                    resp = Read(output, true);
                                    XmlDocument doc = new XmlDocument();
                                    doc.LoadXml(resp);
                                    var nodes = doc.SelectNodes("INVENTORY/HOME_LIST/HOME");
                                    for (int i = 0; i < nodes.Count; i++)
                                    {
                                        if (Regex.IsMatch(nodes[i].Attributes["NAME"].Value, @"EpmSystem_\S+"))
                                        {
                                            tbxUnixPath.Text = nodes[i].Attributes["LOC"].Value;
                                            break;
                                        }
                                    }
                                    MessageBox.Show("Success");
                                }
                            }
                    }
                    client.Disconnect();
                }
            }
            catch (Ssh.Common.SshAuthenticationException)
            {
                MessageBox.Show("Failed to authenticate to server. Check username and password.");
            }
            catch (Exception)
            {
                MessageBox.Show("Unknown error.");
            }
        }
Example #16
-1
 private ConnectionInfo GenerateConnectionInfo()
 {
     var auth1 = new PasswordAuthenticationMethod(username, password);
     var auth2 = new KeyboardInteractiveAuthenticationMethod(username);
     auth2.AuthenticationPrompt += auth2_AuthenticationPrompt;
     ConnectionInfo ci = new ConnectionInfo(host, username, auth1, auth2);
     return ci;
 }
Example #17
-1
        public SSHClient(string host, string port, string username, string password)
        {
            int portNum = 0;
            if(!int.TryParse(port, out portNum))
            {
                throw new Exception($"Port: {port}, must be an integer.");
            }

            try
            {
                var auth = new PasswordAuthenticationMethod(username, password);

                _connectionInfo = new ConnectionInfo(host, username, auth);
                _sshClient = new SshClient(_connectionInfo);
                _sftpClient = new SftpClient(_connectionInfo);
            }
            catch (Exception)
            {
                throw;
            }
        }