Monday, 27 April 2009

Managing tunnels


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.


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 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


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

if [ -x $TUNN ]; then

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

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


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/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.

Monday, 6 April 2009

Using Alias

I am forever using ssh to do something or other on another box from my laptop. Of course, whenever I need to run an X application to display on my machine I find out that I have forgotten to type the -X argumentssh -X 192.168.blahSo setting up alias to do this for me by default was the ideal solution.

First of all, edit ~./bashrc and uncomment the following lines:if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
Then create a file ~/.bash_aliases to insert your alias comands.alias ssh='ssh -X'That's it. As an aside: for ssh -X to work, ensure you have the directive X11Forwarding yes enabled in /etc/ssh/sshd_config on the remote machine.

Alias in action