Categories
IPTables

Fail2Ban Howto: Block IP Address Using Fail2ban and IPTables


Fail2ban scans log files for various services ( SSH, FTP, SMTP, Apache, etc., ) and bans the IP that makes too many password failures. It also updates the firewall rules to reject these ip addresses.

Fail2ban is an intrusion prevention framework written in the Python programming language.

Main purpose of Fail2ban is to prevent brute force login attacks.

Also, refer to our earlier article on Tripwire (Linux host based intrusion detection system).

Install Fail2ban

To install fail2ban from source, download it from sourceforge..

Use apt-get to install Fail2ban on a Debian based system as shown below.

# apt-get install fail2ban

You can also install Fail2ban manually by downloading the fail2ban deb package.

# dpkg -i fail2ban_0.8.1-1_all.deb

How to configure fail2ban

All Fail2ban configuration files are located under the /etc/fail2ban directory.

/etc/fail2ban/fail2ban.conf

Main purpose of this file is to configure fail2ban log related directives.

Actions taken by the Fail2ban are logged in the /var/log/fail2ban.log file. You can change the verbosity in the conf file to one of: 1 – ERROR, 2 – WARN, 3 – INFO or 4 – DEBUG.

/etc/fail2ban/jail.conf

jail.conf file contains the declaration of the service configurations. This configuration file is broken up into different contexts. The DEFAULT settings apply to all sections.

The following DEFAULT section of jail.conf says that after five failed access attempts from a single IP address within 600 seconds or 10 minutes (findtime), that address will be automatically blocked for 600 seconds (bantime).

[DEFAULT]
ignoreip = 127.0.0.1
maxretry = 5
findtime = 600
bantime = 600

Service Configurations

By default, some services are inserted as templates. Following is an example of the ssh services section.

[ssh]
enabled = true
port	= ssh
filter	= sshd
logpath  = /var/log/auth.log
action = iptables

Fail2ban will monitor the /var/log/auth.log file for failed access attempts, and if it finds repeated failed ssh login attempts from the same IP address or host, fail2ban stops further login attempts from that IP address/host by blocking it with fail2ban iptables firewall rule.

Fail2ban Filters

The directory /etc/fail2ban/filter.d contains regular expressions that are used to detect break-in attempts, password failures, etc., for various services.

For example:

We can also add our own regular expression to find unwanted action.

Fail2ban Actions

The directory /etc/fail2ban/action.d contains different scripts defining actions which will execute once a filter matches. Only one filter is allowed per service, but it is possible to specify several actions, on separate lines.

For example:

Start/Stop Fail2ban Service

After making configuration changes stop and start the Fail2ban daemon as shown below.

# /etc/init.d/fail2ban stop

# /etc/init.d/fail2ban start


Source