Skip to content

This document is a WORK IN PROGRESS.
This is just a quick personal cheat sheet: treat its contents with caution!


Fail2ban

Fail2ban scans log files (e.g. /var/log/httpd/error_log) and bans IPs that show the malicious signs like 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 other arbitrary action (e.g. sending an email) could also be configured.

Reference(s)

Table of contents


Install

# emerge -a fail2ban
# pacman -S fail2ban
# apt install fail2ban
# yum install fail2ban
# dnf install fail2ban

For most jail.conf configurations, it is recommended to install either pyinotify or gamin (in order of preference) to control how log file modifications are detected.


Config

Due to the possibility of the /etc/fail2ban/jail.conf file being overwritten or improved during a distribution update, it is recommended to create /etc/fail2ban/jail.local file. E.g.:

# vi /etc/fail2ban/jail.local

    > [DEFAULT]
    >
    > ignoreself = true
    > ignoreip = 127.0.0.1/8
    >
    > bantime = 7d
    > findtime = 1d
    > maxretry = 3
(See /etc/fail2ban/jail.conf for all possible options)

Now to configure a specific service like sshd:

# vi /etc/fail2ban/jail.d/sshd.local
    > [sshd]
    > enabled = true
    > logpath = /var/log/messages
    > bantime = 1y

Add the fail2ban service to the default start level:

# rc-update add fail2ban default


Use

  • Start fail2ban service:

    # rc-service fail2ban start
    

  • Print the running jails:

    # fail2ban-client status
    
        Status
        |- Number of jail:    1
        `- Jail list:         sshd
    

  • Obtain specific information about each jail, such as the list of currently banned addresses, executed filters, etc:

    # fail2ban-client status sshd
    
    Status for the jail: sshd
    |- filter
    |  |- File list:    /var/log/auth.log
    |  |- Currently failed: 1
    |  `- Total failed: 12
    `- action
       |- Currently banned: 1
       |  `- IP list:   192.168.100.50
       `- Total banned: 2
    

  • Unban an IP (e.g. 42.41.40.118) from a jail:

    sudo fail2ban-client set jail-name unbanip 42.41.40.118
    

Troubleshooting

When you think the filters are not working properly, you can use fail2ban-regex to try them out. You pass it the log file to check and the filter to run, and it will give back what it found:

# fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf


If this cheat sheet has been useful to you, then please consider leaving a star here.