1. CentOS7. Настройка почтового сервера. Установка системы, postfix, dovecot, postfixadmin

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

Postfix is one of the most popular open-source Mail Transfer Agent (MTA) which route and delivers mails. It is an alternative to Sendmail MTA which comes pre-installed in all version before Centos/RHEL 5. CentOS Postfix installation is a process which requires a lot of precision.

Let us look at Wikipedia’s definition of Postfix, which says,

The main job of the (CentOS) postfix is to relay mails locally or to a destination server outside the network. In order to install postfix and avoid conflicts, you need to remove sendmail if it is already installed.

Before starting you can also refresh your concepts on how email works with Postfix as a reference. This would help you go further with this content.

Step 1: Checking And Removing Sendmail (Required Only If Sendmail Is Installed)

Input: Run the below command to check whether sendmail is installed or not:

rpm -qa | grep sendmail

1. CentOS7. Настройка почтового сервера. Установка системы, postfix, dovecot, postfixadmin

If you didn’t get any output that means you don’t have sendmail installed and you are good to skip to step 2.

If you get an output similar to one shown above, then you need to remove Sendmail using the below command:

sudo yum remove sendmail*

Once you have successfully removed Sendmail, you will be getting an output similar to one shown below:

1. CentOS7. Настройка почтового сервера. Установка системы, postfix, dovecot, postfixadmin

Step 2: Install Postfix

It is always one of the easiest ways to install postfix using yum installer (ideally if you are using Centos/RHEL > 5 postfix comes pre-installed).

You can check if postfix centos 7 is already installed or not using the below command:

rpm -qa | grep postfix

1. CentOS7. Настройка почтового сервера. Установка системы, postfix, dovecot, postfixadmin

You will get the above output, if Postfix is already installed. In case Postfix is not installed, then use the below command to install postfix:

sudo yum install postfix

Keep saying «Yes» to the prompt each time it asks. Once all the components are downloaded, you will have the postfix centos 7 installed successfully.

Step 3: Configure Postfix.

We need to edit /etc/postfix/main.cf file.

vim /etc/postfix/main.cf

Make changes according to the below steps.

Note: Mostly you will find the line which needs to be changed on line 67.

Add hostname to the file by unhashing and editing at line no 75

myhostname = smtp.example.local

Uncomment and set domain name at line no 83

mydomain = example.local

Uncomment line no 99

myorigin = $mydomain

Uncomment and Set ipv4 at line no 113

inet_interfaces = all

edit line no 119 to all

inet_protocols = all

Comment at line no 164

mydestination = $myhostname, localhost.$mydomain, localhost,

Uncomment and add IP range at line no 264

mynetworks = 192.168.1.0/24, 127.0.0.0/8

Uncomment at line no 419

home_mailbox = Maildir/

save and exit the file.

Enable the service using the below command

systemctl enable postfix

Start/restart the postfix service.

systemctl restart postfix

once you have restarted postfix need check the status of the service using below command:

systemctl status postfix 
OR 
service postfix status
[[email protected] ~]# service postfix status
Redirecting to /bin/systemctl status postfix.service
● postfix.service - Postfix Mail Transport Agent
Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2019-08-04 18:02:45 IST; 51min ago
Main PID: 4501 (master)
CGroup: /system.slice/postfix.service
├─ 4501 /usr/libexec/postfix/master -w
├─ 4506 pickup -l -t unix -u
├─ 4507 qmgr -l -t unix -u
├─15652 smtpd -n smtp -t inet -u -s 2
├─15653 proxymap -t unix -u
└─15654 anvil -l -t unix -u

Aug 04 18:02:08 nl587 systemd[1]: Starting Postfix Mail Transport Agent...

Step 4: Testing Postfix Server

useradd postfixtester
passwd postfixtester
telnet localhost smtp

Once you have successfully done with the configuration you get the following output
[[email protected] ~]# telnet localhost smtp
Trying ::1…
Connected to localhost.
Escape character is '^]'.
220 smtp.example.local ESMTP Postfix

Start your transaction writing below command.

ehlo localhost
250-smtp.example.local
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

Once you get 250 DSN you can sendmail.

Case 1: Successful Test

mail from:<postfixtester>
250 2.1.0 Ok [success output]
# rcpt to:<postfixtester>
250 2.1.5 Ok [success output]
# data # type this to pass input of email body
354 End data with <CR><LF>.<CR><LF> [success output ]
This is test mail from your local host server #mail body
. # dot(.) for completing the mail body
250 2.0.0 Ok: queued as E2R572042D75 [success output]
quit # quit from the telnet command prompt
221 2.0.0 Bye
Connection closed by foreign host.

Case 2: Failed Testcase

mail from:<postfixtester>
250 2.1.0 Ok [success output]
# rcpt to:<postfixtester>
454 4.7.1 <postfixtester>: Relay access denied [failure point]
ls /home/postfixtester/Maildir/new/
1336588056.Vfe01I786e3e7M938078.smtp.example.local
cat /home/postfixtester/Maildir/new/1336588056.Vfe01I786e3e7M938078.smtp.example.local
Return-Path: <[email protected]>
X-Original-To: postfixtester
Delivered-To: [email protected]
Received: from localhost (localhost [IPv6:::1])
by smtp.example.local (Postfix) with ESMTP id E2R572042D75
for <postfixtester>; Sun, o4 Aug 2019 17:42:36 +0530 (IST)
Message-Id: <[email protected]>
Date: Sun, 04 Aug 2019 17:42:36 +0530 (IST)
From: [email protected]

This is test mail from your localhost server.

Finally! You have postfix installed and emails getting sent! You are all set to use your server as your private SMTP server to send emails.

  • Установка PostfixAdmin
  • Установка postfix
  • Установка dovecot
  • Запуск сервисов
  • Проверка работоспособности SMTP
  • Настройка firewall
  • Настройка FetchMail

этой ссылке

Установка PostfixAdmin

