HOWTO: SSH Tunnel SMTP traffic

A lot of ISPs these days are blocking outgoing traffic on port 25 due to spammers. They force you to use their unreliable SMTP server. I have used the following workaround for this successfully: find a good Linux box outside of your network from a friend who has a reliable SMTP server running and create a port forwarding SSH tunnel to it.

1) Setup an SSH tunnel between client (your machine where outgoing SMTP traffic is being blocked) to server:

a. Enable keys in sshd.conf on the server:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

b. On client: ssh-keygen -t dsa
c. copy .ssh/id_dsa.pub to .ssh/authorized_keys in ~user on remote host machine

2) Create the connection as root:
ssh patrick@aaa.bbb.ccc.ddd -2 -L 25:127.0.0.1:25 -q -N -g &
Options explained:o
  • ssh patrick@aaa.bbb.ccc.ddd creates an SSH connection to this host
  • -2 forces version 2
  • -L 25:127.0.0.1:25 listens on port 25 on the localhost and connects to
  • 127.0.0.1 (aaa.bbb.ccc.ddd, that is) on port 25. NOTE: The 127.0.0.1 symbolizes 127.0.0.1 on the REMOTE side, not on the local side.
  • -q does quiet mode
  • -N does a non-interactive session (no shell)
  • -g allows other people on your LAN to connect to the remote host
  • & puts it into the background.

If you run on a port other >1024, you can run this as a non-root user, but if you put it in &, it'll kill the process after you logout, which is why I run it as root.

3) Make sure the connection stays alive; create a script to monitor it.

      #!/bin/sh
       TUNNEL=`ps -aux | grep aaa.bbb.ccc.ddd | grep -v grep` 
      if [ ! -n "$TUNNEL" ]; then 
      echo -n "SSH Tunnel is not running... " 
      ssh patrick@aaa.bbb.ccc.ddd -2 -L 25:127.0.0.1:25 -q -N -g & 
      echo "started!" 
      fi 
Add this to crontab every 5 minutes or so.

4) Point your SMTP client to your linux box and send e-mail! my /var/qmail/contrl/smtproutes looks like this:
:localhost:25