PROCEDIMIENTO DE INSTALACIÓN FAIL2BAN
DERECHOS DE USO
La presente documentación es propiedad de la Superintendencia de Servicios
de Certificación Electrónica SUSCERTE, tiene carácter privado y restringido
y esta dirigido exclusivamente a su(s) destinatario(s), no podrá ser objeto
de reproducción total o parcial, ni transmisión de ninguna forma o por
cualquier medio, ya sea electrónico, mecánico, digital, registro o
cualquier otro, no podrá ser distribuido sin el permiso previo y escrito de
SUSCERTE, bajo ningún concepto. Si usted ha recibido este mensaje por
error, debe evitar realizar cualquier acción descrita anteriormente,
asimismo le agradecemos comunicarlo al remitente y borrar el mensaje y
cualquier documento adjunto. El incumplimiento de las limitaciones
señaladas por cualquier persona que tenga acceso a la documentación será
sancionada conforme a la ley.
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
Autor VENCERT
Fecha 26/06/2014
Versión 1.0
Control de versiones
Versión Áreas Descripción del cambio Autor Fecha
Modificadas
1 Todas Version Inicial VenCERT 26 /06/2014
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
Índice
INTRODUCCIÓN................................................................................................................................... 4
PROCEDIMIENTO........................................................................................................................... 5-15
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
INTRODUCCIÓN
Es un script programado en Python que “observa” los logs de Apache en busca de patrones
sospechosos y es capaz de tomar medidas para bloquear a los atacantes ya sea con iptables o
lanzando un comando de nuestra elección. Se distribuye bajo licencia GNU.
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
PROCEDIMIENTO
1.- Instalar de fail2ban
# aptitude install fail2ban
En el directorio: /etc/fail2ban/ deberán estar presente dos directorios (action.d y filter.d) y los
archivos ( fail2ban.conf, jail.conf,jail.local):
• action.d: Encontraremos las acciones que Fail2ban realizará cuando alguno de nuestros
filtros encuentre alguna IP haciendo maldades. Estas acciones pasan por filtrado con iptables,
envio de e-mails de aviso o hasta realizar una llamada utilizando Asterisk.
• filter.d: Tenemos todos los filtros que utilizaremos para identificar a nuestros atacantes.
• fail2ban.conf: archivo de configuración de la herramienta como tal, están presentes
parámetros de funcionamiento de la herramienta ( este archivo no se modifica).
• jail.conf y jail.local: configuración personalizada de las reglas y filtros.
También es importante tener en cuenta los siguientes parámetros que estarán presentes en el archivo
de configuración de fail2ban.
• maxretry: Especifica cuantos intentos vamos a dejar antes de banear la ip.
• findtime: Es el período de tiempo en segundos que estamos contando los “reintentos” (300
segundos = 5 minutos).
• bantime: Es el tiempo que debemos esperar para liberar las peticiones, osea el tiempo que la
IP estará baneada, en este caso se trata de 5 minutos.
2.- 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 el archivo jail.local, 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, 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.
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
Un ejemplo del archivo jail.local se presenta de la siguiente manera:
# Fail2Ban configuration file.
#
# This file was composed for Debian systems from the original one
# provided now under /usr/share/doc/fail2ban/examples/jail.conf
# for additional examples.
#
# To avoid merges during upgrades DO NOT MODIFY THIS FILE
# and rather provide your changes in /etc/fail2ban/jail.local
#
# Author: Yaroslav O. Halchenko <
[email protected]>
#
# $Revision$
#
# The DEFAULT allows a global definition of the options. They can be overridden
# in each jail afterwards.
[DEFAULT]
# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip = “ aqui se coloca la ip de confianza”
bantime = 600
maxretry = 3
# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
# This issue left ToDo, so polling is default backend for now
backend = auto
#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = root@localhost
#
# ACTIONS
#
# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overridden globally or per
# section within jail.local file
banaction = iptables-multiport
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
# 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
# Default protocol
protocol = tcp
# Specify chain where jumps would need to be added in iptables-* actions
chain = INPUT
#
# Action shortcuts. To be used to define action parameter
# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%
(chain)s"]
# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s",
chain="%(chain)s"]
%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s",
chain="%(chain)s"]
# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s",
chain="%(chain)s"]
%(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s,
chain="%(chain)s"]
# 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_)s
#
# JAILS
#
# Next jails corresponds to the standard configuration in Fail2ban 0.6 which
# was shipped in Debian. Enable any defined here jail by including
#
# [SECTION_NAME]
# enabled = true
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
#
# in /etc/fail2ban/jail.local.
# Optionally you may override any other parameter (e.g. banaction,
# action, port, logpath, etc) in that section within jail.local
[ssh]
enabled = true
port = 22 se cambia por el puerto asignado a ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 6
[dropbear]
enabled = false
port = ssh
filter = sshd
logpath = /var/log/dropbear
maxretry = 6
# Generic filter for pam. Has to be used with action which bans all ports
# such as iptables-allports, shorewall
[pam-generic]
enabled = false
# pam-generic filter can be customized to monitor specific subset of 'tty's
filter = pam-generic
# port actually must be irrelevant but lets leave it all for some possible uses
port = all
banaction = iptables-allports
port = anyport
logpath = /var/log/auth.log
maxretry = 6
[xinetd-fail]
enabled = false
filter = xinetd-fail
port = all
banaction = iptables-multiport-log
logpath = /var/log/daemon.log
maxretry = 2
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
[ssh-ddos]
enabled = false
port = ssh
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
# 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) releases
[apache-multiport]
enabled = false
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 6
#prevenir ejecución de script
[apache-noscript]
enabled = true
port = http,https
filter = apache-noscript
logpath = /var/log/apache*/*error.log
maxretry = 6
#prevenir overflows
[apache-overflows]
enabled = true
port = http,https
filter = apache-overflows
logpath = /var/log/apache*/*error.log
maxretry = 2
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
# FTP servers
#
[vsftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = vsftpd
logpath = /var/log/vsftpd.log
# or overwrite it in jails.local to be
# logpath = /var/log/auth.log
# if you want to rely on PAM failed login attempts
# vsftpd's failregex should match both of those formats
maxretry = 6
[proftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 6
[pure-ftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = pure-ftpd
logpath = /var/log/auth.log
maxretry = 6
[wuftpd]
enabled = false
port = ftp,ftp-data,ftps,ftps-data
filter = wuftpd
logpath = /var/log/auth.log
maxretry = 6
# Mail servers
#
[postfix]
enabled = false
port = smtp,ssmtp
filter = postfix
logpath = /var/log/mail.log
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
[couriersmtp]
enabled = false
port = smtp,ssmtp
filter = couriersmtp
logpath = /var/log/mail.log
#
# Mail servers authenticators: might be used for smtp,ftp,imap servers, so
# all relevant ports get banned
#
[courierauth]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = courierlogin
logpath = /var/log/mail.log
[sasl]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = sasl
# You might consider monitoring /var/log/mail.warn instead if you are
# running postfix since it would provide the same log lines at the
# "warn" level but overall at the smaller filesize.
logpath = /var/log/mail.log
[dovecot]
enabled = false
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = dovecot
logpath = /var/log/mail.log
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
# DNS Servers
# These jails block attacks against named (bind9). By default, logging is off
# with bind9 installation. You will need something like this:
#
# logging {
# channel security_file {
# file "/var/log/named/security.log" versions 3 size 30m;
# severity dynamic;
# print-time yes;
# };
# category security {
# security_file;
# };
# };
#
# in your named.conf to provide proper logging
# !!! WARNING !!!
# Since UDP is connection-less protocol, spoofing of IP and imitation
# of illegal actions is way too simple. Thus enabling of this filter
# might provide an easy way for implementing a DoS against a chosen
# victim. See
# http://nion.modprobe.de/blog/archives/690-fail2ban-+-dns-fail.html
# Please DO NOT USE this jail unless you know what you are doing.
#[named-refused-udp]
#enabled = false
#port = domain,953
#protocol = udp
#filter = named-refused
#logpath = /var/log/named/security.log
[named-refused-tcp]
enabled = false
port = domain,953
protocol = tcp
filter = named-refused
logpath = /var/log/named/security.log
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
#prevenir ataques de fuerza bruta al puerto ssh
[SSH-iptables]
enabled = true
filter = sshd
action = iptables-allports[name=SSH, protocol=tcp, port=22]
logpath = /var/log/auth.log
maxretry = 3
bantime = 10800
#Para prevenir ataques de host que se conectan User Agent sospechoso
[apache-badbots]
enabled = true
filter = apache-badbots
action = iptables-multiport[name=BadBots, port="http,https"]
logpath = /var/log/apache*/*access*.log
bantime = 86400 # 1 day
maxretry = 1
###################### Fin del Archivo de configuración ################################
Es importante destacar que en este archivo se debe colocar la ruta correcta de los logs de registros
de nuestro servidor web, ya que de hay es donde fail2ban va a verificar las peticiones que se le
hagan al mismo.
4.- Directorio donde se encuentran los archivos de configuración de los filtros es
/etc/fail2ban/filter.d/
Para crear nuevos filtros personalizados de debe crear el archivo en este directorio
/etc/fail2ban/filter.d/ luego en el archivo jail.local se debe agregar las reglas correspondientes
al filtro creado para que pueda funcionar adecuadamente.
5.- Reiniciar el servicio de fail2ban
#/etc/init.d/fail2ban restart
Deberá mostrar algo como esto
[ ok ] Restarting authentication failure monitor: fail2ban
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial
6.- Para verificar los logs de registros de fai2ban ingresar a al siguiente directorio
# cd /var/log/fail2ban.log
En los logs de fail2ban se observa que cuando se activa algún filtro, muestra la acción tomada y
especifica el filtro que bloquea la IP atacante.
Av. Andrés Bello, Torre BFC, Piso 13, Sector Guaicaipuro, Caracas – Venezuela
Tlfs. +58 212 5785674 – Fax +58 212 5724932 . http://www.suscerte.gob.ve Confidencial