$ wget http://sourceforge.net/projects/postfixadmin/files/latest/download?source=files -O postfixadmin.tar.gz
$ tar zxvf postfixadmin.tar.gz --no-same-owner --no-same-permissions --directory=/usr/share
$ rm -f postfixadmin.tar.gz
$ ln -s /usr/share/postfixadmin-2.92 /usr/share/postfixadmin
$ chcon -u system_u /usr/share/postfixadmin* -R
$ mkdir /usr/share/doc/postfixadmin-2.92
$ chcon -u system_u /usr/share/doc/postfixadmin-2.92
$ mv /usr/share/postfixadmin/{ADDITIONS,DOCUMENTS,VIRTUAL_VACATION} /usr/share/doc/postfixadmin-2.92
$ rm -rf /usr/share/postfixadmin/debian
$ chcon -t httpd_sys_rw_content_t /usr/share/postfixadmin/templates_c
$ chown root:apache /usr/share/postfixadmin/templates_c
$ chmod g+w /usr/share/postfixadmin/templates_c
$ mkdir /etc/postfixadmin
$ touch /etc/postfixadmin/config.local.php
$ chown root:apache /etc/postfixadmin/config.local.php
$ chmod 0640 /etc/postfixadmin/config.local.php
$ chcon -u system_u /etc/postfixadmin -R
$ chcon -t httpd_sys_content_t /etc/postfixadmin/config.local.php
$ ln -s /etc/postfixadmin/config.local.php /usr/share/postfixadmin/
$ chcon -u system_u /usr/share/postfixadmin/config.local.php -R

Теперь создадим в MySQL базу данных, в которой будет храниться информация о почтовых пользователях:

$ mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 5.5.40-MariaDB MariaDB Server

Copyright (c) 2000, 2014, Oracle, Monty Program Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CREATE DATABASE `%VMailDB%` DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> CREATE USER '%VMailUser%'@'localhost' IDENTIFIED BY '%VMailPassWord%';
Query OK, 0 rows affected (0.03 sec)

MariaDB [(none)]> GRANT ALL PRIVILEGES ON `%VMailDB%`.* TO '%VMailUser%'@'localhost';
Query OK, 0 rows affected (0.03 sec)

MariaDB [(none)]> \q
Bye

$ nano -w /etc/postfixadmin/config.local.php
<?php
$CONF['configured'] = true;
$CONF['setup_password'] = 'changeme';
$CONF['default_language'] = 'en';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = '%VMailUser%';
$CONF['database_password'] = '%VMailPassWord%';
$CONF['database_name'] = '%VMailDB%';
$CONF['admin_email'] = 'postmaster@example.com';
$CONF['page_size'] = '50';
$CONF['default_aliases'] = array (
    'MAILER-DAEMON' => 'postmaster@example.com',
    'abuse' => 'postmaster@example.com',
    'postmaster' => 'hostmaster@example.com',
    'webmaster' => 'hostmaster@example.com',
    'hostmaster' => 'root@example.com',
    'root' => 'admin@example.com'
);
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
$CONF['transport'] = 'YES';
$CONF['transport_options'] = array (
    'dovecot',  // for virtual accounts
    'virtual',  // for virtual accounts
    'local',    // for system accounts
    'relay'     // for backup mx
);
$CONF['transport_default'] = 'dovecot';
$CONF['vacation'] = 'NO';
$CONF['vacation_control'] = 'NO';
$CONF['vacation_control_admin'] = 'NO';
$CONF['backup'] = 'YES';
$CONF['sendmail'] = 'YES';
$CONF['logging'] = 'YES';
$CONF['fetchmail'] = 'YES';
$CONF['fetchmail_extra_options'] = 'YES';
$CONF['footer_text'] = 'Return to mail.example.com';
$CONF['footer_link'] = 'http://mail.example.com';
$CONF['used_quotas'] = 'YES';
$CONF['new_quota_table'] = 'YES';
$ nano -w /etc/httpd/conf.d/postfixadmin.conf
# postfixadmin - Web based Management tool created for Postfix.
# 
# Allows only localhost by default
#
# But allowing postfixadmin to anyone other than localhost should be considered
# dangerous unless properly secured by SSL

Alias /postfixadmin /usr/share/postfixadmin

<Directory /usr/share/postfixadmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       Require ip 127.0.0.1
       Require ip ::1
       Require ip 192.168.0.0/16
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
     Allow from 192.168.0.0/16
   </IfModule>
</Directory>
$ chcon -u system_u /etc/httpd/conf.d/postfixadmin.conf
$ systemctl reload httpd.service
$ nano -w /etc/postfixadmin/config.local.php
$CONF['setup_password'] = 'd2aec49ec9b65d5e606ea7ddcdb78d3a:831aa5735816eb6480232a93e859a1de84aec174';

https://mail.example.com/postfixadmin/setup.php

  • Для начала исправим кодировку в таблицах MySQL:
    $ echo "ALTER DATABASE \`%VMailDB%\` CHARACTER SET utf8;" >temp.txt
    $ echo "ALTER TABLE \`%VMailDB%\`.\`quota\` DROP PRIMARY KEY, ADD PRIMARY KEY (`username`) COMMENT '';" >>temp.txt
    $ mysql -u root -p --database=%VMailDB% -B -N -e "SHOW TABLES" | awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' >>temp.txt
    $ mysql -u root -p --database=%VMailDB% <temp.txt
    $ rm -f temp.txt
    
  • А теперь исправим php-скрипты PostfixAdmin для правильной работы с кодировкой utf-8:
    Исправить нужно все вызовы функции htmlentities в каталогах /usr/share/postfixadmin и /usr/share/postfixadmin/templates, нужно добавить 2 аргумента |, ENT_QUOTES, 'UTF-8'|.

  • В файле fetchmail.php дважды выполняется функция escape_string, поэтому слеши сохраняются в MySQL.
  • $ nano -w /usr/share/postfixadmin/fetchmail.php
    #		$formvars[$key]= escape_string( function_exists($func) ?$func($val) :$val);
    		$formvars[$key]= function_exists($func) ?$func($val) :$val;
    

Установка postfix

Для начала определимся где будут физически находиться почтовые ящики пользователей. Если планируется их оставить в дефолтной папке – пропускаем этот пункт. У меня почта физически лежит на специальном разделе, который примонтирован в /srv. Для того чтобы сделать так же – монтируем раздел и выполняем следующее:

Читайте также:  Понимание автоответчиков: подробное руководство

