メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定


投稿日:2015年1月26日
  • 4
  • 0



GMO VPSでメールサーバを構築します

gmo_postfix

前回」に続いて「GMO VPSを契約してWordPressを安定動作させるまでのサーバ設定方法」の最終章である第六弾。

この投稿ではOpenSSLでプライベートCAを構築しPostfix用の秘密鍵・公開鍵の作成。
さらにPostfixとDovecotを使ってメールサーバを構築します。

基本的なことは過去の投稿でまとめたので必要な方は参照してください。
カテゴリー「Postfix」の記事一覧

今回の解説で利用したVPSはこちら


目次


OpenSSLに関する設定

まずプライベートCAを作成してpostfixで利用する鍵を作ります。
致命的な脆弱性「Heartbleed」の例もありますので、最新版にアップデートしておきます。

# yum update openssl

CAスクリプトの編集

# cd /etc/pki/tls/misc/
# cp CA CA.org
# vi CA

有効期限の変更

鍵を作りなおすのも面倒なので3年から10年に変更します。

# if [ -z "$DAYS" ] ; then DAYS="-days 365" ; fi        # 1 year
# CADAYS="-days 1095"   # 3 years

if [ -z "$DAYS" ] ; then DAYS="-days 3650" ; fi
CADAYS="-days 3650"

openssl.cnfの編集

# cd /etc/pki/tls
# cp openssl.cnf openssl.cnf.org
# vi openssl.cnf

「usr_cert」セクションの項目を変更

basicConstraintsの項目を変更

basicConstraints=CA:FALSE
↓
# basicConstraints=CA:FALSE
basicConstraints=CA:TRUE

nsCertTypeの項目を変更

# nsCertType = sslCA, emailCA
↓
# nsCertType = sslCA, emailCA
nsCertType = sslCA, emailCA

keyUsageの項目を変更

# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
↓
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
keyUsage = cRLSign, keyCertSign

ここから「v3_req」セクション

<h4>basicConstraintsの項目を変更</h4>
basicConstraints = CA:FALSE
↓
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

以上で下準備は完了です。


プライベートCAの構築とPostfix用の秘密鍵・公開鍵の作成

# cd /etc/pki/tls/misc/
# ./CA -newca

CA certificate filename (or enter to create)

Making CA certificate ...
Generating a 2048 bit RSA private key
............................+++
................+++
writing new private key to '/etc/pki/CA/private/./cakey.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:JP ←国を入力
State or Province Name (full name) []:Tokyo ←都市を入力
Locality Name (eg, city) [Default City]:Shinagawa ←市区町村を入力
Organization Name (eg, company) [Default Company Ltd]:example ←組織名を入力
Organizational Unit Name (eg, section) []: ←部署名を入力(空欄でよい)
Common Name (eg, your name or your server's hostname) []:example.com ←サイト名やサーバ名など
Email Address []:info@example.com ←メールアドレスを入力(空欄でよい)

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ←証明書破棄時のパスワードを入力(空欄でよい)
An optional company name []: ←別の組織名を入力(空欄でよい)
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for /etc/pki/CA/private/./cakey.pem: ←上で入力したパスを入力
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 12436273577774291098 (0xac9684edc4d0189a)
        Validity
            Not Before: Jun 15 14:10:29 2014 GMT
            Not After : Jun 12 14:10:29 2024 GMT
        Subject:
            countryName               = JP
            stateOrProvinceName       = Tokyo
            organizationName          = example
            commonName                = example
            emailAddress              = info@example.com
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                3E:15:CA:D1:0B:04:06:74:94:5F:DB:E8:01:80:4B:C2:EF:78:8B:4D
            X509v3 Authority Key Identifier:
                keyid:3E:15:CA:D1:0B:04:06:74:94:5F:DB:E8:01:80:4B:C2:EF:78:8B:4D

            X509v3 Basic Constraints:
                CA:TRUE
Certificate is to be certified until Jun 12 14:10:29 2024 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

CAの秘密鍵のパーミッション変更

# cd /etc/pki/CA/private
# chmod 600 cakey.pem

ルート証明書に追加するプライベートCAの証明書を作成

# cd /etc/pki/CA/
# openssl x509 -inform pem -in cacert.pem -outform der -out cacert.der

/etc/pki/CA/cacert.der」が作成される。

メールサーバ用の秘密鍵を作成

# mkdir /etc/pki/postfix
# cd /etc/pki/postfix
# openssl genrsa -des3 -out postfix.key 2048
Generating RSA private key, 2048 bit long modulus
..................................................................................................+++
........+++
e is 65537 (0x10001)
Enter pass phrase for postfix.key: ←postfix.key用のパス
Verifying - Enter pass phrase for postfix.key: ←同じパス

これで「/etc/pki/postfix/postfix.key」が作成される。

パーミッション変更

# chmod 600 postfix.key

メールサーバ用の秘密鍵を元に、証明書署名要求(CSR)を作成

# openssl req -new -key postfix.key -out postfix.csr

Enter pass phrase for postfix.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:JP ←国コードを入力
State or Province Name (full name) []:Tokyo ←都市を入力
Locality Name (eg, city) [Default City]:Shinagawa ←市区町村を入力
Organization Name (eg, company) [Default Company Ltd]:sukegra ←組織名を入力
Organizational Unit Name (eg, section) []: ←部署名を入力(空欄でもよい)
Common Name (eg, your name or your server's hostname) []:mail.example.com ←postfixで設定したホスト名の入力。重要なので間違えないように
Email Address []:info@example.com ←メールアドレスを入力(空欄でよい)

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ←証明書破棄時のパスワードを入力(空欄でよい)
An optional company name []: ←別の組織名を入力(空欄でよい)

/etc/pki/postfix/postfix.csr」が作成される。

証明書署名要求(CSR)をプライベートCAで署名して、公開鍵証明書(公開鍵)の作成

# openssl x509 -CA /etc/pki/CA/cacert.pem -CAkey /etc/pki/CA/private/cakey.pem -req -in postfix.csr -out postfix.pem -days 3650 -CAcreateserial
Signature ok
subject=/C=JP/ST=Tokyo/L=Shinagawa/O=example.com/CN=example.com/emailAddress=info@example.com
Getting CA Private Key
Enter pass phrase for /etc/pki/CA/private/cakey.pem: ←プライベートCAの秘密鍵に指定したパスワードを入力

/etc/pki/postfix/postfix.pem」が作成される。

パスフレーズで暗号化された秘密鍵を復号化

# openssl rsa -in postfix.key -out postfix_noenc.key
Enter pass phrase for postfix.key: ←postfix.key用のパスワードの入力
writing RSA key

/etc/pki/postfix/postfix_noenc.key」が作成される。

パーミッション変更

# chmod 600 postfix_noenc.key

postfixの設定

まずインストールされているか確認。

# yum list installed | grep postfix
postfix.x86_64                     2:2.6.6-6.el6_5                   @updates

main.cfの編集

# cd /etc/postfix/
# cp main.cf main.cf.org
# vi /etc/postfix/main.cf

myhostnameの設定

#myhostname = virtual.domain.tld
↓
#myhostname = virtual.domain.tld
myhostname = mail.example.com

mydomainの設定

#mydomain = domain.tld
↓
#mydomain = domain.tld
mydomain = example.com

mydomainの設定

#myorigin = $mydomain
↓
#myorigin = $mydomain
myorigin = $mydomain

inet_interfacesの設定

inet_interfaces = localhost
↓
#inet_interfaces = localhost
inet_interfaces = ipv4

mydestinationの設定

mydestination = $myhostname, localhost.$mydomain, localhost
↓
#mydestination = $myhostname, localhost.$mydomain, localhost
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain

mynetworksの設定

#mynetworks = hash:/etc/postfix/network_table
↓
#mynetworks = hash:/etc/postfix/network_table
mynetworks = 192.168.0.0/24, 127.0.0.0/8

relay_domainsの設定

#relay_domains = $mydestination
↓
#relay_domains = $mydestination
relay_domains = $mydestination

home_mailboxの設定

#home_mailbox = Maildir/
↓
#home_mailbox = Maildir/
home_mailbox = Maildir/

smtpd_bannerの設定

#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
↓
#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
smtpd_banner = $myhostname ESMTP unknown

SSLや認証に関する設定

ファイルの最後に追記。

#SSL用の設定
smtpd_tls_security_level = may
smtpd_tls_cert_file = /etc/pki/postfix/postfix.pem
smtpd_tls_key_file = /etc/pki/postfix/postfix_noenc.key
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache

smtpd_tls_CAfile = /etc/pki/CA/cacert.pem
smtpd_tls_CApath = /etc/pki/CA

#SMTP認証用の設定
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
smtpd_recipient_restrictions = permit_mynetworks permit_sasl_authenticated reject_unauth_destination

#メールの最大サイズの設定
message_size_limit = 10485760

メール エイリアス データベースの作成

$ cd /etc
$ echo -n > aliases.db

saslauthの設定

まずはsaslでplainでログインできるようにする。

# cd /usr/lib64/sasl2/
# cp smtpd.conf smtpd.conf.org ←ない場合もあり
# vi smtpd.conf
pwcheck_method: saslauthd
↓
pwcheck_method: saslauthd
mech_list: plain login

続いて認証メソッドにpamを使う指定

Postfix専用のユーザーを作成せずとも、Linuxユーザーでメールを使えるようにするため。

# cd /etc/sysconfig/
# cp saslauthd saslauthd.org
# vi saslauthd

以下有効であることを確認。

MECH=pam

最後にUNIX認証を有効にするためモジュール「pam_unix.so」を指定

# cd /etc/pam.d/
# cp smtp smtp.org
# vi smtp
auth       include      system-auth
account    include      system-auth
↓
#auth       include      system-auth
#account    include      system-auth
auth    required        pam_unix.so     nullok
account required        pam_unix.so

サスルの再起動

# /etc/init.d/saslauthd restart

サスルの自動起動を有効にする

# chkconfig --list saslauthd
# chkconfig saslauthd on

「/etc/postfix/master.cf」の設定

# cd /etc/postfix/
# cp master.cf master.cf.org
# vi /etc/postfix/master.cf

SMTPsを有効

#smtps     inet  n       -       n       -       -       smtpd
↓
smtps     inet  n       -       n       -       -       smtpd

TLSとSASLを有効、不明なホストの接続を拒否

#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
↓
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_sender=yes

「tlsmgr(TLSセッションキャッシュ)」の設定

(postfix2.3.3ではデフォルトで有効になっています)

tlsmgr    unix  -       -       n       1000?   1       tlsmgr

Postfixで複数ドメインの管理

設定が前後するがバーチャルメールボックスの設定。

# vi /etc/postfix/main.cf
#バーチャルホスト用設定
virtual_alias_maps=hash:/etc/postfix/virtual

Postfixのバーチャルホスト用の設定ファイルを作成

info@example.com宛のメールもinfoに配信する方法。
上の「main.cf」で「mydomain = example.com」に指定していない方のアドレスを登録する。
2nd.example.com」用の、hogeとhugaユーザー用のメールアドレスを作成する場合。

# vi /etc/postfix/virtual

最終行に以下を追記。

#example.com用メールアドレス
example.com anything
hoge@2nd.example.com hoge
huga@2nd.example.com huga

作成したデータベースの反映とリロード

# postmap /etc/postfix/virtual
# /etc/init.d/postfix reload

メールエイリアスの変更

通常infoはroot宛に届くようにエイリアスされているので変更する。

# vi /etc/aliases
info:          postmaster
↓
#info:          postmaster

さらにrootユーザー当てのメールを転送するようにする。最後の行に追加する。

#root:          marc
root:          hoge
hoge:          hoge@example.com

データベースの更新

# rm /etc/aliases.db
# newaliases

メールサーバの再起動

# /etc/init.d/postfix restart

postfixの自動起動

# chkconfig --list postfix
# chkconfig postfix on

cyrus-sasl関連のインストール

認証にsaslauthd使うのでcyrus-sasl関連をインストールして、設定を済ませます。

# yum install cyrus*
(省略)
Dependencies Resolved

================================================================================
 Package                Arch        Version                  Repository    Size
================================================================================
Installing:
 cyrus-imapd            x86_64      2.3.16-6.el6_2.5         base          11 M
 cyrus-imapd-devel      x86_64      2.3.16-6.el6_2.5         base         232 k
 cyrus-imapd-utils      x86_64      2.3.16-6.el6_2.5         base         255 k
 cyrus-sasl-devel       x86_64      2.1.23-13.el6_3.1        base         302 k
 cyrus-sasl-gssapi      x86_64      2.1.23-13.el6_3.1        base          34 k
 cyrus-sasl-ldap        x86_64      2.1.23-13.el6_3.1        base          29 k
 cyrus-sasl-md5         x86_64      2.1.23-13.el6_3.1        base          47 k
 cyrus-sasl-ntlm        x86_64      2.1.23-13.el6_3.1        base          36 k
 cyrus-sasl-plain       x86_64      2.1.23-13.el6_3.1        base          31 k
 cyrus-sasl-sql         x86_64      2.1.23-13.el6_3.1        base          32 k
Installing for dependencies:
 postgresql-libs        x86_64      8.4.20-1.el6_5           updates      201 k

Transaction Summary
================================================================================
(省略)

メール送信テスト

まずtelnetが入っていないのでインストール。

# yum install telnet
(省略)
Dependencies Resolved

================================================================================
 Package         Arch            Version                    Repository     Size
================================================================================
Installing:
 telnet          x86_64          1:0.17-47.el6_3.1          base           58 k

Transaction Summary
================================================================================
(省略)

root@example.comからpiyo@example.comへ送信する例

# telnet localhost 25
HELO localhost
MAIL FROM: ←ユーザーネームを置き換える
RCPT TO: ←相手のメールアドレス
DATA
Subject:Send Test Mail
From:root ←ユーザー名とユーザーネームを置き換える
To:mrtobikko ←相手のメールアドレス(実際に利用しているメールアドレス)
This is test mail ←ここから本文
from telnet
.

最後の「.(ドット)」も必要なので注意。
終了は「quit」です


Dovecotのインストールと設定

# yum install dovecot
(省略)
Dependencies Resolved

================================================================================
 Package          Arch            Version                   Repository     Size
================================================================================
Installing:
 dovecot          x86_64          1:2.0.9-7.el6             base          1.9 M

Transaction Summary
================================================================================
(省略)

Dovecot設定

昔は「/etc/dovecot.conf」でしたが専用のディレクトリが作成されるようになったようです。

# vi /etc/dovecot/dovecot.conf

listenの設定

#listen = *, ::
↓
#listen = *, ::
listen = *

protocolsの設定

pop3s等はもう古いらしい。

#protocols = imap pop3 lmtp
↓
#protocols = imap pop3 lmtp
protocols = imap pop3 lmtp

mail_locationの設定

#mail_location =
↓
mail_location = maildir:~/Maildir

過去sslに関する設定もこのファイルで行ってましたが「/etc/dovecot/conf.d/10-ssl.conf」で管理するように変更になってます。

# vi /etc/dovecot/conf.d/10-ssl.conf

sslの確認とpostfix用の鍵を登録。

ssl = yes

#ssl_cert = </etc/pki/dovecot/certs/dovecot.pem
#ssl_key = </etc/pki/dovecot/private/dovecot.pem
ssl_cert = </etc/pki/postfix/postfix.pem
ssl_key = </etc/pki/postfix/postfix_noenc.key

※複数のドメインでメールサーバを建てるなら以下のように個別に証明書を発行して指定する必要があります。

local_name imap.example.org {
  ssl_cert = </etc/ssl/certs/imap.example.org.crt
  ssl_key = </etc/ssl/private/imap.example.org.key
}
local_name imap.example2.org {
  ssl_cert = </etc/ssl/certs/imap.example2.org.crt
  ssl_key = </etc/ssl/private/imap.example2.org.key
}

dovecotの再起動

# /etc/init.d/dovecot restart

dovecotの自動起動

# chkconfig dovecot on
# chkconfig --list dovecot

後はルート証明書「/etc/pki/CA/cacert.der」をインストールする場合はダウンロードしてOutlookなんかに取り込めばセキュリティの警告はでなくなります。

あたりまえだけど、ちゃんとユーザー作成しておかないと送受信できないので注意。info使うにはパスワードの設定も忘れずに。


今回の解説で利用したVPSはこちら
GMOクラウドのVPS

以上で6回に渡った解説も終了です。
長らくお付き合いいただきありがとうございました。


現在のページを共有する



現在のページに関連する記事

メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 OpenSSLとプライベートCAでメールサーバ用の秘密鍵と公開鍵証明書を作成
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 Postfixによる、セキュリティに配慮したメールサーバの構築方法
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 OpenSSLの基本と、メールサーバに暗号化通信を導入する際の流れを確認
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 OpenSSLでプライベートCAを構築して、クライアント用ルート証明書を作成
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 Dovecot IMAP/POP3 Serverで受信用メールサーバを構築
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 PostfixのSMTP認証で利用するCyrus SASLライブラリについて
メールサーバ構築のためOpenSSL、Postfix、Dovecotのインストールと設定 メモリ消費の多いClam AntiVirusの代替としてSophos Anti-Virus for Linuxを使う方法

おすすめの記事

自前の国別IPv6、IPv4アドレス割当リストを作成しよう

自前の国別IPv6、IPv4アドレス割当リストを作成しよう

シンプルなスパムコメント対策プラグイン「Simple AntiSpam」を作成しました

シンプルなスパムコメント対策プラグイン「Simple AntiSpam」を…

iptablesの設定ファイルをシェルスクリプトを利用して動的に作成

iptablesの設定ファイルをシェルスクリプトを利用して動的に作成

Excelでセルとセルの間をダブルクリックすると移動する機能を停止する方法

Excelでセルとセルの間をダブルクリックすると移動する機能を停…

WordPressでアイキャッチ画像をサムネイルとして一覧ページに表示する方法

WordPressでアイキャッチ画像をサムネイルとして一覧ページに表…

Custom Post Type UIでカスタム投稿を作って、誰でも簡単に編集できる投稿画面を作る方法

Custom Post Type UIでカスタム投稿を作って、誰でも簡単に編集…

lazysizesの使い方を通して学ぶ、画像の遅延読み込みとレスポンシブイメージの基本

lazysizesの使い方を通して学ぶ、画像の遅延読み込みとレスポン…

公式ドキュメントよりも詳しいTinyMCEの使い方(基本編)

公式ドキュメントよりも詳しいTinyMCEの使い方(基本編)


コメントを残す

コメントは認証制のため、すぐには反映されません。

プログラミングに関する質問は「日本語でプログラミングの悩みを解決するQ&Aサイト sukegra」をご利用ください。