CentOS6.x postfix,dovecot によるメール サーバー構築

<< トップページへ

■ 概要

長い間CentOS5.xでメールサーバーを運用してきました。
今回はCentOS6.xで構築をしてみようと思います。
デストリの性格上、大きな差異はありませんでした。


■ 現状、動作しているパッケージ

$ rpm -qi postfix
Name        : postfix                      Relocations: (not relocatable)
Version     : 2.6.6                             Vendor: CentOS
Release     : 6.el6_5                       Build Date: 2014年02月20日 19時06分17秒
Install Date: 2014年04月05日 17時25分19秒      Build Host: c6b10.bsys.dev.centos.org
Group       : System Environment/Daemons    Source RPM: postfix-2.6.6-6.el6_5.src.rpm
Size        : 9732852                          License: IBM
Signature   : RSA/SHA1, 2014年02月20日 19時50分17秒, Key ID 0946fca2c105b9de
Packager    : CentOS BuildSystem <http://bugs.centos.org>
URL         : http://www.postfix.org
Summary     : Postfix Mail Transport Agent
Description :
Postfix is a Mail Transport Agent (MTA), supporting LDAP, SMTP AUTH (SASL),
TLS
-------------------------------------------------------------------------------------------
$ rpm -qi dovecot
Name        : dovecot                      Relocations: (not relocatable)
Version     : 2.0.9                             Vendor: CentOS
Release     : 7.el6_5.1                     Build Date: 2014年06月26日 01時07分53秒
Install Date: 2014年08月28日 23時45分00秒      Build Host: c6b8.bsys.dev.centos.org
Group       : System Environment/Daemons    Source RPM: dovecot-2.0.9-7.el6_5.1.src.rpm
Size        : 5789349                          License: MIT and LGPLv2
Signature   : RSA/SHA1, 2014年06月26日 04時00分38秒, Key ID 0946fca2c105b9de
Packager    : CentOS BuildSystem <http://bugs.centos.org>
URL         : http://www.dovecot.org/
Summary     : Secure imap and pop3 server
Description :
Dovecot is an IMAP server for Linux/UNIX-like systems, written with security
primarily in mind.  It also contains a small POP3 server.  It supports mail
in either of maildir or mbox formats.

The SQL drivers and authentication plug-ins are in their subpackages.
-------------------------------------------------------------------------------------------
$ rpm -qi clamd
Name        : clamd                        Relocations: (not relocatable)
Version     : 0.98.3                            Vendor: Fedora Project
Release     : 1.el6                         Build Date: 2014年05月10日 05時10分37秒
Install Date: 2014年06月16日 17時00分06秒      Build Host: buildvm-19.phx2.fedoraproject.org
Group       : System Environment/Daemons    Source RPM: clamav-0.98.3-1.el6.src.rpm
Size        : 585846                           License: GPLv2
Signature   : RSA/8, 2014年05月12日 07時25分01秒, Key ID 3b49df2a0608b895
Packager    : Fedora Project
URL         : http://www.clamav.net/
Summary     : The Clam AntiVirus Daemon
Description :
The Clam AntiVirus Daemon
-------------------------------------------------------------------------------------------
$ rpm -qi amavisd-new
Name        : amavisd-new                  Relocations: (not relocatable)
Version     : 2.8.0                             Vendor: Fedora Project
Release     : 8.el6                         Build Date: 2013年12月03日 00時34分50秒
Install Date: 2014年04月05日 23時54分19秒      Build Host: buildhw-01.phx2.fedoraproject.org
Group       : Applications/System           Source RPM: amavisd-new-2.8.0-8.el6.src.rpm
Size        : 2963861                          License: GPLv2+ and BSD and GFDL
Signature   : RSA/8, 2013年12月03日 07時59分19秒, Key ID 3b49df2a0608b895
Packager    : Fedora Project
URL         : http://www.ijs.si/software/amavisd/
Summary     : Email filter with virus scanner and spamassassin support
Description :
amavisd-new is a high-performance and reliable interface between mailer
(MTA) and one or more content checkers: virus scanners, and/or
Mail::SpamAssassin Perl module. It is written in Perl, assuring high
reliability, portability and maintainability. It talks to MTA via (E)SMTP
or LMTP, or by using helper programs. No timing gaps exist in the design
which could cause a mail loss.
-------------------------------------------------------------------------------------------
$ rpm -qi clamav
Name        : clamav                       Relocations: (not relocatable)
Version     : 0.98.3                            Vendor: Fedora Project
Release     : 1.el6                         Build Date: 2014年05月10日 05時10分37秒
Install Date: 2014年06月16日 17時00分03秒      Build Host: buildvm-19.phx2.fedoraproject.org
Group       : Applications/System           Source RPM: clamav-0.98.3-1.el6.src.rpm
Size        : 4018532                          License: GPLv2
Signature   : RSA/8, 2014年05月12日 07時26分05秒, Key ID 3b49df2a0608b895
Packager    : Fedora Project
URL         : http://www.clamav.net/
Summary     : Anti-virus software
Description :
Clam AntiVirus is a GPL anti-virus toolkit for UNIX. The main purpose of
this software is the integration with mail servers (attachment scanning).
The package provides a flexible and scalable multi-threaded daemon, a
command line scanner, and a tool for automatic updating via Internet.

The programs are based on a shared library distributed with the Clam
AntiVirus package, which you can use with your own software. Most
importantly, the virus database is kept up to date
-------------------------------------------------------------------------------------------
$ rpm -qi clamav-db
Name        : clamav-db                    Relocations: (not relocatable)
Version     : 0.98.3                            Vendor: Fedora Project
Release     : 1.el6                         Build Date: 2014年05月10日 05時10分37秒
Install Date: 2014年06月16日 17時00分00秒      Build Host: buildvm-19.phx2.fedoraproject.org
Group       : Applications/Databases        Source RPM: clamav-0.98.3-1.el6.src.rpm
Size        : 88494522                         License: GPLv2
Signature   : RSA/8, 2014年05月12日 07時23分05秒, Key ID 3b49df2a0608b895
Packager    : Fedora Project
URL         : http://www.clamav.net/
Summary     : Virus database for clamav
Description :
The actual virus database for clamav

インストール時にレポジトリの設定はCentOS6の場合
# yum install postfix dovecot  ← これを実行するときのレポジトリは base,update
# yum install clamd amavisd-new ← レポジトリは epel,
base,update
設定に入る前に 「mxレコ−ドが登録されてい て正引き ができること。」をクリアしてから次へ進んでください。
逆引きはプロバイダー名でも動作するようで す。
$ dig  hoge.sytes.net
; <<>> DiG 9.7.0-P2-RedHat-9.7.0-5.P2.el6_0.1 <<>> hoge.sytes.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 5076
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;
hoge.sytes.net.        IN    A

;; ANSWER SECTION:
hoge.sytes.net.    60    IN    A    58.95.119.186
← 正引ができる状態である

;; Query time: 35 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Tue Sep  6 09:46:03 2011
;; MSG SIZE  rcvd: 53

設定するのはpostfix + Auth + clamd + amavisd-new の環境です。 
これからrelayhost + sasl auth で ISPのMTAを経由した送信を行う設定を行います。
設定の際には最悪の場合に元に戻せるように各段階ごとに設定ファイルを別名でコピーした後に行ってく ださい。
ここからはmain.cfの設定です。以下を参考に設定してください。

$ grep -v "#" /etc/postfix/master.cf | sed '/^$/ d'

smtp      inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd
   -o smtpd_sasl_auth_enable=yes
smtps     inet  n       -       n       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
pickup    fifo  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp
    -o smtp_fallback_relay=
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache
smtp-amavis unix -    -    n    -    2  smtp

ここから追加分

smtp-amavis unix -    -    n    -    2  smtp
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
127.0.0.1:10025 inet n    -    n    -    -  smtpd
    -o content_filter=
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_client_restrictions=
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o mynetworks=127.0.0.0/8
    -o strict_rfc821_envelopes=yes
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
scache    unix  -       -       n       -       1       scache
discard   unix  -       -       n       -       -       discard
tlsmgr    unix  -       -       n       1000?   1       tlsmgr

