Adding fail2ban on Ubuntu machine with Apache2

Install Fail2Ban

sudo apt update
sudo apt install fail2ban -y

Create Apache Jail Configuration

Create a new file jail.local

sudo nano /etc/fail2ban/jail.local

Add the following configuration to monitor excessive requests in the Apache access log:

[apache-overload]
enabled  = true
port     = http,https
filter   = apache-overload
logpath  = /var/log/apache2/access.log
findtime = 60
maxretry = 1000
bantime  = 43200 // for 12 hours ban
  • enabled: Enables this specific jail.
  • port: The ports used by Apache (HTTP, HTTPS).
  • filter: The name of the filter (you’ll create this in the next step).
  • logpath: The location of your Apache access logs.
  • findtime: The time window (in seconds) in which the number of requests (maxretry) is counted (here it’s 60 seconds).
  • maxretry: The number of requests allowed before banning the IP (1000 requests in 60 seconds in this case).
  • bantime: The duration (in seconds) the IP is banned for (43200 seconds = 12 Hours).

Create the Apache Overload Filter

Now, you need to create the filter definition for this jail. Create a new filter file for apache-overload.

sudo nano /etc/fail2ban/filter.d/apache-overload.conf

Add the following configuration, which matches all requests in the Apache access log:

[Definition]
failregex = ^<HOST> -.*"(GET|POST|HEAD).*"$
ignoreregex =
  • failregex: Matches any GET, POST, or HEAD request from any client. is replaced with the client's IP address by Fail2Ban.
  • ignoreregex: No lines are ignored in this configuration.

Restart Apache and Fail2Ban

After configuring, restart both Apache and Fail2Ban for changes sudo systemctl restart apache2 sudo systemctl restart fail2ban

Monitor Fail2Ban

To check the status of the jail:

sudo fail2ban-client status apache-overload

To see banned IPs:

sudo fail2ban-client status

To see in more details for specific item eg: sshd

sudo fail2ban-client status sshd
Written on October 23, 2024