Mail Server

Install ‘iRedMail’ (Fully Featured Mail Server) with Virtual Domains, Webmail, SpamAssassin & ClamAV in Linux

Install &-8216;iRedMail&-8217; (Fully Featured Mail Server) with Virtual Domains, Webmail, SpamAssassin & ClamAV in Linux &-8211; this Article or News was published on this date:2019-05-28 19:19:23 kindly share it with friends if you find it helpful

After HTTP and shadow DNS services, mail (SMTP, POP, IMAP and all related encrypted mail protocols) is one of the most used service in Internet, and also, one of the most sensible, due to spam and open-relay mail servers.

Install iRedMail in LinuxInstall iRedMail in Linux

Install iRedMail in Linux

This tutorial will guide you through installing a full mail server with MTA, MDA and MUA software in a few minutes on RHEL, CentOS, Scientific Linux and Debian, Ubuntu, Linux Mint with Postfix, Virtual Domains and Users with MySQL, Dovecot – support for POP3/POP3S, IMAP/IMAPS, Roundcube – Webmail and also, mail spam and virus scanning with SpamAssassin and ClamAV, all installed using a single software package called ‘iRedMail’.

What is iRedMail

iRedMail is an Open Source full featured mail server solution that can spare a lot of time for system administrators for complex configurations, has support for all major Linux distributions and ships with the following Linux packages.

  1. Postfix: SMTP service – default MTA.
  2. Dovecot: POP3/POP3S, IMAP/IMAPS, Managesieve service – default MDA.
  3. Apache: Web server.
  4. MySQL/PostgreSQL: Storing application data and/or mail accounts.
  5. OpenLDAP: Storing mail accounts.
  6. Policyd: Postfix policy server.
  7. Amavisd: An interface between Postfix and SpamAssassin, ClamAV. Used for spam and virus scanning.
  8. Roundcube: Webmail – default MUA.
  9. Awstats: Apache and Postfix log analyzer.
  10. Fail2ban: scans log files (e.g. /var/log/maillog) and bans IPs that show malicious system attempts.

Requirements

  1. CentOS 6.5 minimal installation – CentOS 6.5 Installation Guide
  2. A valid DNS MX record that points to your mail server responsible for your domain name.

Also, this tutorial is designed for testing and learning purposes only and does not use a valid MX records, nor a valid DNS domain mane, all of configurations are made locally using virtual recipients with MySQL (can receive or send mail between local domain users only – local domain name provided from hosts file) but be aware that, although our system can’t receive mails from internet domains, it can actually relay mails to those domain mail servers through Postfix MTA, even if you reside on a private IP address space, with no valid MX record and using a fictional domain, so pay much attention to what you’re doing.

Step 1: Initial Configurations and Static IP Address

1. After first reboot login with your root account and make sure your system is up to date and install some useful packages needed for later usage.

On RHEL/CentOS/Scientific Linux
- yum update && yum upgrade
- yum install nano wget bzip2
On Debian/Ubuntu/Linux Mint
- apt-get update && apt-get upgrade
- apt-get install nano wget bzip2

2. Because this box acts like a Mail Server, a static IP needs to be configured on Network Interface. To add a static IP open and edit your NIC configurations file located on /etc/sysconfig/network-scripts/ path and add the following values.

On RHEL/CentOS/Scientific Linux
- nano /etc/sysconfig/network-scripts/ifcfg-eth0

Use this file as a template and replace it with your customize values.

DEVICE="eth0"
BOOTPROTO="static"
HWADDR="00:0C:29:01:99:E8"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"
UUID="7345dd1d-f280-4b9b-a760-50208c3ef558"
NAME="eth0"
IPADDR=192.168.1.40
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=192.168.1.1
DNS2=8.8.8.8
Install iRedMail in LinuxSetup Static IP Address

Setup Static IP Address

After you finish editing your NIC file, open network file from the same location as above and add your server unqualified hostname on HOSTNAME directive.

- nano /etc/sysconfig/network-scripts/network
Install iRedMail in LinuxSetup System Hostname

Setup System Hostname

On Debian/Ubuntu/Linux Mint
- nano /etc/network/interfaces

Replace following values with your settings.

auto eth0
iface eth0 inet static
  address 192.168.1.40
  netmask 255.255.255.0
  gateway 192.168.1.1
  dns-nameservers 192.168.1.1
  dns-search 8.8.8.8

Once, you finish with your network file, now add your hostname in /etc/hostname file.

- nano /etc/hostnames

3. Then open /etc/resolv.conf file and append your DNS IP servers system wide like in the screenshot below.

- nano /etc/resolv.conf

Add the following content with your favorite name servers.

search mydomain.lan
nameserver 8.8.8.8
nameserver 8.8.8.8
Install iRedMail in LinuxAdd DNS Entries

Add DNS Entries

4. After all the configurations above had been written to their corresponding files restart your network service to apply newly configurations and verify it using ping and ifconfig commands.

- service network restart	[On RedHat based systems]

- service networking restart	[On Debian based systems]
Install iRedMail in LinuxRestart Network Services

Restart Network Services

- ifconfig
Install iRedMail in LinuxVerify Network

Verify Network

5. Now that your static network is fully operational, edit /etc/hosts file and add your unqualified and FQDN hostname like the example below.

- nano /etc/hosts
127.0.0.1   centos.mydomain.lan centos localhost localhost.localdomain
192.168.1.40 centos.mydomain.lan centos
Install iRedMail in LinuxAdd System Hostname

Add System Hostname

To verify your hostname configuration issue, run hostname and hostname –f commands.

- hostname
- hostname -f
Install iRedMail in LinuxVerify System Hostname

Verify System Hostname

6. Another useful package is bash-completion (auto-complete commands sequence using [Tab] key) which is provided by EPEL repository under RedHat based systems and then update your sources.

On RHEL/CentOS/Scientific Linux
- rpm –Uvh http://fedora.mirrors.romtelecom.ro/pub/epel/6/i386/epel-release-6-8.noarch.rpm
- yum repolist && yum upgrade
Install iRedMail in LinuxInstall Epel Repository

Install Epel Repository

After your sources had been updated install bash-completion utility (answer Yes on all questions).

- yum install bash-completion
Install iRedMail in LinuxInstall Bash Completion in CentOS

Install Bash Completion

On Debian/Ubuntu/Linux Mint

The bash-completion package under Debian based systems can be easily installed using following command.

- apt-get install bash-completion

7. The last step is to add a system user with root privileges. First add the user and setup its password.

- adduser your_user
- passwd your_user
Install iRedMail in LinuxAdd New User

Add New User

After your user has been added, open /etc/sudoers file and uncomment %wheel group, then add your newly created user to wheel group.

- nano /etc/sudoers

Search and uncomment wheel group line to look like this.