設定するのはpostfix + Auth + clamd + amavisd-new の環境です。 
これからrelayhost + sasl auth で ISPのMTAを経由した送信を行う設定を行います。
設定の際には最悪の場合に元に戻せるように各段階ごとに設定ファイルを別名でコピーした後に行ってく ださい。
ここからはmain.cfの設定です。以下を参考に設定してください。

# grep -v "#" /etc/postfix/main.cf | sed '/^$/ d' ← /etc/postfix/main.cfの設定内容を確認

queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
myhostname = hogehoge.ne.net
mydomain = hogehoge.ne.net
inet_interfaces = all
inet_protocols = all
mydestination = $myhostname, localhost.$mydomain, localhost
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
unknown_local_recipient_reject_code = 550
mynetworks_style = subnet
relayhost = [hoge.mail.or.jp] ←契約ISPの送信メールサー バー
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
home_mailbox = Maildir/
 
 
debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.6.6/samples
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES

ここから追加分
#------------------------------------------------------------------------
# SMTPの設定
#
# smtpd_:サーバー動作関するもの
#
# smtp_ :クライアント動作に関するもの
#
#------------------------------------------------------------------------
#クライアント自宅サーバー間

#SMTP Authを有効にする。
smtpd_sasl_auth_enable = yes

#TLSの設定
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/postfix/certs/server.pem
smtpd_tls_key_file = /etc/postfix/certs/server.key
#smtpd_tls_session_cache_database = btree:/etc/postfix/smtpd_scache
#smtpd_tls_session_cache_database = sdbm:/etc/postfix/smtpd_scache
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_scache

smtpd_tls_loglevel = 1

#リレ-制限の設定
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
#------------------------------------------------------------------------
#自宅サーバーISP間

#SMTP Authを有効にする。
smtp_sasl_auth_enable = yes
#
smtp_use_tls = yes
smtp_sasl_password_maps = hash:/etc/postfix/saslpass
smtp_sasl_tls_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
smtp_tls_CApath = /etc/pki/tls/certs/ca-bundle.crt
#
#smtp_sasl_type = cyrus
#------------------------------------------------------------------------
#その他

#OutLookなどのためにLOGIN認証を使用する
broken_sasl_auth_clients = yes

#postfix amavis連携
content_filter = smtp-amavis:[127.0.0.1]:10024
#------------------------------------------------------------------------
#メール本文の内容で拒否
#body_checks = pcre:/etc/postfix/body_checks
#------------------------------------------------------------------------
#特定ドメインIPアドレス受信拒否
#smtpd_client_restrictions=permit_mynetworks,check_client_access hash:/etc/postfix/reject_list,permit
#------------------------------------------------------------------------
# 配送条件をtransportファイルで指定
transport_maps = hash:/etc/postfix/transport


その他設定ファイルを編集します。
設定ファイル
設定内容
/etc/sasl2/smtpd.conf
pwcheck_method: saslauthd
mech_list: plain login
/etc/aliases root:           hoge ← 追加
virusalert:     hoge ← 追加

# postalias hash:aliases ← デ−タ−ベ −スを更新する
/etc/clamd.conf

LocalSocket /var/run/clamav/clamd.sock これで正しい

$ grep -v "#" /etc/clamd.conf | sed '/^$/ d'

LogFile /var/log/clamav/clamd.log
LogFileMaxSize 0
LogTime yes
LogSyslog yes
PidFile /var/run/clamav/clamd.pid
TemporaryDirectory /var/tmp
DatabaseDirectory /var/lib/clamav
LocalSocket /var/run/clamav/clamd.sock
FixStaleSocket yes
TCPAddr 127.0.0.1
MaxConnectionQueueLength 30
MaxThreads 50
ReadTimeout 300
User clam
AllowSupplementaryGroups yes
ScanPE yes
ScanELF yes
DetectBrokenExecutables yes
ScanOLE2 yes
ScanMail yes
ScanArchive yes
ArchiveBlockEncrypted no

/etc/crontab # vi crontab

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
25 22 * * * root /root/clamav.sh  ← 追加する
*/5 * * * * root /var/video/cgi-bin/prog_gen.cgi 2&>1 /dev/null

