Skip to main content

This tutorial applies to postfix server and CentOS 7 environment.

If you have a standalone virtual host and have a mail service installed, when you look at your system log, you find out thousands of spammers are trying to send spam emails to your server every day.

So how to stop them from spamming your mail server?

In fact, as long as your server is publicly available, you can't completely stop all spam. However, there are ways to reduce the impact of these spam traffic on your server, and make your server more secure.

In this tutorial, we block spam senders by modifying postfix configuration file and add spam sender email address to the blacklist. Then we configure fail2ban to ban corresponding ip address automatically. 

The detailed steps are as follows:

  1. Open your system's mail log (/var/log/maillog) and find the spam sender email address that repeatedly send spam to your server. 
  2. Add the spam sender address to postfix blacklist.
    • Open /etc/postfix/sender_access file (if not exists, create a new one):

      # cd /etc/postfix # nano sender_access
    • Append sender email as follows:   550  Blacklisted
    • Save and close the file.  Use postmap to generate a mapped database sender_access.db:

      # postmap hash:sender_access
    • Open /etc/postfix/, find the 'smtpd_recipient_restrictions'  sections,  and add the following code:

      check_sender_access hash:/etc/postfix/sender_access 

      Note: 'check_sender_access' should be added rather than replacing the current options. The edited code should look like this:   

      smtpd_recipient_restrictions =          check_recipient_access hash:/etc/postfix/sender_access,          permit_mynetworks,          ....Save and close the file.
    • Reload postfix:

      # service postfix reload
  3. Modify fail2ban filter to ban the spam senders ip address. (Before you do this make sure you have fail2ban installed and postfix filter enabled.)
    • Open /etc/ fail2ban/filter.d/postfix.conf, find the `failregex` section and add code as follows:

      ^%(__prefix_line)sNOQUEUE: reject: RCPT from \S+\[<HOST>\]: 550 5\.7\.1 <\S*>: Sender address rejected: Blacklisted; from=<\S*> to$
    • Reload Fail2ban:

      # fail2ban-client reload

After completing the above steps, postfix will reject mails from senders of the mail in the blacklist, and then fail2ban will extract the sender's host IP from the mail log and add it to the firewall's rejection list.  The rejected host will not be able to connect to this server any more.