%wheel                ALL=(ALL)            ALL
Install iRedMail in LinuxAdd User to Sudoers

Add User to Sudoers

Close the file and add your user to wheel group issuing the following command.

- usermod -aG wheel your_user
Install iRedMail in LinuxAdd User to Wheel Group

Add User to Wheel Group

8. Before we can start download and install iRedMail software, reboot your system, then login with your newly created user and make sure everything is fully functional.

Install iRedMail in LinuxLogin With New User

Login With New User

Step 2: Install iRedMail

9. In order to downlad iRedMail archive package you must visit it’s official download page section or you can use wget command to download the last version ( 0.8.7 at the time of writing this article).

- wget https://bitbucket.org/zhb/iredmail/downloads/iRedMail-0.8.7.tar.bz2
Install iRedMail in LinuxDownload IRedMail

Download IRedMail

10. After iRedMail archive download finishes, extract it using the following command.

- tar xvjf iRedMail-0.8.7.tar.bz2

11. Then enter newly extracted iRedMail directory path, mark iRedMail.sh script with executable permissions then run it.

- cd iRedMail-0.8.7
- chmod +x iRedMail.sh
- sudo ./iRedMail.sh

12. After initial system checks the program starts adding required repository then the first guidance prompt asks you whether you wish to continue with installation or abort. Choose Yes to continue.

Install iRedMail in LinuxInitial System Checks

Initial System Checks

Install iRedMail in LinuxDownloading iRedMail Packages

Downloading iRedMail Packages

Install iRedMail in LinuxClick Yes to Confirm Installation

Click Yes to Confirm Installation

13. iRedMail uses Maildir format to store e-mails on /var/vmail system path where it creates separated directories for every domain that you append to your MTA server. If you’re comfortable with this path hit Next to move forward with server configurations else provide your desired location then Next.

Install iRedMail in LinuxEnter Mailbox User Path

Enter Mailbox User Path

14. On the next step choose you preferred database to store mail domains names and recipients that will connect to Postfix. This tutorial focuses on MySQL database, so choose MySQL using [Space] bar then continue with Next and provide a strong password for MySQL root account.

Install iRedMail in LinuxSelect MySQL Database

Select MySQL Database

Install iRedMail in LinuxSet MySQL Administrative Password

Set MySQL Administrative Password

15. On the next step add your first virtual domain name. If you own a registered domain name added here (add just the domain name not system FQDN).

Install iRedMail in LinuxAdd Virtual Domain Name

Add Virtual Domain Name

16. By default iRedAdmin creates an administrative user with full powers over your server that can be accessed through iRedAdmin panel or through Dovecot protocols (default Roundcube webmail interface or any other IMAP/POP MUA software like SquirrelMail, Rainloop, Microsoft Outlook, Mozilla Thunderbird, Evolution, Mutt, Elm etc ).

Also this postmaster administrative account is used by the system to report incidents related to mail functions or other system failures or useful information – logwatch usually sends its statistics here- so choose a strong password and continue with Next.

Install iRedMail in LinuxEnter iRedMail Administrative Password

Enter iRedMail Administrative Password

17. On the next step choose your other mail server components like iRedAdmin official administrative panel to Postfix, DKIM domain keys – ( adds a signature to message header evaluating message trust for final delivery or further relays), Roundcube default webmail interface ( if you plan to use other Mail Delivery Agent skip Roundcube ), PhpMyadmin (if you are comfortable with MySQL command line you should also skip installing PhpMyAdmin ), Awstats ( useful log statistics and analyzer ), Fail2ban ( protects your server from brute force attacks).

Install iRedMail in LinuxSelect Optional Components

Select Optional Components

18. On next series of questions, depending on your optional components installed you should answer with Yes. Pay extra attention to iRedMail.tips file located on $HOME extracted directory because it contains sensitive mail server information like usernames and passwords for server applications, server configurations files, default URL and other important information.

Install iRedMail in LinuxiRedMail Configuration Completed

iRedMail Configuration Completed

Install iRedMail in LinuxiRedMail Configuration Packages

iRedMail Configuration Packages

Install iRedMail in LinuxiRedMail Installation Process

iRedMail Installation Process

19. After installation finishes reboot your system and verify iRedmail.tips file to see your server default settings – you should move this file to a secure system path with 600 permissions on it.

Install iRedMail in LinuxVerify iRedmail.tips File

Verify iRedmail.tips File

Install iRedMail in LinuxVerify Server Default Settings

Verify Server Default Settings

20. Access default web applications on the following URLs.

  1. Roundcube Webmail – https://domain_name or server_IP/mail/
  2. IRedAdmin panel – https://domain_name or server_IP/iredadmin/
  3. PhpMyadmin – https://domain_name or server_IP /phpmyadmin/
  4. Awstats – https://domain_name or server_IP/awstats/awstats.pl?config=web (or ?config=smtp)
  5. Policyd anti-spam plugin – https://domain_name or server_IP/cluebringer/

Step 3: Initial Webmail Configurations

21. iRedAdmin administrative panel offers a basic webmail interface where you can add virtual domains and accounts for your mail server that Postfix can handle through MySQL backend. To login to iRedAdmin panel point your browser to https://domain_name/iredadmin/ or https://server_IP/iredadmin/ URL and use the following default credentials.

  1. Username: [email protected]_domain_name.tld
  2. Password: postmaster password set on -16 point
Install iRedMail in LinuxiRedAdmin Administrative Panel

iRedAdmin Administrative Panel

22. To add a user navigate to Add -> User then provide your desired username mail address and password. You can also setup the amount of space your user Mailbox can handle with Quota and you can also promote users with administrative powers over iRedAdmin panel by Marking user as Global admin.

Install iRedMail in LinuxAdd a New Mail User

Add a New Mail User

Install iRedMail in LinuxUser Profile Settings

User Profile Settings

Install iRedMail in LinuxAdd Another Mail User

Add Another Mail User

Install iRedMail in LinuxDomain User Email List

Domain User Email List

23. Reading users email is provided by Roundcube web interface. To access it navigate to https://domain_name/mail or https://server_IP/mail/ URL and supply your mail account credentials in the form of [email protected].

Accessing the default administrative mail account postmaster you will find two initial emails, one of them including your server sensitive information. From here you can now read emails, compose and send mails to other domain users.

Install iRedMail in LinuxLogin to Roundcube Webmail

Login to Roundcube Webmail

Install iRedMail in LinuxUser Mail Interface

User Mail Interface

Install iRedMail in LinuxVerify Sending a Mail

Verify Sending a Mail

Install iRedMail in LinuxConfirm Received Mail

Confirm Received Mail

24. To access server Policyd anti-spam policy navigate to https://domain_name/cluebringer or https://server_IP/cluebringer/ and provide the following credentials.

  1. User Name: [email protected]
  2. Password: postmaster password
