How do I install Mail Server on Linux/Ubuntu/CentOS?

Introduction

In this how-to article, we will walk you through building a complete mail server on Ubuntu 14.04 with Postfix. Building a Linux mail server from ground up can be a painful process unless you do it day in and day out, but we are going to show you how to do it as painlessly as we can.

A mail server usually consists of a range of different packages that handle SMTP, POP3/IMAP, storage of the mail, and spam-related tasks, and they must all talk together. Here is an outline of the packages and goals for this how-to article.




Prerequisites

– Fully updated Ubuntu 14.04 Server.

– Access to the domain name for which you will set up mail (we will be using “example.tld” in the examples in this article).


1 – Basic Server Preparation

The base installation of Ubuntu is comes with a limited set of packages, so the first thing we want to do is install the tools we’ll be using to complete all tasks.

First, make sure that you are logged in as the root user account.

sudo su -

Now, let’s install the basic tools so that we can download files, and edit configuration files easily.

apt-get install wget nano ssl-cert
  • wget: package for retrieving files using HTTP, HTTPS and FTP, the most widely-used Internet protocols.
  • nano: command line text editor with easy to use controls.
  • ssl-cert: package that enables the ability to create SSL certificates.

Next, we are going to update the hostname and domain name of the server so that when you send email it will match the reverse pointer DNS record that we set up with your hosting provider. We will also update the /etc/hostname file. Make sure to replace example with your real hostname and domain name.

hostname mail.example.tld echo "mail.example.tld" > /etc/hostname 

Now we are going to manually edit the /etc/hosts configuration file so that it matches the name we just entered.

nano /etc/hosts

Edit the first line and add your FQDN (fully qualified domain name) just after the 127.0.0.1 IP address.

127.0.0.1 mail.example.tld localhost

We are now going to update the default SSL certificate on the server so that it matches our new hostname. If you purchased an SSL certificate for your mail server, you can skip this step.

make-ssl-cert generate-default-snakeoil --force-overwrite

This command tells the server to regenerate the default system SSL certificate and forces it to overwrite the original CRT and KEY files.

We have now completed the Basic Server Preparation and can move on to installing our web server services.

[Back to top]

2 – Build out the LAMP Web Server

During this step, we are going to install the “LAMP” packages. LAMP stands for Linux, Apache, MySQL, and PHP. These packages combined will enable your server to provide dynamic web services with MySQL connectivity.

First, let’s install the packages. This is called a task package installation.

apt-get install lamp-server^

To see a list of the packages that are included in this group install, you can execute the following:

tasksel --task-packages lamp-server


As these packages are being installed, the server will ask you to enter a password for your MySQL database installation. This password will be set for the “root” user account of the MySQL database. Make sure that this password is a secure password, and make sure that you document the password used as you will need it again throughout this article.

After all the packages are installed, we will be ready to install some additional PHP modules. These additional modules will enable your server to support APC User Cache for PHP 5, memcached, cURL, an XML parser, and GD image processing.

apt-get install php-apc php5-memcache php5-curl php5-gd php-xml-parser php5-imap

[Back to top]

3 – Configure PHP

We are now going to update the configuration of PHP. The default configuration is usually sufficient for most systems; however, we want to make sure that PHP does not expose information to potential attackers. We are going to edit the file /etc/php5/apache2/php.ini.

nano /etc/php5/apache2/php.ini

Locate the variable expose_php and update the value from On to Off. With nano, you can search by pressing CTRL-W and then enter your search word.

367 ;;;;;;;;;;;;;;;;; 368 ; Miscellaneous ; 369 ;;;;;;;;;;;;;;;;; 370  371 ; Decides whether PHP may expose the fact that it is installed on the server 372 ; (e.g. by adding its signature to the Web server header). It is no security 373 ; threat in any way, but it makes it possible to determine whether you use PHP 374 ; on your server or not. 375 ; http://php.net/expose-php 376 expose_php = Off 377

[Back to top]

4 – Configure Apache2

We are now ready to move on to customizing the configuration of the Apache web services. The end result for Apache is that it will serve a single website with a couple of running web applications: Webmail (RoundCube) and Postfix Admin. All traffic will be directed to HTTPS (secured) web services.

First, we are going to minimize the information that Apache exposes to the public. Using nano, we are going to edit the configuration file /etc/apache2/conf-available/security.conf.

nano /etc/apache2/conf-available/security.conf

Search for the configuration variable ServerTokens and set the value from OS to Prod.

