Example #1
0
        public void Test_PortForwarding_Remote()
        {
            //  ******************************************************************
            //  ************* Tests are still in not finished ********************
            //  ******************************************************************

            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80);
                client.AddForwardedPort(port1);
                port1.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Assert.Fail(e.Exception.ToString());
                };
                port1.Start();
                var boundport = port1.BoundPort;

                System.Threading.Tasks.Parallel.For(0, 5,
                                                    //new ParallelOptions
                                                    //{
                                                    //    MaxDegreeOfParallelism = 1,
                                                    //},
                                                    (counter) =>
                {
                    var cmd    = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport));
                    var result = cmd.Execute();
                    var end    = DateTime.Now;
                    Debug.WriteLine(string.Format("Length: {0}", result.Length));
                }
                                                    );
                Thread.Sleep(1000 * 100);
                port1.Stop();
            }
        }
 public void StopTest()
 {
     uint boundPort = 0; // TODO: Initialize to an appropriate value
     string host = string.Empty; // TODO: Initialize to an appropriate value
     uint port = 0; // TODO: Initialize to an appropriate value
     ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value
     target.Stop();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Example #3
0
        [Ignore] // placeholder
        public void StopTest()
        {
            uint   boundPort           = 0;                                              // TODO: Initialize to an appropriate value
            string host                = string.Empty;                                   // TODO: Initialize to an appropriate value
            uint   port                = 0;                                              // TODO: Initialize to an appropriate value
            ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value

            target.Stop();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        protected void Arrange()
        {
            var random = new Random();

            _closingRegister   = new List <EventArgs>();
            _exceptionRegister = new List <ExceptionEventArgs>();
            _bindEndpoint      = new IPEndPoint(IPAddress.Any, random.Next(IPEndPoint.MinPort, 1000));
            _remoteEndpoint    = new IPEndPoint(IPAddress.Parse("193.168.1.5"), random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));
            _forwardedPort     = new ForwardedPortRemote(_bindEndpoint.Address, (uint)_bindEndpoint.Port, _remoteEndpoint.Address, (uint)_remoteEndpoint.Port);

            _connectionInfoMock = new Mock <IConnectionInfo>(MockBehavior.Strict);
            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);

            _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_REQUEST_FAILURE"));
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_REQUEST_SUCCESS"));
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_CHANNEL_OPEN"));
            _sessionMock.Setup(
                p =>
                p.SendMessage(
                    It.Is <GlobalRequestMessage>(
                        g =>
                        g.RequestName == GlobalRequestName.TcpIpForward &&
                        g.AddressToBind == _forwardedPort.BoundHost &&
                        g.PortToBind == _forwardedPort.BoundPort)))
            .Callback(
                () =>
                _sessionMock.Raise(s => s.RequestSuccessReceived += null,
                                   new MessageEventArgs <RequestSuccessMessage>(new RequestSuccessMessage())));
            _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny <WaitHandle>()))
            .Callback <WaitHandle>(handle => handle.WaitOne());
            _sessionMock.Setup(
                p =>
                p.SendMessage(
                    It.Is <GlobalRequestMessage>(
                        g =>
                        g.RequestName == GlobalRequestName.CancelTcpIpForward &&
                        g.AddressToBind == _forwardedPort.BoundHost && g.PortToBind == _forwardedPort.BoundPort)))
            .Callback(
                () =>
                _sessionMock.Raise(s => s.RequestSuccessReceived += null,
                                   new MessageEventArgs <RequestSuccessMessage>(new RequestSuccessMessage())));
            _sessionMock.Setup(p => p.MessageListenerCompleted).Returns(new ManualResetEvent(false));

            _forwardedPort.Closing   += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session    = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Stop();

            _closingRegister.Clear();
        }
 protected void Act()
 {
     try
     {
         _forwardedPort.Stop();
         Assert.Fail();
     }
     catch (ObjectDisposedException ex)
     {
         _actualException = ex;
     }
 }