$ mv /var/spool/mail/ /srv/
$ ln -s /srv/mail/ /var/spool/mail
$ chcon -u system_u -t mail_spool_t /var/spool/mail -R

В CentOS 7 по умолчанию устанавливается postfix, а в предыдущих версиях CentOS нужно было выполнить команду:

$ yum -y install postfix && yum -y remove sendmail

Отредактируем основной конфигурационный файл postfix:

$ nano -w /etc/postfix/main.cf
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
inet_protocols = ipv4
mynetworks_style = host
mynetworks = $config_directory/mynetworks
smtpd_banner = $myhostname ESMTP $mail_name

# ---------------------- VIRTUAL DOMAINS START ----------------------
virtual_alias_maps		= proxy:mysql:$config_directory/sql/virtual_alias_maps.cf
virtual_mailbox_domains		= proxy:mysql:$config_directory/sql/virtual_domains_maps.cf
virtual_mailbox_maps		= proxy:mysql:$config_directory/sql/virtual_mailbox_maps.cf
#virtual_mailbox_limit_maps	= proxy:mysql:$config_directory/sql/virtual_mailbox_limit_maps.cf
virtual_mailbox_base		= /var/spool/mail
virtual_uid_maps		= static:8
virtual_gid_maps		= static:12
mailbox_size_limit		= 104857600
message_size_limit		= 104857600
relay_domains			= proxy:mysql:$config_directory/sql/relay_domains.cf
relay_recipient_maps		= proxy:mysql:$config_directory/sql/relay_recipient_maps.cf
transport_maps			= proxy:mysql:$config_directory/sql/transport_maps.cf
#transport_maps			= hash:$config_directory/transport
#virtual_transport		= dovecot
dovecot_destination_recipient_limit = 1
# ----------------------- VIRTUAL DOMAINS END -----------------------

# ------------------------- SASL PART START -------------------------
broken_sasl_auth_clients	= yes
smtpd_helo_required		= yes
smtpd_client_restrictions	= permit_sasl_authenticated
smtpd_sender_restrictions	= permit_sasl_authenticated
smtpd_sasl_auth_enable		= yes
smtpd_sasl_security_options	= noanonymous
smtpd_sasl_tls_security_options	= $smtpd_sasl_security_options
smtpd_sasl_type			= dovecot
# Can be an absolute path, or relative to $queue_directory
smtpd_sasl_path			= private/auth
# -------------------------- SASL PART END --------------------------

# -------------------------- TLS PART START -------------------------
smtpd_use_tls			= yes
smtpd_tls_auth_only		= yes
smtpd_tls_CAfile		= /etc/pki/tls/certs/sub.class2.server.ca.pem
smtpd_tls_cert_file		= /etc/pki/tls/certs/mail.example.com.crt
smtpd_tls_key_file		= /etc/pki/tls/private/mail.example.com.key
smtpd_tls_mandatory_protocols	= !SSLv2,!SSLv3
smtpd_tls_received_header	= yes
smtpd_tls_loglevel		= 1
tls_random_source		= dev:/dev/urandom
# --------------------------- TLS PART END --------------------------

# ------------------ SMTPD RESTRICTIONS PART START ------------------
disable_vrfy_command		= yes
non_fqdn_reject_code		= 450
invalid_hostname_reject_code	= 450
maps_rbl_reject_code		= 450
unverified_sender_reject_code	= 550
#header_checks			= pcre:$config_directory/header_checks
#body_checks			= pcre:$config_directory/body_checks
#warning: the restrictions reject_unknown_(sender|recipient)_domain
#will trigger if your DNS becomes unavailable
smtpd_recipient_restrictions =
	permit_mynetworks
	permit_sasl_authenticated
	reject_unauth_destination
	reject_invalid_helo_hostname
	warn_if_reject reject_non_fqdn_helo_hostname
	warn_if_reject reject_unknown_helo_hostname
	warn_if_reject reject_unknown_client
	reject_non_fqdn_sender
	reject_non_fqdn_recipient
	reject_unknown_sender_domain
	reject_unknown_recipient_domain
	check_client_access hash:$config_directory/rbl_override
	reject_rbl_client zen.spamhaus.org
	reject_rbl_client bl.spamcop.net
	reject_rbl_client dnsbl.sorbs.net=127.0.0.2
	reject_rbl_client dnsbl.sorbs.net=127.0.0.3
	reject_rbl_client dnsbl.sorbs.net=127.0.0.4
	reject_rbl_client dnsbl.sorbs.net=127.0.0.5
	reject_rbl_client dnsbl.sorbs.net=127.0.0.7
	reject_rbl_client dnsbl.sorbs.net=127.0.0.9
	reject_rbl_client dnsbl.sorbs.net=127.0.0.11
	reject_rbl_client dnsbl.sorbs.net=127.0.0.12
	permit

smtpd_data_restrictions =
	permit_mynetworks,
	reject_unauth_pipelining,
	reject_multi_recipient_bounce,
	permit
# ------------------- SMTPD RESTRICTIONS PART END --------------------

Создадим список исключений из RBL-списка. Для того чтобы иметь возможность получать почту с этих серверов даже если они по какой-то причине попадут в RBL-список.

$ nano -w /etc/postfix/rbl_override
mail.example.com	OK
1.2.3.4			OK
mail.example.org	OK
2.3.4.5			OK
$ postmap /etc/postfix/rbl_override
$ chcon -u system_u /etc/postfix/rbl_override*

Создадим список хостов, которые смогут без авторизации отправлять почту через наш почтовый сервис (очень опасная штука, на моей памяти реально такое понадобилось только для одного блейд-центра, который не умел авторизовываться, всё остальное железо спокойно авторизуется на smtp и без проблем отправляет почту).

$ nano -w /etc/postfix/mynetworks
# localhost
127.0.0.0/8
# sw01.example.com
192.168.255.123/32
$ chcon -u system_u /etc/postfix/mynetworks

Настроим dovecot в качестве почтового транспорта:

$ nano -w /etc/postfix/master.cf
smtps     inet  n       -       n       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=mail:mail argv=/usr/libexec/dovecot/deliver -d ${recipient}

Создадим дополнительные конфигурационные файлы с данными для подключения к SQL-таблицам с данными о наших доменах и пользователях:

$ mkdir /etc/postfix/sql

$ nano -w /etc/postfix/sql/virtual_alias_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= alias
select_field	= goto
where_field	= address
additional_conditions = AND active = '1'

$ nano -w /etc/postfix/sql/virtual_domains_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= domain
select_field	= description
where_field	= domain
additional_conditions = AND backupmx = '0' AND active = '1'

$ nano -w /etc/postfix/sql/virtual_mailbox_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= mailbox
select_field	= maildir
where_field	= username
additional_conditions = AND active = '1'

$ nano -w /etc/postfix/sql/virtual_mailbox_limit_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= mailbox
select_field	= quota
where_field	= username
additional_conditions = AND active = '1'

$ nano -w /etc/postfix/sql/relay_domains.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= domain
select_field	= domain
where_field	= domain
additional_conditions = AND backupmx = '1' AND active = '1'

$ nano -w /etc/postfix/sql/relay_recipient_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= alias
select_field	= goto
where_field	= address
additional_conditions = AND active = '1'

$ nano -w /etc/postfix/sql/transport_maps.cf
hosts		= localhost
dbname		= %VMailDB%
user		= %VMailUser%
password	= %VMailPassWord%
table		= domain
select_field	= transport
where_field	= domain
additional_conditions = AND active = '1'

$ chown root:postfix /etc/postfix/sql/ -R
$ chcon -u system_u /etc/postfix/sql -R
$ chmod 0640 /etc/postfix/sql/*.cf
$ chmod 0750 /etc/postfix/sql/
$ newaliases

Postfix настроен, но запускать его не будем, пока не настроим dovecot.

Установка dovecot

Установим сервер dovecot и сопутствующие плагины для работы с базой MySQL и для работы с Sieve-фильтрами:

$ yum -y install dovecot dovecot-mysql dovecot-pigeonhole

$ nano -w /etc/dovecot/dovecot.conf
protocols = imap

$ nano -w /etc/dovecot/conf.d/10-auth.conf
#!include auth-system.conf.ext
!include auth-sql.conf.ext

$ nano -w /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:/var/spool/mail/%d/%n
mail_privileged_group = mail
mail_access_groups = mail
mmap_disable = yes
first_valid_uid = 8
first_valid_gid = 12

$ nano -w /etc/dovecot/conf.d/10-master.conf
service auth {
  unix_listener auth-userdb {
    mode = 0600
    user = mail
    group = mail
  }
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }
}

$ nano -w /etc/dovecot/conf.d/10-ssl.conf
ssl = yes
ssl_cert = </etc/pki/tls/certs/mail.example.com.crt
ssl_key = </etc/pki/tls/private/mail.example.com.key
ssl_ca = </etc/pki/tls/certs/sub.class2.server.ca.pem
ssl_protocols = !SSLv2 !SSLv3

$ nano -w /etc/dovecot/conf.d/15-lda.conf
postmaster_address = postmaster@example.com
hostname = mail.example.com
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
protocol lda {
  mail_plugins = sieve
}

$ nano -w /etc/dovecot/conf.d/20-managesieve.conf
protocols = $protocols sieve

$ nano -w /etc/dovecot/conf.d/90-sieve.conf
plugin {
  sieve = /var/spool/mail/%Ld/%Ln.sieve/.dovecot.sieve
  sieve_dir = /var/spool/mail/%Ld/%Ln.sieve/
  sieve_extensions = +notify +imapflags
}

$ nano -w /etc/dovecot/dovecot-sql.conf.ext
driver = mysql
connect = host=localhost dbname=%VMailDB% user=%VMailUser% password=%VMailPassWord%
user_query = \
  SELECT CONCAT("/var/spool/mail/", domain) AS home, 8 AS uid, 12 AS gid, \
    'maildir:/var/spool/mail/%d/%n' AS mail, CONCAT("dirsize:storage=", quota) AS quota \
  FROM mailbox WHERE username = '%u' AND active = '1'
password_query = \
  SELECT username AS user, password, \
    CONCAT("/var/spool/mail/", domain) AS userdb_home, 8 AS userdb_uid, 12 AS userdb_gid \
  FROM mailbox WHERE username = '%u' AND active='1'
iterate_query = SELECT username AS user FROM mailbox WHERE active='1'
$ chcon -u system_u /etc/dovecot/dovecot-sql.conf.ext
$ chmod 0600 /etc/dovecot/dovecot-sql.conf.ext

Запуск сервисов

Запустим dovecot и postfix и добавим их в автозагрузку:

$ systemctl enable dovecot
$ systemctl start dovecot
$ systemctl status dovecot
dovecot.service - Dovecot IMAP/POP3 email server
   Loaded: loaded (/usr/lib/systemd/system/dovecot.service; enabled)
   Active: active (running) since Wed 2014-11-26 15:58:44 MSK; 3min 41s ago
 Main PID: 20380 (dovecot)
   CGroup: /system.slice/dovecot.service
           ├─20380 /usr/sbin/dovecot -F
           ├─20384 dovecot/anvil
           ├─20385 dovecot/log
           └─20387 dovecot/config

Nov 26 15:58:44 example.com systemd[1]: Started Dovecot IMAP/POP3 email server.
Nov 26 15:58:44 example.com dovecot[20380]: master: Dovecot v2.2.10 starting up for imap, sieve (core dumps disabled)

$ systemctl enable postfix
$ systemctl restart postfix
$ systemctl status postfix
postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled)
   Active: active (running) since Wed 2014-11-26 16:01:53 MSK; 1s ago
  Process: 20542 ExecStop=/usr/sbin/postfix stop (code=exited, status=0/SUCCESS)
  Process: 20558 ExecStart=/usr/sbin/postfix start (code=exited, status=0/SUCCESS)
  Process: 20555 ExecStartPre=/usr/libexec/postfix/chroot-update (code=exited, status=0/SUCCESS)
  Process: 20552 ExecStartPre=/usr/libexec/postfix/aliasesdb (code=exited, status=0/SUCCESS)
 Main PID: 20630 (master)
   CGroup: /system.slice/postfix.service
           ├─20630 /usr/libexec/postfix/master -w
           ├─20631 pickup -l -t unix -u
           ├─20632 qmgr -l -t unix -u
           └─20633 proxymap -t unix -u

Nov 26 16:01:52 example.com systemd[1]: Starting Postfix Mail Transport Agent...
Nov 26 16:01:53 example.com postfix/postfix-script[20628]: starting the Postfix mail system
Nov 26 16:01:53 example.com postfix/master[20630]: daemon started -- version 2.10.1, configuration /etc/postfix
Nov 26 16:01:53 example.com systemd[1]: Started Postfix Mail Transport Agent.

Проверка работоспособности SMTP

Теперь проверим, принимает ли postfix почту для нашего домена:

$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mail.example.com ESMTP Postfix
EHLO localhost
250-mail.example.com
250-PIPELINING
250-SIZE 104857600
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
MAIL FROM: wakko@example.org
250 2.1.0 Ok
RCPT TO: admin@example.com
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
Hi, Admin!

It's only test and nothing else.
.
250 2.0.0 Ok: queued as 43A7A209ED22
QUIT
221 2.0.0 Bye
Connection closed by foreign host.

А таким образом проверим подключение через TLS и авторизацию:

$ echo -ne "\0test@example.com\0testpassword" | base64
AHRlc3RAZXhhbXBsZS5jb20AdGVzdHBhc3N3b3Jk
$ openssl s_client -starttls smtp -connect localhost:25 -crlf -ign_eof
CONNECTED(00000003)
depth=2 C = IL, O = StartCom Ltd., OU = Secure Digital Certificate Signing, CN = StartCom Certification Authority
verify return:1
depth=1 C = IL, O = StartCom Ltd., OU = Secure Digital Certificate Signing, CN = StartCom Class 1 Primary Intermediate Server CA
verify return:1
depth=0 C = RU, CN = mail.example.com, emailAddress = hostmaster@example.com
verify return:1
---
Certificate chain
 0 s:/C=RU/CN=mail.example.com/emailAddress=hostmaster@example.com
   i:/C=IL/O=StartCom Ltd./OU=Secure Digital Certificate Signing/CN=StartCom Class 1 Primary Intermediate Server CA
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/C=RU/CN=mail.example.com/emailAddress=hostmaster@example.com
issuer=/C=IL/O=StartCom Ltd./OU=Secure Digital Certificate Signing/CN=StartCom Class 1 Primary Intermediate Server CA
---
No client certificate CA names sent
Server Temp Key: ECDH, prime256v1, 256 bits
---
SSL handshake has read 2450 bytes and written 410 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: ...
    Session-ID-ctx:
    Master-Key: ...
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    TLS session ticket lifetime hint: 3600 (seconds)
    TLS session ticket:
    0000 - ...

    Start Time: 1417022108
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
250 DSN
EHLO localhost
250-mail.example.com
250-PIPELINING
250-SIZE 104857600
250-ETRN
250-AUTH PLAIN
250-AUTH=PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
AUTH PLAIN AHRlc3RAZXhhbXBsZS5jb20AdGVzdHBhc3N3b3Jk
235 2.7.0 Authentication successful
MAIL FROM: test@example.com
250 2.1.0 Ok
RCPT TO: test@example.org
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
It's only test message.
.
250 2.0.0 Ok: queued as 8078F20A8F43
QUIT
221 2.0.0 Bye
closed

Настройка firewall

Проверив что postfix функционирует и готов к принятию почты – открываем его во внешний мир:

$ firewall-cmd --permanent --zone=public --add-service=smtp
$ firewall-cmd --permanent --zone=public --add-service=imaps
$ firewall-cmd --permanent --zone=public --add-port=465/tcp
$ firewall-cmd --permanent --zone=public --add-port=4190/tcp
$ firewall-cmd --reload

Настройка FetchMail

Прежде всего установим необходимые пакеты:

$ yum -y install fetchmail perl-LockFile-Simple perl-Sys-Syslog

Теперь создадим конфигурационный файл для fetchmail:

$ nano -w /etc/postfixadmin/fetchmail.conf
$db_type = "mysql";
$db_host="localhost";
$db_name="%VMailDB%";
$db_username="%VMailUser%";
$db_password="%VMailPassWord%";

$ chcon -u system_u /etc/postfixadmin/fetchmail.conf
$ chown root:postfix /etc/postfixadmin/fetchmail.conf
$ chmod 0640 /etc/postfixadmin/fetchmail.conf

Затем подготовим скрипт, который будет запускаться сервисом cron в определённое время и забирать для нас почту:

$ cp /usr/share/doc/postfixadmin-*/ADDITIONS/fetchmail.pl /usr/libexec/postfix/
$ chmod 0755 /usr/libexec/postfix/fetchmail.pl
$ sed -i 's/\/etc\/mail\/postfixadmin/\/etc\/postfixadmin/g' /usr/libexec/postfix/fetchmail.pl
$ sed -i 's/-f \$filename -i/-s -f \$filename --pidfile/g' /usr/libexec/postfix/fetchmail.pl
$ nano -w /usr/libexec/postfix/fetchmail.pl
	$mda =~ s/\${mailbox}/${mailbox}/;
