Linux Blog

Remote SSH Port Forwarding

Filed under: General Linux — TheLinuxBlog.com at 1:00 am on Wednesday, February 23, 2011

SSH Remote Port Forwarding

SSH is an amazing tool, I often find myself finding new and interesting ways (at least to me) to use it. It is a great tool to have in your toolbox.

This may be hard to explain in works, but here goes.

Picture this: you have 3 hosts, Host A has outbound access only and is on the same network as Host B. Host B has port 22 open, accepts ssh and is allowed to ssh to Host A. Host C is the computer you are sitting at and on a different network. So, you need to connect to Host A from host C. The way to do this is with SSH port forwarding.

Lets say Host A is 192.168.1.2, Host B is 192.168.1.1 and Host C is 10.0.0.1 on the different network. Host C also has port 22 open.

So, in order to connect to Host A from Host C you can do the following with local port forwarding:

ssh -L 2222:<HostA>:22 user@HostB

Since this is a local forward in another terminal you use ssh -p 2222 remoteuser@localhost (on your localmachine host c) to connect to Host A. This works, but you have to keep the SSH session to Host B open. Which may or may not be a problem.

One thing I like to do is use the SSH Remote port forward, this gives the advantage of not needing to keep the Host C (local) -> Host B connection open. Here is how it goes:

SSH from your current workstation (local) to the host that has access to your target host (host A in this case)

user@hostC: ssh hostB

From that connection, ssh to host A (the final target)

user@hostB: ssh hostA

Now you’re on your target host, you can open screen (to resume if you need to) and then ssh back to your current workstation (host C) and use the remote forward option (-r) and use a port that is open on your current workstation (2222) to connect to localhost (host A on port 22.

user@hostA: screen

user@hostA: ssh hostC -r 2222:localhost:22

Finally, from your workstation, in another terminal window, you’ll connect to your local port 2222, to connect to Host A.

user@hostC: ssh localhost -p2222

Once this is done, you can actually de-attach from your screen session on host a, logout of host A and host B. Once that is done, you’ll essentially have a connection from host A, to host C with a port forward that allows host C to connect to host A even though you cannot SSH directly to host A from host C.

So, if you’ve followed it this far good job. Here is an attempt at drawing a graphic to represent what I typed. It should make the text a little easier to follow.

Remote SSH Port Forwarding