Tag: imap


  • Installing a Mail Server

    This guide walks through deploying a lightweight, always-on mail server for yourdomain.net on a dedicated Mail VM running Debian 13. The stack uses Postfix (SMTP), OpenDKIM (DKIM signing), Dovecot (IMAP/LMTP), Roundcube behind nginx (webmail), and nftables (firewall). It covers architecture, prerequisites, automated installation scripts, firewall rules, secret management, and day-2 account provisioning.

    1. Architecture & Capabilities

    • Mailboxes: Dedicated virtual mailboxes (no aliases): admin, dmarc, postmaster, abuse, no-reply, and user.
    • Private Network Access Only: Webmail, IMAP, authenticated mail submission, SSH, and VNC are restricted strictly to private RFC 1918 networks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).
    • Public Internet Access: Only incoming mail on port 25 is exposed to the internet, and only for addresses listed in EXTERNAL. Mail addressed to any other user from outside is rejected.
    • Internal Relaying: Unauthenticated sending on port 25 is permitted only from 10.0.1.0/24 (for LAN applications and services).
    • Outbound Delivery: Outgoing mail is DKIM-signed (selector mail) and delivered directly to recipient servers. Specific destination domains (configured in RELAY_DOMAINS) can optionally route through an external SMTP relay with sender rewriting enabled only on that path.
    • Backup Strategy: None for mailbox contents; the Mail VM itself is designed to be rebuilt quickly from the configuration scripts and password vault.
    ServiceAddress / PortAllowed Clients
    Webmail[https://mail.yourdomain.net](https://mail.yourdomain.net)Private addresses
    IMAPmail.yourdomain.net, port 993 (TLS)Private addresses
    Sending (authenticated)mail.yourdomain.net, port 587 (STARTTLS)Private addresses
    Sending (unauthenticated)mail.yourdomain.net, port 2510.0.1.0/24
    Incoming mailPort 25Public internet (addresses in EXTERNAL)

    The login username for every mailbox is its full email address (in Roundcube webmail, the local part before @ is sufficient), and passwords are stored in a KeePassXC vault.

    2. Requirements & Prerequisites

    The Mail VM

    • A dedicated Mail VM running Debian 13 with a static private IP (10.0.1.24) and FQDN mail.yourdomain.net.
    • An administrative user (sysadmin) with SSH key access from your management machine and passwordless sudo.

    DNS & Networking

    • Local DNS: mail.yourdomain.net → 10.0.1.24.
    • Router / NAT: Forward public port 25 to 10.0.1.24, and route the Mail VM’s outbound mail through your static public IP (shown below using documentation IP 203.0.113.10).
    • Reverse DNS (PTR): Ask your ISP or hosting provider to set the PTR record for 203.0.113.10 to mail.yourdomain.net.

    Public DNS Records (yourdomain.net):

    TypeNameValue
    Amail203.0.113.10
    MX@mail.yourdomain.net (priority 10)
    TXT@v=spf1 mx a:mail.yourdomain.net ~all
    TXT_dmarcv=DMARC1; p=none; rua=mailto:dmarc@yourdomain.net; adkim=r; aspf=r
    TXTmail._domainkeyYour DKIM public key record

    Secrets & Certificates (KeePassXC Vault)

    • Wildcard TLS Certificate (*.yourdomain.net): yourdomain.crt, ca_bundle.crt, and yourdomain.key stored in ~/ssl on your management machine (and backed up in the vault under Certificates/yourdomain).
    • DKIM Private Key: Vault entry Mail/DKIM key (selector mail) with attachment mail.private.
    • SMTP Relay Account (Optional): Vault entry Mail/Relay Provider containing the relay username and password.

    Configuring Passwordless sudo on the Mail VM

    Because the deployment scripts execute remote commands via ssh sysadmin@mail.yourdomain.net 'sudo …', the sysadmin user needs passwordless sudo.

    Log in to the Mail VM (ssh sysadmin@mail.yourdomain.net) and confirm your prompt shows sysadmin@mail before running:

    echo 'sysadmin ALL=(ALL) NOPASSWD: ALL' > /tmp/nopwsudo
    sudo visudo -c -f /tmp/nopwsudo
    sudo install -m 0440 -o root -g root /tmp/nopwsudo /etc/sudoers.d/010_sysadmin-nopasswd
    rm /tmp/nopwsudo
    

    Ensure visudo reports parsed OK before installing; a malformed file in /etc/sudoers.d can break sudo, and the filename must not contain a dot.

    Test locally on the Mail VM:

    sudo -k
    sudo -n true && echo OK
    

    Test from your management machine:

    ssh sysadmin@mail.yourdomain.net 'sudo -n true && echo OK'
    

    To revert this rule later, run sudo rm /etc/sudoers.d/010_sysadmin-nopasswd.

    3. Deployment Scripts Overview

    The installation is split into four idempotent, secret-free scripts (full source code is in the Appendix):

    ScriptRuns OnPurposeWhen to Run
    1-packages.shMail VMPreseeds and installs all required packagesOnce on a fresh Mail VM
    2-setup.shMail VM (as root, saved to /usr/local/sbin/mail-vm-setup.sh)Writes full configs for Postfix, OpenDKIM, Dovecot, Roundcube, and nginx; restarts servicesInitial install and after modifying mailboxes, external recipients, or relay domains
    3-firewall.shMail VM (as root, saved to /usr/local/sbin/mail-vm-firewall.sh)Writes and loads /etc/nftables.conf with a 90-second dead-man’s switchInitial install and after firewall rule changes
    4-secrets.shManagement machine (with KeePassXC vault)Pushes DKIM key, relay credentials, and mailbox password hashes; reruns setup; tests IMAP/SMTP/DKIMInitial install, new mailboxes, or password/relay updates

    4. Step-by-Step Installation

    Run steps 4.1–4.4 from the scripts directory on your management machine.

    4.1 Install Packages

    Package(s)Role
    postfix, libsasl2-modulesSMTP server and SASL relay authentication
    postfix-policyd-spf-pythonInbound SPF verification
    opendkim, opendkim-toolsOutbound DKIM signing and key tools
    dovecot-core, dovecot-imapd, dovecot-lmtpdIMAP server, LMTP local delivery, SASL auth
    roundcube, roundcube-sqlite3Webmail client with SQLite backend
    nginx, php-fpm, php-{sqlite3,intl,mbstring,xml,zip,curl,gd}Web server and PHP runtime for Roundcube
    nftablesHost firewall
    bsd-mailx, ca-certificatesCLI mail testing tool and trusted root CAs

    Execute the package script remotely:

    ssh sysadmin@mail.yourdomain.net 'bash -s' < 1-packages.sh
    

    This preseeds Postfix (“Internet Site” for yourdomain.net) and Roundcube (SQLite), installs all packages without recommended extras, and prints installed versions and listening ports.

    4.2 Deploy TLS Certificates

    Build the full certificate chain (leaf + intermediates, excluding root) and copy the chain and private key to the Mail VM:

    ssh sysadmin@mail.yourdomain.net 'sudo install -d -m 0755 /etc/postfix/tls'
    cat ~/ssl/yourdomain.crt ~/ssl/ca_bundle.crt \
      | ssh sysadmin@mail.yourdomain.net 'sudo sh -c "umask 022; cat > /etc/postfix/tls/fullchain.pem"'
    ssh sysadmin@mail.yourdomain.net 'sudo sh -c "umask 077; cat > /etc/postfix/tls/privkey.pem"' < ~/ssl/yourdomain.key
    

    Verify on the Mail VM that the certificate subject, expiration date, and private key match:

    sudo openssl x509 -in /etc/postfix/tls/fullchain.pem -noout -subject -enddate
    [ "$(sudo openssl x509 -in /etc/postfix/tls/fullchain.pem -noout -pubkey)" = "$(sudo openssl pkey -in /etc/postfix/tls/privkey.pem -pubout)" ] && echo "key matches"
    

    Postfix, Dovecot, and nginx all share these two TLS files.

    4.3 Configure Services

    Install and run the configuration script:

    ssh sysadmin@mail.yourdomain.net 'sudo install -m 0755 /dev/stdin /usr/local/sbin/mail-vm-setup.sh' < 2-setup.sh
    ssh sysadmin@mail.yourdomain.net 'sudo bash /usr/local/sbin/mail-vm-setup.sh'
    

    The script verifies it is running as root on mail.yourdomain.net and that the TLS files exist. Everything customizable lives in three variables at the top of the script:

    • MAILBOXES: All virtual mailboxes (admin dmarc postmaster abuse no-reply user).
    • EXTERNAL: Mailboxes permitted to receive mail from the public internet.
    • RELAY_DOMAINS: Destination domains routed through the external SMTP relay.

    It configures:

    • Mail storage: System user vmail (UID 5000) and Maildir paths under /var/vmail/yourdomain.net/<mailbox>/Maildir.
    • Postfix: Virtual mailbox delivery via Dovecot LMTP, SPF checks on external mail, authenticated submission on port 587 with sender-login enforcement, private client header stripping, and optional relay transport.
    • OpenDKIM: Signs mail from internal hosts and authenticated users using selector mail (remains stopped until the private key is deployed in Step 4.5).
    • Dovecot: IMAPS-only on port 993, password hashes from /etc/dovecot/users, auto-subscribed Drafts, Sent, Junk, and Trash folders.
    • Roundcube & nginx: HTTPS webmail on [https://mail.yourdomain.net](https://mail.yourdomain.net) with HTTP-to-HTTPS redirection.

    4.4 Configure the Firewall

    Install and apply the nftables ruleset:

    ssh sysadmin@mail.yourdomain.net 'sudo install -m 0755 /dev/stdin /usr/local/sbin/mail-vm-firewall.sh' < 3-firewall.sh
    ssh sysadmin@mail.yourdomain.net 'sudo bash /usr/local/sbin/mail-vm-firewall.sh'
    ssh sysadmin@mail.yourdomain.net 'sudo touch /run/nft-confirmed && sudo systemctl enable nftables'
    

    The second command loads the firewall with a 90-second safety rollback: if you cannot open a new SSH connection to run the third command and create /run/nft-confirmed, the rules automatically flush so you are not locked out.

    TrafficPolicy
    Incoming TCP port 25Accept from everywhere
    Incoming TCP ports 22, 80, 443, 587, 993, 5900Accept from 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
    Established/related traffic & ICMPAccept
    All other incoming trafficDrop
    Outgoing trafficAccept

    Inspect active rules anytime with sudo nft list ruleset.

    4.5 Deploy Secrets & Verify Logins

    On your management machine (where KeePassXC holds the vault):

    bash 4-secrets.sh
    

    You will be prompted once for your KeePassXC master password. The script never prints secrets—only OK, FAIL, and character lengths—and performs six steps:

    1. Copies the DKIM private key to the Mail VM and verifies it against the live mail._domainkey.yourdomain.net DNS TXT record.
    2. Writes the SMTP relay credentials to /etc/postfix/sasl_passwd.
    3. Generates 24-character passwords in KeePassXC for any missing mailbox entries and writes SHA512-CRYPT hashes to /etc/dovecot/users.
    4. Reruns /usr/local/sbin/mail-vm-setup.sh to activate OpenDKIM and relay rewriting.
    5. Tests IMAP (port 993) and SMTP submission (port 587) logins for every mailbox.
    6. Sends a test message through port 25 and confirms it arrives in admin‘s Maildir with a valid DKIM-Signature header.

    5. Post-Installation Checks

    1. Open [https://mail.yourdomain.net](https://mail.yourdomain.net) from a private network and log in with a mailbox password from the vault.
    2. Send an internal email from one mailbox to another and verify delivery.
    3. Send an external email to admin@yourdomain.net (should succeed) and to a nonexistent address (should be rejected with 550).
    4. Send an email to a major external provider (such as Gmail) and inspect the message headers for spf=pass and dkim=pass.
    5. If using an outbound relay, send a test message to a domain in RELAY_DOMAINS and verify it routes through the relay.

    6. Day-2 Operations & Adding New Email Accounts

    Common Maintenance Tasks

    TaskAction
    Add a mailbox (automated)Add the name to MAILBOXES in 2-setup.sh and 4-secrets.sh (and EXTERNAL if receiving external mail); rerun Steps 4.3 and 4.5
    Change a mailbox passwordUpdate the password in KeePassXC and rerun Step 4.5
    Add a relay domainAdd the domain to RELAY_DOMAINS in 2-setup.sh and rerun Step 4.3
    Update relay passwordUpdate the vault entry and rerun Step 4.5
    Renew TLS certificateCopy new files as in Step 4.2, then run sudo systemctl restart postfix dovecot nginx
    Update firewall rulesEdit 3-firewall.sh and rerun Step 4.4
    Rebuild on a new Mail VMRun Steps 4.1 through 4.5 in order

    Useful monitoring commands on the Mail VM:

    sudo postqueue -p                                              # View queued mail
    sudo journalctl -u 'postfix*' -u dovecot -u opendkim -f        # Follow live mail logs
    systemctl is-active postfix dovecot opendkim nginx php8.4-fpm  # Check service health
    

    Manually Adding a Single Virtual Mailbox

    (Runbook – Day N – Executing setup again will remove the added mailboxes)

    If you need to provision a quick standalone mailbox directly on the Mail VM (for example, a dedicated service account like unifi), run the following steps as root on mail.yourdomain.net, replacing <user> with the account name:

    1. Generate the password hash (copy the full output including {SHA512-CRYPT}):
      1. doveadm pw -s SHA512-CRYPT
    2. Add the account to Dovecot (check your path with doveconf -n passdb if unsure):
      1. echo '<user>@yourdomain.net:{SHA512-CRYPT}<paste_hash_here>' >> /etc/dovecot/users
    3. Register the virtual mailbox in Postfix:
      1. echo '<user>@yourdomain.net OK' >> /etc/postfix/mailboxes
      2. postmap /etc/postfix/mailboxes
    4. Authorize the sender address for port 587 submission:
      1. echo '<user>@yourdomain.net <user>@yourdomain.net' >> /etc/postfix/sender_login
      2. postmap /etc/postfix/sender_login
        1. (If this mailbox also needs to receive mail from the public internet, add <user>@yourdomain.net OK to /etc/postfix/inbound_recipients and run postmap /etc/postfix/inbound_recipients.)
    5. Reload Postfix without dropping active connections:
      1. systemctl reload postfix
    6. Verify authentication and initialize the Maildir:
      1. doveadm auth test <user>@yourdomain.net '<password>' Confirm auth succeeded, then log into Roundcube webmail once to initialize the Maildir folders.

    Client & Appliance SMTP Settings Reference

    When configuring mail clients or network appliances (such as a UniFi controller) to send alerts through the Mail VM:

    SettingValue
    SMTP Servermail.yourdomain.net
    Port587
    EncryptionRequire STARTTLS (SSL unchecked)
    AuthenticationEnabled (PLAIN over TLS)
    SMTP Username<user>@yourdomain.net
    Sender AddressMust match <user>@yourdomain.net

    7. File Locations on the Mail VM

    ComponentPath
    Mailboxes/var/vmail/yourdomain.net/<mailbox>/Maildir
    Mailbox password hashes/etc/dovecot/users
    Postfix configs & maps/etc/postfix/main.cf, master.cf, mailboxes, inbound_recipients, transport, sender_login
    Relay credentials/etc/postfix/sasl_passwd
    TLS certificate & key/etc/postfix/tls/fullchain.pem, /etc/postfix/tls/privkey.pem
    DKIM private key/etc/opendkim/keys/yourdomain.net/mail.private
    Webmail & nginx/etc/roundcube/config.inc.php, /etc/nginx/sites-available/roundcube
    Firewall rules/etc/nftables.conf
    Installed scripts/usr/local/sbin/mail-vm-setup.sh, /usr/local/sbin/mail-vm-firewall.sh

    Appendix: Complete Scripts

    1-packages.sh

    #!/bin/bash
    # Run on: mail.yourdomain.net (sysadmin, sudo) – step 1: install mail server packages; no configuration yet
    
    if [ "$(hostname -f)" = "mail.yourdomain.net" ] && [ "$(id -un)" = "sysadmin" ]; then
      set -u
      export DEBIAN_FRONTEND=noninteractive
    
      echo ">> preseed (Postfix as Internet Site, Roundcube with SQLite)"
      printf '%s\n' \
        'postfix postfix/main_mailer_type select Internet Site' \
        'postfix postfix/mailname string yourdomain.net' \
        'roundcube-core roundcube/dbconfig-install boolean true' \
        'roundcube-core roundcube/database-type select sqlite3' \
        | sudo -n debconf-set-selections
    
      echo ">> apt-get update"
      sudo -n apt-get update -q > /tmp/mail-vm-apt-update.log 2>&1
      echo "update rc=$?"
    
      echo ">> apt-get install"
      sudo -n apt-get install -y -q --no-install-recommends \
        postfix postfix-policyd-spf-python opendkim opendkim-tools libsasl2-modules \
        dovecot-core dovecot-imapd dovecot-lmtpd \
        roundcube roundcube-sqlite3 nginx php-fpm php-sqlite3 php-intl php-mbstring php-xml php-zip php-curl php-gd \
        nftables bsd-mailx ca-certificates > /tmp/mail-vm-apt-install.log 2>&1
      rc=$?
      echo "install rc=$rc"
      [ $rc -eq 0 ] || tail -15 /tmp/mail-vm-apt-install.log
    
      echo ">> installed versions"
      for p in postfix postfix-policyd-spf-python opendkim dovecot-core dovecot-imapd dovecot-lmtpd roundcube roundcube-core roundcube-sqlite3 nginx php-fpm nftables; do
        printf '%s=%s  ' "$p" "$(dpkg-query -W -f='${Version}' "$p" 2>/dev/null)"
      done
      echo
    
      echo ">> services after installation"
      for s in postfix opendkim dovecot nginx nftables; do
        printf '%s=%s/%s  ' "$s" "$(systemctl is-active "$s")" "$(systemctl is-enabled "$s" 2>/dev/null)"
      done
      printf 'php-fpm=%s\n' "$(systemctl list-units --type=service --no-legend 'php*-fpm.service' | awk '{print $1"="$3"/"$4}' | tr '\n' ' ')"
    
      echo ">> listening TCP ports"
      sudo -n ss -ltnpH | awk '{split($NF,a,"\""); print $4, a[2]}' | sort -u | tr '\n' ';'
      echo
    else
      echo "WRONG HOST/USER – nothing done"
    fi
    

    2-setup.sh

    #!/bin/bash
    # Run on: mail.yourdomain.net (root) – Mail VM setup: Postfix, OpenDKIM, Dovecot 2.4, Roundcube, nginx.
    #   sudo bash /usr/local/sbin/mail-vm-setup.sh
    # Idempotent. Secrets (DKIM key, relay account, mailbox passwords) are deployed separately via 4-secrets.sh.
    
    set -euo pipefail
    
    DOMAIN=yourdomain.net
    HOST=mail.$DOMAIN
    SELECTOR=mail
    KEYDIR=/etc/opendkim/keys/$DOMAIN
    MAILBOXES="admin dmarc postmaster abuse no-reply user"
    EXTERNAL="admin dmarc postmaster abuse no-reply user"
    RELAY="[smtp.relayprovider.com]:587"
    RELAY_DOMAINS="partnerdomain.com relayprovider.com"
    
    die() { echo "ERROR: $*" >&2; exit 1; }
    [ "$(id -u)" = 0 ] || die "run as root"
    [ "$(hostname -f)" = "$HOST" ] || die "not the mail server"
    for f in fullchain.pem privkey.pem; do
      [ -s /etc/postfix/tls/$f ] || die "/etc/postfix/tls/$f missing"
    done
    
    echo ">> 1. mail user and store"
    getent passwd vmail > /dev/null || useradd --system --uid 5000 --user-group --home-dir /var/vmail --shell /usr/sbin/nologin vmail
    install -d -o vmail -g vmail -m 0750 /var/vmail
    
    echo ">> 2. Postfix"
    tee /etc/postfix/main.cf > /dev/null <<'CF'
    # /etc/postfix/main.cf – mail server (written by mail-vm-setup.sh)
    compatibility_level = 3.9
    myhostname = mail.yourdomain.net
    mydomain = yourdomain.net
    myorigin = $mydomain
    mydestination = $myhostname, localhost
    inet_interfaces = all
    inet_protocols = ipv4
    
    # Unauthenticated relay permitted only from local LAN subnet
    mynetworks = 127.0.0.0/8 10.0.1.0/24
    smtpd_banner = $myhostname ESMTP
    biff = no
    append_dot_mydomain = no
    readme_directory = no
    alias_maps = hash:/etc/aliases
    alias_database = hash:/etc/aliases
    message_size_limit = 10485760
    disable_vrfy_command = yes
    smtpd_helo_required = yes
    
    # Virtual mailboxes delivered to Dovecot via LMTP
    virtual_mailbox_domains = yourdomain.net
    virtual_mailbox_maps = hash:/etc/postfix/mailboxes
    virtual_transport = lmtp:unix:private/dovecot-lmtp
    
    # Relay & recipient restrictions
    smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
    smtpd_recipient_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_non_fqdn_recipient,
        reject_unauth_destination,
        check_client_access cidr:/etc/postfix/private_clients,
        check_policy_service unix:private/policyd-spf,
        check_recipient_access hash:/etc/postfix/inbound_recipients,
        reject
    reject_code = 550
    policyd-spf_time_limit = 3600
    
    # TLS configuration
    smtpd_tls_cert_file = /etc/postfix/tls/fullchain.pem
    smtpd_tls_key_file = /etc/postfix/tls/privkey.pem
    smtpd_tls_security_level = may
    smtpd_tls_loglevel = 1
    smtp_tls_security_level = may
    smtp_tls_CApath = /etc/ssl/certs
    smtp_tls_loglevel = 1
    
    # SASL authentication enabled on port 587 (master.cf) via Dovecot
    smtpd_sasl_auth_enable = no
    smtpd_sasl_type = dovecot
    smtpd_sasl_path = private/auth
    
    # Optional per-domain relay routing
    transport_maps = hash:/etc/postfix/transport
    
    # DKIM signing via OpenDKIM
    milter_default_action = accept
    milter_protocol = 6
    smtpd_milters = inet:127.0.0.1:8891
    non_smtpd_milters = $smtpd_milters
    
    # Strip internal private IP Received headers from outgoing mail
    header_checks = regexp:/etc/postfix/header_checks
    CF
    
    tee /etc/postfix/header_checks > /dev/null <<'HC'
    /^Received: from [^[]*\[(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)[0-9.]+\]\)/ IGNORE
    HC
    
    tee /etc/postfix/private_clients > /dev/null <<'PC'
    10.0.0.0/8      OK
    172.16.0.0/12   OK
    192.168.0.0/16  OK
    PC
    
    : > /etc/postfix/mailboxes
    : > /etc/postfix/sender_login
    : > /etc/postfix/inbound_recipients
    : > /etc/postfix/transport
    
    for m in $MAILBOXES; do
      printf '%s@%s OK\n' "$m" "$DOMAIN" >> /etc/postfix/mailboxes
      printf '%s@%s %s@%s\n' "$m" "$DOMAIN" "$m" "$DOMAIN" >> /etc/postfix/sender_login
    done
    for m in $EXTERNAL; do
      printf '%s@%s OK\n' "$m" "$DOMAIN" >> /etc/postfix/inbound_recipients
    done
    for d in $RELAY_DOMAINS; do
      printf '%s relay:%s\n' "$d" "$RELAY" >> /etc/postfix/transport
    done
    for f in mailboxes sender_login inbound_recipients transport; do
      postmap /etc/postfix/$f
    done
    
    tee /etc/aliases > /dev/null <<AL
    # /etc/aliases – mail server (written by mail-vm-setup.sh)
    postmaster: admin@$DOMAIN
    root: admin@$DOMAIN
    AL
    newaliases
    
    if [ -s /etc/postfix/sasl_passwd ]; then
      RUSER=$(awk 'NR==1 {split($2, a, ":"); print a[1]}' /etc/postfix/sasl_passwd)
      printf '/@yourdomain\\.net$/ %s\n' "$RUSER" > /etc/postfix/relay_sender
      echo "   relay account present – sender rewritten on the relay path only"
    else
      install -o root -g root -m 0600 /dev/null /etc/postfix/sasl_passwd
      : > /etc/postfix/relay_sender
      echo "   relay account not present yet – mail to relay domains waits in the queue"
    fi
    chown root:root /etc/postfix/sasl_passwd && chmod 0600 /etc/postfix/sasl_passwd
    ( umask 077 && postmap /etc/postfix/sasl_passwd )
    
    postconf -M 'policyd-spf/unix=policyd-spf unix - n n - 0 spawn user=policyd-spf argv=/usr/bin/policyd-spf'
    postconf -M 'relay/unix=relay unix - - y - - smtp'
    postconf -P 'relay/unix/syslog_name=postfix/relay' 'relay/unix/smtp_sasl_auth_enable=yes' \
      'relay/unix/smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd' 'relay/unix/smtp_sasl_security_options=noanonymous' \
      'relay/unix/smtp_tls_security_level=encrypt' 'relay/unix/smtp_generic_maps=regexp:/etc/postfix/relay_sender'
    postconf -M 'submission/inet=submission inet n - y - - smtpd'
    postconf -P 'submission/inet/syslog_name=postfix/submission' 'submission/inet/smtpd_tls_security_level=encrypt' \
      'submission/inet/smtpd_sasl_auth_enable=yes' 'submission/inet/smtpd_sasl_security_options=noanonymous' \
      'submission/inet/smtpd_relay_restrictions=permit_sasl_authenticated,reject' \
      'submission/inet/smtpd_recipient_restrictions=permit_sasl_authenticated,reject' \
      'submission/inet/smtpd_sender_login_maps=hash:/etc/postfix/sender_login' \
      'submission/inet/smtpd_sender_restrictions=reject_sender_login_mismatch' \
      'submission/inet/milter_macro_daemon_name=ORIGINATING'
    postfix check
    
    echo ">> 3. OpenDKIM"
    tee /etc/opendkim.conf > /dev/null <<'DK'
    # /etc/opendkim.conf – mail server (written by mail-vm-setup.sh)
    Syslog                  yes
    SyslogSuccess           yes
    UMask                   007
    Mode                    s
    Canonicalization        relaxed/simple
    OversignHeaders         From
    Domain                  yourdomain.net
    Selector                mail
    KeyFile                 /etc/opendkim/keys/yourdomain.net/mail.private
    InternalHosts           /etc/opendkim/internal-hosts
    Socket                  inet:8891@127.0.0.1
    PidFile                 /run/opendkim/opendkim.pid
    UserID                  opendkim
    DK
    
    install -d -m 0755 /etc/opendkim
    printf '127.0.0.1\n10.0.0.0/8\n172.16.0.0/12\n192.168.0.0/16\n' > /etc/opendkim/internal-hosts
    if [ -f /etc/default/opendkim ]; then
      sed -i 's|^SOCKET=.*|SOCKET=inet:8891@127.0.0.1|' /etc/default/opendkim
      grep -q '^SOCKET=inet:8891@127.0.0.1' /etc/default/opendkim || echo 'SOCKET=inet:8891@127.0.0.1' >> /etc/default/opendkim
      if [ -x /lib/opendkim/opendkim.service.generate ]; then /lib/opendkim/opendkim.service.generate; fi
    fi
    install -d -o opendkim -g opendkim -m 0750 /etc/opendkim/keys "$KEYDIR"
    if [ -s "$KEYDIR/$SELECTOR.private" ]; then
      chown opendkim:opendkim "$KEYDIR/$SELECTOR.private" && chmod 0600 "$KEYDIR/$SELECTOR.private"
      opendkim -n -x /etc/opendkim.conf
      DKIM=present
    else
      DKIM=absent
    fi
    
    echo ">> 4. Dovecot (IMAPS on 993, mailboxes in /var/vmail)"
    tee /etc/dovecot/dovecot.conf > /dev/null <<'DC'
    # /etc/dovecot/dovecot.conf – mail server (written by mail-vm-setup.sh)
    dovecot_config_version = 2.4.0
    dovecot_storage_version = 2.4.0
    protocols = imap lmtp
    listen = *
    ssl = required
    ssl_server_cert_file = /etc/postfix/tls/fullchain.pem
    ssl_server_key_file = /etc/postfix/tls/privkey.pem
    ssl_min_protocol = TLSv1.2
    auth_mechanisms = plain login
    auth_username_format = %{user | lower}
    
    passdb passwd-file {
      default_password_scheme = SHA512-CRYPT
      passwd_file_path = /etc/dovecot/users
    }
    
    userdb static {
      userdb_static_allow_all_users = yes
      fields {
        uid = vmail
        gid = vmail
        home = /var/vmail/%{user | domain}/%{user | username}
      }
    }
    
    first_valid_uid = 5000
    mail_driver = maildir
    mail_path = ~/Maildir
    
    namespace inbox {
      inbox = yes
      mailbox Drafts {
        special_use = \Drafts
        auto = subscribe
      }
      mailbox Sent {
        special_use = \Sent
        auto = subscribe
      }
      mailbox Junk {
        special_use = \Junk
        auto = subscribe
      }
      mailbox Trash {
        special_use = \Trash
        auto = subscribe
      }
    }
    
    service imap-login {
      inet_listener imap {
        port = 0
      }
      inet_listener imaps {
        port = 993
      }
    }
    
    service lmtp {
      unix_listener /var/spool/postfix/private/dovecot-lmtp {
        mode = 0600
        user = postfix
        group = postfix
      }
    }
    
    service auth {
      unix_listener /var/spool/postfix/private/auth {
        mode = 0660
        user = postfix
        group = postfix
      }
    }
    DC
    
    [ -e /etc/dovecot/users ] || install -o root -g dovecot -m 0640 /dev/null /etc/dovecot/users
    chown root:dovecot /etc/dovecot/users && chmod 0640 /etc/dovecot/users
    doveconf -n > /dev/null || die "dovecot.conf invalid"
    
    echo ">> 5. Roundcube behind nginx (HTTPS)"
    RC=/etc/roundcube/config.inc.php
    sed -i '/^\/\/ >>> mail-vm-setup/,/^\/\/ <<< mail-vm-setup/d' "$RC"
    tee -a "$RC" > /dev/null <<'RCF'
    // >>> mail-vm-setup
    $config['imap_host'] = 'ssl://mail.yourdomain.net:993';
    $config['smtp_host'] = 'tls://mail.yourdomain.net:587';
    $config['smtp_user'] = '%u';
    $config['smtp_pass'] = '%p';
    $config['username_domain'] = 'yourdomain.net';
    $config['mail_domain'] = 'yourdomain.net';
    $config['product_name'] = 'Mail';
    // <<< mail-vm-setup
    RCF
    php -l "$RC" > /dev/null || die "Roundcube configuration invalid"
    
    tee /etc/nginx/sites-available/roundcube > /dev/null <<'NG'
    # /etc/nginx/sites-available/roundcube – webmail (written by mail-vm-setup.sh)
    server {
        listen 80;
        server_name mail.yourdomain.net;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl;
        server_name mail.yourdomain.net;
        ssl_certificate     /etc/postfix/tls/fullchain.pem;
        ssl_certificate_key /etc/postfix/tls/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;
        root /var/lib/roundcube/public_html;
        index index.php;
        client_max_body_size 12m;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header X-Content-Type-Options nosniff always;
    
        location / {
            try_files $uri $uri/ /index.php$is_args$args;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php-fpm.sock;
        }
    }
    NG
    
    ln -sfn /etc/nginx/sites-available/roundcube /etc/nginx/sites-enabled/roundcube
    rm -f /etc/nginx/sites-enabled/default
    nginx -t 2> /dev/null || die "nginx configuration invalid"
    
    echo ">> 6. start and check"
    systemctl enable -q postfix dovecot nginx opendkim
    systemctl restart dovecot postfix nginx
    if [ "$DKIM" = present ]; then
      systemctl restart opendkim
    else
      systemctl stop opendkim
      echo "   DKIM key not present yet – OpenDKIM stopped, mail leaves unsigned until the key is placed"
    fi
    sleep 2
    for s in postfix dovecot nginx; do
      systemctl is-active -q "$s" || die "$s is not active"
    done
    
    echo "   postfix $(postconf -h mail_version) · dovecot $(dovecot --version | cut -d' ' -f1) · $(nginx -v 2>&1 | cut -d/ -f2 | sed 's/^/nginx /') · roundcube $(dpkg-query -W -f='${Version}' roundcube-core)"
    echo ">> mail-vm-setup complete (DKIM key: $DKIM · relay account: $([ -s /etc/postfix/sasl_passwd ] && echo present || echo absent) · mailbox logins: $(grep -c . /etc/dovecot/users || true))"
    

    3-firewall.sh

    #!/bin/bash
    # Run on: mail.yourdomain.net (root) – firewall for the Mail VM
    #   sudo bash /usr/local/sbin/mail-vm-firewall.sh
    # Guard: rules automatically flush after 90 seconds unless /run/nft-confirmed is created from a new connection.
    
    set -euo pipefail
    [ "$(id -u)" = 0 ] || { echo "ERROR: run as root" >&2; exit 1; }
    [ "$(hostname -f)" = "mail.yourdomain.net" ] || { echo "ERROR: not the mail server" >&2; exit 1; }
    
    tee /etc/nftables.conf.new > /dev/null <<'NFT'
    #!/usr/sbin/nft -f
    # /etc/nftables.conf – mail server (written by mail-vm-firewall.sh)
    flush ruleset
    
    table inet filter {
        set private4 {
            type ipv4_addr
            flags interval
            elements = { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 }
        }
    
        chain input {
            type filter hook input priority 0; policy drop;
            iif "lo" accept
            ct state established,related accept
            ct state invalid drop
            ip protocol icmp accept
            meta l4proto ipv6-icmp accept
            tcp dport 25 accept comment "incoming mail, from everywhere"
            ip saddr @private4 tcp dport { 22, 80, 443, 587, 993, 5900 } accept comment "SSH, webmail, submission, IMAPS, VNC: private addresses only"
        }
    
        chain forward {
            type filter hook forward priority 0; policy drop;
        }
    
        chain output {
            type filter hook output priority 0; policy accept;
        }
    }
    NFT
    
    nft -c -f /etc/nftables.conf.new
    rm -f /run/nft-confirmed
    setsid nohup sh -c 'sleep 90; [ -f /run/nft-confirmed ] || { nft flush ruleset; logger -t mail-vm-firewall "rules removed: not confirmed"; }' > /dev/null 2>&1 &
    install -o root -g root -m 0755 /etc/nftables.conf.new /etc/nftables.conf && rm -f /etc/nftables.conf.new
    nft -f /etc/nftables.conf
    echo "rules applied: $(nft list ruleset | grep -c .) lines – confirm within 90 seconds from a new connection"
    

    4-secrets.sh

    #!/bin/bash
    # Run on: management VM (sysadmin)
    # Pushes secrets from KeePassXC to mail.yourdomain.net. Prints only OK, FAIL, and lengths.
    
    if [ "$(hostname -f)" = "dev.yourdomain.net" ] && [ "$(id -un)" = "sysadmin" ]; then
    (
      set -u
      DB=~/Secrets/yourdomain.kdbx
      DOMAIN=yourdomain.net
      MAIL_VM=sysadmin@mail.$DOMAIN
      SSH="ssh -o BatchMode=yes -o StrictHostKeyChecking=yes -o ConnectTimeout=8 $MAIL_VM"
      E_DKIM="Mail/DKIM key (selector mail)"
      E_RELAY="Mail/Relay Provider"
      RELAY="[smtp.relayprovider.com]:587"
      GROUP="Mail"
      MAILBOXES="admin dmarc postmaster abuse no-reply user"
      KEY=/etc/opendkim/keys/$DOMAIN/mail.private
    
      fail() { echo "FAIL: $*"; unset MP P; exit 1; }
      kp() { printf '%s\n' "$MP" | keepassxc-cli "$@"; }
    
      [ -r "$DB" ] || fail "database $DB not readable"
      [ "$($SSH 'hostname -f' 2> /dev/null)" = "mail.$DOMAIN" ] || fail "mail server not reachable by ssh"
    
      read -rs -p "KeePassXC master password: " MP; echo
      kp ls -q "$DB" > /dev/null 2>&1 || fail "the database did not open (master password?)"
      echo "database opened: OK"
    
      echo ">> 0. group Mail"
      kp mkdir -q "$DB" "$GROUP" > /dev/null 2>&1 || true
    
      echo ">> 1. DKIM key"
      $SSH "sudo -n install -d -o opendkim -g opendkim -m 0750 /etc/opendkim/keys /etc/opendkim/keys/$DOMAIN" || fail "key directory"
      kp attachment-export -q --stdout "$DB" "$E_DKIM" mail.private 2> /dev/null \
        | $SSH "sudo -n sh -c 'umask 077; cat > $KEY; chown opendkim:opendkim $KEY; chmod 0600 $KEY'"
      [ "${PIPESTATUS[0]}" = 0 ] || fail "entry \"$E_DKIM\" (attachment mail.private) not readable"
    
      PUB=$($SSH "sudo -n openssl pkey -in $KEY -pubout -outform DER 2> /dev/null | base64 -w0")
      DNS=$(dig +short TXT mail._domainkey.$DOMAIN | tr -d '" ' | sed 's/.*p=//; s/;.*//')
      if [ -n "$PUB" ] && [ "$PUB" = "$DNS" ]; then
        echo "DKIM key placed, equal to the public key in DNS: OK"
      else
        fail "DKIM key on the server does not match the record mail._domainkey.$DOMAIN"
      fi
    
      echo ">> 2. relay account"
      U=$(kp show -q -a username "$DB" "$E_RELAY" 2> /dev/null) || fail "entry \"$E_RELAY\" not readable"
      P=$(kp show -q -s -a password "$DB" "$E_RELAY" 2> /dev/null) || fail "entry \"$E_RELAY\" not readable"
      [ -n "$U" ] && [ -n "$P" ] || fail "relay entry has no user or no password"
      printf '%s %s:%s\n' "$RELAY" "$U" "$P" \
        | $SSH "sudo -n sh -c 'umask 077; cat > /etc/postfix/sasl_passwd; chown root:root /etc/postfix/sasl_passwd; chmod 0600 /etc/postfix/sasl_passwd'" \
        || fail "relay account not written"
      echo "relay account written (user length ${#U}, password length ${#P}): OK"
      unset P
    
      echo ">> 3. mailbox passwords"
      USERS=""
      for m in $MAILBOXES; do
        A="$m@$DOMAIN"
        E="$GROUP/$A"
        if kp show -q -a username "$DB" "$E" > /dev/null 2>&1; then
          st="kept"
        else
          kp add -q -g -L 24 -l -U -n -u "$A" --url "https://mail.$DOMAIN" \
            --notes "Mailbox on mail.$DOMAIN – webmail https://mail.$DOMAIN, IMAPS 993, submission 587 (STARTTLS); user name = the address" \
            "$DB" "$E" > /dev/null 2>&1 || fail "entry \"$E\" not created"
          st="created"
        fi
        P=$(kp show -q -s -a password "$DB" "$E" 2> /dev/null) || fail "entry \"$E\" not readable"
        [ -n "$P" ] || fail "entry \"$E\" has no password"
        H=$(printf '%s\n' "$P" | openssl passwd -6 -stdin) || fail "hash"
        USERS="$USERS$A:{SHA512-CRYPT}$H"$'\n'
        echo "$A: entry $st, password length ${#P}"
        unset P
      done
    
      printf '%s' "$USERS" \
        | $SSH "sudo -n sh -c 'umask 027; cat > /etc/dovecot/users; chown root:dovecot /etc/dovecot/users; chmod 0640 /etc/dovecot/users'" \
        || fail "mailbox logins not written"
      [ "$($SSH 'sudo -n grep -c . /etc/dovecot/users')" = "$(echo $MAILBOXES | wc -w)" ] \
        && echo "mailbox logins written: OK" || fail "number of logins on the server"
      unset USERS
    
      echo ">> 4. setup run again on the mail server"
      $SSH 'sudo -n bash /usr/local/sbin/mail-vm-setup.sh > /tmp/mail-vm-setup.log 2>&1; echo "exit $?"; tail -1 /tmp/mail-vm-setup.log'
      [ "$($SSH 'systemctl is-active opendkim')" = active ] && echo "OpenDKIM active: OK" || fail "OpenDKIM not active"
    
      echo ">> 5. logins (IMAP and mail submission)"
      for m in $MAILBOXES; do
        A="$m@$DOMAIN"
        P=$(kp show -q -s -a password "$DB" "$GROUP/$A" 2> /dev/null) || fail "entry not readable"
        printf '%s\n' "$P" | python3 -I -c '
    import sys, ssl, imaplib, smtplib
    a = sys.argv[1]; p = sys.stdin.readline().rstrip("\n"); ctx = ssl.create_default_context(); r = []
    try:
        i = imaplib.IMAP4_SSL("mail.yourdomain.net", 993, ssl_context=ctx, timeout=10); i.login(a, p); i.select("INBOX"); i.logout(); r.append("IMAP OK")
    except Exception: r.append("IMAP FAIL")
    try:
        s = smtplib.SMTP("mail.yourdomain.net", 587, timeout=10); s.starttls(context=ctx); s.login(a, p); s.quit(); r.append("submission OK")
    except Exception: r.append("submission FAIL")
    print(a + ": " + " · ".join(r))
    ' "$A"
        unset P
      done
      unset MP
    
      echo ">> 6. signature on a mail sent through port 25"
      python3 -I -c '
    import smtplib
    s = smtplib.SMTP("mail.yourdomain.net", 25, timeout=10); s.ehlo("probe.yourdomain.net")
    s.sendmail("no-reply@yourdomain.net", ["admin@yourdomain.net"], "Subject: DKIM check\r\nFrom: no-reply@yourdomain.net\r\nTo: admin@yourdomain.net\r\n\r\nsigned?\r\n")
    s.quit()
    '
      sleep 3
      N=$($SSH "sudo -n sh -c 'grep -l \"^Subject: DKIM check\" /var/vmail/$DOMAIN/admin/Maildir/new/* 2> /dev/null | xargs -r grep -l \"^DKIM-Signature:.*d=$DOMAIN\" | wc -l'")
      [ "${N:-0}" -ge 1 ] && echo "mail arrived with a DKIM signature of $DOMAIN: OK" || echo "FAIL: no signed mail found in the admin mailbox"
      echo "mail-secrets finished"
    )
    else
      echo "WRONG HOST/USER – nothing done"
    fi