Install iRedMail in LinuxLogin to Policyd anti-spam Policy

Login to Policyd anti-spam Policy

Install iRedMail in LinuxPolicyd Web Administration

Policyd Web Administration

25. To view your mail server statistics navigate to https://mydomain.lan/awstats/awstats.pl/?config=smtp or https://mydomain.lan/awstats/awstats.pl and use the following credentials.

  1. User Name: [email protected]
  2. Password: postmaster password
Install iRedMail in LinuxLogin to Awstats

Login to Awstats

Install iRedMail in LinuxView Mail Server Statistics

View Mail Server Statistics

Install iRedMail in LinuxMail Server Monthly History

Mail Server Monthly History

26. If you want to check your server’s opened connections and listening daemon state with their afferent sockets issue the following commands.

- netstat -tulpn   -- numerical view
- netstat -tulp    -- semantic view
Install iRedMail in LinuxCheck Server Open Connections

Check Server Open Connections

Install iRedMail in LinuxCheck Server Listening Daemons

Check Server Listening Daemons

27. To debug other problems with mail transactions or view your server live working you can use the following commands.

- tailf /var/log/maillog   -- visualize mail logs in real time
- mailq    		   --  inspect mail queue
- telnet    		   -- test your server protocols and security form a different location
- nmap                     -- scan your server opened connections from different locations
Install iRedMail in LinuxVisualize Mail Logs in Real Time

Visualize Mail Logs in Real Time

Install iRedMail in LinuxCheck Server Status

Check Server Status

28. Now you have deployed a full mail environment, the only thing that is missing, at least on this topic is a valid domain name with a MX DNS record to receive mail from other internet domains but local SMTP server can and will relay mail on other Internet valid domains so pay extra attention who you send mails because you can get into illegal problems with your ISP.

From the screenshot below you can see that I have send an email from my local non-valid domain to one of my google.com accounts and the email was successfully received by my google account.

Install iRedMail in LinuxVerify Outgoing Mails

Verify Outgoing Mails

Unlike other network services where you install and forget about them for a long time managing a mail server is a continuous hard work due to mail service related problems like SPAM, open relay and message bounces.

Reference Links

iRedMail Homepage

How to Setup a Complete Mail Server (Postfix) using ‘SquirrelMail’ (Webmail) on Ubuntu/Debian

How to Setup a Complete Mail Server (Postfix) using &-8216;SquirrelMail&-8217; (Webmail) on Ubuntu/Debian &-8211; this Article or News was published on this date:2019-05-28 18:55:07 kindly share it with friends if you find it helpful

Creating a mail server on Linux powered machines can be one of the most essential things that every system administrator needs to do while configuring his servers for the first time, if you don’t know what it means; it’s simple, if you have a website like “example.com”, you can create an email account like “[email protected]” to use it to send / receive emails easily instead of using services like Hotmail, Gmil, Yahoo Mail.. etc.

Setup Postfix Mail Server in DebianSetup Postfix Mail Server in Debian

Setup Postfix Mail Server in Ubuntu/Debian

In this article, we’ll learn how to do so by installing the Postfix with “SquirrelMail” webmail application and its dependences on Debian/Ubuntu machines.

Step 1: Installing Apache2 and PHP5

1. In order to create a running mail server using “SquirrelMail”, we’ll have to install both Apache2 & PHP5 packages first, to do so, run.

$ sudo apt-get update
$ sudo apt-get install apache2 php5
Setup Postfix Mail Server in DebianInstall Apache and PHP in Ubuntu

Install Apache and PHP

Step 2: Installing Postfix Mail Server

2. Postfix is a mail transfer agent (MTA) which is the responsible software for delivering & receiving emails, it’s essential in order to create a complete mail server.

To install it on Ubuntu/Debian or even Mint, run:

$ sudo apt-get install postfix

During installation, you will be asked to choose the default file configuration for your server.

Setup Postfix Mail Server in DebianPostfix Configuration in Ubuntu

Select Postfix Configuration

3. Next, it asks you to select type of mail configuration, choose “Internet Site”.

Setup Postfix Mail Server in DebianSelect Mail Configuration

Select Mail Configuration

4. Now enter the fully qualified domain name that you want to use for send and receive mails.

Setup Postfix Mail Server in DebianSystem Mail Name

Enter System Mail Name

5. Once the FQDN set, you’ve restart the Postfix mail server using.

$ sudo service postfix restart

Step 3: Installing Dovecot

6. Dovecot is a mail delivery agent (MDA), it delivers the emails from/to the mail server, to install it, run the following command.

$ sudo apt-get install dovecot-imapd dovecot-pop3d
Setup Postfix Mail Server in DebianInstall Dovecot in Ubuntu

Install Dovecot

During the installation process, you will be asked if you want to create a self-signed SSL certificate, choose Yes.

Setup Postfix Mail Server in DebianCreate Mail SSl Certificate

Create Mail SSl Certificate

7. Next, enter your host name to use in the SSL certificate.

Setup Postfix Mail Server in DebianEnter Hostname to use SSL

Enter Hostname to use SSL

8. Next, restart Dovecot service using the following command.

$ sudo service dovecot restart

Step 4: Installing SquirrelMail

9. SquirrelMail is the email server that you’ll be using to manage emails on your server, it has a simple web interface to do the job, it can be customized by installing more modules & themes.

$ sudo apt-get install squirrelmail
Setup Postfix Mail Server in Debianinstall squirrelmail in Ubuntu

install Squirrelmail

10. After the installation, you will have to run this command in order to configure SquirrelMail.

$ sudo squirrelmail-configure
Setup Postfix Mail Server in DebianConfigure Squirrelmail in Ubuntu

Configure Squirrelmail

11. Next, enter “2” in order to edit the server settings, and you will be prompted to it.

Setup Postfix Mail Server in DebianConfigure Server Settings for Mail

Configure Server Settings for Mail

12. Now enter “1” in order to change the domain name and write up your domain (e.g: example.com).

Setup Postfix Mail Server in DebianSet Mail Domain Name

Set Mail Domain Name

13. Go back to the main menu by writing “R” and hitting the enter key, write “4” in order to configure the general options.

Setup Postfix Mail Server in DebianConfigure Mail General Optionsb

Configure Mail General Options

You see “Allow server-side sorting”? Enter “11” and change it from “false” to “true” by entering “y”. Now hit the Enter key, and enter the “S” key in order to save the configuration file.

Now, we’ll copy the default configuration file to the apache2 directory in order to be able to access the web interface, run.

$ sudo cp /etc/squirrelmail/apache.conf /etc/apache2/sites-available/squirrelmail.conf

And enable it using:

$ sudo a2ensite squirrelmail.conf

14. You can now access the mail server by going to example.com/squirrelmail.

Setup Postfix Mail Server in DebianAccess Squirrelmail in Ubuntu

