Monday, May 25, 2015

Securing SSH logins using fail2ban

fail2ban utility helps with mitigation of brute force attacks on SSH logins by automatically blacklisting the ip address in the iptables rules based on filter conditions. In order to install fail2ban on your Amazon linux instances, you can follow the steps below

1. Install fail2ban through package manager

************
$sudo yum install -y fail2ban
************

2. configure fail2ban configuration

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

$sudo vi /etc/fail2ban/jail.local
...
# The DEFAULT allows a global definition of the options. They can be overridden
# in each jail afterwards.

[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 198.172.1.10/32

# "bantime" is the number of seconds that a host is banned.
bantime  = 1800
....
[ssh-iptables]

enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
           sendmail-whois[name=SSH, dest=user@mycompany.com, sender=fail2ban@example.com]
logpath  = /var/log/secure
maxretry = 5
************

3. Configure iptables with some basic rules

************
$sudo iptables -A INPUT -i lo -j ACCEPT
$sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
$sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
$sudo iptables -A INPUT -j DROP
************

4. Start fail2ban service

************
$sudo service fail2ban start
************

5. Inspect iptables rules to make sure fail2ban ipchain has been added

************
$ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-SSH
-A INPUT -p tcp -m tcp --dport 22 -j fail2ban-SSH
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -j DROP
-A fail2ban-SSH -j RETURN
************

6. You will also receive an email from sendmail like below

************
From: Fail2Ban <fail2ban@example.com>
Date: Mon, May 25, 2015 at 10:58 AM
Subject: [Fail2Ban] SSH: started
To: admin@mycompany.com


Hi,

The jail SSH has been started successfully.

Regards,

Fail2Ban
************

7. Now try to SSH into the machine from an ip address that is not part of ignoreip rule and after 3 tries, you will notice a permission denied message and the below iptable rule added

***********
-A fail2ban-ssh -s 10.98.1.12/32 -j REJECT --reject-with icmp-port-unreachable
***********

To understand in detail how fail2ban protects linux servers you can refer to the link below:-

https://www.digitalocean.com/community/tutorials/how-fail2ban-works-to-protect-services-on-a-linux-server

No comments:

Post a Comment