Mail Transfer Agent : Postfix

(最終更新日時:2010-04-14 12:45:13)
オープンソースのメール転送エージェント(MTA)である Postfix を SMTP メールサーバーとしてインストールします。

ダウンロード

The Postfix Home Page(http://www.postfix.org/)から次のファイルをダウンロードします。
Postfix 2.6 Patchlevel 5 Source Code postfix-2.6.5.tar.gz
 (※)下線部は 2010/04/14 現在の最新安定バージョンです。

事前準備

関連パッケージとして、下記を事前にインストールしておきます。
MySQL データベース 仮想ドメイン、アカウント管理や認証情報管理は MySQL を使用します
アンチウィルス Clam Anti Virus によるウィルス検査を行います
POP3/IMAP サーバー SMTP-AUTH の認証サーバーとして使用します
ウィルススキャン SMTP フィルタ SMTP でウィルス検査を行うためのフィルタです
Postgrey(Postfix Greylisting Policy Server) 迷惑メール対策用のポリシーサーバです
SPF ライブラリ Postfix を SPF 対応させるために必要なライブラリです
ポリシーサービスデーモン(SPF) Postfix の SPF 対応ポリシーデーモンです
GUI 管理ツール 仮想ドメイン、アカウントの運用管理は Postfix Admin を使用します

インストール

postfix 用の group および user を作成します。
# groupadd -g 89 postfix
# groupadd -g 90 postdrop
# useradd -M -u 89 -g postfix -G postdrop -s /sbin/nologin -d /var/spool/postfix postfix

/usr/local/src ディレクトリでアーカイブを展開し、コンパイルおよびインストールを行います。
$ cd /usr/local/src
$ tar zxvf ダウンロード先/postfix-2.5.6.tar.gz
$ cd postfix-2.5.6

$ # 迷惑メール対策として 佐藤潔さんtaRgrey を使用するにあたり、sleep 時の余計なプロセス増を減らすためのパッチを適用します
$ wget http://k2net.hakuba.jp/pub/postfix-sleep.patch
$ patch -bp1 < postfix-sleep.patch
$ rm -f postfix-sleep.patch

$ make makefiles \
>    CCARGS='-DUSE_TLS \                                      # SSL/TLS を使用します
>            -DHAS_MYSQL \                                    # MySQL を使用します
>            -DUSE_SASL_AUTH \                                # SMTP-AUTH を使用します
>            -DDEF_SASL_SERVER_TYPE="dovecot" \               # SMTP-AUTH の認証は dovecot で行います
>            -I/usr/local/include/mysql \                     # MySQL の include パスを指定しています
>   AUXLIBS='-L/usr/local/lib/mysql \                         # MySQL の lib パスを指定しています
>            -lssl -lcrypto -lmysqlclient -lz -lm'
$ make

$ sudo make install
パスワード:自身のログインパスワード

     :
install_root: [/][enter]
     :
tempdir: [/usr/local/src/postfix-2.6.5][enter]
     :
config_directory: [/etc/postfix][enter]
     :
command_directory: [/usr/sbin][enter]
     :
daemon_directory: [/usr/libexec/postfix][enter]
     :
data_directory: [/var/lib/postfix][enter]
     :
html_directory: [no][enter]
     :
mail_owner: [postfix][enter]
     :
mailq_path: [/usr/bin/mailq][enter]
     :
manpage_directory: [/usr/local/man][enter]
     :
newaliases_path: [/usr/bin/newaliases][enter]
     :
queue_directory: [/var/spool/postfix][enter]
     :
readme_directory: [no][enter]
     :
sendmail_path: [/usr/sbin/sendmail][enter]
     :
setgid_group: [postdrop][enter]

設定

仮想ドメイン、アカウント管理を Postfix Admin と MySQL で行うための定義ファイルを作成します。
なお、postfix を chroot 環境で動作させるため、MySQL サーバーとは TCP/IP で接続するようにします。

MySQL サーバーが Postfix と同じサーバー上にある場合、設定ファイルの hosts パラメータに localhost を設定すると TCP/IP 接続ではなく、Unix Socket 接続になります。TCP/IP 接続にするには IP アドレス 127.0.0.1 を設定します。
# mkdir /etc/postfix/virtual_maps
# cd    /etc/postfix/virtual_maps
# vi domains.cf

user         = postfix
password     = MySQL ユーザー postfix の接続パスワード
hosts        = actmysql.server.localnet
dbname       = postfix
table        = domain
select_field = domain
where_field  = domain
additional_conditions = AND backupmx = '0' AND active = '1'

# vi mailbox.cf

user         = postfix
password     = MySQLユーザ postfix の接続パスワード
hosts        = actmysql.server.localnet
dbname       = postfix
table        = mailbox
select_field = maildir
where_field  = username

# vi alias.cf

user         = postfix
password     = MySQLユーザ postfix の接続パスワード
hosts        = actmysql.server.localnet
dbname       = postfix
table        = alias
select_field = `goto`
where_field  = address

# chown root.postfix *.cf
# chmod 640          *.cf
# chown root.postfix .
# chmod 750          .

定義ファイル main.cf を編集します。
# vi /etc/postfix/main.cf

     :
myhostname = mail.system-act.com                              # メールサーバーのホスト名(FQDN)を設定します
     :
mydomain = system-act.com                                     # メールサーバーのドメイン名を設定します
     :
myorigin = $mydomain                                          # 外部へのメールアドレスのドメイン部分を設定します
     :
#inet_interfaces = all
inet_interfaces = all                                         # すべてのインターフェースで待ち受けます
     :
#mydestination = $myhostname, localhost.$mydomain, localhost
mydestination = $myhostname, localhost.$mydomain, localhost   # 最終配送先として許可するドメイン名
     :
#mynetworks = 168.100.189.0/28, 127.0.0.0/8
mynetworks = 192.168.101.0/24, 192.168.201.0/24, 127.0.0.0/8  # 信頼された SMTP クライアントのリスト
     :
#alias_maps = hash:/etc/aliases
alias_maps = hash:/etc/postfix/aliases                        # ローカル配送で使用するエイリアスデータベース
     :
#home_mailbox = Maildir/
home_mailbox = Maildir/                                       # メールボックスは Maildir 形式にします# MySQL による仮想ドメイン、ユーザー(非UNIXユーザー)を使用するための設定
#
virtual_transport       = virtual                             # virtual_mailbox_domains 宛のメールは virtual 配送を使用します
virtual_mailbox_base    = /home/postfix                       # virtual 配送におけるメールボックスの場所
virtual_alias_maps      = mysql:/etc/postfix/virtual_maps/alias.cf
                                                              # virtual 配送で使用するエイリアスデータベース(MySQL を使用)
virtual_alias_domains   = $virtual_alias_maps
virtual_mailbox_domains = mysql:/etc/postfix/virtual_maps/domains.cf
                                                              # virtual 配送で使用するドメインデータベース(MySQL を使用)
virtual_mailbox_maps    = mysql:/etc/postfix/virtual_maps/mailbox.cf
                                                              # virtual 配送で使用するメールボックスデータベース(MySQL を使用)
virtual_minimum_uid     = 5000                                # virtual 配送がユーザーとして受付ける最小の UID
virtual_uid_maps        = static:5000                         # virtual 配送ユーザーの UID は固定で 5000
virtual_gid_maps        = static:5000                         # virtual 配送ユーザーの GID は固定で 5000

# SMTP-AUTH を使用するための設定と迷惑メール対策
#
smtpd_sasl_auth_enable   = yes                                # 自メールサーバー SASL による認証を有効にします
smtpd_sasl_authenticated_header = yes                         # SASL 認証のユーザー名を Received ヘッダに出力します
broken_sasl_auth_clients = yes                                # 古いバージョンの AUTH コマンドを有効にします
smtpd_sasl_type          = dovecot                            # SASL 認証は dovecot で行います
smtpd_sasl_path          = private/auth                       # dovecot との認証ソケットファイルを指定します
smtpd_helo_required      = yes                                # SMTP セッションの最初で HELO/EHLO コマンドを要求します
disable_vrfy_command     = yes                                # SMTP VRFY コマンドを無効にします
smtpd_recipient_restrictions =                                # RCPT コマンド時に認証します
  permit_sasl_authenticated                                   # SASL により認証された場合は接続します
  permit_mynetworks                                           # 信頼された SMTP クライアントのリストにある場合は接続します
  reject_unauth_destination                                   # 指定配送先以外は拒否します
  reject_invalid_hostname                                     # HELO/EHLO のホスト名が正しくない場合は拒否します
  reject_non_fqdn_sender                                      # FQDN で表現されていない MAIL FROM を拒否します
  reject_non_fqdn_recipient                                   # FQDN で表現されていない RCPT TO を拒否します
  reject_unauth_pipelining                                    # 正しくない SMTP コマンドパイプラインを使用した場合は拒否します
  check_policy_service unix:private/policy                    # Received ヘッダに SPF のチェック結果を出力します
  check_client_access  regexp:/etc/postfix/filter/white_client
                                                              # 迷惑メール配信元判定前にホワイトリストのチェックを行います
  check_client_access  regexp:/etc/postfix/filter/permit_client_nots25r
                                                              # S25R による迷惑メール配信元判定を行います
  check_policy_service inet:10023                             # taRgrey による迷惑メール配信元対策を行います

smtpd_data_restrictions =                                 # DATA コマンド時に認証します
  permit_sasl_authenticated                               # SASL により認証された場合は接続します
  permit_mynetworks                                       # 信頼された SMTP クライアントのリストにある場合は接続します
  reject_multi_recipient_bounce                           # エンベロープ送信者がなく、エンベロープ受信者が複数の場合に拒否します
  check_client_access  regexp:/etc/postfix/filter/white_client
                                                          # 迷惑メール配信元判定前にホワイトリストのチェックを行います
  check_client_access  regexp:/etc/postfix/filter/permit_client_nots25r
                                                          # S25R による迷惑メール配信元判定を行います
  check_policy_service inet:10023                         # taRgrey による迷惑メール配信元対策を行います

# ClamSMTP でウィルススキャンをするための設定
#
content_filter = scan:127.0.0.1:10025                         # スキャンを依頼するサービス名・アドレス・ポート
receive_override_options = no_address_mappings                # アドレスマッピングを無効にします
queue_directory = /var/spool/postfix                          # Postfix デーモンプロセスのルートディレクトリ


定義ファイル master.cf を編集します。
# vi /etc/postfix/master.cf

     :
smtp      inet  n       -       y       -       -       smtpd                  # chroot を有効にします
     :
pickup    fifo  n       -       y       60      1       pickup                 # 以降、chroot を有効にします
cleanup   unix  n       -       y       -       0       cleanup
qmgr      fifo  n       -       y       300     1       qmgr
#qmgr     fifo  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       y       -       -       proxymap
proxywrite unix -       -       y       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       y       -       -       smtp
        -o smtp_fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local                  # chroot してはいけません!
virtual   unix  -       n       n       -       -       virtual                # chroot してはいけません!
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
# (ClamSMTP によるウィルススキャンの設定を追加します)
#
# ====================================================================
# AntiVirus Scan Filter
# ====================================================================
scan      unix  -       -       n       -       16      smtp
      -o smtp_send_xforward_command=yes
127.0.0.1:10026 inet   n   -    n       -       16      smtpd
      -o content_filter=
      -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks
      -o smtpd_helo_restrictions=
      -o smtpd_client_restrictions=
      -o smtpd_sender_restrictions=
      -o smtpd_recipient_restrictions=permit_mynetworks,reject
      -o mynetworks_style=host
      -o smtpd_authorized_xforward_hosts=127.0.0.0/8
# (SPF チェックの設定を追加します)
#
# ====================================================================
# SPF Policy Daemon
# ====================================================================
scan      unix  -       -       n       -       16      smtp
policy    unix  -       n       n       -       -       spawn
      user=nobody argv=/usr/local/sbin/policyd


迷惑メール配信元判定用のホワイトリストを作成します。
Gabacho-Net さんのホワイトリストを使用されてもいいかもしれません。
当サイトにおいては、送信元がある程度特定できることと、新規送信元は taRgrey による救済で十分と考え、都度追加作成しています。
# mkdir /etc/postfix/filter
# vi /etc/postfix/filter/white_client

#
# *** WHITE LIST ***
     :
正規表現形式で適宜追加してください
(IPアドレスによる例)
/^203\.189\.48\.125$/     OK
(ドメインによる例)
/system-act\.com$/        OK

S25R による迷惑メール配信元判定用のリストを作成します。
当サイトでは、taRgrey にある作成例ではなく、佐藤さんが初期に発表されたものに若干の手を加えて使用しています。
# vi /etc/postfix/filter/permit_client_nots25r

#
# *** DOMAIN BLACK LIST ***
/\.dip\.t-dialin\.net$/                         DUNNO
/\.dyn\.optonline\.net$/                        DUNNO
/\.(internetdsl|adsl|sdi)\.tpnet\.pl$/          DUNNO

#
# *** S25R ***
/^unknown$/                                     DUNNO
/^[^\.]*[0-9][^0-9\.]+[0-9]/                    DUNNO
/^[^\.]*[0-9]{5}/                               DUNNO
/^([^\.]+\.)?[0-9][^\.]*\.[^\.]+\..+\.[a-z]/    DUNNO
/^[^\.]*[0-9]\.[^\.]*[0-9]-[0-9]/               DUNNO
/^[^\.]*[0-9]\.[^\.]*[0-9]\.[^\.]+\..+\./       DUNNO
/^(dhcp|dialup|ppp|adsl|xdsl|pool)[^\.]*[0-9]/  DUNNO

/./                                             OK


Mailbox ディレクトリを作成します。
# mkdir /home/postfix                                         # Mailboxディレクトリを作成します
# chown 5000.5000 /home/postfix                               # virtual_uid_maps.virtual_uid_mapsを設定します
# chmod 750 /home/postfix

SSL/TLS設定

OpenSSL運用 を参考にサーバー証明書とサーバー秘密鍵を生成し、メールサーバーに設定します。
# mkdir /home/ssl/server/mail                                 # サーバー証明書の生成・保管場所を作成します
# cd    /home/ssl/server/mail

     :
(サーバー証明書とサーバー秘密鍵を生成)
     :

# mkdir     /etc/postfix/ssl                                  # サーバー証明書をサーバーに設定します
# chmod 755 /etc/postfix/ssl
# cp /home/ssl/server/mail/server.{crt,key} /etc/postfix/ssl/

定義ファイル main.cf に SSL/TLS 設定を追加します。
# vi /etc/postfix/main.cf
# SSL/TLS を使用するための設定
#
smtpd_tls_CAfile    = /home/ssl/CA/cacert.pem                                  # CA 証明書を指定します
smtpd_tls_cert_file = /etc/postfix/ssl/server.crt                              # サーバー証明書を指定します
smtpd_tls_key_file  = /etc/postfix/ssl/server.key                              # サーバー秘密鍵を指定します
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_tls_scache     # キャッシュファイルを指定します
smtpd_tls_session_cache_timeout  = 3600s                                       # キャッシュされている時間を指定します
smtpd_use_tls       = yes                                                      # STARTTLS を有効にします
smtpd_tls_loglevel  = 1
smtpd_tls_received_header = yes                                                # 情報を Received: メッセージヘッダに含めます


定義ファイル master.cf を編集します。
# vi /etc/postfix/master.cf
# (SMTPS ポートによる SSL/TLS 待ち受けを有効にするため、以下の 2 行のコメントを外します)
smtps     inet  n       -       y       -       -       smtpd                  # さらに chroot を有効にします
  -o smtpd_tls_wrappermode=yes
     :

その他の設定

その他、必要な設定を行います。
# postalias /etc/postfix/aliases                                               # エイリアスデータベースを作成します

# sh /usr/local/src/postfix-2.6.5/examples/chroot-setup/LINUX2                 # chroot 設定を行います

起動

自動起動設定を行います。
# vi /etc/rc.d/init.d/postfix
# (ディストリビューション RPM から取得したものです)

#!/bin/bash
#
# postfix      Postfix Mail Transfer Agent
#
# chkconfig: 2345 80 30
# description: Postfix is a Mail Transport Agent, which is the program \
#              that moves mail from one machine to another.
# processname: master
# pidfile: /var/spool/postfix/pid/master.pid
# config: /etc/postfix/main.cf
# config: /etc/postfix/master.cf
#
# Based on startup script from Simon J Mudd
# 25/02/99: Mostly s/sendmail/postfix/g by John A. Martin
# 23/11/00: Changes & suggestions by Ajay Ramaswamy
# 20/01/01: Changes to fall in line with RedHat 7.0 style
# 23/02/01: Fix a few untidy problems with help from Daniel Roesen.

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

[ -x /usr/sbin/postfix ] || exit 0
[ -d /etc/postfix ] || exit 0
[ -d /var/spool/postfix ] || exit 0

RETVAL=0

start() {
        # Start daemons.
        echo -n "Starting postfix: "
        alias_database=$(postconf -h alias_database 2>/dev/null)
        RETVAL=1
        [ -z "$alias_database" ] && {
            failure "determination of alias_database"
            echo
            return 0
        }
        /usr/sbin/postalias ${alias_database//,} 2>/dev/null
        RETVAL=$?
        [ $RETVAL -ne 0 ] && {
            failure "postalias $alias_database"
            echo
            return 0
        }
        /usr/sbin/postfix start 2>/dev/null 1>&2 && success || failure
        RETVAL=$?
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/postfix
        echo
        return $RETVAL
}

stop() {
        # Stop daemons.
        echo -n "Shutting down postfix: "
        /usr/sbin/postfix stop 2>/dev/null 1>&2 && success || failure
        RETVAL=$?
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/postfix
        echo
        return $RETVAL
}

reload() {
        echo -n "Reloading postfix: "
        /usr/sbin/postfix reload 2>/dev/null 1>&2 && success || failure
        RETVAL=$?
        echo
        return $RETVAL
}

abort() {
        /usr/sbin/postfix abort 2>/dev/null 1>&2 && success || failure
        return $?
}

flush() {
        /usr/sbin/postfix flush 2>/dev/null 1>&2 && success || failure
        return $?
}

check() {
        /usr/sbin/postfix check 2>/dev/null 1>&2 && success || failure
        return $?
}

restart() {
        stop
        start
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        start
        ;;
  reload)
        reload
        ;;
  abort)
        abort
        ;;
  flush)
        flush
        ;;
  check)
        check
        ;;
  status)
        status master
        ;;
  condrestart)
        [ -f /var/lock/subsys/postfix ] && restart || :
        ;;
  *)
        echo "Usage: postfix {start|stop|restart|reload|abort|flush|check|status|condrestart}"
        exit 1
