Introduction

Fail2ban est un service de sécurité qui permet de modifier les règles de pare-feu de manière dynamique en fonction des erreurs de connexion relevées dans les fichiers de log.

Information Caractéristiques
Site web origine http://www.fail2ban.org
Version installée 0.8.6
Code Python
Paquet fail2ban

Pré-requis

  • Pour la réinstallation de fail2ban, il est nécessaire d'avoir réinstallé le système.
  • fail2ban est destiné à être installé sur une distribution Debian Wheezy de base.

Installation du logiciel

L'installation est très simple:

# aptitude install fail2ban

Répertoires concernés

  • Les fichiers de configuration de fail2ban sont logiquement situés dans /etc/fail2ban/.
  • Le fichier de configuration globale est situé dans /etc/fail2ban/jail.local.
  • Les règles d'interception des erreurs de logs sont situées dans /etc/fail2ban/filter.d.
  • Les définitions des actions à lancer en cas de détection d'erreur sont situées dans /etc/fail2ban/action.d.

Restauration

Les éléments à restaurer sont uniquement les fichiers de configuration de fail2ban.

# obnam restore /etc/fail2ban /tmp/
# mv /tmp/fail2ban /etc/
# chown -R root:root /etc/fail2ban/

Contenu des fichiers de configuration locale

Fichier de jail

Le fichier de configuration /etc/fail2ban/jail.local est customisé. Voici son contenu (en cas de problème de restauration):

# 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 <debian@onerussian.com>
#
# $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 = 127.0.0.1/8
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

# 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"]

# Action pour envoyer des SMS en plus du mail
action_mws = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
             %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"]
             sendsms[name=%(__name__)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
#
# 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 = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
action = %(action_mws)s

[apache-http-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/error.log
maxretry = 3
action = %(action_mw)s

[apache-noscript]
enabled = true
port = http,https
filter = apache-noscript
logpath = /var/log/apache2/error.log
maxretry = 1
action = %(action_mwl)s

[dovecot]
enabled = true
port = imap
filter = dovecot
logpath = /var/log/mail.log
maxretry = 3
action = %(action_mw)s

[exim]
enabled = true
port = smtp
filter = exim
logpath = /var/log/exim4/rejectlog
maxretry = 1
action = %(action_mwl)s

[exim-dos]
enabled  = true
port     = smtp
filter   = exim
logpath  = /var/log/exim4/mainlog
maxretry = 3
action   = %(action_mwl)s

Fichier d'action pour envoyer des SMS

Il s'agit du fichier /etc/fail2ban/action.d/sendsms.local.

# Fail2Ban configuration file
#
# Author: Médéric RIBREUX
#
# $Revision$
#

[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart =

# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop =

# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =

# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionban = printf %%b "Alerte Fail2Ban sur le service <name> : <ip> bannie...\n
                        Alerte !,\n
                        L'adresse IP <ip> a été bannie par Fail2ban après
                        <failures> tentatives d'accès à <name>.\n\n
                        --\n
                        Envoyé depuis `hostname`." | /usr/local/sbin/notify_sms.sh

# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionunban =

[Init]

# Defaut name of the chain
#
name = default

Fichiers d'action spécifiques pour envoyer des courriers électroniques

/etc/fail2ban/action.d/sendmail-whois.local:

# Fail2Ban configuration file
#
# Author: Médéric RIBREUX
#
# $Revision$
#

[Definition]

# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart =

# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop =

# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =

# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionban = printf %%b "Subject: [Fail2Ban] service <name>: <ip> bannie...
                        Date: `LC_TIME=C date -u +"%%a, %%d %%h %%Y %%T +0000"`
                        From: Fail2Ban <<sender>>
                        To: <dest>\n
                        Alerte !\n
                        L'adresse IP <ip> a été bannie par Fail2ban après
                        <failures> tentatives d'accès à <name>.\n\n
                        Quelques informations sur cet hôte:\n
                        `/usr/bin/whois <ip>`\n\n
                        A+,\n
                        Fail2Ban" | /usr/sbin/sendmail -f <sender> <dest>

# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionunban =

[Init]
# Defaut name of the chain
#
name = default

# Destination/Addressee of the mail
#
dest = root

# Sender of the mail
#
sender = root 

/etc/fail2ban/action.d/sendmail-whois-lines.local:

# Fail2Ban configuration file
#
# Author: Médéric RIBREUX
#
# $Revision$
#

[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart =

# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop =

# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =

# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionban = printf %%b "Subject: [Fail2Ban] service <name>: <ip> bannie...
                        Date: `LC_TIME=C date -u +"%%a, %%d %%h %%Y %%T +0000"`
                        From: Fail2Ban <<sender>>
                        To: <dest>\n
                        Alerte !,\n
                        L'adresse IP <ip> a été bannie par Fail2ban après
                        <failures> tentatives d'accès à <name>.\n\n
                        Lignes du log <logpath> concernées:\n
                        `/bin/grep '\<<ip>\>' <logpath>`\n\n
                        Quelques informations sur cet hôte:\n
                        `/usr/bin/whois <ip>`\n\n
                        A+,\n
                        Fail2Ban" | /usr/sbin/sendmail -f <sender> <dest>

# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionunban =

[Init]
# Defaut name of the chain
#
name = default

# Destination/Addressee of the mail
#
dest = root

# Sender of the mail
#
sender = root

Fichiers de filtre customisés

/etc/fail2ban/filter.d/apache-noscript.local:

# Fail2Ban configuration file
#
# Authors: Cyril Jacquier, Médéric Ribreux
#
# $Revision$
#

[INCLUDES]
# Read common prefixes. If any customizations available -- read them from
# common.local
before = apache-common.conf

[Definition]

# Option: failregex
# Notes.: regex to match the password failure messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
failregex = ^%(_apache_error_client)s (File does not exist|script not found or unable to stat): /\S*(\.php|\.asp|\.exe|\.pl)\s*$
            ^%(_apache_error_client)s script '/\S*(\.php|\.asp|\.exe|\.pl)\S*' not found or unable to stat\s*$
            ^%(_apache_error_client)s (File does not exist|script not found or unable to stat): /\S*([mM]y[Aa]dmin|php|cgi-|administrator|w00t|vtigercrm|tmUnblock).*$
            ^%(_apache_error_client)s client sent HTTP/1.1 request without hostname.*$

# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex = 

/etc/fail2ban/filter.d/exim.local:

# Fail2Ban configuration file
#
# Author: Médéric Ribreux
#
# $Revision$
#

[Definition]
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
# In versions >= 0.8.11 below strings defined in exim-common.conf
host_info = H=([\w.-]+ )?(\(\S+\) )?\[<HOST>\](:\d+)? (I=\[\S+\]:\d+ )?(U=\S+ )?(P=e?smtp )?
pid = ( \[\d+\])?

failregex = ^%(pid)s %(host_info)ssender verify fail for <\S+>: Unrouteable address\s*$
            ^%(pid)s \S+ F=(<>|\S+@\S+) %(host_info)srejected by local_scan\(\): .{0,256}$
            ^%(pid)s %(host_info)s.*(?:relay not permitted).*$
            ^%(pid)s %(host_info)s.*rejected (EXPN|VRFY) root.*$
            ^%(pid)s rejected EHLO from \[<HOST>\]: syntactically invalid argument\(s\): \(no argument given\).*$
            ^%(pid)s.*rejected connection from H=\[<HOST>\].*$
            ^%(pid)s Connection from \[<HOST>\] refused: too many connections.*$

# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex = 

Procédure de vérification du service

  • Pour tester les règles, il faut disposer d'un script de test. Ce dernier injecte des messages ciblés dans les journaux systèmes (les logs en langage sysadmin).
  • Voici le contenu de ce script:
TODO