To allow LOCAL_SERVER behind a firewall/NAT/Home Router to be accessible via SSH from a REMOTE_SERVER you can use a ssh tunnel (reverse).
Basically, from your LOCAL_SERVER you forward port 22 (ssh) to another port on REMOTE_SERVER, for example 8000 and you can ssh into your LOCAL_SERVER from the public IP of the REMOTE_SERVER via port 8000.
To do so, you need to run the following from LOCAL_SERVER:
local-server: ~ ssh -fNR 8000:localhost:22 <user>@<REMOTE_SERVER>
On REMOTE_SERVER you can use netstat -nlpt
to check if there is a service listening on port 8000.
Example:
remote-server ~# netstat -nplt | grep 8000 tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 1396/sshd: root tcp6 0 0 :::8000 :::* LISTEN 1396/sshd: root
In this case, the REMOTE_SERVER allows connection from ALL the interfaces (0.0.0.0) to port 8000.
This means that, if the REMOTE_SERVER has IP 217.160.150.123, if you can connect to LOCAL_SERVER from a THIRD_SERVER using the following:
third-server: ~ ssh -p 8000 <user_local_server>@217.160.150.123
NOTE. If you see that the LISTEN connection on REMOTE_SERVER is bound to 127.0.0.1 and not to 0.0.0.0, it is probably related to the setting GatewayPorts
set to no
in /etc/ssh/sshd_config
on REMOTE_SERVER.
Best setting is clientspecified
(rather than yes) as per this post.
Set this value to yes and restart sshd service.
With that setting, you can potentially allow only connection from the REMOTE_SERVER to the LOCAL_SERVER, to increase security.
To do so, you need to use the following ssh command from LOCAL_SERVER:
local-server: ~ ssh -fNR 127.0.0.1:8000:localhost:22 <user>@<REMOTE_SERVER>
With netstat, you’ll see now this:
remote-server:~# netstat -nplt | grep 8000 tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 1461/sshd: root
With this forward, you will be able to access LOCAL_SERVER ONLY from the REMOTE_SERVER itself:
remote-server: ~ ssh -p 8000 <user_local_server>@localhost
I hope this helps 🙂
Happy tunnelling!