esac

exit $?

# chmod 755 /etc/rc.d/init.d/postfix
# chkconfig postfix on

postfix を起動します。
# service postfix start

ファイアーウォール iptables の設定スクリプトに設定を追加します。
# vi /usr/local/sbin/firewall.sh
# --- (INPUTチェイン) ---# SMTP/SMTPS 接続を許可
iptables -A INPUT -i $EXTIF -p tcp --dport  25 -j CHK-SYNFLOOD
iptables -A INPUT -i $EXTIF -p tcp --dport 465 -j CHK-SYNFLOOD# --- (OUTPUTチェイン) ---# SMTP/SMTPS 接続を許可
iptables -A OUTPUT -o $EXTIF -p tcp --sport  25 -j ACCEPT
iptables -A OUTPUT -o $EXTIF -p tcp --sport 465 -m state --state ESTABLISHED -j ACCEPT
# firewall.sh                                                 # 設定を反映させます

フィードバック

記事の内容についてのご質問、ご指摘、その他ご意見等は、Weblog/Twitter にて受け付けております。

System House ACT Weblog 内記事 : Mail Transfer Agent : Postfix

トラックバックまたはコメントにてお寄せください。

Twitter では .systemact 宛につぶやいてください。
また、こちら から、この記事についてつぶやくことができます。
 
a System House to build an Accounting system by the Computer Technology