Block malicious IPs with /24 subnet banning for Apache2 web server.
sudo apt update
sudo apt install fail2ban -y
Create a custom action that bans entire /24 subnets (256 IPs) instead of individual IPs:
sudo vim /etc/fail2ban/action.d/iptables-subnet.conf
Add the following content:
[Definition]
actionban = iptables -I INPUT -s <ip>/24 -j DROP
actionunban = iptables -D INPUT -s <ip>/24 -j DROP
Create a filter to catch spam bots hitting search endpoints:
sudo vim /etc/fail2ban/filter.d/apache-search.conf
Add the following content:
[Definition]
failregex = ^<HOST> .* "(GET|POST) /search\?.*"
ignoreregex =
Create a filter to catch any request containing "php" in the URL:
sudo vim /etc/fail2ban/filter.d/apache-php.conf
Add the following content:
[Definition]
failregex = ^<HOST> .* "(GET|POST) .*php.*"
ignoreregex =
This filter will catch:
/hello.php/wp-admin/something.php?id=1/phpMyAdmin//something/php/test.htmlCreate the jail configuration file:
sudo vim /etc/fail2ban/jail.local
Add the following content:
[apache-search]
enabled = true
port = http,https
filter = apache-search
logpath = /var/log/apache2/protonchat.access.log
backend = auto
maxretry = 1
findtime = 86400
bantime = 432000
banaction = iptables-subnet
[apache-php]
enabled = true
port = http,https
filter = apache-php
logpath = /var/log/apache2/protonchat.access.log
backend = auto
maxretry = 1
findtime = 86400
bantime = 432000
banaction = iptables-subnet
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban
# List all jails
sudo fail2ban-client status
# Check specific jail
sudo fail2ban-client status apache-search
sudo fail2ban-client status apache-php
sudo fail2ban-regex /var/log/apache2/protonchat.access.log /etc/fail2ban/filter.d/apache-search.conf
sudo fail2ban-regex /var/log/apache2/protonchat.access.log /etc/fail2ban/filter.d/apache-php.conf
sudo iptables -L INPUT -n | grep "/24"
Expected output:
DROP 0 -- 103.3.220.0/24 0.0.0.0/0
DROP 0 -- 102.89.75.0/24 0.0.0.0/0
DROP 0 -- 125.164.122.0/24 0.0.0.0/0
# View all banned IPs for a jail
sudo fail2ban-client get apache-search banned
# View jail status with ban list
sudo fail2ban-client status apache-search
# Unban a specific IP
sudo fail2ban-client set apache-search unbanip 1.2.3.4
# Unban all IPs from all jails
sudo fail2ban-client unban --all
# Watch fail2ban activity in real-time
sudo tail -f /var/log/fail2ban.log
/etc/fail2ban/jail.conf (do not edit)/etc/fail2ban/jail.local/etc/fail2ban/filter.d//etc/fail2ban/action.d//var/log/fail2ban.log