Page 1 of 1

How to Protect ssh Server Using fail2ban

PostPosted: Wed Jul 03, 2013 7:55 am
by tanmay.01
One common attack on ssh service is brute force attacks where a remote attacker indefinitely attempts to log in with different passwords.

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 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, or ejecting CD-ROM tray) could also be configured. Out of the box Fail2Ban comes with filters for various services (apache, curier, ssh, etc).

To install fail2ban on Ubuntu or Debian, run the following command.
Code: Select all
sudo apt-get install fail2ban


Now you are ready to configure fail2ban ,

Code: Select all
sudo nano /etc/fail2ban/jail.local


[DEFAULT]
# a space delimited list of IP addresses, CIDR prefixes, or DNS hostnames
# to bypass fail2ban protection
ignoreip = 127.0.0.1 172.31.0.0/24 10.10.0.0/24 192.168.0.0/24

# number of seconds during which a client host is blocked
bantime = 86400

# number of failures before a client host is blocked
maxretry = 5

# number of seconds within which "maxentry" failures result in banning
findtime = 600

mta = sendmail

[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, [email protected], [email protected]]
logpath = /var/log/auth.log
# ssh-specific max-retry threshold
maxretry = 5
logpath=/var/log/secure


Once the configuration file is ready, start fail2ban service as follows.
Code: Select all
sudo service fail2ban start


To verify fail2ban is running successfully, run fail2ban-client command with “ping” argument. If fail2ban service is running okay, you should see “pong” as a response.
Code: Select all
sudo fail2ban-client ping


Server replied: pong


Show failed SSH logins by date:
Code: Select all
cat /var/log/secure | grep ‘Failed password’ |  sort | uniq -c


A log file called /var/log/messages demonstrates fail2ban in action.
Code: Select all
sudo tail /var/log/messages


You can verify the ban by checking current iptables rules.
Code: Select all
sudo iptables --list -n


If you want to unblock the IP address from fail2ban, run the following command.
$ sudo iptables -D fail2ban-SSH -s The.IP.To.Unblock -j DROP

Note that fail2ban itself is stateless. So if you restart fail2ban, all blocked IP addresses will be unblocked.