Dovecot et Postfix avec comptes virtuels

On a installé un certain nombre de choses sur le serveur, mais il nous manque quand mème un service essentiel, à savoir le mail, que ce soit à l’envoie (SMTP) ou à la reception (POP/IMAP).

Pour ce faire, et mème si on a le choix entre plus fournisseurs de serveurs SMTP et POP/IMAP (sendmail, exim, postfix, courier, solid, dovecot, etc..) mon penchant va plutôt vers un couplage Postfix/Dovecot avec un backend MySQL pour le stockage des noms de domaines virtuel ainsi que données d’authentification utilisateur.

Nous allons tout d’abord créer une base de donnée nommée vmails avec un compte utilisateur ayant les privilèges spécifiques à cette base de donnée, puis nous allons y exécuter le script sql suivant :

DROP TRIGGER IF EXISTS `vmail_users_trg_sha512_new`;
DROP TRIGGER IF EXISTS `vmail_users_trg_sha512_upd`;
DROP TABLE IF EXISTS `vmail_users`;
DROP TABLE IF EXISTS `vmail_domains`;
DROP TABLE IF EXISTS `vmail_aliases`;
CREATE TABLE `vmail_aliases` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `email_src` text COLLATE utf8mb4_bin NOT NULL,
  `email_dst` text COLLATE utf8mb4_bin NOT NULL,
  `dtcrea` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `dtupdt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;


CREATE TABLE `vmail_domains` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_bin NOT NULL,
  `transport` varchar(255) COLLATE utf8mb4_bin NOT NULL DEFAULT 'virtual:',
  `dtcrea` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `dtupdt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `vmail_domains_uk_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

CREATE TABLE `vmail_users` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `domain_id` int UNSIGNED NOT NULL,
  `email` varchar(512) COLLATE utf8mb4_bin NOT NULL,
  `passwd` varchar(200) COLLATE utf8mb4_bin NOT NULL,
  `cpasswd` text COLLATE utf8mb4_bin NOT NULL,
  `quota` int UNSIGNED NOT NULL DEFAULT '1048576000',
  `dtcrea` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `dtupdt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `vmail_users_uk_email` (`email`),
  CONSTRAINT `vmail_users_ibfk_1` FOREIGN KEY (`domain_id`) REFERENCES `vmail_domains` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
DELIMITER $$
CREATE TRIGGER `vmail_users_trg_sha512_new` BEFORE INSERT ON `vmail_users` FOR EACH ROW SET NEW.passwd = TO_BASE64(UNHEX(SHA2(NEW.cpasswd, 512)))
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `vmail_users_trg_sha512_upd` BEFORE UPDATE ON `vmail_users` FOR EACH ROW SET NEW.passwd = TO_BASE64(UNHEX(SHA2(NEW.cpasswd, 512)))
$$
DELIMITER ;

INSERT INTO `vmail_domains` (`name`) VALUES ('toto.com');

INSERT INTO `vmail_users` (`domain_id`, `email`, `cpasswd` ) VALUES (1, 'me@toto.com', 'emailpass');

On ajoute pas la suite un compte système dont le repertoire personnel servira au stockages des différentes boites emails :

groupadd -g 5000 vmail
useradd -u 5000 -g vmail -s /usr/sbin/nologin -d /srv/mail -m vmail

On procède maintenant à l’installation de dovecot :

apt install dovecot-antispam dovecot-managesieved dovecot-sieve dovecot-mysql dovecot-imapd dovecot-lmtpd

On modifie pa la suite le fichier /etc/dovecot/conf.d/10-auth.conf pour avoir la prise en charge de la configuration mysql :

# ...
#!include auth-system.conf.ext
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-static.conf.ext

et le fichier /etc/dovecot/dovecot-sql.conf.ext avec les bon paramètres :

# ...
# Database driver: mysql, pgsql, sqlite
driver = mysql


# 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=127.0.0.1 dbname=vmails user=vmailuser password=vmailSuperPass

# Default password scheme.
#
# List of supported schemes is in
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
#
#default_pass_scheme = MD5
default_pass_scheme = SHA512

# userdb query to retrieve the user information. It can return fields:
#   uid - System UID (overrides mail_uid setting)
#   gid - System GID (overrides mail_gid setting)
#   home - Home directory
#   mail - Mail location (overrides mail_location setting)
#
# None of these are strictly required. If you use a single UID and GID, and
# home or mail directory fits to a template string, you could use userdb static
# instead. For a list of all fields that can be returned, see
# http://wiki2.dovecot.org/UserDatabase/ExtraFields
user_query =  SELECT 5000 as uid, 8 as gid, CONCAT('/srv/mail/vhosts/', SUBSTRING_INDEX(email, '@', -1) ,'/', SUBSTRING_INDEX(email, '@', 1),'/') as home, CONCAT('*:bytes=',quota*100)  AS quota_rule  FROM vmail_users  WHERE email = '%u'

# If you wish to avoid two SQL lookups (passdb + userdb), you can use
# userdb prefetch instead of userdb sql in dovecot.conf. In that case you'll
# also have to return userdb fields in password_query prefixed with "userdb_"
# string. For example:
password_query = SELECT email as user, passwd as password, CONCAT('/srv/mail/vhosts/', SUBSTRING_INDEX(email, '@', -1) ,'/', SUBSTRING_INDEX(email, '@', 1),'/') as userdb_home, 5000 as userdb_uid,  5000 as userdb_gid, CONCAT('*:bytes=',quota*100)  AS userdb_quota_rule  FROM vmail_users WHERE email='%u'

# Query to get a list of all usernames.
iterate_query = SELECT email as user FROM vmail_users

et on fini par ajouter un fichier de configuration /etc/dovecot/conf.d/99-overwrite.conf qui remplacera le reste des paramètres dovecot :

auth_debug = no
auth_debug_passwords=no
auth_default_realm =
auth_failure_delay = 3 secs
auth_mechanisms = login plain
auth_stats = yes
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@
auth_verbose=no
auth_verbose_passwords=plain
config_cache_size = 1 M
debug_log_path =
default_client_limit = 1000
disable_plaintext_auth = yes
last_valid_gid = 0
last_valid_uid = 0
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
#log_path = syslog
log_timestamp = "%b %d %H:%M:%S "
login_access_sockets =
login_greeting = Dovecot ready.
login_log_format = %$: %s
login_log_format_elements = user=<%u> method=%m rip=%r lip=%l mpid=%e %c session=<%{session}>
mail_gid = 8
mail_home =
mail_location = maildir:/srv/mail/vhosts/%d/%n
#mail_plugins = " quota"
mail_uid = 5000
mailbox_idle_check_interval = 30 secs
mailbox_list_index = yes
mailbox_list_index_very_dirty_syncs = no
maildir_broken_filename_sizes = no
maildir_copy_with_hardlinks = yes
maildir_empty_new = yes
maildir_stat_dirs = yes
maildir_very_dirty_syncs = no
managesieve_client_workarounds =
#managesieve_implementation_string = Dovecot Pigeonhole
managesieve_logout_format = bytes=%i/%o
managesieve_max_compile_errors = 5
managesieve_max_line_length = 65536
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext
master_user_separator =
namespace inbox {
        disabled = no
        hidden = no
        ignore_on_failure = no
        inbox = yes
        list = yes
        mailbox Archive {
                special_use = \All
                auto = subscribe
        }
        mailbox Archive {
                special_use = \Archive
                auto = subscribe
        }
        mailbox Drafts {
                special_use = \Drafts
                auto = subscribe
        }
        mailbox Junk {
                special_use = \Junk
                auto = subscribe
        }
        mailbox Sent {
                special_use = \Sent
                auto = subscribe
        }
        mailbox Trash {
                special_use = \Trash
                auto = subscribe
        }
}
passdb {
        args = /etc/dovecot/dovecot-sql.conf.ext
        driver = sql
}
plugin {
        quota = maildir:User quota
        quota_rule = Trash:storage=+100M
        quota_rule2 = SPAM:ignore
        quota_exceeded_message = Storage quota for this account has been exceeded, please try again later.
        quota_warning = storage=90%% quota-warning 90 %u
        quota_warning2 = storage=75%% quota-warning 75 %u
        sieve_default = file:/srv/mail/default.sieve
#        sieve_global = /srv/mail/default.sieve
        sieve_dir = ~/sieve
        sieve = file:~/sieve;active=~/.dovecot.sieve
}
postmaster_address = admin@toto.com
protocols = " imap lmtp sieve"
service auth-worker {
        user = vmail
}
service auth {
        unix_listener /var/spool/postfix/private/auth {
                mode = 0666
                user = postfix
                group = postfix
        }
        unix_listener auth-userdb {
                mode = 0600
                user = vmail
                group = mail
        }
        user = dovecot
}
service imap-login {
        inet_listener imap {
                address = 127.0.0.1
                port = 143
                ssl = no
        }
        inet_listener imaps {
                port = 993
                ssl = yes
        }
}
service lmtp {
        unix_listener /var/spool/postfix/private/dovecot-lmtp {
                mode = 0666
                user = postfix
                group = postfix
        }
}
service managesieve-login {
        inet_listener sieve {
#                address = 127.0.0.1
                port = 4190
#                ssl = no
               ssl = yes
        }
}
shutdown_clients = yes
ssl = yes
ssl_cert = </etc/letsencrypt/live/monhost.toto.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/monhost.toto.com/privkey.pem
ssl_cert_username_field = commonName
ssl_dh = </etc/dovecot/dh.pem
#ssl_dh_parameters_length = 2048
local_name mail.toto.com  {
  ssl_key = </etc/letsencrypt/live/mail.toto.com/privkey.pem
  ssl_cert = </etc/letsencrypt/live/mail.toto.com/fullchain.pem
}
#ssl_cipher_list=ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
ssl_cipher_list = EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS !RC4 !CAMELLIA !SEED
ssl_prefer_server_ciphers = yes
#ssl_protocols = !SSLv2 !SSLv3
#ssl_protocols = TLSv1.1 TLSv1.2 !SSLv2 !SSLv3

syslog_facility = mail

userdb {
   driver = static
   args = uid=vmail gid=mail home=/srv/mail/vhosts/%d/%n
}
verbose_proctitle = yes
verbose_ssl=no

Bien entendu cela suppose que à chaque nouveau domaine/sous-domaine pour lequel on gérera les emails, il faudra pointer le domaine sur le serveur, créer les certificats SSL et ajouter les lignes suivant dans ce fichier :

#...
local_name mail.titi.com  {
  ssl_key = </etc/letsencrypt/live/mail.titi.com/privkey.pem
  ssl_cert = </etc/letsencrypt/live/mail.titi.com/fullchain.pem
}

Ah, il ne faut pas oublier de générer le fichier dhpram avec la commande suivante :

openssl dhparam -out /etc/dovecot/dh.pem 4096

Maintenant on peut passer à l’installation et la configuration de postfix et la génération du fichier dhpram qui lui sera associé :

apt install postfix postfix-mysql postfix-pcre postfix-policyd-spf-python amavis-new
openssl dhparam -out /etc/postfix/dh.pem 2048

On passe alors à la modification du fichier /etc/postfix/main.cf :

# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# The alias databases for local delivery that are updated with "newaliases" or with "sendmail -bi". 
alias_database = hash:/etc/aliases

# The alias databases that are used for local delivery. 
# Specify zero or more "type:name" lookup tables, separated by whitespace or comma. 
# Tables will be searched in the specified order until a match is found. Note: these lookups are recursive.
alias_maps = hash:/etc/aliases

# Optional address that receives a "blind carbon copy" of each message that is received by the Postfix mail system.
#always_bcc = bcc@toto.com

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Whether or not to use the local biff service.
# This service sends "new mail" notifications to users who have requested new mail notification with the UNIX command "biff y". 
biff = no

# Enable interoperability with remote SMTP clients that implement an obsolete version of the AUTH command (RFC 4954). 
# Examples of such clients are MicroSoft Outlook Express version 4 and MicroSoft Exchange version 5.0.
# Specify "broken_sasl_auth_clients = yes" to have Postfix advertise AUTH support in a non-standard way.
broken_sasl_auth_clients = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 3.6 on
# fresh installs.
compatibility_level = 3.6

# The default location of the Postfix main.cf and master.cf configuration files.
config_directory = /etc/postfix

# After the message is queued, send the entire message to the specified transport:destination.
# The transport name specifies the first field of a mail delivery agent definition in master.cf;
# the syntax of the next-hop destination is described in the manual page of the corresponding delivery agent.
#content_filter = amavis:[127.0.0.1]:10024
content_filter = smtp-amavis:[127.0.0.1]:10024

# The time after which the sender receives a copy of the message headers of mail that is still queued. 
delay_warning_time = 4h

# Disable the SMTP VRFY command. This stops some techniques used to harvest email addresses. 
disable_vrfy_command = yes


# The default maximal number of recipients per message delivery.

# Setting this parameter to a value of 1 affects email deliveries as follows:
#   It changes the meaning of the corresponding per-destination concurrency limit, from concurrency of deliveries to the same domain into concurrency of deliveries to the same recipient. 
#Different recipients are delivered in parallel, subject to the process limits specified in master.cf. 
#   It changes the meaning of the corresponding per-destination rate delay, from the delay between deliveries to the same domain into the delay between deliveries to the same recipient. 
#Again, different recipients are delivered in parallel, subject to the process limits specified in master.cf. 
#   It changes the meaning of other corresponding per-destination settings in a similar manner, from settings for delivery to the same domain into settings for delivery to the same recipient. 
#default_destination_recipient_limit = 1
default_destination_recipient_limit = 20000
dovecot_destination_recipient_limit = 1

# Enable support for the original recipient address after an address is rewritten to a different address (for example with aliasing or with canonical mapping). 
# Final delivery : With "enable_original_recipient = yes", the original recipient address is stored in the X-Original-To message header. This header may be used to distinguish between different recipients that share the same mailbox. 
# Recipient deduplication : With "enable_original_recipient = yes", the cleanup(8) daemon performs duplicate recipient elimination based on the content of (original recipient, maybe-rewritten recipient) pairs. Otherwise, the cleanup(8) daemon performs duplicate recipient elimination based only on the maybe-rewritten recipient address. 
#enable_original_recipient = no
enable_original_recipient = yes


# Optional lookup tables for content inspection of primary non-MIME message headers, as specified in the header_checks(5) manual page. 
# Getting rid of unwanted headers. See: https://posluns.com/guides/header-removal/
#header_checks = regexp:/etc/postfix/header_check

# Optional pathname of a mailbox file relative to a local(8) user's home directory. 
# Specify a pathname ending in "/" for qmail-style delivery.
home_mailbox = Maildir/

# The location of Postfix HTML files that describe how to build, configure or operate a specific Postfix subsystem or feature. 
#html_directory = /usr/share/doc/postfix/html

# The network interface addresses that this mail system receives mail on. Specify "all" to receive mail on all network interfaces (default), and "loopback-only" to receive mail on loopback network interfaces only (Postfix version 2.2 and later). The parameter also controls delivery of mail to user@[ip.address]. 
inet_interfaces = all

# The Internet protocols Postfix will attempt to use when making or accepting connections. Specify one or more of "ipv4" or "ipv6", separated by whitespace or commas. The form "all" is equivalent to "ipv4, ipv6" or "ipv4", depending on whether the operating system implements IPv6. 
#inet_protocols = all
inet_protocols = ipv4, ipv6

# The maximal size of any local(8) individual mailbox or maildir file, or zero (no limit). In fact, this limits the size of any file that is written to upon local delivery, including files written by external commands that are executed by the local(8) delivery agent. 
mailbox_size_limit = 0

# Optional message delivery transport that the local(8) delivery agent should use for mailbox delivery to all local recipients, whether or not they are found in the UNIX passwd database. 
#mailbox_transport = lmtp:unix:/var/spool/postfix/private/dovecot-lmtp
mailbox_transport = lmtp:unix:private/dovecot-lmtp

# The maximal time between attempts to deliver a deferred message. 
maximal_backoff_time = 8000s

# Consider a message as undeliverable, when delivery fails with a temporary error, and the time in the queue has reached the maximal_queue_lifetime limit. 
maximal_queue_lifetime = 7d

# The maximal size in bytes of a message, including envelope information. 
message_size_limit=52428800


# The minimal time between attempts to deliver a deferred message; prior to Postfix 2.4 the default value was 1000s. 
minimal_backoff_time = 1000s

# The list of domains that are delivered via the $local_transport mail delivery transport. By default this is the Postfix local(8) delivery agent which looks up all recipients in /etc/passwd and /etc/aliases. The SMTP server validates recipient addresses with $local_recipient_maps and rejects non-existent recipients. See also the local domain class in the ADDRESS_CLASS_README file. 
mydestination = $myhostname, monhost, monhost.toto.com, , localhost
# The internet hostname of this mail system. The default is to use the fully-qualified domain name (FQDN) from gethostname(), or to use the non-FQDN result from gethostname() and append ".$mydomain". $myhostname is used as a default value for many other configuration parameters. 
myhostname = monhost.toto.com

# The list of "trusted" remote SMTP clients that have more privileges than "strangers".
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

# The domain name that locally-posted mail appears to come from, and that locally posted mail is delivered to. The default, $myhostname, is adequate for small sites. If you run a domain with multiple machines, you should (1) change this to $mydomain and (2) set up a domain-wide alias database that aliases each user to user@that.users.mailhost. 
#myorigin = $mydomain
#myorigin = /etc/mailname
myorigin = $myhostname

# added by policy-spf
policy-spf_time_limit = 3600s

# The lookup tables that the proxymap(8) server is allowed to access for the read-only service. 
proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps

# The location of Postfix README files that describe how to build, configure or operate a specific Postfix subsystem or feature. 
#readme_directory = /usr/share/doc/postfix
readme_directory = no

# Enable or disable recipient validation, built-in content filtering, or address mapping. 
# Typically, these are specified in master.cf as command-line arguments for the smtpd(8), qmqpd(8) or pickup(8) daemons. 
# Specify zero or more of the following options. The options override main.cf settings and are either implemented by smtpd(8), qmqpd(8), or pickup(8) themselves, or they are forwarded to the cleanup server. 
# no_unknown_recipient_checks : Do not try to reject unknown recipients (SMTP server only). This is typically specified AFTER an external content filter. 
# no_address_mappings : Disable canonical address mapping, virtual alias map expansion, address masquerading, and automatic BCC (blind carbon-copy) recipients. This is typically specified BEFORE an external content filter. 
# no_header_body_checks :  Disable header/body_checks. This is typically specified AFTER an external content filter. 
# no_milters :  Disable Milter (mail filter) applications. This is typically specified AFTER an external content filter. 
receive_override_options = no_address_mappings

# The set of characters that can separate a user name from its extension (example: user+foo), or a .forward file name from its extension (example: .forward+foo). Basically, the software tries user+foo and .forward+foo before trying user and .forward. This implementation recognizes one delimiter character and one extension per email address or .forward file name. 
recipient_delimiter = +

# The next-hop destination of non-local mail; overrides non-local domains in recipient addresses. 
# This information is overruled with relay_transport, sender_dependent_default_transport_maps, default_transport, sender_dependent_relayhost_maps and with the transport(5) table.
# On an intranet, specify the organizational domain name. If your internal DNS uses no MX records, specify the name of the intranet gateway host instead. 
relayhost =

# The address type ("ipv6", "ipv4" or "any") that the Postfix SMTP client will try first, when a destination has IPv6 and IPv4 addresses with equal MX preference. 
# This feature has no effect unless the inet_protocols setting enables both IPv4 and IPv6.
# Postfix SMTP client address preference has evolved. With Postfix 2.8 the default is "ipv6"; earlier implementations are hard-coded to prefer IPv6 over IPv4.
# Notes for mail delivery between sites that have both IPv4 and IPv6 connectivity:
#    The setting "smtp_address_preference = ipv6" is unsafe. It can fail to deliver mail when there is an outage that affects IPv6, while the destination is still reachable over IPv4.
#    The setting "smtp_address_preference = any" is safe. With this, mail will eventually be delivered even if there is an outage that affects IPv6 or IPv4, as long as it does not affect both.
smtp_address_preference = ipv4
#smtp_address_preference = any

# The Postfix SMTP client time limit for sending the HELO or EHLO command, and for receiving the initial remote SMTP server response.
smtp_helo_timeout = 60s

# A file containing CA certificates of root CAs trusted to sign either remote SMTP server certificates or intermediate CA certificates.
# These are loaded into memory before the smtp(8) client enters the chroot jail.
#smtp_tls_CAfile = /etc/letsencrypt/live/monhost.toto.com/chain.pem

# Try to detect a mail hijacking attack based on a TLS protocol vulnerability (CVE-2009-3555), where an attacker prepends malicious HELO, MAIL, RCPT, DATA commands to a Postfix SMTP client TLS session. 
# The attack would succeed with non-Postfix SMTP servers that reply to the malicious HELO, MAIL, RCPT, DATA commands after negotiating the Postfix SMTP client TLS session. 
smtp_tls_block_early_mail_reply = yes

# File with the Postfix SMTP client RSA certificate in PEM format.
# This file may also contain the Postfix SMTP client private RSA key, and these may be the same as the Postfix SMTP server RSA certificate and key file. 
smtp_tls_cert_file = /etc/letsencrypt/live/monhost.toto.com/fullchain.pem
# List of ciphers or cipher types to exclude from the Postfix SMTP client cipher list at all TLS security levels.
# This is not an OpenSSL cipherlist, it is a simple list separated by whitespace and/or commas. 
# The elements are a single cipher, or one or more "+" separated cipher properties, in which case only ciphers matching all the properties are excluded. 
#smtp_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CDC3-SHA, KRB5-DE5, CBC3-SHA
#smtp_tls_exclude_ciphers = RC4 aNULL eNULL LOW 3DES MD5 EXP PSK SRP DSS ADH CAMELLIA SEED DES MEDIUM EXPORT aDSS kECDHe kECDHr kDHd kDHr IDEA RC2 aNULL


smtp_tls_ciphers = high

#  File with the Postfix SMTP client RSA private key in PEM format. This file may be combined with the Postfix SMTP client RSA certificate file specified with $smtp_tls_cert_file.
# The private key must be accessible without a pass-phrase, i.e. it must not be encrypted. 
# File permissions should grant read-only access to the system superuser account ("root"), and no access to anyone else. 
smtp_tls_key_file = /etc/letsencrypt/live/monhost.toto.com/privkey.pem
# Enable additional Postfix SMTP client logging of TLS activity. Each logging level also includes the information that is logged at a lower logging level.
#    0 Disable logging of TLS activity. 
#    1 Log only a summary message on TLS handshake completion — no logging of remote SMTP server certificate trust-chain verification errors if server certificate verification is not required.
#    2 Also log levels during TLS negotiation. 
#    3 Also log hexadecimal and ASCII dump of TLS negotiation process. 
#    4 Also log hexadecimal and ASCII dump of complete transmission after STARTTLS. 
smtp_tls_loglevel = 1

# The minimum TLS cipher grade that the Postfix SMTP client will use with mandatory TLS encryption. The default value "medium" is suitable for most destinations with which you may want to enforce TLS, and is beyond the reach of today's cryptanalytic methods. See smtp_tls_policy_maps for information on how to configure ciphers on a per-destination basis. 
#smtp_tls_mandatory_ciphers = medium

# Additional list of ciphers or cipher types to exclude from the Postfix SMTP client cipher list at mandatory TLS security levels. This list works in addition to the exclusions listed with smtp_tls_exclude_ciphers (see there for syntax details). 
#smtp_tls_mandatory_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CDC3-SHA, KRB5-DE5, CBC3-SHA

# List of SSL/TLS protocols that the Postfix SMTP client will use with mandatory TLS encryption. In main.cf the values are separated by whitespace, commas or colons.
#smtp_tls_mandatory_protocols = !SSLv2,!SSLv3
smtp_tls_mandatory_ciphers = high

# Log the hostname of a remote SMTP server that offers STARTTLS, when TLS is not already enabled for that server. 
smtp_tls_note_starttls_offer = yes

# Optional lookup tables with the Postfix SMTP client TLS security policy by next-hop destination; when a non-empty value is specified, this overrides the obsolete smtp_tls_per_site parameter. See TLS_README for a more detailed discussion of TLS security levels. 
#smtp_tls_policy_maps = may

# List of TLS protocols that the Postfix SMTP client will exclude or include with opportunistic TLS encryption. The default value is "!SSLv2, !SSLv3" for Postfix releases after the middle of 2015, "!SSLv2" for older releases.
smtp_tls_protocols = !TLSv1, !SSLv2, !SSLv3

# The default SMTP TLS security level for the Postfix SMTP client; when a non-empty value is specified, this overrides the obsolete parameters smtp_use_tls, smtp_enforce_tls, and smtp_tls_enforce_peername. 
smtp_tls_security_level = may
# Name of the file containing the optional Postfix SMTP client TLS session cache. Specify a database type that supports enumeration, such as btree or sdbm; there is no need to support concurrent access.
# The file is created if it does not exist. The smtp(8) daemon does not use this parameter directly, rather the cache is implemented indirectly in the tlsmgr(8) daemon.
# This means that per-smtp-instance master.cf overrides of this parameter are not effective.
# Note, that each of the cache databases supported by tlsmgr(8) daemon: $smtpd_tls_session_cache_database, $smtp_tls_session_cache_database
# (and with Postfix 2.3 and later $lmtp_tls_session_cache_database), needs to be stored separately.
# It is not at this time possible to store multiple caches in a single database. 
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# Opportunistic mode: use TLS when a remote SMTP server announces STARTTLS support, otherwise send the mail in the clear.
# Beware: some SMTP servers offer STARTTLS even if it is not configured. With Postfix < 2.3, if the TLS handshake fails, and no other server is available, delivery is deferred and mail stays in the queue.
# If this is a concern for you, use the smtp_tls_per_site feature instead. 
smtp_use_tls = yes

#  The text that follows the 220 status code in the SMTP greeting banner. Some people like to see the mail version advertised. By default, Postfix shows no version.
# You MUST specify $myhostname at the start of the text. This is required by the SMTP protocol. 
smtpd_banner = ESMTP $mail_name
#smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)

# Optional restrictions that the Postfix SMTP server applies in the context of a client connection request.
# See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
#smtpd_client_restrictions = reject_rbl_client zen.spamhaus.org,        reject_rbl_client bl.spamcop.net, permit
smtpd_client_restrictions = permit

# Optional restrictions that the Postfix SMTP server applies in the context of a client connection request.
# See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
smtpd_data_restrictions = reject_unauth_pipelining

# Wait until the RCPT TO command before evaluating $smtpd_client_restrictions, $smtpd_helo_restrictions and $smtpd_sender_restrictions, or wait until the ETRN command before evaluating $smtpd_client_restrictions and $smtpd_helo_restrictions. 
smtpd_delay_reject = yes

# A case insensitive list of EHLO keywords (pipelining, starttls, auth, etc.) that the Postfix SMTP server will not send in the EHLO response to a remote SMTP client. 
#smtpd_discard_ehlo_keyword_address_maps = cidr:/etc/postfix/esmtp_access

# The maximal number of errors a remote SMTP client is allowed to make without delivering mail. The Postfix SMTP server disconnects when the limit is exceeded.
# Normally the default limit is 20, but it changes under overload to just 1. With Postfix 2.5 and earlier, the SMTP server always allows up to 20 errors by default. 
smtpd_hard_error_limit = 12

# Require that a remote SMTP client introduces itself with the HELO or EHLO command before sending the MAIL command or other commands that require EHLO negotiation. 
#smtpd_helo_required = no
smtpd_helo_required = yes

# Optional restrictions that the Postfix SMTP server applies in the context of a client HELO command. See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
# The default is to permit everything. 
#smtpd_helo_restrictions = permit_mynetworks, permit
#smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_helo_hostname , reject_invalid_helo_hostname, permit
#smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit
smtpd_helo_restrictions = permit_mynetworks, permit

# The maximal number of recipients that the Postfix SMTP server accepts per message delivery request. 
smtpd_recipient_limit = 2000

smtpd_recipient_overshoot_limit = 20000

# Optional restrictions that the Postfix SMTP server applies in the context of a client RCPT TO command, after smtpd_relay_restrictions.
# See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
#smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_pipelining, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, reject_unknown_sender_domain, reject_unknown_client, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, check_policy_service unix:private/policy-spf, permit
#smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_pipelining, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, reject_unknown_sender_domain, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, check_policy_service unix:private/policy-spf, permit
#smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_pipelining, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, reject_unknown_sender_domain, check_policy_service unix:private/policy-spf, permit
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_pipelining, reject_unknown_recipient_domain, reject_unauth_destination, reject_unknown_sender_domain, check_policy_service unix:private/policy-spf, permit

# Access restrictions for mail relay control that the Postfix SMTP server applies in the context of the RCPT TO command, before smtpd_recipient_restrictions.
# See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
#smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination
smtpd_relay_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, defer_unauth_destination, check_policy_service unix:private/policy-spf, permit