Access Squirrelmail

Step 5: Creating Mail Users

15. In order to start using squirrelmail webmail, you’ll have to create a new user, to do so, run.

$ sudo useradd myusername

Replace “myusername” with the user name you want, create a password for the new user by running.

$ sudo passwd myusername

16. Create a home folder for the user in /var/www/html/myusername and make it default home directory.

$ sudo mkdir -p /var/www/html/myusername
$ usermod -m -d /var/www/html/myusername myusername

17. Now go back to the login page and enter the user name and the password of newly created user.

Setup Postfix Mail Server in DebianAccess Squirrelmail in Ubuntu

Access Squirrelmail

You will be surprise to see the following error message.

Setup Postfix Mail Server in DebianLogin to Squirrelmail

Login to Squirrelmail

This is just a problem in the permissions, you have to give the user “myusername” the complete permissions on its home folder.

$ sudo chown -R myusername:myusername /var/www/html/myusername

18. Once permission set, you should able to login into squirrelmail.

Setup Postfix Mail Server in DebianSquirrelmail Mail Interface

Squirrelmail Mail Interface

You can try to send email from it, or you can try to receive emails by sending it to “[email protected]” , don’t forget to replace “myusername” with the user name you created.

If you faced any other error.. Just check the “/var/log/mail.err” file, all the error message will be stored there, you won’t lose your way 🙂

Have you tried to create an email server before? How did it go? Have you used SquirrelMail or any other mail server before? What do you think about it?

How to Setup Postfix Mail Server and Dovecot with Database (MariaDB) Securely – Part 1

How to Setup Postfix Mail Server and Dovecot with Database (MariaDB) Securely &-8211; Part 1 &-8211; this Article or News was published on this date:2019-05-28 18:10:52 kindly share it with friends if you find it helpful

Setup Postfix Mail Server in CentOS 7Setup Postfix Mail Server in CentOS 7

Setup Postfix Mail Server in CentOS 7

In this 3-article series we will discuss how to set up a Postfix mail server with antivirus and spam protection in a CentOS 7 box. Please note these instructions also works on other distributions such as RHEL/Fedora and Debian/Ubuntu.

Part 1: How to Create and Setup Postfix Mail Server Database (MariaDB) Securely

Our plan consists in storing email accounts and aliases in a MariaDB database which is for our convenience, will be managed through phpMyAdmin.

If you choose to not install phpMyAdmin, or are dealing with a CLI-only server, we will also provide the equivalent code to create the database tables that will be used throughout this series.

Since keeping a mail server up and running is one of the essentials tasks that are usually assigned to system administrators and engineers, we will also provide a few tips to efficiently run this critical service in a production environment.

Create A and MX Records for Domain in DNS

Before proceeding further, there are a few prerequisites that must be met:

1. You will need a valid domain registered through a domain registrar. In this series we will use www.linuxnewz.com, which was registered through GoDaddy.

2. Such domain must be pointed to the external IP of your VPS or cloud hosting provider. If you are self-hosting your mail server, you can use the service offered by FreeDNS (requires registration).

In any event, you have to set up A and MX records for your domain as well (you can learn more about MX records in this FAQ from Google).

Once added, you can look them up using an online tool such as MxToolbox or ViewDNS to ensure they are properly set up.

Important: Please note that it may take a while (1-2 days) until the DNS records are propagated and your domain is available. In the meanwhile, you can access your VPS through its IP address to perform the tasks indicated below.

3. Configure the FQDN (Fully Qualified Domain Name) of your VPS:

- hostnamectl set-hostname yourhostname

to set the system hostname, then edit /etc/hosts as follows (replace AAA.BBB.CCC.DDD, yourhostname, and yourdomain with the public IP of your server, your hostname, and your registered domain):

AAA.BBB.CCC.DDD yourhostname.yourdomain.com       yourhostname

where yourhostname is the system hostname that was set previously using hostnamectl command.

Installing Required Software Packages

4. To install required software packages such as Apache, Postfix, Dovecot, MariaDB, PhpMyAdmin, SpamAssassin, ClamAV, etc, you need to enable the EPEL repository:

- yum install epel-release

5. Once you have followed the above steps, install the necessary packages:

In CentOS based Systems:

- yum update && yum install httpd httpd-devel postfix dovecot dovecot-mysql spamassassin clamav clamav-scanner clamav-scanner-systemd clamav-data clamav-update mariadb mariadb-server php phpMyAdmin

In Debian and derivatives:

- aptitude update && aptitude install apache2 postfix dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-mysql spamassassin clamav clamav-daemon clamav-base mariadb-client mariadb-server php5 phpMyAdmin

6. Start and enable the web and database servers:

In CentOS based Systems:

- systemctl enable httpd mariadb
- systemctl start httpd mariadb

In Debian and derivatives:

- systemctl enable apache2 mariadb
- systemctl start apache2 mariadb

When the installation is complete and the above service are enabled and running, we will start off by setting up the database and tables to store information about Postfix mail accounts.

Creating Postfix Mail Accounts Database

For simplicity, we will use phpMyAdmin, a tool intended to handle the administration of MySQL / MariaDB databases through a web interface, to create and manage the email database.

However, in order to log on to and use this tool, we need to follow these steps:

