Пример #1
0
 private void closeAll()
 {
     client.RemoveForwardedPort(fwPort);
     fwPort.Dispose();
     client.Disconnect();
     client.Dispose();
 }
Пример #2
0
        public void RemoveForwardedPortTest()
        {
            ConnectionInfo connectionInfo = null;                          // TODO: Initialize to an appropriate value
            SshClient      target         = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
            ForwardedPort  port           = null;                          // TODO: Initialize to an appropriate value

            target.RemoveForwardedPort(port);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Пример #3
0
 /// <summary>
 /// If port forwarding is taking place in the sshClient, removes the port forwarding capabilities from it.
 /// </summary>
 private void RemoveForwardPort()
 {
     if (_forwardedPort != null)
     {
         if (_client != null)
         {
             _client.RemoveForwardedPort(_forwardedPort);
         }
         _forwardedPort.Dispose();
     }
 }
Пример #4
0
        private void StopPortForwarding()
        {
            foreach (ForwardedPortLocal forwardedPortLocal in sshClient.ForwardedPorts.ToArray())
            {
                logger?.LogInformation($"Stopping port forwarding from {forwardedPortLocal.BoundHost}:{forwardedPortLocal.BoundPort} " +
                                       $"to server's {forwardedPortLocal.Host}:{forwardedPortLocal.Port}...");

                sshClient.RemoveForwardedPort(forwardedPortLocal);
            }

            logger?.LogInformation($"All port forwarding stopped.");
        }
Пример #5
0
        public static void StopForwarding(int local_port)
        {
            System.Diagnostics.Debug.WriteLine("Attempting to stop forwarding on port " + local_port);

            foreach (ForwardedPortLocal port in client.ForwardedPorts)
            {
                if (port.BoundPort == local_port)
                {
                    client.RemoveForwardedPort(port);
                    break;
                }
            }
        }
Пример #6
0
        public bool Close()
        {
            bool bResult = true;

            if (MySqlConnection_ != null)
            {
                MySqlConnection_.Close();
                MySqlConnection_.Dispose();
                MySqlConnection_ = null;
            }
            else
            {
                bResult = false;
            }

            if (SshClient_ != null)
            {
                foreach (var pData in SshClient_.ForwardedPorts.ToArray())
                {
                    if (pData.IsStarted)
                    {
                        pData.Stop();
                    }

                    SshClient_.RemoveForwardedPort(pData);
                }

                if (SshClient_.IsConnected == true)
                {
                    SshClient_.Disconnect();
                    SshClient_.Dispose();
                }
                else
                {
                    bResult = false;
                }

                SshClient_ = null;
            }
            else
            {
                bResult = false;
            }


            return(bResult);
        }
Пример #7
0
        private bool Reconnect()
        {
            _client.ErrorOccurred -= OnErrorHandler;

            var retryCount = NUMBERS_OF_RETRIES;

            foreach (var port in _ports)
            {
                _client.RemoveForwardedPort(port.NativePort);
            }

            while (!_client.IsConnected && retryCount-- > 0)
            {
                Thread.Sleep(1500);
                _loggerProvider.Write("Reconnect... Attempt: " + (NUMBERS_OF_RETRIES - retryCount));

                try
                {
                    ConnectionStatusChanged?.Invoke(ConnectionStatus.Reconnecting);
                    _client.Connect();
                }
                catch (Exception e)
                {
                    _loggerProvider.Write("Reconnect exception: " + e);
                    ConnectionStatusChanged?.Invoke(ConnectionStatus.Failed);
                }

                if (_client.IsConnected)
                {
                    _loggerProvider.Write("Connection established.");
                    ConnectionStatusChanged?.Invoke(ConnectionStatus.Established);

                    foreach (var p in _ports)
                    {
                        p.Init();
                        _client.AddForwardedPort(p.NativePort);
                        p.Start();
                    }

                    _client.ErrorOccurred += OnErrorHandler;
                }
            }
            return(_client.IsConnected);
        }
Пример #8
0
        void SSHConnect(object sender, DoWorkEventArgs e)
        {
            if (_MainForm.textBox1.Text == string.Empty)
            {
                MessageBox.Show("No hostname specified"); return;
            }
            if (_MainForm.textBox2.Text == string.Empty)
            {
                MessageBox.Show("No username specified");
            }
            if (!_MainForm.radioButton1.Checked && !_MainForm.radioButton2.Checked)
            {
                MessageBox.Show("No authentication specified"); return;
            }
            try
            {
                using (var client = new SshClient(_MainForm.textBox1.Text, _MainForm.textBox2.Text, _MainForm.getAuth()))
                {
                    var ProxyPort = new ForwardedPortDynamic("127.0.0.1", 1080);
                    _MainForm.WriteLog("Attempting connection to " + _MainForm.textBox1.Text);
                    client.Connect();
                    if (client.IsConnected)
                    {
                        //Connect
                        isConnected = true;
                        _MainForm.WriteLog("Connected");
                        _MainForm.WriteLog("Adding SOCKS port: " + ProxyPort.BoundHost + ":" + ProxyPort.BoundPort);
                        client.AddForwardedPort(ProxyPort);
                        ProxyPort.Start();
                        _MainForm.WriteLog("Ready for connections");
                        _MainForm.ConnectionButton.Text = "Disconnect";
                        _MainForm.textBox1.ReadOnly     = true;
                        _MainForm.textBox2.ReadOnly     = true;
                        _MainForm.textBox3.ReadOnly     = true;
                        _MainForm.radioButton1.Enabled  = false;
                        _MainForm.radioButton2.Enabled  = false;
                        _MainForm.textBox4.ReadOnly     = true;
                        _MainForm.textBox5.ReadOnly     = true;
                        _MainForm.button3.Enabled       = false;
                        _MainForm.WriteLog("Setting windows proxy");
                        _MainForm.WriteLog("Connected");
                        RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                        registry.SetValue("ProxyEnable", 1);
                        registry.SetValue("ProxyServer", "socks=127.0.0.1:1080");
                        settingsReturn           = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        refreshReturn            = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                        ConnectionButton.Enabled = true;

                        while (isConnected)
                        {
                            Thread.Sleep(1000);
                        }
                        //Disconnect
                        _MainForm.WriteLog("Setting windows proxy to default values");
                        WriteLog("Disconnecting");
                        registry.SetValue("ProxyEnable", 0);
                        registry.DeleteValue("ProxyServer");
                        settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        refreshReturn  = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                        ProxyPort.Stop();
                        client.RemoveForwardedPort(ProxyPort);
                        client.Disconnect();
                        Thread.Sleep(500);
                        WriteLog("Disconnected");
                        _MainForm.textBox1.ReadOnly     = false;
                        _MainForm.textBox2.ReadOnly     = false;
                        _MainForm.textBox3.ReadOnly     = false;
                        _MainForm.radioButton1.Enabled  = true;
                        _MainForm.radioButton2.Enabled  = true;
                        _MainForm.textBox4.ReadOnly     = false;
                        _MainForm.textBox5.ReadOnly     = false;
                        _MainForm.button3.Enabled       = true;
                        ConnectionButton.Enabled        = true;
                        _MainForm.ConnectionButton.Text = "Connect";
                    }
                }
            } catch (Exception ex)
            {
                _MainForm.WriteLog(ex.Message);
                MessageBox.Show(ex.Message);
                _MainForm.textBox1.ReadOnly     = false;
                _MainForm.textBox2.ReadOnly     = false;
                _MainForm.textBox3.ReadOnly     = false;
                _MainForm.radioButton1.Enabled  = true;
                _MainForm.radioButton2.Enabled  = true;
                _MainForm.textBox4.ReadOnly     = false;
                _MainForm.textBox5.ReadOnly     = false;
                _MainForm.button3.Enabled       = true;
                ConnectionButton.Enabled        = true;
                _MainForm.ConnectionButton.Text = "Connect";
            }
        }
Пример #9
0
        private static void RunEx(ClientConfiguration.SshOptions config)
        {
            BondManager.CurrentPorts.Clear();

            try
            {
                _log.Info(
                    $"Starting SSH client with {config.KeepAliveIntervalInSeconds}s keep-alive to {config.Host}:{config.Port} as {config.Username}...");

                using (var client = new SshClient(config.Host, config.Port, config.Username, config.Password))
                {
                    try
                    {
                        client.Connect();
                        client.KeepAliveInterval = TimeSpan.FromSeconds(config.KeepAliveIntervalInSeconds);

                        client.ErrorOccurred   += delegate(object sender, ExceptionEventArgs e) { _log.Trace(e); };
                        client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            _log.Trace($"Host key received: {e.HostKey}:{e.HostKeyName}");
                        };

                        foreach (var forwardedPort in config.SshPorts)
                        {
                            //define port and add it to client
                            var port = new ForwardedPortRemote(forwardedPort.Server, forwardedPort.ServerPort, forwardedPort.Guest,
                                                               forwardedPort.GuestPort);
                            client.AddForwardedPort(port);

                            //add delegates to handle port exceptions and requests received
                            port.Exception       += delegate(object sender, ExceptionEventArgs e) { _log.Info(e.Exception.ToString()); };
                            port.RequestReceived += delegate(object sender, PortForwardEventArgs e)
                            {
                                _log.Info($"{e.OriginatorHost}:{e.OriginatorPort}—{sender}");
                            };

                            //start the port, which will give us connection information back from server
                            port.Start();
                            //get that bound port from server
                            _log.Info($"Bound port: {port.BoundPort} - Is started?: {port.IsStarted}");

                            forwardedPort.ServerPort = port.BoundPort;

                            if (!BondManager.CurrentPorts.Contains(forwardedPort))
                            {
                                BondManager.CurrentPorts.Add(forwardedPort);
                            }
                        }

                        var result = client.RunCommand("uptime");
                        _log.Info(result.Result);

                        while (client.IsConnected)
                        {
                            // ... hold the port open ... //
                            Thread.Sleep(1000);
                        }
                    }
                    catch (SocketException se)
                    {
                        _log.Error(se);
                    }
                    catch (Exception e)
                    {
                        _log.Error(e);
                    }
                    finally
                    {
                        try
                        {
                            foreach (var port in client.ForwardedPorts)
                            {
                                port.Stop();
                                client.RemoveForwardedPort(port);
                                _log.Info($"Bound port stopped and removed: {port}");
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }

                        client.Disconnect();
                        _log.Info($"Client disconnected...");
                    }
                }
            }
            catch (SocketException se)
            {
                _log.Error(se);
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
        }
Пример #10
0
 public void RemoveForwardedPortTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     ForwardedPort port = null; // TODO: Initialize to an appropriate value
     target.RemoveForwardedPort(port);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Пример #11
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            iSFtp = new SftpClient(txtSFtpIP.Text, Convert.ToInt32(numUpDownSFtpPort.Value), txtSFtpUsername.Text, txtSFtpPassword.Text);

            try {
                iSFtp.Connect();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                iSFtp.Dispose();
                iSFtp = null;

                FlashState();
                return;
            }

            if (checkBoxUseSSH.Checked)
            {
                // Setup SSH connection.
                iSSHClient = new SshClient(txtSSHTunnelIP.Text, Convert.ToInt32(numUpDownSSHTunnelPort.Value), txtSSHTunnelUsername.Text, txtSSHTunnelPassword.Text);

                try {
                    iSSHClient.Connect();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    iSSHClient.Dispose();
                    iSSHClient = null;

                    iSFtp.Disconnect();
                    iSFtp.Dispose();
                    iSFtp = null;

                    FlashState();
                    return;
                }

                // Setup port forwarding.
                iSSHTunnel = new ForwardedPortLocal("127.0.0.1", 0, txtDBIP.Text, Convert.ToUInt32(numUpDownDBPort.Value));
                iSSHClient.AddForwardedPort(iSSHTunnel);

                try {
                    iSSHTunnel.Start();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    iSSHClient.RemoveForwardedPort(iSSHTunnel);

                    iSSHTunnel.Dispose();
                    iSSHTunnel = null;

                    iSSHClient.Disconnect();
                    iSSHClient.Dispose();
                    iSSHClient = null;

                    iSFtp.Disconnect();
                    iSFtp.Dispose();
                    iSFtp = null;

                    FlashState();
                    return;
                }
            } // End if(checkBoxUseSSH.Checked)

            MySqlConnectionStringBuilder connStrBuilder = new MySqlConnectionStringBuilder();

            connStrBuilder.Server   = checkBoxUseSSH.Checked ? iSSHTunnel.BoundHost : txtDBIP.Text;
            connStrBuilder.Port     = checkBoxUseSSH.Checked ? iSSHTunnel.BoundPort : Convert.ToUInt32(numUpDownDBPort.Value);
            connStrBuilder.UserID   = txtDBUsername.Text;
            connStrBuilder.Password = txtDBPassword.Text;

            MysqlConn = new MySqlConnection(connStrBuilder.GetConnectionString(true));

            try {
                MysqlConn.Open();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                MysqlConn.Dispose();
                MysqlConn = null;

                if (checkBoxUseSSH.Checked)
                {
                    iSSHTunnel.Stop();

                    iSSHClient.RemoveForwardedPort(iSSHTunnel);

                    iSSHTunnel.Dispose();
                    iSSHTunnel = null;

                    iSSHClient.Disconnect();
                    iSSHClient.Dispose();
                    iSSHClient = null;
                }

                iSFtp.Disconnect();
                iSFtp.Dispose();
                iSFtp = null;

                FlashState();
                return;
            }

            // Connect Done.
            Connected = true;
            FlashState();
        }