# Enable SASL authentication in the Postfix SMTP server. By default, the Postfix SMTP server does not use authentication. 
smtpd_sasl_auth_enable = yes

# Report the SASL authenticated user name in the smtpd(8) Received message header. 
smtpd_sasl_authenticated_header = yes

# Implementation-specific information that the Postfix SMTP server passes through to the SASL plug-in implementation that is selected with smtpd_sasl_type.
# Typically this specifies the name of a configuration file or rendezvous point. 
smtpd_sasl_path = private/auth

# Postfix SMTP server SASL security options; as of Postfix 2.3 the list of available features depends on the SASL server implementation that is selected with smtpd_sasl_type. 
smtpd_sasl_security_options = noanonymous

# The SASL plug-in type that the Postfix SMTP server should use for authentication. The available types are listed with the "postconf -a" command.
smtpd_sasl_type = dovecot

# Optional lookup table with the SASL login names that own the sender (MAIL FROM) addresses. 
#smtpd_sender_login_maps = mysql:/etc/postfix/mysql-virtual-mailboxes.cf

# Optional restrictions that the Postfix SMTP server applies in the context of a client MAIL FROM command.
# See SMTPD_ACCESS_README, section "Delayed evaluation of SMTP access restriction lists" for a discussion of evaluation context and time. 
#smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unknown_sender_domain, reject_unauth_pipelining, reject_non_fqdn_sender, reject_unknown_address
#smtpd_sender_restrictions = permit_mynetworks, reject_authenticated_sender_login_mismatch, permit_sasl_authenticated, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_unknown_sender_domain, warn_if_reject reject_unauth_pipelining, warn_if_reject reject_non_fqdn_sender, warn_if_reject reject_unknown_address

# The number of errors a remote SMTP client is allowed to make without delivering mail before the Postfix SMTP server slows down all its responses. 
smtpd_soft_error_limit = 3

# A file containing (PEM format) CA certificates of root CAs trusted to sign either remote SMTP client certificates or intermediate CA certificates.
# These are loaded into memory before the smtpd(8) server enters the chroot jail
#smtpd_tls_CAfile = /etc/letsencrypt/live/monhost.toto.com/chain.pem
#smtpd_tls_CAfile = $smtp_tls_CAfile

# When TLS encryption is optional in the Postfix SMTP server, do not announce or accept SASL authentication over unencrypted connections. 
smtpd_tls_auth_only = yes

# File with the Postfix SMTP server RSA certificate in PEM format. This file may also contain the Postfix SMTP server private RSA key. 
#smtpd_tls_cert_file = /etc/letsencrypt/live/monhost.toto.com/fullchain.pem
smtpd_tls_cert_file = $smtp_tls_cert_file

smtpd_tls_ciphers = high

# ---------------------------------
# TLS Updates relating to Logjam SSL attacks. See: https://weakdh.org/sysadmin.html
# ---------------------------------
# File with DH parameters that the Postfix SMTP server should use with non-export EDH ciphers. 
smtpd_tls_dh1024_param_file = /etc/postfix/dh.pem
# ---------------------------------
# TLS Updates relating to Logjam SSL attacks. See: https://weakdh.org/sysadmin.html
# ---------------------------------
# List of ciphers or cipher types to exclude from the SMTP server cipher list at all TLS security levels.
# Excluding valid ciphers can create interoperability problems.
# DO NOT exclude ciphers unless it is essential to do so. This is not an OpenSSL cipherlist; it is a simple list separated by whitespace and/or commas.
# The elements are a single cipher, or one or more "+" separated cipher properties, in which case only ciphers matching all the properties are excluded. 
#smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CDC3-SHA, KRB5-DE5, CBC3-SHA
#smtpd_tls_exclude_ciphers = RC4 aNULL eNULL LOW 3DES MD5 EXP PSK SRP DSS ADH CAMELLIA SEED DES MEDIUM EXPORT aDSS kECDHe kECDHr kDHd kDHr IDEA RC2 aNULL

#smtpd_tls_chain_files = /etc/letsencrypt/live/monhost.toto.com/fullchain.pem

tls_server_sni_maps = hash:/etc/postfix/vmail_ssl.map

# File with the Postfix SMTP server RSA private key in PEM format. This file may be combined with the Postfix SMTP server RSA certificate file specified with $smtpd_tls_cert_file.
# The private key must be accessible without a pass-phrase, i.e. it must not be encrypted.
# File permissions should grant read-only access to the system superuser account ("root"), and no access to anyone else. 
#smtpd_tls_key_file = /etc/letsencrypt/live/monhost.toto.com/privkey.pem
smtpd_tls_key_file = $smtp_tls_key_file

# Enable additional Postfix SMTP server logging of TLS activity. Each logging level also includes the information that is logged at a lower logging level. 
#   0 Disable logging of TLS activity. 
#   1 Log only a summary message on TLS handshake completion — no logging of client certificate trust-chain verification errors if client certificate verification is not required. With Postfix 2.8 and earlier, log the summary message, peer certificate summary information and unconditionally log trust-chain verification errors. 
#   2 Also log levels during TLS negotiation. 
#   3 Also log hexadecimal and ASCII dump of TLS negotiation process. 
#   4 Also log hexadecimal and ASCII dump of complete transmission after STARTTLS. 
smtpd_tls_loglevel = 0

# The SSL/TLS protocols accepted by the Postfix SMTP server with mandatory TLS encryption. If the list is empty, the server supports all available SSL/TLS protocol versions.
# A non-empty value is a list of protocol names separated by whitespace, commas or colons. The supported protocol names are "SSLv2", "SSLv3" and "TLSv1", and are not case sensitive.
# The default value is "!SSLv2, !SSLv3" for Postfix releases after the middle of 2015, "!SSLv2" for older releases. 
#smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_mandatory_protocols = !TLSv1, !SSLv2, !SSLv3