#	syslog("info","fetch ${src_user}@${src_server} for ${mailbox}");

$ chcon -u system_u /usr/libexec/postfix/fetchmail.pl
$ mkdir /var/run/fetchmail
$ chcon -u system_u /var/run/fetchmail
$ chown postfix:mail /var/run/fetchmail
$ chmod 0775 /var/run/fetchmail

Добавим выполнение этого скрипта в cron:

$ crontab -u postfix -e
MAILTO=root
*/1 * * * *	/usr/libexec/postfix/fetchmail.pl
$ echo "QUIT" | openssl s_client -connect mail.example.org:993 -showcerts | sed -ne '/BEGIN/,/END/p' >/tmp/temp.crt
depth=2 C = IL, O = StartCom Ltd., OU = Secure Digital Certificate Signing, CN = StartCom Certification Authority
verify return:1
depth=1 C = IL, O = StartCom Ltd., OU = Secure Digital Certificate Signing, CN = StartCom Class 1 Primary Intermediate Server CA
verify return:1
depth=0 description = 907535-Ri93n22WJHt0psNK, CN = mail.example.org, emailAddress = postmaster@example.org
verify return:1
notAfter=Oct 13 05:50:16 2015 GMT
verify return:1
depth=0 description = 907535-Ri93n22WJHt0psNK, CN = mail.example.org, emailAddress = postmaster@example.org
notAfter=Oct 13 05:50:16 2015 GMT
verify return:1
DONE
$ openssl x509 -in /tmp/temp.crt -fingerprint -noout -md5 | sed "s/MD5 Fingerprint=//"
4F:80:51:CD:B5:1C:6A:37:74:3A:46:4B:E1:02:A7:BC
$ rm -f /tmp/temp.crt

