Aller au contenu

Déployer Listmonk pour les infolettres sur Ubuntu 22.04 (prêt pour la production)

Monter une plateforme Listmonk autohébergée et durcie sur Ubuntu 22.04 — PostgreSQL, nginx + Let's Encrypt, relais SMTP Postal ou SES, gestion des bounces.

Vous déployez Listmonk pour remplacer un compte Mailchimp à 400 $ par mois. Importation de la liste, conception du gabarit, clic sur Envoyer pour les 5 000 premiers abonnés. Une demi-heure plus tard, quelqu’un chez Gmail transfère un « Ça ressemble à du pourriel ? » au responsable marketing. Au matin, le taux de bounce frappe les 8 % et l’IP apparaît sur b.barracudacentral.org. Rien dans Listmonk lui-même n’a échoué — il a envoyé chaque message qu’on lui a demandé. Les échecs étaient en amont : la liste contenait trois années d’adresses non vérifiées, le relais SMTP était le Server Postal existant de l’entreprise (préchauffé soigneusement pour le trafic transactionnel, pas pour le bulk), et le traitement des bounces n’a jamais été câblé, donc la liste n’a jamais rétréci. Listmonk est un outil de publication ; il hérite de la discipline qu’on met autour.

Ce qui se passe

Un Listmonk de production demande plus que le binaire sur une VM. La liste doit être opt-in, idéalement en double opt-in. SPF doit inclure le relais (Postal, SES, ou un MTA dédié) à qui Listmonk remet le courriel — Listmonk lui-même ne livre pas. La signature DKIM se fait au relais, ce qui veut dire que le domaine d= doit correspondre au domaine From: sinon DMARC rejette. Un sous-domaine dédié comme mailings.example.com et un identifiant de relais distinct empêchent la réputation de la masse de fuir vers la réputation transactionnelle. PostgreSQL doit être lié à localhost uniquement, et Listmonk doit être joint exclusivement en HTTPS, jamais sur le port 9000 brut qu’il ouvre par défaut. La gestion des bounces doit être activée et la boîte de bounces doit réellement exister — Listmonk lit l’IMAP, parse les DSN, et désinscrit l’adresse. Sans cette boucle, chaque envoi compose les dégâts de réputation.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(80|443|5432|9000)\b'
# 0.0.0.0:80     nginx
# 0.0.0.0:443    nginx
# 127.0.0.1:5432 postgres
# 127.0.0.1:9000 listmonk

PostgreSQL uniquement sur 127.0.0.1 ; Listmonk uniquement joignable derrière nginx. Vérifiez le certificat Let’s Encrypt sur le tableau de bord :

curl -sI https://lists.example.com/ | head -5
openssl s_client -connect lists.example.com:443 -servername lists.example.com </dev/null 2>/dev/null | grep -E 'subject=|issuer='

Échafaudage DNS pour le sous-domaine d’envoi (en supposant que Postal fait relais) :

dig +short TXT mailings.example.com | grep spf
dig +short TXT postal-<token>._domainkey.mailings.example.com
dig +short TXT _dmarc.mailings.example.com

Si SPF ne renvoie rien ou omet le relais, chaque destinataire fera softfail ou mettra en quarantaine. Si DKIM est absent, l’alignement DMARC est cassé dès le premier envoi.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-listmonk-ubuntu22.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour apt, ajustement noyau/réseau, limites de fichiers, durcit SSH en gardant la clé root, configure UFW avec seulement SSH/HTTP/HTTPS ouverts, installe PostgreSQL 15 lié à localhost, crée l’utilisateur et la base listmonk, télécharge le dernier binaire Listmonk, génère config.toml avec des bindings localhost uniquement et un bloc relais SMTP prêt pour les identifiants Postal, écrit une unit systemd avec LimitNOFILE=64000, exécute listmonk --install pour amorcer le schéma, monte le service, configure nginx en reverse proxy TLS-terminé avec Let’s Encrypt, et configure fail2ban pour SSH plus une jail d’authentification admin Listmonk.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Listmonk newsletter platform clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs PostgreSQL 15 + Listmonk + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${LISTMONK_HOSTNAME:?Set LISTMONK_HOSTNAME, e.g. lists.example.com}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL}"
: "${SMTP_HOST:?Set SMTP_HOST, e.g. send.example.com}"
: "${SMTP_PORT:=587}"
: "${SMTP_USERNAME:?Set SMTP_USERNAME for the relay}"
: "${SMTP_PASSWORD:?Set SMTP_PASSWORD for the relay}"
: "${SMTP_FROM:?Set SMTP_FROM, e.g. news@mailings.example.com}"
: "${BOUNCE_MAILBOX_HOST:?Set BOUNCE_MAILBOX_HOST}"
: "${BOUNCE_MAILBOX_USERNAME:?Set BOUNCE_MAILBOX_USERNAME}"
: "${BOUNCE_MAILBOX_PASSWORD:?Set BOUNCE_MAILBOX_PASSWORD}"
: "${TIMEZONE:=America/Toronto}"

export DEBIAN_FRONTEND=noninteractive

echo
echo "========================================"
echo "Listmonk Ubuntu 22.04 Setup"
echo "Hostname: ${LISTMONK_HOSTNAME}"
echo "========================================"
echo

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget gnupg ca-certificates chrony \
  fail2ban unattended-upgrades \
  lsof tcpdump dnsutils \
  ufw jq \
  apt-transport-https software-properties-common

timedatectl set-ntp true
timedatectl set-timezone "${TIMEZONE}"

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-listmonk.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-listmonk.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 UFW"
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
yes | ufw enable

echo "==> Configuring unattended-upgrades for security only"
cat > /etc/apt/apt.conf.d/52unattended-upgrades-local <<'UA'
Unattended-Upgrade::Allowed-Origins {
  "${distro_id}:${distro_codename}-security";
  "${distro_id}ESMApps:${distro_codename}-apps-security";
  "${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::Automatic-Reboot "false";
UA
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AAU'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AAU

echo "==> Installing PostgreSQL 15 (localhost-bound)"
install -d /etc/apt/keyrings
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
  | gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
echo "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt jammy-pgdg main" \
  > /etc/apt/sources.list.d/pgdg.list
apt-get update
apt-get -y install postgresql-15

sed -i "s|^#listen_addresses.*|listen_addresses = '127.0.0.1'|" /etc/postgresql/15/main/postgresql.conf
sed -i "s|^listen_addresses.*|listen_addresses = '127.0.0.1'|" /etc/postgresql/15/main/postgresql.conf
systemctl restart postgresql

LISTMONK_DB_PASSWORD="$(openssl rand -hex 24)"
sudo -u postgres psql <<SQL
DO \$\$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'listmonk') THEN
    CREATE ROLE listmonk LOGIN PASSWORD '${LISTMONK_DB_PASSWORD}';
  ELSE
    ALTER ROLE listmonk WITH LOGIN PASSWORD '${LISTMONK_DB_PASSWORD}';
  END IF;
END \$\$;
SQL
sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='listmonk'" \
  | grep -q 1 \
  || sudo -u postgres createdb -O listmonk listmonk

echo "==> Creating listmonk service user"
id -u listmonk >/dev/null 2>&1 || useradd --system --home /opt/listmonk --shell /usr/sbin/nologin listmonk
install -d -o listmonk -g listmonk /opt/listmonk

echo "==> Downloading Listmonk binary"
cd /tmp
LISTMONK_TAG="$(curl -s https://api.github.com/repos/knadh/listmonk/releases/latest | jq -r .tag_name)"
LISTMONK_VER="${LISTMONK_TAG#v}"
curl -fsSL "https://github.com/knadh/listmonk/releases/download/${LISTMONK_TAG}/listmonk_${LISTMONK_VER}_linux_amd64.tar.gz" \
  | tar -xz
install -m 0755 -o root -g root listmonk /usr/local/bin/listmonk

echo "==> Writing /opt/listmonk/config.toml"
cat > /opt/listmonk/config.toml <<TOML
[app]
address = "127.0.0.1:9000"
admin_username = "admin"
admin_password = "$(openssl rand -hex 16 | tee /root/.listmonk_admin_password)"

[db]
host = "127.0.0.1"
port = 5432
user = "listmonk"
password = "${LISTMONK_DB_PASSWORD}"
database = "listmonk"
ssl_mode = "disable"
max_open = 25
max_idle = 25
max_lifetime = "300s"

[smtp]
host = "${SMTP_HOST}"
port = ${SMTP_PORT}
auth_protocol = "login"
username = "${SMTP_USERNAME}"
password = "${SMTP_PASSWORD}"
hello_hostname = "${LISTMONK_HOSTNAME}"
max_conns = 10
max_msg_retries = 2
idle_timeout = "15s"
wait_timeout = "5s"
tls_type = "STARTTLS"
tls_skip_verify = false

[bounce]
enabled = true
webhooks_enabled = true
count = 2
action = "blocklist"

[[bounce.mailboxes]]
enabled = true
type = "imap"
host = "${BOUNCE_MAILBOX_HOST}"
port = 993
auth_protocol = "login"
username = "${BOUNCE_MAILBOX_USERNAME}"
password = "${BOUNCE_MAILBOX_PASSWORD}"
return_path = "${SMTP_FROM}"
scan_interval = "1m"
tls_enabled = true
tls_skip_verify = false
TOML

chown listmonk:listmonk /opt/listmonk/config.toml
chmod 600 /opt/listmonk/config.toml

echo "==> Initialising Listmonk schema"
sudo -u listmonk bash -c "cd /opt/listmonk && /usr/local/bin/listmonk --config /opt/listmonk/config.toml --install --yes"

echo "==> Writing systemd unit"
cat > /etc/systemd/system/listmonk.service <<'UNIT'
[Unit]
Description=Listmonk newsletter platform
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
Type=simple
User=listmonk
Group=listmonk
WorkingDirectory=/opt/listmonk
ExecStart=/usr/local/bin/listmonk --config /opt/listmonk/config.toml
Restart=on-failure
RestartSec=5s
LimitNOFILE=64000
ProtectSystem=full
ProtectHome=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now listmonk

echo "==> Waiting for Listmonk to listen on 127.0.0.1:9000"
for i in {1..30}; do
  if ss -lntp | grep -q '127.0.0.1:9000'; then
    break
  fi
  sleep 1
done

echo "==> Installing nginx + Let's Encrypt"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/listmonk.conf <<NGINX
server {
    listen 80;
    server_name ${LISTMONK_HOSTNAME};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://\$host\$request_uri; }
}

server {
    listen 443 ssl http2;
    server_name ${LISTMONK_HOSTNAME};

    ssl_certificate /etc/letsencrypt/live/${LISTMONK_HOSTNAME}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${LISTMONK_HOSTNAME}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    client_max_body_size 100m;

    # Block /api/admin from the public internet unless you really need it
    location /api/admin/ {
        allow 10.0.0.0/8;
        allow 192.168.0.0/16;
        deny all;
        proxy_pass http://127.0.0.1:9000;
        proxy_set_header Host \$host;
    }

    location / {
        proxy_pass http://127.0.0.1:9000;
        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
ln -sf /etc/nginx/sites-available/listmonk.conf /etc/nginx/sites-enabled/listmonk.conf
rm -f /etc/nginx/sites-enabled/default
certbot --nginx -n --agree-tos -m "${LETSENCRYPT_EMAIL}" -d "${LISTMONK_HOSTNAME}"
systemctl reload nginx

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/listmonk-auth.conf <<'F2B'
[Definition]
failregex = ^.*"POST /api/admin/login HTTP/[\d.]+" 401 .* "[^"]*" "[^"]*" \[client <HOST>\]$
            ^.*"POST /admin/login HTTP/[\d.]+" 401 .* \[client <HOST>\]$
ignoreregex =
F2B

cat > /etc/fail2ban/jail.d/listmonk.local <<'FAIL2BAN_LM'
[listmonk-auth]
enabled = true
filter = listmonk-auth
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 10m
bantime = 24h
banaction = iptables-multiport
port = http,https
FAIL2BAN_LM

systemctl enable --now fail2ban

echo "==> Final package update"
apt-get update
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|5432|9000)\b' || true
echo
echo "Services:"
systemctl is-active postgresql listmonk nginx fail2ban || true
echo
echo "Web UI:"
echo "https://${LISTMONK_HOSTNAME}/admin/"
echo "Admin user:     admin"
echo "Admin password: $(cat /root/.listmonk_admin_password)"
echo
echo "Relay configured: ${SMTP_HOST}:${SMTP_PORT} as ${SMTP_USERNAME}"
echo "From address:     ${SMTP_FROM}"
echo "Bounce mailbox:   ${BOUNCE_MAILBOX_USERNAME}@${BOUNCE_MAILBOX_HOST}"
echo
echo "Suggested DNS for the mailings subdomain:"
echo "  TXT mailings.example.com   -> v=spf1 include:${SMTP_HOST} ~all"
echo "  TXT _dmarc.mailings.example.com -> v=DMARC1; p=none; rua=mailto:dmarc@example.com"
echo
echo "Next: log in, send a test broadcast to a Gmail-verified address, confirm"
echo "Authentication-Results shows spf=pass dkim=pass dmarc=pass."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-listmonk-ubuntu22.sh
LISTMONK_HOSTNAME=lists.example.com \
LETSENCRYPT_EMAIL=ops@example.com \
SMTP_HOST=send.example.com \
SMTP_USERNAME=ListmonkBulk \
SMTP_PASSWORD=<identifiant-postal> \
SMTP_FROM=news@mailings.example.com \
BOUNCE_MAILBOX_HOST=mail.example.com \
BOUNCE_MAILBOX_USERNAME=bounces@example.com \
BOUNCE_MAILBOX_PASSWORD=<mot-de-passe-boîte> \
/root/setup-listmonk-ubuntu22.sh

Le mot de passe admin Listmonk est écrit dans /root/.listmonk_admin_password. Connectez-vous, importez la liste en double opt-in uniquement, et envoyez une diffusion test à une adresse Gmail vérifiée avant tout passage en production. Confirmez que Authentication-Results affiche spf=pass dkim=pass dmarc=pass. Réglez l’action de bounce à blocklist après 2 bounces souples pour que les adresses quittent la liste automatiquement. Le script n’active volontairement pas de sauvegardes au niveau hôte — supposez des instantanés au niveau VM ; sur bare metal, ajoutez un pg_dump listmonk quotidien plus une étape restic couvrant /opt/listmonk/uploads si vous y rangez les images de campagne.

Une plateforme d’infolettres autohébergée ne rapporte que si la livrabilité est supervisée, que la liste reste propre, et que la courbe de préchauffage est respectée. Stack Harbor fait tourner Listmonk dans le cadre des environnements infogérés, avec taux de bounce, taux de plainte et Gmail Postmaster Tools surveillés.