Using SSH to Tunnel Between Ports
SSH connection allows you to open itself as a "tunnel" (do not confused with VPN). It facilitates port secure connection across internet for non-secure applications like VNC. However, if the destination machine is behind a firewall server, it needs to be allowed for SSH tunneling for the given domain name, IP address and port.
We will do it step by step.
Preparing SSH Server on Remote Side
SSH Server Configurations
If you're tunneling SSH protocol, you need to enable this to your /etc/ssh/sshd_config
:
GatewayPorts yes
If you're tunneling via TCP (e.g. using a remote desktop solution that has TCP Tunneling capability, you need to enable allow TCP forwarding:
AllowTcpForwarding yes
Setup SSH Connection
Now, we can setup SSH connection with the destination machine. We will be using a port forwarding mechanism when we setup the connection. Here is the command:
$ ssh -N -f -L <local_port>:localhost:<destination_port> USER@IP_OR_DOMAIN_NAME
# example
$ ssh -N -f -L 5000:localhost:5901 u0@192.168.0.1
This will forward the destination port to our localhost:port. In this example above, it is 192.168.0.1:5901
to localhost:5000
.
Local App Connecting to Local Port
This section is about establishing a connection between local application via the tunnelled port.
Local App Connecting to Local Port
Once done, instead of connecting to the destination directly, have your local application like VNC to connect to the local port-forwarded address. From the example above, we should have the following command for VNC application:
$ <APP> localhost:<local_port>
# example
$ vncviewer localhost:5901
SSH Connecting Remote Server via Tunnelled Port
Once done, instead of connecting to the destination directly, have your local SSH client to connect to the local port-forwarded address. From the example above, we should have the following command:
$ ssh -R <remote_port>:localhost:<local tunnelled port> <remote user>@<remote domain>
# example
$ ssh -R 22:localhost:5283 u0@testSubject
That's all about SSH tunneling. It's dead simple to establish connection between machines across internet securely.