HostOnNet Blog

Blocking Layer 7 DDoS with CloudFlare Firewall using Fail2ban

Looking for Linux Server Admin or WordPress Expert? We can help.


Fail2Ban can be configured to work with CloudFlare Firewall to block Layer 7 DDos (DoS) attacks.

On Ubuntu install fail2ban with command

apt-get install fail2ban

Now you can edit and remove most of the [SECTION] from /etc/fail2ban/jail.conf if you are not using them.

Instead of adding your rule to jails.conf (this get overwritten when you upgrade fail2ban), create a file /etc/fail2ban/jail.local

enabled  = true
filter   = http-dos
action   = cloudflare
logpath = /var/log/apache2/access.log
maxretry = 200
findtime = 300
bantime  = 604800

Now create file /etc/fail2ban/filter.d/http-dos.conf


# Option:  failregex
# Notes.:  regex to match the password failure messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT
failregex = ^<HOST> -.*"(GET|POST).*

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
ignoreregex =

Lets download CloudFlare action file provided by Fail2ban and put it in /etc/fail2ban/action.d folder.

cd /etc/fail2ban/action.d

You need to edit the file. Change values for

cftoken = 
cfuser = 

Now restart Fail2ban

service fail2ban restart

if any visitor make maxretry connections in findtime seconds, they get banned for bantime seconds.

You can verify the filter by running

fail2ban-regex /var/log/apache2/access.log /etc/fail2ban/filter.d/http-dos.conf

To verify CloudFlare blocking works, run Apache benchmark tool (ab) on your web site

ab -kc 20 -t 60

If everything works, the IP get blocked in CloudFlare firewall.

You can see IPs blocked in Fail2Ban log file at

tail -f /var/log/fail2ban.log

See fail2ban-client

Posted in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.