Getting fail2ban to Ban / Unban a Class C at a time

Fail2ban is great, but with the rise of AI bots and other malware I am finding that maintaining 10's of thousands of IP addresses to ban is causing slowdowns on the server. I've long wanted to be able to ban a class C when any IP address in the range matches, but I could not find out a way to do this online. Its not actually that hard to implement. Here is how I did it.

I created a new rule in action.d. The rule is closely based on the iptables.conf rule, but modifies it to replace the last octet with "0/24" and thus bans and unbans a class C instead of a single IP address. I called the rule iptablesclassc.conf with the below content:

# Fail2Ban configuration file

 

To use this ban for a ruleset (rather then the iptables rules), simply specify

banaction = iptablesclassc

For any rules in jail.local or similar where you want to use the Class C.

I have only done basic testing on this, but wanted to record this solution here.

[INCLUDES]

before = iptables-common.conf

# The below magic converts the given echo address into a /24
## $( echo $@ | sed -E 's/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}/\10\/24/g' )

[Definition]

# Option: actionstart
# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values: CMD
#
actionstart = <iptables> -N f2b-<name>
<iptables> -A f2b-<name> -j <returntype>
<iptables> -I <chain> -p <protocol> --dport <port> -j f2b-<name>

# Option: actionstop
# Notes.: command executed at the stop of jail (or at the end of Fail2Ban)
# Values: CMD
#
actionstop = <iptables> -D <chain> -p <protocol> --dport <port> -j f2b-<name>
<actionflush>
<iptables> -X f2b-<name>

# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'

# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = <iptables> -I f2b-<name> 1 -s $( echo <ip> | sed -E 's/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}/\10\/24/g' ) -j <blocktype>

# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionunban = <iptables> -D f2b-<name> -s $( echo <ip> | sed -E 's/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}/\10\/24/g' ) -j <blocktype>

[Init]

To use this ban for a ruleset (rather then the iptables rules), simply specify

banaction = iptablesclassc

For any rules in jail.local or similar where you want to use the Class C.

I have only done basic testing on this, but wanted to record this solution here.

Leave a Comment