Apr 192011
 

fail2ban

As comment of the article Knockd, to secure your ports, i’ve received:

“Port knocking is bad idea; a very bad idea.

Port knocking is, in the end, a password. A sniffable one that is subject to man-in-the-middle attacks so you can’t even use one-time-passwords and be secure.

Public/private key pairs and/or one-time-passwords (opie, skey and the like) are the real solutions, along with dynamic monitoring to prevent DOS CPU resource exhaustion attacks. (OpenBSD’s PF incorporates a nice solution, as does the iptables with fail2ban/denyhosts/etc. Even swatch can work wonders.)”

Well, in my opinion knockd it’s a layer of security, perhaps thin but still can save you from some brute force script and so it adds a bit of security to your solution, in this article i’ll show you fail2ban that add another layer of security to our network services.




From wikipedia:

Fail2ban is an intrusion prevention framework written in the Python programming language. It is able to run on POSIX systems that have an interface to a packet-control system or firewall installed locally (such as, iptables or TCP Wrapper).
Fail2ban’s main function is to block selected IP addresses that may belong to hosts that are trying to breach the system’s security. It determines the hosts to be blocked by monitoring log files (e.g. /var/log/pwdfail, /var/log/auth.log, etc.) and bans any host IP that makes too many login attempts or performs any other unwanted action within a time frame defined by the administrator.

Installation

fail2ban it’s available on Debian, Ubuntu, Gentoo, Arch, Suse and Fedora so on these distro you can use the standard package manager to install it (and his dependency), i.g aptitude install fail2ban, emerge net-analyzer/fail2ban.

usage

fail2ban is composed of 2 parts: a client and a server. The server (fail2ban-server) is multi-threaded and listens on a Unix socket for commands and to give to the client information in real-time. The server itself knows nothing about the configuration files. Thus, at start-up, the server is in a “default” state in which no jails are defined.

fail2ban-client is the frontend of Fail2ban. It connects to the server socket file and sends commands in order to configure and operate the server. The client can read the configuration files or can simply be used to send a single command to the server using either the command line or the interactive mode (which is activated with the -i option).

Configuration

A typical configuration look like this:

/etc/fail2ban/
├── action.d
│   ├── dummy.conf
│   ├── hostsdeny.conf
│   ├── iptables.conf
│   ├── mail-whois.conf
│   ├── mail.conf
│   └── shorewall.conf
├── fail2ban.conf
├── fail2ban.local
├── filter.d
│   ├── apache-auth.conf
│   ├── apache-noscript.conf
│   ├── couriersmtp.conf
│   ├── postfix.conf
│   ├── proftpd.conf
│   ├── qmail.conf
│   ├── sasl.conf
│   ├── sshd.conf
│   └── vsftpd.conf
├── jail.conf
└── jail.local

Every .conf file can be overridden with a file named .local. The .conf file is read first, then .local, with later settings overriding earlier ones. Thus, a .local file doesn’t have to include everything in the corresponding .conf file, only those settings that you wish to override. Modifications should take place in the .local and not in the .conf. This avoids merging problem when upgrading.

General Configuration

The file fail2ban.conf contains general settings for the fail2ban-server daemon, such as the logging level and target. You can also specify here the socket path used for communication between the client and the server.

jails

The most important file is probably jail.conf, which contains the declaration of your jails.
The most importants parameters are:

Parameter	Description
ignoreip	List of IP to be Ignored, IP can be entered with a netmask /24 for example
bantime	        Duration (in seconds) for IP to be banned for.
findtime	The counter is set to zero if no match is found within "findtime" seconds.
maxretry	Number of matches (i.e. value of the counter) which triggers ban action on the IP.
action	        What to do when you reach maxretry, usually that ports is blocked for that IP.
port	        The service, or better the port that use the service that we want to control
filter	        Name of the filter to be used by the jail to detect matches (/etc/fail2ban/filter.d).
logpath	        Path to the log file which is provided to the filter

Examples:

[ssh]
 
enabled = true
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
maxretry = 6

This is the classic example for ssh, check the log /var/log/auth.log using the filter sshd and if it find 6 attempts of attack closes the port 22 (default action).

[apache-multiport]
 