Example #6
0
        public static void startTunnel()
        {
            var keypath  = @"C:\file.ppk";
            var pk       = new PrivateKeyFile(keypath);
            var keyFiles = new[] { pk };

            var client = new SshClient("domain.com", 22, "root", pk);

            client.KeepAliveInterval      = new TimeSpan(0, 0, 30);
            client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
            try
            {
                client.Connect();
                Console.WriteLine("[INFO] Connecté");
            }
            catch
            {
                Console.WriteLine("[FATAL] Erreur de connexion au tunnel");
            }
            IPAddress           iplocal      = IPAddress.Parse("127.0.0.1");
            IPAddress           ipremote     = IPAddress.Parse("IP");
            UInt32              portdistant1 = 7000;
            UInt32              portlocal1   = 5900;
            UInt32              portdistant2 = 7006;
            UInt32              portlocal2   = 4500;
            ForwardedPortRemote port1        = new ForwardedPortRemote(ipremote, portdistant1, iplocal, portlocal1);
            ForwardedPortRemote port2        = new ForwardedPortRemote(ipremote, portdistant2, iplocal, portlocal2);

            client.AddForwardedPort(port1);
            client.AddForwardedPort(port2);
            port1.Exception += delegate(object sender, ExceptionEventArgs e)
            {
                Console.WriteLine("[FATAL] " + e.Exception.ToString());
            };
            port2.Exception += delegate(object sender, ExceptionEventArgs e)
            {
                Console.WriteLine("[FATAL] " + e.Exception.ToString());
            };
            port1.Start();
            port2.Start();
            Console.WriteLine("[DEBUG] Port forwarding ok");
            System.Threading.Thread.Sleep(1000 * 60 * 60 * 8);
            port1.Stop();
            port2.Stop();
            client.Disconnect();
        }
Example #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("SSH Client!");

            using (var client = new SshClient("52.231.201.187", "<SSH username>", "<SSH password>"))
            {
                try
                {
                    client.Connect();
                }
                catch (Exception ex2)
                {
                    Console.WriteLine("SSH connection error!");
                    Console.WriteLine(ex2.ToString());
                }

                // SSH Remote Port Forwarding
                // 1234 : SSH server side port(remote port)
                // 554 : local service port (ex, 80, 3389 ...)
                // localhost: local service hostname or ipaddress
                var port = new ForwardedPortRemote(1234, "127.0.0.1", 8554);

                client.AddForwardedPort(port);

                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.RequestReceived += delegate(object sender, PortForwardEventArgs e)
                {
                    Console.WriteLine(e.OriginatorHost);
                };
                port.Start();

                // ... hold the port open ... //
                Console.WriteLine("Press any key to close.");
                Console.ReadLine();

                port.Stop();
                client.Disconnect();
            }
        }
