Что такое ssl сертификат для сайта, почты [айти бубен]
SSL (Secure Sockets Layer — уровень защищённых сокетов) — криптографический протокол, который обеспечивает установление безопасного соединения между клиентом и сервером. Впоследствии на основании протокола SSL 3.0 был разработан и принят стандарт RFC, получивший имя TLS.
Протокол обеспечивает конфиденциальность обмена данными между клиентом и сервером, использующими TCP/IP, причем для шифрования используется асимметричный алгоритм с открытым ключом. При шифровании с открытым ключом используется два ключа, причем любой из них может использоваться для шифрования сообщения. Тем самым, если мы используем один ключ для шифрования, то соответственно для расшифровки нужно использовать другой ключ. В такой ситуации мы можем получать защищенные сообщения, публикуя открытый ключ, и храня в тайне секретный ключ.
Протокол SSL состоит из двух под-протоколов: протокол SSL записи и рукопожатия. Протокол SSL записи определяет формат, используемый для передачи данных. Протокол SSL включает рукопожатие с использованием протокола SSL записи для обмена сериями сообщений между сервером и клиентом, во время установления первого соединения.
SSL поддерживает три типа аутентификации: Аутентификация обеих сторон (клиент — сервер), аутентификация сервера с неаутентифицированным клиентом и полная анонимность. Всякий раз, когда сервер аутентифицируется, канал безопасен против атаки человек посредине, но полностью анонимная сессия по своей сути уязвима к такой атаке. Анонимный сервер не может аутентифицировать клиента. Если сервер аутентифицирован, то его сообщение сертификации должно обеспечить верную сертификационную цепочку, ведущую к приемлемому центру сертификации. Проще говоря, аутентифицированный клиент должен предоставить допустимый сертификат серверу. Каждая сторона отвечает за проверку того, что сертификат другой стороны еще не истек и не был отменен. Главная цель процесса обмена ключами — это создание секрета клиента (pre_master_secret), известного только клиенту и серверу. Секрет (pre_master_secret) используется для создания общего секрета (master_secret). Общий секрет необходим для того чтобы создать сообщение для проверки сертификата, ключей шифрования, секрета MAC (message authentication code) и сообщения «finished». При посылке верного сообщения «finished», тем самым стороны докажут что они знают верный секрет (pre_master_secret).
Начиная с 2021 года SSL сертификат должен быть установлен на каждом сайте. Если вы запускаете новый сайт, даже это если это просто информационный сайт или блог, на нем должен быть установлен SSL сертификат. В Google наличие или отсутствие SSL сертификата (протокола HTTPS) является одним из факторов ранжирования вашего сайта.
SSL-сертификат нужен для того, чтобы мошенники не могли перехватить личные данные, которые пользователи вводят у вас на сайте. Личные данные — это логины и пароли от аккаунтов, номера банковских карт, адреса электронной почты и т.д. Это значит, что SSL-сертификат пригодится на сайтах банков, платёжных систем, корпораций, интернет-магазинов, социальных сетей, государственных предприятий, онлайн-форумов и др.
SSL-сертификат выгоден для владельца сайта: так вы подтвердите, что на сайте безопасно вводить личные данные и проявите заботу о клиентах. Если человек переживает, что конфиденциальная информация попадёт не в те руки, он получит дополнительные гарантии. Меньше риска для пользователей, выше репутация компании.
Для работы SSL требуется, чтобы на сервере имелся SSL-сертификат. Технология шифрования не зависит от сертификатов, но они необходимы для того, чтобы гарантировать, что общаться друг с другом будут только те хосты, которые действительно намеревались это сделать. Если каждый из хостов может проверить сертификат другого, то они договариваются о шифровании сеанса. В противном случае они полностью отказываются от шифрования и формируют предупреждение, т.к. отсутствует Аутентичность.
Центр сертификации или Удостоверяющий центр (англ. Certification authority, CA) — это организация или подразделение организации, которая выпускает сертификаты ключей электронной цифровой подписи, это компонент глобальной службы каталогов, отвечающий за управление криптографическими ключами пользователей. Открытые ключи и другая информация о пользователях хранится центрами сертификации в виде цифровых сертификатов, имеющих следующую структуру:
Если вы решили самостоятельно выпускать сертификаты, то первым делом вам нужно создать сертификат вашего собственного центра сертификации. Для этого используем программу CA.pl входящую в поставку Как пользоваться OpenSSL, предварительно отредактируем конфигурационный файл openssl.cnf.
# cp /etc/ssl/openssl.cnf /etc/ssl/openssl.cnf.orig # nano openssl.cnf ... [ CA_default ] dir = ./demoCA # cacert.pem- Это открытый ключ центра сертификации. Он должен находиться в корневых хранилищах ваших хостов, # чтобы они могли проверить родпись в открытом сертификате (например, Postfix). certificate = $dir/cacert.pem # cakey.pem - это секретный ключ центра сертификации. Он должен быть хорошо защищен, # доступ к нему на чтение и запись должен иметь только администратор центра сертификации. private_key = $dir/private/cakey.pem # Время жизни сертификата (по умолчанию 1 год) default_days = 1095 [ req ] # длина RSA ключа (по умолчанию 1024 bit). Длину ключа можете настроить по своему усмотрению. default_bits = 1024 [ req_distinguished_name ] countryName_default = UA 0.organizationName_default = Example INC stateOrProvinceName_default = Example organizationalUnitName_default = Example # В подавляющем большинстве случае должно соответствовать полному доменному имени хоста. # Common Name (eg, your name or your server's hostname) []:OpenVPN-CA commonName = Common Name (eg, YOUR name) commonName_default = mail.example.com ... # /usr/lib/ssl/misc/CA.pl -newca
TLS- шифрование трафика предназначено для обеспечения защиты трафика при взаимодействии клиентов, находящихся за пределами доверенных сетей, с нашим сервером, а также при взаимодействии нашего сервера c другими почтовыми серверами. Для TLS-шифрования трафика мы будем использовать функции OpenSSL и самоподписной доверенный сертификат X.509. Для создания самоподписного доверенного сертификата необходимо выполнить команду:
# mkdir /etc/postfix/certs # cd /etc/postfix/certs # openssl req -new -nodes -x509 -out smtpd.pem -keyout smtpd.pem -days 3650 # chmod 644 smtpd.pem
В процессе выполнения команды на экран будут выданы запросы о вводе таких параметров как: Country Name, State or Province Name; Locality Name; Organization Name; Organizational Unit Name; Common Name; Email Address. Самым важным параметром является значение Common Name. В нашем случае оно должно совпадать с FQDN сервера, по которому клиенты будут обращаться к нему для отправки почты. Чтобы не вводить эти данные вручную каждый раз при создании сертификата можно отредактировать файл /etc/ssl/openssl.cnf.
После генерации сертификата необходимо включить поддержку TLS в файле main.cf:
smtp_use_tls = yes smtpd_use_tls = yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache smtpd_tls_auth_only = yes smtp_tls_note_starttls_offer = yes smtpd_tls_key_file = /etc/postfix/certs/smtpd.pem smtpd_tls_cert_file = /etc/postfix/certs/smtpd.pem smtpd_tls_CAfile = /etc/postfix/certs/smtpd.pem smtpd_tls_CApath = /etc/ssl/certs smtpd_tls_loglevel = 1 smtpd_tls_received_header = yes smtpd_tls_session_cache_timeout = 3600s tls_random_source = dev:/dev/urandom
Указанные параметры имеют следующие значения:
Администраторы сервера выбирают, какой порт будут использовать клиенты для ретрансляции исходящей почты – 25 или 587. Спецификации и многие сервера поддерживают и тот, и другой порты. Хотя некоторые сервера поддерживают порт 465 для безопасного SMTP, но предпочтительнее использовать стандартные порты и ESMTP-команды, если необходима защищенная сессия между клиентом и сервером.
Отличия портов 25, 465, 587. По 465 порту соединение сразу должно открываться по TLS/SSL. С 587 работают как с 25: соединение в открытом виде, а для включения шифрования подаётся команда STARTTLS, если сервер заявил о такой возможности в ответ на EHLO от клиента. smtps (465 порт) фича более старая, starttls – более новая и, понятно, более гибкая.
Для того, чтобы Postfix принимал TLS- соединения на специальный порт (465/SMTPS, а не 25/SMTP), в файле /usr/local/etc/postfix/master.cf необходимо раскомментировать строки:
smtps inet n - n - - smtpd -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes
Не забудьте, что Ваш брандмауэр должен разрешать прохождение TCP-трафика на адреса нужных интерфейсов сервера порт 465, поэтому добавьте соответствующие правила, если они отсутствуют. На этом добавление поддержки TLS-шифрования трафика к Postfix заканчивается. Остается перезапустить Postfix и начать пользоваться аутентификацией SMTP и TLS-шифрованием трафика.
Настраиваем Dovecot
Устанавливаем пакет dovecot-postfix который автоматически установит dovecot и настроит postfix на использование SASL. Также этот пакет настроит dovecot для IMAP, IMAPS, POP3, и POP3S.
apt-get install dovecot-postfix
Приступаем к настройке dovecot.
Создадим пользователя для почты
useradd -d /bin/false vmail
Создадим папку для почты и установим на неё права
mkdir /home/mail && chown vmail:mail /home/mail
Зайдём в папку dovecot
cd /etc/dovecot
На данный момент dovecot не настроен на использование виртуальных пользователей из ldap, а так же пакет dovecot-postfix разделил конфигурацию dovecot на несколько файлов
dovecot.conf auth.d/01-dovecot-postfix.auth conf.d/01-dovecot-postfix.conf
лично мне это не удобно, поэтому я сделал копию текущего dovecot.conf
mv dovecot.conf dovecot.conf.bak1
и создал свой dovecot.conf
> dovecot.conf
следующего содержания
# Поддерживаемые протоколы protocols = imap pop3 imaps pop3s managesieve log_timestamp = "%Y-%m-%d %H:%M:%S " mail_privileged_group = mail # Отключаем plaintext аутентификацию disable_plaintext_auth = yes # Включаем ssl ssl = yes ssl_cert_file = /etc/ssl/certs/mydovecot.pem ssl_key_file = /etc/ssl/private/server.key ssl_ca_file = /etc/ssl/certs/cacert.pem ssl_cipher_list = ALL:!LOW:!SSLv2:ALL:!aNULL:!ADH:!eNULL:!EXP:RC4 RSA: HIGH: MEDIUM # Место нахождения почтовых папок mail_location = maildir:/home/mail/%d/%u # Символы используемые для аутентификации auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@ # Допустимый интервал UID для пользователей first_valid_uid = 1000 last_valid_uid = 50000 # Интервал для группы. Минимальный GID для группы у меня выставлен в 8, т.к. под этим номером у # меня находится группа mail. first_valid_gid = 8 last_valid_gid = 50000 # Пользователь и группа от которых будет работать dovecot с почтой mail_uid = vmail mail_gid = mail # Пути к логам dovecot log_path = /var/log/dovecot.log info_log_path = /var/log/dovecot_info.log # Конфигурация IMAP протокола protocol imap { mail_max_userip_connections = 10 imap_client_workarounds = outlook-idle delay-newmail mail_plugins = quota imap_quota } # Конфигурация POP3 протокола protocol pop3 { pop3_uidl_format = XuXv mail_max_userip_connections = 10 pop3_client_workarounds = outlook-no-nuls oe-ns-eoh mail_plugins = quota } # Конфигурация LDA протокола protocol lda { postmaster_address = postmaster@citramon.donetsk.ua mail_plugins = sieve quota quota_full_tempfail = yes deliver_log_format = msgid=%m: %$ rejection_reason = Your message to <%t> was automatically rejected:%n%r } protocol managesieve { } auth default { # Механизмы аутентификации mechanisms = plain login # База паролей passdb ldap { args = /etc/dovecot/dovecot-ldap.conf } # База пользователей userdb ldap { args = /etc/dovecot/dovecot-ldap.conf } socket listen { master { path = /var/run/dovecot/auth-master mode = 0600 user = vmail group = mail } client { path = /var/spool/postfix/private/dovecot-auth mode = 0660 user = postfix group = postfix } } user = vmail } dict { } # Конфигурация плагинов plugin { sieve=/home/mail/%d/%u/.dovecot.sieve sieve_dir=/home/mail/%d/%u/sieve quota = maildir:User quota quota_rule = *:storage=0B quota_rule2 = Trash:ignore } # Эти опции включают отладочные сообщения, раскоментируйте их # на стадии тестирования, но потом их лучше отключить #mail_debug = yes #verbose_ssl = yes #auth_verbose = yes #auth_debug = yes #auth_debug_passwords = yes
Теперь необходимо настроить подключение к ldap, переименовываем файл настроек ldap
mv dovecot-ldap.conf dovecot-ldap-example.conf
и создаём свой dovecot-ldap.conf
> dovecot-ldap.conf
слеждующего содержания
# Хост на котором работает ldap uris = ldaps://ldap.example.com # Админ ldap и его пароль dn = cn=admin,dc=example,dc=com dnpass = secret # Пути к сертификатам для tls соединения tls_ca_cert_file = /etc/ssl/certs/ mail_server_ldap_ca.pem tls_ca_cert_dir = /etc/ssl/certs tls_cert_file = /etc/ssl/certs/mail_server_ldap_cert.pem tls_key_file = /etc/ssl/private/mail_server_ldap_key.pem # Отладочные сообщения при соединении с ldap, после окончания тестирования лучше отключить #debug_level = -1 # Поиск в ldap будет проходить не от пользователя проходящего аутентификацию auth_bind = no # Версия протокола ldap ldap_version = 3 # Где искать пользователя base = dc=example,dc=com deref = never scope = subtree # Соответствие ldpa и dovecot переменных (слева ldap, справа dovecot) pass_attrs = mail=user,userPassword=password # Фильтр для проверки паролей pass_filter = (&(objectClass=gosaMailAccount)(mail=%u)) # Здесь переменным home, uid, gid присваиваются фиксированные значения, а значение quota_rule # берётся в ldap из параметра gosaMailQuota, 1001 и 8 это uid пользователя vmail и gid группы mail user_attrs = =home=/home/mail/%d/%u, =uid=1001, =gid=8, gosaMailQuota=quota_rule=?:storage=%$B # Фильтр для выборки пользователей user_filter = (&(objectClass=gosaMailAccount)(mail=%u)) # Метод шифрования паролей в ldap default_pass_scheme = MD5
Не знаю с чем это связано но для того чтоб dovecot смог соединиться с ldap на другом сервере по tls, необходимо чтоб на сервере с dovecot присутствовал файл /etc/ldap/ldap.conf в котором находится строка
TLS_CACERT /etc/ssl/certs/mail_server_ldap_ca.pem
в ubuntu 10.04 этот файл присутствует, поэтому просто добавляем в него выше указанную строку.
echo "TLS_CACERT /etc/ssl/certs/mail_server_ldap_ca.pem" >> /etc/ldap/ldap.conf
Перезагружаем dovecot
/etc/init.d/dovecot restart
Настраиваем postfix
Конфигурируем main.cf
# Настраиваем tls и SASL postconf -e 'smtpd_tls_key_file = /etc/ssl/private/server.key' postconf -e 'smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem' postconf -e 'smtpd_tls_CAfile = /etc/ssl/certs/cacert.pem' postconf -e 'smtpd_tls_loglevel = 1' postconf -e 'smtpd_tls_session_cache_timeout = 3600s' postconf -e 'smtp_tls_note_starttls_offer = yes' postconf -e 'smtpd_sasl_local_domain =' # Почта будет находится в каталоге /home/mail/domain/user_mail поэтому значение home_mailbox # должно быть пустым, mailbox_command выполняться не будет поэтому тоже пусто postconf -e 'home_mailbox =' postconf -e 'mailbox_command =' # Домен почтового сервера postconf -e 'mydomain = example.com' postconf -e 'myorigin = $mydomain' # Отклонять команду ETRN postconf -e 'smtpd_etrn_restrictions = reject' # Дополнительные ограничения, применяемые сервером Postfix в контексте команды MAIL FROM postconf -e 'smtpd_sender_restrictions = reject_sender_login_mismatch, reject_unlisted_sender, reject_unknown_sender_domain' # Дополнительные ограничения, применяемые сервером Postfix в контексте команды RCPT TO postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_hostname, reject_non_fqdn_sender, reject_non_fqdn_recipient, reject_unverified_recipient, reject_invalid_hostname, reject_multi_recipient_bounce, reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_unauth_pipelining, reject_unauth_destination' # Настройка виртуальных пользователей, здесь 1001 и 8 это uid и gid пользователя vmail и группы mail postconf -e 'virtual_mailbox_base = /home/mail' postconf -e 'virtual_mailbox_domains = ldap:/etc/postfix/ldap_virtual_domains_maps.cf' postconf -e 'virtual_mailbox_maps = ldap:/etc/postfix/ldap_virtual_mailbox_maps.cf' postconf -e 'virtual_alias_maps = ldap:/etc/postfix/ldap_virtual_alias_maps.cf' postconf -e 'virtual_uid_maps = static:1001' postconf -e 'virtual_gid_maps = static:8' postconf -e 'virtual_minimum_uid = 1000' # Устанавливаем dovecot в качестве транспорта postconf -e 'virtual_transport = dovecot' postconf -e 'mailbox_transport = dovecot' postconf -e 'dovecot_destination_recipient_limit = 1' # Настраиваем квоту postconf -e 'virtual_create_maildirsize = yes' postconf -e 'virtual_maildir_extended = yes' postconf -e 'virtual_mailbox_limit_override = yes' postconf -e 'virtual_overquota_bounce = yes' postconf -e 'virtual_mailbox_limit_maps = ldap:/etc/postfix/ldap_virtual_mailbox_limit_maps.cf' postconf -e 'virtual_maildir_limit_message = Sorry, the users mailbox is full, please try again later.' # Здесь к значениям по умолчанию добавляются $virtual_mailbox_limit_maps и # $smtpd_sender_login_maps postconf -e 'proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $sender_bcc_maps $recipient_bcc_maps $smtp_generic_maps $lmtp_generic_maps $virtual_mailbox_limit_maps $smtpd_sender_login_maps' # Не разрешает отправку сообщений от другого пользователя # Логин пользователя для отправки сообщений и MAIL FROM должны совпадать postconf -e 'smtpd_sender_login_maps = ldap:/etc/postfix/ldap_logins.cf' # Отключаем команду VRFY postconf -e 'disable_vrfy_command = yes' # Ставить исходящие сообщения в очередь postconf -e 'defer_transports=smtp'
Теперь заходим в файл /etc/postfix/master.cf, убираем комментарий со строк
smtps inet n - - - - smtpd -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes -o smtpd_client_restrictions=permit_sasl_authenticated,reject
и добавляем в конец файла строки
dovecot unix - n n - - pipe flags=DRhu user=vmail:mail argv=/usr/lib/dovecot/deliver -d ${recipient}
Осталось создать файлы запросов к LDAP серверу
К сожалению мне не удалось подключиться к LDAP по защищённому соединению ldaps. При попытке подключения по ldaps или start_tls в логах появляются строки
warning: process /usr/lib/postfix/trivial-rewrite pid 1289 killed by signal 6 warning: /usr/lib/postfix/trivial-rewrite: bad command startup — throttling
и postfix наотрез отказывается принимать почту. В связи с эти файлы запросов соединяются с ldap через не защищённое соединение. Если кто решил данную проблему или знает с чем это связано, поделитесь пожалуйста буду очень признателен. Лично я перерыл весь инет но решение так и не нашёл.
И так создаём файлы запросов в папке /etc/postfix
Файл ldap_logins.cf
# адрес LDAP-сервера server_host = ldap://ldap_server_ip/ # где искать людей search_base = ou=Users,dc=example,dc=com # версия протокола version = 3 # какие записи отфильтровывать # брать только тех, у кого создан почтовый акаунт query_filter = (&(objectClass=gosaMailAccount)(|(mail=%s)(gosaMailAlternateAddress=%s))) # требуемый атрибут result_attribute = mail # DN-запись для подключения к LDAP bind_dn = cn=admin,dc=example,dc=com bind_pw = secret
Файл ldap_virtual_alias_maps.cf
# адрес LDAP-сервера server_host = ldap://ldap_server_ip/ # где искать людей search_base = ou=Users,dc=example,dc=com # версия протокола version = 3 # какие записи отфильтровывать # брать только тех, у кого создан почтовый акаунт query_filter = (&(objectClass=gosaMailAccount)(|(mail=%s)(gosaMailAlternateAddress=%s))) # требуемый атрибут - мы забираем mail result_attribute = mail # DN-запись для подключения к LDAP bind_dn = cn=admin,dc=example,dc=com bind_pw = secret
Файл ldap_virtual_domains_maps.cf
# адрес LDAP-сервера server_host = ldap://ldap_server_ip/ # где искать домены search_base = ou=servers,ou=systems,dc=example,dc=com # версия протокола version = 3 # какие записи отфильтровывать # брать только текущий почтовый сервер, ip указывается текущего почтового сервера query_filter = (&(objectClass=goMailServer)(ipHostNumber=192.168.0.2)(postfixMyDestinations=%s)) # требуемый атрибут - мы забираем список доменов result_attribute = postfixMyDestinations # DN-запись для подключения к LDAP bind_dn = cn=admin,dc=example,dc=com bind_pw = secret
Файл ldap_virtual_mailbox_limit_maps.cf
# адрес LDAP-сервера server_host = ldap://ldap_server_ip/ # где искать пользователей search_base = ou=Users,dc=example,dc=com # версия протокола version = 3 # какие записи отфильтровывать # брать только тех, у кого создан почтовый акаунт query_filter = (&(objectClass=gosaMailAccount)(|(mail=%s)(gosaMailAlternateAddress=%s))) # требуемый атрибут - мы забираем квоту result_attribute = gosaMailQuota # DN-запись для подключения к LDAP bind_dn = cn=admin,dc=example,dc=com bind_pw = secret
Файл ldap_virtual_mailbox_maps.cf
# адрес LDAP-сервера server_host = ldap://ldap_server_ip/ # где искать людей search_base = ou=Users,dc=example,dc=com # версия протокола version = 3 # какие записи отфильтровывать # брать только тех, у кого создан почтовый акаунт query_filter = (&(objectClass=gosaMailAccount)(mail=%s)) # требуемый атрибут - мы забираем mail и gosaMailForwardingAddress result_attribute = mail, gosaMailForwardingAddress # по каким путям будет создаваться папка для юзера и подпапки (%d/ будет создаваться подпапка с # доменом вида domain.dom/mail_adress/) result_format = %d/%s/ # DN-запись для подключения к LDAP bind_dn = cn=admin,dc=example,dc=com bind_pw = secret
Перезагружаем postfix
/etc/init.d/postfix restart
Разрешим группе mail писать логи в файлы dovecot.log и dovecot_info.log, если этого не сделать postfix не будет принимать почту
chown root:mail /var/log/dovecot* && chmod 660 /var/log/dovecot*
На этом настройка postfix и dovecot закончена.
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:
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.
Protocol | Usage | Plain text / encrypted session | Encrypted session only |
POP3 | Incoming mail | 110 | 995 |
IMAP | Incoming mail | 143 | 993 |
SMTP | Outgoing mail | 25 | 465 |
Submission | Outgoing mail | 587 |
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)
- Open to edit the file named main.cf (Postfix configuration file). You can usually find it in the /etc/postfix/ directory.
- 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.
Ports 587 (Submission with STARTTLS) and 465 (SMTPS)
- Locate the Postfix’s master.cf file in the /etc/postfix/ directory and open it;
- 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.
Ports 110 (POP3 with STARTTLS), 143 (IMAP with STARTTLS), 993 (IMAPS) and 995 (POP3S)
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.
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:
openssl s_client -connect example.com:[port] -servername example.com
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