#  List of TLS protocols that the Postfix SMTP server will exclude or include with opportunistic TLS encryption.
# The default value is "!SSLv2, !SSLv3" for Postfix releases after the middle of 2015, empty for older releases allowing all protocols to be used with opportunistic TLS.
# A non-empty value is a list of protocol names separated by whitespace, commas or colons. The supported protocol names are "SSLv2", "SSLv3" and "TLSv1", and are not case sensitive. 
smtpd_tls_protocols = !TLSv1, !SSLv2, !SSLv3

# Request that the Postfix SMTP server produces Received: message headers that include information about the protocol and cipher used, as well as the remote SMTP client CommonName and client certificate issuer CommonName.
# This is disabled by default, as the information may be modified in transit through other mail servers. Only information that was recorded by the final destination can be trusted. 
#smtpd_tls_received_header = yes

# The SMTP TLS security level for the Postfix SMTP server; when a non-empty value is specified, this overrides the obsolete parameters smtpd_use_tls and smtpd_enforce_tls.
# This parameter is ignored with "smtpd_tls_wrappermode = yes". 
#smtpd_tls_security_level = encrypt
smtpd_tls_security_level = may

# Name of the file containing the optional Postfix SMTP server TLS session cache.
# Specify a database type that supports enumeration, such as btree or sdbm; there is no need to support concurrent access.
# The file is created if it does not exist.
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache

# The expiration time of Postfix SMTP server TLS session cache information. A cache cleanup is performed periodically every $smtpd_tls_session_cache_timeout seconds.
# As with $smtpd_tls_session_cache_database, this parameter is implemented in the tlsmgr(8) daemon and therefore per-smtpd-instance master.cf overrides are not possible. 
smtpd_tls_session_cache_timeout = 3600s

smtpd_use_tls = yes

# The external entropy source for the in-memory tlsmgr(8) pseudo random number generator (PRNG) pool. Be sure to specify a non-blocking source.
# If this source is not a regular file, the entropy source type must be prepended: egd:/path/to/egd_socket for a source with EGD compatible socket interface, or dev:/path/to/device for a device file.
# Note: on OpenBSD systems specify /dev/arandom when /dev/urandom gives timeout errors. 
tls_random_source = dev:/dev/urandom

# Optional lookup tables with mappings from recipient address to (message delivery transport, next-hop destination). See transport(5) for details.
transport_maps = mysql:/etc/postfix/mysql-virtual-transport.cf

# The numerical Postfix SMTP server response code when a recipient address is local, and $local_recipient_maps specifies a list of lookup tables that does not match the recipient.
# A recipient address is local when its domain matches $mydestination, $proxy_interfaces or $inet_interfaces. 
unknown_local_recipient_reject_code = 450

# Optional lookup tables that alias specific mail addresses or domains to other local or remote address.
# The table format and lookups are documented in virtual(5). For an overview of Postfix address manipulations see the ADDRESS_REWRITING_README document. 
virtual_alias_maps=mysql:/etc/postfix/mysql-virtual-forwardings.cf,mysql:/etc/postfix/mysql-virtual-forwardings-self.cf

# Lookup tables with the per-recipient group ID for virtual(8) mailbox delivery. 
# This parameter is specific to the virtual(8) delivery agent. It does not apply when mail is delivered with a different mail delivery program. 
virtual_gid_maps = static:8

# A prefix that the virtual(8) delivery agent prepends to all pathname results from $virtual_mailbox_maps table lookups.
# This is a safety measure to ensure that an out of control map doesn't litter the file system with mailboxes. While virtual_mailbox_base could be set to "/", this setting isn't recommended.
# This parameter is specific to the virtual(8) delivery agent. It does not apply when mail is delivered with a different mail delivery program. 
virtual_mailbox_base = /srv/mail/vhosts

# Postfix is final destination for the specified list of domains; mail is delivered via the $virtual_transport mail delivery transport.
# By default this is the Postfix virtual(8) delivery agent. The SMTP server validates recipient addresses with $virtual_mailbox_maps and rejects mail for non-existent recipients.
# See also the virtual mailbox domain class in the ADDRESS_CLASS_README file. 
virtual_mailbox_domains=mysql:/etc/postfix/mysql-virtual-domains.cf

# The maximal size in bytes of an individual virtual(8) mailbox or maildir file, or zero (no limit).
# This parameter is specific to the virtual(8) delivery agent. It does not apply when mail is delivered with a different mail delivery program.
virtual_mailbox_limit = 0

# not used anymore
#virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql-virtual-quota.cf

# not used anymore
#virtual_mailbox_limit_override = yes

# Optional lookup tables with all valid addresses in the domains that match $virtual_mailbox_domains. 
virtual_mailbox_maps=mysql:/etc/postfix/mysql-virtual-mailboxes.cf
# not used anymore
#virtual_maildir_extended = yes

# not used anymore
#virtual_maildir_limit_message = "The user you are trying to reach is over quota."

# not used anymore
#virtual_overquota_bounce = yes

# The default mail delivery transport and next-hop destination for final delivery to domains listed with $virtual_mailbox_domains. This information can be overruled with the transport(5) table. 
#virtual_transport = lmtp:unix:/var/spool/postfix/private/dovecot-lmtp
virtual_transport = lmtp:unix:private/dovecot-lmtp

# Lookup tables with the per-recipient user ID that the virtual(8) delivery agent uses while writing to the recipient's mailbox.
# This parameter is specific to the virtual(8) delivery agent. It does not apply when mail is delivered with a different mail delivery program. 
virtual_uid_maps = static:5000

