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

提供: ArchWiki
2016年6月4日 (土) 19:39時点におけるKusakata (トーク | 投稿記録)による版 (ページの作成:「Category:メールサーバー en:Virtual user mail system {{Related articles start}} {{Related4|Courier MTA}} {{Related4|OpenDKIM}} {{Related|Postfix}} {{Related...」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

関連記事

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

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

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

インストール

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

そして dovecotroundcubemail パッケージをインストールします。

設定

ユーザー

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

# 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

Postfix

SMTPS

Postfix#Secure SMTP に書かれているように SMTP を有効化します。

要件

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

警告: relay_domains can be dangerous. You usually do not want Postfix to forward mail of strangers. $mydestination is a sane default value. Double check it's value before running postfix! See 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
  • 上記の設定で virtual_mailbox_domains はメールを受信したいドメインのリストになります。mydestination に設定したドメインを含めてはいけません。mydestination はローカルホストだけで使うからです。
  • virtual_mailbox_maps には仮想ユーザーとメールボックスのディレクトリの情報を記述します。ハッシュファイルを使って永続的なマップを保存することで、MySQL データベースの転送を上書きします。
  • virtual_mailbox_base は仮想メールボックスを保存するベースディレクトリになります。

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

ノート: Since we will be using a web interface (Roundcube), and do not want people accessing this by any other means, we will be creating this account later without providing any login access.

Create the file structure

Those new additional settings reference a lot of files that do not even exist yet. We will create them with the following steps.

If you were setting up your database with PostfixAdmin and created the database schema through PostfixAdmin, you can create the following files. Do not forget to change the password:

/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 setups without using PostfixAdmin, create the following files.
/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

Run postmap on transport to generate its db:

# postmap /etc/postfix/transport

Dovecot

Instead of using the provided Dovecot example config file, we'll create our own /etc/dovecot/dovecot.conf. Please note that the user and group here might be vmail instead of postfix!

/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
ノート: If you instead want to modify dovecot.conf.sample, beware that the default configuration file imports the content of conf.d/*.conf. Those files call other files that aren't present in our configuration.

Now we create /etc/dovecot/dovecot-sql.conf, which we just referenced in the config above. Use the following contents and check if everything is set accordingly to your system's configuration.

If you used PostfixAdmin, then you add the following:

/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 http://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

Without having used PostfixAdmin you can use:

/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 http://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
ヒント: Visit http://wiki2.dovecot.org/Variables to learn more about Dovecot variables.

PostfixAdmin

Postfix#PostfixAdmin を見てください。

Roundcube

Make sure that both the pdo_mysql.so extension and iconv.so extension are uncommented in your php.ini file. Also check the .htaccess for access restrictions. Assuming that localhost is your current host, navigate a browser to http://localhost/roundcube/installer/ and follow the instructions.

Roundcube needs a separate database to work. You should not use the same database for Roundcube and PostfixAdmin. Create a second database roundcube_db and a new user named roundcube_user.

While running the installer ...

  • Make sure to address of the IMAP host is ssl://localhost/ or tls://localhost/ and not just localhost.
  • Use port 993. Likewise with SMTP.
  • Make sure to provide ssl://localhost/ with port 465 if you used the wrapper mode
  • and use tls://localhost/ port 587 if you used the proper TLS mode.
  • See here for an explanation on that.

The post install process is similar to any other webapp like PhpMyAdmin or PostFixAdmin. The configuration file is in /etc/webapps/roundcubemail/config/config.inc.php which works as an override over 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: Change Password Plugin

To let users change their passwords from within Roundcube, do the following:

Enable the password plugin by adding this line to

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

Configure the password plugin and make sure you alter the settings accordingly:

/usr/share/webapps/roundcubemail/plugins/password/config.inc.php
$config['password_driver'] = 'sql';
$config['password_db_dsn'] = 'mysql://<postfix_database_user>:<password>@localhost/<postfix_database_name>';
$config['password_query'] = 'UPDATE mailbox SET password=%c WHERE username=%u';

起動

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

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

任意設定

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

クォータ

To enable mailbox quota support by dovecot, do the following:

  • First add the following lines to /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
}
  • Create a new file /etc/dovecot/dovecot-dict-sql.conf.ext with the following code:
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
}
  • Create a warning script /usr/local/bin/quota-warning.sh and make sure it is executable. This warning script works with postfix lmtp configuration as well.
 #!/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
  • Edit the user_query line and add iterat_query in dovecot-sql.conf as following:
 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
  • Set up LDA as described above under SpamAssassin. If you're not using SpamAssassin, the pipe should look like this in /etc/postfix/master.cf :
 dovecot    unix  -       n       n       -       -       pipe
 flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${recipient}

As above activate it in Postfix main.cf

 virtual_transport = dovecot
  • You can set up quota per each mailbox in postfixadmin. Make sure the relevant lines in config.inc.php look like this:
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';

Restart postfix and dovecot services. If things go well, you should be able to list all users' quota and usage by the this command:

doveadm quota get -A

You should be able to see the quota in roundcube too.

注記

Alternative vmail folder structure

Instead of having a directory structure like /home/vmail/example.com/user@example.com you can have cleaner subdirectories (without the additional domain name) by replacing select_field and where_field with:

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

トラブルシューティング

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

If you get similar errors, take a look into /var/log/mail.log or use journalctl -xn --unit postfix.service to find out more.

It may turn out that the Maildir /home/vmail/mail@domain.tld is just being created if there is at least one email waiting. Otherwise there wouldn't be any need for the directory creation before.

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;