enabled   = true
port      = http,https
filter    = apache-auth
logpath   = /var/log/apache*/*error.log
maxretry  = 6

This example for Apache is very similar, the difference are that blocks 2 ports (http and https) and check more log files.

Filters

The directory filter.d contains mainly regular expressions which are used to detect break-in attempts, password failures, etc. Here is an example for filter.d/sshd.conf with some possible regular expressions to match the lines of the logfile:

failregex = ^%(__prefix_line)s(?:error: PAM: )?Authentication failure for .* from s*$
            ^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from s*$
            ^%(__prefix_line)sFailed (?:password|publickey) for .* from (?: port d*)?(?: sshd*)?$
            ^%(__prefix_line)sROOT LOGIN REFUSED.* FROM s*$
            ^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from s*$
            ^%(__prefix_line)sUser .+ from  not allowed because not listed in AllowUsers$
            ^%(__prefix_line)sauthentication failure; logname=S* uid=S* euid=S* tty=S* ruser=S* rhost=(?:s+user=.*)?s*$
            ^%(__prefix_line)srefused connect from S+ ()s*$
            ^%(__prefix_line)sAddress  .* POSSIBLE BREAK-IN ATTEMPT!*s*$
            ^%(__prefix_line)sUser .+ from  not allowed because none of user's groups are listed in AllowGroupss*$

Start the server

Once you have configured all the filters and services that you want to check you can start the server with the command:

sudo /etc/init.d/fail2ban start

Useful commands

To see all the configuration with the warning, we use the command:

fail2ban-client -d

We can test the regular expressions of a filter:

fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

To see who has been banned:

iptables -L

References:

Examples of configurations
Fail2ban howto

From minute 7.00 for a short guide to fail2ban


Popular Posts:

Flattr this!

  10 Responses to “Fail2ban,stop brute force attacks”

  1. knockd has never been my favorite either. fail2ban has been a terrific tool. One thing to include in the individual jails that I like to include is the bantime statement. This might be useful if you wanted to ban certain intrusion attempts longer than others.

  2. “Well, in my opinion knockd it’s a layer of security, perhaps thin but still can save you from some brute force script and so it adds a bit of security to your solution”

    Nice article. And, I just had to comment about the above quote: Exactly right! Of course keeping ports closed and opening them only on demand adds security.

    Apparently there are some amateur “security experts” reading your posts who think they’re clever, but lack some basic common sense.

  3. Ciao, per mod_sec ho usato le direttive di debianizzati.org, ma mi da un problema con la action, che loro hanno impostato così:

    iptables-multiport[name=ModSec, port=”http,https”]

    – Questa sarebbe la direttiva per bloccare l’IP che attacca?
    – Di Default quale è la action?

    Appena attivo questa jail, il server non funziona più, se invece la disattivo, va tutto bene.

    – Posso levare questa action, richiamando così quella di dafult e bloccando l’ip che attacca?
    – Dove è il mio problema? Perchè IPTABLES non va?

    Mi dai una mano? Grazie

    • Ciao,

      Non ho mai usato mod_sec, ma guardando la documentazione ufficiale vedo una riga molto simile:
      http://www.fail2ban.org/wiki/index.php/HOWTO_fail2ban_with_ModSecurity2.5

      Nel jail dovresti avere:

      [modsec]
      enabled = true
      filter = modsec
      action = iptables-multiport[name=ModSec, port=”http,https”]
      # sendmail-buffered[name=ModSec, lines=5, [email protected]]
      logpath = /var/log/apache2/modsec_audit.log
      bantime = 172800
      maxretry = 1

      Che errore hai nei log quando fai partire fail2ban ?

      • ciao linuxari,
        grazie anzitutto per la risposta. Mi pare (non ricordo) che risolsi quel problema, e ora non saprei dirti gli errori sul log, quale conf usaiper mod_sec, e come sta andando…so solo che fail2ban non mi convince del tutto perchè nel logo auth continuo a vedere tentativi…

        Il punto è che sono solo…terribilmente solo…e tra l’altro ho voluto 5 server virtuali…mi diverto tantissimo, ma ovviamente è anche una faticaccia…
        tentativi ne vedo parecchi, è vero, ma credo che ancora nessuno sia riuscito ad entrare…questa sarebbe anche un’altra cosa interessante da sapere…consigli?

        • Come consiglio cerca di automatizzare il più possibile (aggiornamenti, restart dei demoni con monit, etc.) e fatti mandare email o sms se qualcosa va male, questo di solito aiuta a respirare un po.

          Sul come capire se qualcuno è entrato…ci sono i programmi che fanno verifiche per rootkit noti, in generale cerca di avere dei report dai tuoi sistemi su uso di rete/cpu/disco ed indaga se noti anomalie.

          Ciao

          • Grazie per i consigli,
            hai la mia mail, perchè non mi mandi qualche script per automatizzare, e qualche nome di qualche programma.

            Considera però che io stringo tutto all’osso, relativamente a demoni e utilizzo ram. Perchè ne ho solo 512mb, e preferisco utilizzarla tutta o quasi per apache2(in modalità prefork purtroppo).

            Grazie ancora
            Saluti

  4. Un tool alternativo di brute force protection è SSHGuard. Oltre a proteggere SSH protegge anche diversi altri demoni frequenti su UNIX per e-mail, FTP etc. E’ scritto in C anziché essere uno script intepretato, quindi è più leggero in memoria, ed è tutto italiano.

    • Ciao Michele,
      Grazie per l’informazione. Ci guardo ed a breve ci scappa un’articoletto 😉

    • Ciao Federico,
      grazie per l’informazione anche da parte mia! Purtroppo sui miei server ho già installato e configurato fail2ban, altrimenti volentierissimo avrei provato un progetto italiano, che pare sia anche più completo.

      Alcune domande:

      Pacchetto su/per Ubuntu?
      lavora accoppiato a fail2ban, o si dovrebbe poi levare l’ultimo?
      Per pulizia del sistema, sono un pò restio a cambiare completamente, perchè purtroppo io sono solo e il giorno è solo di 24 ore anche per me… però magari se tu riuscissi a convincermi magari dicendomi anche come posso tenere pulito il sistema, levando tutti i file di fali2ban. magari ci faccio un pensierino… se ti va vorrei farti alcune domande, potrei contattarti?
      Saluti

Leave a Reply to Michele Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*