Главная / ОС / Linux / Postfix — настройка отправки e…

Читайте также:  Пошаговое руководство: загрузка файлов на FTP-сервер стала проще

Postfix — настройка отправки email от пользователей сервера

Задача: настроить отправку электронной почты (e-mail) от пользователей сервера в интернет. Необходимо для мониторинга оборудования, извещения о событиях и т.п. Пример: получать оповещения от smartd в случае обнаружения проблем со SMART диска.

Чем меньше посредников на пути письма, тем меньше точек возможных отказов и тем больше шансов, что email будет доставлен получателю. Исходя из этих соображений, самый надежный вариант — это настроить собственный сервер отправки почты (почтовый агент; Mail Transfer Agent — MTA), а не использовать, например, SMTP своего почтового ящика в Gmail.com.

Но для того, чтобы отправленные из своего MTA письма были доставлены до адресата, а не удалены спам-фильтром получателя, необходимо располагать:

  • внешним арендованным или приобретенным белым IP-адресом (в примерах ниже будет использоваться случайный IP 5.6.7.8) и возможностью настроить PTR (Reverse DNS);
  • реальным доменным именем (example.com), поддомен которого будет настроен в качестве имени сервера с возможностью управления его настройками DNS;

Почтовый сервер — программа, которая отправляет e-mail получателю напрямую (на его почтовый сервер) или через посредника (relay).

Здесь будет рассматриваться установка и настройка Postfix для CentOS 7. Эта информация будет полезна и для выбора и установки MTA на другие системы.

Выбор почтового сервера

Из огромного множества рассмотрим 3 самых массовых почтовых сервера: Sendmail, Exim и Postfix.

Согласно cтатистики использования MTA на июнь 2020 г. самым популярным в мире является Exim (466853 — 57%), за ним следует Postfix (289401 — 35%), а вот некогда самый массово используемый Sendmail уже практически не используется (30640 — 4%).

Еще в 2007 году Sendmail был установлен на большинстве серверов, но утрата позиций связана, в первую очередь, с часто возникающими проблемами с безопасностью. Exim — мощный почтовый агент, большинство функционала которого не будет использоваться для поставленной задачи. Postfix — самый безопасный и простой в настройке полноценный MTA, он и был выбран для отправки писем с сервера.

Установка и настройка Postfix в CentOS 7

Установка и сохранения настроек по умолчанию в файле main.cf.origin:

# yum install postfix
# cp /etc/postfix/main.cf /etc/postfix/main.cf.origin

Для настройки конфигурации Postfix необходимо отредактировать или добавить следующие параметры в главном конфигурационном файле Postfix /etc/postfix/main.cf:

myhostname = server.example.com
mydomain = example.com
myorigin = $myhostname
mynetworks = 127.0.0.0/8
inet_protocols = ipv4

  • myhostname — полное доменное имя сервера;
  • mydomain — обычно это доменное имя, без первой части myhostname;
  • myorigin — домен для почтового ящика, указываемого как отправитель/from (например: root@server.example.com);
  • mynetworks — белый список сетей, из которых разрешено отправлять письма, отправка писем с IP не указанных в этом параметре — запрещена;
  • inet_protocols — all или ipv4 или ipv6 — протокол, по которому MTA будет пытаться подключиться к MTA получателя.

После первичной настройки запускаем Postfix и прописываем его в автозагрузку:

# systemctl start postfix
# systemctl enable postfix
# systemctl status postfix

Чтобы перечитать конфиг Postfix после его редактирования, пригодятся такие команды:

# systemctl reload postfix

# systemctl restart postfix

Если в журнале присутствует такая строчка со статусом «status=bounced«, значит e-mail отклонен сервером получателя. Причину ищите в этой же строке журнала чуть дальше:

Если же в журнале «status=sent«, значит e-mail принят сервером получателя и будет скорее всего доставлен по назначению:

Но даже если письмо принято получателем, оно может быть (точнее скорее всего) будет автоматически перемещено в папку «Спам». Как с этим бороться — читайте ниже.

Дополнительные настройки для работы почтового сервера

Настройка Hostname сервера

Посмотреть, как называется сервер можно такой командой:

Если название отличается от необходимого или не установлено, тогда записать hostname для сервера:

Обратите внимание, что hostname сервера не равно домену сервера! Если полный домен сервера: «server.example.com», то hostname сервера — это «server».

Настройка PTR (Reverse DNS)

Сервер-отправитель письма указывает в параметре HELO (EHLO) свой домен, например server.example.com, а сервер получателя делает специальный whois-запрос, чтобы проверить, какой домен записан для IP сервера отправителя. Если домен, указанный для IP и в заголовке HELO (EHLO) не совпадают, то с большой долей вероятности письмо будет или отклонено, или перемещено в папку Спам.

Проверить домен, присвоенный PTR, можно утилитой командной строки dig: $ dig -x 5.6.7.8 или используя различные онлайн-сервисы.

Настройка DNS доменного имени почтового сервера

В панели управления регистратора домена example.com поддомен для сервера (server) конфигирируется, обычно, в разделе «Настройка DNS«:

server.example.com A 5.6.7.8
server.example.com MX 10 server.example.com
server.example.com TXT v=spf1 +a +mx -all

В третьей строке указывается SPF-запись для поддомена. SPF используется почтовым сервером-получателем для проверки: разрешено ли владельцем домена отправка писем с IP, с которого пришло в действительности письмо? Параметры SPF «+a +mx -all» указывают, что письма могут отправлять только те IP, которые прописаны в A и MX записях домена, а со всех остальных IP принимать почту запрещено.

Проверка влияния настроек PTR и DNS на отправляемые e-mail

