Instalar y configurar Fail2ban


Fail2ban (“si fallas te baneo”) es una aplicación escrita en Python para la prevención de intrusos en un sistema, permite bloquear y avisar de las conexiones remotas que intentan ataques por fuerza bruta (Brutus, TCH-Hydra, Medusa, ncrack) o acceso no autorizados. Fail2ban no sólo sirve para detectar los típicos ataques de fuerza bruta a servicios tan populares como ssh (Secure Shell) o FTP, también admite reglas mediante expresiones regulares para detectar intrusiones y ataques en Apache, MySQL, Bind (named).


Fail2ban monitoriza y lee los logs del servidor en busca de patrones:

  • /var/log/auth.log
  • /var/log/secure

Instalación

CentOS/Red Hat (hay que usar un repositorio EPEL o tipo atrpms, rpmfusion, rpmforge, para una versión actualizada)

yum install fail2ban

Debian/Ubuntu:

apt-get update && apt-get -y upgrade
apt-get install fail2ban

Instalación manual desde las fuentes (código fuente)

cd /usr/src
wget https://codeload.github.com/fail2ban/fail2ban/tar.gz/0.8.13
tar xvzf fail2ban-0.8.13.tar.gz
cd fail2ban-0.8.13
python setup.py install
cp /usr/src/fail2ban-0.8.13/files/redhat-initd /etc/init.d/fail2ban
chmod 755 /etc/init.d/fail2ban

Arrancar el servicio:

service fail2ban start

Para ver si está realmente funcionando y las jaulas:

