diff --git a/DOCUMENTS/DOVECOT-2.4.md b/DOCUMENTS/DOVECOT-2.4.md new file mode 100644 index 00000000..73e670ef --- /dev/null +++ b/DOCUMENTS/DOVECOT-2.4.md @@ -0,0 +1,301 @@ +# Dovecot 2.4 configuration notes for PostfixAdmin + +This document provides a Dovecot 2.4-style SQL configuration baseline for +PostfixAdmin installations using virtual mailboxes, multi-domain storage, quota, +LMTP, IMAP, POP3 and optional ManageSieve. + +The older `DOCUMENTS/DOVECOT.txt` example is still useful background, but it +uses older Dovecot configuration syntax. Dovecot 2.4 also makes password scheme +compatibility more explicit, so deployments with old hashes should plan the +migration before changing `default_password_scheme`. + +## Scope + +The example files in this document cover: + +* Dovecot 2.4 SQL `passdb` / `userdb` +* PostfixAdmin 4.x and current master-style schemas +* multi-domain virtual mailbox paths +* Maildir baseline storage +* optional per-user Maildir to mdbox migration +* optional post-login password hash migration to `{ARGON2ID}` +* quota and quota clone support +* quota warning delivery to the user's INBOX +* optional IMAPSieve spam/ham learning hooks +* LMTP, IMAP, POP3 and ManageSieve listeners + +Review all paths, users, groups, database names and service ownership before +using the examples in production. + +## Loading the example configuration + +The example file is named `examples/dovecot-2.4-local.conf`. Dovecot will not +load it automatically just because it exists; it must be included by the active +Dovecot configuration used by your package or service. + +Dovecot 2.4 packages may not use the same `dovecot.conf` layout that older 2.3 +installations used. Before installing the example, check which configuration +file is active: + +```sh +doveconf -n +``` + +For this Dovecot 2.4 proposal, the recommended deployment style is a single +local override file. Keeping the PostfixAdmin SQL auth, storage, quota, Sieve +and migration settings together makes the example easier to audit and avoids +missing one required fragment in a package-specific `conf.d` layout. + +If your installation has a main `/etc/dovecot/dovecot.conf`, add a local +include near the end: + +```conf +!include_try /etc/dovecot/local.conf +``` + +On Dovecot 2.4 installations where you intentionally want this single-file +layout instead of the older `conf.d` split, the end of `dovecot.conf` can be +kept explicit: + +```conf +#!include_try conf.d/*.conf +!include_try local.conf +``` + +Only disable the package `conf.d` include after reviewing the existing package +defaults and moving any required local settings into `local.conf`. + +Then install the example as: + +```sh +install -m 0640 -o root -g dovecot examples/dovecot-2.4-local.conf /etc/dovecot/local.conf +``` + +If your package uses a `conf.d` layout and you prefer to keep it, install the +example with a late name so it is loaded after package defaults: + +```sh +install -m 0640 -o root -g dovecot examples/dovecot-2.4-local.conf /etc/dovecot/conf.d/99-postfixadmin-local.conf +``` + +After installing or including the file, always validate the effective +configuration before reloading Dovecot: + +```sh +doveconf -n +doveadm reload +``` + +Adjust ownership/group names if your distribution does not use a `dovecot` +group. + +## Important Dovecot 2.4 differences + +### Password schemes + +If old `MD5`, `PLAIN-MD5` or `MD5-CRYPT` hashes still exist, Dovecot 2.4 may +require weak schemes to be explicitly enabled: + +```conf +auth_allow_weak_schemes = yes +``` + +Treat this as a temporary migration setting only. After active users have been +upgraded to stronger hashes such as `{ARGON2ID}`, disable weak schemes again: + +```conf +auth_allow_weak_schemes = no +``` + +PostfixAdmin password hash settings are documented in `DOCUMENTS/HASHING.md`. + +### Calling doveadm from PostfixAdmin + +When PostfixAdmin is configured to use Dovecot's `doveadm` for password hashing, +Dovecot 2.4 may need `-O` so `doveadm pw` does not try to read full Dovecot +configuration files: + +```php +$CONF['dovecotpw'] = "/usr/bin/doveadm -O pw"; +``` + +This avoids common permissions problems when the web server user cannot read +Dovecot certificates or private configuration. + +## Baseline SQL authentication + +For installations that do not need post-login password migration, keep the +password query simple: + +```conf +passdb sql { + default_password_scheme = ARGON2ID + query = SELECT username AS user, password FROM mailbox WHERE username = '%{user}' AND active = '1' +} +``` + +For Maildir-only installations, a simple `userdb` query is enough: + +```conf +userdb sql { + query = SELECT \ + '/var/vmail/%{user | domain}/%{user | username}' AS home, \ + 150 AS uid, \ + 12 AS gid, \ + CONCAT(quota, 'B') AS quota_storage_size \ + FROM mailbox \ + WHERE username = '%{user}' AND active = '1' + + iterate_query = SELECT username AS user FROM mailbox WHERE active = '1' +} +``` + +See `examples/dovecot-2.4-local.conf` for a full working example. + +## Optional password hash migration to ARGON2ID + +If users still have legacy hashes, one migration pattern is to re-hash the +password after a successful login. Dovecot authenticates the user with the +currently stored hash, then a local post-login script generates an `{ARGON2ID}` +hash and updates the mailbox row. + +The temporary query exposes the clear password only to the local Dovecot login +environment: + +```conf +passdb sql { + default_password_scheme = ARGON2ID + + # Normal query after migration: + # query = SELECT username AS user, password FROM mailbox WHERE username = '%{user}' AND active = '1' + + # Temporary query used only by the post-login migration script: + query = SELECT username AS user, password, '%{password}' AS userdb_plain_pass FROM mailbox WHERE username = '%{user}' AND active = '1' +} +``` + +Use this only during a controlled migration window. Review local permissions, +logs and process environment exposure before enabling it. After migration, revert +to the normal query without `userdb_plain_pass`. + +The related post-login script is provided in +`examples/dovecot-upgrade-pass.sh`. + +Keep verbose password logging disabled in production: + +```conf +# Debug only. WARNING: enabling this may log plaintext passwords. +# Never enable it on production systems or shared logs. +#auth_verbose = yes +#auth_verbose_passwords = plain +``` + +## Optional per-user Maildir to mdbox migration + +Dovecot 2.4 can receive `mail_driver` and `mail_path` from SQL. This makes it +possible to migrate users gradually from Maildir to mdbox instead of changing +the mailbox format for everyone at once. + +This requires a local extension such as: + +```sql +ALTER TABLE mailbox + ADD COLUMN mail_format VARCHAR(16) NOT NULL DEFAULT 'maildir'; +``` + +Then the `userdb` query can return the mailbox driver per user: + +```conf +userdb sql { + query = SELECT \ + '/var/vmail/%{user | domain}/%{user | username}' AS home, \ + 150 AS uid, \ + 12 AS gid, \ + CONCAT(quota, 'B') AS quota_storage_size, \ + CASE WHEN mail_format = 'mdbox' THEN 'mdbox' ELSE 'maildir' END AS mail_driver, \ + CONCAT('/var/vmail/', '%{user | domain}/', '%{user | username}') AS mail_path \ + FROM mailbox \ + WHERE username = '%{user}' AND active = '1' + + iterate_query = SELECT username AS user FROM mailbox WHERE active = '1' +} +``` + +Installations that do not need per-user mailbox format selection should use the +simpler Maildir-only query. + +The related migration script is provided in +`examples/migrate-maildir-to-mdbox.sh`. Treat it as an operational example: +test with dry-run first, back up mail storage and the database, and review +paths, ownership and Dovecot permissions before running with `--real`. + +## Optional quota warning delivery + +The full configuration example uses Dovecot quota warnings: + +```conf +quota "User Quota" { + warning warn-95 { + quota_storage_percentage = 95 + execute quota-warning { + args = 95 %{user} + } + } +} + +service quota-warning { + executable = script /usr/local/bin/quota-warning.sh + user = vmail +} +``` + +`examples/quota-warning.sh` is a sanitized helper that delivers a warning +message directly to the user's INBOX with `doveadm submaster deliver`. + +Review the sender address, server name, support signature, script ownership and +Dovecot permissions before using it. Keep all production hostnames and domains +out of public examples. + +## Optional IMAPSieve spam and ham learning + +The full configuration example references two IMAPSieve scripts: + +```conf +path = /var/vmail/sieve/bin/report-spam.sieve +path = /var/vmail/sieve/bin/report-ham.sieve +``` + +These are optional hooks for spam/ham learning, commonly used with Rspamd. The +example files are: + +```text +examples/sieve/report-spam.sieve +examples/sieve/report-ham.sieve +examples/sieve/rspamd-learn-spam.sh +examples/sieve/rspamd-learn-ham.sh +``` + +The `.sieve` files use `vnd.dovecot.pipe`, so the helper shell scripts must be +installed under the configured `sieve_pipe_bin_dir`: + +```conf +sieve_pipe_bin_dir = /var/vmail/sieve/bin +``` + +Review Rspamd paths, script ownership and execution permissions before enabling +these hooks. Installations that do not use IMAPSieve or Rspamd can remove the +`sieve_script spam` and `imapsieve_from Junk` blocks from the example config. + +## Recommended migration sequence + +1. Back up the PostfixAdmin database and mail storage. +2. Update Dovecot 2.4 configuration using the baseline SQL queries. +3. If old MD5 hashes exist, temporarily enable `auth_allow_weak_schemes = yes`. +4. Enable the post-login hash migration query and script if migrating passwords. +5. Let active users migrate to `{ARGON2ID}` after successful logins. +6. Revert the password query to the normal form without `userdb_plain_pass`. +7. Disable weak schemes again with `auth_allow_weak_schemes = no`. +8. If migrating mailbox format, add `mailbox.mail_format`, switch to the + per-user `userdb` query, and run the mdbox migration script in dry-run first. +9. Migrate selected users, selected domains, or all mailboxes with `--real`. +10. Keep old Maildir backups until users and indexes have been validated. diff --git a/DOCUMENTS/DOVECOT.txt b/DOCUMENTS/DOVECOT.txt index db293da5..9ba330f7 100644 --- a/DOCUMENTS/DOVECOT.txt +++ b/DOCUMENTS/DOVECOT.txt @@ -11,6 +11,10 @@ http://wiki.dovecot.org/Quota http://wiki.dovecot.org/Quota/Dict http://www.opensourcehowto.org/how-to/mysql/mysql-users-postfixadmin-postfix-dovecot--squirrelmail-with-userprefs-stored-in-mysql.html +NOTE: This document contains older Dovecot configuration examples. For +Dovecot 2.4 SQL configuration, password migration and optional Maildir to +mdbox migration notes, see DOCUMENTS/DOVECOT-2.4.md. + Here are the relevant parts of Dovecot v2.1.x configuration for Postfixadmin setup. diff --git a/DOCUMENTS/HASHING.md b/DOCUMENTS/HASHING.md index 885161df..fbe3434a 100644 --- a/DOCUMENTS/HASHING.md +++ b/DOCUMENTS/HASHING.md @@ -222,3 +222,10 @@ and then formatted to become : This format should support older passwords with a {MD5-CRYPT} prefix, to allow you to migrate. +## Dovecot 2.4 migration notes + +For Dovecot 2.4 deployments, especially those moving away from old +MD5/MD5-CRYPT hashes, see `DOCUMENTS/DOVECOT-2.4.md`. It includes notes about +temporary weak-scheme compatibility, post-login migration to `{ARGON2ID}`, and +the related security considerations. + diff --git a/DOCUMENTS/examples/add-mail-format-field.sql b/DOCUMENTS/examples/add-mail-format-field.sql new file mode 100644 index 00000000..e139f23c --- /dev/null +++ b/DOCUMENTS/examples/add-mail-format-field.sql @@ -0,0 +1,11 @@ +-- Optional local extension for gradual per-user Maildir to mdbox migration. +-- +-- This is not required for standard PostfixAdmin installations. +-- Use it only if your Dovecot 2.4 userdb query returns mail_driver/mail_path +-- from SQL and you want to migrate users gradually. + +ALTER TABLE mailbox + ADD COLUMN mail_format VARCHAR(16) NOT NULL DEFAULT 'maildir'; + +-- Optional visibility check: +SELECT username, mail_format FROM mailbox ORDER BY username LIMIT 20; diff --git a/DOCUMENTS/examples/dovecot-2.4-local.conf b/DOCUMENTS/examples/dovecot-2.4-local.conf new file mode 100644 index 00000000..ef8653e4 --- /dev/null +++ b/DOCUMENTS/examples/dovecot-2.4-local.conf @@ -0,0 +1,459 @@ +# Dovecot 2.4 example configuration for PostfixAdmin. +# Review hostnames, paths, users, groups, database names and passwords. +# +# This file must be included by the active Dovecot configuration. +# +# Preferred Dovecot 2.4 layout for this example: keep the PostfixAdmin SQL auth, +# storage, quota, Sieve and migration settings together in one local file, then +# include it explicitly from the end of dovecot.conf: +# !include_try /etc/dovecot/local.conf +# +# If you intentionally replace an older conf.d split layout, the end of +# dovecot.conf can be: +# #!include_try conf.d/*.conf +# !include_try local.conf +# +# Only comment out conf.d/*.conf after reviewing package defaults and moving +# any required local settings into local.conf. Alternatively, install this as a +# late conf.d file such as /etc/dovecot/conf.d/99-postfixadmin-local.conf. +# Validate with doveconf -n. + +ssl = yes +ssl_server_cert_file = /etc/letsencrypt/live/server.domain.com/fullchain.pem +ssl_server_key_file = /etc/letsencrypt/live/server.domain.com/privkey.pem +ssl_server_alt_cert_file = /etc/letsencrypt/live/server-rsa.domain.com/fullchain.pem +ssl_server_alt_key_file = /etc/letsencrypt/live/server-rsa.domain.com/privkey.pem + +# Set this to yes only while old MD5 / MD5-CRYPT hashes still need to work. +# Disable it again after migrating active users to stronger hashes. +auth_allow_weak_schemes = no + +ssl_min_protocol = TLSv1.2 +ssl_cipher_list = PROFILE=SYSTEM +ssl_server_prefer_ciphers = client + +login_log_format_elements = user=<%{user}> method=%{mechanism} rip=%{remote_ip} lip=%{local_ip} session=<%{session}> tls=%{ssl_security} +login_greeting = IMAPS/POP3S only ready. + +mail_driver = maildir +mail_path = /var/vmail/%{user | domain}/%{user | username} +mail_home = /var/vmail/%{user | domain}/%{user | username} +mail_uid = vmail +mail_gid = mail +mail_privileged_group = mail +first_valid_uid = 150 +last_valid_uid = 150 + +mail_max_userip_connections = 100 +mailbox_list_index = yes +imap_idle_notify_interval = 24mins + +auth_cache_ttl = 5mins +auth_cache_size = 50M +auth_cache_negative_ttl = 5mins +auth_cache_verify_password_with_worker = no +auth_allow_cleartext = no +auth_mechanisms = plain login +default_internal_user = dovecot + +sql_driver = mysql + +mysql 127.0.0.1 { + dbname = postfix + user = postfix + password = DATABASE_PASSWORD +} + +service imap-login { + inet_listener imap { + port = 0 + } + inet_listener imaps { + port = 993 + ssl = yes + } + client_limit = 1000 + process_limit = 200 + process_min_avail = 20 +} + +service pop3-login { + inet_listener pop3 { + port = 0 + } + inet_listener pop3s { + port = 995 + ssl = yes + } +} + +service lmtp { + unix_listener /var/spool/postfix/private/dovecot-lmtp { + mode = 0600 + user = postfix + group = postfix + } + process_limit = 16 +} + +service auth { + unix_listener auth-userdb { + mode = 0600 + user = vmail + group = mail + } + unix_listener /var/spool/postfix/private/auth { + mode = 0660 + user = postfix + group = postfix + } + user = $SET:default_internal_user + client_limit = 1000 +} + +service auth-worker { + user = vmail + process_limit = 50 +} + +namespace inbox { + type = private + inbox = yes + prefix = + separator = / + list = yes + + mailbox Drafts { + auto = subscribe + special_use = \Drafts + } + mailbox Junk { + auto = subscribe + special_use = \Junk + autoexpunge = 30d + sieve_script spam { + cause = copy + # Optional IMAPSieve spam learning. Install examples/sieve/report-spam.sieve + # and its helper under sieve_pipe_bin_dir before enabling this. + path = /var/vmail/sieve/bin/report-spam.sieve + type = after + } + } + imapsieve_from Junk { + sieve_script ham { + cause = copy + # Optional IMAPSieve ham learning. Install examples/sieve/report-ham.sieve + # and its helper under sieve_pipe_bin_dir before enabling this. + path = /var/vmail/sieve/bin/report-ham.sieve + type = after + } + } + mailbox Trash { + auto = subscribe + special_use = \Trash + autoexpunge = 30d + quota_storage_extra = 200M + } + mailbox Sent { + auto = subscribe + special_use = \Sent + } + mailbox "Sent Messages" { + auto = create + } +} + +namespace shared { + type = shared + prefix = Shared/$user/ + separator = / + mail_path = %{owner_home} + mail_index_private_path = ~/shared/%{owner_user} + subscriptions = no + list = children +} + +mail_plugins { + acl = yes + quota = yes + quota_clone = yes + fts = yes + fts_flatcurve = yes +} + +acl_driver = vfile + +acl_sharing_map { + dict file { + path = /var/lib/dovecot/acl/shared-mailboxes.db + } +} + +protocol imap { + mail_plugins { + imap_quota = yes + imap_acl = yes + imap_sieve = yes + mail_log = yes + notify = yes + fts = yes + fts_flatcurve = yes + } +} + +fts flatcurve { + commit_limit = 500 + min_term_size = 2 +} +fts_autoindex = yes + +language es { + default = yes + tokenizers = generic +} +language en { + tokenizers = generic +} +language_tokenizer_generic_algorithm = simple + +protocol lmtp { + mail_plugins { + quota = yes + quota_clone = yes + sieve = yes + } + postmaster_address = postmaster@domain.com +} + +protocol pop3 { + mail_plugins { + quota = yes + quota_clone = yes + } +} + +pop3_no_flag_updates = yes +pop3_client_workarounds = outlook-no-nuls oe-ns-eoh + +quota "User Quota" { + driver = count + enforce = yes + storage_grace = 50M + + warning warn-95 { + quota_storage_percentage = 95 + execute quota-warning { + args = 95 %{user} + } + } + warning warn-90 { + quota_storage_percentage = 90 + execute quota-warning { + args = 90 %{user} + } + } + warning warn-under { + quota_storage_percentage = 100 + threshold = under + execute quota-warning { + args = below %{user} + } + } +} + +service quota-warning { + # Install examples/quota-warning.sh as /usr/local/bin/quota-warning.sh + # before enabling quota warnings in production. + executable = script /usr/local/bin/quota-warning.sh + user = vmail + unix_listener quota-warning { + mode = 0660 + user = vmail + group = mail + } +} + +quota_status_success = DUNNO +quota_status_nouser = DUNNO +quota_status_overquota = 552 5.2.2 Mailbox is full + +service quota-status { + executable = quota-status -p postfix + unix_listener /var/spool/postfix/private/dovecot-quota { + mode = 0660 + user = postfix + group = postfix + } + client_limit = 10 +} + +sieve_script personal { + path = /var/vmail/%{user | domain}/%{user | username}/sieve + active_path = /var/vmail/%{user | domain}/%{user | username}/sieve/default.sieve +} +sieve_script before { + type = before + driver = file + path = /var/vmail/sieve/sieve-before.d/ +} +sieve_script after { + type = after + driver = file + path = /var/vmail/sieve/sieve-after.d/ +} +sieve_plugins = sieve_imapsieve sieve_extprograms +sieve_extensions { + copy = yes + vnd.dovecot.pipe = yes +} +# Helper scripts referenced by report-spam.sieve / report-ham.sieve are looked +# up relative to this directory. +sieve_pipe_bin_dir = /var/vmail/sieve/bin + +service indexer-worker { + vsz_limit = 2G + process_limit = 4 +} + +dict_server { + dict mysql { + driver = sql + sql_driver = mysql + mysql 127.0.0.1 { + dbname = postfix + user = postfix + password = DATABASE_PASSWORD + } + dict_map "priv/quota/messages" { + dict_map_pattern = "priv/quota/messages" + sql_table = quota2 + dict_map_username_field = username + dict_map_value_field messages { + type = uint + } + } + dict_map "priv/quota/storage" { + dict_map_pattern = "priv/quota/storage" + sql_table = quota2 + dict_map_username_field = username + dict_map_value_field bytes { + type = uint + } + } + } +} + +quota_clone { + dict proxy { + name = mysql + } +} + +service dict { + unix_listener dict { + mode = 0660 + user = vmail + group = mail + } +} + +protocols { + imap = yes + pop3 = yes + lmtp = yes + sieve = yes +} + +service managesieve-login { + inet_listener sieve { + port = 4190 + } + process_min_avail = 0 + vsz_limit = 1024M +} + +service stats { + unix_listener stats-reader { + user = vmail + mode = 0660 + } + unix_listener stats-writer { + user = apache + mode = 0660 + } +} + +passdb sql { + default_password_scheme = ARGON2ID + + # Normal query: + query = SELECT username AS user, password FROM mailbox WHERE username = '%{user}' AND active = '1' + + # Password migration query. Use temporarily with dovecot-upgrade-pass.sh, + # then revert to the normal query above. + # query = SELECT username AS user, password, '%{password}' AS userdb_plain_pass FROM mailbox WHERE username = '%{user}' AND active = '1' +} + +userdb sql { + # Standard Maildir-only query: + query = SELECT '/var/vmail/%{user | domain}/%{user | username}' AS home, 150 AS uid, 12 AS gid, CONCAT(quota, 'B') AS quota_storage_size FROM mailbox WHERE username = '%{user}' AND active = '1' + + # Optional per-user Maildir/mdbox query. Requires a local mailbox.mail_format + # field with values such as 'maildir' and 'mdbox'. + # query = SELECT '/var/vmail/%{user | domain}/%{user | username}' AS home, 150 AS uid, 12 AS gid, CONCAT(quota, 'B') AS quota_storage_size, CASE WHEN mail_format = 'mdbox' THEN 'mdbox' ELSE 'maildir' END AS mail_driver, CONCAT('/var/vmail/', '%{user | domain}/', '%{user | username}') AS mail_path FROM mailbox WHERE username = '%{user}' AND active = '1' + + iterate_query = SELECT username AS user FROM mailbox WHERE active = '1' +} + +userdb prefetch { +} + +service imap { + # Normal mode: + executable = imap + + # Optional password migration mode: + # Enable this only together with: + # - the passdb query that returns userdb_plain_pass + # - service imap-postlogin executable below + # - an installed and reviewed dovecot-upgrade-pass.sh script + # executable = imap imap-postlogin + vsz_limit = 1024M +} + +service imap-postlogin { + # Optional password migration mode: + # Enable only during a controlled password hash migration window. + # executable = script-login /usr/local/bin/dovecot-upgrade-pass.sh + unix_listener imap-postlogin { + mode = 0660 + user = $SET:default_internal_user + } +} + +service pop3 { + # Normal mode: + executable = pop3 + + # Optional password migration mode: + # Enable this only together with: + # - the passdb query that returns userdb_plain_pass + # - service pop3-postlogin executable below + # - an installed and reviewed dovecot-upgrade-pass.sh script + # executable = pop3 pop3-postlogin +} + +service pop3-postlogin { + # Optional password migration mode: + # Enable only during a controlled password hash migration window. + # executable = script-login /usr/local/bin/dovecot-upgrade-pass.sh + unix_listener pop3-postlogin { + mode = 0660 + user = $SET:default_internal_user + } +} + +# Debug only. WARNING: enabling this may log plaintext passwords. +# Never enable it on production systems or shared logs. +#auth_verbose = yes +#auth_verbose_passwords = plain diff --git a/DOCUMENTS/examples/dovecot-upgrade-pass.sh b/DOCUMENTS/examples/dovecot-upgrade-pass.sh new file mode 100644 index 00000000..f75f9a8d --- /dev/null +++ b/DOCUMENTS/examples/dovecot-upgrade-pass.sh @@ -0,0 +1,94 @@ +#!/bin/sh + +# Dovecot post-login password hash migration helper. +# +# Purpose: +# After a successful login, re-hash the user's password with ARGON2ID and +# update the PostfixAdmin mailbox row. Future logins skip this script once the +# stored password starts with {ARGON2ID}$argon2id$. +# +# Requirements: +# - Dovecot passdb query temporarily returns: +# '%{password}' AS userdb_plain_pass +# - Dovecot exposes the clear password to this script as PLAIN_PASS. +# - /etc/dovecot/mysql-postfix.cnf is readable by the script user and contains +# safe MySQL credentials. +# +# Security: +# Use only during a controlled migration window. Revert the passdb query after +# migration and keep auth_verbose_passwords disabled in production. + +set -u + +MYSQL_CNF=${MYSQL_CNF:-/etc/dovecot/mysql-postfix.cnf} +DB_NAME=${DB_NAME:-postfix} +DOVEADM=${DOVEADM:-/usr/bin/doveadm} +MYSQL=${MYSQL:-/usr/bin/mysql} + +log() { + printf '%s\n' "$*" >&2 +} + +sql_escape() { + # Escape single quotes for SQL string literals. + printf "%s" "$1" | sed "s/'/''/g" +} + +finish_login() { + exec "$@" +} + +if [ -z "${USER:-}" ]; then + log "MIGRATION_SKIP: USER is empty; continuing login." + finish_login "$@" +fi + +if [ -z "${PLAIN_PASS:-}" ]; then + log "MIGRATION_SKIP: PLAIN_PASS is empty; continuing login." + finish_login "$@" +fi + +if [ ! -f "$MYSQL_CNF" ]; then + log "MIGRATION_SKIP: missing MySQL defaults file: $MYSQL_CNF" + finish_login "$@" +fi + +USER_SQL=$(sql_escape "$USER") + +CURRENT_HASH=$("$MYSQL" --defaults-extra-file="$MYSQL_CNF" -N -B "$DB_NAME" \ + -e "SELECT password FROM mailbox WHERE username='${USER_SQL}' AND active='1' LIMIT 1;" 2>/dev/null) + +case "$CURRENT_HASH" in + "{ARGON2ID}\$argon2id\$"*) + if [ ${#CURRENT_HASH} -gt 50 ]; then + log "MIGRATION_SKIP: $USER already uses ARGON2ID." + finish_login "$@" + fi + ;; +esac + +NEW_HASH=$("$DOVEADM" pw -s ARGON2ID -p "$PLAIN_PASS" 2>/dev/null) + +case "$NEW_HASH" in + "{ARGON2ID}\$argon2id\$"*) ;; + *) + log "MIGRATION_ERROR: doveadm returned an invalid ARGON2ID hash; database not updated." + finish_login "$@" + ;; +esac + +if [ ${#NEW_HASH} -lt 50 ]; then + log "MIGRATION_ERROR: generated hash is unexpectedly short; database not updated." + finish_login "$@" +fi + +NEW_HASH_SQL=$(sql_escape "$NEW_HASH") + +if "$MYSQL" --defaults-extra-file="$MYSQL_CNF" "$DB_NAME" \ + -e "UPDATE mailbox SET password='${NEW_HASH_SQL}' WHERE username='${USER_SQL}' AND active='1';" >/dev/null 2>&1; then + log "MIGRATION_SUCCESS: updated $USER to ARGON2ID." +else + log "MIGRATION_ERROR: MySQL update failed for $USER." +fi + +finish_login "$@" diff --git a/DOCUMENTS/examples/migrate-maildir-to-mdbox.sh b/DOCUMENTS/examples/migrate-maildir-to-mdbox.sh new file mode 100644 index 00000000..06fb212e --- /dev/null +++ b/DOCUMENTS/examples/migrate-maildir-to-mdbox.sh @@ -0,0 +1,232 @@ +#!/bin/sh + +# Gradual per-user Maildir to mdbox migration helper for Dovecot 2.4. +# +# Usage: +# migrate-maildir-to-mdbox.sh user@example.com +# migrate-maildir-to-mdbox.sh @example.com +# migrate-maildir-to-mdbox.sh ALL +# migrate-maildir-to-mdbox.sh user@example.com --real +# +# The default mode is dry-run. Use --real only after testing, backing up the +# database and mail storage, and reviewing all paths below. + +set -u + +MYSQL=${MYSQL:-/usr/bin/mysql} +DOVEADM=${DOVEADM:-/usr/bin/doveadm} +MYSQL_CNF=${MYSQL_CNF:-/etc/dovecot/mysql-postfix.cnf} +DB_NAME=${DB_NAME:-postfix} + +VMAIL_ROOT=${VMAIL_ROOT:-/var/vmail} +MIGRATION_ROOT=${MIGRATION_ROOT:-/var/vmail/mdbox} +BACKUP_ROOT=${BACKUP_ROOT:-/var/vmail/MIGRATION_TMP} +VMAIL_USER=${VMAIL_USER:-vmail} +VMAIL_GROUP=${VMAIL_GROUP:-mail} + +PARAM=${1:-} +OPTION=${2:-} +MODE=DRY_RUN + +if [ -z "$PARAM" ]; then + echo "Usage: $0 [user@example.com | @example.com | ALL] [--real]" >&2 + exit 1 +fi + +if [ "$OPTION" = "--real" ]; then + MODE=REAL +elif [ -n "$OPTION" ]; then + echo "ERROR: unsupported option: $OPTION" >&2 + exit 1 +fi + +log() { + printf '%s\n' "$*" +} + +err() { + printf '%s\n' "$*" >&2 +} + +sql_escape() { + printf "%s" "$1" | sed "s/'/''/g" +} + +is_safe_email() { + printf "%s" "$1" | grep -Eq '^[A-Za-z0-9._%+~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$' +} + +is_safe_domain() { + printf "%s" "$1" | grep -Eq '^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$' +} + +require_safe_child_path() { + child=$1 + parent=$2 + case "$child" in + "$parent"/*) return 0 ;; + *) + err "SAFETY_ERROR: path '$child' is outside '$parent'" + return 1 + ;; + esac +} + +mysql_exec() { + "$MYSQL" --defaults-extra-file="$MYSQL_CNF" "$DB_NAME" -e "$1" +} + +mysql_scalar() { + "$MYSQL" --defaults-extra-file="$MYSQL_CNF" -N -B "$DB_NAME" -e "$1" +} + +if [ ! -f "$MYSQL_CNF" ]; then + err "ERROR: missing MySQL defaults file: $MYSQL_CNF" + exit 1 +fi + +if ! mysql_exec "SELECT 1;" >/dev/null 2>&1; then + err "ERROR: MySQL connection test failed." + exit 1 +fi + +log "=== Selected mode: $MODE ===" +log "MySQL connection: OK" + +if [ "$MODE" = "REAL" ]; then + mkdir -p "$MIGRATION_ROOT" "$BACKUP_ROOT" + chown "$VMAIL_USER:$VMAIL_GROUP" "$MIGRATION_ROOT" "$BACKUP_ROOT" + chmod 750 "$MIGRATION_ROOT" "$BACKUP_ROOT" +fi + +migrate_user() { + mailbox=$1 + + if ! is_safe_email "$mailbox"; then + err "SKIP: '$mailbox' does not look like a safe email address." + return 1 + fi + + mailbox_sql=$(sql_escape "$mailbox") + current_format=$(mysql_scalar "SELECT mail_format FROM mailbox WHERE username='${mailbox_sql}' LIMIT 1;" 2>/dev/null) + + if [ "$current_format" = "mdbox" ]; then + log "SKIP: $mailbox is already mdbox." + return 0 + fi + + if [ "$MODE" = "DRY_RUN" ]; then + log "[DRY-RUN] Would migrate: $mailbox (current format: ${current_format:-unknown})" + return 0 + fi + + domain=${mailbox#*@} + account=${mailbox%@*} + + base_dir="$VMAIL_ROOT/$domain/$account" + tmp_mdbox="$MIGRATION_ROOT/$domain/$account" + backup_domain="$BACKUP_ROOT/$domain" + timestamp=$(date +%Y%m%d_%H%M%S) + backup_old="$backup_domain/${account}_MAILDIR_OLD_${timestamp}" + + require_safe_child_path "$base_dir" "$VMAIL_ROOT" || return 1 + require_safe_child_path "$tmp_mdbox" "$MIGRATION_ROOT" || return 1 + require_safe_child_path "$backup_old" "$BACKUP_ROOT" || return 1 + + log ">>> [REAL] Processing: $mailbox" + + if [ ! -d "$base_dir" ]; then + err "SAFETY_ERROR: source Maildir does not exist: $base_dir" + return 1 + fi + + "$DOVEADM" auth cache flush "$mailbox" >/dev/null 2>&1 || true + + rm -rf "$tmp_mdbox" + mkdir -p "$MIGRATION_ROOT/$domain" "$backup_domain" + chown -R "$VMAIL_USER:$VMAIL_GROUP" "$MIGRATION_ROOT/$domain" "$backup_domain" + + log "[1/5] Syncing mailbox to temporary mdbox location..." + if ! "$DOVEADM" sync -u "$mailbox" "mdbox:$tmp_mdbox"; then + err "SAFETY_ERROR: initial doveadm sync failed." + rm -rf "$tmp_mdbox" + return 1 + fi + + log "[2/5] Disabling account and closing active sessions..." + mysql_exec "UPDATE mailbox SET active='0' WHERE username='${mailbox_sql}';" + "$DOVEADM" kick "$mailbox" >/dev/null 2>&1 || true + "$DOVEADM" sync -u "$mailbox" "mdbox:$tmp_mdbox" >/dev/null 2>&1 || true + + if [ ! -d "$tmp_mdbox/storage" ] || [ ! -d "$tmp_mdbox/mailboxes" ]; then + err "SAFETY_ERROR: temporary mdbox structure is incomplete." + mysql_exec "UPDATE mailbox SET active='1' WHERE username='${mailbox_sql}';" + rm -rf "$tmp_mdbox" + return 1 + fi + + log "[3/5] Backing up old Maildir and installing mdbox..." + if ! mv "$base_dir" "$backup_old"; then + err "SAFETY_ERROR: could not move original Maildir to backup." + mysql_exec "UPDATE mailbox SET active='1' WHERE username='${mailbox_sql}';" + return 1 + fi + + if ! mv "$tmp_mdbox" "$base_dir"; then + err "ERROR: could not install mdbox. Restoring original Maildir..." + mv "$backup_old" "$base_dir" + mysql_exec "UPDATE mailbox SET active='1' WHERE username='${mailbox_sql}';" + return 1 + fi + + chown -R "$VMAIL_USER:$VMAIL_GROUP" "$base_dir" + + log "[4/5] Updating mailbox format and re-enabling account..." + mysql_exec "UPDATE mailbox SET mail_format='mdbox', active='1' WHERE username='${mailbox_sql}';" + "$DOVEADM" auth cache flush "$mailbox" >/dev/null 2>&1 || true + + log "[5/5] Rebuilding FTS indexes..." + "$DOVEADM" fts rescan -u "$mailbox" || true + "$DOVEADM" index -u "$mailbox" "*" || true + + rm -rf "$base_dir/cur" "$base_dir/new" "$base_dir/tmp" "$base_dir/maildirfolder" + + log "SUCCESS: $mailbox migrated to mdbox. Old Maildir backup: $backup_old" + log "------------------------------------------------" +} + +case "$PARAM" in + ALL) + log "Selecting active accounts: all mailboxes" + accounts=$(mysql_scalar "SELECT username FROM mailbox WHERE active='1';") + ;; + @*) + domain=${PARAM#@} + if ! is_safe_domain "$domain"; then + err "ERROR: unsafe domain argument: $PARAM" + exit 1 + fi + domain_sql=$(sql_escape "$domain") + log "Selecting active accounts for domain: @$domain" + accounts=$(mysql_scalar "SELECT username FROM mailbox WHERE active='1' AND username LIKE '%@${domain_sql}';") + ;; + *) + if ! is_safe_email "$PARAM"; then + err "ERROR: unsafe mailbox argument: $PARAM" + exit 1 + fi + log "Selecting one mailbox: $PARAM" + accounts=$PARAM + ;; +esac + +if [ -z "${accounts:-}" ]; then + err "No active accounts found." + exit 1 +fi + +for account in $accounts; do + migrate_user "$account" +done + +log "=== Process finished in $MODE mode ===" diff --git a/DOCUMENTS/examples/quota-warning.sh b/DOCUMENTS/examples/quota-warning.sh new file mode 100644 index 00000000..072cca62 --- /dev/null +++ b/DOCUMENTS/examples/quota-warning.sh @@ -0,0 +1,68 @@ +#!/bin/sh + +# Dovecot quota warning delivery helper. +# +# Called by Dovecot quota warnings, for example: +# execute quota-warning { +# args = 95 %{user} +# } +# +# It delivers a local warning message directly to the user's INBOX using +# doveadm. Review sender address, support text and local doveadm permissions. + +set -u + +PERCENT=${1:-} +USER=${2:-} +DOVEADM=${DOVEADM:-/usr/bin/doveadm} +FROM_ADDRESS=${FROM_ADDRESS:-postmaster@domain.com} +SERVER_NAME=${SERVER_NAME:-mail.domain.com} +SUPPORT_SIGNATURE=${SUPPORT_SIGNATURE:-Mail Support} + +if [ -z "$PERCENT" ] || [ -z "$USER" ]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +case "$PERCENT" in + below|[0-9]|[0-9][0-9]|100) ;; + *) + echo "ERROR: unsafe quota percentage argument: $PERCENT" >&2 + exit 1 + ;; +esac + +case "$USER" in + *@*.*) ;; + *) + echo "ERROR: unsafe user argument: $USER" >&2 + exit 1 + ;; +esac + +if [ "$PERCENT" = "below" ]; then + SUBJECT="Storage alert: your mailbox is below the quota limit" + STATUS_TEXT="Your mailbox is now below the configured quota limit." +else + SUBJECT="Storage alert: your mailbox is at ${PERCENT}% capacity" + STATUS_TEXT="Your mailbox (${USER}) has reached ${PERCENT}% of its assigned storage." +fi + +cat <