Hace unos días termine una guía para la instalación y configuración de fail2ban, algunos colegas cuando lean esto se reirán un poco.
Para
comenzar hay que realizar la instalación de el paquete fail2ban
#aptitude
install fail2ban
Copiamos
el archivo de configuración del jail.conf a jail.local, donde
tendremos nuestra configuración personalizada
#cp
/etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Al
momento de editar veremos algo como esto, donde colocaremos en true
los servicios que se requieran. Por defecto el único servicio que
viene habilitado en el fail2ban es el ssh, si se requieren habilitar
algún otro como por ejemplo apache, postfix, proftpd, se deben
colocar en true y verificar los valores que vienen por defecto. Antes
de habilitar algún servicio se debe personalizar los valores que
vienen por defecto.
Tiempo
de bloqueo, las ip de redes locales, el máximo de intentos.
#
"ignoreip" can be an IP address, a CIDR mask or a DNS host 
ignoreip
= 127.0.0.1 192.168.1.0/24 
bantime
 = 1800 
maxretry
= 3
La
dirección de correo de la persona que recibirá las alertas.
#
Destination email address used solely for the interpolations in 
#
jail.{conf,local} configuration files. 
destemail
= root@localhost 
El
tipo de servicio que utiliza el sistema para enviar los correos
electrónicos, el caso de fail2ban utiliza sendmail pero en caso de
que el sistema utilice “mail” se puede cambiar la orden.
#
email action. Since 0.8.1 upstream fail2ban uses sendmail 
#
MTA for the mailing. Change mta configuration parameter to mail 
#
if you want to revert to conventional 'mail'. 
mta
= sendmail 
Cambiamos
la acción para que envié el correo electrónico, al momento de un
evento.
#
Choose default action.  To change, just override value of 'action'
with the 
#
interpolation to the chosen action shortcut (e.g.  action_mw,
action_mwl, etc) in jail.local 
#
globally (section [DEFAULT]) or per specific section 
action
= %(action_mwl)s 
Parte
del contenido del archivo
[ssh]
enabled
 = true 
port
    = ssh 
filter
  = sshd 
logpath
 = /var/log/auth.log 
maxretry
= 6 
[apache]
enabled
 = false 
port
    = http,https 
filter
  = apache-auth 
logpath
 = /var/log/apache*/*error.log 
maxretry
= 6 
[proftpd]
enabled
 = false 
port
    = ftp,ftp-data,ftps,ftps-data 
filter
  = proftpd 
logpath
 = /var/log/proftpd/proftpd.log 
maxretry
= 6 
[postfix]
enabled
 = false 
port
    = smtp,ssmtp 
filter
  = postfix 
logpath
 = /var/log/mail.log
En
caso de que configuremos el fail2ban para proteger el apache debemos
habilitar lo siguiente.
#
HTTP servers 
[apache]
enabled
 = false 
port
    = http,https 
filter
  = apache-auth 
logpath
 = /var/log/apache*/*error.log 
maxretry
= 6
#
#
default action is now multiport, so apache-multiport jail was left 
#
for compatibility with previous (<0 .7.6-2=".7.6-2" font="font" releases="releases">0>
[apache-multiport]
enabled
  = true 
port
     = http,https 
filter
   = apache-auth 
logpath
  = /var/log/apache*/*error.log 
maxretry
 = 6 
#
Para prevenir ejecucion de scripts
[apache-noscript]
enabled
 = true 
port
    = http,https 
filter
  = apache-noscript 
logpath
 = /var/log/apache*/*error.log 
maxretry
= 6 
#
Para prevenir overflows
[apache-overflows]
enabled
 = true 
port
    = http,https 
filter
  = apache-overflows 
logpath
 = /var/log/apache*/*error.log 
maxretry
= 2 
#
Para prevenir ataques de inyeccion de codigo tipo GET.
[php-url-fopen]
enabled
= true 
port
   = http,https 
filter
 = php-url-fopen 
logpath
= /var/www/vhosts/*/statistics/logs/access_log 
maxretry
= 1 
#Para
prevenir ataques de host que se conectan haciendo un “User Agent”
sospechoso
[apache-badbots]
enabled
 = true 
filter
  = apache-badbots 
port
    = http,https 
logpath
 = /var/log/apache*/*access.log 
maxretry
= 1 
#Para
prevenir busqueda de directorios en el servidor
[apache-nohome]
enabled
 = true 
filter
  = apache-nohome 
port
    = http,https 
logpath
 = /var/log/apache*/*access.log 
maxretry
= 1
#Para
prevenir SQL Injection
[sqli-attack]
enabled
 = true 
port
    = 80 
protocol
= tcp 
maxentry
= 3 
bantime
 = 90000 
filter
  = apache-sqli-blocklist 
logpath
 = /var/log/apache2/*.log
#Para
prevenir RFI (Remote File Inclusion)
[rfi-attack]
enabled
 = true 
port
    = 80 
protocol
= tcp 
maxentry
= 6 
filter
  = apache-rfi-blocklist 
logpath
 = /var/log/apache2/*.log
Para
que las funciones de SQL Injection y RFI funcionen debemos crear los
siguientes archivos de configuración dentro de
/etc/fail2ban/filter.d/ con el siguiente contenido.
#vim
apache-sqli-blocklist.conf
Agregamos
#
Fail2Ban configuration file 
#
#
Author: Martin Schiftan 
#
#
$Revision: 510 $ 
[Definition]
#
Option:  failregex 
#
Notes.:  regex to match the w00tw00t scan messages in the logfile.
The 
#
         host must be matched by a group named "host". The
tag "" can  
#
         be used for standard IP/hostname matching. 
#
Values:  TEXT 
failregex
= ^ .*\+SELECT.*  
            ^
.*UNION\+ALL\+SELECT.*  
            ^
(.*)UNION\+SELECT(.*)  
            ^
(.*)1337+UNION+SELECT+(.*)  
            ^
(.*)UNION(.*)SELECT(.*)  
            ^
(.*)UNION(.*)DATABASE(.*)  
#
Option:  ignoreregex 
#
Notes.:  regex to ignore. If this regex matches, the line is ignored.
#
Values:  TEXT 
ignoreregex
= 
#vim
apache-rfi-blocklist.conf
Agregamos
#
Fail2Ban configuration file 
#
#
Author: Martin Schiftan 
#
#
$Revision: 510 $ 
[Definition]
#
Option:  failregex 
#
Notes.:  regex to match the w00tw00t scan messages in the logfile.
The 
#
         host must be matched by a group named "host". The
tag "" can  
#
         be used for standard IP/hostname matching. 
#
Values:  TEXT 
failregex
= ^ (.*)etc\/passwd(.*)  
            ^
(.*)28sleep(.*)  
            ^
(.*)acunetix_wvs_security_test(.*)  
            ^
(.*)email.tst(.*)  
            ^
(.*)appserv_root(.*)  
            ^
(.*)proc/self/(.*)  
            ^
(.*)proc\/self\/(.*)  
            ^
(.*)FHScan(.*)  
            ^
-.*"(GET|POST).*\?.*\=.*tt.*\:\/\/.* HTTP\/.*$  
#
Option:  ignoreregex 
#
Notes.:  regex to ignore. If this regex matches, the line is ignored.
#
Values:  TEXT 
ignoreregex
= 
Por
ultimo reiniciamos el servicio y observamos que se envío un correo
electrónico a la dirección de destino, se aplicaron las reglas de
iptables para los servicios habilitados.
#/etc/init.d/fail2ban
restart 
[
ok ] Restarting authentication failure monitor: fail2ban
#iptables
-L -n
Chain
INPUT (policy ACCEPT) 
target
    prot opt source               destination         
fail2ban-ssh
 tcp  --  0.0.0.0/0            0.0.0.0/0            multiport dports
22 
Chain
FORWARD (policy ACCEPT) 
target
    prot opt source               destination         
Chain
OUTPUT (policy ACCEPT) 
target
    prot opt source               destination         
Chain
fail2ban-ssh (1 references) 
target
    prot opt source               destination         
RETURN
    all  --  0.0.0.0/0            0.0.0.0/0
Buenos días.
ResponderEliminarGracias por el artículo. En mi caso con debian squeeze con kernel 3.9.0, Python 2.6.6 y fail2ban versión 0.8.4 he tenido que modificar las reglas de apache-sqli-blocklist.conf porque daba una excepción al relanzar fail2ban:
(...)
ConfigParser.ParsingError: File contains parsing errors: /etc/fail2ban/filter.d/apache-sqli-blocklist.conf
[line 16]: '^ .*UNION\\+ALL\\+SELECT.*\n'
[line 17]: '^ (.*)UNION\\+SELECT(.*)\n'
[line 18]: '^ (.*)1337+UNION+SELECT+(.*)\n'
[line 19]: '^ (.*)UNION(.*)SELECT(.*)\n'
[line 20]: '^ (.*)UNION(.*)DATABASE(.*)\n'
(...)
La he corregido y me ha funcionado de la siguiente forma:
(...)
failregex = ^ .*\+SELECT.*$
^ .*UNION\+ALL\+SELECT.*$
^ (.*)UNION\+SELECT(.*)$
^ (.*)1337+UNION+SELECT+(.*)$
^ (.*)UNION(.*)SELECT(.*)$
^ (.*)UNION(.*)DATABASE(.*)$
(...)
La otra regla no la he usado, pero al no tener el caracter '$' para delimiar, supongo que puede fallar al importar.
Un saludo.
Compañero excelente pots; pero vengo a consultarte una duda que tengo.
ResponderEliminarFijate en la configuracion del jail.local donde estan los parametros del ssh donde dice:
port = ssh
se podria colocar el numero de puerto?? te lo consulto ya que no utilizo el puerto por defecto del ssh que es el 22.
Espero me alla explicado y esperar a ver si puedes ayudarme con eso.
saludos...
Es posible que falle al copiar y pegar en la consola, debes verificar en los logs si existe algun otro error de sintaxis.
ResponderEliminarSaludos Eduardo, donde dice port colcoas el valor que estes utilizando para el ssh.
ResponderEliminarGracias por Escribir