public void Test_KeyExchange_Rekeying()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                //  TODO:   Add test to test re-keying
                Assert.Inconclusive();
                client.Disconnect();
            }
        }
Ejemplo n.º 2
1
        public void Test_HMac_Sha1_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha1", (key) => { return new HMac<SHA1Hash>(key.Take(20).ToArray()); });

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 3
1
        public void Test_Cipher_Aes192CTR_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("aes192-ctr", new CipherInfo(192, (key, iv) => { return new AesCipher(key, new CtrCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 4
1
        public void Test_HMac_Sha1_96_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha1", new HashInfo(20 * 8, key => CryptoAbstraction.CreateHMACSHA1(key, 96)));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 5
1
        public void Test_HostKey_SshDss_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HostKeyAlgorithms.Clear();
            connectionInfo.HostKeyAlgorithms.Add("ssh-dss", (data) => { return new KeyHostAlgorithm("ssh-dss", new DsaKey(), data); });

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 6
1
        public void Test_HMac_MD5_96_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-md5", new HashInfo(16 * 8, key => HashAlgorithmFactory.CreateHMACMD5(key, 96)));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 7
1
        public void Test_HMac_Sha256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha2-256", new HashInfo(32 * 8, HashAlgorithmFactory.CreateHMACSHA256));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 8
0
 public void DisposeTest()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     byte[] password = null; // TODO: Initialize to an appropriate value
     PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Ejemplo n.º 9
0
 public void PasswordConnectionInfoConstructorTest10()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     string password = string.Empty; // TODO: Initialize to an appropriate value
     ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
     string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
     int proxyPort = 0; // TODO: Initialize to an appropriate value
     PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Ejemplo n.º 10
0
        public void Test_Cipher_AEes128CBC_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("aes128-cbc", new CipherInfo(128, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
        public void Test_KeyExchange_GroupExchange_Sha256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.KeyExchangeAlgorithms.Clear();
            connectionInfo.KeyExchangeAlgorithms.Add("diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 12
0
        public void Test_PasswordConnectionInfo()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo
            var connectionInfo = new PasswordConnectionInfo(host, username, password);
            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
Ejemplo n.º 13
0
        public void Test_Connect_Timeout()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example SshClient Connect Timeout
            var connectionInfo = new PasswordConnectionInfo(host, username, password);

            connectionInfo.Timeout = TimeSpan.FromSeconds(30);

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion
            Assert.Inconclusive();
        }
Ejemplo n.º 14
0
        private SshClient CreateClient()
        {
            ConnectionInfo connInfo;

            if (string.IsNullOrEmpty(_pkey))
            {
                connInfo = new PasswordConnectionInfo(_host, 22, _username, _password ?? string.Empty);
            }
            else if (!string.IsNullOrEmpty(_password))
            {
                connInfo = new PrivateKeyConnectionInfo(_host, 22, _username,
                                                        new PrivateKeyFile(_pkey, _password));
            }
            else
            {
                connInfo = new PrivateKeyConnectionInfo(_host, 22, _username,
                                                        new PrivateKeyFile(_pkey));
            }

            connInfo.Timeout = TimeSpan.FromSeconds(_connectTimeout);
            return(new SshClient(connInfo));
        }
Ejemplo n.º 15
0
        private bool FTPConnect()
        {
            try
            {
                //TODO: add option to use passkey

                var connectionInfo = new PasswordConnectionInfo(Host.ValueForDriver, UserName.ValueForDriver, Password.ValueForDriver);
                UnixFTPClient = new SftpClient(connectionInfo);
                UnixFTPClient.Connect();
                workdir = UnixFTPClient.WorkingDirectory;
                if (UnixFTPClient.IsConnected)
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, "Cannot Login to Unix", ex);
                throw (ex);
            }
            return(false);
        }
Ejemplo n.º 16
0
        public void Test_PasswordConnectionInfo_AuthenticationBanner()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo AuthenticationBanner
            var connectionInfo = new PasswordConnectionInfo(host, username, password);
            connectionInfo.AuthenticationBanner += delegate(object sender, AuthenticationBannerEventArgs e)
            {
                Console.WriteLine(e.BannerMessage);
            };
            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
Ejemplo n.º 17
0
        public void Test_PasswordConnectionInfo_AuthenticationBanner()
        {
            var host     = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo AuthenticationBanner
            var connectionInfo = new PasswordConnectionInfo(host, username, password);
            connectionInfo.AuthenticationBanner += delegate(object sender, AuthenticationBannerEventArgs e)
            {
                Console.WriteLine(e.BannerMessage);
            };
            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
Ejemplo n.º 18
0
 public void ExSSH(string ip, string log, string pass, List <String> list)
 {
     //     foreach (string ipadd in ip)
     //     {
     using (var conninfo = new PasswordConnectionInfo(ip, log, pass))
     {
         Renci.SshNet.SshClient client = new Renci.SshNet.SshClient(conninfo);
         client.Connect();
         Renci.SshNet.ShellStream stream = client.CreateShellStream("ssh", 180, 324, 1800, 3600, 8000);
         foreach (string command in list)
         {
             // var command = "show config modified";
             stream.Write(command + "\n");
             System.Threading.Thread.Sleep(10000);
             string temp_string = stream.Read();
             //  Console.Write(temp_string);
             File.WriteAllText("C:/" + ip + " thread n- " + System.Threading.Thread.CurrentThread.ManagedThreadId + ".txt", temp_string, Encoding.UTF8);
             //     System.Threading.Thread.Sleep(5000);
         }
         client.Disconnect();
         //   }
     }
 }
Ejemplo n.º 19
0
 public async Task UploadFileAsync(string filepath)
 {
     await Task.Run(() =>
     {
         if (File.Exists(filepath))
         {
             var connInfoSource = new PasswordConnectionInfo(_setting.Host, _setting.Port, _setting.User, _setting.Password);
             using (var sftp = new SftpClient(connInfoSource))
             {
                 sftp.Connect();
                 if (!sftp.Exists(_setting.RemotePath))
                 {
                     sftp.CreateDirectory(_setting.RemotePath);
                 }
                 using (FileStream wrt = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     sftp.UploadFile(wrt, $"{_setting.RemotePath}/{Path.GetFileName(filepath)}", true);
                 }
                 sftp.Disconnect();
             }
         }
     });
 }
Ejemplo n.º 20
0
 private void Connect()
 {
     if (connection != null && connection.State == ConnectionState.Open)
     {
         return;
     }
     #region Подключение по SSH
     if (port == null || !port.IsStarted)
     {
         // сервер, порт, логин, пароль
         PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("free9.beget.com", 22, "h982945m", "56QLYf5C");
         connectionInfo.Timeout = TimeSpan.FromSeconds(30);
         SshClient client = new SshClient(connectionInfo);
         client.Connect();
         // проброс порта
         port = new ForwardedPortLocal("127.0.0.1", 3307, "127.0.0.1", 3306);
         client.AddForwardedPort(port);
         port.Start();
     }
     #endregion
     #region Собственно, подключение к БД
     try
     {
         MySqlConnectionStringBuilder connBuilder = new MySqlConnectionStringBuilder();
         connBuilder.Server   = "127.0.0.1";
         connBuilder.Port     = 3307;
         connBuilder.UserID   = "h982945m_sectech";
         connBuilder.Password = "******";
         connBuilder.Database = "h982945m_sectech";
         //string connStr = "SERVER=127.0.0.1;PORT=3307;UID=h982945m_sectech;PASSWORD=n6&uX99*;DATABASE=h982945m_sectech";
         connection = new MySqlConnection(connBuilder.ConnectionString);
         connection.Open();
     }
     catch { }
     #endregion
 }
Ejemplo n.º 21
0
        private void uploadSetup()
        {
            ConnectionInfo connectionInfo = new PasswordConnectionInfo(this.IPAdress, "root", "");

            using (SftpClient sftp = new SftpClient(connectionInfo))
            {
                try
                {
                    sftp.Connect();
                    string remoteDirectoryFile = @"/data/coatapp_config/setup";
                    string sourceDir           = Path.Combine(Directory.GetCurrentDirectory(), "Labware\\" + "setup");
                    using (var localfile = File.OpenRead(sourceDir))
                    {
                        sftp.BufferSize = 4 * 1024;
                        sftp.UploadFile(localfile, remoteDirectoryFile, true);
                    }
                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    Console.WriteLine("An exception has been caught " + er.ToString());
                }
            }
        }
Ejemplo n.º 22
0
        public void Test_PasswordConnectionInfo_PasswordExpired()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo PasswordExpired
            var connectionInfo = new PasswordConnectionInfo("host", "username", "password");
            var encoding = new Renci.SshNet.Common.ASCIIEncoding();
            connectionInfo.PasswordExpired += delegate(object sender, AuthenticationPasswordChangeEventArgs e)
            {
                e.NewPassword = encoding.GetBytes("123456");
            };

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();

                client.Disconnect();
            }
            #endregion

            Assert.Inconclusive();
        }
Ejemplo n.º 23
0
        public void Test_PasswordConnectionInfo_PasswordExpired()
        {
            var host     = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo PasswordExpired
            var connectionInfo = new PasswordConnectionInfo("host", "username", "password");
            var encoding       = SshData.Ascii;
            connectionInfo.PasswordExpired += delegate(object sender, AuthenticationPasswordChangeEventArgs e)
            {
                e.NewPassword = encoding.GetBytes("123456");
            };

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();

                client.Disconnect();
            }
            #endregion

            Assert.Inconclusive();
        }
Ejemplo n.º 24
0
        public Task GetDirectoryList(string uri, string user, string pass, string path)
        {
            return(Task.Run(() => {
                result = "";
                try
                {
                    var connectionInfo = new PasswordConnectionInfo(uri,
                                                                    user,
                                                                    pass);
                    using (var client = new SftpClient(connectionInfo))
                    {
                        client.Connect();

                        fileList = client.ListDirectory(path);

                        result = "Directory List Complete";
                    }
                }
                catch (Exception e)
                {
                    result = "An exception has been caught " + e.ToString();
                }
            }));
        }
Ejemplo n.º 25
0
        public void Test_Ssh_Connect_Via_HttpProxy()
        {
            var connInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, Resources.PASSWORD, ProxyTypes.Http, Resources.PROXY_HOST, int.Parse(Resources.PROXY_PORT));
            using (var client = new SshClient(connInfo))
            {
                client.Connect();

                var ret = client.RunCommand("ls -la");

                client.Disconnect();
            }
        }
Ejemplo n.º 26
0
 public void Test_ConnectionInfo_BigPortNumber()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 27
0
 public void Test_ConnectionInfo_Password_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, (string)null);
 }
Ejemplo n.º 28
0
        public void Test_Cipher_Arcfour256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("arcfour256", new CipherInfo(256, (key, iv) => { return new Arc4Cipher(key, true); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 29
0
        public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }



            String server   = config["server"].ToString();
            String username = config["username"].ToString();
            String password = config["password"].ToString();

            StringBuilder processLog = new StringBuilder();
            PluginLogType logType    = PluginLogType.Information;

            try
            {
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(server, username, password);
                connectionInfo.Timeout = new TimeSpan(0, 1, 0);

                using (SshClient client = new SshClient(connectionInfo))
                {
                    try
                    {
                        client.Connect();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro on connect SSH", ex);
                    }


                    String prefix = "echo '" + config["password"].ToString() + "' | sudo ";

                    if (config.ContainsKey("use_prefix"))
                    {
                        try
                        {
                            Boolean up = Boolean.Parse(config["use_prefix"].ToString());
                            if (!up)
                            {
                                prefix = "";
                            }
                        }
                        catch { }
                    }


                    List <UserData> users = GetList(client, config, package.login);

                    UserData selectedUser = null;
                    foreach (UserData u in users)
                    {
                        if (u.Username.ToLower() == package.login.ToLower())
                        {
                            selectedUser = u;
                        }
                    }

                    if (selectedUser != null)
                    {
                        //Usuário existente
                    }
                    else
                    {
                        //Não existe, cria

                        //useradd -G {group-name} username

                        //Cria grupo genérico para o IM

                        SshCommand grpAdd = client.RunCommand("groupadd IAMUsers ");
                        if (grpAdd.ExitStatus != 0)
                        {
                            if (grpAdd.Error.ToLower().IndexOf("already exists") == -1)
                            {
                                logType = PluginLogType.Error;
                                processLog.AppendLine("Error creating IAMUsers group: " + grpAdd.Error.Trim("\r\n".ToCharArray()));
                                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating IAMUsers group", grpAdd.Error.Trim("\r\n".ToCharArray()));
                                return;
                            }
                        }

                        SshCommand cmdAdd = client.RunCommand("useradd -G IAMUsers " + package.login);
                        if (cmdAdd.ExitStatus != 0)
                        {
                            logType = PluginLogType.Error;
                            processLog.AppendLine("Error creating users: " + cmdAdd.Error.Trim("\r\n".ToCharArray()));
                            Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating users", cmdAdd.Error.Trim("\r\n".ToCharArray()));
                            return;
                        }

                        processLog.AppendLine("User added");
                    }

                    if (package.password != "")
                    {
                        String md5Pwd = "";
                        using (MD5 hAlg = MD5.Create())
                            md5Pwd = ComputeHash(hAlg, package.password);

                        SshCommand cmdChangePwd = client.RunCommand("echo '" + package.login + ":" + package.password + "' | chpasswd");

                        if (cmdChangePwd.ExitStatus != 0)
                        {
                            logType = PluginLogType.Error;
                            processLog.AppendLine("Error on set user password, check the password complexity rules");
                            processLog.AppendLine(cmdChangePwd.Error.Trim("\r\n".ToCharArray()));

                            String sPs = "";
                            try
                            {
                                PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName);

                                sPs += "Length = " + package.password.Length + Environment.NewLine;
                                sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine;
                                sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine;
                                sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine;
                                sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine;
                                sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine;

                                processLog.AppendLine(sPs);
                            }
                            catch { }

                            Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", cmdChangePwd.Error.Trim("\r\n".ToCharArray()) + Environment.NewLine + sPs);
                            return;
                        }
                    }

                    //Lock and unlock account
                    //usermod -L
                    //usermod -U

                    processLog.AppendLine("User locked? " + (package.locked || package.temp_locked ? "true" : "false"));

                    SshCommand userLock = client.RunCommand("usermod " + (package.locked || package.temp_locked ? "-L " : "-U ") + package.login);
                    if (userLock.ExitStatus != 0)
                    {
                        logType = PluginLogType.Error;
                        processLog.AppendLine("Error " + (package.locked || package.temp_locked ? "locking" : "unlocking") + " user: "******"\r\n".ToCharArray()));
                        Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error " + (package.locked || package.temp_locked ? "locking" : "unlocking") + " user", userLock.Error.Trim("\r\n".ToCharArray()));
                        return;
                    }

                    //Executa as ações do RBAC
                    if ((package.pluginAction != null) && (package.pluginAction.Count > 0))
                    {
                        List <GroupData> groups = GetUserGroups(client, config);

                        foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction)
                        {
                            try
                            {
                                processLog.AppendLine("Role: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString());

                                switch (act.actionKey.ToLower())
                                {
                                case "group":
                                    GroupData findGroup       = groups.Find(g => (g.Groupname == act.actionValue));
                                    GroupData findUserInGroup = groups.Find(g => (g.Groupname == act.actionValue && g.Users.Contains(package.login)));

                                    if ((act.actionType == PluginActionType.Add) && (findUserInGroup == null))
                                    {
                                        if (findGroup == null)
                                        {
                                            //Not found, add group

                                            SshCommand grpAdd = client.RunCommand("groupadd " + act.actionValue);
                                            if (grpAdd.ExitStatus != 0)
                                            {
                                                if (grpAdd.Error.ToLower().IndexOf("already exists") == -1)
                                                {
                                                    logType = PluginLogType.Error;
                                                    processLog.AppendLine("Error creating " + act.actionValue + " group: " + grpAdd.Error.Trim("\r\n".ToCharArray()));
                                                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating " + act.actionValue + " group", grpAdd.Error.Trim("\r\n".ToCharArray()));
                                                    continue;
                                                }
                                            }
                                        }

                                        SshCommand userGrpAdd = client.RunCommand("usermod -a -G " + act.actionValue + " " + package.login);
                                        if (userGrpAdd.ExitStatus != 0)
                                        {
                                            logType = PluginLogType.Error;
                                            processLog.AppendLine("Error adding user on group " + act.actionValue + ": " + userGrpAdd.Error.Trim("\r\n".ToCharArray()));
                                            Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error adding user on group " + act.actionValue, userGrpAdd.Error.Trim("\r\n".ToCharArray()));
                                            continue;
                                        }
                                        else
                                        {
                                            processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName);
                                        }
                                    }
                                    else if ((act.actionType == PluginActionType.Remove) && (findUserInGroup != null))
                                    {
                                        SshCommand userGrpDel = client.RunCommand("gpasswd -d " + package.login + " " + act.actionValue);
                                        if (userGrpDel.ExitStatus != 0)
                                        {
                                            logType = PluginLogType.Error;
                                            processLog.AppendLine("Error removing user on group " + act.actionValue + ": " + userGrpDel.Error.Trim("\r\n".ToCharArray()));
                                            Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error removing user on group " + act.actionValue, userGrpDel.Error.Trim("\r\n".ToCharArray()));
                                            continue;
                                        }
                                        else
                                        {
                                            processLog.AppendLine("User removed from group " + act.actionValue + " by role " + act.roleName);
                                        }
                                    }
                                    break;

                                default:
                                    processLog.AppendLine("Action not recognized: " + act.actionKey);
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message);
                                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, "");
                            }
                        }
                    }

                    client.Disconnect();

                    NotityChangeUser(this, package.entityId);

                    if (package.password != "")
                    {
                        processLog.AppendLine("User updated with password");
                    }
                    else
                    {
                        processLog.AppendLine("User updated without password");
                    }
                }
            }
            catch (Exception ex)
            {
                logType = PluginLogType.Error;
                processLog.AppendLine("Error on process deploy: " + ex.Message);
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "");
            }
            finally
            {
                Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString());
                processLog.Clear();
                processLog = null;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient {
                    Host = controller.Account.Host, Port = controller.Account.Port
                };

                // Add accepted certificates
                _ftpc.ClientCertificates.AddRange(Certificates);

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateCertificate += (sender, x) =>
                    {
                        var fingerPrint = new X509Certificate2(x.Certificate).Thumbprint;

                        if (_ftpc.ClientCertificates.Count <= 0 && x.PolicyErrors != SslPolicyErrors.None)
                        {
                            Certificates.Add(x.Certificate);
                            x.Accept = false;
                            return;
                        }

                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                            x.Accept = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint  = fingerPrint,
                            SerialNumber = x.Certificate.GetSerialNumberString(),
                            Algorithm    = x.Certificate.GetKeyAlgorithmParametersString(),
                            ValidFrom    = x.Certificate.GetEffectiveDateString(),
                            ValidTo      = x.Certificate.GetExpirationDateString(),
                            Issuer       = x.Certificate.Issuer
                        };
                        // Prompt user to validate
                        ValidateCertificate(null, e);
                        x.Accept = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                    {
                        _ftpc.EncryptionMode = FtpEncryptionMode.Explicit;
                    }
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                    {
                        _ftpc.EncryptionMode = FtpEncryptionMode.Implicit;
                    }
                }

                _ftpc.Credentials = new NetworkCredential(controller.Account.Username, controller.Account.Password);

                try
                {
                    _ftpc.Connect();
                }
                catch (Exception exc)
                {
                    // Since the ClientCertificates are added when accepted in ValidateCertificate, the first
                    // attempt to connect will fail with an AuthenticationException. If this is the case, a
                    // re-connect is attempted, this time with the certificates properly set.
                    // This is a workaround to avoid storing Certificate files locally...
                    if (exc is System.Security.Authentication.AuthenticationException &&
                        _ftpc.ClientCertificates.Count <= 0)
                    {
                        Connect();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else             // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                {
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                }
                else
                {
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);
                }

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key         = x.HostKeyName,
                        KeySize     = x.KeyLength.ToString()
                    };
                    // Prompt user to validate
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                    }
                    if (ConnectionClosed != null)
                    {
                        ConnectionClosed(null, new ConnectionClosedEventArgs {
                            Text = e.Exception.Message
                        });
                    }

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                    {
                        Log.Write(l.Warning, "Permission denied error occured");
                    }
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                    {
                        Reconnect();
                    }
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
            {
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                {
                    WorkingDirectory = controller.Paths.Remote;
                }
            }

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
            {
                LogServerInfo();
            }

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
Ejemplo n.º 31
0
        internal static Connection GetInstance(string name, ConnectionReason reason)
        {
            UnixSystem          remoteSystem   = null;
            ConnectionInfoStore store          = new ConnectionInfoStore();
            ConnectionInfo      connectionInfo = null;

            StoredConnectionInfo storedConnectionInfo = store.Connections.FirstOrDefault(connection =>
            {
                return(name.Equals(GetFormattedConnectionName((ConnectionInfo)connection), StringComparison.OrdinalIgnoreCase));
            });

            if (storedConnectionInfo != null)
            {
                connectionInfo = (ConnectionInfo)storedConnectionInfo;
            }

            if (connectionInfo == null)
            {
                IVsConnectionManager connectionManager = (IVsConnectionManager)ServiceProvider.GlobalProvider.GetService(typeof(IVsConnectionManager));

                string userName;
                string hostName;

                int atSignIndex = name.IndexOf('@');
                if (atSignIndex > 0)
                {
                    userName = name.Substring(0, atSignIndex);
                    hostName = name.Substring(atSignIndex + 1);
                }
                else
                {
                    userName = string.Format(CultureInfo.CurrentCulture, StringResources.UserName_PlaceHolder);
                    hostName = name;
                }

                PasswordConnectionInfo newConnectionInfo = new PasswordConnectionInfo(hostName, userName, new System.Security.SecureString());

                IConnectionManagerResult result = connectionManager.ShowDialog(newConnectionInfo);

                if (result.DialogResult == ConnectionManagerDialogResult.Succeeded)
                {
                    // Retrieve the newly added connection
                    store.Load();
                    connectionInfo = store.Connections.First(info => info.Id == result.StoredConnectionId);
                }
            }

            if (connectionInfo != null)
            {
                remoteSystem = new UnixSystem();

                while (true)
                {
                    try
                    {
                        VSOperationWaiter.Wait(string.Format(CultureInfo.CurrentCulture, StringResources.WaitingOp_Connecting, name), throwOnCancel: false, action: () =>
                        {
                            remoteSystem.Connect(connectionInfo);
                        });
                        break;
                    }
                    catch (RemoteAuthenticationException)
                    {
                        IVsConnectionManager     connectionManager = (IVsConnectionManager)ServiceProvider.GlobalProvider.GetService(typeof(IVsConnectionManager));
                        IConnectionManagerResult result            = connectionManager.ShowDialog(StringResources.AuthenticationFailureHeader, StringResources.AuthenticationFailureDescription, connectionInfo);

                        if (result.DialogResult == ConnectionManagerDialogResult.Succeeded)
                        {
                            // Update the credentials in the store
                            store.Load();
                            store.RemoveById(result.StoredConnectionId);
                            store.Add(result.ConnectionInfo);
                            store.Save();

                            connectionInfo = result.ConnectionInfo;
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        VsShellUtilities.ShowMessageBox(ServiceProvider.GlobalProvider, ex.Message, null,
                                                        OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return(null);
                    }
                }

                // NOTE: This will be null if connect is canceled
                if (remoteSystem != null)
                {
                    return(new Connection(remoteSystem));
                }
            }

            return(null);
        }
Ejemplo n.º 32
0
 public void Test_ConnectionInfo_Host_Is_Whitespace()
 {
     var connectionInfo = new PasswordConnectionInfo(" ", Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 33
0
 public void Test_ConnectionInfo_Password_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, (string)null);
 }
 public void Test_ConnectionInfo_Host_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(null, Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 35
0
 public void Test_ConnectionInfo_Host_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(null, Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Метод копирования файла на хост
        /// </summary>
        /// <param name="fileName">имя файла</param>
        /// <param name="pathToFile">путь к файлу</param>
        /// <param name="pathDestination">путь, куда будет скопирован файл</param>
        /// <param name="ipAddress">ip адрес хоста</param>
        /// <param name="login">логин, для подключения к хосту</param>
        /// <param name="password">пароль, для подключения к хосту</param>
        public void SftpCopy(string fileName, string pathToFile, string pathDestination, string ipAddress, string login, string password, bool addToListBoxTask = true)
        {
            try
            {
                bool endRunThread = false;
                var  startThread  = new Thread(new ThreadStart(() =>
                {
                    //BackgroundWorker progressBarCopyWorker = new BackgroundWorker();
                    PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ipAddress, 22, login, password);
                    connectionInfo.Timeout         = TimeSpan.FromSeconds(15);
                    string fileFullName            = System.IO.Path.Combine(pathToFile, fileName);
                    string fileDestinationFullName = System.IO.Path.Combine(pathDestination, fileName);

                    ItemListBoxTask curItemLBT = new ItemListBoxTask()
                    {
                        IPOrName = ipAddress, Description = $"Выполняется копирование: {fileName} в {pathDestination}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}"
                    };


                    #region Скопировать файл на хост
                    // Проверка доступности файла
                    if (File.Exists(fileFullName))
                    {
                        //Dispatcher.Invoke(() =>
                        //{

                        if (addToListBoxTask)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                Bindings.listBoxTaskItemsSource.Add(curItemLBT);
                            });
                            //ListBoxTask.Items.Add(curItemLBT);
                        }
                        using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                        {
                            curItemLBT.MaxValueProgressBar = stream.Length;
                            //progressBarStatus.Maximum = stream.Length;
                        }
                        //progressBarStatus.Value = 0;
                        //progressBarStatus.Visibility = Visibility.Visible;
                        //Bindings.StatusBarText = $"Выполняется копирование файла {fileName}";
                        bool uploadFileStoped = false;
                        UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        //UpdateProgressBarDelegate updProgressItemTask = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        using (var sftp = new SftpClient(connectionInfo))
                        {
                            try
                            {
                                sftp.Connect();

                                using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                                {
                                    var startUpload = sftp.BeginUploadFile(stream, fileDestinationFullName, (asyncCallback) =>
                                    {
                                        //sftp.EndUploadFile(startUpload);
                                        endRunThread = true;
                                    }, null, (progressBarStatusCallBack) =>
                                    {
                                        var temp = curItemLBT.StopProcess;
                                        if (curItemLBT.StopProcess)
                                        {
                                            if (!uploadFileStoped)
                                            {
                                                try
                                                {
                                                    uploadFileStoped = true;
                                                    sftp.Disconnect();
                                                    endRunThread = true;
                                                }
                                                catch (Exception)
                                                {
                                                }
                                            }
                                        }
                                        Dispatcher.Invoke((Action)(() => { curItemLBT.CurValueProgressBar = (double)progressBarStatusCallBack; }));
                                        Dispatcher.Invoke(updProgress, System.Windows.Threading.DispatcherPriority.Render, new object[] { MetroProgressBar.ValueProperty, (double)progressBarStatusCallBack });
                                    });


                                    while (!startUpload.IsCompleted)
                                    {
                                        if (startUpload.IsCompleted)
                                        {
                                            stream.Close();
                                            stream.Dispose();
                                            endRunThread = true;
                                        }
                                    }

                                    Log(!uploadFileStoped ? $"Выполнено копирование {fileDestinationFullName} на хост {ipAddress}" : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                }
                            }
                            //catch(excep)
                            catch (Exception ex)
                            {
                                Log(!uploadFileStoped ? ex.Message : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                //Log(ex.Message, true, false, ex.StackTrace);
                            }
                            finally
                            {
                                try
                                {
                                    sftp.Disconnect();
                                    sftp.Dispose();
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                    else
                    {
                        Log($"{fileFullName} не доступен", true, true);
                    }

                    #endregion
                    //}
                }));
                startThread.Start();

                //startThread.Suspend();

                //new Thread(new ThreadStart(() =>
                //{
                //    while (!endRunThread)
                //    {
                //        if (endRunThread)
                //        {
                //            int endD = 1;
                //        }
                //    }
                //})).Start();
            }
            catch (Exception ex)
            {
                Log(ex.Message, true, true, ex.StackTrace);
            }
        }
Ejemplo n.º 37
0
 public void Test_ConnectionInfo_Username_Is_Whitespace()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, " ", Resources.PASSWORD);
 }
Ejemplo n.º 38
0
 public void Test_ConnectionInfo_BigPortNumber()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 39
0
 public void Test_ConnectionInfo_BigPortNumber()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, null, null);
 }
Ejemplo n.º 40
0
        internal static Connection GetInstance(string name, ConnectionReason reason)
        {
            UnixSystem remoteSystem = null;
            ConnectionInfoStore store = new ConnectionInfoStore();
            ConnectionInfo connectionInfo = null;

            StoredConnectionInfo storedConnectionInfo = store.Connections.FirstOrDefault(connection =>
                {
                    return name.Equals(GetFormattedConnectionName((ConnectionInfo)connection), StringComparison.OrdinalIgnoreCase);
                });

            if (storedConnectionInfo != null)
                connectionInfo = (ConnectionInfo)storedConnectionInfo;

            if (connectionInfo == null)
            {
                IVsConnectionManager connectionManager = (IVsConnectionManager)ServiceProvider.GlobalProvider.GetService(typeof(IVsConnectionManager));

                string userName;
                string hostName;

                int atSignIndex = name.IndexOf('@');
                if (atSignIndex > 0)
                {
                    userName = name.Substring(0, atSignIndex);
                    hostName = name.Substring(atSignIndex + 1);
                }
                else
                {
                    userName = string.Format(CultureInfo.CurrentCulture, StringResources.UserName_PlaceHolder);
                    hostName = name;
                }

                PasswordConnectionInfo newConnectionInfo = new PasswordConnectionInfo(hostName, userName, new System.Security.SecureString());

                IConnectionManagerResult result = connectionManager.ShowDialog(newConnectionInfo);

                if ((result.DialogResult & ConnectionManagerDialogResult.Succeeded) == ConnectionManagerDialogResult.Succeeded)
                {
                    // Retrieve the newly added connection
                    store.Load();
                    connectionInfo = store.Connections.First(info => info.Id == result.StoredConnectionId);
                }
            }

            if (connectionInfo != null)
            {
                remoteSystem = new UnixSystem();

                while (true)
                {
                    try
                    {
                        VSOperationWaiter.Wait(string.Format(CultureInfo.CurrentCulture, StringResources.WaitingOp_Connecting, name), throwOnCancel: false, action: () =>
                        {
                            remoteSystem.Connect(connectionInfo);
                        });
                        break;
                    }
                    catch (RemoteAuthenticationException)
                    {
                        IVsConnectionManager connectionManager = (IVsConnectionManager)ServiceProvider.GlobalProvider.GetService(typeof(IVsConnectionManager));
                        IConnectionManagerResult result = connectionManager.ShowDialog(StringResources.AuthenticationFailureHeader, StringResources.AuthenticationFailureDescription, connectionInfo);

                        if ((result.DialogResult & ConnectionManagerDialogResult.Succeeded) == ConnectionManagerDialogResult.Succeeded)
                        {
                            connectionInfo = result.ConnectionInfo;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (Exception ex)
                    {
                        VsShellUtilities.ShowMessageBox(ServiceProvider.GlobalProvider, ex.Message, null,
                            OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return null;
                    }
                }

                // NOTE: This will be null if connect is canceled
                if (remoteSystem != null)
                {
                    return new Connection(remoteSystem);
                }
            }

            return null;
        }
Ejemplo n.º 41
0
 public void Test_ConnectionInfo_Username_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, null, Resources.PASSWORD);
 }
Ejemplo n.º 42
0
        public void Test_Cipher_TripleDESCBC_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("3des-cbc", new CipherInfo(192, (key, iv) => { return new TripleDesCipher(key, new CbcCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 43
0
 public void Test_ConnectionInfo_Host_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(null, "username", "password");
 }
Ejemplo n.º 44
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            LogEvent iLog = new LogEvent(delegate(Object sender, PluginLogType type, string text)
            {
                if (Log != null)
                {
                    Log(sender, type, text);
                }
            });

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }



            String server   = config["server"].ToString();
            String username = config["username"].ToString();
            String password = config["password"].ToString();


            try
            {
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(server, username, password);
                connectionInfo.Timeout = new TimeSpan(0, 1, 0);

                using (SshClient client = new SshClient(connectionInfo))
                {
                    try
                    {
                        client.Connect();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro on connect SSH", ex);
                    }


                    List <UserData> users = GetList(client, config);

                    foreach (UserData u in users)
                    {
                        PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);


                        String property = "";

                        property = "username";
                        package.AddProperty(property, u.Username, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "user_id";
                        package.AddProperty(property, u.UserId, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "default_group";
                        package.AddProperty(property, u.DefaultGroup, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "information";
                        package.AddProperty(property, u.Information, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "home_path";
                        package.AddProperty(property, u.HomePath, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "bash";
                        package.AddProperty(property, u.Bash, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));


                        ImportPackageUser(package);
                    }

                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                iLog(this, PluginLogType.Error, ex.Message);
            }
        }
Ejemplo n.º 45
0
 public void Test_ConnectionInfo_Username_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo("host", null, "password");
 }
Ejemplo n.º 46
0
        public override PluginConnectorBaseFetchResult FetchFields(Dictionary <String, Object> config)
        {
            PluginConnectorBaseFetchResult ret = new PluginConnectorBaseFetchResult();

            LogEvent iLog = new LogEvent(delegate(Object sender, PluginLogType type, string text)
            {
                if (Log != null)
                {
                    Log(sender, type, text);
                }
            });


            if (!CheckInputConfig(config, true, iLog, true, true))
            {
                ret.success = false;
                return(ret);
            }

            List <PluginConfigFields> cfg = new List <PluginConfigFields>();

            PluginConfigFields[] tmpF = this.GetConfigFields();
            foreach (PluginConfigFields cf in tmpF)
            {
                try
                {
                    iLog(this, PluginLogType.Information, "Field " + cf.Name + " (" + cf.Key + "): " + (config.ContainsKey(cf.Key) ? config[cf.Key].ToString() : "empty"));
                }
                catch (Exception ex)
                {
                    iLog(this, PluginLogType.Error, "Field " + cf.Name + " (" + cf.Key + "): error on get data -> " + ex.Message);
                }
            }


            String server   = config["server"].ToString();
            String username = config["username"].ToString();
            String password = config["password"].ToString();


            try
            {
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(server, username, password);
                connectionInfo.Timeout = new TimeSpan(0, 1, 0);

                using (SshClient client = new SshClient(connectionInfo))
                {
                    try
                    {
                        client.Connect();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro on connect SSH", ex);
                    }



                    List <UserData> users = GetList(client, config);

                    ret.fields.Add("username", new List <string>());
                    ret.fields.Add("user_id", new List <string>());
                    ret.fields.Add("default_group", new List <string>());
                    ret.fields.Add("information", new List <string>());
                    ret.fields.Add("home_path", new List <string>());
                    ret.fields.Add("bash", new List <string>());


                    foreach (UserData u in users)
                    {
                        ret.fields["username"].Add(u.Username);

                        ret.fields["user_id"].Add(u.UserId);

                        ret.fields["default_group"].Add(u.DefaultGroup);

                        ret.fields["information"].Add(u.Information);

                        ret.fields["home_path"].Add(u.HomePath);

                        ret.fields["bash"].Add(u.Bash);
                    }

                    client.Disconnect();
                }

                ret.success = true;
            }
            catch (Exception ex)
            {
                iLog(this, PluginLogType.Error, ex.Message);
            }

            return(ret);
        }
Ejemplo n.º 47
0
 public void Test_ConnectionInfo_Password_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo("host", "username", null);
 }
Ejemplo n.º 48
0
 public void Test_ConnectionInfo_Username_Is_Null()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, null, Resources.PASSWORD);
 }
Ejemplo n.º 49
0
 public void Test_ConnectionInfo_Host_Is_Whitespace()
 {
     var connectionInfo = new PasswordConnectionInfo(" ", Resources.USERNAME, Resources.PASSWORD);
 }
Ejemplo n.º 50
0
 public void Test_ConnectionInfo_Username_Is_Whitespace()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, " ", Resources.PASSWORD);
 }
Ejemplo n.º 51
0
 public void Test_ConnectionInfo_SmallPortNumber()
 {
     var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MinPort - 1, null, null);
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient(controller.Account.Host, controller.Account.Port);
                _ftpc.ConnectionClosed += (o, e) =>
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null)
                    {
                        ConnectionClosed(null, new ConnectionClosedEventArgs {
                            Text = _ftpc.LastResponse.Text
                        });
                    }
                    Reconnect();
                };

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateServerCertificate += (sender, x) =>
                    {
                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(x.Certificate.Thumbprint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", x.Certificate.Thumbprint);
                            x.IsCertificateValid = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint  = x.Certificate.Thumbprint,
                            SerialNumber = x.Certificate.SerialNumber,
                            Algorithm    = x.Certificate.SignatureAlgorithm.FriendlyName,
                            ValidFrom    = x.Certificate.NotBefore.ToString("MM/dd/yy"),
                            ValidTo      = x.Certificate.NotAfter.ToString("MM/dd/yy"),
                            Issuer       = x.Certificate.IssuerName.Name
                        };

                        ValidateCertificate(null, e);
                        x.IsCertificateValid = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                    {
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    }
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                    {
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                    }
                }

                try
                {
                    _ftpc.Open(controller.Account.Username, controller.Account.Password);
                }
                catch (Exception)
                {
                    if (controller.Account.FtpsMethod == FtpsMethod.None)
                    {
                        throw;
                    }
                    bool connected = false;
                    // Try connecting with the other available Security Protocols
                    foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol)))
                    {
                        if ((controller.Account.FtpsMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit")) ||
                            (controller.Account.FtpsMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit")))
                        {
                            Log.Write(l.Debug, "Testing with {0}", p.ToString());

                            try {
                                _ftpc.Close();
                                _ftpc.SecurityProtocol = p;
                                _ftpc.Open(controller.Account.Username, controller.Account.Password);
                            }
                            catch (Exception exe) {
                                Log.Write(l.Warning, "Unable to connect: {0}", exe.GetType().ToString());
                                continue;
                            }
                            connected = true;
                            controller.Account.FtpSecurityProtocol = p;
                            break;
                        }
                    }

                    if (!connected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                        throw;
                    }
                }
            }
            else             // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                {
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                }
                else
                {
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);
                }

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key         = x.HostKeyName,
                        KeySize     = x.KeyLength.ToString()
                    };
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                    }
                    if (ConnectionClosed != null)
                    {
                        ConnectionClosed(null, new ConnectionClosedEventArgs {
                            Text = e.Exception.Message
                        });
                    }

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                    {
                        Log.Write(l.Warning, "Permission denied error occured");
                    }
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                    {
                        Reconnect();
                    }
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
            {
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                {
                    WorkingDirectory = controller.Paths.Remote;
                }
            }

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
            {
                LogServerInfo();
            }
        }
Ejemplo n.º 53
0
 [Ignore] // placeholder for actual test
 public void PasswordConnectionInfoConstructorTest14()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     string password = string.Empty; // TODO: Initialize to an appropriate value
     PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Ejemplo n.º 54
0
        public void Test_HMac_RIPEMD160_OPENSSH_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("*****@*****.**", new HashInfo(160, HashAlgorithmFactory.CreateHMACRIPEMD160));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 55
0
        private void SetupFilesystem()
        {
            Debug.WriteLine("SetupFilesystem {0},{1},{2},{3}", Host, Port, Username, ConnectionType.ToString());

            ProxyTypes pt = ProxyTypes.None;

            switch (ProxyType)
            {
            case 1: pt = ProxyTypes.Http; break;

            case 2: pt = ProxyTypes.Socks4; break;

            case 3: pt = ProxyTypes.Socks5; break;
            }
            int ProxyPort = 8080;
            var Proxy     = ProxyHost;

            if (ProxyHost != null)
            {
                var s = ProxyHost.Split(':');
                if (s.Length > 1)
                {
                    Int32.TryParse(s[1], out ProxyPort);
                    Proxy = s[0];
                }
            }

            ConnectionInfo info;

            switch (ConnectionType)
            {
            case ConnectionType.Pageant:
                var agent = new PageantProtocol();
                if (pt == ProxyTypes.None)
                {
                    info = new AgentConnectionInfo(Host, Port, Username, agent);
                }
                else if (ProxyUser.Length > 0)
                {
                    info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, agent);
                }
                else
                {
                    info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, agent);
                }
                break;

            case ConnectionType.PrivateKey:
                if (pt == ProxyTypes.None)
                {
                    info = new PrivateKeyConnectionInfo(Host, Port, Username, new PrivateKeyFile(PrivateKey, Passphrase));
                }
                else if (ProxyUser.Length > 0)
                {
                    info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, new PrivateKeyFile(PrivateKey, Passphrase));
                }
                else
                {
                    info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, new PrivateKeyFile(PrivateKey, Passphrase));
                }
                break;

            default:
                if (pt == ProxyTypes.None)
                {
                    info = new PasswordConnectionInfo(Host, Port, Username, Password);
                }
                else if (ProxyUser.Length > 0)
                {
                    info = new PasswordConnectionInfo(Host, Username, Password, pt, Proxy, ProxyPort, ProxyUser, ProxyPass);
                }
                else
                {
                    info = new PasswordConnectionInfo(Host, Port, Username, Password, pt, Proxy, ProxyPort);
                }
                break;
            }

            _connection = Settings.Default.UseNetworkDrive ? String.Format("\\\\{0}\\{1}\\{2}", info.Host, Root, info.Username) : Name;

            _filesystem = new SftpFilesystem(info, Root, _connection, Settings.Default.UseOfflineAttribute, false, (int)Settings.Default.AttributeCacheTimeout, (int)Settings.Default.DirContentCacheTimeout);
            Debug.WriteLine("Connecting...");
            _filesystem.KeepAliveInterval = new TimeSpan(0, 0, 60);
            _filesystem.Connect();
        }
Ejemplo n.º 56
0
        public override async Task Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            ConnectionInfo connectionInfo;

            if (Controller.IsPrivateKeyValid)
            {
                connectionInfo = new PrivateKeyConnectionInfo(Controller.Account.Host, Controller.Account.Port,
                                                              Controller.Account.Username,
                                                              new PrivateKeyFile(Controller.Account.PrivateKeyFile, Controller.Account.Password));
            }
            else
            {
                connectionInfo = new PasswordConnectionInfo(Controller.Account.Host, Controller.Account.Port,
                                                            Controller.Account.Username, Controller.Account.Password);
            }
            connectionInfo.Encoding = this.Charset;

            connectionInfo.AuthenticationBanner += (o, x) =>
                                                   Log.Write(l.Warning, x.BannerMessage);

            _sftpc = new Renci.SshNet.SftpClient(connectionInfo);

            _sftpc.HostKeyReceived += (o, x) =>
            {
                var fingerPrint = x.FingerPrint.GetCertificateData();

                // if ValidateCertificate handler isn't set, accept the certificate and move on
                if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                {
                    Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                    x.CanTrust = true;
                    return;
                }

                var e = new ValidateCertificateEventArgs
                {
                    Fingerprint = fingerPrint,
                    Key         = x.HostKeyName,
                    KeySize     = x.KeyLength.ToString()
                };
                // Prompt user to validate
                ValidateCertificate?.Invoke(null, e);
                x.CanTrust = e.IsTrusted;
            };

            var caughtException = default(Exception);
            await Task.Run(() =>
            {
                try
                {
                    _sftpc.Connect();
                }
                catch (SshAuthenticationException ex)
                {
                    ex.LogException();
                    caughtException = new AuthenticationException(ex.Message, ex.InnerException);
                }
                catch (SshConnectionException ex)
                {
                    ex.LogException();
                    caughtException = new CertificateDeclinedException(ex.Message, ex.InnerException);
                }
                catch (Exception ex)
                {
                    ex.LogException();
                    caughtException = ex;
                }
            });

            if (caughtException != default(Exception))
            {
                throw caughtException;
            }

            _sftpc.ErrorOccurred += async(o, e) =>
            {
                if (!IsConnected)
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                }

                OnConnectionClosed(new ConnectionClosedEventArgs {
                    Text = e.Exception.Message
                });

                if (e.Exception is SftpPermissionDeniedException)
                {
                    Log.Write(l.Warning, "Permission denied error occured");
                }
                if (e.Exception is SshConnectionException)
                {
                    await Reconnect();
                }
            };

            Controller.HomePath = WorkingDirectory;

            if (IsConnected)
            {
                if (!string.IsNullOrWhiteSpace(Controller.Paths.Remote) && !Controller.Paths.Remote.Equals("/"))
                {
                    WorkingDirectory = Controller.Paths.Remote;
                }
            }

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
            {
                LogServerInfo();
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        ///     Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public override void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");


            lock (ftpcLock)
            {
                ConnectionInfo connectionInfo;
                if (_controller.IsPrivateKeyValid)
                {
                    connectionInfo = new PrivateKeyConnectionInfo(_controller.Account.Host, _controller.Account.Port,
                                                                  _controller.Account.Username,
                                                                  new PrivateKeyFile(_controller.Account.PrivateKeyFile, _controller.Account.Password));
                }
                else
                {
                    connectionInfo = new PasswordConnectionInfo(_controller.Account.Host, _controller.Account.Port,
                                                                _controller.Account.Username, _controller.Account.Password);
                }

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key         = x.HostKeyName,
                        KeySize     = x.KeyLength.ToString()
                    };
                    // Prompt user to validate
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                    }
                    if (ConnectionClosed != null)
                    {
                        ConnectionClosed(null, new ConnectionClosedEventArgs {
                            Text = e.Exception.Message
                        });
                    }

                    if (e.Exception is SftpPermissionDeniedException)
                    {
                        Log.Write(l.Warning, "Permission denied error occured");
                    }
                    if (e.Exception is SshConnectionException)
                    {
                        Reconnect();
                    }
                };
            }

            _controller.HomePath = WorkingDirectory;

            if (isConnected)
            {
                if (!string.IsNullOrWhiteSpace(_controller.Paths.Remote) && !_controller.Paths.Remote.Equals("/"))
                {
                    WorkingDirectory = _controller.Paths.Remote;
                }

                if (connectionState == null)
                {
                    connectionState         = new BackgroundWorker();
                    connectionState.DoWork += new DoWorkEventHandler((o, e) =>
                    {
                        while (true)
                        {
                            if (!isConnected)
                            {
                                // RECONNECT
                                //_controller.Client.Reconnect();
                            }
                            Thread.Sleep(5000);
                        }
                    });

                    connectionState.RunWorkerAsync();
                }
            }

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
            {
                LogServerInfo();
            }

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }