Vous montez Stalwart parce que l’équipe en a assez de faire tourner trois conteneurs Mailcow et quatre fichiers de config pour faire ce qu’un binaire Rust unique réussit aujourd’hui dans 80 Mo de mémoire. L’installeur récupère le binaire, génère un certificat auto-signé, ouvre 25/465/587/993/4190, et en cinq minutes vous pouvez envoyer et recevoir. Le danger est exactement le même qu’avec n’importe quel autre serveur de courriel : le travail au niveau protocole est correct par défaut, le périmètre, lui, ne l’est pas. Il n’y a pas de certificat Let’s Encrypt sur les interfaces publiques, la clé DKIM générée par Stalwart traîne dans la base sans enregistrement DNS, fail2ban ne connaît pas les logs structurés de Stalwart, et l’API admin est liée au même socket que l’IMAP public — ce qui veut dire que quiconque trouve le port admin a les clés de la boîte aux lettres.
Ce qui se passe
Un Stalwart prêt pour la production a besoin : d’un certificat Let’s Encrypt câblé pour STARTTLS sur 25/587, TLS implicite sur 465/993, ManageSieve sur 4190, et l’UI JMAP/admin sur 443 ; de l’endpoint d’admin JMAP lié à localhost ou derrière nginx avec liste blanche, jamais directement sur l’interface publique ; de RocksDB ou SQLite comme store (RocksDB monte plus haut, SQLite est plus simple — les deux sont fichier, pas de base de données séparée à faire tourner) ; d’un rDNS aligné avec la bannière SMTP ; de clés DKIM par domaine générées via l’UI admin, avec les enregistrements TXT correspondants publiés dans le DNS avant le premier message sortant ; d’un débit limité contre le brute-force SMTP AUTH, soit via les règles de throttle intégrées de Stalwart soit via fail2ban qui suit le log structuré ; et d’une unit systemd avec LimitNOFILE=64000 parce qu’un seul processus Stalwart peut tenir des milliers de sessions IMAP ouvertes et que la limite par défaut de 1024 s’effondre sous la moindre concurrence réelle. Stalwart est un binaire unique, mais ça reste un serveur de courriel — la discipline opérationnelle est identique.
Comment vérifier
Après installation, les écouteurs doivent ressembler à ça :
ss -lntp | grep -E ':(25|443|465|587|993|4190|8080)\b'
# 0.0.0.0:25 stalwart-mail
# 0.0.0.0:465 stalwart-mail
# 0.0.0.0:587 stalwart-mail
# 0.0.0.0:993 stalwart-mail
# 0.0.0.0:4190 stalwart-mail
# 0.0.0.0:443 nginx
# 127.0.0.1:8080 stalwart-mail (admin/JMAP)
Le port d’admin (8080) doit être sur 127.0.0.1. STARTTLS sur soumission et certificat sur IMAPS :
openssl s_client -starttls smtp -crlf -connect mail.example.com:587 -servername mail.example.com </dev/null 2>/dev/null | grep -E 'subject=|issuer='
openssl s_client -connect mail.example.com:993 -servername mail.example.com </dev/null 2>/dev/null | grep -E 'subject=|issuer='
Vérification DNS :
dig +short MX example.com
dig +short A mail.example.com
dig +short -x <votre-ip>
dig +short TXT default._domainkey.example.com
Si le TXT DKIM ne résout pas, Stalwart signe le courriel sortant avec une clé qui n’existe pas dans le DNS — chaque message échouera DKIM chez le destinataire.
Le correctif
Enregistrez le script ci-dessous sous /root/setup-stalwart-almalinux9.sh, puis exécutez-le. Il déroule l’installation complète sur une VM AlmaLinux 9.x fraîche : mise à jour de base + EPEL, ajustement noyau/réseau, limites de fichiers, retire postfix et sendmail de l’hôte pour qu’aucun service ne se batte pour le port 25, durcit SSH en gardant la clé root, configure firewalld avec les bonnes règles, active dnf-automatic.timer pour les mises à jour de sécurité, télécharge le dernier binaire Stalwart Mail Server, crée un utilisateur de service stalwart-mail, exécute le --init non interactif pour générer un fichier TOML de référence sous /opt/stalwart, bascule le store vers RocksDB, lie l’API de management à 127.0.0.1:8080, écrit une unit systemd avec LimitNOFILE=64000, installe nginx en reverse proxy TLS-terminé pour JMAP/admin avec un certificat Let’s Encrypt, configure Stalwart pour utiliser le même certificat Let’s Encrypt pour SMTP/IMAPS via le watcher de fichier, configure fail2ban pour SSH plus une jail SMTP AUTH Stalwart, et affiche les identifiants admin de bootstrap et la base DKIM à la fin.
#!/usr/bin/env bash
set -euo pipefail
### AlmaLinux 9.x Stalwart Mail Server clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs Stalwart Mail with RocksDB store
### No local backups; assumes VM-level backup
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${MAIL_HOSTNAME:?Set MAIL_HOSTNAME, e.g. mail.example.com}"
: "${PRIMARY_DOMAIN:?Set PRIMARY_DOMAIN, e.g. example.com}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL}"
: "${TIMEZONE:=America/Toronto}"
echo
echo "========================================"
echo "Stalwart AlmaLinux 9.x Setup"
echo "Hostname: ${MAIL_HOSTNAME}"
echo "Primary domain: ${PRIMARY_DOMAIN}"
echo "========================================"
echo
echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y update
echo "==> Installing base packages"
dnf -y install \
vim curl wget ca-certificates gnupg2 \
chrony fail2ban dnf-automatic \
policycoreutils-python-utils \
lsof tcpdump bind-utils \
tar gzip unzip iproute net-tools jq
echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true
timedatectl set-timezone "${TIMEZONE}"
echo "==> Removing host MTAs that would collide with port 25"
dnf -y remove postfix sendmail || true
echo "==> Configuring SELinux to enforcing on next boot"
if [[ -f /etc/selinux/config ]]; then
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
fi
setenforce 1 2>/dev/null || true
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-stalwart.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
cat > /etc/security/limits.d/99-stalwart.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS
echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart sshd
echo "==> Configuring firewalld"
dnf -y install firewalld
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=smtp
firewall-cmd --permanent --add-service=smtps
firewall-cmd --permanent --add-service=smtp-submission
firewall-cmd --permanent --add-service=imaps
firewall-cmd --permanent --add-port=4190/tcp
firewall-cmd --reload
echo "==> Configuring automatic security updates"
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
[base]
debuglevel = 1
DNFAUTO
systemctl enable --now dnf-automatic.timer
echo "==> Creating stalwart-mail service user"
id -u stalwart-mail >/dev/null 2>&1 || useradd --system --home /opt/stalwart --shell /usr/sbin/nologin stalwart-mail
install -d -o stalwart-mail -g stalwart-mail /opt/stalwart /opt/stalwart/etc /opt/stalwart/data /opt/stalwart/queue /opt/stalwart/reports /opt/stalwart/logs
echo "==> Downloading Stalwart Mail Server"
STALWART_TAG="$(curl -s https://api.github.com/repos/stalwartlabs/mail-server/releases/latest | jq -r .tag_name)"
cd /tmp
curl -fsSL "https://github.com/stalwartlabs/mail-server/releases/download/${STALWART_TAG}/stalwart-mail-x86_64-unknown-linux-gnu.tar.gz" \
-o stalwart-mail.tar.gz
tar -xzf stalwart-mail.tar.gz
install -m 0755 -o root -g root stalwart-mail /usr/local/bin/stalwart-mail
echo "==> Initialising Stalwart config (RocksDB store)"
ADMIN_PASSWORD="$(openssl rand -hex 16 | tee /root/.stalwart_admin_password)"
sudo -u stalwart-mail /usr/local/bin/stalwart-mail \
--init "/opt/stalwart" \
--no-input || true
# Write a deterministic configuration over whatever --init produced
cat > /opt/stalwart/etc/config.toml <<TOML
[server]
hostname = "${MAIL_HOSTNAME}"
[server.listener."smtp"]
bind = ["[::]:25"]
protocol = "smtp"
[server.listener."submission"]
bind = ["[::]:587"]
protocol = "smtp"
tls.implicit = false
[server.listener."submissions"]
bind = ["[::]:465"]
protocol = "smtp"
tls.implicit = true
[server.listener."imaps"]
bind = ["[::]:993"]
protocol = "imap"
tls.implicit = true
[server.listener."sieve"]
bind = ["[::]:4190"]
protocol = "managesieve"
[server.listener."http"]
bind = ["127.0.0.1:8080"]
protocol = "http"
[storage]
data = "rocksdb"
fts = "rocksdb"
blob = "rocksdb"
lookup = "rocksdb"
directory = "internal"
[store."rocksdb"]
type = "rocksdb"
path = "/opt/stalwart/data"
compression = "lz4"
[directory."internal"]
type = "internal"
store = "rocksdb"
[certificate."default"]
cert = "%{file:/etc/letsencrypt/live/${MAIL_HOSTNAME}/fullchain.pem}%"
private-key = "%{file:/etc/letsencrypt/live/${MAIL_HOSTNAME}/privkey.pem}%"
[server.tls]
certificate = "default"
sni = [
{ subject = "${MAIL_HOSTNAME}", certificate = "default" }
]
[session.rcpt]
relay = false
max-recipients = 25
[session.throttle."concurrent-smtp"]
key = "remote-ip"
concurrency = 10
enable = true
[session.throttle."auth-rate"]
key = "remote-ip"
rate = "30/1m"
enable = true
[queue.outbound]
hostname = "${MAIL_HOSTNAME}"
next-hop = "local"
[authentication.fallback-admin]
user = "admin"
secret = "${ADMIN_PASSWORD}"
[tracer."stdout"]
type = "stdout"
level = "info"
ansi = false
enable = true
TOML
chown -R stalwart-mail:stalwart-mail /opt/stalwart
echo "==> Writing systemd unit"
cat > /etc/systemd/system/stalwart-mail.service <<'UNIT'
[Unit]
Description=Stalwart Mail Server
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=stalwart-mail
Group=stalwart-mail
WorkingDirectory=/opt/stalwart
ExecStart=/usr/local/bin/stalwart-mail --config /opt/stalwart/etc/config.toml
Restart=on-failure
RestartSec=5s
LimitNOFILE=64000
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
ProtectSystem=full
ProtectHome=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
UNIT
echo "==> Installing nginx + Let's Encrypt"
dnf -y install nginx certbot python3-certbot-nginx
cat > /etc/nginx/conf.d/stalwart.conf <<NGINX
server {
listen 80;
server_name ${MAIL_HOSTNAME};
location /.well-known/acme-challenge/ { root /var/www/html; }
location / { return 301 https://\$host\$request_uri; }
}
server {
listen 443 ssl http2;
server_name ${MAIL_HOSTNAME};
ssl_certificate /etc/letsencrypt/live/${MAIL_HOSTNAME}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${MAIL_HOSTNAME}/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 100m;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_read_timeout 300s;
}
}
NGINX
mkdir -p /var/www/html
# Issue cert before starting Stalwart so the file references resolve
systemctl enable --now nginx
certbot --nginx -n --agree-tos -m "${LETSENCRYPT_EMAIL}" -d "${MAIL_HOSTNAME}"
systemctl reload nginx
# Make sure stalwart-mail can read the live cert
chmod 0755 /etc/letsencrypt/live /etc/letsencrypt/archive 2>/dev/null || true
# Reload hook so renewal triggers a Stalwart restart
mkdir -p /etc/letsencrypt/renewal-hooks/deploy
cat > /etc/letsencrypt/renewal-hooks/deploy/stalwart.sh <<'HOOK'
#!/usr/bin/env bash
systemctl reload nginx || true
systemctl reload stalwart-mail || systemctl restart stalwart-mail || true
HOOK
chmod 0755 /etc/letsencrypt/renewal-hooks/deploy/stalwart.sh
echo "==> Enabling and starting Stalwart"
systemctl daemon-reload
systemctl enable --now stalwart-mail
echo "==> Waiting for SMTP listener"
for i in {1..60}; do
if ss -lntp | grep -q ':25 '; then
break
fi
sleep 2
done
echo "==> Waiting for IMAPS listener"
for i in {1..60}; do
if ss -lntp | grep -q ':993 '; then
break
fi
sleep 2
done
echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d /etc/fail2ban/filter.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN_SSH'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN_SSH
cat > /etc/fail2ban/filter.d/stalwart-auth.conf <<'F2B'
[Definition]
failregex = ^.* (smtp|imap) .* auth.* failed .* remoteIp=<HOST>.*$
^.* authentication failed .* remote-ip=<HOST>.*$
ignoreregex =
F2B
cat > /etc/fail2ban/jail.d/stalwart.local <<'FAIL2BAN_S'
[stalwart-auth]
enabled = true
filter = stalwart-auth
backend = systemd
journalmatch = _SYSTEMD_UNIT=stalwart-mail.service
maxretry = 6
findtime = 10m
bantime = 24h
banaction = iptables-multiport
port = smtp,submission,smtps,imaps
FAIL2BAN_S
systemctl enable --now fail2ban
echo "==> Final package update"
dnf -y update
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "SELinux:"
getenforce || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(25|443|465|587|993|4190|8080)\b' || true
echo
echo "Services:"
systemctl is-active stalwart-mail nginx fail2ban chronyd || true
echo
echo "Web/Admin UI:"
echo "https://${MAIL_HOSTNAME}/"
echo "Admin user: admin"
echo "Admin password: $(cat /root/.stalwart_admin_password)"
echo
echo "Next: in the admin UI, add the mail domain (${PRIMARY_DOMAIN}), then generate a DKIM key"
echo "for it from Settings > DKIM. Stalwart will show the exact TXT record (selector default)"
echo "to publish at default._domainkey.${PRIMARY_DOMAIN}."
echo
echo "Suggested DNS:"
echo " A ${MAIL_HOSTNAME} -> <this server IP>"
echo " MX ${PRIMARY_DOMAIN} -> ${MAIL_HOSTNAME}"
echo " TXT ${PRIMARY_DOMAIN} -> v=spf1 mx ~all"
echo " TXT _dmarc.${PRIMARY_DOMAIN} -> v=DMARC1; p=none; rua=mailto:dmarc@${PRIMARY_DOMAIN}"
echo
echo "Final step: confirm rDNS (PTR) for the public IP resolves to ${MAIL_HOSTNAME}"
Rendez-le exécutable et lancez-le :
chmod 700 /root/setup-stalwart-almalinux9.sh
MAIL_HOSTNAME=mail.example.com \
PRIMARY_DOMAIN=example.com \
LETSENCRYPT_EMAIL=ops@example.com \
/root/setup-stalwart-almalinux9.sh
Le mot de passe admin de bootstrap est écrit dans /root/.stalwart_admin_password. Connectez-vous à l’admin web sur https://mail.example.com/, ajoutez example.com comme domaine de courriel, générez la clé DKIM depuis Settings > DKIM, copiez l’enregistrement TXT textuellement dans le DNS, puis créez la première boîte aux lettres. Envoyez un test à une adresse Gmail vérifiée et confirmez que Authentication-Results affiche spf=pass dkim=pass dmarc=pass. Maintenez DMARC à p=none pendant deux semaines en lisant les rapports agrégés, puis escaladez. Le script n’active volontairement pas de sauvegardes au niveau hôte — supposez des instantanés au niveau VM ; sur bare metal, ajoutez une étape restic quotidienne couvrant /opt/stalwart/data (le store RocksDB) et /opt/stalwart/etc.
L’empreinte mono-binaire de Stalwart coupe beaucoup de surface opérationnelle, mais le périmètre — DNS, rDNS, rotation DKIM, supervision de la livrabilité — c’est encore là que les serveurs de courriel se trompent. Stack Harbor fait tourner Stalwart avec supervision et soutien câblés, pour que la dérive de livrabilité soit attrapée pendant qu’elle est encore corrigeable plutôt qu’après que Gmail commence à rebondir. Pour cadrer l’intervention, démarrez la conversation ici.