Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt

Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt Сертификаты

Почтовый сервер exim

Скопируйте файл SSL-сертификата в папку /etc/exim4/ssl/, файл с ключом – в папку /etc/exim4/ssl/. Установите права доступа для этих файлов:

Почтовый сервер dovecot

Скопируйте файл SSL-сертификата в папку /etc/dovecot/, файл с ключом — в папку /etc/dovecot/private/. Установите права доступа для этих файлов:

Dovecot ssl

По теме:

Linux Dovecot Secure IMAPS / POP3S SSL Server configuration

Бекапим конфиг:

[root@venti /etc] # cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf_07_08_2021

Обновляем /etc/dovecot/dovecot.conf, задаём протокол imaps вместо imap:

...
protocols = imaps
...

И SSL:

...
ssl = yes
ssl_cert_file = /etc/letsencrypt/live/mail.domain.kiev.ua/fullchain.pem
ssl_key_file = /etc/letsencrypt/live/mail.domain.kiev.ua/privkey.pem
...

Перезапускаем:

protocols=imaps is no longer supported – ну, ОК, меняем на imap:

Лог:

Aug  7 23:23:12 venti dovecot: master: Error: service(imap-login): command startup failed, throttling
Aug  7 23:23:12 venti dovecot: imap-login: Fatal: Can’t load ssl_cert: There is no valid PEM certificate. (You probably forgot ‘<‘ from ssl_cert=</etc/letsencrypt/live/
mail.domain.kiev.ua/fullchain.pem)
Aug  7 23:23:12 venti dovecot: imap-login: Fatal: Can’t load ssl_cert: There is no valid PEM certificate. (You probably forgot ‘<‘ from ssl_cert=</etc/letsencrypt/live/
mail.domain.kiev.ua/fullchain.pem)
Aug  7 23:24:12 venti dovecot: imap-login: Fatal: Can’t load ssl_cert: There is no valid PEM certificate. (You probably forgot ‘<‘ from ssl_cert=</etc/letsencrypt/live/
mail.domain.kiev.ua/fullchain.pem)

ОК, добавляем “<“:

...
ssl = yes 
ssl_cert=</etc/letsencrypt/live/mail.domain.kiev.ua/fullchain.pem 
ssl_key=</etc/letsencrypt/live/mail.domain.kiev.ua/privkey.pem 
...

(странный синтаксис, ну да ладно)

Обновляем листенеры – комментим старый и добавляем новый:

Installing and configuring an ssl certificate on postfix/dovecot mail server – helpdesk |

This guide describes the ways to enable the SSL/TLS encryption using a trusted SSL certificate for receiving secured incoming and outgoing connections on a Postfix-Dovecot server.

For testing purposes, a Comodo (now Sectigo) PositiveSSL certificate has been used; however, to secure your mail server, you can purchase any certificate with us as they meet your needs.

The testing was done on the following server stack:

  • Ubuntu 16.04
  • Postfix 3.1.0
  • Dovecot 2.2.22

If you do not have any issued (trusted) certificate yet for the hostname of your mail server, it is necessary to purchase it, generate a CSR needed for activation and once done, activateit.


If you have your certificate issued, you are able to download it from the my-sertif.ru user account or from the email (fulfillment email) received  from the Certificate Authority to the administrative contact email address you have chosen during the activation process.

The first thing you need to do is to upload and concatenate the certificate files on the server. You can follow the actions below:


1. Upload the certificate file yourdomainname.crt to the server along with the CA bundle. Keep in mind that the CA bundle can be either in a single file (example.ca-bundle) or in separate files (COMODORSADomainValidationSecureServerCA.crt, COMODORSAAddTrustCA.crt, AddTrustExternalCARoot.crt as in our case). The following files should be saved in the following way: the certificate and CA bundle files in the /etc/ssl/certs/ directory; the corresponding private key (example_com.key) in the /etc/ssl/private/ folder.

2.Combine the uploaded files into one using one of the commands below:

   2.1. Create a file with the server certificate and CA chain:

  cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/yourdomainname.ca-bundle >> /etc/ssl/certs/certificate.crt

  cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/COMODORSADomainValidationSecureServerCA.crt /etc/ssl/certs/COMODORSAAddTrustCA.crt /etc/ssl/certs/AddTrustExternalCARoot.crt >> /etc/ssl/certs/certificate.crt

  2.2. One file with the combined certificate, CA chain and Private Key can be acceptable for Postfix and  Dovecot. One of the commands below can be used to create it:

  cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/yourdomainname.ca-bundle /etc/ssl/private/yourdomainname.key >> /etc/ssl/certs/certificate_and_key.crt

  cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/COMODORSADomainValidationSecureServerCA.crt /etc/ssl/certs/COMODORSAAddTrustCA.crt /etc/ssl/certs/AddTrustExternalCARoot.crt /etc/ssl/private/yourdomainname.key >> /etc/ssl/certs/certificate_and_key.crt

In order to check the content of the new file in question, run the following command:

Про сертификаты:  Occupational health and safety Management System (OHSMS). Planning an occupation Health, Saftiness Society

  cat /etc/ssl/certs/certificate.crt

or

  cat /etc/ssl/certs/certificate_and_key.crt

It is necessary to check whether there are no excessive white spaces between or inside the PEM-encoded certificate and key blocks in the output.

If you notice such spaces, they can be edited manually – open the file in a text editor like “vi” or “nano” and remove the odd elements.

The editing of Postfix and Dovecot configuration files to enable SSL/TLS on specific ports

The process of sending and receiving mail over the Internet is a complex system of endpoint and intermediary instances (mail server and client software) labeled as mail user agents (MUA), mail submission agents (MSA), mail transfer agents (MTA) and mail delivery agents (MDA) depending on the functions they perform. Normally, an email is passed over each type of the above-mentioned parties, and different transport protocols are used on every step, namely submission protocol, Simple Mail Transfer Protocol (SMTP), Post Office Protocol (POP3) and Internet Message Access Protocol (IMAP).

The below chart shows the use of ports for specific transport protocol execution.

ProtocolUsagePlain text / encrypted sessionEncrypted session only
POP3Incoming mail110995
IMAPIncoming mail143993
SMTPOutgoing mail25465
SubmissionOutgoing mail587

TheOpportunistic TLS approach gives the possibility to use ports 25, 110, 143 and 587 either in the plain text (unencrypted) or secure (encrypted) mode. According to this approach, the STARTTLS command is requested when an existing active plain text session happens.

Technically, using ports 465, 993 and 995 and the way HTTP protocol is used over SSL/TLS are similar: 1) secure ports are detached from their “unsecured” counterparts; 2) any data exchange can be performed after establishing an encrypted session.

NOTE: Although port 465 is not listed as the SMTPS port in the official standards of IANA’s documentation, it is used to serve encrypted outgoing mail traffic by mail server administrators.

Both techniques described above are considered to be used in the Internet mail system nowadays. In order to secure your mail, it is better to install an SSL certificate on every mail port you are planning to use.

The steps below will help you to install your SSL certificate for both mail ports: incoming and outgoing ones:


Port 25 (SMTP with STARTTLS)

  1. Open to edit the file named main.cf (Postfix configuration file). You can usually find it in the /etc/postfix/ directory.
  2. Locate the TLS parameters section in the main.cf fileand make the changes in the following values of certain directives. See the example below:

if  you save the certificate and private key in separate files:

  smtpd_tls_cert_file=/etc/ssl/certs/certificate.crt

  smtpd_tls_key_file=/etc/ssl/private/yourdomainname.key

if  you save the certificate and private key in a single file:

  smtpd_tls_cert_file=/etc/ssl/certs/certificate_and_key.crt

  smtpd_tls_key_file=$smtpd_tls_cert_file

NB: It is necessary to make sure that smtpd_use_tls directive is set to yes:

  smtpd_use_tls=yes

Once done, close the main.cf file and save the changes you made.

Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt

Ports 587 (Submission with STARTTLS) and 465 (SMTPS)

  1. Locate the Postfix’s master.cf file in the /etc/postfix/ directory and open it;
  2. When it is opened, uncomment (or edit if needed) the next lines:

to open and protect port 587:

  submission inet n       –       y       –       –       smtpd

     -o syslog_name=postfix/submission

     -o smtpd_tls_security_level=may

     -o smtpd_sasl_auth_enable=yes

to open and protect port 465:

  smtps     inet  n       –       y       –       –       smtpd

     -o syslog_name=postfix/smtps

     -o smtpd_tls_wrappermode=yes

     -o smtpd_sasl_auth_enable=yes

Now you can close this file.

Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt

Ports 110 (POP3 with STARTTLS), 143 (IMAP with STARTTLS), 993 (IMAPS) and 995 (POP3S)

Про сертификаты:  Об утверждении единой формы сертификата на тип продукции, отвечающей требованиям технического регламента Таможенного союза "О безопасности оборудования, работающего под избыточным давлением" (ТР ТС 032/2013), и правил его оформления от 18 ноября 2013 -

If you need to install an SSL certificate for Dovecot, it is essential to follow the next steps:

1. Open the file named 10-ssl.conf. This file can be usually located in the /etc/dovecot/conf.d/ directory.

2. Edit the following lines:

if  you save the certificate and private key in separate files:

  ssl_cert = </etc/ssl/certs/certificate.crt

  ssl_key = </etc/ssl/private/yourdomainname.key

if  you save the certificate and private key in a single file:

  ssl_cert = </etc/ssl/certs/cert_and_key.crt

  ssl_key = </etc/ssl/certs/cert_and_key.crt

3. Make sure that thessl directive is set to yes:

  ssl = yes

4. When the changes are made, close the 10-ssl.conf file.

If the steps mentioned above are made, the SSL certificate is installed for all incoming ports now.

Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt

Note: If you have the Dovecot version 1.x, the directives for SSL certificates in configuration files may slightly differ:

It is necessary to check whether /etc/dovecot/dovecot.conf has the following line:

  protocols = imap pop3 imaps pop3s

Edit the /etc/dovecot/conf.d/10-ssl.conf file in the following way:

  ssl_disable = no

If  you save the certificate and private key in separate files:

  ssl_cert_file = </etc/ssl/certs/certificate.crt

  ssl_key_file = </etc/ssl/private/yourdomainname.key

 If  you save the certificate and private key in a single file:

  ssl_cert_file = </etc/ssl/certs/cert_and_key.crt

  ssl_key_file = </etc/ssl/certs/cert_and_key.crt

Useful tips:

Below you can find the information regarding some additional settings which can be useful in setting up your mail server’s SSL/TLS handling. For further information, you can refer to Postfix and Dovecotofficial documentation regarding this matter as well.

It is possible to use the STARTTLS port on Postfix in the “wrapper” mode with the smtpd_tls_wrappermode directive. Instead of showing the STARTTLS support and waiting for the request from a remote client, this option helps to run  a secure connection from the very beginning. The following directive should be added to /etc/postfix/master.cf , for instance:

  smtps inet n     –     n     –     –     smtpd

  -o smtpd_tls_wrappermode=yes

On Dovecot, when you try to log in, there is an opportunity to set the ssl directive to required value (ssl=required), which implies forcing the SSL handshake.

In such cases, the password will be sent in a secure way, meanwhile with ssl = yes, email clients are not requested to use SSL/TLS in precedence. Both plaintext and non-plaintext authentication mechanisms can be applied with this setting.

In order to switch off the plaintext authentication mechanism, it is possible to use disable_plaintext_auth directive (/etc/dovecot/conf.d/10-auth.conf):

  disable_plaintext_auth=yes

The following directives on Dovecot (/etc/dovecot/dovecot.conf) can be used for eliminating the ciphers which are better not to be used due to low encryption strength:

  ssl_dh_parameters_length = 2048

  ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL

To exclude certain ciphers or protocols for opportunistic (STARTTLS) or mandatory (regular SSL) encryption, it is possible to use the following directives in /etc/postfix/main.cf and assign the corresponding values to them:

– for mandatory TLS

  smtpd_tls_mandatory_exclude_ciphers = [cipher] smtpd_tls_mandatory_protocols = ![protocol]

– for opportunistic TLS

smtpd_tls_exclude_ciphers = [cipher]

smtpd_tls_protocols = ![protocol]

To set the server side cipher list more preferable over the client-side one, these directives can be used:

– on Dovecot (/etc/dovecot/conf.d/10-ssl.conf)

  ssl_prefer_server_ciphers = yes

– on Postfix (/etc/postfix/main.cf)

  tls_preempt_cipherlist = yes

How to check SSL installation

OpenSSL

The OpenSSL toolkit helps to check the SSL certificate installation on a server both remotely and locally.

In order to check STARTTLS ports, the following command should be run. Replace [port] with the port number and [protocol] with smtp, pop3 or imap value:

openssl s_client -connect example.com:[port] -servername example.com -starttls [protocol]

In order to check non-STARTTLS ports, use the following command:

Про сертификаты:  Полноценный почтовый сервер с iRedMail на Ubuntu — Подручные Записки

openssl s_client -connect example.com:[port] -servername example.com

Email: Exim и Dovecot – настройка SSL/TLS от Let’s Encrypt

How to check your secure connection

In order to check your mail server connectivity over SSL/TLS, the online checkers listed below can be used.

You need to specify the server hostname and port number or an existing email account and run the test.

SSL-Tools:https://ssl-tools.net/mailservers  

CheckTLS:https://www.checktls.com/index.html

MXToolbox: https://mxtoolbox.com/diagnostic.aspx

High-Tech Bridge: https://www.htbridge.com/ssl

Ispmanager

Зайдите в панель управления ISPmanager, перейдите в раздел «Домены» — «Почтовые домены» и нажмите «SSL-сертификат» на панели инструментов.

Измените значения ключей на ключи вашего сертификата и нажмите «ОК».

Let’s encrypt ssl для exim

Загружаем LE клиент:

Openssl verify tls

Проверяем с помощью openssl:

[root@venti /etc] # openssl s_client -connect mail.domain.kiev.ua:465 -tls1 -servername venti.domain.kiev.ua

CONNECTED(00000003)

depth=0 C = UA, L = Kiev, O = Default Company Ltd, CN = mail.domain.kiev.ua, emailAddress = user@domain.kiev.ua

verify error:num=18:self signed certificate

verify return:1

depth=0 C = UA, L = Kiev, O = Default Company Ltd, CN = mail.domain.kiev.ua, emailAddress = user@domain.kiev.ua

verify return:1

Certificate chain

0 s:/C=UA/L=Kiev/O=Default Company Ltd/CN=mail.domain.kiev.ua/emailAddress=user@domain.kiev.ua

i:/C=UA/L=Kiev/O=Default Company Ltd/CN=mail.domain.kiev.ua/emailAddress=user@domain.kiev.ua

Server certificate

—–BEGIN CERTIFICATE—–

MIIFzTCCA7WgAwIBAgIJAI3/E0l5HkHEMA0GCSqGSIb3DQEBCwUAMH0xCzAJBgNV

6hpCEGJj8XmSPg QMbGq8rNDY5HmqXZV6grpyqtDGgWVUitn3my4ZHEPtIDDzmU

ag==

—–END CERTIFICATE—–

subject=/C=UA/L=Kiev/O=Default Company Ltd/CN=mail.domain.kiev.ua/emailAddress=user@domain.kiev.ua

issuer=/C=UA/L=Kiev/O=Default Company Ltd/CN=mail.domain.kiev.ua/emailAddress=user@domain.kiev.ua

No client certificate CA names sent

Server Temp Key: ECDH, prime256v1, 256 bits

SSL handshake has read 2446 bytes and written 319 bytes

New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-SHA

SSL-Session:

Protocol  : TLSv1

TLS session ticket lifetime hint: 200 (seconds)

TLS session ticket:

Timeout   : 7200 (sec)

Verify return code: 18 (self signed certificate)

220 mail.domain.org.ua, ESMTP EXIM 4.89

Verify return code: 18 (self signed certificate) – ОК, тут проблема понятна.

Настройка ssl для почты

Статья давно не обновлялась, поэтому информация могла устареть.

Настройка ssl/tls в apache, posfix, dovecot на примере сертификатов от globalsign. | записки админа

В случае с купленным сертификатом в вашем распоряжении будет четыре сертификата: приватный сертификат (server.key), публичный сертификат (server_cert.pem), сертификат промежуточного центра сертификации (intermediate_CA.pem), и рут-сертификат центра сертификации (root_CA.pem). Названия файлов вплоть до расширения могут быть любыми, главное содержимое.

Для того чтобы удаленный клиент мог запустить проверку сертификата сервера, выпущенные сертификаты центра сертификации (CA) должны быть ему доступны. Для этого необходимо включить в сертификат сервера (публичный сертификат) необходимые сертификаты центра сертификации. Например, создайте сертификат сервера server.pem командой “cat server_cert.pem intermediate_CA.pem root_CA.pem
> server.pem”. Порядок следования сертификатов важен.

В результате вы получаете два сертификата: приватный (server.key) и публичный (server.pem), которые мы укажем в соответствующих строках конфигурационных файлов postfix и dovecot. Не забудьте выставить права доступа (права – 0400, владелец – root) к файлу server.key.

POSTFIX

DOVECOT

APACHE

Проверка правильности настроек:
openssl s_client -connect your.domain.ru:imaps
openssl s_client -connect your.domain.ru:smtps
openssl s_client -connect your.domain.ru:https
Смотрим последнюю строчку: Verify return code: 0 (ok)

Сервер dovecot | русскоязычная документация по ubuntu

Dovecot – это агент доставки почты (MDA), написанный с учетом в первую очередь безопасности. Он поддерживает основные форматы почтовых ящиков: mbox и Maildir. В этом разделе рассматривается как его настроить в качестве imap или pop3 сервера.

Чтобы настроить dovecot вам потребуется отредактировать файл /etc/dovecot/dovecot.conf. Вы можете выбрать какой протокол использовать. Это может быть pop3, pop3s (безопасный pop3), imap или imaps (безопасный imap). Описание этих протоколов находится за пределами рассматриваемых вопросов данного руководства. Для дополнительной информации обратитесь к статьям Wikipedia по POP3 и IMAP.

IMAPS и POP3S более безопасные чем обычные IMAP и POP3, поскольку используют SSL шифрование для соединения. Как только вы выберете протокол, исправьте следующую строку в файле /etc/dovecot/dovecot.conf:

protocols = pop3 pop3s imap imaps

Далее выберите формат почтового ящика, который вы собираетесь использовать. Dovecot поддерживает форматы maildir и mbox. Они оба имеют свои преимущества, которые обсуждаются на сайте Dovecot.

Выбрав тип почтового ящика, измените в файле

/etc/dovecot/dovecot.conf

/etc/dovecot/conf.d/10-mail.conf следующую строку:

mail_location = maildir:~/Maildir # (для maildir)

или

mail_location = mbox:~/mail:INBOX=/var/spool/mail/%u # (для mbox)

Вам будет надо настроить ваш MTA (транспортного агента) для передачи входящих сообщений на данный формат ящика, если он отличается от того, который вы настроили.

Настроив dovecot, перезапустите сервис dovecot чтобы проверить свои установки:

sudo /etc/init.d/dovecot restart

Если вы разрешили imap или pop3, вы можете попробовать подключиться с помощью команд

telnet localhost pop3

или

telnet localhost imap2

Если вы увидите что-то, похожее на следующий код, установка успешно завершена:

bhuvan@rainbow:~$ telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.
 OK Dovecot ready.

Оцените статью
Мой сертификат
Добавить комментарий