После изменения настроек DNS необходимо подождать какое-то время, для того, чтобы они обновились на всех DNS серверах. Иногда это может затянуться до одних суток.

Отправляем тестовое письмо на свой e-mail и смотрим журнал:

Если «status» отправки e-mail Postfix равен «sent», значит письмо было получено сервером принимающей стороны. Следует проверить, не попало ли оно в спам, и если нет — значит большая часть работы по настройке Postfix выполнена успешно. Но остается еще один важный момент, требующий настройки: шифрование письма.

По умолчанию, Postfix, да и, наверное, все другие MTA, отправляет письма в открытом не зашифрованном виде. Это сравнимо с просмотром web-страниц по небезопасному протоколу HTTP, вместо HTTPS. В этом случае, например, в интерфейсе Gmail, напротив получателя будет отображаться красный перечеркнутый замок, означающий, что сообщение не зашифровано. Но самое печальное, что если в письме будут какие-либо конфиденциальные данные, их смогут без проблем прочитать все, через кого проходит трафик, что очень и очень не безопасно.

Добавить шифрование в Postfix для отправляемых писем — весьма просто, инструкция расположена ниже.

TLS-шифрование отправляемых писем в Postfix

Первым делом необходимо получить сертификат, при помощи которого будут шифроваться все отправляемые из Postfix e-mail. Самый простой и быстрый способ — создать сертификат самостоятельно.

openssl req -new -nodes -x509 -out /etc/postfix/smtpd.pem -keyout /etc/postfix/smtpd.pem -days 18400

На все вопросы, кроме указания Common Name, можно отвечать на свое усмотрение, Common Name сертификата должно совпадать с именем сервера (в этой конфигурации — server.example.com). Этой командой будет создан сертификат со сроком действия 50 лет.

Далее нужно внести изменения в главный файл конфигурации Postfix (/etc/postfix/main.cf), а точнее, просто добавить строки, опубликованные ниже в конец файла:

tls_random_source = dev:/dev/urandom
smtp_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_auth_only = yes
smtpd_tls_key_file = /etc/postfix/smtpd.pem
smtpd_tls_cafile = /etc/postfix/smtpd.pem
smtpd_tls_cert_file = /etc/postfix/smtpd.pem
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_loglevel = 1
smtpd_use_tls = yes

Краткое описание настроек для шифрования исходящих писем:

  • tls_random_source — ссылка на генератор случайных чисел;
  • smtp_use_tls — оповещение клиентов о наличии TLS-шифрования;
  • smtp_tls_note_starttls_offer — записывать в журнал имена серверов, у которых поддержка TLS не включена (ответ STARTTLS);
  • smtpd_tls_auth_only — применять SMTP-аутентификацию только для соединений с использованием TLS;
  • smtpd_tls_key_file — закрытый ключ сервера;
  • smtpd_tls_cafile — сертификат;
  • smtpd_tls_cert_file — сертификат;
  • smtpd_tls_received_header — запрос на получение данных про алгоритм шифрования и версию протокола;
  • smtpd_tls_session_cache_timeout — данные в кэше TLS-сессии считаются актуальными в указанном периоде (сек);
  • smtpd_tls_loglevel — на сколько подробно записывать сообщения в журнал;
  • smtpd_use_tls — оповестить об использовании TLS;

HTML-код ссылки на эту страницу:

<a data-hren=»https://petrenco.com/linux.php?txt=728″ target=»_blank»>Postfix — настройка отправки email от пользователей сервера</a>

Postfix HOWTO

[object Object]

Installation

The first thing we need to do is install the requisite software. The easiest way to do this is with yum from the command line:

yum install postfix dovecot system-switch-mail system-switch-mail-gnome

Yum should automatically resolve any dependencies. Dovecot is dependent on mysql and perl, so these will likely be installed too if they are not already installed on the system.

Alternatively, we can skip ‘system-switch-mail’ and ‘system-switch-mail-gnome’ installation and remove the default MTA ‘sendmail’, this will make ‘postfix’ the default MTA in our system.

yum install postfix dovecot 
yum remove sendmail

Please note that the default MTA in CentOS 5 is sendmail. If you do not make postfix the default MTA, updating postfix may cause the default MTA to revert to sendmail.

Читайте также:  Понимание статусов HTML-сервера: подробное руководство

Configuration

Next we need to configure the various parts of our email server.

3.1. Postfix

myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 192.168.0.0/24, 127.0.0.0/8
relay_domains =
home_mailbox = Maildir/

