Ceci est une ancienne révision du document !



Installation d'une solution mail complète : Postfix, Dovecot, MySQL, Postfixadmin

Cette page propose un pas-à-pas pour mettre en place rapidement un serveur de messagerie en faisant appel à l'ensemble:

  • Une solution LAMP fonctionnelle.
  • Un certificat SSL (auto-signé ou autre) valide.
Rappel simple :
sudo apt-get install ssl-cert
sudo make-ssl-cert generate-default-snakeoil --force-overwrite

Installation des paquets

  1. Installez la première série de paquets utiles à savoir:
  2. Relancez le service apache
    sudo service apache2 restart
  3. Installez la seconde série de paquets utiles à savoir :

Création de l'administrateur mail dans MySQL

sudo mysql -u root -p

Créez la base de données (ici postfixadmin) et l'utilisateur (ici postfixadmin)

create database postfixadmin;
grant all on postfixadmin.* to 'mail'@'localhost' identified by 'mot_de_passe_administrateur_mail';

Plus d'informations sur la page MySQL

Postfixadmin permet de gérer graphiquement les domaines et les boites e-mail rattachées. Il permet de créer des administrateurs par domaine qui peuvent eux-mêmes créer des boites ainsi que des alias. Le tout se pilotant au travers d'un navigateur web.

Installation

Un paquet tout prêt est disponible et évite plusieurs étapes de configuration/mise en place. Il s'agit donc de

  1. le télécharger à cette adresse

Ceci se résume dans un terminal par:

wget http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.3.5/postfixadmin_2.3.5-1_all.deb
sudo dpkg -i postfixadmin_2.3.5-1_all.deb

Configuration

Paramètres principaux

Ouvrez avec les droits d'administration le fichier /etc/postfixadmin/config.inc.php, pour modifier/vérifier les variables comme suit :

$CONF['configured'] = true;
$CONF['postfix_admin_url'] = '/postfixadmin'; # à laisser tel quel pour le multi-domaine
$CONF['admin_email'] = 'me@example.com'; # l'adresse mail de l'administrateur général
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
$CONF['encrypt'] = 'md5crypt';
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';

Définition de la base de données

Ouvrez avec les droits d'administration le fichier /etc/postfixadmin/dbconfig.inc.php pour insérer les accès MySQL précédemment créés.

$dbuser='postfixadmin';
$dbpass='mot_de_passe_administrateur_mail';
$basepath='';
$dbname='postfixadmin';
$dbserver=''; # utilisera la valeur par défaut : localhost
$dbport=''; # utilisera le port MySQL par défaut
$dbtype='mysql';

Mise en place

Lancez la configuration en saisissant dans votre navigateur l'adresse : http://localhost/postfixadmin/setup.php
Créez un administrateur Postfixadmin. Il est fortement conseillé de bien le différencier de l'administrateur mail quant à son ensemble nom/mot de passe.

Attention une fois cet administrateur créé, le script vous retourne votre mot de passe "hashé". NOTEZ LE BIEN !!!
Il sera utilisé dans votre configuration finale.

Ouvrez avec les droits d'administration le fichier /etc/postfixadmin/config.inc.php et modifier la variable :

$CONF['setup_password'] = '… votre mot de passe hashé …';

Il faut ensuite protéger cette page (vous pourrez créer d'autres administrateurs via l'interface de postfixadmin).
Ouvrez avec les droits d'administration le fichier /etc/apache2/conf.d/postfixadmin, et ajouter :

<Files "setup.php">
deny from all
</Files>

Se rendre sur la page http://localhost/postfixadmin, et créer le premier domaine. Ajouter une boite mail à ce domaine.
À ce stade, Postfixadmin est opérationnel.

Ici les utilisateurs sont virtuels, et donc indépendant de la création/gestion classique Unix. Un seul utilisateur (Unix) aura les droits sur ce dossiers et permettra de gérer les liaisons entre Dovecot et Postfix.
Pour l'exemple, l'utilisateur sera vmail et le groupe mail. Le répertoire dédié sera dans /home/vmail (ces valeurs sont à votre convenance).

  • Création du groupe mail puis de l'utilisateur vmail associé à ce groupe
    sudo groupadd mail
    sudo useradd -r -u 150 -g mail -d /home/vmail -s /sbin/nologin -c "Propriétaire des répertoires e-mail virtuel" vmail
  • Création du répertoire dédié et les droits associés
    sudo mkdir /home/vmail
    sudo chmod 770 /home/vmail
  • Désignation du propriétaire:groupe du dossier
    sudo chown vmail:mail /home/vmail

Dovecot gère les connexions POP3 et IMAP, permet de gérer les mails locaux et récupère les courriers en provenance de Postfix.
Il gère également l'authentification SMTP.

Configuration

Vous allez attaquer la première partie "fatiguante" .

Définition de la base de données ?

Éditez ou créez avec les droits d'administration le fichier /etc/dovecot/conf.d/auth-sql.conf.ext avec le contenu suivant :

# 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
}

Définition des accès à la base de données ?

Vérifiez avant tout l'UID et le GID :

grep vmail /etc/passwd

devrait répondre quelque chose comme

vmail:x:150:1001:Virtual maildir handler:/home/vmail:/sbin/nologin

Notez bien ces informations avant d' éditer avec les droits d'administration le fichier /etc/dovecot/dovecot-sql.conf.ext que vous modifierez comme suit :

  • Type de base de données:
    # Database driver: mysql, pgsql, sqlite
    driver = mysql
  • Ici remplacez mot_de_passe_postfixadmin par celui entrée à la section 1.2
    # Examples:
    #   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=postfixadmin user=postfixadmin password=mot_de_passe_postfixadmin
  • Type d'authentification
    # Default password scheme.
    #
    # List of supported schemes is in
    # http://wiki2.dovecot.org/Authentication/PasswordSchemes
    #
    default_pass_scheme = MD5-CRYPT
  • Requète de mot de passe (adaptez avec les informations obtenues en début de ce chapitre)
    # Define the query to obtain a user password.
    password_query = \
      SELECT username as user, password, '/home/vmail/%d/%n' as userdb_home, \
      'maildir:/home/vmail/%d/%n' as userdb_mail, 150 as userdb_uid, 1001 as userdb_gid \
      FROM mailbox WHERE username = '%u' AND active = '1'
  • Information utilisateur (adaptez avec les informations obtenues en début de ce chapitre)
    # Define the query to obtain user information.
    user_query = \
      SELECT '/home/vmail/%d/%n' as home, 'maildir:/home/vmail/%d/%n' as mail, \
      150 AS uid, 1001 AS gid, concat('dirsize:storage=', quota) AS quota \
      FROM mailbox WHERE username = '%u' AND active = '1'

FIXME

Éditez avec les droits d'administration le fichier /etc/dovecot/conf.d/10-auth.conf et modifier comme suit :

# 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>
 
#!include auth-deny.conf.ext
#!include auth-master.conf.ext
 
#!include auth-system.conf.ext
# Use the SQL database configuration rather than any of these others.
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext

FIXME

Éditez avec les droits d'administration le fichier /etc/dovecot/conf.d/10-mail.conf et modifier comme suit :

# 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 user@domain, same as %u if there's no domain
#   %d - domain part in user@domain, 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:/home/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

FIXME

Éditez avec les droits d'administration le fichier /etc/dovecot/conf.d/10-ssl.conf et modifier comme suit :
Si vous voulez utiliser le support SSL/TLS et/ou utiliser votre propre certificat. Dans le cas de votre propre certificat, il vous faudra renseigner les parties ssl_key_password = et ssl_ca =

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = yes
 
# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem

FIXME

Éditez avec les droits d'administration le fichier /etc/dovecot/conf.d/10-master.conf et modifier comme suit :
Ajout des options de Postfix à Dovecot.

service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Its default
  # permissions make it readable only by root, but you may need to relax these
  # permissions. Users that have access to this socket are able to get a list
  # of all usernames and get results of everyone's userdb lookups.
  unix_listener auth-userdb {
   mode = 0600
    user = vmail
    group = mail
  }
 
  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    # Assuming the default Postfix user and group
    user = postfix
    group = postfix       
  }

Rendre accessible la configuration à Dovecot et aux utilisateurs vmail.

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

Ajout des utilisateurs clamav et amavis et partage de leurs droits :

sudo adduser clamav amavis
sudo adduser amavis clamav

Configuration Amavis ClamAV

Éditez avec les droits d'administration le fichier /etc/amavis/conf.d/15-content_filter_mode et modifier comme suit :

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

Configuration SpamAssassin

Éditez avec les droits d'administration le fichier /etc/default/spamassassin et modifier comme suit :

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

On relance les services :

sudo service amavis restart
sudo service spamassassin restart

Seconde partie "fatiguante" :-P
Postfix gère les courriers entrant, via le protocole SMTP. Ici nous allons configurer Postfix pour qu'il gère les courriers au niveau Antivirus et AntiSpam avant de transmettre le tout à Dovecot, ainsi que la gestion des utilisateurs virtuels se connectant via SMTP pour envoyer du courrier.

Configuration

Création des fichiers de configuration pour que Postfix trouve les utilisateurs et domaines.

Éditez avec les droits d'administration le fichier /etc/postfix/mysql_virtual_alias_domainaliases_maps.cf et modifier comme suit :

user = postfixadmin
password = mot_de_passe_administrateur_postfix
hosts = 127.0.0.1
dbname = postfixadmin
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

Éditez avec les droits d'administration le fichier /etc/postfix/mysql_virtual_alias_maps.cf et modifier comme suit :

user = postfixadmin
password = mot_de_passe_administrateur_postfix
hosts = 127.0.0.1
dbname = postfixadmin
table = alias
select_field = goto
where_field = address
additional_conditions = and active = '1'

Éditez avec les droits d'administration le fichier /etc/postfix/mysql_virtual_domains_maps.cf et modifier comme suit :

user = postfixadmin
password = mot_de_passe_administrateur_postfix
hosts = 127.0.0.1
dbname = postfixadmin
table = domain
select_field = domain
where_field = domain
additional_conditions = and backupmx = '0' and active = '1'

Éditez avec les droits d'administration le fichier /etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf et modifier comme suit :

user = postfixadmin
password = mot_de_passe_administrateur_postfix
hosts = 127.0.0.1
dbname = postfixadmin
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

Éditez avec les droits d'administration le fichier /etc/postfix/mysql_virtual_mailbox_maps.cf et modifier comme suit :

user = postfixadmin
password = mot_de_passe_administrateur_postfix
hosts = 127.0.0.1
dbname = postfixadmin
table = mailbox
select_field = CONCAT(domain, '/', local_part)
where_field = username
additional_conditions = and active = '1'

Création du fichier qui contient les directives pour "nettoyer" les entêtes des courriers, tel que la base originale de l'adresse IP ou les identifiants de messagerie.
Éditez avec les droits d'administration le fichier /etc/postfix/header_checks et modifier comme suit :

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

Fichier de configuration principale de Postfix qui contient un bon nombre de choix complexes et des options sur la façon dont le courrier est relayé et comment se comporte SMTP. Pour affiner votre configuration, reportez vous à la configuration de Postfix (/usr/share/postfix/main.cf.dist).

Attention aux différents points, tel que :
- Le nom de domaine principal
- Dossier de vmail
- UID / GID

Éditez avec les droits d'administration le fichier /etc/postfix/main.cf et modifier comme suit :

# 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
smtpd_use_tls=yes
smtp_tls_security_level = may
smtpd_tls_security_level = may
#smtpd_tls_auth_only = no
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
 
# 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 a Very Bad Thing.
#
# You are encouraged to read up on what exactly each of these options accomplish.
 
# Requirements for the HELO statement
smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit
# Requirements for the sender details
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
# Requirements for the connecting server
smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl, reject_rbl_client dnsbl.njabl.org
# Requirement for the recipient address. Note that the entry for
# "check_policy_service inet:127.0.0.1:10023" enables Postgrey.
smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit
smtpd_data_restrictions = reject_unauth_pipelining
 
# require proper helo at connections
smtpd_helo_required = yes
# waste spammers time before rejecting them
smtpd_delay_reject = yes
disable_vrfy_command = yes
 
# General host and delivery info
# ----------------------------------
 
myhostname = blinckers-groups.eu
myorigin = /etc/hostname
#mydestination = blinckers-groups.eu, localhost
mydestination = localhost
#relayhost =
# If you have a separate web server that sends outgoing mail through this
# mailserver, you may want to add its IP address to the space-delimited list in
# mynetworks, e.g. as 111.222.333.444/32.
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
mynetworks_style = host
 
# This specifies where the virtual mailbox folders will be located.
virtual_mailbox_base = /home/vmail
# This is for the mailbox location for each user. The domainaliases
# map allows us to make use of Postfix Admin's domain alias feature.
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf, mysql:/etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf
# and their user id
virtual_uid_maps = static:150
# and group id
virtual_gid_maps = static:1001
# This is for aliases. The domainaliases map allows us to make
# use of Postfix Admin's domain alias feature.
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf, mysql:/etc/postfix/mysql_virtual_alias_domainaliases_maps.cf
# This is for domain lookups.
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
 
# Integration with other packages
# ---------------------------------------
 
# Tell postfix to hand off mail to the definition for dovecot in master.cf
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
 
# Use amavis for virus and spam scanning
content_filter = amavis:[127.0.0.1]:10024
 
# Header manipulation
# --------------------------------------
 
# Getting rid of unwanted headers. See: https://posluns.com/guides/header-removal/
header_checks = regexp:/etc/postfix/header_checks
# getting rid of x-original-to
enable_original_recipient = no

Configuration

Configuration

Configuration

* Projet de PostfixAdmin (en)


Contributeurs:McPeter

  • utilisateurs/mcpeter/postfix_dovecot_mysql_postfixadmin.1350040716.txt.gz
  • Dernière modification: Le 12/10/2012, 13:18
  • par McPeter