# ServerTokens # This directive configures what you return as the Server HTTP response # Header. The default is 'Full' which sends information about the OS-Type # and compiled in modules. # Set to one of: Full | OS | Minimal | Minor | Major | Prod # where Full conveys the most information, and Prod the least. #ServerTokens Minimal ServerTokens Prod #ServerTokens Full

Now search for the configuration variable ServerSignature and set the value from On to Off.

# Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail ServerSignature Off #ServerSignature On 

You can now save and exit this configuration file.

We are now going to enable the additional modules rewrite, and ssl in Apache so that we can redirect default HTTP traffic to the HTTPS port as well as support SSL certificates within Apache.

a2enmod rewrite ssl a2ensite default-ssl

We are now moving on to customize the website configuration. These files are located in the directory /etc/apache2/sites-available. We are going to update the existing default configuration files to support SSL services.

First, edit the configuration file 000-default.conf. You can replace the existing configuration with the below, just replace the ServerName variable with your hostname.

nano /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName mail.example.tld  DocumentRoot /var/www/html  <Directory "/var/www/html"> Options FollowSymLinks AllowOverride All </Directory>  # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. LogLevel info ssl:warn  ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined  # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf </VirtualHost>

You can now save and exit this configuration file.

If you have not purchased your own SSL certificate, the system default SSL configuration filedefault-ssl.conf will work for our needs. However, if you have purchased a custom SSL certificate, you will need to edit the configuration file and update the variables SSLCertificateFile,SSLCertificateKeyFile and SSLCertificateChainFile to point to the location where you have saved your certificate and key files (consult your certificate authority or vendor for additional configuration assistance).

We are now going to create an .htaccess configuration file that will force visitors to your web server to use the HTTPS (SSL) protocol.

nano /var/www/html/.htaccess

Copy and paste the following variables into the .htaccess configuration.

RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*) https://%{HTTP_HOST}/$1 [L]

These configuration variables tell Apache to enable the mod_rewrite engine, and then to redirect visitors on HTTP (port 80) to the HTTPS (port 443) URL.

[Back to top]

5 – Install and Configure Memcached

Memcached is a high-performance, distributed memory object caching system. This package will help speed up dynamic web applications, such as RoundCube and Postfix Webadmin.

First, let’s install the package using apt-get.

apt-get install memcached

For smaller systems, the default configuration is usually sufficient. It locks down access to the localhost and provides sufficient memory allocation values. However, if you are building a larger server that may get heavy usage, you will most likely want to change the memory allocation values to be higher than the default of 64M.

The memcached configuration files is located at /etc/memcached.conf.

[Back to top]

6 – Install the Mailserver Packages

We are now ready to install the mail server packages. Again, these are located in a tasksel package group.

apt-get install mail-server^

 

To see a list of the packages that are included in this group install, you can execute the following:

tasksel --task-packages mail-server

During the package installation, Postfix will ask you a series of questions:

  1. Installation configuration type —
    You will want to select “Internet Site” as the configuration type.
  2. Hostname of the mail server —
    Make sure to enter the same hostname (FQDN) that you used in Step #1
  3. Create a self-signed SSL Certificate —
    Select the ‘Yes’ option
  4. Setup the SSL Certificate Common Name —
    Enter the same hostname (FQDN) that you used in Step #1

We are now going to install the remainder of the packages that are needed for the mail server to support MySQL based users as well as the Spam and AntiVirus detection packages. (Note: these packages could be installed via a single apt-get install command, with each package name separated by a space, but they are presented here as separate commands for ease of reading.)

apt-get install postfix-mysql dovecot-mysql dovecot-imapd postgrey apt-get install amavis clamav clamav-daemon spamassassin apt-get install php5-imap

This next set of optional packages extends the abilities of the anti-spam and antivirus detection packages by allowing greater inspection of attached files that come in to your mail server.

apt-get install libnet-dns-perl pyzor razor apt-get install arj bzip2 cabextract cpio file gzip nomarch pax unzip zip

Now, let’s restart the Apache2 services so that it will see the new modules we have provided it.

service apache2 restart

[Back to top]

7 – Creating a MySQL Database for the EMail Server

We are now ready to create the database for our user accounts and other mail server functions.

To begin, we need to log into the MySQL database service as the root user. You will need thatpassword that you first entered in Step #2.

mysql -u root -p

You will now see a different command line prompt (mysql>). This is the MySQL CLI console where you can manage your MySQL server databases and tables.

First, we are going to create a new database named “mail”, and then we will create a system user account with full permissions to this new database. Make sure to replace the <secure password>variable with another *new* secure password for this account. Do not use the same password that you used for the root user account.

