SSH tunnel to use other mailserver than localhost

Because I have a lot of virtual machines, laptops, work environments, and so on, I never seem to find the time to setup SMTP authentication everywhere. I typically use Linux for everything except hardcore gaming, so it’s only natural that I have some sort of mail server installed like Postfix. The problem in using that mail server to send e-mail is that I also quite often have dynamic IP addresses on these machines, which doesn’t work well with “e-mail protection” (well..) like SPF.

So instead of making my life very complicated, I have a trusted server on the Internet through which I send e-mail.

If you were looking for something fancy in this article, you can move along now, there’s nothing to see 🙂

To make all my Linux work instances believe they’re talking to an SMTP server locally, I simply setup a tunnel from the given Linux instance to this trusted server on the Internet using the ever so versatile OpenSSH / SSH. I know there are a lot of ways to do this, but this is what works for me:

Local machine or “where I work”

I have a private/public key keypair on all of these machines. The public key is placed in the /root/.ssh/authorized_keys file on the trusted server that is running the mail server.

On this machine, as root, I setup a tunnel that looks like this:

ssh -N -L 25:localhost:25 root@mail.example.org -p 2222

This will create a tunnel from “localhost” port 25 (where I work) to “localhost” port 25 on mail.example.org. It will connect the end point of the tunnel to mail.example.org on port 2222. If the mail.example.org server is running an SSH server on its standard port (22), you can remove the “-p 2222” part.

Mail server

On this server, I only need to put the public key from the local machine “where I work” into /root/.ssh/authorized_keys to allow the tunnel to come up.

When I access port 25 on my local machine “where I work”, it will be sent through the tunnel and then attempt to access “localhost” port 25 on the mail server. The mail server software, Postfix in my case, will never know this connection did not actually originate from “inside” the machine, but rather through the tunnel.

Closing thoughts

You can (obviously) make this somewhat more automated with tools like AutoSSH, init scripts, and what not. The above only intends to show how uncomplicated it is to create useful SSH/SMTP tunnels 🙂

 

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.