3. Managing Mail Services

In this chapter we discuss a network configuration containing a local SMTP server and POP/IMAP server authentified on a LDAP directory. The protection against viruses and SPAM is assured by amavisd-new and the necessary components.and the needed modules. We assume that the LDAP is operational.

3.1. POP/IMAP Cyrus-IMAPD Server

Today, Cyrus-IMAP works by default with a SASL (Simple Authentication and Security Layer)authentication security layer. By default, the SASL-secured authentication uses an authentication mode based on PAM.

You will find more information on the project's official website: http://cyrusimap.web.cmu.edu/

3.1.1. Installation and Tree Structure of Cyrus-IMAPD

Three packages are necessary:

  • cyrus-sasl: provides the SASL client and server;

  • cyrus-imapd: provides the POP/IMAP Cyrus-IMAP server;

  • cyrus-imapd-utils: provides Cyrus-IMAP utilities, and notably cyradm, which is the server's administration interface.

[Note] Note

Versions don't evolve a lot. However, be rigorous concerning eventual security updates, particularly concerning SASL.

Let's install the required packages:

# urpmi cyrus-sasl cyrus-imapd cyrus-imapd-utils

Cyrus-IMAP's tree structure is quite simple:

  • /etc/imapd.conf: configuration file used to access the IMAP server's resources;

  • /etc/cyrus.conf: Cyrus configuration file;

  • /var/spool/imap/: directory where mailboxes are stored;

  • /var/log/mail: log file directory.

3.1.2. Configuring Cyrus-IMAP

First, let's check the list of authentication modes available with the SASL version we installed:

# saslauthd -v
saslauthd 2.1.22
authentication mechanisms: getpwent kerberos5 pam rimap shadow ldap

ldap appears in this list. The mechanism used for authentication is specified in the /etc/sysconfig/saslauthd file:

# cat /etc/sysconfig/saslauthd
# $Id: CS-service-messaging.xml,v 1.9 2008-09-12 14:19:36 ennael Exp $
# Authentications mechanism (for list see saslauthd -v)
SASL_AUTHMECH=pam
...

By default, PAM is the activated authentication mechanism. Let's replace it by LDAP:

# cat /etc/sysconfig/saslauthd
# $Id: CS-service-messaging.xml,v 1.9 2008-09-12 14:19:36 ennael Exp $
# Authentications mechanism (for list see saslauthd -v)
SASL_AUTHMECH=ldap
...

Now we must define the necessary elements to identify the LDAP directory's contact mode:

# cat /etc/saslauthd.conf
ldap_servers: ldap://<ip_ldap_server>
ldap_version: 3
ldap_auth_method: bind
ldap_bind_dn: cn=Manager,dc=example,dc=com
ldap_bind_pw: <password>
ldap_search_base: ou=Users,dc=example,dc=com
ldap_scope: one
ldap_filter: uid=%u
ldap_verbose: on
   

Finally, verify that the service is active on boot-up. If not, it must be configured differently, by activating saslauthd for levels 3 and 5:

# chkconfig --level 35 saslauthd on
# chkconfig --list saslauthd
saslauthd  0:Arrêt  1:Arrêt  2:Marche  3:Marche  4:Marche  5:Marche  6:Arrêt

Let's configure Cyrus-IMAP. You only need to specify the server's administrator(s) through the admins parameter.

# cat /etc/imapd.conf
configdirectory: /var/lib/imap
partition-default: /var/spool/imap
admins: imapadmin cyrus
allowanonymouslogin: no
sieveusehomedir: no
sievedir: /var/lib/imap/sieve
sendmail: /usr/sbin/sendmail
hashimapspool: true
sasl_pwcheck_method: saslauthd
sasl_mech_list: PLAIN
tls_cert_file: /etc/ssl/cyrus-imapd/cyrus-imapd.pem
tls_key_file: /etc/ssl/cyrus-imapd/cyrus-imapd.pem

Restart the server:

# service cyrus-imapd restart

3.1.3. Testing the Server's Behavior

First, we must test saslauthd and the LDAP directory contact with the testsaslauthd:

   

Let's make sure that Cyrus-IMAP for POP3 (port 110) and IMAP (port 143) works correctly:

# telnet 192.168.1.2 143
Trying 192.168.1.2...
Connected to imap.example.com (192.168.1.2).
Escape character is '^]'.
* OK tellure Cyrus IMAP4 v2.3.12-0.p2.4mdv2009.0 server ready
# telnet 192.168.1.2 110
Trying 192.168.1.2...
Connected to imap.example.com (192.168.1.2).
Escape character is '^]'.
+OK tellure Cyrus POP3 v2.3.12-0.p2.4mdv2009.0 server ready 
<2428069223.1136796638@imap>

3.1.4. Managing Cyrus-IMAPD

You can manage Cyrus through the cyradm utility. First, connect to the server as a service administrator.

# cyradm --user imapadmin localhost
IMAP Password:
tellure> help
authenticate, login, auth         authenticate to server
chdir, cd                         change current directory
createmailbox, create, cm         create mailbox
deleteaclmailbox, deleteacl, dam  remove ACLs from mailbox
deletemailbox, delete, dm         delete mailbox
disconnect, disc                  disconnect from current server
exit, quit                        exit cyradm
help, ?                           show commands
info                              display mailbox/server metadata
listacl, lam, listaclmailbox      list ACLs on mailbox
listmailbox, lm                   list mailboxes
listquota, lq                     list quotas on specified root
listquotaroot, lqr, lqm           show quota roots and quotas for mailbox
mboxcfg, mboxconfig               configure mailbox
reconstruct                       reconstruct mailbox (if supported)
renamemailbox, rename, renm       rename (and optionally relocate) mailbox
server, servername, connect       show current server or connect to server
setaclmailbox, sam, setacl        set ACLs on mailbox
setinfo                           set server metadata
setquota, sq                      set quota on mailbox or resource
version, ver                      display version info of current server

