Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a forwarded port within an SSH tunnel

I'm attempting to use SSH.NET to create a tunnel from localhost:3306 to port 3306 on a remote machine:

  PrivateKeyFile file = new PrivateKeyFile(@" .. path to private key .. ");
  using (var client = new SshClient(" .. remote server .. ", "ubuntu", file))
  {

      client.Connect();
      var port = new ForwardedPortLocal(3306, "localhost", 3306);
      client.AddForwardedPort(port);
      port.Start();

            // breakpoint set within the code here

      client.Disconnect();
  }

When the breakpoint is hit, client.IsConnected is returning true, but telnet localhost 3306 is not connecting. If I create the connection using Putty instead, and set up the same tunnel there, it succeeds. What have I missed?

like image 921
Adrian Wragg Avatar asked Aug 29 '13 10:08

Adrian Wragg


People also ask

What is SSH tunnel port forwarding?

SSH tunneling, or SSH port forwarding, is a method of transporting arbitrary data over an encrypted SSH connection. SSH tunnels allow connections made to a local port (that is, to a port on your own desktop) to be forwarded to a remote machine via a secure channel.

How do I tunnel a port over SSH?

Set up SSH Tunneling in WindowsLaunch Putty and enter the SSH server IP Address in the Host name (or IP address) field. Under the Connection menu, expand SSH and select Tunnels . Check the Local radio button to setup local, Remote for remote, and Dynamic for dynamic port forwarding.

Does SSH support port forwarding?

SSH is a secure shell and it offers a private connection between hosts. SSH port forwarding is one method that is used to tunnel traffic through an SSH connection. This can be done either locally or remotely if you are not close by to the target machine. Port 22 is used by default for establishing SSH connections.


1 Answers

By changing the parameters of ForwardedPortLocal to:

    var port = new ForwardedPortLocal("localhost", 3306, "localhost", 3306);

(to make it explicit which interface I was binding to), and adding the following code in just before port.Start();:

    port.RequestReceived += delegate(object sender, PortForwardEventArgs e)
    {
        Console.WriteLine(e.OriginatorHost + ":" + e.OriginatorPort);
    };

I noticed the following being output:

    ::1:60309

The e.OriginatorHost part of this was ::1, which is the IPv6 equivalent of localhost; however, the destination server was using IPv4. Changing the parameters to:

    var port = new ForwardedPortLocal("127.0.0.1", 3306, "localhost", 3306);

forced the tunnel to run over IPv4 instead, and my code then worked exactly as I'd expected it to.

like image 112
Adrian Wragg Avatar answered Sep 20 '22 08:09

Adrian Wragg