Monday, November 22, 2021

Forward local connection to a remote server that is accessible to public using ssh

When we use standard ssh remote forwarding, the listening ip address on the remote side will always be 127.0.0.1 or localhost, and cannot be accessed using the remote machine's IP address. If you have no idea what this is about, please refer to this guide on how to create a reverse ssh tunnel.

In order to make the remote port accessible from any ip address available in the remote machine, we can use an option, -g. This option will allow remote host to connect to local forwarded port, and in turn, make our forwarded port available on the non loopback network interfaces.


Just use this command to achieve that:
$ ssh -R 18080:localhost:8080 myremotemachine -t 'ssh -g -L 8080:localhost:18080'


The meaning of the options are:

"ssh -R 18080:localhost:8080 myremotemachine" means that, local port 8080 will be forwarded to remote host's (myremotemachine) port 18080

"-t" means, force pseudo-terminal allocation, to allow running a command on a remote ssh session

"ssh -g -L 8080:localhost:18080" means that, the local port 18080 will be available on port 8080 locally, on all interfaces.


To verify, just run ss command. You will see that port 18080 is available only for localhost, and port 8080 is available for all interfaces (0.0.0.0).

$ ss -tulpn | grep 8080 

tcp    LISTEN   0        128               0.0.0.0:8080           0.0.0.0:*      users:(("ssh",pid=20656,fd=4))                                                 

tcp    LISTEN   0        128             127.0.0.1:18080          0.0.0.0:*                                                                                     

tcp    LISTEN   0        128                  [::]:8080              [::]:*      users:(("ssh",pid=20656,fd=5))                                                 

tcp    LISTEN   0        128                 [::1]:18080             [::]:*                                                                                     

Now you are able to use port 8080 on the remote machine, and you will be tunneled to port 8080 on local machine via ssh.


No comments:

Post a Comment