Testing Postfix regular expression header checks

Postfix has a useful feature where you can filter mail before delivery based on its header contents. If you add the line:

header_checks = regexp:/etc/postfix/header_checks

to Postfix's config file /etc/postfix/main.cf, then incoming mail will be filtered against each line of the header check file. This can be useful in blocking spam that fits certain patterns even when the (usually spoofed) sender keeps changing. However, regular expressions are notoriously complex, so it can be difficult to verify that your filter lines are actually working until more spam comes in. Fortunately, postfix includes an inbuilt tool to check this. Let's suppose that you want to block mail from a particular mailing list that prefixes its message subjects with [SPAM]. Add the following line to /etc/postfix/header_checks:

/^Subject: \[SPAM\] / REJECT

Now you can test it with the command:

postmap -q 'Subject: [SPAM] Simulated spam message' regexp:/etc/postfix/header_checks

If your filter rule is correct, then you should get the response REJECT. If you get an empty response, then the regular expression did not match and needs fixing.

Alternatively, you can test rules on a complete sample email rather than an individual header. Get the source of the email to test by choosing “View source” in your email client and save it to a file such spam-sample.eml. Then run this command:

postmap -h -q - regexp:/etc/postfix/header_checks < spam-sample.eml

This should give you a response like Subject: [SPAM] Message subject REJECT, showing you which filter rule(s) matched the message. As before, if you get an empty response, then the regular expression did not match and needs fixing.

Once you’ve got your filter working correctly, don’t forget to run postfix reload or systemctl reload postfix for the new changes to take effect.

Add new comment

CAPTCHA