Tuesday, June 7, 2011

Installing and configuring fail2ban

If you're running a server that's exposed to the internet you will sooner or later realize while checking the server security logs that you're constantly being attacked, it can be via multiple ftp,ssh,http break-in attempts (brute force attacks),(D)DoS attacks and many other nasty stuff, what's for sure - this is not something that can be neglected.

A great solution for such scenario is an open source, Python-based application called "Fail2ban".

Fail2ban is capable of working with multiple log filesand multiple services.
The flexibility and integration with iptables is a major benefit of fail2ban - so the IP filtering is performed at the kernel-level.

Instalaltion pre-requirements:
1)python
2)logrotate
3)iptables

Basically ,all of these should already be installed on your system (default install).

Installation process (I used a CentOS box for this example):

1)Install the application using Yum
#yum install fail2ban -y

2)Edit fail2ban configuration file called "jail.conf"
#vi /etc/fail2ban/jail.conf

3)Under the[DEFAULT] section we can find global configuration such as - friendly hosts, ban time, search time etc, lets adjust these parameters to meet our needs.

Here we will allow localhost, host1@friendly.com and 192.168.1.0/24 subnet  to be ignored by fail2ban:

ignoreip = 127.0.0.1, host1@friendly.com, 192.168.1.0/24

If the host is violating the rules it will be banned to this amount of time (in seconds):

bantime  = 1209600

A host is banned if it has generated "maxretry" during the last "findtime"

findtime  = 1800

The number of failures before a host get banned.
maxretry = 3


4)Let's say we want  to enable fail2ban scan on ssh log-in attempts.
Scroll to section "[ssh-iptables]" and enable it:

enabled = true

Next,change the the SSH logfile we want to scan:

logfile = /var/log/secure

Adjust the max failures the system will allow:

maxretry = 3

Comment out the "sendmail-whois" section and change it to your mail, so you will receive mail alerts when fail2ban has banned some IP.

sendmail-whois[name=SSH, dest=admin@somedomain.org, sender=fail2ban]

5) That's it, save the file and restart fail2ban and iptables.
#/etc/init.d/iptables restart 
#/etc/init.d/fail2ban restart
 
#chkconfig iptables on
#chkconfig failban on

Don't forget to check that email works, and you are done.