Example #8
0
        public void Test_ForwardedPortRemote()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshClient AddForwardedPort Start Stop ForwardedPortRemote
                client.Connect();
                var port = new ForwardedPortRemote(8082, "www.cnn.com", 80);
                client.AddForwardedPort(port);
                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.Start();

                Thread.Sleep(1000 * 60 * 20); //	Wait 20 minutes for port to be forwarded

                port.Stop();
                #endregion
            }
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
        public void Test_ForwardedPortRemote()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshClient AddForwardedPort Start Stop ForwardedPortRemote
                client.Connect();
                var port = new ForwardedPortRemote(8082, "www.cnn.com", 80);
                client.AddForwardedPort(port);
                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.Start();

                Thread.Sleep(1000 * 60 * 20); //	Wait 20 minutes for port to be forwarded

                port.Stop();
                #endregion
            }
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
        public void Test_PortForwarding_Remote()
        {
            //  ******************************************************************
            //  ************* Tests are still in not finished ********************
            //  ******************************************************************

            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80);
                client.AddForwardedPort(port1);
                port1.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Assert.Fail(e.Exception.ToString());
                };
                port1.Start();
                var boundport = port1.BoundPort;

                System.Threading.Tasks.Parallel.For(0, 5,

                    //new ParallelOptions
                    //{
                    //    MaxDegreeOfParallelism = 1,
                    //},
                    (counter) =>
                    {
                        var cmd = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport));
                        var result = cmd.Execute();
                        var end = DateTime.Now;
                        Debug.WriteLine(string.Format("Length: {0}", result.Length));
                    }
                );
                Thread.Sleep(1000 * 100);
                port1.Stop();
            }
        }
        public static void startTunnel()
        {
            var keypath  = @"";
            var pk       = new PrivateKeyFile(keypath);
            var keyFiles = new[] { pk };

            var client = new SshClient("server.com", 22, "user", pk);

            client.KeepAliveInterval      = new TimeSpan(0, 0, 30);
            client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
            try
            {
                client.Connect();
                Console.WriteLine("Connecté à server");
            }
            catch
            {
                Console.WriteLine("Erreur de connexion au tunnel");
            }
            IPAddress           iplocal     = IPAddress.Parse("127.0.0.1");
            IPAddress           ipremote    = IPAddress.Parse("ipserver");
            UInt32              portdistant = 22;
            UInt32              portlocal   = 25;
            ForwardedPortRemote port        = new ForwardedPortRemote(ipremote, portdistant, iplocal, portlocal);

            client.AddForwardedPort(port);
            port.Exception += delegate(object sender, ExceptionEventArgs e)
            {
                Console.WriteLine(e.Exception.ToString());
            };
            port.Start();
            Console.WriteLine("Port forwarding ok");
            System.Threading.Thread.Sleep(1000 * 60 * 60 * 8);
            port.Stop();
            client.Disconnect();
        }
 protected void Act()
 {
     _forwardedPort.Stop();
 }
        protected void Arrange()
        {
            var random = new Random();
            _closingRegister = new List<EventArgs>();
            _exceptionRegister = new List<ExceptionEventArgs>();
            _bindEndpoint = new IPEndPoint(IPAddress.Any, random.Next(IPEndPoint.MinPort, 1000));
            _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));
            _forwardedPort = new ForwardedPortRemote(_bindEndpoint.Address, (uint)_bindEndpoint.Port, _remoteEndpoint.Address, (uint)_remoteEndpoint.Port);

            _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_REQUEST_FAILURE"));
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_REQUEST_SUCCESS"));
            _sessionMock.Setup(p => p.RegisterMessage("SSH_MSG_CHANNEL_OPEN"));
            _sessionMock.Setup(
                p =>
                    p.SendMessage(
                        It.Is<TcpIpForwardGlobalRequestMessage>(
                            g =>
                                g.AddressToBind == _forwardedPort.BoundHost &&
                                g.PortToBind == _forwardedPort.BoundPort)))
                .Callback(
                    () =>
                        _sessionMock.Raise(s => s.RequestSuccessReceived += null,
                            new MessageEventArgs<RequestSuccessMessage>(new RequestSuccessMessage())));
            _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny<WaitHandle>()))
                .Callback<WaitHandle>(handle => handle.WaitOne());
            _sessionMock.Setup(
                p =>
                    p.SendMessage(
                        It.Is<CancelTcpIpForwardGlobalRequestMessage>(
                            g =>
                                g.AddressToBind == _forwardedPort.BoundHost &&
                                g.PortToBind == _forwardedPort.BoundPort)))
                .Callback(
                    () =>
                        _sessionMock.Raise(s => s.RequestSuccessReceived += null,
                            new MessageEventArgs<RequestSuccessMessage>(new RequestSuccessMessage())));
            _sessionMock.Setup(p => p.MessageListenerCompleted).Returns(new ManualResetEvent(false));

            _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Stop();

            _closingRegister.Clear();
        }
Example #14
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);
            }
        }