Fail2Ban is an intrusion-prevention software that scans log files and takes action as directed. Hence, it may be used to scan SSH logs for invalid user attempts or authentication failures and invoke iptables to block further traffic from that IP address for a specific period. Fail2Ban uses the concept of a jail to protect a system, wherein a jail comprises a filter (intrusion detection) and an action (intrusion prevention).
Here’s a brief description of how I used fail2ban to protect a publicly accessible SFTP server (RHEL 7). All the configurations and scripts referenced below are available in my Github fail2ban repository.
- Installed fail2ban
sudo yum install fail2ban fail2ban-systemd
- Created custom filters sshd-valid.conf and sshd-invalid.conf in /etc/fail2ban/filter.d
- Created a custom action sshd-action.conf in /etc/fail2ban/action.d . Apart from this custom action, the out-of-the-box action iptables.conf shall also be used.
- Developed a script banaction.sh for the custom action
- Created custom jails sshd-valid.local and sshd-invalid.local in /etc/fail2ban/jail.d
- Developed a script secOpsReport.sh for reporting and further action on banned IPs.
The above setup classifies users as valid (accounts in /etc/passwd) and invalid and takes appropriate action based on the type of user (e.g. ban invalid users for longer duration than valid users). The banaction.sh script logs data (client IP, user, date/time) regarding the bans and will send email notifications to the admins only for valid users that are banned (to allow the admins to unban those IP addresses if required). Banning invalid users (most likely malicious login attempts) will not suffice to keep away constant offenders. Therefore, it would be useful to take action to block constant offenders permanently. So, the secOpsReport.sh script may be scheduled to run once a month and send the top banned IP addresses to the Security Operations team to analyze and implement a permanent ban (e.g. on perimeter firewalls).
Some useful fail2ban-client commands:
- Unban an IP address MYIP
sudo fail2ban-client set sshd-valid unbanip MYIP
- Unban all banned IP addresses
sudo fail2ban-client unban --all