et du fichier /etc/postfix/master.cf :

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
# Choose one: enable submission for loopback clients only, or for any client.
#127.0.0.1:submission inet n -   y       -       -       smtpd
#submission inet n       -       y       -       -       smtpd
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_tls_auth_only=yes
#  -o smtpd_reject_unlisted_recipient=no
#     Instead of specifying complex smtpd_<xxx>_restrictions here,
#     specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions"
#     here, and specify mua_<xxx>_restrictions in main.cf (where
#     "<xxx>" is "client", "helo", "sender", "relay", or "recipient").
#  -o smtpd_client_restrictions=
#  -o smtpd_helo_restrictions=
#  -o smtpd_sender_restrictions=
#  -o smtpd_relay_restrictions=
#  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes  
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
  -o smtpd_tls_auth_only=yes
  -o smtpd_client_restrictions=permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination,reject
  -o smtpd_sasl_security_options=noanonymous,noplaintext
  -o smtpd_sasl_tls_security_options=noanonymous
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
# Choose one: enable submissions for loopback clients only, or for any client.
#127.0.0.1:submissions inet n  -       y       -       -       smtpd
#submissions     inet  n       -       y       -       -       smtpd
#  -o syslog_name=postfix/submissions
#  -o smtpd_tls_wrappermode=yes 
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#     Instead of specifying complex smtpd_<xxx>_restrictions here,
#     specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions"
#     here, and specify mua_<xxx>_restrictions in main.cf (where
#     "<xxx>" is "client", "helo", "sender", "relay", or "recipient").
#  -o smtpd_client_restrictions=
#  -o smtpd_helo_restrictions=
#  -o smtpd_sender_restrictions=
#  -o smtpd_relay_restrictions=
#  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
        -o syslog_name=postfix/$service_name
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
postlog   unix-dgram n  -       n       -       1       postlogd
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRXhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  flags=DRX user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FRX user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py ${nexthop} ${user}
# The next two entries integrate with Amavis for anti-virus/spam checks.
smtp-amavis unix    -       -       y       -       3       smtp
  -o smtp_data_done_timeout=1200
  -o smtp_send_xforward_command=yes
  -o disable_dns_lookups=yes
  -o max_use=20
127.0.0.1:10025 inet    n       -       y       -       -       smtpd
  -o content_filter=
  -o local_header_rewrite_clients=
  -o local_recipient_maps=
  -o mynetworks=127.0.0.0/8
  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters
  -o relay_recipient_maps=
  -o smtpd_client_connection_count_limit=0
  -o smtpd_client_connection_rate_limit=0
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_data_restrictions=reject_unauth_pipelining
  -o smtpd_delay_reject=no
  -o smtpd_end_of_data_restrictions=
  -o smtpd_error_sleep_time=0
  -o smtpd_hard_error_limit=1000
  -o smtpd_helo_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o smtpd_restriction_classes=
  -o smtpd_sender_restrictions=
  -o smtpd_soft_error_limit=1001
#  -o smtpd_tls_security_level=none

# Integration with Dovecot - hand mail over to it for local delivery, and
# # run the process under the vmail user and mail group.
dovecot      unix   -        n      n       -       -   pipe
  flags=DRhu user=vmail:mail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${recipient}

# Integration with the SPF check package.
policy-spf unix    -       n       n       -       -     spawn user=nobody argv=/usr/bin/policyd-spf

l’authentification sur postfix et la distribution se font donc via dovecot, mais il nous faudra tout de mème ajouter le fichier /etc/postfix/mysql-virtual-domains.cf pour les domaines :

user = vmailuser
hosts = 127.0.0.1
dbname = vmails
password = vmailSuperPass
query = SELECT name FROM vmail_domains WHERE name = '%s'

le fichier /etc/postfix/mysql-virtual-mailboxes.cf pour les boites :

user = vmailuser
hosts = 127.0.0.1
dbname = vmails
password = vmailSuperPass
query = SELECT CONCAT(SUBSTRING_INDEX(email, '@', -1),'/',SUBSTRING_INDEX(email, '@', 1),'/') FROM vmail_users WHERE email = '%s'

le fichier /etc/postfix/mysql-virtual-forwardings.cf pour le forwarding :

user = vmailuser
hosts = 127.0.0.1
dbname = vmails
password = vmailSuperPass
query = SELECT email_dst FROM vmail_aliases WHERE email_src = '%s'

et le fichier /etc/postfix/mysql-virtual-forwardings-self.cf pour le forwarding interne :

user = vmailuser
hosts = 127.0.0.1
dbname = vmails
password = vmailSuperPass
query = SELECT email FROM vmail_users WHERE email = '%s'

Dans le fichier /etc/postfix/main.cf il faudra noter que nous avons indiqué le fichier /etc/postfix/vmail_ssl.map en tant que hash pour les certificats SSL SNI :

monhost.toto.com /etc/letsencrypt/live/monhost.toto.com/privkey.pem /etc/letsencrypt/live/monhost.toto.com/fullchain.pem
toto.com /etc/letsencrypt/live/toto.com/privkey.pem /etc/letsencrypt/live/toto.com/fullchain.pem
mail.toto.com /etc/letsencrypt/live/mail.toto.com/privkey.pem /etc/letsencrypt/live/mail.toto.com/fullchain.pem

Une fois ce fichier créé, et à chaque ajout/suppression de domaine dans le fichier, il faudra executer la commande:

postmap -F hash:/etc/postfix/vmail_ssl.map

qui permettra de regénérer le fichier /etc/postfix/vmail_ssl.map.db avec le hash correspondant.

Voila voila, il ne reste plus que à redémarrer les services dovecot et postfix et à tester l’adresse mail ma@toto.com insérée lors de la création de la base de donnée.

On notera qu’on a installé le service amavis qui pourra/devra être au besoin couplé avec avec d’autres outils tels que spamassassin et clamav.

Une bonne idée par la suite si vous ne voulez pas utiliser un client mail desktop comme outlook ou thunderbird, serait de configurer un webmail (squirrelmail, roundcube, rainloop, mailpile, snappymail, etc..).

Une autre bonne idée serait de configurer un service d’autodiscover/autoconfig pour les clients mail desktop tel que décrit dans le git de SmartlyWay.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.