Note: Each line should start at the beginning of a new line and should not be preceded by white space or tabs. White space or tabs at the beginning of a line are treated as a continuation of the previous line, and if the previous line is a comment (#) line then the subsequent line is also treated as such. Further, inline comments should be avoided.

Now lets take a look at each setting it turn to understand what we’ve just done:

myhostname: is the host name of the system (i.e, the system is called mail or mail.example.com).

mydomain: is the domain name for the email server (it can be a real or fake domain name).

myorigin: is the domain name that locally-posted email appears to have come from and is delivered to.

inet_interfaces: sets the network interfaces that Postfix can receive mail on. These need to include at least localhost and the local domain.

mydestination: is the list of domains that will be delivered to (i.e, this server is the final destination for email addressed to these domains).

relay_domains: is a list of destination domains this system will relay mail to. By setting it to be blank we ensure that our mail server isn’t acting as an open relay for untrusted networks. The reader is advised to test that their system isn’t acting as an open relay here: http://www.abuse.net/relay.html

3.2. Dovecot

protocols = imap imaps pop3 pop3s
mail_location = maildir:~/Maildir
pop3_uidl_format = %08Xu%08Xv
# Required on x86_64 kernels
login_process_size = 64

Again, looking at each option:

login_process_size: The release notes for CentOS 5.1 state that «the Dovecot package on x86_64 kernels requires the parameter «login_process_size = 64″ to be added to /etc/dovecot.conf after an upgrade to CentOS 5.1». 32-Bit installations are unaffected and do not require this setting.

Note: If you have any issues connecting with either imap or pop3 to dovecot, check the IMAP specific settings and POP3 specific settings sections of the dovecot.conf configuration file for workarounds. The available options mostly affect older mail clients and workarounds for Microsoft Outlook and Outlook Express.

Note on dovecot and C6: With CentOS 6 the configuration moved to /etc/dovecot/dovecot.conf. Dovecot can be started without any further changes to the configuration file and will automatically listen for connections on the ports for pop3(s) and imap(s). Changes to suite your environment will probably be required.

3.3. Create users mailboxes

mkdir /home/john/Maildir
chown john:john /home/john/Maildir
chmod -R 700 /home/john/Maildir 

3.4. Aliases

# Person who should get root's mail
root:           john
# User aliases
jsmith:         john
j.smith:        john

Starting the server

We are now ready to fire up our new email server. First we need to tell our system to use postfix as the MTA rather than the default sendmail. To do this, run the system-switch-mail command and select postfix as the MTA. This will install the postfix service and set it to start automatically at runlevels 3, 4, and 5. Next we need to set the dovecot service to also automatically start at runlevels 3, 4, and 5, and start both services:

chkconfig --level 345 dovecot on
/etc/init.d/dovecot start
/etc/init.d/postfix start

at which point you should be up and running. Your email server should have no trouble sending and receiving email internally and sending external email. To receive external email on your domain, you will also need to configure MX records in DNS for your domain (ideally a PTR rDNS entry should also be configured through your ISP mapping your IP address to your domain). Don’t forget to open any required ports on your Linux firewall depending what services you are running (SMTP 25; POP3 110; IMAP 143; IMAPS 993; POP3S 995) and enable port forwarding for those ports on any routers.

If you make any changes to the postfix configuration file main.cf, you can either restart the postfix service or run the postfix reload command to update the changes.

Summary

Readers are now encouraged to read the complimentary postfix restrictions guide.

Readers are encouraged to read the extensive postfix documentation available at the postfix website including the many example configurations:

Test for email servers configured as open relays:

Postfix/dovecot SASL and SSL/TLS guide

[object Object]

Introduction

This guide is designed to compliment the basic postfix guide. It is written for CentOS 5. Configuration will differ for CentOS 6.

What about SSL/TLS?

So SASL is able to provide a mechanism to authenticate remote users by username and password who wish to send mail through the mail server. Additionally, remote users are able to retrieve mail through IMAP and/or POP3 mechanisms provided by dovecot. However, we have a problem in that these mechanisms are sending usernames and passwords in plain text across the Internet (SASL does support various encrypted authentication methods such as DIGEST-MD5 but these aren’t always universally supported by email client software). This poses a security risk as anyone can potentially intercept this information and steal login details so we need to encrypt the connection. SSL (Secure Sockets Layer), and more recently TLS (Transport Layer Security), offer a mechanism to encrypt communications between two hosts, in our case our mail server and our remote client. SSL was renamed TLS by the IETF as of version 3.1.

Configuring SASL in postfix

smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_recipient_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    reject_unauth_destination
auth default {
    mechanisms = plain login
    passdb pam {
    }
    userdb passwd {
    }
    user = root
    socket listen {
      client {
        path = /var/spool/postfix/private/auth
        mode = 0660
        user = postfix
        group = postfix
      }
    }
}

Restart dovecot and reload postfix configuration setting:

service dovecot restart
postfix reload

/! Note: For CentOS 6, which uses dovecot 2.x, please see here: http://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL

Testing SASL

Now we have SASL configured we need to test that it is working correctly. For the purposes of testing and/or local security considerations, it may also be useful to restrict $mynetworks to only allow 127.0.0.0/8 so that we may enforce SASL authentication, otherwise relaying from incorrectly configured local clients may still be permitted under the permit_mynetworks setting in smtpd_recipient_restrictions.

$ perl -MMIME::Base64 -e 'print encode_base64("\000test\000test1234");'
AHRlc3QAdGVzdDEyMzQ=

For reference, our Base64 encoded string may be decoded with:

$ perl -MMIME::Base64 -e 'print decode_base64("AHRlc3QAdGVzdDEyMzQ=");'
testtest1234

For those that don’t have perl, there is an online Base64 encoder available here.

Using our Base64 encoded string to test authentication:

$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 mail.example.com ESMTP Postfix
EHLO example.com
250-mail.example.com
250-PIPELINING
250-SIZE 20480000
250-VRFY
250-ETRN
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
AUTH PLAIN AHRlc3QAdGVzdDEyMzQ=
235 2.0.0 Authentication successful
quit
221 2.0.0 Bye
Connection closed by foreign host.

Outlook Express: Tools > Accounts > Mail tab > select an account and click properties. Then on the Servers tab, under Outgoing Mail Server, tick «My server requires authentication».

If we send a test message and tail our maillog, assuming everything is working, we should now see our email client authenticated using SASL:

tail -f /var/log/maillog
Mar 18 13:25:56 mail postfix/smtpd[22400]: connect from mail[127.0.0.1]
Mar 18 13:26:02 mail postfix/smtpd[22400]: 105892006E: client=mail[127.0.0.1], sasl_method=PLAIN, sasl_username=ned
Mar 18 13:26:02 mail postfix/cleanup[22404]: 105892006E: message-id=<47DFC2E4.30402@example.com>
Mar 18 13:26:02 mail postfix/qmgr[22338]: 105892006E: from=<ned@example.com>, size=518, nrcpt=2 (queue active)
Mar 18 13:26:02 mail postfix/smtpd[22400]: disconnect from mail[127.0.0.1]
Mar 18 13:26:02 mail postfix/local[22405]: 105892006E: to=<ned@example.com>, relay=local, delay=0.26,
       delays=0.11/0.02/0/0.14, dsn=2.0.0, status=sent (delivered to maildir)
Mar 18 13:26:06 mail postfix/qmgr[22338]: 105892006E: removed

Generating SSL certificates

yum install crypto-utils
genkey --days 365 mail.example.com

/! Note: CentOS 6.4 or later uses a version of nss that does not support md5. Because of this, the genkey command would not work. More details and a workaround can be found in the NSS_3.14 release notes. With the release of CESA-2013:1144 md5 is once again supported.

/etc/pki/tls/certs/mail.example.com.cert  # public cert
/etc/pki/tls/private/mail.example.com.key  # private key

You can leave the certificates in their current location or copy/move them elsewhere. The private key must be owned and read/writable (0600) only by root.

Оцените статью
Хостинги