Provides functionality for local port forwarding
Inheritance: ForwardedPort, IDisposable
Esempio n. 1
0
 public void OpenPort(uint local, uint remote)
 {
     if (!_connected) { Connect(); }
     var port = new ForwardedPortLocal("localhost",local,_client.ConnectionInfo.Host,remote);
     _client.AddForwardedPort(port);
     _ports.Add(port);
     port.Start();
 }
Esempio n. 2
0
        static int HackExtractPort(ForwardedPortLocal fwl)
        {
            var type = fwl.GetType();
            var listener = (System.Net.Sockets.TcpListener)type
                .GetField("_listener",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)
                .GetValue(fwl);

            return ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
        }
        public static void SSH_Start()
        {
            string host = ConfigurationManager.AppSettings["MongoSSHHost"];
            if (!String.IsNullOrEmpty(host) && PersistenceGlobal.SshClient == null)
            {
                string user = ConfigurationManager.AppSettings["MongoSSHUser"];
                string pwd = ConfigurationManager.AppSettings["MongoSSHPassword"];

                PersistenceGlobal.SshClient = new SshClient(host, user, pwd);

                PersistenceGlobal.SshClient.Connect();

                var connData = ConfigurationManager.AppSettings["MongoConnectionString"].Replace("mongodb://", "").Split(':');
                var port = new ForwardedPortLocal("127.0.0.1", Convert.ToUInt32("27017"), connData[0], Convert.ToUInt32(connData[1]));
                PersistenceGlobal.SshClient.AddForwardedPort(port);
                port.Start();

                AppDomain.CurrentDomain.DomainUnload += new EventHandler(SSH_Stop);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// SSH连接端口转发
        /// </summary>
        /// <param name="server">服务器地址</param>
        /// <param name="port">服务器端口</param>
        /// <param name="uid">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public static bool sshConnected(string server, int port, string uid, string pwd) {
            bool sshState = false;
            var client = new SshClient(server, port, uid, pwd);
            try {
                client.Connect();
                Constant.sshConnected = client.IsConnected;
            } catch(Exception ex) {
                throw ex;
            }
            var porcik = new ForwardedPortLocal("localhost", 3306, "localhost", 3306);
            try {
                client.AddForwardedPort(porcik);
                porcik.Start();
                sshState = true;
            } catch(Exception ex) {
                throw ex;
            }
            return sshState;

        }
Esempio n. 5
0
        public Proxy(Target target)
        {
            _client = new SshClient(target.ProxyServer.Host,
                target.ProxyServer.UserInfo,
                target.ProxyPassword);
            _client.Connect();

            var fwPort = new ForwardedPortLocal("127.0.0.1",0, target.TargetServer.Host, (uint) target.TargetServer.Port);
            _client.AddForwardedPort(fwPort);
            fwPort.Start();

            var port = HackExtractPort(fwPort); // TODO: Update the library to read it directly from BoundPort

            _localUri = string.Format("{0}://{1}@127.0.0.1:{2}{3}", target.TargetServer.Scheme,
                target.TargetServer.UserInfo,
                port,
                target.TargetServer.LocalPath);

            _subBackend = Backend.OpenBackend(new Uri(_localUri), target.Password);
        }
Esempio n. 6
0
        /// <summary>
        /// Starts an ssh tunnel, where conntection to a local port (which this will listen on), transparently connects it to a remote port.
        /// </summary>
        /// <returns><c>true</c>, if tunnel was started, <c>false</c> otherwise.</returns>
        /// <param name="TunnelPortLocal">Tunnel port local.</param>
        /// <param name="TunnelPortRemote">Tunnel port remote.</param>
        /// <param name="LocalNetwork">Local network.</param>
        public bool StartTunnel(UInt32 TunnelPortLocal, UInt32 TunnelPortRemote, String LocalNetwork = null)
        {
            if (!ConnectSSH ())	return false;

            try
            {

            if (LocalNetwork == null) LocalNetwork = IPAddress.Loopback.ToString ();

            Write ("ssh tunnel: {0}:{1} -> {2}:{3}...",LocalNetwork, TunnelPortLocal, "localhost", TunnelPortRemote);
            if (forwardPort!=null)
            {
                if (forwardPort.BoundPort == TunnelPortLocal && forwardPort.Port == TunnelPortRemote) {
                    if (forwardPort.IsStarted) {
                        WriteLine ("Tunnel already connencted");
                        return true;
                    } else {
                        forwardPort.Dispose ();
                    }
                } else {
                    forwardPort.Dispose ();
                }
            }

            forwardPort = new ForwardedPortLocal(LocalNetwork, TunnelPortLocal, "localhost", TunnelPortRemote);

            sshClient.AddForwardedPort(forwardPort);

            forwardPort.Exception += (object sender, ExceptionEventArgs e) =>
            {
                    WriteLine("Tunnel error: {0}",e.Exception.Message);
            };

            forwardPort.RequestReceived += (object sender, PortForwardEventArgs e) =>
            {
                WriteLine("Tunnel connection: {0}->{1}",e.OriginatorHost, e.OriginatorPort);
            };
            forwardPort.Start();
            WriteLine ("OK");

            return forwardPort.IsStarted;

            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.AccessDenied)
                {
                    WriteLine("FAILED\r\nAccess Denied - Cannot create port redirect. Try running Monodevelop with higher privileges.");
                }
                else
                {
                    WriteLine("FAILED\r\nTunnel Error: {0}",ex);
                }
            }
            catch (Exception ex)
            {
                WriteLine("Tunnel Error: {0}",ex);
            }
            return false;
        }
Esempio n. 7
0
        /// <summary>
        /// Setup the SSH connection, port forwarding, and connect.
        /// </summary>
        private bool setupSSH()
        {
            // Need username?
              if (this.connection.SSHUsername == "") {
            this.log("Requesting SSH username from user.");

            fmRequestInput dialog = new fmRequestInput("Enter your SSH username to connect.");
            DialogResult dialogResult = dialog.ShowDialog(this);

            if (dialogResult == System.Windows.Forms.DialogResult.OK)
              this.connection.SSHUsername = dialog.tbInput.Text.Trim();
            else {
              this.log("User aborted the connect process.", ICON_WARNING);
              return false;
            }
              }

              // Need password?
              if (this.connection.SSHPassword == "") {
            this.log("Requesting SSH password from user.");

            fmRequestInput dialog = new fmRequestInput("Enter your SSH password to connect.", true);
            DialogResult dialogResult = dialog.ShowDialog(this);

            if (dialogResult == System.Windows.Forms.DialogResult.OK)
              this.connection.SSHPassword = Encryption.Encrypt(dialog.tbInput.Text);
            else {
              this.log("User aborted the connect process.", ICON_WARNING);
              return false;
            }
              }

              try {
            this.log("Setting up SSH connection.");

            this.sshClient = new SshClient(
              this.connection.SSHHostname,
              (int)this.connection.SSHPort,
              this.connection.SSHUsername,
              Encryption.Decrypt(this.connection.SSHPassword));

            this.log("Attempting to connect to SSH, " + this.connection.SSHUsername + "@" + this.connection.SSHHostname + ":" + this.connection.SSHPort.ToString());

            this.sshClient.Connect();

            this.log("SSH connected.");
              }
              catch (SshException sshex) {
            this.log("SSH Exception: " + sshex.Message, ICON_ERROR);
            return false;
              }
              catch (Exception ex) {
            this.log("Exception: " + ex.Message, ICON_ERROR);
            return false;
              }

              uint localPort = this.connection.LocalForwardedPort;
              uint attempts = 1;
              uint maxAttempts = 10;

              Random random = new Random();

              while (true) {
            if (this.connection.LocalForwardedPort == 0)
              localPort = (uint)random.Next(10000, 65000);

            try {
              this.log("Attempting (" + attempts.ToString() + " of " + maxAttempts.ToString() + ") to setup port forwarding on local port " + localPort.ToString() + " to remote port " + this.connection.MySQLPort.ToString() + ".");

              ForwardedPortLocal forwardedPort = new ForwardedPortLocal(
            "127.0.0.1",
            localPort,
            "localhost",
            this.connection.MySQLPort);

              this.sshClient.AddForwardedPort(forwardedPort);
              forwardedPort.Start();

              this.log("Port forwarding successfully setup on local port " + localPort.ToString() + ".");
              this.connection.ForwardedPort = localPort;

              break;
            }
            catch (SshException sshex) {
              this.log("SSH Exception: " + sshex.Message, ICON_ERROR);
              break;
            }
            catch (Exception ex) {
              if (ex.Message == "An attempt was made to access a socket in a way forbidden by its access permissions") {
            this.log("Unable to bind local port to " + localPort.ToString() + ". " + ex.Message, ICON_WARNING);
              }
              else {
            this.log("Exception: " + ex.Message, ICON_ERROR);
            break;
              }
            }

            localPort++;
            attempts++;

            if (attempts == maxAttempts) {
              this.log("Unable to bind local port for port forwarding. Aborting.", ICON_ERROR);
              return false;
            }
              }

              return true;
        }
 public void AddForwardedPort(uint localPort, string host, uint port)
 {
     try
     {
         var dPort = new ForwardedPortLocal("127.0.0.1", localPort, host, port);
         conn.AddForwardedPort(dPort);
         dPort.Start();
     }
     catch (SocketException e)
     {
         Logger.LOG_SSH.Error(e.Message);
     }
 }
Esempio n. 9
0
        public void Dispose()
        {
            if (port != null)
                port.Dispose();
            if (client != null)
                client.Dispose();

            port = null;
            client = null;
        }
Esempio n. 10
0
        private void ConnectSSH(string ip, string port, string dbname, string account, string pw, string sshhostname, string sshuser, string sshpw)
        {
            SshClient_ = new SshClient(ip, sshuser, sshpw);
            SshClient_.Connect();
            var fowardport = new ForwardedPortLocal("127.0.0.1", sshhostname, Convert.ToUInt32(port));
            //var fowardport = new ForwardedPortLocal("127.0.0.1", 25251, sshhostname, Convert.ToUInt32(port));
            SshClient_.AddForwardedPort(fowardport);

            //private string connection_string_ssh_ = "server={0};user={1};database={2};port={3};password={4};";
            fowardport.Start();
            real_connection_string_ = string.Format(connection_string_ssh_, "127.0.0.1", account, dbname, fowardport.BoundPort, pw);

            MySqlConnection_ = new MySqlConnection(real_connection_string_);
        }
Esempio n. 11
-1
        public SshTunnel(ConnectionInfo connectionInfo, uint remotePort)
        {
            try
            {
                client = new SshClient(connectionInfo);
                port = new ForwardedPortLocal("127.0.0.1", "leisuredb01", remotePort);
                //port = new ForwardedPortLocal("127.0.0.1", 3306, "leisuredb01", remotePort);
                //port = new ForwardedPortLocal("127.0.0.1", 22, "leisuredb01", remotePort);
                //port = new ForwardedPortLocal("127.0.0.1", "leisuredb01", remotePort);
                //port = new ForwardedPortLocal()

                //client.ErrorOccurred += (s, args) => args.Dump();
                //port.Exception += (s, args) => args.Dump();
                //port.RequestReceived += (s, args) => args.Dump();

                client.Connect();
                client.AddForwardedPort(port);
                port.Start();

                // Hack to allow dynamic local ports, ForwardedPortLocal should expose _listener.LocalEndpoint
                var listener = (TcpListener)typeof(ForwardedPortLocal).GetField("_listener", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(port);
                localPort = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
            }
            catch
            {
                Dispose();
                throw;
            }
        }