create database mail; grant all on mail.* to 'mail'@'localhost' identified by '<secure password>'; flush privileges; exit;

We have now setup the database that will be used by your mail server services.

[Back to top]

8.1 – Installing Postfix Admin

Postfix Admin is a web-based management tool created for Postfix. It is a PHP-based application that handles Postfix-style virtual domains and users that are stored in MySQL or PostgreSQL.

First, we need to download the latest release of the application. This example will download version 2.92–always check the version on the provider’s website to make sure you are getting the latest release.

cd /tmp wget http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.92/postfixadmin-2.92.tar.gz 

We are now going to extract the application and copy it to the HTML directory/var/www/html/postfixadmin on our server.

tar -xvf postfixadmin-2.92.tar.gz cp -r postfixadmin-2.92/ /var/www/html/postfixadmin  

Now we need to update the permissions of this new folder so that the www-data user account has access to it.

chown -R www-data:www-data /var/www/html/postfixadmin

[Back to top]

8.2 – Configuring Postfix Admin

We now have some configurations to update in the Postfix Admin files. First, we will modify theconfig.inc.php file so that it knows how to communicate with the database that we just created in Step #7.

nano /var/www/html/postfixadmin/config.inc.php

Search for the variable 'configured' and reset the value from false to true.

$CONF['configured'] = true;

Now search for the variable 'database_' and replace the values for your MySQL server configuration. Make sure to replace the variable <your secure password> with the password for the database user “mail” that you entered in Step #7.

$CONF['database_type'] = 'mysqli'; $CONF['database_host'] = 'localhost'; $CONF['database_user'] = 'mail'; $CONF['database_password'] = '<your secure password>'; $CONF['database_name'] = 'mail';

Now search for the variable 'admin_email' and replace the value with the email address you will setup for your administrator email account.

$CONF['admin_email'] = [email protected]';

Now search for the variable 'domain_path' and replace the value from ‘YES‘ to ‘NO‘.

$CONF['domain_path'] = 'NO';

Now search for the variable 'domain_in_mailbox' and replace the value from ‘NO‘ to ‘YES‘.

$CONF['domain_in_mailbox'] = 'YES';

These last configuration variables do not define the path to where the actual user mailbox data will be stored on the server. These will be defined later during the Dovecot configuration steps.

You are now ready to save the configuration file, but do not exit yet!

We are now going to open a web browser enter the URL of your mail server, pointing directly to thesetup.php configuration page. Make sure to replace mail.example.tld with your real server hostname.

http://mail.example.tld/postfixadmin/setup.php

When you access the URL, the script will automatically check the server and confirm that all the prerequisite modules are installed and working.

Postfix Admin setup checker output

Postfix Admin setup checker output

 

Once the checks are completed, you will be prompted to enter a setup password. This password is used to create master admin accounts for the Postfix Admin web interface.

Enter a secure password and press the “Generate Password Hash” button.

Postfix Admin generate password hash

Postfix Admin generate password hash

Postfix Admin example password hash

Postfix Admin example password hash

Do NOT close the web browser yet! We are coming back here in a few minutes.

After generating the password hash, we will then need to update the config.inc.php file again with this password. Search for the variable 'setup_password' and replace the value with the one generated from the script.

// In order to setup Postfixadmin, you MUST specify a hashed password here. // To create the hash, visit setup.php in a browser and type a password into the field, // on submission it will be echoed out to you as a hashed value. $CONF['setup_password'] = '<enter your hashed password here>';

You can now save and exit the configuration file.

We are now ready to return to the web browser and generate the “super admin” account for the Postfix Admin portal.
When you clicked the ‘Generate Password Hash’ button, the form fields changed to look like the example below. You can now fill out the form to generate a super admin account.

Creating a superadmin account with Postfix Admin

Creating a superadmin account with Postfix Admin

[Back to top]

9 – Adding User Accounts (mailboxes) to Postfix Admin

We are now ready to create a virtual user account on our mail server. To do this, we will return to the Postfix Admin URL in our web browser and enter the URL of your mail server. Make sure to replacemail.example.tld with your real server hostname.

https://mail.example.tld/postfixadmin/

You will now be able to log in to the Postfix Admin portal where you can manage virtual domains and virtual user accounts. Enter the super admin username and password that you created above during the Postfix Admin configuration, and then press the “Login” button.

Admin login for Postfix Admin

Admin login for Postfix Admin