/etc/hosts 192.168.1.12    hoge.sytes.net    hoge    # Added by NetworkManager
127.0.0.1    localhost.localdomain    localhost
::1   
hoge.sytes.net    hoge    localhost6.localdomain6    localhost6
192.168.1.16   
hoge-i5
192.168.1.12   
hoge
192.168.1.30    PS3
/etc/freshclam.conf $ grep -v "#" /etc/freshclam.conf  | sed '/^$/ d'
DatabaseDirectory /var/lib/clamav
UpdateLogFile /var/log/clamav/freshclam.log
LogSyslog yes
DatabaseOwner clam
DatabaseMirror db.jp.clamav.net
DatabaseMirror db.local.clamav.net
[root@kkuma-i5:/etc]$
/etc/amavisd/amavisd.conf # ### http://www.clamav.net/
['ClamAV-clamd',
  \&ask_daemon, ["CONTSCAN {}\n", "/var/spool/amavisd/clamd.sock"],
  qr/\bOK$/, qr/\bFOUND$/,
  qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],
# # NOTE: the easiest is to run clamd under the same user as amavisd; match
$myhostname = 'hoge.sytes.net';  # must be a fully-qualified domain name!

#$mydomain = 'example.com';   # a convenient default for other settings
$mydomain = 'hoge.sytes.net';   # a convenient default for other settings



#$virus_admin               = undef;  # notifications recip.
$virus_admin               = "virusalert\@$mydomain";

/etc/clamd.d/amavisd.conf


/etc/clamd.d /amavisd.confとLocalSocketの場所を同じにしないと下のようなエラーがでます。

 (!)ClamAV-clamd: Can't connect to UNIX socket /var/run/clamav/clamd.sock: 2, retrying (2)
 (!)ClamAV-clamd av-scanner FAILED:
run_av error: Too many retries to talk to
/var/run/clamav/clamd.sock
(Can't connect to UNIX socket /var/run/clamav/clamd.sock:
 \343\201\235\343\201\256\343\202\210\343\201\206\343\
201\252\343\203\225\343\202\241\343\202\244\343\203\
253\343\202\204\343\203\207\343\202\243\343\203\254\
343\202\257\343\203\210\343\203\252\343\201\257\
343\201\202\343\202\212\343\201\276\343\201\233\343\
202\223) at (eval 100) line 373.\n
 (!!)WARN: all primary virus scanners failed, considering backups

/etc/clamd.d /amavisd.confとLocalSocketの場所を同じにする。

$ grep -v "#" /etc/clamd.d/amavisd.conf  | sed '/^$/ d'
LogSyslog yes
LogFacility LOG_MAIL
PidFile /var/run/amavisd/clamd.pid
FixStaleSocket yes
User amavis
LocalSocket /var/spool/amavisd/clamd.sock
/etc/postfix/saslpass ISPのメールサーバに対してClient SASL を設定、認証可能に する。
#SMTPサー バ名ユーザー名:パスワード
[mail.boke.ne.jp]  hoge:xxxxx

[mail.boke.ne.jp]:587  hoge:xxxxx
とす ると、Submission ポートへも転送できる。

/etc/sysconfig/network hostnameの 設定
NETWORKING=yes
HOSTNAME=hoge
/root/clamav.sh
# cd /root
# vi clamav.sh

#!/bin/bash

PATH=/usr/bin:/bin
CLAMSCANTMP=`mktemp`
freshclam > /dev/null
#clamscan --recursive --no-archive --exclude=iptables --exclude-dir=/sys --remove / >
$CLAMSCANTMP
clamscan --recursive --remove / 2>/dev/null > $CLAMSCANTMP
[ ! -z "$(grep FOUND$ $CLAMSCANTMP)" ] && \
grep FOUND$ $CLAMSCANTMP | mail -s "Virus Found in `hostname`" root
rm -f $CLAMSCANTMP

# chmod +x clamav.sh

/etc/dovecot.conf
プレインテキスト認証を許可

