Saltar a contenido

4. Configurar Fail2ban (sshd + servidor web)

Protección activa con jaulas integradas en UFW.

Traefik en Docker

Si tu servidor web corre detrás de Traefik en contenedores, fail2ban no lee los logs del host de forma directa — este paso no cubre ese caso todavía. La parte de sshd de abajo sí aplica igualmente.

  1. Comprobar si ya está instalado:

    dpkg -l | grep fail2ban
    
  2. Instalar si hace falta:

    sudo apt install fail2ban
    
  3. Comprobar que existe la acción ufw de fail2ban:

    ls /etc/fail2ban/action.d/ufw.conf
    

    Si no existe, usa banaction = iptables-multiport en vez de ufw en el paso siguiente.

  4. Crear el filtro para rutas sensibles:

    sudo vim /etc/fail2ban/filter.d/apache-sensitive-paths.conf
    

    Contenido:

    [Definition]
    failregex = ^<HOST> .* "(GET|POST) .*(wp-config\.php|\.env|\.git/config|xmlrpc\.php|\.htpasswd).*" (403|404)
    ignoreregex =
    
    sudo vim /etc/fail2ban/filter.d/nginx-sensitive-paths.conf
    

    Contenido (mismo patrón, adaptado al log de nginx):

    [Definition]
    failregex = ^<HOST> .* "(GET|POST) .*(wp-config\.php|\.env|\.git/config|xmlrpc\.php|\.htpasswd).*" (403|404)
    ignoreregex =
    
  5. Crear jail.local desde cero (no copiar jail.conf — solo va aquí lo que sobreescribes):

    sudo vim /etc/fail2ban/jail.local
    

    Contenido:

    [DEFAULT]
    banaction = ufw
    
    [sshd]
    enabled = true
    port    = 22
    maxretry = 5
    bantime  = 3600
    
    [apache-auth]
    enabled = true
    
    [apache-badbots]
    enabled = true
    
    [apache-sensitive-paths]
    enabled  = true
    port     = http,https
    filter   = apache-sensitive-paths
    logpath  = /var/log/apache2/*access.log
    maxretry = 1
    bantime  = 86400
    
    [DEFAULT]
    banaction = ufw
    
    [sshd]
    enabled = true
    port    = 22
    maxretry = 5
    bantime  = 3600
    
    [nginx-http-auth]
    enabled = true
    
    [nginx-botsearch]
    enabled = true
    
    [nginx-sensitive-paths]
    enabled  = true
    port     = http,https
    filter   = nginx-sensitive-paths
    logpath  = /var/log/nginx/*access.log
    maxretry = 1
    bantime  = 86400
    

     

    Fail2ban trae de serie los filtros nginx-http-auth y nginx-botsearch (equivalentes a apache-auth/apache-badbots), así que no hace falta crearlos a mano — solo el de rutas sensibles del paso anterior.

  6. Reiniciar y verificar:

    sudo service fail2ban restart
    sudo fail2ban-client status
    sudo fail2ban-client status sshd
    sudo ufw status numbered