Gyepi Sam
2013-05-12
How to send email through a dynamic ssh tunnel

If you run a UNIX variant on your laptop and want to be able to send email from anywhere, you need to configure a permanent SMTP host. This is easy. If you want to send the message securely and your SMTP host does not do so, one solution is to send the message through a dynamic, on demand, ssh tunnel to your SMTP host or any other ssh server on which you have a login and will accept locally generated messages.

There are a few simple steps to set this up.

run nullmailer locally on laptop.

smart host only accepts emails for known recipients or locally generated messages. I have ssh access to the smart host.

nullmailer sends messages to localhost:2525

cat /etc/nullmailer/remotes
127.0.0.1 smtp --port=2525

tcpsvd listens to localhost:2525, and, when a connection is made, runs ssh to connect to smarthost and, upon connecting, runs a netcat instance, connecting to localhost:25.

This requires an ssh key

ssh-keygen -f mail-tunnel -N ""

The remote ~$USER/.ssh/authorized_keys needs the public key to be added, along with the command to run upon connection

ssh $USER@$REMOTE cat - >> .ssh/authorized_key <<EOS 
command="/usr/bin/nc localhost 25",no-X11-forwarding,no-agent-forwarding,no-port-forwarding ssh-rsa $(cat mail-tunnel.pub)
EOS

Set up tcpsvd

cat /etc/sv/mail-tunnel/run

#!/bin/sh

d=$(dirname $0)

exec 2>&1
exec chpst -e $d/env \
  /usr/bin/tcpsvd \
  -E \
  -u $USER:$USER \
  127.0.0.1 2525 \
  /usr/bin/ssh -C -q \
     -o BatchMode=yes \
     -i $d/mail-tunnel \
     -e none -S none \
     $SSH_USER@$SSH_HOST

Done. nullmailer sends the email over an ssh connection to the smarthost, which, believing that the message originated locally, delivers it to the next hop.

Obviously this solution can be used for other kinds of systems but it is more relevant to machines that roam.