service fail2ban status
Fail2ban (pid 21740) is running…
Status
|- Number of jail:      1
`- Jail list:           proftpd-iptables

Comprobar si responde:

 fail2ban-client ping
Server replied: pong

 Fichero Configuración principal /etc/fail2ban/fail2ban.conf

[Definition]
# Option:  loglevel
# Notes.:  Set the log level output.
#          1 = ERROR
#          2 = WARN
#          3 = INFO
#          4 = DEBUG
# Values:  NUM  Default:  3
#
loglevel = 3
# Option:  logtarget
# Notes.:  Set the log target. This could be a file, SYSLOG, STDERR or STDOUT.
#          Only one log target can be specified.
#          If you change logtarget from the default value and you are
#          using logrotate — also adjust or disable rotation in the
#          corresponding configuration file
#          (e.g. /etc/logrotate.d/fail2ban on Debian systems)
# Values:  STDOUT STDERR SYSLOG file  Default:  /var/log/fail2ban.log
#
logtarget = SYSLOG
# Option: socket
# Notes.: Set the socket file. This is used to communicate with the daemon. Do
#         not remove this file when Fail2ban runs. It will not be possible to
#         communicate with the server afterwards.
# Values: FILE  Default:  /var/run/fail2ban/fail2ban.sock
#
socket = /var/run/fail2ban/fail2ban.sock
# Option: pidfile
# Notes.: Set the PID file. This is used to store the process ID of the
#         fail2ban server.
# Values: FILE  Default:  /var/run/fail2ban/fail2ban.pid
#
pidfile = /var/run/fail2ban/fail2ban.pid

Fichero Configuración “Jaulas” (Jail) /etc/fail2ban/jail.conf

[DEFAULT]
# “ignoreip” can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip = 127.0.0.1/8 192.168.0.1/24
# “bantime” is the number of seconds that a host is banned.
# 1 hora
bantime  = 3600
# 10 minutos
#bantime  = 600
# A host is banned if it has generated “maxretry” during the last “findtime”
# seconds.
findtime  = 600
# “maxretry” is the number of failures before a host get banned.
maxretry = 5
# “backend” specifies the backend used to get files modification.
# Available options are “pyinotify”, “gamin”, “polling” and “auto”.
# This option can be overridden in each jail as well.
#
# pyinotify: requires pyinotify (a file alteration monitor) to be installed.
#              If pyinotify is not installed, Fail2ban will use auto.
# gamin:     requires Gamin (a file alteration monitor) to be installed.
#              If Gamin is not installed, Fail2ban will use auto.
# polling:   uses a polling algorithm which does not require external libraries.
# auto:      will try to use the following backends, in order:
#              pyinotify, gamin, polling.
backend = auto
# “usedns” specifies if jails should trust hostnames in logs,
#   warn when DNS lookups are performed, or ignore all hostnames in logs
#
# yes:   if a hostname is encountered, a DNS lookup will be performed.
# warn:  if a hostname is encountered, a DNS lookup will be performed,
#        but it will be logged as a warning.
# no:    if a hostname is encountered, will not be used for banning,
#        but it will be logged as info.
usedns = warn

# This jail corresponds to the standard configuration in Fail2ban 0.6.
# The mail-whois action send a notification e-mail with a whois request
# in the body.
[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, dest=root, sender=fail2ban@example.com]
logpath  = /var/log/secure
maxretry = 5
[proftpd-iptables]
enabled  = true
filter   = proftpd
action   = iptables[name=ProFTPD, port=ftp, protocol=tcp]
sendmail-whois[name=ProFTPD, dest=webmaster@elhacker.net]
logpath  = /var/log/proftpd/proftpd.log
maxretry = 6

Ejemplo de lo que buscará Fail2ban en la jaula de SSH

cat /var/log/secure | grep ‘Failed password’ | sort | uniq -c

Filtros de las Jails (Jaulas, Cárcel) /etc/fail2ban/filter.d

Filtros para
  • apache-auth.conf
  • apache-badbots.conf
  • apache-common.conf
  • apache-nohome.conf
  • apache-noscript.conf
  • apache-overflows.conf
  • assp.conf
  • asterisk.conf
  • common.conf
  • courierlogin.conf
  • couriersmtp.conf
  • cyrus-imap.conf
  • dovecot.conf
  • dropbear.conf
  • exim.conf
  • gssftpd.conf
  • lighttpd-auth.conf
  • lighttpd-fastcgi.conf
  • mysqld-auth.conf
  • named-refused.conf
  • pam-generic.conf
  • php-url-fopen.conf
  • postfix.conf
  • proftpd.conf
  • pure-ftpd.conf
  • qmail.conf
  • recidive.conf
  • roundcube-auth.conf
  • sasl.conf
  • sieve.conf
  • sogo-auth.conf
  • sshd-ddos.conf
  • sshd.conf
  • vsftpd.con
  • webmin-auth.conf
  • wuftpd.conf
  • xinetd-fail.conf

Acciones a tomar /etc/fail2ban/action.d

  • bsd-ipfw.conf
  • complain.conf
  • dshield.conf
  • dummy.conf
  • hostsdeny.conf
  • ipfilter.conf
  • ipfw.conf
  • iptables-allports.conf
  • iptables-blocktype.conf
  • iptables-ipset-proto4.conf
  • iptables-ipset-proto6.conf
  • iptables-multiport-log.conf
  • iptables-multiport.conf
  • iptables-new.conf
  • iptables-xt_recent-echo.conf
  • iptables.conf
  • mail-buffered.conf
  • mail-whois-lines.conf
  • mail-whois.conf
  • mail.conf
  • mynetwatchman.conf
  • pf.conf
  • route.conf
  • sendmail-buffered.conf
  • sendmail-whois-lines.conf
  • sendmail-whois.conf
  • sendmail.conf
  • shorewall.conf

Reportes syslog

May 28 12:09:34 ns2 fail2ban.jail : INFO Jail ‘proftpd-iptables’ stopped
May 28 12:09:35 ns2 fail2ban.server : INFO Exiting Fail2ban
May 28 12:09:36 ns2 fail2ban.server : INFO Changed logging target to SYSLOG for Fail2ban v0.8.10
May 28 12:09:36 ns2 fail2ban.jail : INFO Creating new jail ‘proftpd-iptables’
May 28 12:09:36 ns2 fail2ban.jail : INFO Jail ‘proftpd-iptables’ uses pyinotify
May 28 12:09:36 ns2 fail2ban.jail : INFO Initiated ‘pyinotify’ backend
May 28 12:09:36 ns2 fail2ban.filter : INFO Added logfile = /var/log/auth.log
May 28 12:09:36 ns2 fail2ban.filter : INFO Set maxRetry = 6
May 28 12:09:36 ns2 fail2ban.filter : INFO Set findtime = 600
May 28 12:09:36 ns2 fail2ban.actions: INFO Set banTime = 3600
May 28 12:09:36 ns2 fail2ban.jail : INFO Jail ‘proftpd-iptables’ started

Ejemplos

Reporte ip baneada:

May 28 15:56:13 ns2 fail2ban.actions: WARNING [proftpd-iptables] Ban 195.70.62.71
May 28 16:56:14 ns2 fail2ban.actions: WARNING [proftpd-iptables] Unban 195.70.62.71


Ver Regla en iptables (action iptables)

iptables -L

o mejor:

service iptables status

Resultado:

fail2ban-ProFTPD tcp — 0.0.0.0/0 0.0.0.0/0 tcp dpt:21

Chain fail2ban-ProFTPD (1 references)
num target prot opt source destination
1 RETURN all — 0.0.0.0/0 0.0.0.0/0

Ip baneada:

Chain fail2ban-ProFTPD (1 references)
num  target     prot opt source               destination
1    REJECT     all  --  195.70.62.71        0.0.0.0/0           reject-with icmp-port-unreachable

Para borrar la última ip baneada:

# iptables -D fail2ban-ProFTPD 1

Para ver el estado:

fail2ban-client status proftpd-iptables
Status for the jail: proftpd-iptables
|- filter
|  |- File list:        /var/log/secure
|  |- Currently failed: 0
|  `- Total failed:     384
`- action
|- Currently banned: 2
|  `- IP list:       85.25.72.71 175.44.5.140
`- Total banned:     33



Si aparecen errores con iptables en el log:

fail2ban.actions.action: ERROR iptables -N fail2ban-SSH#012iptables -A fail2ban-SSH -j RETURN#012iptables -I INPUT -p tcp –dport ssh -j fail2ban-SSH returned 300

Es debido a los permisos aplicados por SELinux

restorecon -R -v /sbin/



Reporte por e-mail (acción sendmail-whois.conf)

 Hi,

The IP 195.70.62.71 has just been banned by Fail2Ban after
6 attempts against ProFTPD.

Here are more information about 195.70.62.71:

[Querying whois.ripe.net]
[whois.ripe.net]
% This is the RIPE Database query service.
% The objects are in RPSL format.
%
% The RIPE Database is subject to Terms and Conditions.
% See http://www.ripe.net/db/support/db-terms-conditions.pdf

% Note: this output has been filtered.
%       To receive output for a database update, use the “-B” flag.

% Information related to ‘195.70.62.0 – 195.70.62.255’

% Abuse contact for ‘195.70.62.0 – 195.70.62.255’ is ‘net-admin@datanet.hu

inetnum:        195.70.62.0 – 195.70.62.255
netname:        INTERWARE
descr:          InterWare Inc.
descr:          IPs for Server Hosting
country:        HU
admin-c:        IWNA1-RIPE
tech-c:         IWNA1-RIPE
remarks:        rev-srv:        ns1.interware.hu
remarks:        rev-srv:        ns2.interware.hu
status:         ASSIGNED PA
mnt-by:         AS8358-MNT
source:         RIPE # Filtered
remarks:        rev-srv attribute deprecated by RIPE NCC on 02/09/2009

role:           InterWare Network Administration
address:        InterWare Inc.
address:        Victor Hugo u. 18-22.
address:        H-1132 Budapest
address:        Hungary
phone:          +36 1 4525300
fax-no:         +36 1 4525301
admin-c:        ZR1-RIPE
admin-c:        AN845-RIPE
tech-c:         MK1117-RIPE
tech-c:         AN845-RIPE
tech-c:         ZR1-RIPE
nic-hdl:        IWNA1-RIPE
mnt-by:         AS8358-MNT
org:            ORG-IL7-RIPE
remarks:        ——————————

—————
remarks:        Please send all abuse and spam complaints to:
remarks:        noc@interware.hu
remarks:        abuse@interware.hu
remarks:        ———————————————
source:         RIPE # Filtered

% Information related to ‘195.70.32.0/19AS5588

route:          195.70.32.0/19
descr:          GTS Hungary Ltd.
descr:          HU
origin:         AS5588
mnt-by:         AS8358-MNT
source:         RIPE # Filtered

% Information related to ‘195.70.32.0/19AS8358

route:          195.70.32.0/19
descr:          InterWare Inc.
descr:          HU
origin:         AS8358
mnt-by:         AS8358-MNT
source:         RIPE # Filtered

% This query was served by the RIPE Database Query Service version 1.73.1 (DBC-WHOIS3)

Regards,

Fail2Ban

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s