Once you are logged into the Postfix Admin portal, you will see a menu at the top of the page.
The menu options provide the ability to manage your Postfix mail server virtual domains and users and to view log files.

Postfix Admin menu

Postfix Admin menu

 

Postfix Admin Add Mailbox option

Postfix Admin Add Mailbox option

To create a user mailbox, click quick link “Add Mailbox”. You will now be taken to the “Add Mailbox Wizard” screen. Fill out the details in the form and press the “Add Mailbox” button once completed. The wizard will create your first virtual user (mailbox) account.

Creating a new mailbox in Postfix Admin

Creating a new mailbox in Postfix Admin

[Back to top]

10 – Create a System User To Handle Virtual Mail Directories

Virtual users are those that don’t technically exist on your Linux server, and they don’t use the standard Linux methods for authentication or mail delivery and storage. Your mail server virtual user accounts are defined within the database created by Postfix Admin rather than existing as system user accounts. So we have to create a single system user account that will handle services like mail storage and Dovecot authentication.

First, let’s create a system user account called vmail and give it permissions to the required directories. This system account will be responsible for the backend operations for mailbox storage and services.

useradd -r -u 150 -g mail -d /var/vmail -s /sbin/nologin -c "Virtual MailDir Handler" vmail mkdir -p /var/vmail chown vmail:mail /var/vmail chmod 770 /var/vmail

An explanation of the above commands:

  1. We created the system user account vmail, assigned the home directory as /var/vmail, and restricted the ability for this account to login via shell or console.
  2. We then manually created the home directory /var/vmail for the new system user account.
  3. We then set the owner and group for the /var/vmail directory.
  4. We then gave full permissions to the system user vmail and the security group mail assigned to the directory /var/vmail.

[Back to top]

11 – Configuring Dovecot

Dovecot is an open-source IMAP and POP3 email server written with security in mind. Dovecot has many built-in features, which you can view at their public website, http://www.dovecot.org.

Dovecot will be responsible for managing the IMAP and POP3 connections, managing local mail directories, and receiving the incoming mail handed off from the Postfix SMTP mail server process. Dovecot will also manage the authentication for SMTP connections. Many different files within the/etc/dovecot directory handle Dovecot configuration.

First, let’s configure Dovecot to use the database set up by Postfix Admin. We will first edit the configuration file /etc/dovecot/conf.d/auth-sql.conf.ext

nano /etc/dovecot/conf.d/auth-sql.conf.ext

Edit or update the contents to have the following configuration.

# Look up user passwords from a SQL database as # defined in /etc/dovecot/dovecot-sql.conf.ext passdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext } # Look up user information from a SQL database as # defined in /etc/dovecot/dovecot-sql.conf.ext userdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext }

Once done, save and exit the configuration file.

SQL Configuration File

Now we are going to back up the original SQL configuration file /etc/dovecot/dovecot-sql.conf.ext and create a new configuration file for Dovecot to use.

mv /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.original nano /etc/dovecot/dovecot-sql.conf.ext

Now copy the below content into the configuration file and update the values for the mail database you set up in Step 7.

# Database driver: mysql, pgsql, sqlite driver = mysql  # Database Connection: # connect = host=192.168.1.1 dbname=users # connect = host=sql.example.com dbname=virtual user=virtual password=blarg # connect = /etc/dovecot/authdb.sqlite # connect = host=localhost dbname=mail user=mail password=<your secure password>  # Default password scheme. # # List of supported schemes is in # http://wiki2.dovecot.org/Authentication/PasswordSchemes # # Weak but common encryption scheme: default_pass_scheme = MD5-CRYPT #  # Comment the above out and uncomment below  # for stronger encryption: #default_pass_scheme - SHA256-CRYPT   # Define the query to obtain a user password. password_query = \ SELECT username as user, password, '/var/vmail/%d/%n' as userdb_home, \ 'maildir:/var/vmail/%d/%n' as userdb_mail, 150 as userdb_uid, 8 as userdb_gid \ FROM mailbox WHERE username = '%u' AND active = '1'  # Define the query to obtain user information. user_query = \ SELECT '/var/vmail/%d/%n' as home, 'maildir:/var/vmail/%d/%n' as mail, \ 150 AS uid, 8 AS gid, concat('dirsize:storage=', quota) AS quota \ FROM mailbox WHERE username = '%u' AND active = '1'

Once done, save and exit this configuration file.

Authentication Definition File

We are now going to back up the authentication definition file /etc/dovecot/conf.d/10-auth.confand create a new one.

mv /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.original nano /etc/dovecot/conf.d/10-auth.conf

