Friday, November 6, 2015

persistent ssh tunnel, for reverse tunneling and similar

Ok, so this is a very useful function when you need access to your machine which is behind a nat or so, the theory is simple, let your machine connect to remote host and create a tunnel. you will be then be able to connect to that remote machine (from a third node) and use that tunnel to connect back to your machine.

So how to make sure that this connection is always working?
1 - Make sure your machine and connect to the remote machine passwordlessly (use ssh-copy-id user@remotehost to accomplish that)
2- Start something to connect automatically on boot (using rc.local is quick enough)
3- Make sure that this thing detects disconnections and attempts to reconnect (autossh sounds like a good choice)

So, down to details, I will not go into details of step #1, but mind that you want to local (and remote) user you want to create the connection with when you do the ssh-copy-id to be the same ones you want to create the persistent connection with, generally speaking, unless there is a reason such as low port numbers to listen to when doing the tunneling, root privileges are not required.

So lets write something up that would make sure that the connection will stay up, using autossh:

#/bin/bash

#while true
#    do
        autossh -t -t -R 1234:localhost:22 $1
#done

the commented out parts are to re-run autossh in case it fails (i'm not sure this is needed, but well, test it and if needed just uncomment the loop; the $1 is a positional argument, which is the user@ip of the remote host, that needs to be passed to this script, save the content of the script somewhere like /usr/local/bin/autossh-wrapper.sh or something

Now we put this in the rc.local to start on boot time, append this to the /ect/rc.local

su localuser -c "/usr/local/bin/autossh-wrapper.sh user@ip" &

change localuser, user@ip to values of your local user and remote user@remote_host_ip_or_name




No comments: