2014-12-27

SSH portforwarding with autossh

Things you don't do daily you tend to forget. I a couple of Linux servers at home, and usually they just keep chugging along minding  their own business, but now and then they need some love and care. I know I always tend to forget how to do stuff. I spend hours researching things, set them up, get them to work, only to forget most about it when I have to redo it or change something in the future. Therefore I've decided to collect my knowledge and configurations in a blog so I don't have to rack my foggy memory, chase down .history-files or dead links. And with some luck these posts are useful for someone else. This might not be the best way to do it, but it worked for me. 

How to do portforwarding with SSH and autossh under Debian.

Create dedicated user, ex. tunnelguy, on both source and destination. I use gid / uid 500 for special accounts. Make sure it's not taken.

On both source and destination (as root or sudo):
# groupadd  -g 500 tunnelguy
# adduser --firstuid 500 --gid 500 tunnelguy

You can use a "simple" password on the destination first for testing. When everything works you can set hard password or use passwd -l to lock the  account. You wont be using password authentication in the future.

On the source:
# su - tunnelguy
$ ssh-keygen

Set no password, save in default location:
$ cat .ssh/id_rsa.pub

Add the contents of .ssh/id_rsa.pub to .ssh/authorized_keys of tunnelguy on destination. Test it from the source:
# ssh -l tunnelguy -i /home/tunnelguy/.ssh/id_rsa


You will be asked to confirm the authenticity of the destination host. Just answer "yes".
Test the tunnel from the source:

# ssh -T -f -L 80:localhost:80 -N -l tunnelguy -i /home/tunnelguy/.ssh/id_rsa


The command should execute and return to the prompt without further notice. Check that ssh is running with ps aux. You should also be able to telnet to localhost at the specified port on source and arrive at the destination.  Kill the tunnel and set up autossh. should be enough to replace ssh with autossh:
# autossh -T -f -L 80:localhost:80 -N -l tunnelguy -i /home/tunnelguy/.ssh/id_rsa

To test that autossh works kill the sshd-process on the destination:

# netstat -tnp | grep sshd
tcp        0     36 :22      :65108    ESTABLISHED 6914/sshd:  some-user
tcp        0      0 :22      :37675    ESTABLISHED 12019/sshd: tunnelgu


"our" process-ID is 12019, kill it!

# kill 12019

wait a little to let autossh notice that the tunnel is down and reconnect it

# netstat -tnp | grep sshd
tcp        0     36 :22      :65108    ESTABLISHED 6914/sshd:  some-user
tcp        0      0 :22      :37676    ESTABLISHED 12022/sshd: tunnelgu


Tada! You can also check what's happened in /var/log/messages.

Add the autossh-command to  /etc/rc.local to have it automatically connect when the server boots.

Inga kommentarer: