postfixPostfixのTLSサポート - Postfix解説文書

原文(英語)はこちら


PostfixのTLSサポートでできること

トランスポート層セキュリティー(TLS、かつてはSSLと呼ばれていた)により、証明書に基づく認証と暗号化されたセッションを使うことができるようになります。暗号化されたセッションではSMTPメールやSASL認証で転送される情報を保護することができます。

注意:PostfixでTSLサポートを有効化すると、メールを暗号化しリモートのSMTPクライアントやサーバを認証する機能が得られるだけではありません。何十万行ものOpenSSLライブラリコードも有効化することになります。OpenSSLがWietse自身のコードと同じぐらいの慎重さで書かれていると仮定すれば、1000行ごとに1つずつPostfixに新たなバグが発生することになります。

この文書で扱うトピック:

そして最後に、せっかちな人のために:

Postfix TLSサポートのしくみ

下図は、Postfix TLS構造の主要要素とそれらの関係を示しています。 番号がついた色付きのボックスは、Postfixデーモンプログラムを、その他の色付きボックスはストレージ要素を示しています。

この図にはtlsproxy(8)サーバとpostscreen(8)サーバは示していません。これらもsmtpd(8)と同じような方法でTLSを利用します。

ネットワーク->
smtpd(8)
 
<---シード----

<-鍵/証明書->

tlsmgr(8)
 
----シード--->

<-鍵/証明書->

smtp(8)
 
->ネットワーク
/
/
|
|
\
\
smtpd
セッション
鍵キャッシュ
PRNG
状態
ファイル
smtp
セッション
鍵キャッシュ

SMTPサーバ固有の設定

この節で扱うトピック:

サーバ側の証明書と秘密鍵の設定

TLSを使用するためには、一般的にPostfix SMTPサーバは証明書と秘密鍵が必要です。どちらも「PEM」形式である必要があります。秘密鍵は暗号化されていてはいけません。つまり、パスワード無しで鍵にアクセスできなければなりません。証明書と秘密鍵は同じファイルにあってもかまいませんが、その場合、証明書ファイルは「root」が所有し、他のユーザーからは読めないようにする必要があります。鍵が別に保存されている場合、このアクセス制限が必要なのは鍵ファイルのみで、証明書ファイルは「誰でも読み取り可能」であってもかまいません。

よく知られたパブリック認証局によって署名された証明書を持っていない、インターネット上で公開されているMXホストは、自己署名またはプライベート認証局によって署名された証明書を生成し、ほとんどのクライアントに提示できるように準備する必要があります。リモートSMTPクライアントは通常、自己署名証明書を検証することはできませんが、クライアントがPostfixまたは同様のソフトウェアを実行していない限り、サーバ証明書を必要とするTLS暗号化についてのみやり取りを行います。

インターネット上では公開されていないMXホストについて、Postfixは証明書なしの構成に対応しています。これは、一般的なSMTPクライアントではサポートされていない匿名TLS暗号を使うことを意味します。TLSハンドシェイクに失敗しても平文にフォールバックしないクライアントもあるため、証明書なしのPostfix SMTPサーバは、一部のTLS対応クライアントからのメールを受信することができなくなります。偶発的に証明書なしの構成となるのを避けるため、管理者が「smtpd_tls_cert_file = none」を明示的に設定したときのみ、証明書なしの動作を可能にするようPostfixはつくられています。これにより、新しいPostfix SMTPサーバの構成で、誤って証明書なしのTLSを有効にすることがなくなります。

TLS 1.3において、サーバ証明書は設定任意ではないことに注意してください。証明書なしで動作させるには、「smtpd_tls_protocols」に「<=TLSv1.2」(Postfix < 3.6 では「! TLSv1.3」)を設定しTLS 1.3プロトコルを無効にしなければなりませんし、おそらく「smtpd_tls_mandatory_protocols」にもこの設定含めていなければならないでしょう。代わりに、証明書チェーンを設定する方が簡単です。証明書なしの運用は推奨されません。

RSA、DSA、ECDSA(Postfix ≥ 2.6)の証明書に対応しています。ほとんどのサイトでは、RSA証明書しかありません。この場合、リモートSMTPクライアントとネゴシエートされた暗号スイートによって、どの証明書が使用されるかが決定されます。DNSゾーンが署名されており、DANE TLSA(RFC 6698RFC 7671RFC 7672)レコードを公開する場合、これらは構成されたすべての証明書チェーンと一致する必要があります。ベストプラクティスは「3 1 1」の証明書アソシエーションを公開することであるため、各公開鍵証明書ダイジェストに一致するように、個別のTLSAレコードを作成します。

サーバ証明書ファイルをつくる

Postfix SMTP サーバ証明書を検証するには、リモートのSMTPクライアントが、TLS ハンドシェイクまたは公開鍵基盤経由で発行された認証局(CA)証明書を受け取る必要があります。つまり、Postfix サーバの公開鍵証明書ファイルには、最初にサーバ証明書、次に発行した認証局証明書を含める必要があります(ボトムアップの順)。Postfix SMTPサーバ証明書は、SSL サーバ証明書として使用できる必要があるため、「openssl verify -purpose sslserver ...」のテストをパスする必要があります。

以下の例で、サーバ証明書ファイルを作成する方法を示します。ここでは、「server.example.com」の証明書が「intermediate CA」から発行され、この認証局は「root CA」から発行された証明書を持つものと仮定しています。

TLSA レコードで使用する証明書またはその公開キーのダイジェストを計算する方法については、main.cfsmtpd_tls_fingerprint_digest パラメータに関する文書を参照してください。

新しいキーまたは証明書を生成するときは、サーバー上で新しいキーまたは証明書を実際に適用する前に、新しいダイジェストを含む追加の TLSA レコードを公開する必要があります。 古いダイジェストのみを含む TLSA RRset が DNS キャッシュから期限切れになるまで、十分な時間を確保する必要があります。最も安全な方法は、以前の TLSA RRset の DNSSEC 署名が期限切れになるまで待ってから、更新された TLSA RRset で公開された新しいキーを使用するようにサーバーを切り替えることです。新しい証明書信頼チェーンと秘密キーが有効になったら、DNS を再度更新して、TLSA RRset から古いダイジェストを削除する必要があります。

Postfix SMTPサーバが1つ以上のルートCAによって発行されたリモートSMTPクライアント証明書を受け入れるようにしたい場合、ルート証明書を$smtpd_tls_CAfileに追加するか、または$smtpd_tls_CApathディレクトリにインストールしてください。

サーバ証明書と鍵ファイルを設定する

例:Postfix ≥ 3.4ですべてが一つのファイルに記されている場合。鍵で始まり、その鍵に対応する証明書と追加の発行者証明書がすぐ後に続いた1つまたは複数のチェーンファイル。1つのファイルに複数の(鍵、証明書、[証明書チェイン])のセットをアルゴリズムごとに記すことができます。一般的には、各アルゴリズムのチェーンをそれぞれのファイルに保存する方が簡単です。しかし、OpenSSL 1.1.1 では、RSA、ECDSA、ED25519、ED448、および旧式の DSA のそれぞれについて、最大 5つのチェーンを配置することができます。

    # Postfix ≥ 3.4. 好ましい設定条件。各ファイルは秘密鍵で始まり、
    # その後にその鍵に対応する証明書、その証明書を発行した中間認証局証明書
    # が続きます。DANE信用アンカーとして発行したときはルート認証局の証明書も
    # 必要になるでしょう。
    #
    smtpd_tls_chain_files =
        /etc/postfix/rsa.pem,
        /etc/postfix/ecdsa.pem,
        /etc/postfix/ed25519.pem,
        /etc/postfix/ed448.pem

また、鍵は証明書とは別に保存することもできます。この場合も、それぞれを対応する証明書チェーンの前に記載する必要があります。鍵とそれに対応する証明書チェインを別々のファイルに保存することは推奨しません。なぜなら、鍵のロールオーバー時に競合状態が発生しやすく、複数のファイルを都度細かく更新する方法がないためです。

    # Postfix ≥ 3.4.
    # 鍵とそれに対応する証明書を別々に保存するのは推奨しません。
    smtpd_tls_chain_files =
        /etc/postfix/rsakey.pem,
        /etc/postfix/rsacerts.pem,
        /etc/postfix/ecdsakey.pem,
        /etc/postfix/ecdsacerts.pem

以下の例は、Postfix 3.3以前の旧式アルゴリズムに特化した設定です。Postfix ≤ 3.3 では、鍵を証明書と同じファイルに保存しても、ファイルが二度読みされるため、鍵のロールオーバー時に(短時間の)競合状態が発生することがあります。Postfix ≥ 3.4 では、鍵と証明書が同じファイルにある場合、競合は回避されますが、 上に示した新しい "smtpd_tls_chain_files" インターフェイスを使用する必要があります。

The below examples show the legacy algorithm-specific configurations for Postfix 3.3 and older. With Postfix ≤ 3.3, even if the key is stored in the same file as the certificate, the file is read twice and a (brief) race condition still exists during key rollover. While Postfix ≥ 3.4 avoids the race when the key and certificate are in the same file, you should use the new "smtpd_tls_chain_files" interface shown above.

RSA鍵と証明書の例:

/etc/postfix/main.cf:
    smtpd_tls_cert_file = /etc/postfix/server.pem
    smtpd_tls_key_file = $smtpd_tls_cert_file

DSAの場合:

/etc/postfix/main.cf:
    smtpd_tls_dcert_file = /etc/postfix/server-dsa.pem
    smtpd_tls_dkey_file = $smtpd_tls_dcert_file

ECDSAの場合(Postfix ≥ 2.6 + OpenSSL ≥ 1.0.0):

/etc/postfix/main.cf:
    # Some clients will not be ECDSA capable, so you will likely still need
    # an RSA certificate and private key.
    #
    smtpd_tls_eccert_file = /etc/postfix/server-ecdsa.pem
    smtpd_tls_eckey_file = $smtpd_tls_eccert_file

TLS without certificates for servers serving exclusively anonymous-cipher capable clients:

/etc/postfix/main.cf:
    # Not recommended: breaks TLS 1.3 and clients that don't support
    # anonymous cipher suites.
    smtpd_tls_cert_file = none

To verify a remote SMTP client certificate, the Postfix SMTP server needs to trust the certificates of the issuing Certification Authorities. These certificates in "PEM" format can be stored in a single $smtpd_tls_CAfile or in multiple files, one CA per file in the $smtpd_tls_CApath directory. If you use a directory, don't forget to create the necessary "hash" links with:

# $OPENSSL_HOME/bin/c_rehash /path/to/directory 

$smtpd_tls_CAfileには、信頼できる認証局(CA)のCA証明書が1つまたは複数含まれています。このファイルは、Postfixが任意設定によるchroot jailへ入る前に(ルート権限で)開かれるので、chroot jail環境の内部からアクセスできる必要はありません。

Additional trusted CAs can be specified via the $smtpd_tls_CApath directory, in which case the certificates are read (with $mail_owner privileges) from the files in the directory when the information is needed. Thus, the $smtpd_tls_CApath directory needs to be accessible inside the optional chroot jail.

When you configure the Postfix SMTP server to request client certificates, the DNs of Certification Authorities in $smtpd_tls_CAfile are sent to the client, in order to allow it to choose an identity signed by a CA you trust. If no $smtpd_tls_CAfile is specified, no preferred CA list is sent, and the client is free to choose an identity signed by any CA. Many clients use a fixed identity regardless of the preferred CA list and you may be able to reduce TLS negotiation overhead by installing client CA certificates mostly or only in $smtpd_tls_CApath. In the latter case you need not specify a $smtpd_tls_CAfile.

Note, that unless client certificates are used to allow greater access to TLS authenticated clients, it is best to not ask for client certificates at all, as in addition to increased overhead some clients (notably in some cases qmail) are unable to complete the TLS handshake when client certificates are requested.

例:

/etc/postfix/main.cf:
    smtpd_tls_CAfile = /etc/postfix/CAcert.pem
    smtpd_tls_CApath = /etc/postfix/certs

サーバ側の転送セキュリティ設定

転送の秘匿化を実現する暗号を最大限に活用したい場合は、FORWARD_SECRECY_READMEGetting started節を参照してください。この文書には、Postfixの転送の秘匿化サポートに関するすべての情報がまとまっており、転送の秘匿化とは何か、どのようにして設定を変更すればいいのか、Postfixが転送の秘匿化で暗号を使用したときに何が期待できるのかなどが書かれています。

サーバ側のTLS動作ログ記録

Postfix SMTPサーバがTLSを使って行った動作に関してさらなる情報を得るには、ログレベルを0から4まで上げることができます。各ログレベルには、より低いログレベルで記録される情報も含まれます。

レベル Postfix 2.9以降 2.9より前のバージョン
0 TLSを使った動作の記録は行わない
1 Log only a summary message on TLS handshake completion — no logging of client certificate trust-chain verification errors if client certificate verification is not required. Log the summary message, peer certificate summary information and unconditionally log trust-chain verification errors.
2 Also log levels during TLS negotiation.
3 Also log hexadecimal and ASCII dump of TLS negotiation process.
4 Also log hexadecimal and ASCII dump of complete transmission after STARTTLS.

ログレベル3は問題が起きたときにのみ使ってください。ログレベル4の使用は極力避けてください。

例:

/etc/postfix/main.cf:
    smtpd_tls_loglevel = 0

To include information about the protocol and cipher used as well as the client and issuer CommonName into the "Received:" message header, set the smtpd_tls_received_header variable to true. The default is no, as the information is not necessarily authentic. Only information recorded at the final destination is reliable, since the headers may be changed by intermediate servers.

例:

/etc/postfix/main.cf:
    smtpd_tls_received_header = yes

Postfix SMTPサーバでTLSを有効化する

Postfix SMTP サーバは初期状態でTLSが無効になっており、平文通信をするPostfixとの差はないように見えます。TLSを使うには「smtpd_tls_security_level = may」を指定し明示的に有効化してください。

例:

/etc/postfix/main.cf:
    smtpd_tls_security_level = may

これにより、Postfix SMTPサーバはリモートのSMTPクライアントに対してSTARTTLSが使えること通知しますが、クライアントがTLS暗号を使用することを要求する訳ではありません。

注意:非特権ユーザーが「sendmail -bs」を実行した場合、Postfix SMTP サーバの秘密鍵にアクセスする権限がないため、STARTTLSを使うことはできません。これは想定内の動作です。

smtpd_tls_security_level = encrypt」と設定すれば、Postfix SMTP サーバはSTARTTLSが使えることを通知し、TLS 暗号化されていないメールを受け付けないようにして、TLS 使用を強制することができますRFC 2487 によると、一般に公開されている Postfix SMTP サーバの場合、この設定を「適用してはいけません」。このオプションは初期状態では off になっており、めったに使うべきではありません。

例:

/etc/postfix/main.cf:
    smtpd_tls_security_level = encrypt

TLSは、STARTTLSが使用可能であることを通知し、リモートSMTPクライアントがTLSサービスを要求して来るのを待つ代わりに、サーバが常にTLSを使用する「ラッパー」モードでも使われます。Some clients, namely Outlook [Express] prefer the "wrapper" mode. This is true for OE (Win32 < 5.0 and Win32 >=5.0 when run on a port<>25 and OE (5.01 Mac on all ports).

このモードをmain.cfで設定することは極力避けてください。この機能を使いたい場合は、master.cf で特別なポートを有効にし、smtpd(8) のコマンドラインオプションとして「-o smtpd_tls_wrappermode=yes」(注意:= の前後に空白をを入れないこと)を指定してください。かつてこの機能のためにポート465(smtps)が選ばれたことがあります。

例:

/etc/postfix/master.cf:
    smtps    inet  n       -       n       -       -       smtpd
      -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes

クライアントの証明書検証

To receive a remote SMTP client certificate, the Postfix SMTP server must explicitly ask for one (any contents of $smtpd_tls_CAfile are also sent to the client as a hint for choosing a certificate from a suitable CA). Unfortunately, Netscape clients will either complain if no matching client certificate is available or will offer the user client a list of certificates to choose from. Additionally some MTAs (notably some versions of qmail) are unable to complete TLS negotiation when client certificates are requested, and abort the SMTP session. So this option is "off" by default. You will however need the certificate if you want to use certificate based relaying with, for example, the permit_tls_clientcerts feature. A server that wants client certificates must first present its own certificate. While Postfix by default offers anonymous ciphers to remote SMTP clients, these are automatically suppressed when the Postfix SMTP server is configured to ask for client certificates.

Example:

/etc/postfix/main.cf:
    smtpd_tls_ask_ccert = yes
    smtpd_tls_security_level = may

When TLS is enforced you may also decide to REQUIRE a remote SMTP client certificate for all TLS connections, by setting "smtpd_tls_req_ccert = yes". This feature implies "smtpd_tls_ask_ccert = yes". When TLS is not enforced, "smtpd_tls_req_ccert = yes" is ignored and a warning is logged.

Example:

/etc/postfix/main.cf:
    smtpd_tls_req_ccert = yes
    smtpd_tls_security_level = encrypt

The client certificate verification depth is specified with the main.cf smtpd_tls_ccert_verifydepth parameter. The default verification depth is 9 (the OpenSSL default), for compatibility with Postfix versions before 2.5 where smtpd_tls_ccert_verifydepth was ignored. When you configure trust in a root CA, it is not necessary to explicitly trust intermediary CAs signed by the root CA, unless $smtpd_tls_ccert_verifydepth is less than the number of CAs in the certificate chain for the clients of interest. With a verify depth of 1 you can only verify certificates directly signed by a trusted CA, and all trusted intermediary CAs need to be configured explicitly. With a verify depth of 2 you can verify clients signed by a root CA or a direct intermediary CA (so long as the client is correctly configured to supply its intermediate CA certificate).

Example:

/etc/postfix/main.cf:
    smtpd_tls_ccert_verifydepth = 2

AUTH over TLSだけのサポート

Sending AUTH data over an unencrypted channel poses a security risk. When TLS layer encryption is required ("smtpd_tls_security_level = encrypt"), the Postfix SMTP server will announce and accept AUTH only after the TLS layer has been activated with STARTTLS. When TLS layer encryption is optional ("smtpd_tls_security_level = may"), it may however still be useful to only offer AUTH when TLS is active. To maintain compatibility with non-TLS clients, the default is to accept AUTH without encryption. In order to change this behavior, set "smtpd_tls_auth_only = yes".

Example:

/etc/postfix/main.cf:
    smtpd_tls_auth_only = no

サーバ側のTLSセッションキャッシュ

The Postfix SMTP server and the remote SMTP client negotiate a session, which takes some computer time and network bandwidth. SSL protocol versions other than SSLv2 support resumption of cached sessions. Not only is this more CPU and bandwidth efficient, it also reduces latency as only one network round-trip is used to resume a session while it takes two round-trips to create a session from scratch.

Since Postfix uses multiple smtpd(8) service processes, an in-memory cache is not sufficient for session re-use. Clients store at most one cached session per server and are very unlikely to repeatedly connect to the same server process. Thus session caching in the Postfix SMTP server generally requires a shared cache (an alternative available with Postfix ≥ 2.11 is described below).

To share the session information between multiple smtpd(8) processes, a session cache database is used. You can specify any database type that can store objects of several kbytes and that supports the sequence operator. DBM databases are not suitable because they can only store small objects. The cache is maintained by the tlsmgr(8) process, so there is no problem with concurrent access. Session caching is highly recommended, because the cost of repeatedly negotiating TLS session keys is high.

Starting with Postfix 2.11, linked with a compatible OpenSSL library (at least 0.9.8h, preferably 1.0.0 or later) the Postfix SMTP server supports RFC 5077 TLS session resumption without server-side state when the remote SMTP client also supports RFC 5077. The session is encrypted by the server in a session ticket returned to client for storage. When a client sends a valid session ticket, the server decrypts it and resumes the session, provided neither the ticket nor the session have expired. This makes it possible to resume cached sessions without allocating space for a shared database on the server. Consequently, for Postfix ≥ 2.11 the smtpd_tls_session_cache_database parameter should generally be left empty. Session caching can be disabled by setting the session cache timeout to zero, otherwise the timeout must be at least 2 minutes and at most 100 days.

Note, session tickets can only be negotiated if the client disables SSLv2 and does not use the legacy SSLv2 compatible HELLO message. This is true by default with the Postfix ≥ 2.6 SMTP client.

Example:

/etc/postfix/main.cf:
    smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache

Note: as of version 2.5, Postfix no longer uses root privileges when opening this file. The file should now be stored under the Postfix-owned data_directory. As a migration aid, an attempt to open the file under a non-Postfix directory is redirected to the Postfix-owned data_directory, and a warning is logged.

Cached Postfix SMTP server session information expires after a certain amount of time. Postfix/TLS does not use the OpenSSL default of 300s, but a longer time of 3600sec (=1 hour). RFC 2246 recommends a maximum of 24 hours.

Example:

/etc/postfix/main.cf:
    smtpd_tls_session_cache_timeout = 3600s

As of Postfix 2.11 this setting cannot exceed 100 days. If set ≤ 0, session caching is disabled. If set to a positive value less than 2 minutes, the minimum value of 2 minutes is used instead.

When the Postfix SMTP server does not save TLS sessions to an external cache database, client-side session caching is unlikely to be useful. To reduce waste of client resources, the Postfix SMTP server can be configured to not issue TLS session ids. By default the Postfix SMTP server always issues TLS session ids. This works around known interoperability issues with some MUAs, and prevents possible interoperability issues with other MTAs.

Example:

    smtpd_tls_always_issue_session_ids = no

サーバアクセス制御

PostfixのTLSサポートにより、Postfix SMTPサーバアクセス制御のための追加機能が3つ導入されました。

permit_tls_clientcerts

Allow the remote SMTP client request if the client certificate fingerprint or certificate public key fingerprint (Postfix 2.9 and later) is listed in the client certificate table (see relay_clientcerts discussion below).

permit_tls_all_clientcerts

Allow the remote SMTP client request if the client certificate passes trust chain verification. Useful with private-label CAs that only issue certificates to trusted clients (and not otherwise).

check_ccert_access type:table

Use the remote SMTP client certificate fingerprint or public key fingerprint (Postfix 2.9 and later) as the lookup key for the specified access(5) table.

The digest algorithm used to compute the client certificate fingerprints is specified with the main.cf smtpd_tls_fingerprint_digest parameter. The default algorithm is sha256 with Postfix ≥ 3.6 and the compatibility_level set to 3.6 or higher. With Postfix ≤ 3.5, the default algorithm is md5. The best-practice algorithm is now sha256. Recent advances in hash function cryptanalysis have led to md5 and sha1 being deprecated in favor of sha256. However, as long as there are no known "second pre-image" attacks against the older algorithms, their use in this context, though not recommended, is still likely safe.

The permit_tls_all_clientcerts feature must be used with caution, because it can result in too many access permissions. Use this feature only if a special CA issues the client certificates, and only if this CA is listed as a trusted CA. If other CAs are trusted, any owner of a valid client certificate would be authorized. The permit_tls_all_clientcerts feature can be practical for a specially created email relay server.

It is however recommended to stay with the permit_tls_clientcerts feature and list all certificates via $relay_clientcerts, as permit_tls_all_clientcerts does not permit any control when a certificate must no longer be used (e.g. an employee leaving).

Example:

# With Postfix 2.10 and later, the mail relay policy is
# preferably specified under smtpd_relay_restrictions.
/etc/postfix/main.cf:
    smtpd_relay_restrictions = 
        permit_mynetworks
        permit_tls_clientcerts 
        reject_unauth_destination
# Older configurations combine relay control and spam control under
# smtpd_recipient_restrictions. To use this example with Postfix ≥
# 2.10 specify "smtpd_relay_restrictions=".
/etc/postfix/main.cf:
    smtpd_recipient_restrictions = 
        permit_mynetworks
        permit_tls_clientcerts 
        reject_unauth_destination
        ...other rules...

Example: Postfix lookup tables are in the form of (key, value) pairs. Since we only need the key, the value can be chosen freely, e.g. the name of the user or host:

/etc/postfix/main.cf:
    relay_clientcerts = hash:/etc/postfix/relay_clientcerts

/etc/postfix/relay_clientcerts:
    D7:04:2F:A7:0B:8C:A5:21:FA:31:77:E1:41:8A:EE:80 lutzpc.at.home

To extract the public key fingerprint from an X.509 certificate, you need to extract the public key from the certificate and compute the appropriate digest of its DER (ASN.1) encoding. With OpenSSL the "-pubkey" option of the "x509" command extracts the public key always in "PEM" format. We pipe the result to another OpenSSL command that converts the key to DER and then to the "dgst" command to compute the fingerprint.

Example:

$ openssl x509 -in cert.pem -noout -pubkey |
    openssl pkey -pubin -outform DER |
    openssl dgst -sha256 -c
(stdin)= 64:3f:1f:f6:e5:1e:d4:2a:...:8b:fc:09:1a:61:98:b5:bc:7c:60:58

サーバ側のcipher制御

The Postfix SMTP server supports 5 distinct cipher grades as specified by the smtpd_tls_mandatory_ciphers configuration parameter, which determines the minimum cipher grade with mandatory TLS encryption. The default minimum cipher grade for mandatory TLS is "medium" which is essentially 128-bit encryption or better. The smtpd_tls_ciphers parameter (Postfix ≥ 2.6) controls the minimum cipher grade used with opportunistic TLS. Here, the default minimum cipher grade is "medium" for Postfix releases after the middle of 2015, "export" for older Postfix releases. With Postfix < 2.6, the minimum opportunistic TLS cipher grade is always "export".

By default anonymous ciphers are enabled. They are automatically disabled when remote SMTP client certificates are requested. If clients are expected to always verify the Postfix SMTP server certificate you may want to disable anonymous ciphers by setting "smtpd_tls_mandatory_exclude_ciphers = aNULL" or "smtpd_tls_exclude_ciphers = aNULL", as appropriate. One can't force a remote SMTP client to check the server certificate, so excluding anonymous ciphers is generally unnecessary.

With mandatory and opportunistic TLS encryption, the Postfix SMTP server by default disables SSLv2 and SSLv3 with Postfix releases after the middle of 2015; older releases only disable SSLv2 for mandatory TLS. The mandatory TLS protocol list is specified via the smtpd_tls_mandatory_protocols configuration parameter. The smtpd_tls_protocols parameter (Postfix ≥ 2.6) controls the TLS protocols used with opportunistic TLS.

Note that the OpenSSL library only supports protocol exclusion (not inclusion). For this reason, Postfix can exclude only protocols that are known at the time the Postfix software is written. If new protocols are added to the OpenSSL library, they cannot be excluded without corresponding changes to the Postfix source code.

For a server that is not a public Internet MX host, Postfix supports configurations with no server certificates that use only the anonymous ciphers. This is enabled by explicitly setting "smtpd_tls_cert_file = none" and not specifying an smtpd_tls_dcert_file or smtpd_tls_eccert_file. Such configurations may not interoperate with some clients, and require that TLSv1.3 be explicitly disabled. Therefore, they are not recommended, it is better and simpler to just configure a suitable certificate.

Example, MSA that requires TLSv1.2 or higher, with high grade ciphers:

/etc/postfix/main.cf:
    smtpd_tls_cert_file = /etc/postfix/cert.pem
    smtpd_tls_key_file = /etc/postfix/key.pem
    smtpd_tls_mandatory_ciphers = high
    smtpd_tls_mandatory_exclude_ciphers = aNULL, MD5
    smtpd_tls_security_level = encrypt
    # Preferred syntax with Postfix ≥ 3.6:
    smtpd_tls_mandatory_protocols = >=TLSv1.2
    # Legacy syntax:
    smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1

With Postfix ≥ 3.4, specify instead a single file that holds the key followed by the corresponding certificate and any associated issuing certificates, leaving the "smtpd_tls_cert_file" and "smtpd_tls_key_file" and related DSA and ECDSA parameters empty.

/etc/postfix/main.cf:
    smtpd_tls_chain_files = /etc/postfix/rsachain.pem
    smtpd_tls_cert_file =
    smtpd_tls_key_file =
    ...

If you want to take maximal advantage of ciphers that offer forward secrecy see the Getting started section of FORWARD_SECRECY_README. The full document conveniently presents all information about Postfix forward secrecy support in one place: what forward secrecy is, how to tweak settings, and what you can expect to see when Postfix uses ciphers with forward secrecy.

Postfix 2.8 and later, in combination with OpenSSL 0.9.7 and later allows TLS servers to preempt the TLS client's cipher-suite preference list. This is possible only with SSLv3 and later, as in SSLv2 the client chooses the cipher-suite from a list supplied by the server.

By default, the OpenSSL server selects the client's most preferred cipher-suite that the server supports. With SSLv3 and later, the server may choose its own most preferred cipher-suite that is supported (offered) by the client. Setting "tls_preempt_cipherlist = yes" enables server cipher-suite preferences. The default OpenSSL behavior applies with "tls_preempt_cipherlist = no".

While server cipher-suite selection may in some cases lead to a more secure or performant cipher-suite choice, there is some risk of interoperability issues. In the past, some SSL clients have listed lower priority ciphers that they did not implement correctly. If the server chooses a cipher that the client prefers less, it may select a cipher whose client implementation is flawed. Most notably Windows 2003 Microsoft Exchange servers have flawed implementations of DES-CBC3-SHA, which OpenSSL considers stronger than RC4-SHA. Enabling server cipher-suite selection may create interoperability issues with Windows 2003 Microsoft Exchange clients.

さまざまなサーバの制御

The smtpd_starttls_timeout parameter limits the time of Postfix SMTP server write and read operations during TLS startup and shutdown handshake procedures.

Example:

/etc/postfix/main.cf:
    smtpd_starttls_timeout = 300s

With Postfix 2.8 and later, the tls_disable_workarounds parameter specifies a list or bit-mask of default-enabled OpenSSL bug work-arounds to disable. This may be necessary if one of the work-arounds enabled by default in OpenSSL proves to pose a security risk, or introduces an unexpected interoperability issue. The list of enabled bug work-arounds is OpenSSL-release-specific. See the tls_disable_workarounds parameter documentation for the list of supported values.

Example:

/etc/postfix/main.cf:
    tls_disable_workarounds = 0xFFFFFFFF
    tls_disable_workarounds = CVE-2010-4180

With Postfix ≥ 2.11, the tls_ssl_options parameter specifies a list or bit-mask of OpenSSL options to enable. Specify one or more of the named options below, or a hexadecimal bitmask of options found in the ssl.h file corresponding to the run-time OpenSSL library. While it may be reasonable to turn off all bug workarounds (see above), it is not a good idea to attempt to turn on all features. See the tls_ssl_options parameter documentation for the list of supported values.

Example:

/etc/postfix/main.cf:
    tls_ssl_options = no_ticket, no_compression

You should only enable features via the hexadecimal mask when the need to control the feature is critical (to deal with a new vulnerability or a serious interoperability problem). Postfix DOES NOT promise backwards compatible behavior with respect to the mask bits. A feature enabled via the mask in one release may be enabled by other means in a later release, and the mask bit will then be ignored. Therefore, use of the hexadecimal mask is only a temporary measure until a new Postfix or OpenSSL release provides a better solution.

SMTPクライアント固有の設定

Topics covered in this section:

Configuring TLS in the SMTP/LMTP client

Similar to the Postfix SMTP server, the Postfix SMTP/LMTP client implements multiple TLS security levels. These levels are described in more detail in the sections that follow.

none
No TLS.
may
Opportunistic TLS.
encrypt
Mandatory TLS encryption.
dane
Opportunistic DANE TLS.
dane-only
Mandatory DANE TLS.
fingerprint
Certificate fingerprint verification.
verify
Mandatory server certificate verification.
secure
Secure-channel TLS.

LMTP配信エージェントにおけるTLSサポート

The smtp(8) and lmtp(8) delivery agents are implemented by a single dual-purpose program. Specifically, all the TLS features described below apply equally to SMTP and LMTP, after replacing the "smtp_" prefix of the each parameter name with "lmtp_".

The Postfix LMTP delivery agent can communicate with LMTP servers listening on UNIX-domain sockets. When server certificate verification is enabled and the server is listening on a UNIX-domain socket, the $myhostname parameter is used to set the TLS verification nexthop and hostname.

NOTE: Opportunistic encryption of LMTP traffic over UNIX-domain sockets or loopback TCP connections is futile. TLS is only useful in this context when it is mandatory, typically to allow at least one of the server or the client to authenticate the other. The "null" cipher grade may be appropriate in this context, when available on both client and server. The "null" ciphers provide authentication without encryption.

No TLS encryption

At the "none" TLS security level, TLS encryption is disabled. This is the default security level, and can be configured explicitly by setting "smtp_tls_security_level = none". For LMTP, use the corresponding "lmtp_" parameter.

Per-destination settings may override this default setting, in which case TLS is used selectively, only with destinations explicitly configured for TLS.

You can disable TLS for a subset of destinations, while leaving it enabled for the rest. With the Postfix TLS policy table, specify the "none" security level.

Opportunistic TLS

At the "may" TLS security level, TLS encryption is opportunistic. The SMTP transaction is encrypted if the STARTTLS ESMTP feature is supported by the server. Otherwise, messages are sent in the clear. Opportunistic TLS can be configured by setting "smtp_tls_security_level = may". For LMTP, use the corresponding "lmtp_" parameter.

The "smtp_tls_ciphers" and "smtp_tls_protocols" configuration parameters (Postfix ≥ 2.6) provide control over the cipher grade and protocols used with opportunistic TLS. With earlier Postfix releases, opportunistic TLS always uses the cipher grade "export" and enables all protocols.

With opportunistic TLS, mail delivery continues even if the server certificate is untrusted or bears the wrong name. When the TLS handshake fails for an opportunistic TLS session, rather than give up on mail delivery, the Postfix SMTP client retries the transaction with TLS disabled. Trying an unencrypted connection makes it possible to deliver mail to sites with non-interoperable server TLS implementations.

Opportunistic encryption is never used for LMTP over UNIX-domain sockets. The communications channel is already confidential without TLS, so the only potential benefit of TLS is authentication. Do not configure opportunistic TLS for LMTP deliveries over UNIX-domain sockets. Only configure TLS for LMTP over UNIX-domain sockets at the encrypt security level or higher. Attempts to configure opportunistic encryption of LMTP sessions will be ignored with a warning written to the mail logs.

You can enable opportunistic TLS just for selected destinations. With the Postfix TLS policy table, specify the "may" security level.

This is the most common security level for TLS protected SMTP sessions, stronger security is not generally available and, if needed, is typically only configured on a per-destination basis. See the section on TLS limitations above.

Example:

/etc/postfix/main.cf:
    smtp_tls_security_level = may

Mandatory TLS encryption

At the "encrypt" TLS security level, messages are sent only over TLS encrypted sessions. The SMTP transaction is aborted unless the STARTTLS ESMTP feature is supported by the remote SMTP server. If no suitable servers are found, the message will be deferred. Mandatory TLS encryption can be configured by setting "smtp_tls_security_level = encrypt". Even though TLS encryption is always used, mail delivery continues even if the server certificate is untrusted or bears the wrong name. For LMTP, use the corresponding "lmtp_" parameter.

At this security level and higher, the smtp_tls_mandatory_protocols and smtp_tls_mandatory_ciphers configuration parameters determine the list of sufficiently secure SSL protocol versions and the minimum cipher strength. If the protocol or cipher requirements are not met, the mail transaction is aborted. The documentation for these parameters includes useful interoperability and security guidelines.

Despite the potential for eliminating passive eavesdropping attacks, mandatory TLS encryption is not viable as a default security level for mail delivery to the public Internet. Some MX hosts do not support TLS at all, and some of those that do have broken implementations. On a host that delivers mail to the Internet, you should not configure mandatory TLS encryption as the default security level.

You can enable mandatory TLS encryption just for specific destinations. With the Postfix TLS policy table, specify the "encrypt" security level.

Examples:

In the example below, traffic to example.com and its sub-domains via the corresponding MX hosts always uses TLS. The SSLv2 protocol will be disabled (the default setting of smtp_tls_mandatory_protocols excludes SSLv2+3). Only high- or medium-strength (i.e. 128 bit or better) ciphers will be used by default for all "encrypt" security level sessions.

/etc/postfix/main.cf:
    smtp_tls_policy_maps = hash:/etc/postfix/tls_policy

/etc/postfix/tls_policy:
    example.com       encrypt
    .example.com      encrypt

In the next example, secure message submission is configured via the MSA "[example.net]:587". TLS sessions are encrypted without authentication, because this MSA does not possess an acceptable certificate. This MSA is known to be capable of "TLSv1" and "high" grade ciphers, so these are selected via the policy table.

Note: the policy table lookup key is the verbatim next-hop specification from the recipient domain, transport(5) table or relayhost parameter, with any enclosing square brackets and optional port. Take care to be consistent: the suffixes ":smtp" or ":25" or no port suffix result in different policy table lookup keys, even though they are functionally equivalent nexthop specifications. Use at most one of these forms for all destinations. Below, the policy table has multiple keys, just in case the transport table entries are not specified consistently.

/etc/postfix/main.cf:
    smtp_tls_policy_maps = hash:/etc/postfix/tls_policy

/etc/services:
    submission      587/tcp         msa             # mail message submission

/etc/postfix/tls_policy:
    # Postfix ≥ 3.6 "protocols" syntax
    [example.net]:587 encrypt protocols=>=TLSv1.2 ciphers=high
    # Legacy "protocols" syntax
    [example.net]:msa encrypt protocols=!SSLv2:!SSLv3 ciphers=high

DANE TLS authentication.

The Postfix SMTP client supports two TLS security levels based on DANE TLSA (RFC 6698, RFC 7671, RFC 7672) records. The opportunistic "dane" level and the mandatory "dane-only" level.

The "dane" level is a stronger form of opportunistic TLS that is resistant to man in the middle and downgrade attacks when the destination domain uses DNSSEC to publish DANE TLSA records for its MX hosts. If a remote SMTP server has "usable" (see section 3 of RFC 7672) DANE TLSA records, the server connection will be authenticated. When DANE authentication fails, there is no fallback to unauthenticated or plaintext delivery.

If TLSA records are published for a given remote SMTP server (implying TLS support), but are all "unusable" due to unsupported parameters or malformed data, the Postfix SMTP client will use mandatory unauthenticated TLS. Otherwise, when no TLSA records are published, the Postfix SMTP client behavior is the same as with may.

TLSA records must be published in DNSSEC validated DNS zones. Any TLSA records in DNS zones not protected via DNSSEC are ignored. The Postfix SMTP client will not look for TLSA records associated with MX hosts whose "A" or "AAAA" records lie in an "insecure" DNS zone. Such lookups have been observed to cause interoperability issues with poorly implemented DNS servers, and are in any case not expected to ever yield "secure" results, since that would require a very unlikely DLV DNS trust anchor configured between the host record and the associated "_25._tcp" child TLSA record.

The "dane-only" level is a form of secure-channel TLS based on the DANE PKI. If "usable" TLSA records are present these are used to authenticate the remote SMTP server. Otherwise, or when server certificate verification fails, delivery via the server in question tempfails.

At both security levels, the TLS policy for the destination is obtained via TLSA records validated with DNSSEC. For TLSA policy to be in effect, the destination domain's containing DNS zone must be signed and the Postfix SMTP client's operating system must be configured to send its DNS queries to a recursive DNS nameserver that is able to validate the signed records. Each MX host's DNS zone needs to also be signed, and needs to publish DANE TLSA (see section 3 of RFC 7672) records that specify how that MX host's TLS certificate is to be verified.

TLSA records do not preempt the normal SMTP MX host selection algorithm, if some MX hosts support TLSA and others do not, TLS security will vary from delivery to delivery. It is up to the domain owner to configure their MX hosts and their DNS sensibly. To configure the Postfix SMTP client for DNSSEC lookups see the documentation for the smtp_dns_support_level main.cf parameter. The tls_dane_digests parameter controls the list of supported digests.

As explained in section 3 of RFC 7672, certificate usages "0" and "1", which are intended to "constrain" existing Web-PKI trust, are not supported with MTA-to-MTA SMTP. Rather, TLSA records with usages "0" and "1" are treated as "unusable".

The Postfix SMTP client supports only certificate usages "2" and "3". Experimental support for silently mapping certificate usage "1" to "3" has been withdrawn starting with Postfix 3.2.

When usable TLSA records are obtained for the remote SMTP server the Postfix SMTP client sends the SNI TLS extension in its SSL client hello message. This may help the remote SMTP server live up to its promise to provide a certificate that matches its TLSA records.

For purposes of protocol and cipher selection, the "dane" security level is treated like a "mandatory" TLS security level, and weak ciphers and protocols are disabled. Since DANE authenticates server certificates the "aNULL" cipher-suites are transparently excluded at this level, no need to configure this manually. RFC 7672 (DANE) TLS authentication is available with Postfix 2.11 and later.

When a DANE TLSA record specifies a trust-anchor (TA) certificate (that is an issuing CA), the strategy used to verify the peername of the server certificate is unconditionally "nexthop, hostname". Both the nexthop domain and the hostname obtained from the DNSSEC-validated MX lookup are safe from forgery and the server certificate must contain at least one of these names.

When a DANE TLSA record specifies an end-entity (EE) certificate, (that is the actual server certificate), as with the fingerprint security level below, no name checks or certificate expiration checks are applied. The server certificate (or its public key) either matches the DANE record or not. Server administrators should publish such EE records in preference to all other types.

The pre-requisites for DANE support in the Postfix SMTP client are:

The above client pre-requisites do not apply to the Postfix SMTP server. It will support DANE provided it supports TLSv1 and its TLSA records are published in a DNSSEC signed zone. To receive DANE secured mail for multiple domains, use the same hostname to add the server to each domain's MX records. The Postfix SMTP server supports SNI (Postfix 3.4 and later), configured with tls_server_sni_maps.

Note: The Postfix SMTP client's internal stub DNS resolver is DNSSEC-aware, but it does not itself validate DNSSEC records, rather it delegates DNSSEC validation to the operating system's configured recursive DNS nameserver. The Postfix DNS client relies on a secure channel to the resolver's cache for DNSSEC integrity, but does not support TSIG to protect the transmission channel between itself and the nameserver. Therefore, it is strongly recommended (DANE security guarantee void otherwise) that each MTA run a local DNSSEC-validating recursive resolver ("unbound" from nlnetlabs.nl is a reasonable choice) listening on the loopback interface, and that the system be configured to use only this local nameserver. The local nameserver may forward queries to an upstream recursive resolver on another host if desired.

Note: When the operating system's recursive nameserver is not local, enabling EDNS0 expanded DNS packet sizes and turning on the DNSSEC "DO" bit in the DNS request and/or the new DNSSEC-specific records returned in the nameserver's replies may cause problems with older or buggy firewall and DNS server implementations. Therefore, Postfix does not enable DNSSEC by default. Since MX lookups happen before the security level is determined, DANE support is disabled for all destinations unless you set "smtp_dns_support_level = dnssec". To enable DNSSEC lookups selectively, define a new dedicated transport with a "-o smtp_dns_support_level=dnssec" override in master.cf and route selected domains to that transport. If DNSSEC proves to be sufficiently reliable for these domains, you can enable it for all destinations by changing the global smtp_dns_support_level in main.cf.

Example: "dane" security for selected destinations, with opportunistic TLS by default. This is the recommended configuration for early adopters.

main.cf:
    indexed = ${default_database_type}:${config_directory}/
    #
    # default: Opportunistic TLS with no DNSSEC lookups.
    #
    smtp_tls_security_level = may
    smtp_dns_support_level = enabled
    #
    # Per-destination TLS policy
    #
    smtp_tls_policy_maps = ${indexed}tls_policy
    #
    # default_transport = smtp, but some destinations are special:
    #
    transport_maps = ${indexed}transport
transport:
    example.com dane
    example.org dane
tls_policy:
    example.com dane-only
master.cf:
    dane       unix  -       -       n       -       -       smtp
      -o smtp_dns_support_level=dnssec
      -o smtp_tls_security_level=dane

Certificate fingerprint verification

At the fingerprint security level, no trusted Certification Authorities are used or required. The certificate trust chain, expiration date, etc., are not checked. Instead, the smtp_tls_fingerprint_cert_match parameter or the "match" attribute in the policy table lists the remote SMTP server certificate fingerprint or public key fingerprint. Certificate fingerprint verification is available with Postfix 2.5 and later, public-key fingerprint support is available with Postfix 2.9 and later.

If certificate fingerprints are exchanged securely, this is the strongest, and least scalable security level. The administrator needs to securely collect the fingerprints of the X.509 certificates of each peer server, store them into a local file, and update this local file whenever the peer server's public certificate changes. If public key fingerprints are used in place of fingerprints of the entire certificate, the fingerprints remain valid even after the certificate is renewed, provided that the same public/private keys are used to obtain the new certificate.

Fingerprint verification may be feasible for an SMTP "VPN" connecting a small number of branch offices over the Internet, or for secure connections to a central mail hub. It works poorly if the remote SMTP server is managed by a third party, and its public certificate changes periodically without prior coordination with the verifying site.

The digest algorithm used to calculate the fingerprint is selected by the smtp_tls_fingerprint_digest parameter. In the policy table multiple fingerprints can be combined with a "|" delimiter in a single match attribute, or multiple match attributes can be employed. The ":" character is not used as a delimiter as it occurs between each pair of fingerprint (hexadecimal) digits.

The default algorithm is sha256 with Postfix ≥ 3.6 and the compatibility_level set to 3.6 or higher; with Postfix ≤ 3.5, the default algorithm is md5. The best-practice algorithm is now sha256. Recent advances in hash function cryptanalysis have led to md5 and sha1 being deprecated in favor of sha256. However, as long as there are no known "second pre-image" attacks against the older algorithms, their use in this context, though not recommended, is still likely safe.

Example: fingerprint TLS security with an internal mailhub. Two matching fingerprints are listed. The relayhost may be multiple physical hosts behind a load-balancer, each with its own private/public key and self-signed certificate. Alternatively, a single relayhost may be in the process of switching from one set of private/public keys to another, and both keys are trusted just prior to the transition.

    relayhost = [mailhub.example.com]
    smtp_tls_security_level = fingerprint
    smtp_tls_fingerprint_digest = sha256
    smtp_tls_fingerprint_cert_match =
        51:e9:af:2e:1e:40:1f:de:64:...:30:35:2d:09:16:31:5a:eb:82:76
        b6:b4:72:34:e2:59:cd:fb:c2:...:63:0d:4d:cc:2c:7d:84:de:e6:2f

Example: Certificate fingerprint verification with selected destinations. As in the example above, we show two matching fingerprints:

/etc/postfix/main.cf:
    smtp_tls_policy_maps = hash:/etc/postfix/tls_policy
    smtp_tls_fingerprint_digest = sha256
/etc/postfix/tls_policy:
    example.com fingerprint
        match=51:e9:af:2e:1e:40:1f:de:...:35:2d:09:16:31:5a:eb:82:76
        match=b6:b4:72:34:e2:59:cd:fb:...:0d:4d:cc:2c:7d:84:de:e6:2f

To extract the public key fingerprint from an X.509 certificate, you need to extract the public key from the certificate and compute the appropriate digest of its DER (ASN.1) encoding. With OpenSSL the "-pubkey" option of the "x509" command extracts the public key always in "PEM" format. We pipe the result to another OpenSSL command that converts the key to DER and then to the "dgst" command to compute the fingerprint.

Example:

$ openssl x509 -in cert.pem -noout -pubkey |
    openssl pkey -pubin -outform DER |
    openssl dgst -sha256 -c
(stdin)= 64:3f:1f:f6:e5:1e:d4:2a:56:...:09:1a:61:98:b5:bc:7c:60:58

Mandatory server certificate verification

At the verify TLS security level, messages are sent only over TLS encrypted sessions if the remote SMTP server certificate is valid (not expired or revoked, and signed by a trusted Certification Authority) and where the server certificate name matches a known pattern. Mandatory server certificate verification can be configured by setting "smtp_tls_security_level = verify". The smtp_tls_verify_cert_match parameter can override the default "hostname" certificate name matching strategy. Fine-tuning the matching strategy is generally only appropriate for secure-channel destinations. For LMTP use the corresponding "lmtp_" parameters.

If the server certificate chain is trusted (see smtp_tls_CAfile and smtp_tls_CApath), any DNS names in the SubjectAlternativeName certificate extension are used to verify the remote SMTP server name. If no DNS names are specified, the certificate CommonName is checked. If you want mandatory encryption without server certificate verification, see above.

With Postfix ≥ 2.11 the "smtp_tls_trust_anchor_file" parameter or more typically the corresponding per-destination "tafile" attribute optionally modifies trust chain verification. If the parameter is not empty the root CAs in CAfile and CApath are no longer trusted. Rather, the Postfix SMTP client will only trust certificate-chains signed by one of the trust-anchors contained in the chosen files. The specified trust-anchor certificates and public keys are not subject to expiration, and need not be (self-signed) root CAs. They may, if desired, be intermediate certificates. Therefore, these certificates also may be found "in the middle" of the trust chain presented by the remote SMTP server, and any untrusted issuing parent certificates will be ignored.

Despite the potential for eliminating "man-in-the-middle" and other attacks, mandatory certificate trust chain and subject name verification is not viable as a default Internet mail delivery policy. Some MX hosts do not support TLS at all, and a significant portion of TLS-enabled MTAs use self-signed certificates, or certificates that are signed by a private Certification Authority. On a machine that delivers mail to the Internet, you should not configure mandatory server certificate verification as a default policy.

Mandatory server certificate verification as a default security level may be appropriate if you know that you will only connect to servers that support RFC 2487 and that present verifiable server certificates. An example would be a client that sends all email to a central mailhub that offers the necessary STARTTLS support. In such cases, you can often use a secure-channel configuration instead.

You can enable mandatory server certificate verification just for specific destinations. With the Postfix TLS policy table, specify the "verify" security level.

Example:

In this example, the Postfix SMTP client encrypts all traffic to the example.com domain. The peer hostname is verified, but verification is vulnerable to DNS response forgery. Mail transmission to example.com recipients uses "high" grade ciphers.

/etc/postfix/main.cf:
    indexed = ${default_database_type}:${config_directory}/
    smtp_tls_CAfile = ${config_directory}/CAfile.pem
    smtp_tls_policy_maps = ${indexed}tls_policy

/etc/postfix/tls_policy:
    example.com       verify ciphers=high

Secure server certificate verification

At the secure TLS security level, messages are sent only over secure-channel TLS sessions where DNS forgery resistant server certificate verification succeeds. If no suitable servers are found, the message will be deferred. Postfix secure-channels can be configured by setting "smtp_tls_security_level = secure". The smtp_tls_secure_cert_match parameter can override the default "nexthop, dot-nexthop" certificate match strategy. For LMTP, use the corresponding "lmtp_" parameters.

If the server certificate chain is trusted (see smtp_tls_CAfile and smtp_tls_CApath), any DNS names in the SubjectAlternativeName certificate extension are used to verify the remote SMTP server name. If no DNS names are specified, the CommonName is checked. If you want mandatory encryption without server certificate verification, see above.

With Postfix ≥ 2.11 the "smtp_tls_trust_anchor_file" parameter or more typically the corresponding per-destination "tafile" attribute optionally modifies trust chain verification. If the parameter is not empty the root CAs in CAfile and CApath are no longer trusted. Rather, the Postfix SMTP client will only trust certificate-chains signed by one of the trust-anchors contained in the chosen files. The specified trust-anchor certificates and public keys are not subject to expiration, and need not be (self-signed) root CAs. They may, if desired, be intermediate certificates. Therefore, these certificates also may be found "in the middle" of the trust chain presented by the remote SMTP server, and any untrusted issuing parent certificates will be ignored.

Despite the potential for eliminating "man-in-the-middle" and other attacks, mandatory secure server certificate verification is not viable as a default Internet mail delivery policy. Some MX hosts do not support TLS at all, and a significant portion of TLS-enabled MTAs use self-signed certificates, or certificates that are signed by a private Certification Authority. On a machine that delivers mail to the Internet, you should not configure secure TLS verification as a default policy.

Mandatory secure server certificate verification as a default security level may be appropriate if you know that you will only connect to servers that support RFC 2487 and that present verifiable server certificates. An example would be a client that sends all email to a central mailhub that offers the necessary STARTTLS support.

You can enable secure TLS verification just for specific destinations. With the Postfix TLS policy table, specify the "secure" security level.

Examples:

Client-side TLS activity logging

To get additional information about Postfix SMTP client TLS activity you can increase the loglevel from 0..4. Each logging level also includes the information that is logged at a lower logging level.

Level Postfix 2.9 and later Earlier releases.
0 Disable logging of TLS activity.
1 Log only a summary message on TLS handshake completion — no logging of remote SMTP server certificate trust-chain verification errors if server certificate verification is not required. Log the summary message and unconditionally log trust-chain verification errors.
2 Also log levels during TLS negotiation.
3 Also log hexadecimal and ASCII dump of TLS negotiation process.
4 Also log hexadecimal and ASCII dump of complete transmission after STARTTLS.

Example:

/etc/postfix/main.cf:
    smtp_tls_loglevel = 0

Client-side certificate and private key configuration

Do not configure Postfix SMTP client certificates unless you must present client TLS certificates to one or more servers. Client certificates are not usually needed, and can cause problems in configurations that work well without them. The recommended setting is to let the defaults stand:

    smtp_tls_cert_file =
    smtp_tls_dcert_file =
    smtp_tls_key_file =
    smtp_tls_dkey_file =
    # Postfix ≥ 2.6
    smtp_tls_eccert_file =
    smtp_tls_eckey_file =
    # Postfix ≥ 3.4
    smtp_tls_chain_files =

The best way to use the default settings is to comment out the above parameters in main.cf if present.

During TLS startup negotiation the Postfix SMTP client may present a certificate to the remote SMTP server. Browsers typically let the user select among the certificates that match the CA names indicated by the remote SMTP server. The Postfix SMTP client does not yet have a mechanism to select from multiple candidate certificates on the fly, and supports a single set of certificates (at most one per public key algorithm).

RSA, DSA and ECDSA (Postfix ≥ 2.6) certificates are supported. You can configure all three at the same time, in which case the cipher used determines which certificate is presented.

It is possible for the Postfix SMTP client to use the same key/certificate pair as the Postfix SMTP server. If a certificate is to be presented, it must be in "PEM" format. The private key must not be encrypted, meaning: it must be accessible without a password. Both parts (certificate and private key) may be in the same file.

With OpenSSL 1.1.1 and Postfix ≥ 3.4 it is also possible to configure Ed25519 and Ed448 certificates. Rather than add two more pairs of key and certificate parameters, Postfix 3.4 introduces a new "smtp_tls_chain_files" parameter which specifies all the configured certificates at once, and handles files that hold both the key and the associated certificates in one pass, thereby avoiding potential race conditions during key rollover.

To enable remote SMTP servers to verify the Postfix SMTP client certificate, the issuing CA certificates must be made available to the server. You should include the required certificates in the client certificate file, the client certificate first, then the issuing CA(s) (bottom-up order).

Example: the certificate for "client.example.com" was issued by "intermediate CA" which itself has a certificate issued by "root CA". As the "root" super-user create the client.pem file with:

# umask 077
# cat client_key.pem client_cert.pem intermediate_CA.pem > chain.pem 

A Postfix SMTP client certificate supplied here must be usable as an SSL client certificate and hence pass the "openssl verify -purpose sslclient ..." test.

A server that trusts the root CA has a local copy of the root CA certificate, so it is not necessary to include the root CA certificate here. Leaving it out of the "chain.pem" file reduces the overhead of the TLS exchange.

If you want the Postfix SMTP client to accept remote SMTP server certificates issued by these CAs, append the root certificate to $smtp_tls_CAfile or install it in the $smtp_tls_CApath directory.

Example: Postfix ≥ 3.4 all-in-one chain file(s). One or more chain files that start with a key that is immediately followed by the corresponding certificate and any additional issuer certificates. A single file can hold multiple (key, cert, [chain]) sequences, one per algorithm. It is typically simpler to keep the chain for each algorithm in its own file. Most users are likely to deploy at most a single RSA chain, but with OpenSSL 1.1.1, it is possible to deploy up five chains, one each for RSA, ECDSA, ED25519, ED448, and even the obsolete DSA.

    # Postfix ≥ 3.4.  Preferred configuration interface.  Each file
    # starts with the private key, followed by the corresponding
    # certificate, and any intermediate issuer certificates.
    #
    smtp_tls_chain_files =
        /etc/postfix/rsa.pem,
        /etc/postfix/ecdsa.pem,
        /etc/postfix/ed25519.pem,
        /etc/postfix/ed448.pem

You can also store the keys separately from their certificates, again provided each is listed before the corresponding certificate chain. Storing a key and its associated certificate chain in separate files is not recommended, because this is prone to race conditions during key rollover, as there is no way to update multiple files atomically.

    # Postfix ≥ 3.4.
    # Storing keys separately from the associated certificates is not
    # recommended.
    smtp_tls_chain_files =
        /etc/postfix/rsakey.pem,
        /etc/postfix/rsacerts.pem,
        /etc/postfix/ecdsakey.pem,
        /etc/postfix/ecdsacerts.pem

The below examples show the legacy algorithm-specific configurations for Postfix 3.3 and older. With Postfix ≤ 3.3, even if the key is stored in the same file as the certificate, the file is read twice and a (brief) race condition still exists during key rollover. While Postfix ≥ 3.4 avoids the race when the key and certificate are in the same file, you should use the new "smtp_tls_chain_files" interface shown above.

RSA key and certificate examples:

/etc/postfix/main.cf:
    smtp_tls_cert_file = /etc/postfix/client.pem
    smtp_tls_key_file = $smtp_tls_cert_file

Their DSA counterparts:

/etc/postfix/main.cf:
    smtp_tls_dcert_file = /etc/postfix/client-dsa.pem
    smtp_tls_dkey_file = $smtp_tls_dcert_file

Their ECDSA counterparts (Postfix ≥ 2.6 + OpenSSL ≥ 1.0.0):

/etc/postfix/main.cf:
    smtp_tls_eccert_file = /etc/postfix/client-ecdsa.pem
    smtp_tls_eckey_file = $smtp_tls_eccert_file

To verify a remote SMTP server certificate, the Postfix SMTP client needs to trust the certificates of the issuing Certification Authorities. These certificates in "pem" format can be stored in a single $smtp_tls_CAfile or in multiple files, one CA per file in the $smtp_tls_CApath directory. If you use a directory, don't forget to create the necessary "hash" links with:

# $OPENSSL_HOME/bin/c_rehash /path/to/directory 

The $smtp_tls_CAfile contains the CA certificates of one or more trusted CAs. The file is opened (with root privileges) before Postfix enters the optional chroot jail and so need not be accessible from inside the chroot jail.

Additional trusted CAs can be specified via the $smtp_tls_CApath directory, in which case the certificates are read (with $mail_owner privileges) from the files in the directory when the information is needed. Thus, the $smtp_tls_CApath directory needs to be accessible inside the optional chroot jail.

The choice between $smtp_tls_CAfile and $smtp_tls_CApath is a space/time tradeoff. If there are many trusted CAs, the cost of preloading them all into memory may not pay off in reduced access time when the certificate is needed.

Example:

/etc/postfix/main.cf:
    smtp_tls_CAfile = /etc/postfix/CAcert.pem
    smtp_tls_CApath = /etc/postfix/certs

Client-side TLS connection reuse

Historically, the Postfix SMTP client has supported multiple deliveries per plaintext connection. Postfix 3.4 introduces support for multiple deliveries per TLS-encrypted connection. Multiple deliveries per connection improve mail delivery performance, especially for destinations that throttle clients that don't combine deliveries.

To enable multiple deliveries per TLS connection, specify:

/etc/postfix/main.cf:
    smtp_tls_connection_reuse = yes

Alternatively, specify the attribute "connection_reuse=yes" in an smtp_tls_policy_maps entry.

The implementation of TLS connection reuse relies on the same scache(8) service as used for delivering plaintext SMTP mail, the same tlsproxy(8) daemon as used by the postscreen(8) service, and relies on the same hints from the qmgr(8) daemon. See "Postfix Connection Cache" for a description of the underlying connection reuse infrastructure.

Initial SMTP handshake:

    smtp(8) -> remote SMTP server

Reused SMTP/TLS connection, or new SMTP/TLS connection:

    smtp(8) -> tlsproxy(8) -> remote SMTP server 

Cached SMTP/TLS connection:

    scache(8) -> tlsproxy(8) -> remote SMTP server

As of Postfix 3.4, TLS connection reuse is disabled by default. This may change once the impact on over-all performance is understood.

Client-side TLS session cache

The remote SMTP server and the Postfix SMTP client negotiate a session, which takes some computer time and network bandwidth. By default, this session information is cached only in the smtp(8) process actually using this session and is lost when the process terminates. To share the session information between multiple smtp(8) processes, a persistent session cache can be used. You can specify any database type that can store objects of several kbytes and that supports the sequence operator. DBM databases are not suitable because they can only store small objects. The cache is maintained by the tlsmgr(8) process, so there is no problem with concurrent access. Session caching is highly recommended, because the cost of repeatedly negotiating TLS session keys is high. Future Postfix SMTP servers may limit the number of sessions that a client is allowed to negotiate per unit time.

Example:

/etc/postfix/main.cf:
    smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_scache

Note: as of version 2.5, Postfix no longer uses root privileges when opening this file. The file should now be stored under the Postfix-owned data_directory. As a migration aid, an attempt to open the file under a non-Postfix directory is redirected to the Postfix-owned data_directory, and a warning is logged.

Cached Postfix SMTP client session information expires after a certain amount of time. Postfix/TLS does not use the OpenSSL default of 300s, but a longer time of 3600s (=1 hour). RFC 2246 recommends a maximum of 24 hours.

Example:

/etc/postfix/main.cf:
    smtp_tls_session_cache_timeout = 3600s

As of Postfix 2.11 this setting cannot exceed 100 days. If set ≤ 0, session caching is disabled. If set to a positive value less than 2 minutes, the minimum value of 2 minutes is used instead.

Client TLS limitations

The security properties of TLS communication channels are application specific. While the TLS protocol can provide a confidential, tamper-resistant, mutually authenticated channel between client and server, not all of these security features are applicable to every communication.

For example, while mutual TLS authentication between browsers and web servers is possible, it is not practical, or even useful, for web-servers that serve the public to verify the identity of every potential user. In practice, most HTTPS transactions are asymmetric: the browser verifies the HTTPS server's identity, but the user remains anonymous. Much of the security policy is up to the client. If the client chooses to not verify the server's name, the server is not aware of this. There are many interesting browser security topics, but we shall not dwell on them here. Rather, our goal is to understand the security features of TLS in conjunction with SMTP.

An important SMTP-specific observation is that a public MX host is even more at the mercy of the SMTP client than is an HTTPS server. Not only can it not enforce due care in the client's use of TLS, but it cannot even enforce the use of TLS, because TLS support in SMTP clients is still the exception rather than the rule. One cannot, in practice, limit access to one's MX hosts to just TLS-enabled clients. Such a policy would result in a vast reduction in one's ability to communicate by email with the world at large.

One may be tempted to try enforcing TLS for mail from specific sending organizations, but this, too, runs into obstacles. One such obstacle is that we don't know who is (allegedly) sending mail until we see the "MAIL FROM:" SMTP command, and at that point, if TLS is not already in use, a potentially sensitive sender address (and with SMTP PIPELINING one or more of the recipients) has (have) already been leaked in the clear. Another obstacle is that mail from the sender to the recipient may be forwarded, and the forwarding organization may not have any security arrangements with the final destination. Bounces also need to be protected. These can only be identified by the IP address and HELO name of the connecting client, and it is difficult to keep track of all the potential IP addresses or HELO names of the outbound email servers of the sending organization.

Consequently, TLS security for mail delivery to public MX hosts is almost entirely the client's responsibility. The server is largely a passive enabler of TLS security, the rest is up to the client. While the server has a greater opportunity to mandate client security policy when it is a dedicated MSA that only handles outbound mail from trusted clients, below we focus on the client security policy.

On the SMTP client, there are further complications. When delivering mail to a given domain, in contrast to HTTPS, one rarely uses the domain name directly as the target host of the SMTP session. More typically, one uses MX lookups — these are usually unauthenticated — to obtain the domain's SMTP server hostname(s). When, as is current practice, the client verifies the insecurely obtained MX hostname, it is subject to a DNS man-in-the-middle attack.

Adoption of DNSSEC and RFC6698 (DANE) may gradually (as domains implement DNSSEC and publish TLSA records for their MX hosts) address the DNS man-in-the-middle risk and provide scalable key management for SMTP with TLS. Postfix ≥ 2.11 supports the new dane and dane-only security levels that take advantage of these standards.

If clients instead attempted to verify the recipient domain name, an SMTP server for multiple domains would need to list all its email domain names in its certificate, and generate a new certificate each time a new domain were added. At least some CAs set fairly low limits (20 for one prominent CA) on the number of names that server certificates can contain. This approach is not consistent with current practice and does not scale.

It is regrettably the case that TLS secure-channels (fully authenticated and immune to man-in-the-middle attacks) impose constraints on the sending and receiving sites that preclude ubiquitous deployment. One needs to manually configure this type of security for each destination domain, and in many cases implement non-default TLS policy table entries for additional domains hosted at a common secured destination. For these reasons secure-channel configurations will never be the norm. For the generic domain with which you have made no specific security arrangements, this security level is not a good fit.

Given that strong authentication is not generally possible, and that verifiable certificates cost time and money, many servers that implement TLS use self-signed certificates or private CAs. This further limits the applicability of verified TLS on the public Internet.

Historical note: while the documentation of these issues and many of the related features were new with Postfix 2.3, the issue was well understood before Postfix 1.0, when Lutz Jänicke was designing the first unofficial Postfix TLS patch. See his original post http://www.imc.org/ietf-apps-tls/mail-archive/msg00304.html and the first response http://www.imc.org/ietf-apps-tls/mail-archive/msg00305.html. The problem is not even unique to SMTP or even TLS, similar issues exist for secure connections via aliases for HTTPS and Kerberos. SMTP merely uses indirect naming (via MX records) more frequently.

TLS policy table

A small fraction of servers offer STARTTLS but the negotiation consistently fails. As long as encryption is not mandatory, the Postfix SMTP client retries the delivery immediately with TLS disabled, without any need to explicitly disable TLS for the problem destinations.

The policy table is specified via the smtp_tls_policy_maps parameter. This lists optional lookup tables with the Postfix SMTP client TLS security policy by next-hop destination.

The TLS policy table is indexed by the full next-hop destination, which is either the recipient domain, or the verbatim next-hop specified in the transport table, $local_transport, $virtual_transport, $relay_transport or $default_transport. This includes any enclosing square brackets and any non-default destination server port suffix. The LMTP socket type prefix (inet: or unix:) is not included in the lookup key.

Only the next-hop domain, or $myhostname with LMTP over UNIX-domain sockets, is used as the nexthop name for certificate verification. The port and any enclosing square brackets are used in the table lookup key, but are not used for server name verification.

When the lookup key is a domain name without enclosing square brackets or any :port suffix (typically the recipient domain), and the full domain is not found in the table, just as with the transport(5) table, the parent domain starting with a leading "." is matched recursively. This allows one to specify a security policy for a recipient domain and all its sub-domains.

The lookup result is a security level, followed by an optional list of whitespace and/or comma separated name=value attributes that override related main.cf settings. The TLS security levels are described above. Below, we describe the corresponding table syntax:

none
No TLS. No additional attributes are supported at this level.
may
Opportunistic TLS. The optional "ciphers", "exclude" and "protocols" attributes (available for opportunistic TLS with Postfix ≥ 2.6) override the "smtp_tls_ciphers", "smtp_tls_exclude_ciphers" and "smtp_tls_protocols" configuration parameters. At this level and higher, the optional "servername" attribute (available with Postfix ≥ 3.4) overrides the global "smtp_tls_servername" parameter, enabling per-destination configuration of the SNI extension sent to the remote SMTP server.
encrypt
Mandatory encryption. Mail is delivered only if the remote SMTP server offers STARTTLS and the TLS handshake succeeds. At this level and higher, the optional "protocols" attribute overrides the main.cf smtp_tls_mandatory_protocols parameter, the optional "ciphers" attribute overrides the main.cf smtp_tls_mandatory_ciphers parameter, and the optional "exclude" attribute (Postfix ≥ 2.6) overrides the main.cf smtp_tls_mandatory_exclude_ciphers parameter.
dane
Opportunistic DANE TLS. The TLS policy for the destination is obtained via TLSA records in DNSSEC. If no TLSA records are found, the effective security level used is may. If TLSA records are found, but none are usable, the effective security level is encrypt. When usable TLSA records are obtained for the remote SMTP server, SSLv2+3 are automatically disabled (see smtp_tls_mandatory_protocols), and the server certificate must match the TLSA records. RFC 7672 (DANE) TLS authentication and DNSSEC support is available with Postfix 2.11 and later.
dane-only
Mandatory DANE TLS. The TLS policy for the destination is obtained via TLSA records in DNSSEC. If no TLSA records are found, or none are usable, no connection is made to the server. When usable TLSA records are obtained for the remote SMTP server, SSLv2+3 are automatically disabled (see smtp_tls_mandatory_protocols), and the server certificate must match the TLSA records. RFC 7672 (DANE) TLS authentication and DNSSEC support is available with Postfix 2.11 and later.
fingerprint
Certificate fingerprint verification. Available with Postfix 2.5 and later. At this security level, there are no trusted Certification Authorities. The certificate trust chain, expiration date, ... are not checked. Instead, the optional match attribute, or else the main.cf smtp_tls_fingerprint_cert_match parameter, lists the server certificate fingerprints or public key fingerprints (Postfix 2.9 and later). The digest algorithm used to calculate fingerprints is selected by the smtp_tls_fingerprint_digest parameter. Multiple fingerprints can be combined with a "|" delimiter in a single match attribute, or multiple match attributes can be employed. The ":" character is not used as a delimiter as it occurs between each pair of fingerprint (hexadecimal) digits.
verify
Mandatory server certificate verification. Mail is delivered only if the TLS handshake succeeds, if the remote SMTP server certificate can be validated (not expired or revoked, and signed by a trusted Certification Authority), and if the server certificate name matches the optional "match" attribute (or the main.cf smtp_tls_verify_cert_match parameter value when no optional "match" attribute is specified). With Postfix ≥ 2.11 the "tafile" attribute optionally modifies trust chain verification in the same manner as the "smtp_tls_trust_anchor_file" parameter. The "tafile" attribute may be specified multiple times to load multiple trust-anchor files.
secure
Secure certificate verification. Mail is delivered only if the TLS handshake succeeds, and DNS forgery resistant remote SMTP certificate verification succeeds (not expired or revoked, and signed by a trusted Certification Authority), and if the server certificate name matches the optional "match" attribute (or the main.cf smtp_tls_secure_cert_match parameter value when no optional "match" attribute is specified). With Postfix ≥ 2.11 the "tafile" attribute optionally modifies trust chain verification in the same manner as the "smtp_tls_trust_anchor_file" parameter. The "tafile" attribute may be specified multiple times to load multiple trust-anchor files.

Notes:

Example:

/etc/postfix/main.cf:
    smtp_tls_policy_maps = hash:/etc/postfix/tls_policy
    # Postfix 2.5 and later
    smtp_tls_fingerprint_digest = sha256
/etc/postfix/tls_policy:
    example.edu             none
    example.mil             may
    example.gov             encrypt ciphers=high
    example.com             verify match=hostname:dot-nexthop ciphers=high
    example.net             secure
    .example.net            secure match=.example.net:example.net
    [mail.example.org]:587  secure match=nexthop
    # Postfix 2.5 and later
    [thumb.example.org]         fingerprint
        match=b6:b4:72:34:e2:59:cd:fb:...:0d:4d:cc:2c:7d:84:de:e6:2f
        match=51:e9:af:2e:1e:40:1f:de:...:35:2d:09:16:31:5a:eb:82:76
    # Postfix ≥ 3.6 "protocols" syntax
    example.info            may protocols=>=TLSv1 ciphers=medium exclude=3DES
    # Legacy protocols syntax
    example.info            may protocols=!SSLv2:!SSLv3 ciphers=medium exclude=3DES

Note: The "hostname" strategy if listed in a non-default setting of smtp_tls_secure_cert_match or in the "match" attribute in the policy table can render the "secure" level vulnerable to DNS forgery. Do not use the "hostname" strategy for secure-channel configurations in environments where DNS security is not assured.

Discovering servers that support TLS

As we decide on a "per site" basis whether or not to use TLS, it would be good to have a list of sites that offered "STARTTLS". We can collect it ourselves with this option.

If the smtp_tls_note_starttls_offer feature is enabled and a server offers STARTTLS while TLS is not already enabled for that server, the Postfix SMTP client logs a line as follows:

postfix/smtp[pid]: Host offered STARTTLS: [hostname.example.com]

Example:

/etc/postfix/main.cf:
    smtp_tls_note_starttls_offer = yes

Server certificate verification depth

The server certificate verification depth is specified with the main.cf smtp_tls_scert_verifydepth parameter. The default verification depth is 9 (the OpenSSL default), for compatibility with Postfix versions before 2.5 where smtp_tls_scert_verifydepth was ignored. When you configure trust in a root CA, it is not necessary to explicitly trust intermediary CAs signed by the root CA, unless $smtp_tls_scert_verifydepth is less than the number of CAs in the certificate chain for the servers of interest. With a verify depth of 1 you can only verify certificates directly signed by a trusted CA, and all trusted intermediary CAs need to be configured explicitly. With a verify depth of 2 you can verify servers signed by a root CA or a direct intermediary CA (so long as the server is correctly configured to supply its intermediate CA certificate).

Example:

/etc/postfix/main.cf:
    smtp_tls_scert_verifydepth = 2

Client-side cipher controls

The Postfix SMTP client supports 5 distinct cipher grades as specified by the smtp_tls_mandatory_ciphers configuration parameter. This setting controls the minimum acceptable SMTP client TLS cipher grade for use with mandatory TLS encryption. The default value "medium" is suitable for most destinations with which you may want to enforce TLS, and is beyond the reach of today's cryptanalytic methods. See smtp_tls_policy_maps for information on how to configure ciphers on a per-destination basis.

By default anonymous ciphers are allowed, and automatically disabled when remote SMTP server certificates are verified. If you want to disable anonymous ciphers even at the "encrypt" security level, set "smtp_tls_mandatory_exclude_ciphers = aNULL"; and to disable anonymous ciphers even with opportunistic TLS, set "smtp_tls_exclude_ciphers = aNULL". There is generally no need to take these measures. Anonymous ciphers save bandwidth and TLS session cache space, if certificates are ignored, there is little point in requesting them.

The "smtp_tls_ciphers" configuration parameter (Postfix ≥ 2.6) provides control over the minimum cipher grade for opportunistic TLS. The default minimum cipher grade for opportunistic TLS is "medium" for Postfix releases after the middle of 2015, and "export" for older releases. With Postfix < 2.6, the minimum opportunistic TLS cipher grade is always "export".

With mandatory and opportunistic TLS encryption, the Postfix SMTP client will by default disable SSLv2 and SSLv3. The mandatory TLS protocol list is specified via the smtp_tls_mandatory_protocols configuration parameter. The corresponding smtp_tls_protocols parameter (Postfix ≥ 2.6) controls the TLS protocols used with opportunistic TLS.

Example:

/etc/postfix/main.cf:
    smtp_tls_mandatory_ciphers = medium
    smtp_tls_mandatory_exclude_ciphers = RC4, MD5
    smtp_tls_exclude_ciphers = aNULL
    smtp_tls_ciphers = medium
    # Preferred form with Postfix ≥ 3.6:
    smtp_tls_mandatory_protocols = >=TLSv1.2
    smtp_tls_protocols = >=TLSv1
    # Legacy form for Postfix < 3.6:
    smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
    smtp_tls_protocols = !SSLv2,!SSLv3

Client-side SMTPS support

These sections show how to send mail to a server that does not support STARTTLS, but that provides the SMTPS service on TCP port 465. Depending on the Postfix version, some additional tooling may be required.

Postfix ≥ 3.0

The Postfix SMTP client has SMTPS support built-in as of version 3.0. Use one of the following examples, to send all remote mail, or to send only some remote mail, to an SMTPS server.

Postfix ≥ 3.0: Sending all remote mail to an SMTPS server

The first example will send all remote mail over SMTPS through a provider's server called "mail.example.com":

/etc/postfix/main.cf:
    # Client-side SMTPS requires "encrypt" or stronger.
    smtp_tls_security_level = encrypt
    smtp_tls_wrappermode = yes
    # The [] suppress MX lookups.
    relayhost = [mail.example.com]:465

Use "postfix reload" to make the change effective.

See SOHO_README for additional information about SASL authentication.

Postfix ≥ 3.0: Sending only mail for a specific destination via SMTPS

The second example will send only mail for "example.com" via SMTPS. This time, Postfix uses a transport map to deliver only mail for "example.com" via SMTPS:

/etc/postfix/main.cf:
    transport_maps = hash:/etc/postfix/transport

/etc/postfix/transport:
    example.com  relay-smtps:example.com:465

/etc/postfix/master.cf:
    relay-smtps  unix  -       -       n       -       -       smtp
        # Client-side SMTPS requires "encrypt" or stronger.
        -o smtp_tls_security_level=encrypt
        -o smtp_tls_wrappermode=yes

Use "postmap hash:/etc/postfix/transport" and "postfix reload" to make the change effective.

See SOHO_README for additional information about SASL authentication.

Postfix < 3.0

Although older Postfix SMTP client versions do not support TLS wrapper mode, it is relatively easy to forward a connection through the stunnel program if Postfix needs to deliver mail to some legacy system that doesn't support STARTTLS.

Postfix < 3.0: Sending all remote mail to an SMTPS server

The first example uses SMTPS to send all remote mail to a provider's mail server called "mail.example.com".

A minimal stunnel.conf file is sufficient to set up a tunnel from local port 11125 to the remote destination "mail.example.com" and port "smtps". Postfix will later use this tunnel to connect to the remote server.

/path/to/stunnel.conf:
    [smtp-tls-wrapper]
    accept = 11125
    client = yes
    connect = mail.example.com:smtps

To test this tunnel, use:

$ telnet localhost 11125

This should produce the greeting from the remote SMTP server at mail.example.com.

On the Postfix side, the relayhost feature sends all remote mail through the local stunnel listener on port 11125:

/etc/postfix/main.cf:
    relayhost = [127.0.0.1]:11125

Use "postfix reload" to make the change effective.

See SOHO_README for additional information about SASL authentication.

Postfix < 3.0: Sending only mail for a specific destination via SMTPS

The second example will use SMTPS to send only mail for "example.com" via SMTPS. It uses the same stunnel configuration file as the first example, so it won't be repeated here.

This time, the Postfix side uses a transport map to direct only mail for "example.com" through the tunnel:

/etc/postfix/main.cf:
    transport_maps = hash:/etc/postfix/transport

/etc/postfix/transport:
    example.com  relay:[127.0.0.1]:11125

Use "postmap hash:/etc/postfix/transport" and "postfix reload" to make the change effective.

See SOHO_README for additional information about SASL authentication.

Miscellaneous client controls

The smtp_starttls_timeout parameter limits the time of Postfix SMTP client write and read operations during TLS startup and shutdown handshake procedures. In case of problems the Postfix SMTP client tries the next network address on the mail exchanger list, and defers delivery if no alternative server is available.

Example:

/etc/postfix/main.cf:
    smtp_starttls_timeout = 300s

With Postfix 2.8 and later, the tls_disable_workarounds parameter specifies a list or bit-mask of OpenSSL bug work-arounds to disable. This may be necessary if one of the work-arounds enabled by default in OpenSSL proves to pose a security risk, or introduces an unexpected interoperability issue. Some bug work-arounds known to be problematic are disabled in the default value of the parameter when linked with an OpenSSL library that could be vulnerable.

Example:

/etc/postfix/main.cf:
    tls_disable_workarounds = 0xFFFFFFFF
    tls_disable_workarounds = CVE-2010-4180, LEGACY_SERVER_CONNECT

Note: Disabling LEGACY_SERVER_CONNECT is not wise at this time, lots of servers are still unpatched and Postfix is not significantly vulnerable to the renegotiation issue in the TLS protocol.

With Postfix ≥ 2.11, the tls_ssl_options parameter specifies a list or bit-mask of OpenSSL options to enable. Specify one or more of the named options below, or a hexadecimal bitmask of options found in the ssl.h file corresponding to the run-time OpenSSL library. While it may be reasonable to turn off all bug workarounds (see above), it is not a good idea to attempt to turn on all features.

A future version of OpenSSL may by default no longer allow connections to servers that don't support secure renegotiation. Since the exposure for SMTP is minimal, and some SMTP servers may remain unpatched, you can add LEGACY_SERVER_CONNECT to the options to restore the more permissive default of current OpenSSL releases.

Example:

/etc/postfix/main.cf:
    tls_ssl_options = NO_TICKET, NO_COMPRESSION, LEGACY_SERVER_CONNECT

You should only enable features via the hexadecimal mask when the need to control the feature is critical (to deal with a new vulnerability or a serious interoperability problem). Postfix DOES NOT promise backwards compatible behavior with respect to the mask bits. A feature enabled via the mask in one release may be enabled by other means in a later release, and the mask bit will then be ignored. Therefore, use of the hexadecimal mask is only a temporary measure until a new Postfix or OpenSSL release provides a better solution.

TLSマネージャ固有の設定

The security of cryptographic software such as TLS depends critically on the ability to generate unpredictable numbers for keys and other information. To this end, the tlsmgr(8) process maintains a Pseudo Random Number Generator (PRNG) pool. This is queried by the smtp(8) and smtpd(8) processes when they initialize. By default, these daemons request 32 bytes, the equivalent to 256 bits. This is more than sufficient to generate a 128bit (or 168bit) session key.

Example:

/etc/postfix/main.cf:
    tls_daemon_random_bytes = 32

In order to feed its in-memory PRNG pool, the tlsmgr(8) reads entropy from an external source, both at startup and during run-time. Specify a good entropy source, like EGD or /dev/urandom; be sure to only use non-blocking sources (on OpenBSD, use /dev/arandom when tlsmgr(8) complains about /dev/urandom timeout errors). If the entropy source is not a regular file, you must prepend the source type to the source name: "dev:" for a device special file, or "egd:" for a source with EGD compatible socket interface.

Examples (specify only one in main.cf):

/etc/postfix/main.cf:
    tls_random_source = dev:/dev/urandom
    tls_random_source = egd:/var/run/egd-pool

By default, tlsmgr(8) reads 32 bytes from the external entropy source at each seeding event. This amount (256bits) is more than sufficient for generating a 128bit symmetric key. With EGD and device entropy sources, the tlsmgr(8) limits the amount of data read at each step to 255 bytes. If you specify a regular file as entropy source, a larger amount of data can be read.

Example:

/etc/postfix/main.cf:
    tls_random_bytes = 32

In order to update its in-memory PRNG pool, the tlsmgr(8) queries the external entropy source again after a pseudo-random amount of time. The time is calculated using the PRNG, and is between 0 and the maximal time specified with tls_random_reseed_period. The default maximal time interval is 1 hour.

Example:

/etc/postfix/main.cf:
    tls_random_reseed_period = 3600s

The tlsmgr(8) process saves the PRNG state to a persistent exchange file at regular times and when the process terminates, so that it can recover the PRNG state the next time it starts up. This file is created when it does not exist.

Examples:

/etc/postfix/main.cf:
    tls_random_exchange_name = /var/lib/postfix/prng_exch
    tls_random_prng_update_period = 3600s

As of version 2.5, Postfix no longer uses root privileges when opening this file. The file should now be stored under the Postfix-owned data_directory. As a migration aid, an attempt to open the file under a non-Postfix directory is redirected to the Postfix-owned data_directory, and a warning is logged. If you wish to continue using a pre-existing PRNG state file, move it to the data_directory and change the ownership to the account specified with the mail_owner parameter.

With earlier Postfix versions the default file location is under the Postfix configuration directory, which is not the proper place for information that is modified by Postfix.

はじめに、素早く汚く

The following steps will get you started quickly. Because you sign your own Postfix public key certificate, you get TLS encryption but no TLS authentication. This is sufficient for testing, and for exchanging email with sites that you have no trust relationship with. For real authentication you need also enable DNSSEC record signing for your domain and publish TLSA records and/or your Postfix public key certificate needs to be signed by a recognized Certification Authority. To authenticate the certificates of a remote host you need a DNSSEC-validating local resolver and to enable DANE authentication and/or configure the Postfix SMTP client with a list of public key certificates of Certification Authorities, but make sure to read about the limitations of the latter approach.

In the examples below, user input is shown in bold font, and a "#" prompt indicates a super-user shell.

Quick-start TLS with Postfix ≥ 3.1

Postfix 3.1 provides built-in support for enabling TLS in the SMTP client and server and for ongoing certificate and DANE TLSA record management.

Quick-start TLS in the Postfix ≥ 3.1 SMTP client.

If you are using Postfix 3.1 or later, and your SMTP client TLS settings are in their default state, you can enable opportunistic TLS in the SMTP client as follows:

# postfix tls enable-client
# postfix reload

If some of the Postfix SMTP client TLS settings are not in their default state, this will not make any changes, but will instead suggest the minimal required settings for SMTP client TLS. The "postfix reload" command is optional, it is only needed if you want the settings to take effect right away. Note, this does not enable trust in any public certification authorities, and does not configure client TLS certificates as these are largely pointless with opportunistic TLS.

There is not yet a turn-key command for enabling DANE authentication. This is because DANE requires changes to your resolv.conf file and a corresponding DNSSEC-validating resolver local to the Postfix host, these changes are difficult to automate in a portable way.

If you're willing to revert your settings to the defaults and switch to a "stock" opportunistic TLS configuration, then you can: erase all the SMTP client TLS settings and then enable client TLS:

# postconf -X `postconf -nH | egrep '^smtp(_|_enforce_|_use_)tls'`
# postfix tls enable-client
# postfix reload

Quick-start TLS in the Postfix ≥ 3.1 SMTP server.

If you are using Postfix 3.1 or later, and your SMTP server TLS settings are in their default state, you can enable opportunistic TLS in the SMTP server as follows:

# postfix tls enable-server
# postfix reload

If some of the Postfix SMTP client TLS settings are not in their default state, this will not make any changes, but will instead suggest the minimal required settings for SMTP client TLS. The "postfix reload" command is optional, it is only needed if you want the settings to take effect right away. This will generate a self-signed private key and certificate and enable TLS in the Postfix SMTP server.

If you're willing to revert your settings to the defaults and switch to a "stock" server TLS configuration, then you can: erase all the SMTP server TLS settings and then enable server TLS:

# postconf -X `postconf -nH | egrep '^smtpd(_|_enforce_|_use_)tls'`
# postfix tls enable-server
# postfix reload

Postfix ≥ 3.1 provides additional built-in support for ongoing management of TLS in the SMTP server, via additional "postfix tls" sub-commands. These make it easy to generate certificate signing requests, create and deploy new keys and certificates, and generate DANE TLSA records. See the postfix-tls(1) documentation for details.

Self-signed server certificate

The following commands (credits: Viktor Dukhovni) generate and install a 2048-bit RSA private key and 10-year self-signed certificate for the local Postfix system. This requires super-user privileges. (By using date-specific filenames for the certificate and key files, and updating main.cf with new filenames, a potential race condition in which the key and certificate might not match is avoided).

# dir="$(postconf -h config_directory)"
# fqdn=$(postconf -h myhostname)
# case $fqdn in /*) fqdn=$(cat "$fqdn");; esac
# ymd=$(date +%Y-%m-%d)
# key="${dir}/key-${ymd}.pem"; rm -f "${key}"
# cert="${dir}/cert-${ymd}.pem"; rm -f "${cert}"
# (umask 077; openssl genrsa -out "${key}" 2048) &&
  openssl req -new -key "${key}" \
    -x509 -subj "/CN=${fqdn}" -days 3650 -out "${cert}" &&
  postconf -e \
    "smtpd_tls_cert_file = ${cert}" \
    "smtpd_tls_key_file = ${key}" \
    'smtpd_tls_security_level = may' \
    'smtpd_tls_received_header = yes' \
    'smtpd_tls_loglevel = 1' \
    'smtp_tls_security_level = may' \
    'smtp_tls_loglevel = 1' \
    'smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache' \
    'tls_random_source = dev:/dev/urandom'

Note: the last command requires both single (') and double (") quotes.

The postconf(1) command above enables opportunistic TLS for receiving and sending mail. It also enables logging of TLS connections and recording of TLS use in the "Received" header. TLS session caching is also enabled in the Postfix SMTP client. With Postfix ≥ 2.10, the SMTP server does not need an explicit session cache since session reuse is better handled via RFC 5077 TLS session tickets.

Private Certification Authority

TLSをサポートするPostfixの構築

These instructions assume that you build Postfix from source code as described in the INSTALL document. Some modification may be required if you build Postfix from a vendor-specific source package.

To build Postfix with TLS support, first we need to generate the make(1) files with the necessary definitions. This is done by invoking the command "make makefiles" in the Postfix top-level directory and with arguments as shown next.

NOTE: Do not use Gnu TLS. It will spontaneously terminate a Postfix daemon process with exit status code 2, instead of allowing Postfix to 1) report the error to the maillog file, and to 2) provide plaintext service where this is appropriate.

If you need to apply other customizations (such as Berkeley DB databases, MySQL, PostgreSQL, LDAP or SASL), see the respective Postfix README documents, and combine their "make makefiles" instructions with the instructions above:

% make tidy # if you have left-over files from a previous build
% make makefiles CCARGS="-DUSE_TLS \
    (other -D or -I options)" \
    AUXLIBS="-lssl -lcrypto \
    (other -l options for libraries in /usr/lib) \
    (-L/path/name + -l options for other libraries)"

To complete the build process, see the Postfix INSTALL instructions. Postfix has TLS support turned off by default, so you can start using Postfix as soon as it is installed.

問題の報告

Problems are preferably reported via <postfix-users@postfix.org>. See http://www.postfix.org/lists.html for subscription information. When reporting a problem, please be thorough in the report. Patches, when possible, are greatly appreciated too.

作者


トップページに戻る