Fail2ban — Protection brute force SSH + Nginx

Installe et configure Fail2ban pour bloquer les attaques brute force SSH (et Nginx si présent). Ban après 5 échecs pendant 1h, whitelist 127.0.0.1.

sécuritéfail2bansshbrute-forcelinux
$ curl scripts.ysavary.fr/fail2ban | bash

Fail2ban — Protection brute force

Installe et configure Fail2ban pour surveiller les logs SSH (et Nginx si installé) et bannir automatiquement les IPs suspectes.

Configuration appliquée :

Commandes utiles après install :

bash
#!/bin/bash
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERR]${NC}   $*"; exit 1; }

[[ $EUID -ne 0 ]] && error "Ce script doit être exécuté en root."

# ── Installation ──────────────────────────────────────────────────────────────
info "=== Installation de Fail2ban ==="
apt-get update -qq
apt-get install -y fail2ban

# ── Configuration principale ──────────────────────────────────────────────────
info "=== Configuration de Fail2ban ==="

cat > /etc/fail2ban/jail.local <<'EOF'
[DEFAULT]
# Whitelist
ignoreip = 127.0.0.1/8 ::1

# Paramètres globaux
bantime   = 3600      ; 1 heure
findtime  = 600       ; fenêtre de 10 minutes
maxretry  = 5         ; 5 échecs max

# Backend de détection
backend = systemd

# Action par défaut : ban iptables
banaction = iptables-multiport
banaction_allports = iptables-allports

[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
bantime  = 3600
findtime = 600
EOF

# ── Jail Nginx (si installé) ──────────────────────────────────────────────────
if command -v nginx &>/dev/null; then
    info "Nginx détecté — ajout des jails Nginx"
    cat >> /etc/fail2ban/jail.local <<'EOF'

[nginx-http-auth]
enabled  = true
port     = http,https
filter   = nginx-http-auth
logpath  = /var/log/nginx/error.log
maxretry = 5

[nginx-limit-req]
enabled  = true
port     = http,https
filter   = nginx-limit-req
logpath  = /var/log/nginx/error.log
maxretry = 10
bantime  = 1800
findtime = 60

[nginx-botsearch]
enabled  = true
port     = http,https
filter   = nginx-botsearch
logpath  = /var/log/nginx/access.log
maxretry = 2
bantime  = 86400
findtime = 3600
EOF
else
    warn "Nginx non détecté, jails Nginx ignorées."
fi

# ── Redémarrage ───────────────────────────────────────────────────────────────
systemctl enable --now fail2ban
systemctl restart fail2ban

sleep 2

echo ""
info "=== Fail2ban opérationnel ==="
echo ""
fail2ban-client status 2>/dev/null || true
echo ""
echo "  Commandes utiles :"
echo "    fail2ban-client status               — état global"
echo "    fail2ban-client status sshd          — détail jail SSH"
echo "    fail2ban-client set sshd unbanip IP  — débannir une IP"
echo "    fail2ban-client banned               — toutes les IPs bannies"
echo "    tail -f /var/log/fail2ban.log        — logs en direct"
echo ""