Local and remote SSH port forwarding aka tunneling
Local SSH port forwarding allows you to forward requests made to a specified local port to an IP and port on a destination host via a remote host. The three different actors involved in this are:
- Your local host with a local port
- A remote host to which you can establish an SSH connection
- A destination host to which the remote host forwards requests
With this in mind let’s look at the command for establishing local port forwarding:
ssh -L localport:destinationhost:destinationport remotehost
The command could be used in the following way:
ssh -L 8080:facebook.com:80 myremotemachine
This would establish an encrypted connection to myremotemachine
via which all requests on port 8080 on the local machine would be forwarded to facebook.com on port 80. A possible use case would be to circumvent firewall restrictions, for instance if facebook.com was blocked in your current network.
Remote SSH port forwarding does the opposite. It forwards all requests to a specified port on a remote host to a destination host via your local host. Again, let’s look at the actors involved:
- A remote host to which you can establish an SSH connection
- A destination host to which the local host forwards requests
- Your local host
The command for remote port forwarding is similar to that for local port forwarding:
ssh -R remoteport:destinationhost:destinationport remotehost
An example:
ssh -R 80:hugeserver:8080 tinyserver
This would establish an SSH connection between your local machine and the tinyserver
. All requests to port 80 on tinyserver
would be forwarded to the destination host on port 8080 via your localhost. As the choice of server names implies, a use case for remote port forwarding is when you have a tiny server that cannot handle requests itself and thus forwards all requests to hugeserver
. Another use case is to host a web application on a local machine, which does not have a public IP address. With remote port forwarding a remote server with a public IP address could receive the requests and forward them to the local machine.
What is the difference to a normal SSH session
SSH itself is simply a way to establish an encrypted connection between two hosts and transfer arbitrary data over this connection. By default, the data transported via the encrypted SSH channel is a shell session, which allows you to execute shell commands on the remote host. When establishing port forwarding, SSH listens to the specified TCP port and simply transports that additional TCP data over the same connection which is used to transfer the shell session data. To disable the shell session when setting up port forwarding, you can simply pass the -N
flag to the command.