$ grep -v "#" /etc/dovecot/dovecot.conf | sed '/^$/ d'
!include conf.d/*.conf
protocols = pop3
disable_plaintext_auth = no
dict {
}
サー バ証明書、秘密鍵
/etc/postfix/certs/server.pem
/etc/postfix/certs/server.key 

##cd /etc/postfix/
# mkdir certs
# cd certs

サーバ用秘密鍵作成
# openssl genrsa -des3 1024 > server.key

.......
Enter pass phrase: *******
Verifying - Enter pass phrase: *******

SMTP起動時にパスワードを要求されないようにサーバー用秘密 鍵からパスワードを削除
# openssl rsa -in server.key -out server.key

Enter pass phrase for server.key: *******
writing RSA key

サーバ用公開鍵作成
# openssl req -new -key server.key -out server.csr 
You are about to be asked ......
.........
Country Name (2 letter code) [GB]:JP 
State or Province Name (full name) [Berkshire]:Tokyo
Locality Name (eg, city) [Newbury]:Chofu-shi
Organization Name (eg, company) [My Company Ltd]:hoge.sytes.net 
Organizational Unit Name (eg, section) []: 
Common Name(eg, your name or your server's hostname)[]:hoge.sytes.net ホスト名
Email Address []:postmaster@hoge.sytes.net   メールアドレス
.......
A challenge password []: 
An optional company name []:

サーバ証明書作成
# openssl x509 -in server.csr -out server.pem -req -signkey server.key -days 365

Signature ok
subject=/C=JP/ST=Tokyo/L=Chofu-shi/O=hoge.sytes.net/CN=hoge.sytes.net/emailAddress=
postmaster@hoge.sytes.net Getting Private key

# chmod 400 server.*
# 特定ドメイン・IPアドレス受信拒否
smtpd_client_restrictions =
permit_mynetworks
check_client_access hash:/etc/postfix/reject_list, permit
受信拒否リスト作成
/etc/postfix/reject_list というファイルを作成

# vi
/etc/postfix/reject_list
hoge.com REJECT
72.70.52.145 REJECT

reject_list をDB形式に変換
/usr/sbin/postmap /etc/postfix/reject_list
← デ−タ−ベ −スを更新する

Postfixをリロードして終了。
/usr/sbin/postfix reload

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

※main.cf
設 定参照
#TLSの設 定
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/postfix/certs/server.pem
smtpd_tls_key_file = /etc/postfix/certs/server.key
smtpd_tls_session_cache_database = btree:/etc/postfix/smtpd_scache
smtpd_tls_loglevel = 1


※CentOS6 ではkey,pem専用ディレクトリーが用意されているが
 
上記でも動作を確認   (/etc/pki/tls/certs/)
# SSL/TLS support: yes, no, required.
#ssl = yes
ssl = yes ← TLS通信の有効化


/etc/postfix/main.cf
上記参照
/etc/postfix/master.cf 上記参照
メールの送受信をするユーザーアカウントを作成します。
ユーザ追加時にpostfixのMailDirを作成する場合は以下を実行
# mkdir -p /etc/skel/Maildir/new
# mkdir -p /etc/skel/Maildir/cur
# mkdir -p /etc/skel/Maildir/tmp
# chmod -R 700 /etc/skel/Maildir/
# saslpasswd2 -u hoge.sytes.net -c hoge ← ユーザ追加
Password:
Again (for verification):

# sasldblistusers2 ←SMTP-Auth用ユーザ/パスワード確認
hoge@hoge.sytes.net: userPassword

# chgrp postfix /etc/sasldb2 ← 所属 グループをpostfixに変更

※ SMTP-Auth用ユーザ/パスワー ドを削除する場合
# saslpasswd2 -d hoge -u hoge.hoge.sytes.net
あとはルーターで25番、110番、587 番、465番、995番のポートを開けてテストです。 ルーターでのポートの開け方はメーカー機種によって違いますので取扱説明書に従ってください。 ポートが開いたかどうか確認する方法としてポ−トスキャンをしてくれるサイトがあります。 http://www.cman.jp/network/support/port.html に 行って確認したいホスト名(FQDN)またはIPアドレスと確認したいport番号を入力してのポートチェック実行ボタンをクリックすると 開いているポートが開いているかどうかを表示してくれます。ルーターを設定したのにポートが開いていない場合は SELinux Management と ファイヤーウオール が有効になっていないか確認してください。

<< トップページへ