Monday, 27 April 2009

Managing tunnels

Introduction

My laptop tunnels through to my home server for three services: smtp, imap and nntp. I thought it was about time that I managed these services in a completely automated and reliable fashion.

Objectives


I wanted my laptop to initiate the three tunnels every time a new network connection was established. The best place to do this is after if-up processes have been completed. Happily, the Network Manager executes scripts in /etc/network/if-up.d/ directory when such an event occurs.

I am assuming that you have a id_rsa.pub key in /root/.ssh already set up on the laptop and that this key has been appended to the file /root/.ssh/authorized_keys on the server. [TODO write this up]

Listing 1: /etc/network/if-up.d/tunnel

Is called after any if-up event. Calls the kill process first and then initiates new tunnels.#!/bin/sh

# /etc/network/if-up.d/tunnel

KILL=/usr/local/bin/kill-tunnels
TUNN=/usr/local/bin/start-tunnels

# quit if we're called for the loopback
if [ "$IFACE" = lo ]; then
exit 0
fi
# kill tunnel processes
if [ -x $KILL ]; then
$KILL
fi

if [ -x $TUNN ]; then
$TUNN
fi

Listing 2: /usr/local/bin/kill-tunnels

Kills the existing tunnel processes if they are running.#!/bin/sh

#/usr/local/bin/kill-tunnels

ps aux | grep "143\:localhost\:143" \
| sed 's/  */\t/g' | cut -f2 | xargs -r kill -15

ps aux | grep "25\:localhost\:25" \
| sed 's/  */\t/g' | cut -f2 | xargs -r kill -15

ps aux | grep "119\:localhost\:119" \
| sed 's/  */\t/g' | cut -f2 | xargs -r kill -15

Listing 3: /usr/local/bin/start-tunnels

Starts the new tunnels.#!/bin/sh

#/usr/local/bin/start-tunnels

HOST=my.server.fqdn

/usr/bin/ssh -f -N -q -L 143:localhost:143 $HOST

/usr/bin/ssh -f -N -q -L 25:localhost:25 $HOST

/usr/bin/ssh -f -N -q -L 119:localhost:119 $HOST

PROC=`basename $0`

logger -i -t $PROC Tunnels started
So it all works automagically, now and is particularly useful when in hotspots and changing connections.

As these procedures are called by root, I can use the ports numbered below 1024, which is handy.

So for nntp access, localhost:119 on my laptop is actually port 119 on my server.

No comments: