The server IP is 1.1.1.1.
The user on the server is relayserver_user.
The user on the client is homeserver_user.
Connect to the server. Edit the '/etc/ssh/sshd_config' file:
sudo nano /etc/ssh/sshd_config
Add this line to the file:
GatewayPorts clientspecified
Restart the server.
Connect to the client. Run this command:
ssh -fN -R :10022:localhost:22 relayserver_user@1.1.1.1
10022 will be the port on the relayserver.
Done that, go back to server and run this:
sudo netstat -nap | grep 10022
The result must be something like this, to show that the port is allocated:
tcp 0 0 1.1.1.1:10022 0.0.0.0:* LISTEN 1538/sshd: dev
If everything is alright, we now can connect to the remote machine.
Run this command to connect with SSH:
ssh -p 10022 homeserver_user@1.1.1.1
Now you are using the 10022 port to connect on the relayserver IP, using the homeserver_user.
Now you are connected to the remote SSH using the server as a relay.
Install AutoSSH:
sudo apt-get install autossh
Generate a SSH Key:
ssh-keygen -t rsa
Now we will send to the server the generated key:
ssh-copy-id -i ~/.ssh/id_rsa.pub relayserver_user@1.1.1.1
Done this, let's configure the AutoSSH:
autossh -M 0 -fN -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" -o "PasswordAuthentication=no" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 1.1.1.1:10022:localhost:22 relayserver_user@1.1.1.1
The "-fN" option is passed to ssh command, which will let the SSH tunnel run in the background.
The "-o XXXX" options tell ssh to:
Use key authentication, not password authentication. Automatically accept (unknown) SSH host keys. Exchange keep-alive messages every 60 seconds. Send up to 3 keep-alive messages without receiving any response back. The rest of reverse SSH tunneling related options remain the same as before.
If you want an SSH tunnel to be automatically up upon boot, you can add the above autossh command in /etc/rc.local.
Source:
http://xmodulo.com/access-linux-server-behind-nat-reverse-ssh-tunnel.html
http://xmodulo.com/how-to-enable-ssh-login-without.html
http://ask.xmodulo.com/install-autossh-linux.html
https://www.everythingcli.org/ssh-tunnelling-for-fun-and-profit-autossh/