Now copy the below content into the definition file.

# Disable LOGIN command and all other plaintext authentications unless # SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP # matches the local IP (ie. you're connecting from the same computer), the # connection is considered secure and plaintext authentication is allowed. disable_plaintext_auth = yes  # Space separated list of wanted authentication mechanisms: # plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey # gss-spnego # NOTE: See also disable_plaintext_auth setting. auth_mechanisms = plain login  ## ## Password and user databases ##  # # Password database is used to verify user's password (and nothing more). # You can have multiple passdbs and userdbs. This is useful if you want to # allow both system users (/etc/passwd) and virtual users to login without # duplicating the system users into virtual database. # # <doc/wiki/PasswordDatabase.txt> # # User database specifies where mails are located and what user/group IDs # own them. For single-UID configuration use "static" userdb. # # <doc/wiki/UserDatabase.txt>  # Use the SQL database configuration rather than any of the others. !include auth-sql.conf.ext 

Once done, save and exit the file.

Mail Definition File

Next, we are going to tell Dovecot where to store the virtual users’ mail. We will be backing up the mail definition file /etc/dovecot/conf.d/10-mail.conf and creating a new one.

mv /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.original nano /etc/dovecot/conf.d/10-mail.conf

Now copy the below content into the definition file.

# Location for users' mailboxes. The default is empty, which means that Dovecot # tries to find the mailboxes automatically. This won't work if the user # doesn't yet have any mail, so you should explicitly tell Dovecot the full # location. # # If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u) # isn't enough. You'll also need to tell Dovecot where the other mailboxes are # kept. This is called the "root mail directory", and it must be the first # path given in the mail_location setting. # # There are a few special variables you can use, eg.: # # %u - username # %n - user part in [email protected], same as %u if there's no domain # %d - domain part in [email protected], empty if there's no domain # %h - home directory # # See doc/wiki/Variables.txt for full list. Some examples: # # mail_location = maildir:~/Maildir # mail_location = mbox:~/mail:INBOX=/var/mail/%u # mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n # # <doc/wiki/MailLocation.txt> # mail_location = maildir:/var/vmail/%d/%n  # System user and group used to access mails. If you use multiple, userdb # can override these by returning uid or gid fields. You can use either numbers # or names. <doc/wiki/UserIds.txt> mail_uid = vmail mail_gid = mail  # Valid UID range for users, defaults to 500 and above. This is mostly # to make sure that users can't log in as daemons or other system users. # Note that denying root logins is hardcoded to dovecot binary and can't # be done even if first_valid_uid is set to 0. # # Use the vmail user uid here. first_valid_uid = 150 last_valid_uid = 150  # If you need to set multiple mailbox locations or want to change default # namespace settings, you can do it by defining namespace sections. # # You can have private, shared and public namespaces. Private namespaces # are for user's personal mails. Shared namespaces are for accessing other # users' mailboxes that have been shared. Public namespaces are for shared # mailboxes that are managed by sysadmin. If you create any shared or public # namespaces you'll typically want to enable ACL plugin also, otherwise all # users can access all the shared mailboxes, assuming they have permissions # on filesystem level to do so. namespace inbox { # Namespace type: private, shared or public #type = private  # Hierarchy separator to use. You should use the same separator for all # namespaces or some clients get confused. '/' is usually a good one. # The default however depends on the underlying mail storage format. #separator =   # Prefix required to access this namespace. This needs to be different for # all namespaces. For example "Public/". #prefix =   # Physical location of the mailbox. This is in same format as # mail_location, which is also the default for it. #location =  # There can be only one INBOX, and this setting defines which namespace # has it. inbox = yes  # If namespace is hidden, it's not advertised to clients via NAMESPACE # extension. You'll most likely also want to set list=no. This is mostly # useful when converting from another server with different namespaces which # you want to deprecate but still keep working. For example you can create # hidden namespaces with prefixes "~/mail/", "~%u/mail/" and "mail/". #hidden = no  # Show the mailboxes under this namespace with LIST command. This makes the # namespace visible for clients that don't support NAMESPACE extension. # "children" value lists child mailboxes, but hides the namespace prefix. #list = yes  # Namespace handles its own subscriptions. If set to "no", the parent # namespace handles them (empty prefix should always have this as "yes") #subscriptions = yes } 

Once done, save and exit the file.

SSL Definition File

If you have an SSL certificate that you would like to install, you will need to modify the Dovecot SSL definition file /etc/dovecot/conf.d/10-ssl.conf with your valid certificate. Remember, you will have to also include your CA certificate bundle if one has been provided by the certificate issuer.