Here are the principal user management tasks:

  • Adding a user and creating his mailbox: cm;

    localhost> cm user.toto 
    localhost> cm user.toto.sent
    localhost> cm user.toto.trash
  • Deleting a mailbox: dm;

    localhost> dm user.toto
  • list the mailboxes created: lm

    localhost> lm
          user.loic (\HasNoChildren)        
          user.anne (\HasNoChildren)
          user.benjamin (\HasNoChildren)
  • Set quotas: sq

    localhost> sq 524288000 user.anne 
          user.loic (\HasNoChildren) 
          user.anne (\HasNoChildren) 
          user.benjamin (\HasNoChildren)
  • List quotas: lq;

    localhost> lq user.anne 
     STORAGE 0/524288000 (0%)
  • Set ACLs: setacl. We use the ACLs listed below:

    Table 8.2. Managing ACLs in Cyrus-IMAP

    ACL Content
    l see the list of mailboxes without their content
    r read the content of mailboxes
    s keep the “seen” and “recent” states during IMAP sessions
    w write (modification of the “recent”, “answered” and “draft” messages' indicators)
    i inserting a message in a mailbox (moving or copying)
    c create sub-mailboxes in the main box (creating main mailboxes isn't authorized for non-admin users)
    d destroy a message and/or the box itself
    a manage the mailbox (modify ACLs)
    none no rights
    read ((=lrs) read the content of the mailbox
    append (=lrsip) read the content of the mailbox and add a message in queue
    write (=lrswipcd) read the content, post in it, add a message in queue, destroy a message or the box itself. In short, all rights except the one to modify ACLs
    all (=lrswipcda) all rights, usually given to the mailboxes' respective owners

    To set ACLs, use the following command:

    localhost> setacl user.mailgroup anne read
  • list ACL: lam

    localhost> lam user.mailgroup
          anne lrswipcda
          loïc lrswipcda
          benjamin	lrswipcda
[Note] Note

To generate mailboxes on the fly, create a file containing all the mailbox creation commands. Then, send the standard output of the file's display to the cyradm.

Example: let's create boxes for users anne, loic and benjamin:

# cat liste_boites
    cm user.anne
    cm user.loic
    cm user.benjamin
# cat liste_boites |cyradm –user admin localhost

3.1.5. Cyrus Toolbox

Cyrus-IMAP is provided with a number of tools allowing to us test and verify it's good functioning especially on an authentication level:

# imtest -a anne localhost
S: * OK tellure Cyrus IMAP4 v2.3.12-0.p2.4mdv2009.0 server ready
C: C01 CAPABILITY
S: * CAPABILITY IMAP4 IMAP4rev1 ACL QUOTA LITERAL+ MAILBOX-REFERRALS 
NAMESPACE UIDPLUS ID NO_ATOMIC_RENAME UNSELECT CHILDREN MULTIAPPEND 
BINARY SORT THREAD=ORDEREDSUBJECT THREAD=REFERENCES ANNOTATEMORE IDLE 
STARTTLS LISTEXT LIST-SUBSCRIBED X-NETSCAPE
S: C01 OK Completed
Please enter your password:
C: L01 LOGIN anne {8}
S: + go ahead
C: <omitted>
S: L01 OK User logged in
Authenticated.
Security strength factor: 0

3.1.6. Using POP3S and IMAPS

By default, cyrus-imapd is installed and includes the activation of pop3s and imaps. It is strongly recommended you use the secured IMAP protocol through SSL on port 443. IMAPS is a good option to set up a secured mail solution.

Sous Mandriva Enterprise Server 5, lors de l'installation du démon cyrus-imap, IMAPS is activated by default. For that to occur, an SSL certificate was automatically generated. If you want to change the SSL, you can generate a new one with the following command:

# openssl req -new -x509 -nodes -out /etc/ssl/cyrus-imapd/cyrus-imapd.pem
-keyout cyrus-imapd.pem -days 365

3.2. The Postfix SMTP Server

In this section we only address one particular configuration example of Postfix.

3.2.1. Basic SMTP Server Concepts

A SMTP (Simple Mail Transfer Protocol) server can be compared to a post office. The post office receives the letter for the zone in which it's located and sorts it. If a letter is destined to someone living in a zone serviced by the post office, it will deliver it in the person's mailbox. In the opposite case, the letter is sent to the post office which services the recipient's zone.

The standard Postfix server's operations are similar. It receives messages from the local network and of other mail servers which identified it as the mail manager for a given domain. The server reads the recipient's address and:

  • If the domain name corresponds to the domain locally managed, the message is deposited in the corresponding mailbox.

  • In the opposite case, the server looks for the server which manages the concerned zone and sends it the mail.

Postfix is the successor to Sendmail. It's newer and its architecture lies on the notion of modularity.

Postfix's main Web references:

3.2.2. Installation and Tree Structure of Postfix

Installing Postfix is easy: installing the Postfix package will do it. However, Mandriva Enterprise Server 5 provides a number of additional packages:

  • postfix-pcre: supports PCRE (Perl Compatible Regular Expression) for configuration;

  • postfix-ldap : supports LDAP maps in Postfix to manage authentication on an LDAP directory;

Postfix's tree structure reflects the modularity of its design:

  • /etc/postfix: directory containing the server's configuration files;

  • /var/log/mail: directory containing the server's log files, separated into three files (info, warnings, errors) according to the information's importance;

  • /var/spool/postfix: directory containing every spool directory relative to the server's functioning as described earlier;

  • /etc/sysconfig/postfix: group of options used to start the server's daemons.

3.2.3. Configuring the Postfix Server

The main configuration file is /etc/postfix/main.cf. We'll use this file to present the base parameters which assure the server's good functioning in the case described at the beginning of this chapter.

# cat /etc/postfix/main.cf
# paramétrage système du serveur
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/lib/postfix
mail_owner = postfix

# nom de machine
myhostname = host.domain.com
# nom de domaine de la valeur myhostname
mydomain = domain.com
# domaine apparaissant dans le courrier envoyé de cette machine
myorigin = $mydomain

# interfaces sur lesquelles le service va pouvoir écouter (par défaut 
# toutes)
inet_interfaces = all
# domaines pour lequels la machine livrera le courrier localement au 
# lieu de les transmettre à une autre machine
mydestination = $myhostname, localhost.$mydomain, 
	/etc/postfix/destinations
# map contenant les adresses et/ou utilisateurs locaux
local_recipient_maps = $alias_maps

# code spécifiant une réponse du serveur SMTP lorsque le domaine d'un
# destinataire correspond à $mysdestination ou lorsque l'adresse de 
# destination ou l'adresse locale n'existe pas. Par défaut, le code 
# est utilisé est 450, code qui propose de renouveler l'envoi (550 
# pour ne pas le renouveler) 
unknown_local_recipient_reject_code = 450
# réseaux autorisés à utiliser le serveur SMTP
mynetworks = 172.16.51.0/24, 127.0.0.0/8

# spécifie les bases qui seront utilisées par la commande newaliases
# pour générer la table des alias
alias_database = hash:/etc/postfix/aliases

mail_spool_directory = /var/spool/mail
    
# spécifie le mode de transport des mails dans le fichier master.cf 
# à utiliser après avoir traité les fichiers aliases et .forward
mailbox_transport = cyrus
# bannière affichée lors de l'accès au serveur SMTP
smtpd_banner = $myhostname ESMTP $mail_name ($mail_version) (Mandrake
	Linux)

debug_peer_level = 2
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
xxgdb $daemon_directory/$process_name $process_id & sleep 5
# délai en nombre d'heures au bout duquel un avertissement est envoyé
# quand un courrier n'a pas pu être livré
delay_warning_time = 4

# autres paramétrages système du serveur
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.0.6/samples
readme_directory = /usr/share/doc/postfix-2.0.6/README_FILES

The other base file is /etc/postfix/master.cf. It defines the functioning of each server working inside the server:

  • service type: behaviour type (TCP/IP socket or UNIX);

  • private: restricted access to the Postfix service;

  • unprivileged: service executed with or without root privileges;

  • chroot: service which runs in chroot mode;

  • wakeup time time after which the process is automatically reactivated;

  • maxprocmaximum number or processes simultaneously executed;

  • command: executed command.

3.2.4. Postfix Toolbox

Postfix offers a certain number of useful tools for day-to-day server administration:

Verify the configuration

List all the parameters used in the main.cf file.

# postconf

Lists only the personalized parameters.

# postconf -n

Validates Postfix' configuration (main.cf file).

# postfix check
postfix: fatal: bad string length 0 < 1: manpage_directory =
Configure the Postfix daemon

Start | stop | restart | reload the Postfix service's configuration:

# service postfix start | stop | restart | reload

Force the delivery of queued messages.

# service postfix flush

Check the Postfix service's state.

# service postfix status
       master (pid 6417) est en cours d'exécution...
# ps -ef | grep postfix
root      6417     1  0 10:18 ? 00:00:00 /usr/lib/postfix/master
postfix   6422  6417  0 10:18 ? 00:00:00 pickup -l -t fifo -u -c -o 
	content_filter  -o receive_override_options
postfix   6423  6417  0 10:18 ? 00:00:00 qmgr -l -t fifo -u -c
      

That command allows you to check precisely that the different daemons which compose Postfix are working. You should at least see: master, qmgr, and pickup.

Postfix maps management

Recreate the aliases.db map:

# newaliases 

Recreate a specific mapping:

# postmap <map>

Read a mapping's content:

# postmap -q <map>
File management

Display every queued message

# postqueue -p 
-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
9D3F67D5F*      338 Fri Jan  6 19:31:43  plop@plop.com
                                         anne@tellure.example.subnet

-- 0 Kbytes in 1 Request.

or

# mailq
-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
9D3F67D5F*      338 Fri Jan  6 19:31:43  plop@plop.com
                                         anne@tellure.example.subnet

-- 0 Kbytes in 1 Request.

Delete queued mail:

# postsuper -d <queue_ID>
#  postsuper -d  9D3F67D5F
postsuper: 9D3F67D5F: removed
postsuper: Deleted: 1 message

The postsuper -d ALL command allows you to suppress every queued mail.

3.2.5. Securing a Mail Server

Here are a few tips enabling you to secure at a minimum your Postfix server.

3.2.5.1. Postfix in chroot Mode

Securing Postfix can be done by executing the server's daemon's in a “cage”. In Postfix's case, this means that the processes have the weakest possible privileges and have access to a limited tree structure, that is /var/spool/postfix.

Mandriva Enterprise Server 5's Postfix package is provided with a script which allows you to easily execute Postfix in chroot mode (and to revert back to normal state): postfix-chroot.sh. It executes the following:

  • Creates the chroot tree structure in /var/spool/postfix by default;

  • Modifies /etc/postfix/master.cf to specify the execution of the daemons in chroot mode.

  • Reloading the service.

# /usr/sbin/postfix-chroot.sh enable
	setting up chroot at: /var/spool/postfix
copy system files into chroot
  /etc/localtime -> /var/spool/postfix/etc/localtime
  /etc/host.conf -> /var/spool/postfix/etc/host.conf
  /etc/resolv.conf -> /var/spool/postfix/etc/resolv.conf
  /etc/nsswitch.conf -> /var/spool/postfix/etc/nsswitch.conf
  /etc/hosts -> /var/spool/postfix/etc/hosts
  /etc/services -> /var/spool/postfix/etc/services
copy additional files into chroot
copy nss libraries into chroot
  /lib64/libnss_dns.so.2 -> /var/spool/postfix/lib64/libnss_dns.so.2
  /lib64/libnss_dns-2.8.so -> /var/spool/postfix/lib64/libnss_dns-2.8.so
  /lib64/libnss_nis.so.2 -> /var/spool/postfix/lib64/libnss_nis.so.2
  /lib64/libnss_nis-2.8.so -> /var/spool/postfix/lib64/libnss_nis-2.8.so
  /lib64/libnss_winbind.so.2 -> /var/spool/postfix/lib64/libnss_winbind.so.2
  /lib64/libnss_winbind.so -> /var/spool/postfix/lib64/libnss_winbind.so
  /etc/ldap.conf -> /var/spool/postfix/etc/ldap.conf
  /lib64/libnss_ldap.so.2 -> /var/spool/postfix/lib64/libnss_ldap.so.2
  /lib64/libnss_ldap-2.8.so -> /var/spool/postfix/lib64/libnss_ldap-2.8.so
  /lib64/libnss_compat.so.2 -> /var/spool/postfix/lib64/libnss_compat.so.2
  /lib64/libnss_compat-2.8.so -> /var/spool/postfix/lib64/libnss_compat-2.8.so
  /lib64/libnss_files.so.2 -> /var/spool/postfix/lib64/libnss_files.so.2
  /lib64/libnss_files-2.8.so -> /var/spool/postfix/lib64/libnss_files-2.8.so
  /lib64/libnss_files.so.2 -> /var/spool/postfix/lib64/libnss_files.so.2
  /lib64/libnss_files-2.8.so -> /var/spool/postfix/lib64/libnss_files-2.8.so
Reloading Postfix Service:                   [  OK  ]

After this it's important to update the chroot if modifications are done and which could affect the mail environment. To check the presence of such modifications, type the following command:

# postfix-chroot.sh check
files /var/spool/postfix/etc/hosts and /etc/hosts differ
Reloading the Postfix service::             [  OK  ]

To update:

# postfix-chroot.sh check_update
Reloading the Postfix service:             [  OK  ]
    
3.2.5.2. Securing Postfix' Configuration

First of all, let's put a few options in /etc/postfix/main.cf.

smtpd_helo_required = yes
     disable_vrfy_command = yes

smtpd_recipient_restrictions =
    reject_invalid_hostname,
    reject_non_fqdn_hostname,
    reject_non_fqdn_sender,
    reject_non_fqdn_recipient,
    reject_unknown_sender_domain,
    reject_unknown_recipient_domain,
    permit_mynetworks,
    reject_unauth_destination,
    check_recipient_access 
    check_client_access dbm:/etc/postfix/client_checks,
    reject_rbl_client sbl.spamhaus.org,
    reject_rbl_client cbl.abuseat.org,
    reject_rbl_client dnsbl.sorbs.net,
    permit

smtpd_data_restrictions =
    reject_unauth_pipelining, 
    # http://www.postfix.org/postconf.5.html#reject_unauth_pipelining
    permit
3.2.5.3. Filtering at the HELO Step

An important step in the dialog with an SMTP server is the HELO command. A certain number of checks at this level of the dialog allows you to do a first filtering which is non immaterial. The configuration is done in the /etc/postfix/main.cf file:

smtpd_recipient_restrictions = check_helo_access 
dbm:/etc/postfix/helo_checks

This instruction enables us to specify a new file in which the filters to apply are defined. That file is called /etc/postfix/helo_checks:

# cat /etc/postfix/helo_checks
# We can block the machines that present themselves as being part of
# the domain while they're really outside of it
example.tld REJECT You are not in example.tld

# Ditto for IP addresses (the mail server's IP)
192.168.1.2 REJECT You are not 192.168.1.2

# Ditto for localhost
localhost REJECT You are not me
[Note] Note

It's useful to know the dialog's steps between an SMTP client and server. This allows you to detect eventual problem levels:

$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
220 dhcp140.example.com ESMTP Postfix (Mandriva MES5)
HELO mandriva.com
250 mes5.example.com
Mail from test@mandriva.com
250 Ok
RCPT To: a@example.com
250 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
test
.
250 Ok: queued as B4DAE434B

The operation occurs in 4 steps:

  1. HELO: presentation of the host that contacts, the SMTP server answers;

  2. Mail From: sender's address, the SMTP server validates the address;

  3. RCPT To:: recipient's address, the SMTP server validates the address;

  4. DATAdata sending, the message ends with a . (period).

3.2.5.4. Filtering the Sender

In the same manner, let's use a instruction taken from /etc/postfix/main.cf

smtpd_recipient_restrictions = check_sender_access 
dbm:/etc/postfix/sender_checks

In /etc/postfix/sender_checks :

# cat /etc/postfix/sender_checks
# We ban a domain
# Code SMTP 554 corresponds to: "Transaction failed"
domaine.org 554 Spam not tolerated here

# A domain is put on the blacklist (RBL) but we still want to
# receive mails from that domain: domain.com OK

# For a domain on the blacklist, we want to receive certain addresses
someuser@example3.tld OK
example3.tld REJECT
3.2.5.5. Filtrer les destinataires

Let's say we want to filter recipients, for example, from an old mailbox that still gets spammed.

In the /etc/postfix/main.cf file:

smtpd_client_restrictions =
        check_recipient_access regexp:/etc/postfix/rcpt_restrictions

In /etc/postfix/rcpt_restrictions

/sales@domaine\.info/ REJECT
/bob@domaine\.info/ REJECT

If you want to filter on the format of the sender's addresses, in main.cf:

smtpd_recipient_restrictions = check_client_access 
	 pcre:/etc/postfix/client_checks.pcre

In the /etc/postfix/client_checks.pcre file:

/^\@/ 550 Invalid address format.
/[!%\@].*\@/ 550 This server disallows weird address syntax.

3.2.6. Advanced Postfix Usage

3.2.6.1. LDAP Support in Postfix

Postfix offers the possibility to use an LDAP directory to verify the recipient and to deliver his messages. Beforehand, you must install the postfix-ldap package.

The technique consists in declaring the LDAP maps, specifying the LDAP server, how to interrogate the server and the necessary information to recuperate.

# cat /etc/postfix/main.cf
...
# alias list used for local mail
alias_maps = ldap:ldapuser, ldap:ldapgroup

# maps use for LDAP authentication LDAP
virtual_alias_maps = ldap:ldapuser, ldap:ldapgroup

# definition of the necessary information to recuperate a user's mail address
ldapuser_server_host = 192.168.1.1
ldapuser_server_port = 389
ldapuser_bind = yes
ldapuser_bind_dn = cn=Manager,dc=example,dc=com
ldapuser_bind_pw = secret
ldapuser_search_base = ou=Personnes,dc=example ,dc=com
ldapuser_timeout = 60
ldapuser_query_filter = (&(objectclass=qmailuser)(mailLocalAddress=%s))
ldapuser_result_attribute = mail
ldapuser_lookup_timeout = 60

# definition of the necessary information to recuperate a group's mail
# address
ldapgroup_server_host = 192.168.1.1
ldapgroup_server_port = 389
ldapgroup_bind = yes
ldapgroup_bind_dn = cn=Manager,dc=example ,dc=com
ldapgroup_bind_pw = secret
ldapgroup_search_base = ou=Groupes,dc=example ,dc=com
ldapgroup_timeout = 60
ldapgroup_query_filter = (&(objectclass=mailalias)(mailAlias=%s))
ldapgroup_result_attribute = rfc822MailMember
ldapgroup_lookup_timeout = 60

# specifies the bases to use by the newalises command to generate the
# alias table
alias_database = hash:/etc/postfix/aliases, ldap:ldapuser, 
	ldap:ldapgroup

Restart the Postfix server to take the modification into account.

3.2.6.2. SMTP Authentication on Postfix

By default the configured Postfix server will not accept messages coming from its network. To authorize another machine to send messages through Postfix, different possibilities exist. Either you authorize the client machine's IP address to use the server to send a message, or you can use SMTP authentication. We'll see how to use the latter..

We must install the following packages:

#urpmi libsasl2 libsasl2-devel libsasl2-plug-plain libsasl2-plug-login

First of all, we have to generate an SSL certificate for Postfix.

# mkdir /etc/postfix/ssl
# cd /etc/postfix/ssl/
# openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024
# chmod 600 smtpd.key
# openssl req -new -key smtpd.key -out smtpd.csr
# openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out 
	smtpd.crt
# openssl rsa -in smtpd.key -out smtpd.key.unencrypted
# mv -f smtpd.key.unencrypted smtpd.key
# openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out 
	cacert.pem -days 3650

Then, add the configuration options to Postfix in the /etc/postfix/main.cf file:

# cat /etc/postfix/main.cf
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_tls_auth_only = no
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_recipient_restrictions = permit_mynetworks 
	permit_sasl_authenticated

To test the good behavior of the TLS authentication, you can simply connect through telnet:

# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
220 localhost ESMTP Postfix (Mandriva MES5)
ehlo localhost
250-localhost
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250 8BITMIME

If you see line 250-STARTTLS as well as S: 250-AUTH that means that the SMTP authentication is active on your server. From this moment on, only authenticated users will be able to send messages via the SMTP server. Furthermore, the authentication is encrypted through SSL. Remember to configure your mail client accordingly.

3.3. Anti-Virus and Anti-Spam Solutions

Avoiding viruses and SPAM means to protect your mail server and your whole network. Here's how Postfix solves this issue. Before handling any message, it transmits incoming mail to the amavisd-new service. The latter, according to its configuration, handles the messages through an anti-virus and/or anti-spam utility. Once that's done, messages are returned in the incoming queue of Postfix which handles them to send them to the recipients.

3.3.1. Installing Software Components

  1. Install amavisd-new

    Simply install the amavisd-new package. Be careful as the package has numerous dependencies, essentially associated with Perl modules.

  2. Install SpamAssassin

    Simply install the spamassassin package.

  3. Install the Clamav Anti-virus

    Install the following packages: clamav (common library used to access the anti-virus), clamd (anti-virus server daemon) and clam-db (clamav's anti-virus base).

3.3.2. Configuring amavisd-new

The configuration of amavis-d consists of specifying the following in the /etc/amavisd/amavisd.conf file:

  • mail domain;

  • ncoming/outgoing ports of messages;

  • sending address of alerts;

  • handling of messages containing viruses;

  • specification of the anti-virus.

# cat /etc/amavisd/amavisd.conf 
 ... 
 $mydomain = 'mondomaine.com'; 
...
$inet_socket_port = 10024;   # listen on this local TCP port(s) 
	(see $protocol)
...
# Modifier les adresses mails pour l'envoi des rapports virus / spam 
 $virus_admin = "admin\@$mydomain"; 
 $mailfrom_notify_admin = "admin\@$mydomain"; 
 $mailfrom_notify_recip = "admin\@$mydomain"; 
 $mailfrom_notify_spamadmin = "admin\@$mydomain"; 
...

# Redirection des mails vers Postfix après traitement
$notify_method  = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[127.0.0.1]:10025'; # set to undef with milter
...

#Traitement des spams et virus détectés 
$final_virus_destiny = D_DISCARD; 
$final_banned_destiny = D_BOUNCE; 
$final_spam_destiny = D_PASS; 
$final_bad_header_destiny = D_PASS; 
 ... 

#Décommenter les lignes correspondant à clamav
['ClamAV-clamd', \&ask_daemon, ["CONTSCAN {}\n", 
	"/var/lib/clamav/clamd.socket"],qr/\bOK$/, qr/\bFOUND$/,
	qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],
...

#Décommenter les lignes correspondant à clamav
@av_scanners_backup = (

  ### http://www.clamav.net/   - backs up clamd or Mail::ClamAV
  ['ClamAV-clamscan', 'clamscan',
    "--stdout --disable-summary -r --tempdir=$TEMPBASE {}", [0], [1],
    qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],
...
    

VMake sure that the clamd daemon is configured to be launched automatically:

#chkconfig –list clamd
clamd         0:stop         1:stop         2:stop         3:run        4:run        5:run        6:stop

3.3.3. Configuring Postfix

To take into account amavisd-new in Postfix's configuration, we must modify main.cf and master.cf:

# cat /etc/postfix/main.cf 
 ... 
# Handing of incoming messages
 content_filter=smtp-amavis:[127.0.0.1]:10024 
 smtp-amavis_destination_concurrency_limit=2 
 
 # cat /etc/postfix/master.cf 
 ... 
 127.0.0.1:10025 inet n - y - - smtpd 
 -o content_filter= 
 -o smtpd_restriction_classes= 
 -o smtpd_client_restrictions= 
 -o smtpd_helo_restrictions= 
 -o smtpd_sender_restrictions= 
 -o smtpd_recipient_restrictions=permit_mynetworks,reject 
 -o mynetworks=127.0.0.0/8 
 -o mynetworks_style=host 
 -o strict_rfc821_envelopes=yes 
 -o receive_override_options=no_unknown_recipient_checks,
 		no_header_body_checks 
 -o smtpd_client_connection_limit_exceptions=127.0.0.0/8 
 ...

Restart Postfix to take modifications into account. To verify its behaviour:

 # telnet localhost 10024 
 Trying 127.0.0.1... 
 Connected to localhost (127.0.0.1). 
 Escape character is '^]'. 
 220 [127.0.0.1] ESMTP amavisd-new service ready 
  # telnet localhost 10025 
 Trying 127.0.0.1... 
 Connected to localhost (127.0.0.1). 
 Escape character is '^]'. 
 220 example.com Welcome on example.com mail server

3.3.4. Configuring SpamAssassin

The main configuration file is /etc/mail/spamassassin/local.cf:

# cat /etc/mail/spamassassin/local.cf 
required_hits 5
rewrite_header Subject [SPAM]
report_safe 0
auto_whitelist_path        /var/spool/spamassassin/auto-whitelist
auto_whitelist_file_mode   0666
dcc_home                   /var/lib/dcc
auto_learn 1
use_razor2 1
use_bayes 1

LYou should refine the configuration in regards with the server's desired usage: the stricter SpamAssassin's rules are, the more you're bound to get false positives.

To enhance SpamAssassin's SPAM detection, it's good to understand its behaviour as well as the its configuration's different instructions. During its analysis, SpamAssassin observes the email in its ensemble and gives it a score according to different parameters. For example, if the email contains a lot of keywords usually used in SPAM, its score augments. Furthermore, SpamAssassin, uses a system of complex rules which allows it to model the score according to the type of mail generally handled by the server. Through the server's “progressive learning”, this allows you to get precise detection with few false positives.

The required_hits instruction defines the score needed for an email to be considered as SPAM. In this case, the rewrite_header instruction will be taken into account, and will add the “[SPAM]” tag to the email's subject line. The use_bayes instruction indicates to SpamAssassin to use its different internal calculation rules based on its learning. Every mail handled by SpamAssassin will contain in its header a trace of that handling. In your mail client, you can display this information.

X-Spam-Status: No, score=-2.6 required=5.0 tests=BAYES_00
   autolearn=disabled version=3.0.4
[Tip] Tip

Don't hesitate to look at the score that mails labeled as SPAM (but that weren't) so as to modify the required_hits value. Another solution to enhance the score calculation is to define preferred languages for emails. If you receive many emails in English, instruct SpamAssassin with the following instructions:

ok_languages en
     ok_locales en

3.3.5. Launching SpamAssassin's Auto-Learning

Here's another way to refine SpamAssassin's behaviour rules by sending it messages you consider to be SPAM.

  1. Create a box accessible by all users:

     # cyradm --user cyrus localhost
     IMAP Password:
     localhost> cm user.SPAM
     localhost> dam user.SPAM SPAM 
     localhost> sam user.SPAM anyone all
     localhost> lam user.SPAM
     anyone lrswipcda
     localhost> 

    Users will move all the SPAM they receive on their own accounts to that mailbox.

  2. Schedule a script which will launch the auto-learning from those mails, and then destroy them:

    #Running auto-learn
    for i in /var/spool/imap/s/user/SPAM/[0-9]*.; do sa-learn 
    	--showdots --spam $i; done 
    #Suppression des messages de la boîte
    rm -f /var/spool/imap/s/user/SPAM/[0-9]*. 
    Reconstruire la base Cyrus
    su -l cyrus -c "/usr/lib/cyrus-imapd/reconstruct user.SPAM "

    The script should be placed in a crontab and launched regularly.