Reverse SSH tunnel shows connection to 127.0.0.1 instead of IP

Imagine the situation where you have 2 hosts:

  1. server – with public IP accessible via Internet
  2. client – with access to Internet but behind firewall so it is not accessible via Internet

You want to access client via SSH over the Internet but you can not access it because it is behind firewall that does not allow connections to the host via public IP.

My idea was to use reverse SSH tunnel started on client side, so I will be able to access client via server IP.

On your client you need to start SSH connection with something like:

ssh -f -T -N -R SERVER_IP:SERVER_PORT_TO_ACCESS_CLIENT:localhost:CLIENT_PORT_TO_ACCESS user@SERVER_PUBLIC_IP -p SERVER_SSH_PORT

If this works, you could access your client directly from server by using 127.0.0.1 since the reverse tunnel will listen only on localhost.

tcp 0 0 127.0.0.1:9999 0.0.0.0:* LISTEN

So your server is listening on localhost instead on SERVER_IP you ran on the client.

Chech your SSHd server configuration for example in file /etc/ssh/sshd_config following option should be enabled:

GatewayPorts yes

If it is not present you need to add it to your sshd_config and restart sshd.

tcp 0 0 0.0.0.0:9999 0.0.0.0:* LISTEN

You will be able to access your client port from any IP on server via port 9999 in this example.

 

Configure SSH client to keep connection alive in Linux

To keep SSH connection alive you must edit your ~/.ssh/config file (if the file does not exist create it) and enter the following on top of the file:

Host *
ServerAliveInterval 60

First line applies this config to all hosts (*), and the second one is interval when to send keepalive packets in seconds (60).