仮想ユーザーメールシステム

提供: ArchWiki
ナビゲーションに移動 検索に移動

関連記事

この記事では Arch Linux 環境に完全な仮想ユーザーメールシステムを出来る限りシンプルにセットアップする方法を説明しています。シンプルとはいえ、メールシステムは多数の複雑なコンポーネントによって構成されるため、必要な設定の数は大量です。

この記事で使用するコンポーネントを並べると、メールサーバーは Postfix、IMAP サーバーは Dovecot、ウェブメールインターフェイスは Roundcube、全てを管理する管理インターフェイスは PostfixAdmin です。

最新のセキュリティを利用して SMTP と SMTPS を使ってメールを送ったり POP3, POP3S, IMAP, IMAPS を使ってメールを受信できるようになるのが最終的な目標です。PostfixAdmin を利用することで設定は最小限に留め、ユーザーは Roundcube を使ってログインできるようにします。

インストール

まず最初に、MySQL の記事に書かれているように MySQL サーバーをセットアップして、Postfix の記事に従って Postfix サーバーを設定してください。

そして dovecotroundcubemail パッケージをインストールします。また、postfixからmysqlにアクセスするため postfix-mysql パッケージをインストールしてください。

設定

ユーザー

セキュリティの観点から、メールを保存するための新しいユーザーを作成します:

# groupadd -g 5000 vmail
# useradd -u 5000 -g vmail -s /usr/bin/nologin -d /home/vmail -m vmail

通常ユーザーと衝突が発生しないように gid と uid は5000にしています。メールは全て /home/vmail に保存されます。ホームディレクトリから /var/mail/vmail などに変更することはできますが、以下で設定を作成するときに注意してください。

データベース

空のデータベースとユーザーを作成する必要があります。この記事では、例としてユーザー postfix_user がデータベース postfix_db にパスワード hunter2 で読み書きアクセスできるようにします。データベースとユーザーを作成したら、以下のようにデータベースを使用する権限を与えます:

$ mysql -u root -p
CREATE DATABASE postfix_db;
GRANT ALL ON postfix_db.* TO 'postfix_user'@'localhost' IDENTIFIED BY 'hunter2';
FLUSH PRIVILEGES;

次に PostfixAdmin のセットアップページを開きます。PostfixAdmin で必要なテーブルとユーザーを作成してください。

PostfixAdmin

Postfix#PostfixAdmin を見てください。

SSL 証明書

メール通信を暗号化させるために SSL 証明書が必要になります (SMTPS/IMAPS/POP3S)。証明書を持っていない場合、作成してください:

# cd /etc/ssl/private/
# openssl req -new -x509 -nodes -newkey rsa:4096 -keyout vmail.key -out vmail.crt -days 1460 #days are optional
# chmod 400 vmail.key
# chmod 444 vmail.crt

Alternatively, create a free trusted certificate using Let's Encrypt. The private key will be in /etc/letsencrypt/live/yourdomain/privkey.pem, the certificate in /etc/letsencrypt/live/yourdomain/fullchain.pem. Either change the configuration accordingly, or symlink the keys to /etc/ssl/private:

# ln -s /etc/letsencrypt/live/yourdomain/privkey.pem /etc/ssl/private/vmail.key
# ln -s /etc/letsencrypt/live/yourdomain/fullchain.pem /etc/ssl/private/vmail.crt

Postfix

以下の設定をコピーアンドペーストする前に、relay_domains が設定されていることを確認してください。複数のドメインを設定している場合、実行時に警告が表示されます。

警告: relay_domains は危険です。知らない人のメールを Postfix で転送してしまう可能性があります。$mydestination は妥当なデフォルト値です。Postfix を起動する前に値をよく確認してください。http://www.postfix.org/BASIC_CONFIGURATION_README.html#relay_to を参照。

また、SSL 証明書のパスも正しいか確認してください。

Postfix の設定

/etc/postfix/main.cf に以下を追加:

relay_domains = $mydestination
virtual_alias_maps = proxy:mysql:/etc/postfix/virtual_alias_maps.cf
virtual_mailbox_domains = proxy:mysql:/etc/postfix/virtual_mailbox_domains.cf
virtual_mailbox_maps = proxy:mysql:/etc/postfix/virtual_mailbox_maps.cf
virtual_mailbox_base = /home/vmail
virtual_mailbox_limit = 512000000
virtual_minimum_uid = 5000
virtual_transport = virtual
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
local_transport = virtual
local_recipient_maps = $virtual_mailbox_maps
transport_maps = hash:/etc/postfix/transport

smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = /var/run/dovecot/auth-client
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_security_options = noanonymous
smtpd_sasl_tls_security_options = $smtpd_sasl_security_options
smtpd_tls_security_level = may
smtpd_tls_auth_only = yes
smtpd_tls_received_header = yes
smtpd_tls_cert_file = /etc/ssl/private/vmail.crt
smtpd_tls_key_file = /etc/ssl/private/vmail.key
smtpd_sasl_local_domain = $mydomain
broken_sasl_auth_clients = yes
smtpd_tls_loglevel = 1
smtp_tls_security_level = may
smtp_tls_loglevel = 1
  • 上記の設定で virtual_mailbox_domains はメールを受信したいドメインのリストになります。mydestination に設定したドメインを含めてはいけません。mydestination はローカルホストだけで使うからです。
  • virtual_mailbox_maps には仮想ユーザーとメールボックスのディレクトリの情報を記述します。ハッシュファイルを使って永続的なマップを保存することで、MySQL データベースの転送を上書きします。
  • virtual_mailbox_base は仮想メールボックスを保存するベースディレクトリになります。

virtual_uid_mapsvirtual_gid_maps は仮想メールを所有する実際のシステムユーザーの ID になります。ストレージ目的に使用します。

ノート: ウェブインターフェイス (Roundcube) を使用するため、他の方法でアクセスできないようにし、ログイン権限を与えずにアカウントを作成します。

設定ファイルの作成

以下の新しい設定では、まだ存在しない大量のファイルを参照しています。それらのファイルは次のステップから作成していきます。

PostfixAdmin でデータベースを設定して PostfixAdmin でデータベーススキーマを作成した場合、以下のファイルが作成できます。パスワードは必ず変更するようにしてください:

/etc/postfix/virtual_alias_maps.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = alias
select_field = goto
where_field = address
/etc/postfix/virtual_mailbox_domains.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = domain
select_field = domain
where_field = domain
/etc/postfix/virtual_mailbox_maps.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = mailbox
select_field = maildir
where_field = username


For alias domains functionality adjust the following files:

/etc/postfix/main.cf
virtual_alias_maps = proxy:mysql:/etc/postfix/virtual_alias_maps.cf,proxy:mysql:/etc/postfix/virtual_alias_domains_maps.cf
virtual_alias_domains = proxy:mysql:/etc/postfix/virtual_alias_domains.cf
/etc/postfix/virtual_alias_domains_maps.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('%u', '@', alias_domain.target_domain) AND alias.active = '1' AND alias_domain.active='1'
/etc/postfix/virtual_alias_domains.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
query = SELECT alias_domain FROM alias_domain WHERE alias_domain='%s' AND active = '1'
ノート: PostfixAdmin を使わずにセットアップする場合、以下のファイルを作成してください。
/etc/postfix/virtual_alias_maps.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = domains
select_field = virtual
where_field = domain
/etc/postfix/virtual_mailbox_domains.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = forwardings
select_field = destination
where_field = source
/etc/postfix/virtual_mailbox_maps.cf
user = postfix_user
password = hunter2
hosts = localhost
dbname = postfix_db
table = users
select_field = concat(domain,'/',email,'/')
where_field = email

transportpostmap を実行してデータベースを生成:

# postmap /etc/postfix/transport

Dovecot

Dovecot のサンプル設定ファイルは使わずに、/etc/dovecot/dovecot.conf を作成します。ユーザーとグループは postfix ではなく vmail になるので注意してください。

/etc/dovecot/dovecot.conf
protocols = imap pop3
auth_mechanisms = plain
passdb {
    driver = sql
    args = /etc/dovecot/dovecot-sql.conf
}
userdb {
    driver = sql
    args = /etc/dovecot/dovecot-sql.conf
}
 
service auth {
    unix_listener auth-client {
        group = postfix
        mode = 0660
        user = postfix
    }
    user = root
}

mail_home = /home/vmail/%d/%n
mail_location = maildir:~

ssl_cert = </etc/ssl/private/vmail.crt
ssl_key = </etc/ssl/private/vmail.key
ノート: dovecot.conf.sample を修正して使いたい場合、デフォルト設定ファイルでは conf.d/*.conf の中身がインポートされていることに注意してください。上記の設定例では存在しない他のファイルが使われることになります。

次に上の設定で参照した /etc/dovecot/dovecot-sql.conf を作成します。あなたのシステム設定にあわせて以下の設定が正しいか確認してください。

PostfixAdmin を使用する場合、以下を追加:

/etc/dovecot/dovecot-sql.conf
driver = mysql
connect = host=localhost dbname=postfix_db user=postfix_user password=hunter2
# It is highly recommended to not use deprecated MD5-CRYPT. Read more at https://wiki2.dovecot.org/Authentication/PasswordSchemes
default_pass_scheme = SHA512-CRYPT
# Get the mailbox
user_query = SELECT '/home/vmail/%d/%n' as home, 'maildir:/home/vmail/%d/%n' as mail, 5000 AS uid, 5000 AS gid, concat('dirsize:storage=',  quota) AS quota FROM mailbox WHERE username = '%u' AND active = '1'
# Get the password
password_query = SELECT username as user, password, '/home/vmail/%d/%n' as userdb_home, 'maildir:/home/vmail/%d/%n' as userdb_mail, 5000 as  userdb_uid, 5000 as userdb_gid FROM mailbox WHERE username = '%u' AND active = '1'
# If using client certificates for authentication, comment the above and uncomment the following
#password_query = SELECT null AS password, ‘%u’ AS user

PostfixAdmin を使用しない場合、以下を使用:

/etc/dovecot/dovecot-sql.conf
driver = mysql
connect = host=localhost dbname=postfix_db user=postfix_user password=hunter2
# It is highly recommended to not use deprecated MD5-CRYPT. Read more at https://wiki2.dovecot.org/Authentication/PasswordSchemes
default_pass_scheme = SHA512-CRYPT
# Get the mailbox
user_query = SELECT '/home/vmail/%d/%n' as home, 'maildir:/home/vmail/%d/%n' as mail, 5000 AS uid, 5000 AS gid, concat('dirsize:storage=',  quota) AS quota FROM users WHERE email = '%u'
# Get the password
password_query = SELECT email as user, password, '/home/vmail/%d/%n' as userdb_home, 'maildir:/home/vmail/%d/%n' as userdb_mail, 5000 as  userdb_uid, 5000 as userdb_gid FROM users WHERE email = '%u'
# If using client certificates for authentication, comment the above and uncomment the following
#password_query = SELECT null AS password, ‘%u’ AS user
ヒント: Dovecot の変数に関する詳細は https://wiki2.dovecot.org/Variables を参照。

DH parameters

With v2.3 you are required to provide ssl_dh = </path/to/dh.pem yourself.

To generate a new DH parameters file (this will take very long):

# openssl dhparam -out /etc/dovecot/dh.pem 4096

then add the file to /etc/dovecot/dovecot.conf

ssl_dh = </etc/dovecot/dh.pem

PostfixAdmin

Postfix#PostfixAdmin を見てください。

config.inc.php には以下の設定が必要です:

/etc/postfixadmin/config.inc.php
...
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
...

Roundcube

php.ini ファイルで pdo_mysql.soiconv.so 拡張をアンコメントしてください。また、.htaccess のアクセス制限も確認してください。ブラウザで http://localhost/roundcube/installer/ を開いて指示に従います。

Roundcube には別個にデータベースが必要になります。Roundcube と PostfixAdmin で同じデータベースを使うことはできません。新しいデータベース roundcube_db と新しいユーザー roundcube_user を作成してください。

インストーラーの実行時は以下の事柄に注意してください:

  • IMAP ホストのアドレスは ssl://localhost/ あるいは tls://localhost/ になります。localhost ではありません。
  • ポートは 993 を使ってください。SMTP と同じです。
  • ラッパーモードを使用する場合は ssl://localhost/ でポートは 465 にしてください。
  • プロパー TLS モードを使用する場合は tls://localhost/ でポートは 587 にしてください。
  • 上記設定に関する説明はこちらを参照。

インストール後の作業は PhpMyAdmin や PostFixAdmin などのウェブアプリと同じです。設定ファイルは /etc/webapps/roundcubemail/config/config.inc.php にあり、default.inc.php を上書きします。

Apache の設定

Apache を使用する場合、サンプル設定ファイルをウェブサーバーの設定ディレクトリにコピーしてください:

# cp /etc/webapps/roundcubemail/apache.conf /etc/httpd/conf/extra/httpd-roundcubemail.conf

そして以下を追加:

/etc/httpd/conf/httpd.conf
Include conf/extra/httpd-roundcubemail.conf

Roundcube: パスワード変更プラグイン

Roundcube からユーザーのパスワードを変更できるようにするには、以下を実行:

以下の行を追加して password プラグインを有効化:

/etc/webapps/roundcubemail/config/config.inc.php
$rcmail_config['plugins'] = array('password');

password プラグインを設定して設定を変更できることを確認:


/usr/share/webapps/roundcubemail/plugins/password/config.inc.php
<?php

$config['password_driver'] = 'sql';
$config['password_db_dsn'] = 'mysql://<postfix_database_user>:<password>@localhost/<postfix_database_name>';
// If you are not using dovecot specify another algorithm explicitly e.g 'sha256-crypt'
$config['password_algorithm'] = 'dovecot';
// For dovecot salted passwords only (above must be set to 'dovecot')
// $config['password_algorithm_prefix'] = 'true';
// $config['password_dovecotpw'] = 'doveadm pw';
// $config['password_dovecotpw_method'] = 'SHA512-CRYPT';
// $config['password_dovecotpw_with_method'] = true;
$config['password_query'] = 'UPDATE mailbox SET password=%P WHERE username=%u';

起動

必要なデーモン全てを起動して設定をテストしてください。postfixdovecot の両方を起動します。

テスト用に、PostfixAdmin でドメインとメールアカウントを作成してください。作成したアカウントに Roundcube でログインして、自分自身にメールを送ってください。

Testing

この記事あるいはセクションで使われている用語や表現には問題が存在します。
議論: Needs some cleanup. There are probably more general ways to write this. (議論: トーク:仮想ユーザーメールシステム#)

Now lets see if Postfix is going to deliver mail for our test user.

nc servername 25
helo testmail.org
mail from:<test@testmail.org>
rcpt to:<cactus@virtualdomain.tld>
data
This is a test email.
.
quit

Error response

451 4.3.0 <lisi@test.com>:Temporary lookup failure

Maybe you have entered the wrong user/password for MySQL or the MySQL socket is not in the right place.

This error will also occur if you neglect to run newaliases at least once before starting postfix. MySQL is not required for local only usage of postfix.

550 5.1.1 <email@spam.me>: Recipient address rejected: User unknown in virtual mailbox table.

Double check content of mysql_virtual_mailboxes.cf and check the main.cf for mydestination

See that you have received a email

Now type $ find /home/vmailer.

You should see something like the following:

/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/tmp
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/cur
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new/1102974226.2704_0.bonk.testmail.org

The key is the last entry. This is an actual email, if you see that, it is working.

任意設定

以下の設定は必須ではありませんが、セットアップを完全にします。

クォータ

Dovecot によるメールボックスのクォータを有効にするには、以下を実行:

  • まずは /etc/dovecot/dovecot.conf に以下の行を追加:
dict {
	quotadict = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
}
service dict {
	unix_listener dict {
		group = vmail
		mode = 0660
		user = vmail
	}
	user = root
}
service quota-warning {
	executable = script /usr/local/bin/quota-warning.sh
	user = vmail
	unix_listener quota-warning {
		group = vmail
		mode = 0660
		user = vmail
	}
}	
mail_plugins=quota
protocol pop3 {
	 mail_plugins = quota
	 pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
	 pop3_uidl_format = %08Xu%08Xv
}
protocol lda {
	mail_plugins = quota
	postmaster_address = postmaster@yourdomain.com
}
protocol imap {
	mail_plugins = $mail_plugins imap_quota
	mail_plugin_dir = /usr/lib/dovecot/modules
}
plugin {
       quota = dict:User quota::proxy::quotadict
       quota_rule2 = Trash:storage=+10%%
       quota_warning = storage=100%% quota-warning +100 %u
       quota_warning2 = storage=95%% quota-warning +95 %u
       quota_warning3 = storage=80%% quota-warning +80 %u
       quota_warning4 = -storage=100%% quota-warning -100 %u # user is no longer over quota
}
  • /etc/dovecot/dovecot-dict-sql.conf.ext を以下の内容で作成:
connect = host=localhost dbname=yourdb user=youruser password=yourpassword
map {
	pattern = priv/quota/storage
	table = quota2
	username_field = username
	value_field = bytes
}
map {
	pattern = priv/quota/messages
	table = quota2
	username_field = username
	value_field = messages
}
  • 警告スクリプト /usr/local/bin/quota-warning.sh を作成して実行可能属性を付与。警告スクリプトは postfix の lmtp 設定で動作します。
 #!/bin/sh
 BOUNDARY="$1"
 USER="$2"
 MSG=""
 if [[ "$BOUNDARY" = "+100" ]]; then
    MSG="Your mailbox is now overfull (>100%). In order for your account to continue functioning properly, you need to remove some emails NOW."
 elif [[ "$BOUNDARY" = "+95" ]]; then
    MSG="Your mailbox is now over 95% full. Please remove some emails ASAP."
 elif [[ "$BOUNDARY" = "+80" ]]; then
    MSG="Your mailbox is now over 80% full. Please consider removing some emails to save space."
 elif [[ "$BOUNDARY" = "-100" ]]; then
    MSG="Your mailbox is now back to normal (<100%)."
 fi
 
 cat << EOF | /usr/lib/dovecot/dovecot-lda -d $USER -o "plugin/quota=maildir:User quota:noenforcing"
 From: postmaster@yourdomain.com
 Subject: Email Account Quota Warning
 
 Dear User,
 
 $MSG
 
 Best regards,
 Your Mail System
 EOF
  • 以下のように dovecot-sql.conf の user_query を変更して iterat_query を追加:
 user_query = SELECT '/home/vmail/%d/%n' as home, 'maildir:/home/vmail/%d/%n' as mail, 5000 AS uid, 5000 AS gid, concat('*:bytes=', quota) AS quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
 iterate_query = SELECT username AS user FROM mailbox
  • 上記と同じように SpamAssassin で LDA を設定。SpamAssassin を使っていない場合、/etc/postfix/master.cf のパイプは以下のようになります:
 dovecot    unix  -       n       n       -       -       pipe
 flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${recipient}

上と同じように Postfix の main.cf で有効にしてください:

 virtual_transport = dovecot
  • postfixadmin のメールボックスごとにクォータを設定することができます。config.inc.php に以下のような行を設定してください:
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';

postfix と dovecot サービスを再起動してください。問題がなければ、以下のコマンドで全てのユーザーのクォータと使用率を確認できます:

doveadm quota get -A

roundcube でもクォータを確認できるはずです。

注記

vmail フォルダの構造を変更する

/home/vmail/example.com/user@example.com のようなディレクトリを使う代わりに select_fieldwhere_field を以下のように置き換えることで (ドメイン名が付かない) わかりやすいサブディレクトリを使えます:

query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') FROM users WHERE email='%s'

トラブルシューティング

IMAP/POP3 クライアントがメールを受け取れない

エラーが表示される場合、/var/log/mail.log を確認したり journalctl -xn --unit postfix.service で詳しく出力をチェックしてください。

待機中のメールが存在する場合 Maildir の /home/vmail/mail@domain.tld が作成中ということもあります。そうでない場合は先にディレクトリを作成する必要はありません。

Roundcube でメールを削除したり 'standard' フォルダを表示できない

Roundcube の config.inc.php ファイルに以下が記述されていることを確認してください:

$rcmail_config['default_imap_folders'] = array('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash');
$rcmail_config['create_default_folders'] = true;
$rcmail_config['protect_default_folders'] = true;

See also