Thursday, November 21, 2019

Postfix smtp_fallback_relay and HAProxy smtp relay in action

It's possible to use HAProxy to add a SMTP relay for a domain mail service which can be used to add a secondary mx record for a domain name to enable its clients in a restricted network reach the mail server :
Clients in a restricted network -> HA Proxy VPS (second priority mx record) -> Main server
HAProxy - Postfix configuration

You'll need to get a VPS with internet access in the restricted network and install HAProxy on it. Then configure HAProxy on the vps to forward SMTP port 25 to the main server : 

frontend ft_smtp
  bind 0.0.0.0:25
  mode tcp
  timeout client 1m
  log global
  option tcplog
  default_backend bk_postfix

backend bk_postfix
  mode tcp
  log global
  option tcplog
  timeout server 1m
  timeout connect 5s
  server postfix YOUR_MAIN_IP_ADDRESS:2525 send-proxy

Now on the postfix of the main server edit the main.cf and set the upstream proxy for postscreen to haproxy: 

postscreen_upstream_proxy_protocol = haproxy

and finally enable smtpd and postscreen in master.cf :

2525    inet  n       -       n       -       1       postscreen
smtpd     pass  -       -       n       -       -       smtpd


One can add a new mx record with a lower priority to the domain with the IP address of the HAProxy server so that clients that aren't able to reach the main mail server can access it through the HAProxy server.

But how can these clients receive emails from the main mail server? Postfix on the main server can't reach these clients directly, so one can use smtp_fallback_relay feature in postfix to reach them through the same VPS that's running HAProxy.

To do so add the IP address of the vps that's running HAProxy as a SMTP Fallback relay to the main.cf file of the main mail server : 

fallback_relay = [YOUR_VPS_FQDN]:5870

You'll need to also add the IP address of your VPS to the SPF records of the main domain.

Now on the vps server, install postfix and set it to run as a relay. Add the IP address of the main mail server to mynetworks in main.cf file of the vps, to allow it to use this vps as a relay mail server. 

 Ensure that the hostname of the vps matches with the PTR record of YOUR_VPS_IP_ADDRESS and the value in /etc/mailname of the vps.

Edit the master.cf file of the postfix on the vps server and add the port you set in fallback_relay there : 

5870    inet  n       -       y       -       -       smtpd

That's it. With this configuration, clients first try to reach the main mx records and they try the second mx record if the first one was inaccessible. Also the server tries to reach mail servers directly and it tries the relay smtp server if they were unreachable. 


No comments:

Post a Comment

How to export Apple Health / Google Fit training activity to TCX format

  I own a Xiaomi Smart Band 7, and recently, my Mi Fitness app stopped syncing running activities to Strava. Mi Fitness supports syncing dat...