14. Main configuration

Настройка exim4 для отправки почтовых сообщений в linux | облачный виртуальный хостинг cloudlite

Необходимо настроить агент пересылки почтовых сообщений Exim4 на виртуальных серверах под управлением операционных систем Linux? Следуйте инструкциям!

Exim4 – это агент пересылки почтовых сообщений, представляющий собой, по сути, простой SMTP-сервер. В данной статье мы подробно изучим нюансы отправки сообщений через SMTP-сервера крупных компаний (Google и Yandex).

Вначале необходимо обновить локальный список пакетов посредством вашего пакетного менеджера, в случае Ubuntu и Debian вы можете использовать APT:

apt-get update

Чтобы установить, нужна команда:

apt-get install exim4

Внимание: при необходимости использования ACL и других расширенных функций – установите exim4-daemon-heavy:

apt-get install exim4-daemon-heavy

Для перехода к настройкам выполните команду:

dpkg-reconfigure exim4-config

Нажмите ОК и переходите к настройке
Описание: OK

После выберите «mail sent by smarthost; received via SMTP or fetchmail» и нажмите ОК.

Внимание:

internet site; mail is sent and received directly using SMTP – этот вариант пригоден для автономной системы с полным доступом к Интернету. Сообщения принимаются и доставляются на локальные домены при помощи демона Exim. Исходящие сообщения поступают сразу на почтовые серверы домена получателя.

mail sent by smarthost; received via SMTP or fetchmail – такой вариант оптимален для автономной системы с ограниченным доступом к Интернету. Сообщения принимаются и доставляются на локальные домены при помощи демона Exim. Исходящие сообщения доставляются на Smart host, а уже потом на почтовые серверы домена получателя.
mail sent by smarthost; no local mail – этот вариант оптимален для клиентской системы, в этом случае почта отправляется на Smart host без каких-либо локальных доменов.
local delivery only; not on a network – этот вариант подходит для серверов, которые не подключены к Интернету. Прием и доставка сообщений осуществляется только для локальных доменов, отправка на удаленные (внешние) домены невозможна.
Описание: General Type
Введите имя хоста или ваше доменное имя.
Описание: System mail name
Нажмите ОК
Описание: OK
Введите адрес локальной сети (в случае если exim предназначен только для локальных сервисов). Чтобы прослушать все интерфейсы, ставьте поле пустым или просто перечислите нужные через символ «;».
Описание: IP-adresses
Следующее поле оставьте пустым, если отсутствуют локальные домены.

Внимание: по умолчанию все локальные домены будут обрабатываться одинаково. Актуальные локальные домены вы можете указать.
Описание: Other destinations
На этом этапе следует указать список доменов, для которых Exim будет ретранслировать сообщения, выполняя роль Smarthost`а. Если сервер не должен быть smarthost для другого хоста, оставьте список пустым.
Описание: mail for
На этом шаге укажите адрес используемого smtp-сервера:

smtp.yandex.ru::587
smtp.gmail.com::587
mail.example.com::587

Описание: smarthost
Далее вам будет необходимо ответить на вопрос –  NO (при необходимости скрытия локального имени сервера).
Описание: No

Нажмите ОК
Описание: OK
В обычном режиме работы Exim выполняет поиск DNS при запуске, при получении или доставке почты. Выберите этот параметр, если в системе используется Dial-on-Demand. Если сервер всегда подключен к Интернету, отключите этот параметр.
Описание: No
Выберите место хранения сообщений: в каталоге /var/mail или в домашней директории для каждого пользователя.

Описание: mbox format
Ответьте на вопрос о разделении файла конфигурации на маленькие – Yes. Это позволит более удобно конфигурировать exim4 потом.
Описание: Yes
На следующем этапе добавьте данные о почтовом ящике, с которого будет отправляться почта: с помощью текстового редактора, например vi, откройте на редактирование файл:
vi /etc/exim4/passwd.client
Добавьте в него строку такого вида, с указанием вашего логина и пароля.
Для Gmail
smtp.google.com:[email protected]:password
Для Yandex:
smtp.yandex.ru:[email protected]:password
Для вашего SMTP-сервера:
mail.example.com:[email protected]:password

Содержимое файла будет выглядеть так:

# password file used when the local exim is authenticating to a remote
# host as a client.
#
# see exim4_passwd_client(5) for more documentation
#
# Example:
### target.mail.server.example:login:password
smtp.google.com:[email protected]:12345

Следующие настройки будут выполнены аналогично почтовому сервису gmail.

Далее вносятся изменения в файл /etc/exim4/exim4.conf.template. Откройте его на редактирование при помощи текстового редактора:
vi /etc/exim4/exim4.conf.template
Найдите такую строку:

.ifdef DCconfig_smarthost DCconfig_satellite

После нее вставьте такие строки:

send_via_gmail:
driver = manualroute
domains = ! local_domains
transport = gmail_smtp
route_list = * smtp.gmail.com

Найдите первую строку с таким содержимым:

transport/30_exim4-config_remote_smtp_smarthost

Далее вставьте следующие строки:

gmail_smtp:
driver = smtp
port = 587
hosts_require_auth = $host_address
hosts_require_tls = $host_address

Найдите такую строку:

begin authenticators

Вставьте после нее такие строки, а почтовый адрес и пароль измените на нужные:

gmail_login:
driver = plaintext
public_name = login
client_send = : [email protected] : password

Удалите из файла следующий блок строк, чтобы исключить ошибки авторизации:


login:
driver = plaintext
public_name = LOGIN
.ifndef AUTH_CLIENT_ALLOW_NOTLS_PASSWORDS
# Return empty string if not non-TLS AND looking up $host in passwd-file
# yields a non-empty string; fail otherwise.
client_send = "<; ${if and{
{!eq{$tls_out_cipher}{}}
{!eq{PASSWDLINE}{}}
}
{}fail}
; ${extract{1}{::}{PASSWDLINE}}
; ${sg{PASSWDLINE}{\N([^:] :)(.*)\N}{\$2}}"
.endif

Сохраните изменения и закройте файл. Перезагрузите почтовый сервис, чтобы активировать изменения.
sudo /etc/init.d/exim4 restart
Для проверки корректности настроек отправьте тестовое сообщение.
echo «Testing our Exim» | mail -s Test [email protected]
На этапе на ваш адрес, через который вы отправляете почту, может прийти сообщение о небезопасном приложении. Для корректировки включите доступ для ненадежных приложений.
Описание: Google‚

Необходимо настроить агент пересылки почтовых сообщений Exim4 на виртуальных серверах под управлением операционных систем Linux? Следуйте инструкциям!

Exim4 – это агент пересылки почтовых сообщений, представляющий собой, по сути, простой SMTP-сервер. В данной статье мы подробно изучим нюансы отправки сообщений через SMTP-сервера крупных компаний (Google и Yandex).

Вначале необходимо обновить локальный список пакетов посредством вашего пакетного менеджера, в случае Ubuntu и Debian вы можете использовать APT:

apt-get update

Чтобы установить, нужна команда:

apt-get install exim4

Внимание: при необходимости использования ACL и других расширенных функций – установите exim4-daemon-heavy:

apt-get install exim4-daemon-heavy

Для перехода к настройкам выполните команду:

dpkg-reconfigure exim4-config

Нажмите ОК и переходите к настройке
Описание: OK

После выберите «mail sent by smarthost; received via SMTP or fetchmail» и нажмите ОК.

Внимание:

internet site; mail is sent and received directly using SMTP – этот вариант пригоден для автономной системы с полным доступом к Интернету. Сообщения принимаются и доставляются на локальные домены при помощи демона Exim. Исходящие сообщения поступают сразу на почтовые серверы домена получателя.

mail sent by smarthost; received via SMTP or fetchmail – такой вариант оптимален для автономной системы с ограниченным доступом к Интернету. Сообщения принимаются и доставляются на локальные домены при помощи демона Exim. Исходящие сообщения доставляются на Smart host, а уже потом на почтовые серверы домена получателя.
mail sent by smarthost; no local mail – этот вариант оптимален для клиентской системы, в этом случае почта отправляется на Smart host без каких-либо локальных доменов.
local delivery only; not on a network – этот вариант подходит для серверов, которые не подключены к Интернету. Прием и доставка сообщений осуществляется только для локальных доменов, отправка на удаленные (внешние) домены невозможна.
Описание: General Type
Введите имя хоста или ваше доменное имя.
Описание: System mail name
Нажмите ОК
Описание: OK
Введите адрес локальной сети (в случае если exim предназначен только для локальных сервисов). Чтобы прослушать все интерфейсы, ставьте поле пустым или просто перечислите нужные через символ «;».
Описание: IP-adresses
Следующее поле оставьте пустым, если отсутствуют локальные домены.

Внимание: по умолчанию все локальные домены будут обрабатываться одинаково. Актуальные локальные домены вы можете указать.
Описание: Other destinations
На этом этапе следует указать список доменов, для которых Exim будет ретранслировать сообщения, выполняя роль Smarthost`а. Если сервер не должен быть smarthost для другого хоста, оставьте список пустым.
Описание: mail for
На этом шаге укажите адрес используемого smtp-сервера:

smtp.yandex.ru::587
smtp.gmail.com::587
mail.example.com::587

Описание: smarthost
Далее вам будет необходимо ответить на вопрос –  NO (при необходимости скрытия локального имени сервера).
Описание: No

Нажмите ОК
Описание: OK
В обычном режиме работы Exim выполняет поиск DNS при запуске, при получении или доставке почты. Выберите этот параметр, если в системе используется Dial-on-Demand. Если сервер всегда подключен к Интернету, отключите этот параметр.
Описание: No
Выберите место хранения сообщений: в каталоге /var/mail или в домашней директории для каждого пользователя.

Описание: mbox format
Ответьте на вопрос о разделении файла конфигурации на маленькие – Yes. Это позволит более удобно конфигурировать exim4 потом.
Описание: Yes
На следующем этапе добавьте данные о почтовом ящике, с которого будет отправляться почта: с помощью текстового редактора, например vi, откройте на редактирование файл:
vi /etc/exim4/passwd.client
Добавьте в него строку такого вида, с указанием вашего логина и пароля.
Для Gmail
smtp.google.com:[email protected]:password
Для Yandex:
smtp.yandex.ru:[email protected]:password
Для вашего SMTP-сервера:
mail.example.com:[email protected]:password

Содержимое файла будет выглядеть так:

# password file used when the local exim is authenticating to a remote
# host as a client.
#
# see exim4_passwd_client(5) for more documentation
#
# Example:
### target.mail.server.example:login:password
smtp.google.com:[email protected]:12345

Следующие настройки будут выполнены аналогично почтовому сервису gmail.

Далее вносятся изменения в файл /etc/exim4/exim4.conf.template. Откройте его на редактирование при помощи текстового редактора:
vi /etc/exim4/exim4.conf.template
Найдите такую строку:

.ifdef DCconfig_smarthost DCconfig_satellite

После нее вставьте такие строки:

send_via_gmail:
driver = manualroute
domains = ! local_domains
transport = gmail_smtp
route_list = * smtp.gmail.com

Найдите первую строку с таким содержимым:

transport/30_exim4-config_remote_smtp_smarthost

Далее вставьте следующие строки:

gmail_smtp:
driver = smtp
port = 587
hosts_require_auth = $host_address
hosts_require_tls = $host_address
Найдите такую строку:
begin authenticators

Вставьте после нее такие строки, а почтовый адрес и пароль измените на нужные:

gmail_login:
driver = plaintext
public_name = login
client_send = : [email protected] : password

Удалите из файла следующий блок строк, чтобы исключить ошибки авторизации:


login:
driver = plaintext
public_name = LOGIN
.ifndef AUTH_CLIENT_ALLOW_NOTLS_PASSWORDS
# Return empty string if not non-TLS AND looking up $host in passwd-file
# yields a non-empty string; fail otherwise.
client_send = "<; ${if and{
{!eq{$tls_out_cipher}{}}
{!eq{PASSWDLINE}{}}
}
{}fail}
; ${extract{1}{::}{PASSWDLINE}}
; ${sg{PASSWDLINE}{\N([^:] :)(.*)\N}{\$2}}"
.endif

Сохраните изменения и закройте файл. Перезагрузите почтовый сервис, чтобы активировать изменения.
sudo /etc/init.d/exim4 restart
Для проверки корректности настроек отправьте тестовое сообщение.
echo «Testing our Exim» | mail -s Test [email protected]
На этапе на ваш адрес, через который вы отправляете почту, может прийти сообщение о небезопасном приложении. Для корректировки включите доступ для ненадежных приложений.
Описание: Google‚

Support for the submissions (aka ssmtp and smtps) protocol

The history of port numbers for TLS in SMTP is a little messy and has been
contentious. As of RFC 8314, the common practice of using the historically
allocated port 465 for “email submission but with TLS immediately upon connect
instead of using STARTTLS” is officially blessed by the IETF, and recommended
by them in preference to STARTTLS.

The name originally assigned to the port was “ssmtp” or “smtps”, but as
clarity emerged over the dual roles of SMTP, for MX delivery and Email
Submission, nomenclature has shifted. The modern name is now “submissions”.

. Use of TLS Server Name Indication

With TLS1.0 or above, there is an extension mechanism by which extra
information can be included at various points in the protocol. One of these
extensions, documented in RFC 6066 (and before that RFC 4366) is
“Server Name Indication”, commonly “SNI”.

. Multiple messages on the same encrypted TCP/IP connection

Exim sends multiple messages down the same TCP/IP connection by starting up
an entirely new delivery process for each message, passing the socket from
one process to the next. This implementation does not fit well with the use
of TLS, because there is quite a lot of state information associated with a TLS
connection, not just a socket identification.

An older mode of operation can be enabled on a per-host basis by the
hosts_noproxy_tls option on the smtp transport. If the host matches
this list the proxy process described above is not used;

instead Exim
shuts down an existing TLS session being run by the delivery process
before passing the socket to a new process. The new process may then
try to start a new TLS session, and if successful, may try to re-authenticate
if AUTH is in use, before sending the next message.

The RFC is not clear as to whether or not an SMTP session continues in clear
after TLS has been shut down, or whether TLS may be restarted again later, as
just described. However, if the server is Exim, this shutdown and
reinitialization works. It is not known which (if any) other servers operate
successfully if the client closes a TLS session and continues with unencrypted
SMTP, but there are certainly some that do not work.

To test for this case, Exim sends an EHLO command to the server after
closing down the TLS session. If this fails in any way, the connection is
closed instead of being passed to a new delivery process, but no retry
information is recorded.

There is also a manual override; you can set hosts_nopass_tls on the
smtp transport to match those hosts for which Exim should not pass
connections to new processes if TLS has been used.

. Certificates and all that

In order to understand fully how TLS works, you need to know about
certificates, certificate signing, and certificate authorities.
This is a large topic and an introductory guide is unsuitable for the Exim
reference manual, so instead we provide pointers to existing documentation.

The Apache web-server was for a long time the canonical guide, so their
documentation is a good place to start; their SSL module’s Introduction
document is currently at

and their FAQ is at

. Self-signed certificates

You can create a self-signed certificate using the req command provided
with OpenSSL, like this:

openssl req -x509 -newkey rsa:1024 -keyout file1 -out file2 
            -days 9999 -nodes

file1 and file2 can be the same file; the key and the certificate are
delimited and so can be identified independently. The -days option
specifies a period for which the certificate is valid.

The -nodes option is
important: if you do not set it, the key is encrypted with a passphrase
that you are prompted for, and any use that is made of the key causes more
prompting for the passphrase. This is not helpful if you are going to use
this certificate and key in an MTA, where prompting is not possible.

NB: we are now past the point where 9999 days takes us past the 32-bit Unix
epoch. If your system uses unsigned time_t (most do) and is 32-bit, then
the above command might produce a date in the past. Think carefully about
the lifetime of the systems you’re deploying, and either reduce the duration
of the certificate or reconsider your platform deployment.

A self-signed certificate made in this way is sufficient for testing, and
may be adequate for all your requirements if you are mainly interested in
encrypting transfers, and not in secure identification.

. TLS Resumption

TLS Session Resumption for TLS 1.2 and TLS 1.3 connections can be used (defined
in RFC 5077 for 1.2). The support for this requires GnuTLS 3.6.3 or OpenSSL 1.1.1
(or later).

Session resumption (this is the “stateless” variant) involves the server sending
a “session ticket” to the client on one connection, which can be stored by the
client and used for a later session. The ticket contains sufficient state for
the server to reconstruct the TLS session, avoiding some expensive crypto
calculation and (on TLS1.2) one full packet roundtrip time.

  • Operational cost/benefit:

    The extra data being transmitted costs a minor amount, and the client has
    extra costs in storing and retrieving the data.

    In the Exim/Gnutls implementation the extra cost on an initial connection
    which is TLS1.2 over a loopback path is about 6ms on 2022-laptop class hardware.
    The saved cost on a subsequent connection is about 4ms; three or more
    connections become a net win. On longer network paths, two or more
    connections will have an average lower startup time thanks to the one
    saved packet roundtrip. TLS1.3 will save the crypto cpu costs but not any
    packet roundtrips.

    Since a new hints DB is used on the TLS client,
    the hints DB maintenance should be updated to additionally handle “tls”.

  • Security aspects:

    The session ticket is encrypted, but is obviously an additional security
    vulnarability surface. An attacker able to decrypt it would have access
    all connections using the resumed session.
    The session ticket encryption key is not committed to storage by the server
    and is rotated regularly (OpenSSL: 1hr, and one previous key is used for
    overlap; GnuTLS 6hr but does not specify any overlap).
    Tickets have limited lifetime (2hr, and new ones issued after 1hr under
    OpenSSL. GnuTLS 2hr, appears to not do overlap).

    There is a question-mark over the security of the Diffie-Helman parameters
    used for session negotiation.

  • Observability:

    The log_selector “tls_resumption” appends an asterisk to the tls_cipher “X=”
    element.

    The variables $tls_in_resumption and $tls_out_resumption
    have bits 0-4 indicating respectively
    support built, client requested ticket, client offered session,
    server issued ticket, resume used. A suitable decode list is provided
    in the builtin macro _RESUME_DECODE for in listextract expansions.

  • Control:

    The tls_resumption_hosts main option specifies a hostlist for which
    exim, operating as a server, will offer resumption to clients.
    Current best practice is to not offer the feature to MUA connection.
    Commonly this can be done like this:

    tls_resumption_hosts = ${if inlist {$received_port}{587:465} {:}{*}}
    

    If the peer host matches the list after expansion then resumption
    is offered and/or accepted.

    The tls_resumption_hosts smtp transport option performs the
    equivalent function for operation as a client.
    If the peer host matches the list after expansion then resumption
    is attempted (if a stored session is available) or the information
    stored (if supplied by the peer).

  • Issues:

    In a resumed session:

OpenSSL vs GnuTLS

TLS is supported in Exim using either the OpenSSL or GnuTLS library.
To build Exim to use OpenSSL you need to set

in Local/Makefile.

To build Exim to use GnuTLS, you need to set

in Local/Makefile.


You must also set TLS_LIBS and TLS_INCLUDE appropriately, so that the
include files and libraries for GnuTLS can be found.

There are some differences in usage when using GnuTLS instead of OpenSSL:

  • The tls_verify_certificates option
    cannot be the path of a directory
    for GnuTLS versions before 3.3.6
    (for later versions, or OpenSSL, it can be either).

  • The default value for tls_dhparam differs for historical reasons.

  • Distinguished Name (DN) strings reported by the OpenSSL library use a slash for
    separating fields; GnuTLS uses commas, in accordance with RFC 2253. This
    affects the value of the $tls_in_peerdn and $tls_out_peerdn variables.

  • OpenSSL identifies cipher suites using hyphens as separators, for example:
    DES-CBC3-SHA. GnuTLS historically used underscores, for example:
    RSA_ARCFOUR_SHA. What is more, OpenSSL complains if underscores are present
    in a cipher list. To make life simpler, Exim changes underscores to hyphens
    for OpenSSL and passes the string unchanged to GnuTLS (expecting the library
    to handle its own older variants) when processing lists of cipher suites in the
    tls_require_ciphers options (the global option and the smtp transport
    option).

  • The tls_require_ciphers options operate differently, as described in the
    sections 43.4 and 43.5.

  • The tls_dh_min_bits SMTP transport option is only honoured by GnuTLS.
    When using OpenSSL, this option is ignored.
    (If an API is found to let OpenSSL be configured in this way,
    let the Exim Maintainers know and we’ll likely use it).

  • With GnuTLS, if an explicit list is used for the tls_privatekey main option
    main option, it must be ordered to match the tls_certificate list.

  • Some other recently added features may only be available in one or the other.
    This should be documented with the feature. If the documentation does not
    explicitly state that the feature is infeasible in the other TLS
    implementation, then patches are welcome.

  • The output from “exim -bV” will show which (if any) support was included
    in the build.
    Also, the macro “_HAVE_OPENSSL” or “_HAVE_GNUTLS” will be defined.

. Alphabetical list of main options

Those options that undergo string expansion before use are marked with
†.

This option causes Exim to send 8BITMIME in its response to an SMTP
EHLO command, and to accept the BODY= parameter on MAIL commands.
However, though Exim is 8-bit clean, it is not a protocol converter, and it
takes no steps to do anything special with messages received by this route.

Historically Exim kept this option off by default, but the maintainers
feel that in today’s Internet, this causes more problems than it solves.
It now defaults to true.
A more detailed analysis of the issues is provided by Dan Bernstein:

To log received 8BITMIME status use

This option defines the ACL that is run when a non-SMTP message has been
read and is on the point of being accepted. See chapter 44 for
further details.

This option defines the ACL that is run for individual MIME parts of non-SMTP
messages. It operates in exactly the same way as acl_smtp_mime operates for
SMTP messages.

This option defines the ACL that is run before Exim starts reading a
non-SMTP message. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP AUTH command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP connection is received.
See chapter 44 for further details.

This option defines the ACL that is run after an SMTP DATA command has been
processed and the message itself has been received, but before the final
acknowledgment is sent. See chapter 44 for further details.

This option defines the ACL that,
if the PRDR feature has been negotiated,
is run for each recipient after an SMTP DATA command has been
processed and the message itself has been received, but before the
acknowledgment is sent. See chapter 44 for further details.

This option defines the ACL that is run for each DKIM signature
(by default, or as specified in the dkim_verify_signers option)
of a received message.
See section 58.3 for further details.

This option defines the ACL that is run when an SMTP ETRN command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP EXPN command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP EHLO or HELO
command is received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP MAIL command is
received. See chapter 44 for further details.

This option defines the ACL that is run when there is an AUTH parameter on
a MAIL command. See chapter 44 for details of ACLs, and chapter
33 for details of authentication.

This option is available when Exim is built with the content-scanning
extension. It defines the ACL that is run for each MIME part in a message. See
section 45.4 for details.

This option defines the ACL that is run when an SMTP session
ends without a QUIT command being received.
See chapter 44 for further details.

This option defines the ACL that is run when an SMTP DATA command is
received, before the message itself is received. See chapter 44 for
further details.

This option defines the ACL that is run when an SMTP QUIT command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP RCPT command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP STARTTLS command is
received. See chapter 44 for further details.

This option defines the ACL that is run when an SMTP VRFY command is
received. See chapter 44 for further details.

This option adds individual environment variables that the
currently linked libraries and programs in child processes may use.
Each list element should be of the form “name=value”.


See 29.4 for the environment of pipe transports.

GnuTLS parameter computation

This section only applies if tls_dhparam is set to historic or to
an explicit path; if the latter, then the text about generation still applies,
but not the chosen filename.
By default, as of Exim 4.

Requiring specific ciphers or other parameters in GnuTLS

The GnuTLS library allows the caller to provide a “priority string”, documented
as part of the gnutls_priority_init function. This is very similar to the
ciphersuite specification in OpenSSL.

Configuring an Exim server to use TLS

When Exim has been built with TLS support, it advertises the availability of
the STARTTLS command to client hosts that match tls_advertise_hosts,
but not to any others. The default value of this option is *, which means
that STARTTLS is always advertised. Set it to blank to never advertise;
this is reasonable for systems that want to use TLS only as a client.


If STARTTLS is to be used you
need to set some other options in order to make TLS available.

If a client issues a STARTTLS command and there is some configuration
problem in the server, the command is rejected with a 454 error. If the client
persists in trying to issue SMTP commands, all except QUIT are rejected
with the error

If a STARTTLS command is issued within an existing TLS session, it is
rejected with a 554 error code.


To enable TLS operations on a server, the tls_advertise_hosts option
must be set to match some hosts. The default is * which matches all hosts.

If this is all you do, TLS encryption will be enabled but not authentication –
meaning that the peer has no assurance it is actually you he is talking to.
You gain protection from a passive sniffer listening on the wire but not
from someone able to intercept the communication.

Further protection requires some further configuration at the server end.


To make TLS work you need to set, in the server,

tls_certificate = /some/file/name
tls_privatekey = /some/file/name

Requesting and verifying client certificates

If you want an Exim server to request a certificate when negotiating a TLS
session with a client, you must set either tls_verify_hosts or
tls_try_verify_hosts. You can, of course, set either of them to * to
apply to all TLS connections.

For any host that matches one of these options,
Exim requests a certificate as part of the setup of the TLS session. The
contents of the certificate are verified by comparing it with a list of
expected trust-anchors or certificates.
These may be the system default set (depending on library version),
an explicit file or,
depending on library version, a directory, identified by
tls_verify_certificates.

A file can contain multiple certificates, concatenated end to end. If a
directory is used
(OpenSSL only),
each certificate must be in a separate file, with a name (or a symbolic link)
of the form <hash>.0, where <hash> is a hash value constructed from the
certificate. You can compute the relevant hash by running the command

openssl x509 -hash -noout -in /cert/file

where /cert/file contains a single certificate.


There is no checking of names of the client against the certificate
Subject Name or Subject Alternate Names.

The difference between tls_verify_hosts and tls_try_verify_hosts is
what happens if the client does not supply a certificate, or if the certificate
does not match any of the certificates in the collection named by
tls_verify_certificates.

If the client matches tls_verify_hosts, the
attempt to set up a TLS session is aborted, and the incoming connection is
dropped. If the client matches tls_try_verify_hosts, the (encrypted)

SMTP
session continues. ACLs that run for subsequent SMTP commands can detect the
fact that no certificate was verified, and vary their actions accordingly. For
example, you can insist on a certificate before accepting a message for
relaying, but not when the message is destined for local delivery.

When a client supplies a certificate (whether it verifies or not), the value of
the Distinguished Name of the certificate is made available in the variable
$tls_in_peerdn during subsequent processing of the message.

Because it is often a long text string, it is not included in the log line or
Received: header by default. You can arrange for it to be logged, keyed by
“DN=”, by setting the tls_peerdn log selector, and you can use
received_header_text to change the Received: header. When no
certificate is supplied, $tls_in_peerdn is empty.

Revoked certificates

Certificate issuing authorities issue Certificate Revocation Lists (CRLs) when
certificates are revoked. If you have such a list, you can pass it to an Exim
server using the global option called tls_crl and to an Exim client using
an identically named option for the smtp transport.

In each case, the value
of the option is expanded and must then be the name of a file that contains a
CRL in PEM format.
The downside is that clients have to periodically re-download a potentially huge
file from every certificate authority they know of.

Exim4 и procmail

Одним из поддерживаемых транспортов Exim4 является агент Procmail.

  Замечание:
  В процессе использования Exim4 создалось впечатление (?) что при наличии файла конфигурации /etc/procmailrc (? ~/.procmailrc)
  передачи письма для доставки от MTA к procmail и далее локальному пользователю не происходит.

Для поддержки доставки писем локальным пользователя через Procmail

  строку   require_files = ${local_part}:
  на       require_files = 
  # dpkg-reconfigure exim4-config
    с примерным ответом на вопросы
     Разделить конфигурацию на маленькие файлы?                                    нет

Материал из пингвиньи радостей

Статья о почтовом сервере Exim4

Exim4 это программа, обеспечивающая доставку писем локальным пользователям, а так же их пересылку внешнему SMTP-серверу.Работа Exim4 основана на логических элементах — драйверах: роутерах и транспортах.
Роутер производит операции над адресом и определяет, как дальше пойдет процесс доставки сообщения: оно будет передано транспорту как есть или его адрес будет переписан, или процесс доставки следует прервать.

Транспорты передают копию сообщения из почтовой очереди в указанное место назначения (файл, pipe, удаленный хост, etc).Пример построения почтовой системы на базе Exim4 приведён в статье Почтовая система предприятия.

Настройка exim4 как smtp-сервера

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

Для настройки Exim4 в качестве SMTP-сервера интернет

Настройка exim4 как smtp-шлюза

Для настройки Exim4 в качестве elay-агента для пересылки писем на внешний SMTP-сервер

Настройка exim4 как локального mta-агента

Exim4 обеспечивает доставку почты с рабочей станции локальной сети почтовому серверу.
Это может быть использовано, например при сборке служебных писем с рабочих станций локальной сети на общий административный почтовый ящик.

Для настройки Exim4 в качестве MTA-агента рабочей станции

  # dpkg-reconfigure exim4-config
    с примерным ответом на вопросы
     Общий тип почтовой конфигурации:                                              отправка почты через smarthost; прием по SMTP или через fetchmail
     Почтовое имя системы:                                                         localhost
     IP-адреса, с которых следует ожидать входящие соединения SMTP:                127.0.0.1
     Другие места назначения, для которых должна приниматься почта:                
     IP-адрес или имя хоста являющегося исходящим smarthost:                       ip почтового сервера
     Скрывать локальное почтовое имя в исходящей почте?                            да
     Видимое доменное имя локальных пользователей:                                 доменного имя почтовой системы
     Сокращать количество запросов DNS до минимума (дозвон по требованию)?         нет
     Метод доставки локальной почты:                                               mbox формат в /var/mail/
     Разделить конфигурацию на маленькие файлы?                                    нет

На этом настройка Exim4 завершена и он готов к работе для пересылки писем на почтовый сервер локальной сети.Для использования следует добавить строку MAILTO в файлах конфигурации демона cron, например

Настройка exim4 как сервера локальной сети

Exim4 может выступать в качестве локального MTA-агента и SMTP-сервера и обеспечивать тем самым обмен электронными письмами пользователей локальной сети.

Для настройки Exim4 как локального сервера

  # dpkg-reconfigure exim4-config
    с примерным ответом на вопросы
     Общий тип почтовой конфигурации:                                              доставка только локальной почты
     Почтовое имя системы:                                                         localhost
     IP-адреса, с которых следует ожидать входящие соединения SMTP:                127.0.0.1; 192.168.0.1
     Другие места назначения, для которых должна приниматься почта:                доменного имя почтовой системы
     Сокращать количество запросов DNS до минимума (дозвон по требованию)?         нет
     Метод доставки локальной почты:                                               mbox формат в /var/mail/
     Разделить конфигурацию на маленькие файлы?                                    нет

Установка

В дистрибутиве debian программа представлена в двух модификациях: exim4-daemon-light и exim4-daemon-heavy.
Дальнейшее описание приводиться на примере exim4-daemon-heavy. Пакет присутствует в хранилище пакетовdebian. Для установки пакета

После установки пакет готов к использованию в качестве локального MTA.

Некоторые часто используемые команды

  # dpkg-reconfigure exim4-config                  - (пере)конфигурирование пакета
  # /etc/init.d/exim4 restart                      - перезапуск сервера
  # tail -f /var/log/exim4/mainlog                 - просмотр журнала работы
  # iceweasel /usr/share/doc/exim4-base/README.Debian.html  - документация Exim4

Устранение ошибок

Для устранения ошибки T=remote_smtp_smarthost defer (-53): retry time not reached for any host выполняются команды

  # su
  # cd /var/spool/exim4/db/
  # /etc/init.d/exim4 stop
  # rm *
  # /etc/init.d/exim4 start
  # cat /var/log/exim4/mainlog         - проверка устранения ошибок

Ссылки:

Файлы конфигурации

Для сборки текущей конфигурации сервера

  # dpkg-reconfigure exim4-config
    при этом вводимые параметры записываются в файл /etc/exim4/update-exim4.conf.conf
    а сам exim4 перезапускается.
  # update-exim4.conf

Результат размещается в файл /var/lib/exim4/config.autogenerated.

Похожее:  Статьи - Сеть - Отправка по SMTP с авторизацией

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *