Postfix Header Rewrite vs. DKIM

Please note: This is an instruction on how to alter the header of a mail in postfix while also using DKIM. If you just want to alter the header of your mail see the postfix documentation on how to do so. There is no need for the steps below if you do not use DKIM!

DKIM is a great way to protect yourself from spam and to prevent fraud based on your mailserver domain. But in combination with local postfix header rewrites we have one big problem:

In other words: postfix will alter the header of our already DKIM-signed header - this will lead to DKIM Error: 550 5.7.0. Furthermore SRS won't help us on actual header rewrites. So we have to build our own way to trigger the rewrite after the DKIM signing and then re-sign the mail.

External script

Basically we use an external script to dump the content of the initial mail, alter it how ever we like it to (you cannot just alter the header here - we also can alter the message body) and resend the mail with sendmail. If you want to check: send yourself a mail via sendmail directly from your server and you'll find that mail DKIM signed. This is what we want to.

Postfix Hook

To make postfix call this external script we need to create a so called hook in the first line of

-o content_filter=dkimhook:resend

now we trigger the hook in the last line of the file:

dkimhook unix - n n - - pipe flags=F user=username argv=/usr/local/bin/yourscript ${sender} ${size} ${recipient}

as you can see we can pass the bashscript information from the mail such as sender and recipient as params. We can access those values in the script via the param vars later.

If you don't already have a recipient check in postfix you need to create one in the

smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/recipient_block

in the file recipient_block we are now able to define when this hook should be triggered. In my case I only want it for one specific recipient so I have the following entry: FILTER dkimhook:resend

See the Postfix Documentation for all available types of rules. However: you shouldn't use this method on external mails as you completly destroy the benefit of DKIM and lose the origin of the mail!

Now reload your postfix service and the hook should take effect.

Some hints for developing the hook script: