Полноценный виртуальный почтовый сервер/SSL-сертификаты

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Complete Virtual Mail Server/SSL Certificates and the translation is 75% complete.
Other languages:


With security and privacy being a increasingly important issue nowadays, Using SSL to secure the server seems like a no-brainer. Apache, Courier-imap and postfix all can be secured using SSL.

Установка SSL

SSL — это зависимость и параметр компиляции для множества пакетов. dev-libs/openssl ключевой компонент и должен быть установлен из-за включенного USE-флага ssl. Если он не был включен до этого, включите и обновите все пакеты с помощью этой команды:

root #emerge --newuse @world


There are a few issues that arise when using multiple domains on a single IP. Apache has solved this issue using SNI that makes it possible to have several certificates on a single IP. Both the browser and the server need to support this however. IMAP (and POP3) nor SMTP really support this. The only real way to support multiple hosts on a single IP is have a certificate, that covers all domains. Not pretty but can work.

Получение SSL-сертификата

There are currently 2 and a half ways to obtain an SSL certificate. Purchase a certificate from one of the reputable providers is an option. Using a self-signed certificate can also be done, though may have implications with warnings on users clients. The half option, which is the recommended option when not using a bought certificate is using a certificate from cacert.org. They are working hard on getting their certificate included into the main browsers and operating systems, but most of all, it is free and gratis.

Самоподписанный сертификат

Большинство приложений предварительно генерируют самоподписанные сертификат и, как правило, затем устанавливают их в каталог /etc/ssl. Новый самоподписанный сертификат легко может быть создан с помощью OpenSSL:

root #mkdir -p /etc/ssl/postfix/
root #cd /etc/ssl/postfix/
root #/etc/ssl/misc/CA.pl -newca
root #/etc/ssl/misc/CA.pl -newreq-nodes
root #/etc/ssl/misc/CA.pl -sign

Это должно было создать три файла: /etc/ssl/postfix/newkey.pem, /etc/ssl/postfix/newreq.pem, /etc/ssl/postfix/newcert.pem, и еще в компанию к ним CA Root сертификат /etc/ssl/postfix/demoCA/cacert.pem. Рекомендуется переименовать их в что-то более логичное.

Подписанный CACert.org

CACert.org offers a simple script to assist with generating SSL certificates. The csr script should be downloaded and executed. In this example, the mail server will be called imap but will have aliases configured in DNS for mail, pop, pop3, pop3s, imaps and foo. More can be added of course as fit. Note that foo was added because that is the name of the system offering the imap service. It is not named foo because the postfix or web or any other server is named foo.

user $sh csr
Private Key and Certificate Signing Request Generator
This script was designed to suit the request format needed by
the CAcert Certificate Authority. www.CAcert.org
Short Hostname (ie. imap big_srv www2): foo
FQDN/CommonName (ie. www.example.com) : foo.example.com
Type SubjectAltNames for the certificate, one per line. Enter a blank line to finish
SubjectAltName: DNS:mail.example.com
SubjectAltName: DNS:smtp.example.com
SubjectAltName: DNS:smtps.example.com
SubjectAltName: DNS:imap.example.com
SubjectAltName: DNS:imaps.example.com
SubjectAltName: DNS:pop.example.com
SubjectAltName: DNS:pop3.example.com
SubjectAltName: DNS:pop3s.example.com
SubjectAltName: DNS:mail.example.net
SubjectAltName: DNS:imap.example.net
SubjectAltName: DNS:imaps.example.net
SubjectAltName: DNS:pop.example.net
SubjectAltName: DNS:pop3.example.net
SubjectAltName: DNS:pop3s.example.net
SubjectAltName: DNS:
Running OpenSSL...
Generating a 2048 bit RSA private key
writing new private key to '/root/imap.example.com_privatekey.pem'
Copy the following Certificate Request and paste into CAcert website to obtain a Certificate.
When you receive your certificate, you 'should' name it something like foo.example.com_server.pem
The Certificate request is also available in /root/foo_csr.pem
The Private Key is stored in /root/foo_privatekey.pem

This has generated a certificate sign request, which can be used by any root CA to sign with, not only CACert.org. In the case of CACert.org however, under Server Certificates there is a link named New which opens an edit box for the above certificate request. The bit including -----BEGIN CERTIFICATE REQUEST----- until, including -----END CERTIFICATE REQUEST----- needs to be pasted into the edit field and then submitted via the submit button. The server will then verify the request and upon that generate the certificate. The certificate then needs to be copied and pasted, including the BEGIN and END markers again into a new file, named foo.example.com_crt.pem. A link to the certificate will also be e-mailed to the e-mail address bound to the ca-cert.org account.

root #cat > foo.example.com_crt.pem

This should leave 3 files, foo.example.com_[privatekey, csr, crt].pem. This will also be the naming convention followed during the rest of this document.

Before requesting a certificate an account must be created on CAcert website. Once logged in, the domain name for the certificate must be registered. After the registration is completed, the certificate request can be pasted in the Server Certificates (New) page.


Настройка Apache уже хорошо описана в другом месте и в конце дает рабочий веб-сервер с поддержкой SSL. Postfixadmin, если он общедоступен, в идеальном случае должен быть защищен и работать только через https. Roundcube или webmail в целом, можно также настроить, чтобы они были защищены SSL, но могут работать и по обычному HTTP.

Roundcube has one nice option for this however, to force all incoming requests over HTTPS. This means that when a users opens http://webmail.example.com, he will get immediately redirected to https://webmail.example.com. If using a proper SSL certificate this is strongly recommended. When using a self-signed certificate, or a CA-cert.org certificate that does not have the root installed to all users, this should remain off however.

ФАЙЛ /var/www/webmail.example.com/htdocs/roundcube/config/main.inc.phpПринудительно https
$rcmail_config['force_https'] = true;


If anything, securing IMAP with SSL is extremely recommended. Using a secure connection for IMAP, means that if the password is sent in plain text, this is still done over the secured IMAP connection so no security issue comes up.

Создание самоподписанного сертификата

Courier-imap comes with two easy scripts to generate self-signed SSL certificates, mkpop3dcert and mkimapdcert. These scripts parse /etc/courier-imap/pop3d.cnf and /etc/courier-imap/imapd.cnf respectively. It may be an idea to first use self-signed certificates and then swap those out for signed certificates as it can make testing a little bit easier. If self-signed certificates are a must, edit the aforementioned files, otherwise the defaults will suffice.

root #mkpop3dcert
root #mkimapdcert
Currently, as mentioned in gentoo bug #251047, config files use an incorrect format and thus an error may occur. See the bug for more details.
The two generated certificates are named /etc/courier-imap/pop3d.pem and /etc/courier-imap/imapd.pem. If self-signed certificates are insisted upon, the default paths in the config files pointing to these files should be checked as mentioned below.

Использование сертификата подписанного CACert.org

Сценарий mkimapdcert создает самоподписанные сертификаты и объединяет их в один файл, так как Courier-imap не использует три раздельных файла, как это делают большинство приложений, а нуждается в специально отформатированном файле.

Файл начинается с закрытого ключа.

Если нет каталога courier-imap в /etc/ssl, его нужно создать вручную.
root #mkdir -p /etc/ssl/courier-imap/
root #cat foo.example.com_privatekey.pem > /etc/ssl/courier-imap/foo.example.com.pem

Затем следует подписанный сертификат:

root #cat foo.example.com_crt.pem >> /etc/ssl/courier-imap/foo.example.com.pem

И в конец, добавляется параметры Диффи-Хеллмана:

root #openssl gendh 1024 >> /etc/ssl/courier-imap/foo.example.com.pem

В конечном итоге содержимое файла должно выглядеть так:

ФАЙЛ /etc/ssl/courier-imap/foo.example.com.pemсертификат imap

Настройка SSL

As noted above, the certificate entails both pop3 as imap hostnames and it is thus assumed pop3 and imap are running on the same IP/host. This is not required however, pop3 could be very well a different machine with the same (not advised) or its own certificate.


ФАЙЛ /etc/courier-imap/pop3d-sslНастройка сертификата

Запуск этого сервера позволит pop3 работать через SSL:

root #/etc/init.d/courier-pop3d-ssl restart


ФАЙЛ /etc/courier-imap/imapd-sslНастройка сертификата

Запуск этого сервера позволит imap работать через SSL:

root #/etc/init.d/courier-imapd-ssl restart

Тестирование SSL

Testing becomes more difficult, as telnet can not be used anymore. The best option is to start up a mail-client such as thunderbird, configure a normal connection first to verify everything works, which should as telnet worked properly before and then enable the SSL option for the account and see if it is still working. The default imap-ssl port is 993. STARTTLS can be checked whether it is enabled only, via telnet, by checking for the STARTTLS Capability.

Некоторые почтовые клиенты не полностью поддерживают реализацию TLS. Чтобы помочь этим почтовым клиентам вы можете изменить значение TLS_STARTTLS_PROTOCOL в файле /etc/courier-imap/imapd-ssl с TLS1 на SSL3.

Если защищенные SSL сервисы работают хорошо, они могут быть добавлены в уровень запуска по умолчанию:

root #rc-update add courier-pop3d-ssl default
root #rc-update add courier-imapd-ssl default
Как упоминалось ранее, добавляйте pop3 только тогда, когда это действительно нужно.

Защита SMTP с помощью SSL

The certificates for use with postfix should be stored in /etc/ssl/postfix/ or if using the same certificates as with courier-imap they should be stored in /etc/ssl/postfix/. If using CACert.org, then its root certificate needs to be used. Gentoo pre-installs the CACert.org root certificate and should be used.

ФАЙЛ /etc/postfix/main.cfНастройка сертификата для SMTP
# SSL Authentication
smtpd_tls_security_level = may
smtpd_tls_auth_only = no
smtpd_tls_loglevel = 3
smtpd_tls_key_file = /etc/ssl/postfix/foo.example.com_privatekey.pem
smtpd_tls_cert_file = /etc/ssl/postfix/foo.example.com_crt.pem
smtpd_tls_CAfile = /etc/ssl/certs/cacert.org_root.pem
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
For debugging purposes smtpd_tls_loglevel has been increased to 3. Also smtpd_tls_auth_only # no means users (and webmail) can still log in insecurely. Putting this option to yes forces all clients to use only authenticated connections.
The CaCert file is renamed in /etc/ssl/certs/cacert.org_root.pem, it used to be named as /etc/ssl/certs/cacert.org.pem.

Now STARTTLS can be used to use an authenticated connection over port 25. SSL/TLS support on port 465 (smtps) however should be enabled as well. Courier-imap did this automatically, postfix needs a change to master.cf:

ФАЙЛ /etc/postfix/master.cfВключение поддержки smtps
smtps     inet  n       -       n       -       -       smtpd
  -o smtpd_tls_wrappermode=yes

Перезапустите postfix, чтобы запустить демонов в защищенном SSL-режиме:

root #/etc/init.d/postfix restart


Telnet can only be minimally used for testing. Actually it can only be used to verify supported options. STARTTLS should be listed as one of the supported options:

user $telnet foo.example.com 25
220 foo.example.com ESMTP Postfix
EHLO example.com
250-SIZE 10240000
250 DSN
221 2.0.0 Bye
Connection closed by foreign host.

To test if all connections work as wanted, a recent version of Thunderbird works best. When adding a new account, Thunderbird will try to connect using STARTTLS on the default port. If that would fail, or if a manual connection is tried, it's possible to use SSL/TLS via the 993 and 465 ports and hit the re-test button. This should allow the account to be created using secure connections.

Защита соединений от-сервера-к-серверу

Postfix может попытаться использовать защищенные соединения для отправки почтовых сообщений на другие сервера SMTP. Хотя не все сервера поддерживают это, но все равно имеет смысл включить это.

ФАЙЛ /etc/postfix/main.cfПопробуем использовать TLS для пересылки почты
# Включить TLS для отправки почты, если это поддерживается другим сервером
smtp_tls_security_level = may
smtp_tls_CApath = /etc/ssl/certs
smtp_tls_loglevel = 3
For debugging purposes smtp_tls_loglevel has been increased to 3. smtp_tls_security_level can be set to "encrypt" to only send mails over TLS connections. But this is not recommended, because many mail servers on the internet do not support TLS at all or are not compatible.

Перезапустите postfix после этого:

root #/etc/init.d/postfix restart

Чтобы проверить что все работает, необходимо выслать письмо на адрес, сервер которого поддерживает TLS. После этого журнал должен содержать примерно такие строки:

user $tail -n 10 /var/log/mail/mailinfo.log
postfix/smtp[15209]: Trusted TLS connection established to mx.example.com[x.x.x.x]:25: TLSv1 with cipher AES256-SHA (256/256 bits)


Ведение журнала можно отключить снова, если все работает хорошо:

ФАЙЛ /etc/postfix/main.cfОтключение журналирования
smtpd_tls_loglevel = 0
smtp_tls_loglevel = 0