Using Postfix with Tor

This is just a little note explaining how to get the postfix mail transport agent to work as a client with Tor. This is tested on FreeBSD but should work on pretty much any modern UNIX-like system.

The first thing to do, obviously, is get the tor software up and running and presenting its SOCKS proxy interface, which by default will be 127.0.0.1:9050. Next you need one of those SOCKS libraries designed to hook the system calls for creating TCP sockets. I use the NWSL SOCKS5 that's available in the ports tree.

Postfix has a configuration file, typically /etc/postfix/master.cf that it uses to find out which programs to run to do the various things that need doing to be an MTA. The ones of interest are the lines that begin with smtp and relay:

smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp

The last column is a program name, and these programs usually live somewhere like /usr/libexec/postfix. All you need to do is create a little wrapper to make these programs use SOCKS. I use this:

cat > /usr/libexec/postfix/smtp_socks <<EOF
#!/bin/sh

export LD_PRELOAD=/usr/local/lib/libsocks5_sh.so
export SOCKS_SERVER=127.0.0.1:9050

exec /usr/libexec/postfix/smtp $@

EOF

chmod 755 /usr/libexec/postfix/smtp_socks

and then change the last column in master.cf to smtp_socks.

This setup may leak DNS queries. A better socksification technique might be to use torsocks, although for my setup this isn't possible at the moment because postfix also listens on IPv6 sockets which fails when using torsocks. In any event, the principle is the same.

There we have it, postfix will use the Tor network to deliver outgoing mail.

Now the story doesn't really end there. Most of the Tor exit relays are in the spam blacklists. So you can't just do this and expect it to work. In particular you'll probably want to set up a relayhost. For example if you use tormail, and only want to send mail from one account, you could do something like,

relayhost=jhiwjjlqpyawmpjx.onion
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options=

in /etc/postfix/main.cf and putting a line like:

jhiwjjlqpyawmpjx.onion      tormailuser:tormailpass

in the /etc/postfix/sasl_passwd and running the postmap program on it.

Or you could find a remailer and use it as the relayhost. This, and more complex configurations are left as an exercise.

Happy hacking!

And the sequel...