7. Enable the MariaDB account (you can do this by running the mysql_secure_installation utility from the command line, assigning a password for user root, and setting the default settings proposed by the tool EXCEPT “Disallow root login remotely?“:

Setup Postfix Mail Server in CentOS 7Disable MySQL root Login

Disable MySQL root Login

or otherwise create a new database user:

MariaDB [(none)]> CREATE USER 'dba'@'localhost' IDENTIFIED BY 'YourPasswordHere';
MariaDB [(none)]> GRANT ALL PRIVILEGES ON * . * TO 'dba'@'localhost';
MariaDB [(none)]> FLUSH PRIVILEGES;
Setup Postfix Mail Server in CentOS 7Create New Database User

Create New Database User

Secure Apache with a Certificate

8. Since we will be using a web application to manage the email server database, we need to take the necessary precautions to protect connections to the server. Otherwise, our phpMyAdmin credentials will travel in plain text over the wire.

To set up Transport Layer Security (TLS) in your server, follow the steps outlined in Part 8 of the RHCE series: Implementing HTTPS through TLS using Network Security Service (NSS) for Apache before proceeding further.

Note: if you do not have access to the server’s console you will need to find another way to generate the necessary entropy during the key creation. In that case, you may want to consider installing rng-tools and running rngd -r /dev/urandom.

Configure and Secure PhpMyAdmin

9. In /etc/httpd/conf.d/phpMyAdmin.conf (CentOS) or /etc/phpmyadmin/apache.conf (Debian and derivatives), locate all the occurrences of the following lines and make sure they point to the public IP of your server:

Require ip AAA.BBB.CCC.DDD
Allow from AAA.BBB.CCC.DDD

Additionally, disable the default aliases and create a new one to access your phpMyAdmin login page. This will help to secure the site against bots and external attackers who target www.yourdomain.com/phpmyadmin or www.yourdomain.com/phpMyAdmin.

-Alias /phpMyAdmin /usr/share/phpMyAdmin
-Alias /phpmyadmin /usr/share/phpMyAdmin
Alias /managedb /usr/share/phpMyAdmin

Also, add following line inside IfModule mod_authz_core.c>:

Require all granted
Setup Postfix Mail Server in CentOS 7Secure PhpMyAdmin

Secure PhpMyAdmin

Create Apache VirtualHost for Domain

10. Make sure your domain is added to the enabled sites. Create /etc/httpd/sites-available/linuxnewz.com.conf (CentOS) or /etc/apache2/sites-available/linuxnewz.com (Debian) with the following contents (make sure the DocumentRoot, sites-available, and sites-enabled directories exist):

VirtualHost *:80>
    ServerName www.linuxnewz.com
    ServerAlias linuxnewz.com
    DocumentRoot /var/www/linuxnewz.com/public_html
    ErrorLog /var/www/linuxnewz.com/error.log
    CustomLog /var/www/linuxnewz.com/requests.log combined
    Options Indexes FollowSymLinks
/VirtualHost>

and the symbolic link:

On CentOS:
- ln -s /etc/httpd/sites-available/linuxnewz.com.conf /etc/httpd/sites-enabled/linuxnewz.com.conf
On Debian:
- a2ensite linuxnewz.com

and you’re done.

Setup Postfix Email Database

11. Now you can open your phpMyAdmin interface at https://www.yourdomain.com/managedb (note that managedb is the alias that we set up earlier for the phpMyAdmin data directory).

If that does not work (which can be caused by a delay in the propagation or lack of configuration of DNS records) for the time being you can try using your server’s public IP address instead of www.yourdomain.com:

Setup Postfix Mail Server in CentOS 7PhpMyAdmin Login

PhpMyAdmin Login

In any event, after you log on to phpMyAdmin you will see the following interface. Click New in the left section:

Setup Postfix Mail Server in CentOS 7Create New Database in PhpMyAdmin

Create New Database in PhpMyAdmin

Enter a name for the database (EmailServer_db in this case, no need to select a Collation) and click Create:

Setup Postfix Mail Server in CentOS 7Enter Database Name

Enter Database Name

12. On the next screen, choose a name for the first table (where we will store the domains this mail server will manage.

Please note that even when in this series we will only manage one domain, you can add more later) and the number of fields you want in it, then click Go. You will be prompted to name and configure those two fields, where you may safely proceed as indicated in the following images:

Setup Postfix Mail Server in CentOS 7Create Database Table

Create Database Table

When you choose PRIMARY under Index for DomainId, accept the default values and click Go:

Setup Postfix Mail Server in CentOS 7Add Database Index

Add Database Index

Alternatively, you can click Preview SQL to see the code under the hood:

CREATE TABLE `EmailServer_db`.`Domains_tbl` ( `DomainId` INT NOT NULL AUTO_INCREMENT , `DomainName` VARCHAR(50) NOT NULL , PRIMARY KEY (`DomainId`)) ENGINE = InnoDB;
Setup Postfix Mail Server in CentOS 7Database Table Index Code

Database Table Index Code

When you’re ready, click Save to confirm changes. You will then be able to click New under EmailServer_db to continue creating tables:

Setup Postfix Mail Server in CentOS 7Create Tables under Database

Create Tables under Database

13. Now follow these steps to create the rest of the tables. Click on the SQL tab and enter the indicated code for each database object.

Note that in this case we chose to create the table using a SQL query because of the relationships that must be established between different tables:

Users_tbl

CREATE TABLE `Users_tbl` ( 
    `UserId` INT NOT NULL AUTO_INCREMENT,  
    `DomainId` INT NOT NULL,  
    `password` VARCHAR(100) NOT NULL,  
    `Email` VARCHAR(100) NOT NULL,  
    PRIMARY KEY (`UserId`),  
    UNIQUE KEY `Email` (`Email`),  
    FOREIGN KEY (DomainId) REFERENCES Domains_tbl(DomainId) ON DELETE CASCADE 
) ENGINE = InnoDB; 
Setup Postfix Mail Server in CentOS 7Create Postfix User Table

Create Postfix User Table

You should get a confirmation message (if not, phpMyAdmin will prompt for syntax errors):

Setup Postfix Mail Server in CentOS 7MySQL Confirmation

MySQL Confirmation

Alias_tbl

CREATE TABLE `Alias_tbl` (
    `AliasId` INT NOT NULL AUTO_INCREMENT, 
    `DomainId` INT NOT NULL, 
    `Source` varchar(100) NOT NULL, 
    `Destination` varchar(100) NOT NULL, 
    PRIMARY KEY (`AliasId`), 
    FOREIGN KEY (DomainId) REFERENCES Domains_tbl(DomainId) ON DELETE CASCADE
) ENGINE = InnoDB;

(Click Go at the bottom to proceed with the creation of the table).

Up to this point, you should have the following database structure:

Setup Postfix Mail Server in CentOS 7Database Structure

Database Structure

Which means you’re ready to start adding some records in the next section.

Creating a Postfix Domain, Users and Aliases

14. We will now insert the following records into the three tables. The passwords for [email protected] and [email protected] will be encrypted and the INSERT INTO Users_tbl statement.

Also, please note that the emails sent to [email protected] will be redirected to [email protected]:

INSERT INTO Domains_tbl (DomainName) VALUES ('linuxnewz.com');  
INSERT INTO Users_tbl (DomainId, password, Email) VALUES (1, ENCRYPT('PasswordForFirstEmailAccount', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), '[email protected]');  
INSERT INTO Users_tbl (DomainId, password, Email) VALUES (1, ENCRYPT('PasswordForSecondEmailAccount', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), '[email protected]');  
INSERT INTO Alias_tbl (DomainId, Source, Destination) VALUES (1, '[email protected]', '[email protected]');

Having added our domain, two user accounts, and an email alias we are ready to continue setting up our email server in the next article of this series, where we will configure Dovecot and Postfix.

Summary

In this article we have listed the packages required to install an Postfix email server in a CentOS 7 VPS, and explained how to manage the underlying database using phpMyAdmin.

In the next two articles we will review the configuration of the two programs that will take care of the email distribution for our domain (Part 2) and show you how to add protection against spam and viruses (Part 3) for your server.

Until then, feel free to contact us using the form below if you have any questions or comments.

How to Configure Postfix and Dovecot with Virtual Domain Users in Linux – Part 2

How to Configure Postfix and Dovecot with Virtual Domain Users in Linux &-8211; Part 2 &-8211; this Article or News was published on this date:2019-05-28 18:10:03 kindly share it with friends if you find it helpful

In the previous article of this series we explained how to set up and manage the mail server database securely using phpMyAdmin.

Requirement:

  1. Install Postfix Mail Server and Dovecot with MariaDB – Part 1
Configure Postfix and Dovecot with Virtual Domain UsersConfigure Postfix and Dovecot with Virtual Domain Users

Configure Postfix and Dovecot with Virtual Domain Users – Part 2

Now it’s time to configure the internal programs that will make sending and receiving emails a reality: Postfix and Dovecot (to handle outgoing and incoming emails, respectively).

Configuring Postfix Mail Server

Before you begin configuring Postfix, it would be worth and well to take a look at its man pages here, putting special emphasis on the section titled “Information for new Postfix users“. If you do, you will find it easier to follow along with this tutorial.

In few words, you should know that there are two configuration files for Postfix:

  1. /etc/postfix/main.cf (Postfix configuration parameters, refer to man 5 postconf for more details).
  2. /etc/postfix/master.cf (Postfix master daemon configuraton, see man 5 master for further details).

In /etc/postfix/main.cf, locate (or add, if necessary) the following lines and make sure they match the values indicated below:

main.cf
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
dovecot_destination_recipient_limit = 1
message_size_limit = 4194304
readme_directory = no
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (CentOS)
smtpd_tls_cert_file = /etc/pki/dovecot/certs/dovecot.pem
smtpd_tls_key_file = /etc/pki/dovecot/private/dovecot.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
virtual_transport = dovecot
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

The next three settings are of special importance. In the files indicated in yellow we will configure Postfix’s access to the Domains_tbl, Users_tbl, and Alias_tbl tables:

virtual_mailbox_domains = mysql:/etc/postfix/mariadb-vdomains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mariadb-vusers.cf
virtual_alias_maps = mysql:/etc/postfix/mariadb-valias.cf

Note that you can choose different file names above, as long as you make sure to create them and insert the following contents in them. In each case, replace YourPassword with the password you chose for the dba user in Part 1, or you can also use the MariaDB root credentials for user and password below.

Also, make sure you use the exact same names of the email server database and tables created in Part 1.

In /etc/postfix/mariadb-vdomains.cf:

mariadb-vdomains.cf
user = dba
password = YourPassword
hosts = 127.0.0.1
dbname = EmailServer_db
query = SELECT 1 FROM Domains_tbl WHERE DomainName='%s'

In /etc/postfix/mariadb-vusers.cf:

mariadb-vusers.cf
user = dba
password = YourPassword
hosts = 127.0.0.1
dbname = EmailServer_db
query = SELECT 1 FROM Users_tbl WHERE Email='%s'

In /etc/postfix/mariadb-valias.cf:

mariadb-valias.cf
user = dba
password = YourPassword
hosts = 127.0.0.1
dbname = EmailServer_db
query = SELECT Destination FROM Alias_tbl WHERE Source='%s'

Finally, don’t forget to change the permissions to these files to 640:

- chmod 640 /etc/postfix/mariadb-vdomains.cf
- chmod 640 /etc/postfix/mariadb-vusers.cf
- chmod 640 /etc/postfix/mariadb-valias.cf

And the ownership to user root and group postfix:

- chown root:postfix /etc/postfix/mariadb-vdomains.cf
- chown root:postfix /etc/postfix/mariadb-vusers.cf
- chown root:postfix /etc/postfix/mariadb-valias.cf

Next, to enable secure connections we need to make sure the following settings are uncommented (or added, if necessary) in /etc/postfix/master.cf:

master.cf
submission inet n       -       n       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
pickup    unix  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp

showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
-virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache

Note: The indentation in the lines beginning with the -o option is critical; otherwise postfix check will return an error:

Configure Postfix and Dovecot with Virtual Domain UsersCheck Postfix Configuration

Check Postfix Configuration

Before you save changes, add the following lines at the bottom of the file:

master.cf
dovecot   unix  -       n       n       -       -       pipe
    flags=DRhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient}

At this point it is essential to check whether Postfix has access to the database tables and the domains, accounts, and alias that we created in Part 1.

To do so, we will use the postmap command, an utility to test communication with the tables Postfix will look up during operation, but first and foremost we’ll need to restart postfix:

- systemctl postfix restart
- postmap -q linuxnewz.com mysql:/etc/postfix/mariadb-vdomains.cf
- postmap -q someotherdomain.com mysql:/etc/postfix/mariadb-vdomains.cf
- postmap -q [email protected] mysql:/etc/postfix/mariadb-vusers.cf
- postmap -q [email protected] mysql:/etc/postfix/mariadb-vusers.cf
- postmap -q [email protected] mysql:/etc/postfix/mariadb-vusers.cf
- postmap -q [email protected] mysql:/etc/postfix/mariadb-valias.cf

In the image below we can see that for existing records in the database, a 1 is returned. Otherwise, nothing is displayed back to the screen. In the case of the alias check, note that the actual email account the alias is mapped to is returned:

Configure Postfix and Dovecot with Virtual Domain UsersCheck Postfix Table Communication

Check Postfix Table Communication

Note that we are NOT authenticating against the credentials set for each email account, we are only testing the ability of Postfix to detect those records in the database.

Thus, if you get a different output than above, make sure you are using a valid user / password pair in mariadb-vdomains.cf, mariadb-vusers.cf, and mariadb-valias.cf (or whatever you chose to call those files).

Configuring Dovecot

As an IMAP / POP3 server, Dovecot provides a way for users through a Mail User Agent (MUA, or also known as client), such as Thunderbird or Outlook, to name a few examples to access their mail.

To begin, let’s create a user and a group to handle emails (we will need this as our email accounts are not associated with a system user). You can use another UID and GID (other than 5000 as we do below) as long as it’s not in use and is a high number:

- groupadd -g 5000 vmail 
- useradd -g vmail -u 5000 vmail -d /home/vmail -m

The settings for Dovecot are split across several configuration files (make sure the following lines are uncommented and / or edit them to match the settings indicated below).

In /etc/dovecot/dovecot.conf:

dovecot.cf
!include_try /usr/share/dovecot/protocols.d/*.protocol
protocols = imap pop3 lmtp
!include conf.d/*.conf
!include_try local.conf

In /etc/dovecot/conf.d/10-auth.conf (only enable authentication through SQL and leave other authentication methods commented out):

10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login
!include auth-sql.conf.ext

In /etc/dovecot/conf.d/auth-sql.conf.ext (note that we will store emails within a directory named yourdomain.com inside /home/vmail, which you need to create if it doesn’t exist. In our case we did mkdir /home/vmail/linuxnewz.com to manage emails for that domain):

auth-sql.conf.ext
passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
userdb {
  driver = static
  args = uid=vmail gid=vmail home=/home/vmail/%d/%n/Maildir
}

Individual inboxes for user accounts will be created when emails for such accounts are first received.

In /etc/dovecot/conf.d/10-mail.conf:

10-mail.conf
mail_location = maildir:/home/vmail/%d/%n/Maildir
namespace inbox {
  inbox = yes
}
mail_privileged_group = mail
mbox_write_locks = fcntl

In /etc/dovecot/conf.d/10-master.conf:

10-master.conf
service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
  }
}
service pop3-login {
  inet_listener pop3 {
    port = 110
  }
  inet_listener pop3s {
  }
}
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
   mode = 0600
   user = postfix
   group = postfix
  }
}
service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    group = postfix
  }
  unix_listener auth-userdb {
   mode = 0600
   user = vmail
  }
  user = dovecot
}
service auth-worker {
  user = vmail
}
service dict {
  unix_listener dict {
  }
}

In /etc/dovecot/conf.d/10-ssl.conf (replace the certificate and key paths if you are planning on using a certificate signed by a CA):

10-ssl.conf
ssl = required
ssl_cert = /etc/pki/dovecot/certs/dovecot.pem
ssl_key = /etc/pki/dovecot/private/dovecot.pem

In /etc/dovecot/dovecot-sql.conf.ext enter your database information and the credentials of the administrative user created in Part 1.

Important: if your password contains an asterisk (-), you will need to enclose the connect string as indicated in the example below:

dovecot-sql.conf.ext
driver = mysql
connect = "host=127.0.0.1 dbname=EmailServer_db user=dba password=PassWith-Here"
default_pass_scheme = SHA512-CRYPT
password_query = SELECT Email as User, password FROM Users_tbl WHERE Email='%u';

Additionally, you can configure logging for Dovecot to be separate from Postfix in /etc/dovecot/conf.d/10-logging.conf:

log_path = /var/log/dovecot.log

Finally, make sure the Dovecot log is accessible for user dovecot:

- chown vmail:dovecot /var/log/dovecot.log
- chmod 660 /var/log/dovecot.log

Verify and Fix Postifix Configuration and Enable SMTP, POP3, and IMAP in Firewall

If you happen to run into any issues while configuring Postfix and / or Dovecot, instead of submitting all of the configuration files to ask for help, you can get a configuration summary (uncommented lines only) with:

- postconf –n - Summary for /etc/postfix/main.cf
- postconf –M - Summary for /etc/postfix/master.cf
- doveconf –n - Summary of all configuration files for Dovecot

In addition, make sure that the email inboxes are readable by vmail only:

- chown –R vmail:vmail /home/vmail

Configuration files should also be readable by vmail and dovecot users:

- chown -R vmail:dovecot /etc/dovecot 
- chmod -R o-rwx /etc/dovecot 

Finally, make sure you enable SMTP, POP3, and IMAP through the firewall:

- firewall-cmd --add-port=143/tcp
- firewall-cmd --add-port=143/tcp --permanent
- firewall-cmd --add-port=110/tcp
- firewall-cmd --add-port=110/tcp --permanent
- firewall-cmd --add-port=587/tcp
- firewall-cmd --add-port=587/tcp --permanent

Configure Thunderbird as an Email Client for Postfix

Having secured access through the firewall for the ports used in email communications, it’s time to configure an email client. Using [email protected] and its corresponding password, along with mail.linuxnewz.com as IMAP (or POP3) and SMTP server we are ready to start sending and receiving emails to and from such account:

Configure Postfix and Dovecot with Virtual Domain UsersPostfix: Configure Thunderbird Client

Postfix: Configure Thunderbird Client

You can safely disregard the warning message that is shown because you are using a certificate that is not signed by a trusted 3rd-party CA:

Configure Postfix and Dovecot with Virtual Domain UsersThunderbird: Add Security Exception

Thunderbird: Add Security Exception

Let’s compose a brief test email and click Send:

Configure Postfix and Dovecot with Virtual Domain UsersCompose A Email on Thunderbird

Compose A Email on Thunderbird

When prompted to accept the self-signed certificate for the outgoing server, confirm it previously as before:

Configure Postfix and Dovecot with Virtual Domain UsersThunderbird: Accept SSL Certificate

Thunderbird: Accept SSL Certificate

Finally, go to the destination email to see if you received the email that was just sent. If so, reply to it and see if it is delivered back to the source email inbox (otherwise, refer to the Postfix log at /var/log/maillog or the Dovecot log at /var/log/dovecot.log for troubleshooting information):

Configure Postfix and Dovecot with Virtual Domain UsersVerify Postfix and Dovecot Email Delivery

Verify Postfix and Dovecot Email Delivery

You now have a working Postfix and Dovecot email server and can start sending and receiving emails.

Summary

In this article we have explained how to configure Postfix and Dovecot to handle email traffic in your Linux server. If something does not work as indicated in this article, make sure you take time to check the Postfix and Dovecot documentation.

Please note that although setting up a Postfix mail server is not an easy task, it is a rewarding experience for every system administrator.

If after going through the docs you find yourself still struggling with Postfix and / or Dovecot, feel free to drop us a note using the comment form below and we will be glad to help you (don’t forget to upload to an online storage service the Postfix and Dovecot configuration as retrieved using postconf and doveconf as outlined in this article).

How to Add Antivirus and Spam Protection to Postfix Mail Server with ClamAV and SpamAssassin – Part 3

How to Add Antivirus and Spam Protection to Postfix Mail Server with ClamAV and SpamAssassin &-8211; Part 3 &-8211; this Article or News was published on this date:2019-05-28 18:09:43 kindly share it with friends if you find it helpful

In the previous two articles of this Postfix series you learned how to set up and manage the email server database through phpMyAdmin, and how to configure Postfix and Dovecot to handle incoming and outgoing mail. In addition, we explained how to set up a mail client, such as Thunderbird, for the virtual accounts we created previously.

  1. Setup Postfix Mail Server and Dovecot with MariaDB – Part 1
  2. How to Configure Postfix and Dovecot with Virtual Domain Users – Part 2
  3. Install and Configure RoundCube Webmail Client with Virtual Users in Postfix – Part 4
  4. Use Sagator, an Antivirus/Antispam Gateway to Protect Your Mail Server – Part 5

Since no email server setup can be complete without taking precautions against viruses and spam, we are going to cover that topic in the current article.

Integrate ClamAV and SpamAssassin to Protect PostfixIntegrate ClamAV and SpamAssassin to Protect Postfix

Integrate ClamAV and SpamAssassin to Protect Postfix

Please keep in mind that even when *nix-like operating systems are usually considered to be virus-free, chances are clients using other operating systems will also connect to your email server.

For that reason, you need to provide them with the confidence that you have taken the necessary measures to protect them to the extent possible from such threats.

Configuring SpamAssassin for Postfix

In the process of receiving email, spamassassin will stand between the outside world and the email services running on your server itself. If it finds, according to its definition rules and configuration, that an incoming message is spam, it will rewrite the subject line to clearly identify it as such. Let’s see how.

The main configuration file is /etc/mail/spamassassin/local.cf, and we should make sure the following options are available (add them if they are not present or uncomment if necessary):

local.cf
report_safe 0
required_score 8.0
rewrite_header Subject [SPAM]
  1. When report_safe is set to 0 (recommended value), incoming spam is only modified by modifying the email headers as per rewrite_header. If it is set to 1, the message will be deleted.
  2. To set the aggressivity of the spam filter, required_score must be followed by an integer or decimal number. The lesser the number, the more sensitive the filter becomes. Setting required_score to a value somewhere between 8.0 and 10.0 is recommended for a large system serving many (~100s) email accounts.

Once you’ve saved those changes, enable and start the spam filter service, and then update the spam rules:

- systemctl enable spamassassin
- systemctl start spamassassin
- sa-update

For more configuration options, you may want to refer to the documentation by running perldoc Mail::SpamAssassin::Conf in the command line.

Integrating Postfix and SpamAssassin

In order to efficiently integrate Postfix and spamassassin, we will need to create a dedicated user and group to run the spam filter daemon:

- useradd spamd -s /bin/false -d /var/log/spamassassin

Next, add the following line at the bottom of /etc/postfix/master.cf:

master.cf
spamassassin unix - n n - - pipe flags=R user=spamd argv=/usr/bin/spamc -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}

And indicate (at the top) that spamassassin will serve as content_filter:

-o content_filter=spamassassin
Integrate ClamAV and SpamAssassin to Protect PostfixIntegrate Postfix with SpamAssassin

Integrate Postfix with SpamAssassin

Finally, restart Postfix to apply changes:

- systemctl restart postfix

To verify that SpamAssassin is working properly and detecting incoming spam, a test known as GTUBE (Generic Test for Unsolicited Bulk Email) is provided.

To perform this test, send an email from a domain outside your network (such as Yahoo!, Hotmail, or Gmail) to an account residing in your email server. Set the Subject line to whatever you want and include the following text in the message body:

XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X

For example, sending the above text in a message body from my Gmail account produces the following result:

Integrate ClamAV and SpamAssassin to Protect PostfixVerify SpamAssassin Detecting Spam Mails

Verify SpamAssassin Detecting Spam Mails

And shows the corresponding notice in the logs:

- journalctl | grep spam
Integrate ClamAV and SpamAssassin to Protect PostfixMonitor SpamAssassin Mail Logs

Monitor SpamAssassin Mail Logs

As you can see in the image above, this email message got a spam score of 1002.3. Additionally, you can test spamassassin right from the command line:

- spamassassin -D  /usr/share/doc/spamassassin-3.4.0/sample-spam.txt

The above command will produce some really verbose output that should include the following:

Integrate ClamAV and SpamAssassin to Protect PostfixTest SpamAssassin Spam from Commandline

Test SpamAssassin Spam from Commandline

If these tests are not successful, you may want to refer to the spamassassin integrations guide.

Starting ClamAV and Update Virus Definitions

To begin, we will need to edit /etc/clamd.d/scan.conf. Uncomment the following line:

LocalSocket /var/run/clamd.scan/clamd.sock

and comment out or delete the line:

Example

Then enable and start the clamav scanner daemon:

- systemctl enable [email protected]
- systemctl start [email protected]

and don’t forget to set the antivirus_can_scan_system SELinux boolean to 1:

- setsebool -P antivirus_can_scan_system 1

At this point it is worth and well to check on the service’s status:

Integrate ClamAV and SpamAssassin to Protect PostfixStart and Update ClamAV Virus Definitions

Start and Update ClamAV Virus Definitions

As you can see in the image above, our virus signatures are older than 7 days. To update them we will use a tool called freshclam that was installed as part of the clamav-update package.

The easiest way to update the virus definitions is through a cron job that executes as often as desired (once a day for example, at 1 am server time as indicated in the following example is considered enough):

00 01 * * * root /usr/share/clamav/freshclam-sleep

You can also update the virus definitions manually, but before you’ll also have to remove or comment out the following line in /etc/freshclam.conf.

Example

Now you should be able to run:

- freshclam

which will update the virus definitions as desired:

Integrate ClamAV and SpamAssassin to Protect PostfixFreshClam Update ClamAV Virus Database

FreshClam Update ClamAV Virus Database

Testing ClamAV for Virus in Emails

To verify ClamAV is working properly, let’s download a test virus (which we can get from http://www.eicar.org/download/eicar.com) to the Maildir of [email protected] (which is located in /home/vmail/linuxnewz.com/sfnews/Maildir) to simulate an infected file received as a mail attachment:

- cd /home/vmail/linuxnewz.com/sfnews/Maildir
- wget http://www.eicar.org/download/eicar.com

And then scan the /home/vmail/linuxnewz.com directory recursively:

- clamscan --infected --remove --recursive /home/vmail/linuxnewz.com
Integrate ClamAV and SpamAssassin to Protect PostfixClamAV Scan For Email Virus

ClamAV Scan For Email Virus

Now, feel free to set up this scan to run through a cronjob. Create a file named /etc/cron.daily/dailyclamscan, insert the following lines:

-!/bin/bash
SCAN_DIR="/home/vmail/linuxnewz.com"
LOG_FILE="/var/log/clamav/dailyclamscan.log"
touch $LOG_FILE
/usr/bin/clamscan --infected --remove --recursive $SCAN_DIR >> $LOG_FILE

and grant execute permissions:

- chmod +x /etc/cron.daily/dailyclamscan

The above cronjob will scan the mail server directory recursively and leave a log of its operation in /var/log/clamav/dailyclamscan.log (make sure the /var/log/clamav directory exists).

Let’s see what happens when we send the eicar.com file from [email protected] to [email protected]:

Integrate ClamAV and SpamAssassin to Protect PostfixTest and Find Virus in Emails

Test and Find Virus in Emails

Summary

If you followed the steps outlined in this tutorial and in the previous two articles of this series, you now have a working Postfix email server with spam and antivirus protection.

DISCLAIMER: Please note that server security is a vast subject and cannot be adequately covered in a short series like this.

For that reason, I highly encourage you to become familiar with the tools used in this series and their man pages. Although I have done my best to cover the essential concepts associated with this topic, do not assume that after going through this series you are fully qualified to set up and maintain a email server in a production environment.

This series is intended as a starting point and not as an exhaustive guide to mail server administration in Linux.

You will probably think of other ideas that can enrich this series. If so, feel free to drop us a note using the comment form below. Questions and other suggestions are appreciated as well – we look forward to hearing from you!