Fail2ban scans log files (e.g. /var/log/apache/error_log) and bans IPs that show the malicious signs — too many password failures, seeking for exploits, etc. Generally Fail2Ban is then used to update firewall rules to reject the IP addresses for a specified amount of time, although any arbitrary other action (e.g. sending an email) could also be configured. Out of the box Fail2Ban comes with filters for various services (apache, courier, ssh, etc).

Fail2Ban is able to reduce the rate of incorrect authentications attempts however it cannot eliminate the risk that weak authentication presents. Configure services to use only two factor or public/private authentication mechanisms if you really want to protect services.

Installation:

Run following command .

sudo apt-get install fail2ban

Configuration:

Create a local copy of configuration file. This local configuration file allows you to make all changes that you want to enable.

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Open new fail2ban configuration file and edit below given sections into it.

vim /etc/fail2ban/jail.local

Configure the Default Section in Jail.Local

 [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

# "bantime" is the number of seconds that a host is banned.
bantime  = 600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime = 600
maxretry = 3 

Configure the SSH Section in Jail.Local

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

enabled : It indicates that SSH protection is enabled/disabled.
port : define the port on which ssh is working; default SSH works on port no. 22.
logpath : define the log path of the SSH login attempts.
maxretry : defines maximum number of wrong login attempt after which the mentioned IP/s will be blocked for the given bantime.

Configure the FTP Section in Jail.Local

[vsftpd]
 enabled = true
 port = ftp,ftp-data,ftps,ftps-data
 filter = vsftpd
 logpath = /var/log/vsftpd.log
 maxretry = 5

Restart fail2ban service after all changes :-

sudo service fail2ban restart

You can check the rules that fail2ban is appliyng to block IPs in IP table.

sudo iptables -L

You can check the logs of the fail2ban in /var/log/fail2ban.log file. It contains the all information of blocked IPs too.

For more details visit here