Aller au contenu

Déployer HashiCorp Vault sur AlmaLinux 9 (prêt pour la production)

Monter un Vault HashiCorp à nœud unique durci sur AlmaLinux 9 — backend file, TLS, dispositif d'audit, systemd, nginx en pass-through, discipline des clés.

On vous demande de monter Vault comme magasin central de secrets. Le guide HashiCorp Learn vous montre vault server -dev, vous copiez-collez le root token, vous écrivez votre premier secret KV, vous remettez ça à l’équipe d’exploitation. Six mois plus tard, le serveur dev-mode a redémarré avec le backend en mémoire donc tout est perdu, l’écouteur est en HTTP, aucun dispositif d’audit n’a été activé donc personne ne peut répondre à « qui a lu ce secret mardi dernier », les clés de descellement sont toujours dans ~/.vault-keys.txt sur la même VM, et Vault — la pièce sur laquelle la plateforme s’appuie pour stocker chaque identifiant — est à un rollback de snapshot près de l’irrécupérable.

Ce qui se passe

Un déploiement Vault réellement prêt pour la production demande beaucoup plus que vault server -dev. Le serveur doit tourner avec un vrai backend de stockage persistant (file convient en mono-nœud, couplé à des snapshots VM), avec TLS sur l’écouteur — jamais HTTP — et au moins un dispositif d’audit activé avant qu’un seul secret ne soit écrit. Les cinq clés de descellement produites par vault operator init et le root token initial doivent quitter l’hôte immédiatement ; elles sont fragmentées en parts de Shamir précisément pour vivre dans cinq magasins distincts contrôlés par cinq humains différents, pas dans un fichier .txt dans /root. Le root token sert à la bascule uniquement — il doit être rouluté vers un jeton appartenant à un humain nommé avec une politique du moindre privilège, puis révoqué. SSH doit avoir l’authentification par mot de passe désactivée tout en gardant l’accès clé root. Aucune de ces étapes n’est individuellement critique — sautez-les et la pièce sur laquelle tous les autres services s’appuient devient la fuite de masse d’identifiants la plus facile de l’entreprise.

Comment vérifier

Après installation, les écouteurs sur l’hôte doivent être :

ss -lntp | grep -E ':(80|443|8200)\b'
# 0.0.0.0:80      nginx
# 0.0.0.0:443     nginx
# 127.0.0.1:8200  vault

vault doit écouter sur 127.0.0.1, jamais 0.0.0.0. L’état du sceau et le dispositif d’audit :

VAULT_ADDR=https://vault.example.com vault status
# Sealed: false  (après descellement par l'opérateur)
# Initialized: true
# Storage Type: file

VAULT_ADDR=https://vault.example.com VAULT_TOKEN=... vault audit list
# Path     Type   Description
# ----     ----   -----------
# file/    file   audit log to /var/log/vault/audit.log

Si vault status retourne Sealed: true après le descellement, le sceau est cassé ; si vault audit list retourne « No audit devices are enabled. », vous n’avez aucune trace de qui a lu quoi — un problème la première fois qu’un identifiant fuit.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-vault-almalinux9.sh, puis exécutez-le. Il déroule l’installation sur une VM AlmaLinux 9.x fraîche : mise à jour de base + EPEL, ajustement noyau, limites de fichiers, firewalld limité à SSH + HTTP + HTTPS, durcissement SSH, dnf-automatic.timer, le dépôt officiel HashiCorp, Vault comme paquet système, un utilisateur vault avec /opt/vault/data pour le backend file, un écouteur TLS sur 127.0.0.1:8200, une unité systemd avec LimitNOFILE=64000, vault operator init au premier démarrage avec les clés et le root token affichés sur stdout, vault operator unseal piloté avec ces clés, un dispositif d’audit dans /var/log/vault/audit.log, nginx en terminateur TLS pass-through vers Vault, Let’s Encrypt pour le certificat public, et une boucle d’attente qui vérifie que le sceau est ouvert avant de déclarer succès.

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

### AlmaLinux 9.x HashiCorp Vault clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures Vault + 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

: "${VAULT_DOMAIN:?Set VAULT_DOMAIN=vault.example.com}"
: "${VAULT_EMAIL:?Set VAULT_EMAIL=ops@example.com for Let's Encrypt}"

echo
echo "========================================"
echo "HashiCorp Vault AlmaLinux 9.x Setup"
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 openssl

echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true

echo "==> Configuring SELinux to enforcing"
if [[ -f /etc/selinux/config ]]; then
  sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
fi
setenforce 1 || true

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-vault.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
net.ipv6.conf.default.accept_redirects = 0

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_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

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-vault.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
vault soft nofile 64000
vault hard nofile 64000
LIMITS

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 --reload

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 ChallengeResponseAuthentication 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 fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN

systemctl enable --now fail2ban

echo "==> Configuring automatic security updates"
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
network_online_timeout = 60
download_updates = yes
apply_updates = yes

[emitters]
emit_via = stdio

[base]
debuglevel = 1
DNFAUTO

systemctl enable --now dnf-automatic.timer

echo "==> Adding HashiCorp repository"
dnf -y install dnf-plugins-core
dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

echo "==> Installing Vault"
dnf -y install vault

echo "==> Generating loopback TLS for the Vault listener (nginx replaces this on the public side)"
mkdir -p /opt/vault/tls
cd /opt/vault/tls
openssl req -x509 -newkey rsa:4096 -nodes -days 825 \
  -keyout vault-loopback.key \
  -out vault-loopback.crt \
  -subj "/CN=127.0.0.1" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
chown -R vault:vault /opt/vault/tls
chmod 600 /opt/vault/tls/vault-loopback.key
chmod 644 /opt/vault/tls/vault-loopback.crt

echo "==> Writing Vault configuration"
cat > /etc/vault.d/vault.hcl <<HCL
ui = true
disable_mlock = false
cluster_addr  = "https://127.0.0.1:8201"
api_addr      = "https://${VAULT_DOMAIN}"

storage "file" {
  path = "/opt/vault/data"
}

listener "tcp" {
  address       = "127.0.0.1:8200"
  tls_cert_file = "/opt/vault/tls/vault-loopback.crt"
  tls_key_file  = "/opt/vault/tls/vault-loopback.key"
  tls_min_version = "tls12"
}

telemetry {
  prometheus_retention_time = "12h"
  disable_hostname          = true
}
HCL

chown root:vault /etc/vault.d/vault.hcl
chmod 640 /etc/vault.d/vault.hcl

mkdir -p /opt/vault/data /var/log/vault
chown -R vault:vault /opt/vault/data /var/log/vault

echo "==> Patching systemd unit for LimitNOFILE"
mkdir -p /etc/systemd/system/vault.service.d
cat > /etc/systemd/system/vault.service.d/override.conf <<'OVERRIDE'
[Service]
LimitNOFILE=64000
OVERRIDE

systemctl daemon-reload
systemctl enable --now vault

echo "==> Waiting for Vault on 127.0.0.1:8200"
for i in {1..60}; do
  if ss -lntp | grep -q '127.0.0.1:8200'; then
    break
  fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:8200'; then
  echo "Vault failed to listen on 127.0.0.1:8200"
  journalctl -u vault -n 200 --no-pager || true
  exit 1
fi

export VAULT_ADDR="https://127.0.0.1:8200"
export VAULT_CACERT="/opt/vault/tls/vault-loopback.crt"

INIT_OUT="/root/vault-init.txt"

if vault status -format=json 2>/dev/null | jq -e '.initialized == false' >/dev/null; then
  echo "==> Initializing Vault (5 unseal keys, threshold 3)"
  vault operator init -key-shares=5 -key-threshold=3 -format=json > "$INIT_OUT"
  chmod 600 "$INIT_OUT"
fi

UNSEAL_KEY_1="$(jq -r '.unseal_keys_b64[0]' "$INIT_OUT")"
UNSEAL_KEY_2="$(jq -r '.unseal_keys_b64[1]' "$INIT_OUT")"
UNSEAL_KEY_3="$(jq -r '.unseal_keys_b64[2]' "$INIT_OUT")"
ROOT_TOKEN="$(jq -r '.root_token' "$INIT_OUT")"

echo "==> Unsealing Vault"
vault operator unseal "$UNSEAL_KEY_1" >/dev/null
vault operator unseal "$UNSEAL_KEY_2" >/dev/null
vault operator unseal "$UNSEAL_KEY_3" >/dev/null

export VAULT_TOKEN="$ROOT_TOKEN"

echo "==> Enabling audit log device"
if ! vault audit list 2>/dev/null | grep -q '^file/'; then
  vault audit enable file file_path=/var/log/vault/audit.log
fi

echo "==> Installing nginx and certbot"
dnf -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/vault.conf <<NGINX
upstream vault_backend {
    server 127.0.0.1:8200;
    keepalive 16;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${VAULT_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${VAULT_DOMAIN};

    client_max_body_size 32M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location / {
        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 \$scheme;
        proxy_http_version 1.1;
        proxy_ssl_verify off;
        proxy_pass https://vault_backend;
    }
}
NGINX

rm -f /etc/nginx/conf.d/default.conf

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${VAULT_EMAIL}" -d "${VAULT_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then
    break
  fi
  sleep 1
done

echo "==> Final package update"
dnf -y update

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r

echo
echo "SELinux:"
getenforce || true

echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|8200)\b' || true

echo
echo "Vault status:"
vault status || true

echo
echo "Vault audit devices:"
vault audit list || true

echo
echo "Services:"
systemctl is-active vault nginx fail2ban chronyd || true

echo
echo "========================================"
echo "UNSEAL KEYS AND INITIAL ROOT TOKEN"
echo "========================================"
echo
echo "These are printed once. They are also stored in ${INIT_OUT} (mode 600)."
echo "DO IMMEDIATELY:"
echo "  1. Copy them off this host into FIVE separate human-controlled stores."
echo "  2. The threshold is 3 — no single human should hold 3 or more keys."
echo "  3. Use the initial root token to create a named human admin with a policy, then revoke the root token: vault token revoke <root_token>"
echo "  4. Delete ${INIT_OUT} from this host once the keys are out-of-band."
echo
cat "${INIT_OUT}"

echo
echo "Web UI:"
echo "https://${VAULT_DOMAIN}/"

echo
echo "Final step:"
echo "Copy the keys out-of-band, rotate the root token, then enable an auth method (userpass + MFA, or OIDC against your IdP) for daily operator use."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-vault-almalinux9.sh
VAULT_DOMAIN=vault.example.com VAULT_EMAIL=ops@example.com /root/setup-vault-almalinux9.sh

À la fin, le script affiche les cinq clés de descellement et le root token initial. Arrêtez tout au moment où ils apparaissent : copiez-les hors de cet hôte dans cinq magasins distincts détenus par cinq humains différents, puis supprimez /root/vault-init.txt. Le seuil est de trois, donc la règle est « aucune personne ne détient trois clés ou plus ». Utilisez le root token initial une seule fois pour créer un administrateur humain nommé avec une méthode d’authentification (userpass + MFA, ou OIDC), puis exécutez vault token revoke <root_token>. Les sauvegardes au niveau hôte ne sont pas configurées ici ; /opt/vault/data/ et /var/log/vault/audit.log doivent être couverts par votre politique de snapshots VM avec des répétitions de restauration.

Quand l’infrastructure de secrets doit rester correcte à travers les rotations de sceau, les mises à jour de version et un incident de fuite d’identifiants à 3 h du matin, ça relève des Environnements infogérés (Environnements infogérés) — ou réservez une revue d’infrastructure rapide.