Dovecot Master Definition File

We are now going to update the Dovecot master definition file /etc/dovecot/10-master.conf to include the system user account and the postfix settings.

nano /etc/dovecot/conf.d/10-master.conf

Search for the config definition service auth and replace the definition block with the following.

service auth { # auth_socket_path points to this userdb socket by default. It's typically # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have # full permissions to this socket are able to get a list of all usernames and # get the results of everyone's userdb lookups. # # The default 0666 mode allows anyone to connect to the socket, but the # userdb lookups will succeed only if the userdb returns an "uid" field that # matches the caller process's UID. Also if caller's uid or gid matches the # socket's uid or gid the lookup succeeds. Anything else causes a failure. #  # To give the caller full permissions to lookup all users, set the mode to # something else than 0666 and Dovecot lets the kernel enforce the # permissions (e.g. 0777 allows everyone full permissions). unix_listener auth-userdb { mode = 0600  user = vmail group = mail }  # Postfix smtp-auth  unix_listener /var/spool/postfix/private/auth {  mode = 0660 # Assuming the default Postfix userid and groupid user = postfix group = postfix }   }

Once done, save and exit the file.

LDA Definition File

In some cases, you may have to explicitly define the postmaster email address for your server. To do this, you will need to edit the LDA definition file /etc/dovecot/conf.d/15-lda.conf. If you see errors messages like Invalid settings: postmaster_address setting not given showing up in the mail server logs, then this configuration change is the likely fix for that error.

nano /etc/dovecot/conf.d/15-lda.conf

Search for the definition postmaster_address and update the value to include your domain’s postmaster account.

# Address to use when sending rejection mails. # Default is [email protected]<your domain>. %d expands to recipient domain. #postmaster_address = postmaster_address = [email protected]

Once done, save and exit the file.

We now need to update the Dovecot configuration directory to be accessible to the Dovecot service account as well as the vmail system account.

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

You have now completed the configuration of the Dovecot service and we can now move on to the antivirus and anti-spam services.
[Back to top]

12 – Configuring Amavis, ClamAV, and SpamAssassin

What are these packages ?

– Amavis is an interface between Postfix and content filtering packages such as SpamAssassin and ClamAV.

– ClamAV is a high-performance antivirus engine for detecting trojans, viruses, malware & other malicious threats.

– SpamAssassin is a high-performance anti-spam platform famous for its Bayesian spam filtering capabilities. It gives system administrators a filter to classify messages and block unsolicited bulk email.

We will now walk you through the process of installing some protection for your mail server. For the most part, the default configurations are sufficient for a good line of defense against spam and viruses getting through your mail server. If you have special requirements, you can, of course, spend a good amount of time crafting intricate processing rules.

Let’s first create the two system user accounts, amavis and clamav, and allow them to collaborate together.

adduser clamav amavis adduser amavis clamav

We are now going to enable the Amavis daemon by editing the /etc/amavis/conf.d/15-content_filter_mode configuration file.

nano /etc/amavis/conf.d/15-content_filter_mode

By default, the Amavis software is disabled. To enable the Amavis software, all you need to do is remove the comment tags from the bypass configuration lines.

use strict;  # You can modify this file to re-enable SPAM checking through spamassassin # and to re-enable antivirus checking.  # # Default antivirus checking mode # Please note, that anti-virus checking is DISABLED by # default. # If You wish to enable it, please uncomment the following lines:  @bypass_virus_checks_maps = ( %bypass_virus_checks, @bypass_virus_checks_acl, $bypass_virus_checks_re);  # # Default SPAM checking mode # Please note, that anti-spam checking is DISABLED by # default. # If You wish to enable it, please uncomment the following lines:  @bypass_spam_checks_maps = ( %bypass_spam_checks, @bypass_spam_checks_acl, $bypass_spam_checks_re);  1; # ensure a defined return

Once done, you can save and exit the file.

We are now going to enable the SpamAssassin software by editing the /etc/default/spamassassinconfiguration file.

nano /etc/default/spamassassin

First, locate the variable ENABLED=0 in the configuration file and change the value to 1.

# Change to one to enable spamd ENABLED=1

Now search for the variable CRON=0 in the configuration file and change the value to 1.

# Cronjob # Set to anything but 0 to enable the cron job to automatically update # spamassassin's rules on a nightly basis CRON=1

We are now going to set up Amavis to use the database from Postfix Admin to identify mail that is arriving for local delivery. By default, SpamAssassin and Amavis will only check mail that is determined to be arriving for local delivery. Because we are set up to use virtual user mailboxes, we have to tell the services where to locate the user accounts.

To do this, we need to update the configuration file /etc/amavis/conf.d/50-user.

nano /etc/amavis/conf.d/50-user

Replace the contents of this configuration file with the below. Be sure to update the MySQL database password to use the password for the database user “mail” that you entered in Step #7.

use strict;  # # Place your configuration directives here. They will override those in # earlier files. # # See /usr/share/doc/amavisd-new/ for documentation and examples of # the directives you can use in this file #  # Three concurrent processes. This should fit into the RAM available on an # AWS micro instance. This has to match the number of processes specified # for Amavis in /etc/postfix/master.cf. $max_servers = 3;  # Add spam info headers if at or above that level - this ensures they # are always added. $sa_tag_level_deflt = -9999;  # Check the database to see if mail is for local delivery, and thus # should be spam checked. @lookup_sql_dsn = ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'mail', '<your secure password>']); $sql_select_policy = 'SELECT domain from domain WHERE CONCAT("@",domain) IN (%k)';  # Uncomment to bump up the log level when testing. # $log_level = 2;  #------------ Do not modify anything below this line ------------- 1; # ensure a defined return

Once done, save and exit the configuration file.

We will now need to restart the Amavis and SpamAssassin services so that they see the new configuration settings.

service amavis restart services spamassassin restart

[Back to top]

13 – Configuring Postfix

We are now ready to configure the Postfix mail server. Postfix handles all of the incoming and outgoing mail via the SMTP protocol, and we are going to configure it to integrate will all of the other software packages that we have just configured.

From a high level view, we are needing Postfix to hand off incoming mail to the SpamAssassin and ClamAV scanners for filtering, and then to pass unblocked mail messages on to the Dovecot services for final mailbox delivery. Postfix will also authenticate the virtual users who connect via SMTP in order to send email messages.

We are going to create a definition file for Postfix to identify users and mailboxes. Please note that the “hosts” directive in these configuration files must be exactly the same as the “bind-address” in the /etc/mysql/my.cnf configuration files.

First, let’s look up the value of the bind-address in the MySQL configuration files.

cat /etc/mysql/my.cnf | grep bind-address 
<< output >> bind-address = 127.0.0.1

Now that we have the configuration value, we are going to create the required Postfix definition files.

Copy and paste the content for each file. Make sure to update the password value with the password for the database user “mail” that you entered in Step #7.

/etc/postfix/mysql_virtual_alias_domainaliases_maps.cf

nano /etc/postfix/mysql_virtual_alias_domainaliases_maps.cf
user = mail  password = <your secure password>  hosts = 127.0.0.1  dbname = mail  query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' AND alias.address=concat('%u', '@', alias_domain.target_domain) AND alias.active = 1

Once done, save and exit the configuration file.

/etc/postfix/mysql_virtual_alias_maps.cf

nano /etc/postfix/mysql_virtual_alias_maps.cf
user = mail password = <your secure password> hosts = 127.0.0.1 dbname = mail table = alias select_field = goto where_field = address additional_conditions = and active = '1'

Once done, save and exit the configuration file.

/etc/postfix/mysql_virtual_domains_maps.cf

nano /etc/postfix/mysql_virtual_domains_maps.cf
user = mail password = <your secure password> hosts = 127.0.0.1 dbname = mail table = domain select_field = domain where_field = domain additional_conditions = and backupmx = '0' and active = '1'

Once done, save and exit the configuration file.

/etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf

nano /etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf
user = mail password = <your secure password> hosts = 127.0.0.1 dbname = mail query = SELECT maildir FROM mailbox, alias_domain WHERE alias_domain.alias_domain = '%d' AND mailbox.username=concat('%u', '@', alias_domain.target_domain ) AND mailbox.active = 1

Once done, save and exit the configuration file.

/etc/postfix/mysql_virtual_mailbox_maps.cf

nano /etc/postfix/mysql_virtual_mailbox_maps.cf
user = mail password = <your secure password> hosts = 127.0.0.1 dbname = mail table = mailbox select_field = CONCAT(domain, '/', local_part) where_field = username additional_conditions = and active = '1'

Once done, save and exit the configuration file.

We are now going to create the Postfix header-checking directives. These directives remove certain headers when relaying mail through the system. This helps improve privacy for sending users by removing specific headers like origin IP Address and the mail software identifiers. Copy and paste the below content into the file.

nano /etc/postfix/header_checks
/^Received:/ IGNORE /^User-Agent:/ IGNORE /^X-Mailer:/ IGNORE /^X-Originating-IP:/ IGNORE /^x-cr-[a-z]*:/ IGNORE /^Thread-Index:/ IGNORE

Once done, save and exit.

We are now ready to make some changes to the system default Postfix /etc/postfix/main.cfconfiguration file.

This file contains a large amount of complex choices and options for a Postfix server installation. It is far beyond the scope of this article to explain every option or best practice available, so we strongly suggest that you read through the Postfix configuration options/usr/share/postfix/main.cf.dist or the software vendor online manual. O’Reilly has also published a very good book named Postfix: The Definitive Guide.

First, we are going to create a backup of the original main.cf configuration file and then create a new copy of the file.

mv /etc/postfix/main.cf /etc/postfix/main.cf.original nano /etc/postfix/main.cf

Now, copy the below content into the /etc/postfix/main.cf configuration file.

# See /usr/share/postfix/main.cf.dist for a commented, more complete version  # The first text sent to a connecting process. smtpd_banner = $myhostname ESMTP $mail_name biff = no # appending .domain is the MUA's job. append_dot_mydomain = no readme_directory = no  # SASL parameters # --------------------------------- # Use Dovecot to authenticate. smtpd_sasl_type = dovecot # Referring to /var/spool/postfix/private/auth smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yes smtpd_sasl_security_options = noanonymous smtpd_sasl_local_domain = smtpd_sasl_authenticated_header = yes  # TLS parameters # ---------------------------------  # Replace this with your SSL certificate path if you are using one. smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key # The snakeoil self-signed certificate has no need for a CA file. But # if you are using your own SSL certificate, then you probably have # a CA certificate bundle from your provider. The path to that goes # here. #smtpd_tls_CAfile=/path/to/ca/file  smtp_tls_note_starttls_offer = yes smtpd_tls_loglevel = 1 smtpd_tls_received_header = yes smtpd_tls_session_cache_timeout = 3600s tls_random_source = dev:/dev/urandom #smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache #smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache  # Note that forcing use of TLS is going to cause breakage - most mail servers # don't offer it and so delivery will fail, both incoming and outgoing. This is # unfortunate given what various governmental agencies are up to these days.  # These are Postfix 2.2 only. # # Enable (but don't force) use of TLS on incoming smtp connections. smtpd_use_tls = yes smtpd_enforce_tls = no # Enable (but don't force) use of TLS on outgoing smtp connections. smtp_use_tls = yes smtp_enforce_tls = no  # These are Postfix 2.3 and later. # # Enable (but don't force) all incoming smtp connections to use TLS. smtpd_tls_security_level = may # Enable (but don't force) all outgoing smtp connections to use TLS. smtp_tls_security_level = may  # See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for # information on enabling SSL in the smtp client.  # SMTPD parameters # ---------------------------------  # Uncomment the next line to generate "delayed mail" warnings #delay_warning_time = 4h # will it be a permanent error or temporary unknown_local_recipient_reject_code = 450 # how long to keep message on queue before return as failed. # some have 3 days, I have 16 days as I am backup server for some people # whom go on holiday with their server switched off. maximal_queue_lifetime = 7d # max and min time in seconds between retries if connection failed minimal_backoff_time = 1000s maximal_backoff_time = 8000s # how long to wait when servers connect before receiving rest of data smtp_helo_timeout = 60s # how many address can be used in one message. # effective stopper to mass spammers, accidental copy in whole address list # but may restrict intentional mail shots. smtpd_recipient_limit = 16 # how many error before back off. smtpd_soft_error_limit = 3 # how many max errors before blocking it. smtpd_hard_error_limit = 12  # This next set are important for determining who can send mail and relay mail # to other servers. It is very important to get this right - accidentally producing # an open relay that allows unauthenticated sending of mail is 
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How can I find out about any maintenance or other issues related to your services?

You may find any major maintenance or other issues related to your servers on our Announcements page

Why are my services offline?

We offer a 99.9% uptime guarantee on Web Hosting, Reseller, Dedicated Server and Virtual Machine...

Do you provide any support? What is your response time?

Below you will find all of our Support Times and Hours.Technical Support: 24x7x365Sales Support:...

Getting Started: VPS Hosting vs. Shared Hosting

In this article, we will discuss the primary differences between hosting on a VPS solution as...

Do you offer IPv6 Addresses?

Yes, Boxne Network Solutions offers IPv6 addresses for FREE on request only.

Powered by WHMCompleteSolution