Ssh – Using SSH to tunnel over two hops, the last of which is connected through a reverse ssh tunnel

port-forwardingsshssh-tunnel

I would like to use OpenSSH to allow port forwarding over two hops, the last hop being connected through a reverse tunnel.

Here is my current setup:

  1. Server B is running sshd on port 10000. Server C is running sshd on port 20000

  2. Client A connects to Server B via "normal" SSH

  3. Server C opens a reverse SSH tunnel to Server B on port 30000

  4. Server B connects to Server C through that reverse tunnel

What I want to do: open a port on Client A that forwards connections from Client A through Server B to Server C (over the reverse SSH tunnel established between Server B and Server C)

Here are the respective commands I'm currently using:

  1. Client A connects to Server B via "normal" SSH:

     ClientAHostName $  ssh -p 10000 User@ServerBHostName
    
  2. Server C opens a reverse SSH tunnel to Server B on port 30000:

    ServerCHostName $  ssh -p 10000 -N -R 30000:localhost:20000 User@ServerBHostName
    
  3. Server B connects to Server C through that reverse tunnel:

    ServerBHostName $  ssh -p 30000 User@localhost
    

The reason I want to do this is so I can control certain services on Server C from Client A through a web browser (using a forwarded port). Due to limitations imposed by the ISPs of Client A and Server C, I cannot connect directly from Server B (or Client A) to Server C, or from Server C to Client A.

Best Answer

To make things simpler I like to assign a port number or range to each server. Keeping what you've started with, B is 10000, C is 20000, forget about the 30000.

Setup:

A$ ssh -p 10000 -N -L 20000:localhost:20000 UserB@B
C$ ssh -p 10000 -N -R 20000:localhost:20000 UserB@B

Now you should be able to do

A$ ssh -p 20000 UserC@localhost

to get a shell on C, and assuming you want to connect to a web server running on server C port 8080:

A$ ssh -p 20000 -N -L 8080:localhost:8080 UserC@localhost

Connect to:

http://localhost:8080/