Fail2Ban Brute force Protection on Nextcloud
Installation and Setup of Fail2ban Brute force protection on Nextcloud, SSH, FTP etc on Ubuntu or other debian based distributions.

This Article will help you understand how to setup Fail2ban Brute force protection on Nextcloud.

If you’re running an Internet facing server, you probably know its exposed services are constantly being probed and attacks are being attempted against it. Fortunately, an extremely useful, nice and nifty tool is here to help: Fail2Ban.


Nextcloud up and running on ubuntu 22.04 using LAMP stack.

Nextcloud Logo

Running NextCloud or OwnCloud online comes with some risk, as with any online service. It’s important that your installation remains secure against hackers (or at least as secure as it can be). I’ve opted to implement fail2ban in order to help secure it using some custom rules. It’s worth noting that NextCloud does block unwanted login attempts itself through the application, but you’re having to trust application level security. I feel far safer having fail2ban implement firewall rules to prevent access to anyone probing the server.

Fail2ban works IP-based and will block the IPs from which too many failed login attempts are made, however other IPs / users on the same network will not be slowed down (as with Nextcloud brute force protection).

Fail2ban secures nextcloud and helps secure others programs such as sshd etc as well.
A general note about Fail2ban: The program has two types of configuration files: * .conf and * .local. If you want to make changes to the configuration, you should never edit the conf files directly, as they can be overwritten at any time during an update by Fail2ban. Better is here, a file with the same name, but the file extension .local to apply.

The local files works on top of the conf files, and overwrites the default settings. Conf files get updated with fail2ban release updates, however the individual customizations in the local files are not affected with the update. As a result, your Fail2ban installation cannot be “broken” by an update.

Installation and Setup of Fail2Ban on Nextcloud

Disable Nextcloud Brute force protection by modifying the following file

sudo vi /var/www/html/nextcloud/config/config.php

Put a false against the following line

'' => 'false',

Also update the timezone with your correct timezone

'logtimezone' => 'Asia/Kolkata',

Install Fail2ban for Nextcloud

sudo apt-get update
sudo apt-get install fail2ban

Now create a special filter for fail2ban on Nextcloud

sudo vi /etc/fail2ban/filter.d/nextcloud.local

and add following content

failregex=^{"reqId":".*","remoteAddr":".*","app":"core","message":"Login failed: '.*' \(Remote IP: '<HOST>'\)","level":2,"time":".*"}$
          ^{"reqId":".*","level":2,"time":".*","remoteAddr":".*","user":".*","app":".*","method":".*","url":".*","message":"Login failed: '.*' \(Remote IP: '<HOST>'\)".*}$
          ^{"reqId":".*","level":2,"time":".*","remoteAddr":".*","user":".*","app":".*","method":".*","url":".*","message":"Login failed: .* \(Remote IP: <HOST>\).*}$
sudo vi /etc/fail2ban/jail.local

and add the following content

bantime=-1 #1800

Maxretry filter value of 3 ensures that the corresponding IP is blocked (banned) for 1800 seconds (30 minutes), after three failed attempts, also a negative value at ban time ensures a permanent lock.

Restart Fail2ban

sudo service fail2ban restart

Fail2ban remove jams and locks on Nextcloud

Now it can sometimes happen that you shut yourself out of the cloud if you enter too many wrong login data, this lock can also be cancelled manually. to see which IPs are currently locked for Nextcloud, use the following command

sudo fail2ban-client status nextcloud

All banned IPs are listed here in the list Banned IP list, To unlock a specific IP the following command is sufficient (here with the fictional IP xyz.yzx.yzz.zyx)

sudo fail2ban-client set nextcloud unbanip xyz.yzx.yzz.zyx

To lock / ban a specific IP the following command is sufficient (here with the fictional IP xyz.yzx.yzz.zyx)

sudo fail2ban-client set nextcloud banip xyz.yzx.yzz.zyx

Email Dispatch by Fail2Ban

Fail2ban works in the background, so now if an IP and/or group of IPs are banned, then administrator will never know, unless they keep a watch on the corresponding logs at frequent intervals.
So a meaningful extension is therefore the sending an e-mail, if Fail2ban became active and blocked an IP or a group of IPs. In order to send mails using Linux, sSMTP utility can be used, the installation and setup of this program is explained below

Send / Configure email through Terminal

install the ssmtp and mailutils packages

sudo apt-get install ssmtp mailutils

ssmtp is a lightweight smtp server used to send emails, and mailutils package is the set of libraries used for handling emails.

edit the ssmtp’s configuration file

sudo vi /etc/ssmtp/ssmtp.conf

and set

and add the following 4 lines to the file as follows

AuthUser=User[email protected]

First two lines corresponds to the smtp server authentication and the bottom two lines are responsible for encryption.
Save and exit the file. Now we are all set to send our first email through terminal

echo “Hello Inbox” | mail -s “Test” [email protected]

If sSMTP has been configured, sending mails via Fail2ban will be surprisingly easy as e-mail delivery is already planned. For this a small adjustment to the file /etc/fail2ban/jail.local is enough . At the beginning of the file, the add the following lines

# Destination email address used solely for the interpolations in
# jail.{conf,local,d/*} configuration files.
destemail = [email protected]
# Sender email address used solely for some actions
sender = [email protected]
# E-mail action. Since 0.8.1 Fail2Ban uses sendmail MTA for the
# mailing. Change mta configuration parameter to mail if you want to
# revert to conventional 'mail'.
mta = mail
action = %(action_mwl)s

destemail is the mail address to which notifications are to be sent and sender the address from which the email is to be sent. Especially important is the line action =% (action_mwl) s : This will send emails by default.

Configure Email for Fail2ban

Now you automatically receive an e-mail for all actions that Fail2ban makes. The only thing that may be a little unattractive: Even if a “Jail” stopped or loaded, an e-mail will be sent. Just restart Fail2ban ( service fail2ban restart ) and be surprised about the “mail flood”. To really only receive emails when an IP has been banned, adjustments to a few files are still needed. The affected conf files in the directory /etc/fail2ban/action.d are supplemented by corresponding local files


In plain text, the above-mentioned files are newly created and filled with the following content

# Option:  actionstart
# Notes.:  command executed once at the start of Fail2Ban.
# Values:  CMD
actionstart =
# Option:  actionstop
# Notes.:  command executed once at the end of Fail2Ban
# Values:  CMD
actionstop =

After a restart of Fail2ban, now only emails are sent, if an IP was banned by Nextcloud.

That’s it your Nextcloud setup is protected by fail2ban.

Configure Fail2Ban for permanent and persistent bans

Fail2Ban scans service’s log files for patterns defined as regular expressions and, if an offending pattern is found a certain number of times within a given timeframe, the corresponding source IP is banned (ie: blocked) for a configurable time, using local firewall rules such as iptables.

I’m very touchy when it comes to my server security so I’m using Fail2Ban to perform permanent bans of involved source IPs and I’m going to show you how. The problem however is that those bans do not persist across a Fail2ban server restart or a server reboot.

In this article I will show you how to add two simple lines in Fail2Ban configuration file in order to add persistency across restart.

In a typical installation, Fail2ban configuration files are stored in the /etc/fail2ban/ directory. There’s only two files that needs slight modifications:

  • jail.conf : it’s the main file defining default options and behavior for so called jails, that is for each service monitored, the definition of log file, detection patterns (filters), actions, timers (findtime, max retry, bantime).
  • action.d/iptables-multiport.conf : iptables-multiport is the default action performed by Fail2Ban when an IP is to be banned (or jailed), as defined in the jail.conf configuration file. If you’ve changed the default action, then you’ll have to modify the corresponding action file accordingly.

Configure persistent bans on fail2ban

In order for bans to persist across a service restart, they obviously have to be saved somewhere. No fancy database required, a simple text file will do the trick.

The principle is simple: every time Fail2Ban sets a new ban on an IP, we’ll save the information « jail name and IP address » in a file along the way. Next, upon each Fail2Ban service start, we’ll load this file a re-create the corresponding bans. All it takes is two lines in the right configuration file.

Each ban action is defined in a corresponding configuration file. Within this file, there’s two parameters we’re interested in:

  1. actionstart : here we can define a list of commands that will be executed only once at the start of Fail2Ban. So we’ll add a custom command loading the file /etc/fail2ban/persistent.bans and re-create the corresponding iptables entries.
  2. actionban : here we can defined a list of commands that will be executed when banning an IP. So we’ll add a custom command to save the useful information to the file /etc/fail2ban/persistent.bans.

The default action in Fail2Ban is iptables-multiport (as defined in the file jail.conf), so we have to edit the action.d/iptables-multiport.conf file and add the following highlighted lines:

# Option:  actionstart
# Notes.:  command executed once at the start of Fail2Ban.
# Values:  CMD
actionstart = iptables -N f2b-<name>
              iptables -A f2b-<name> -j RETURN
              iptables -I <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>
          cat /etc/fail2ban/persistent.bans | awk '/^f2b-<name>/ {print $2}' \
          | while read IP; do iptables -I f2b-<name> 1 -s $IP -j <blocktype>; done

# Option:  actionstop
# Notes.:  command executed once at the end of Fail2Ban
# Values:  CMD
actionstop = iptables -D <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>
             iptables -F f2b-<name>
             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 <ip> -j <blocktype>
if ! grep -Fq "f2b-<name> <ip>" /etc/fail2ban/persistent.bans; then echo "f2b-<name> <ip>" >> /etc/fail2ban/persistent.bans; fi
#        if ! grep -q "f2b-<name> `sed 's,\.,\\.,g' <<<<ip>`$" /etc/fail2ban/persistent.bans; then 
#              echo "f2b-<name> <ip>" >> /etc/fail2ban/persistent.bans; 
#            fi

Once done, it is required to restart Fail2Ban in order for those change to be applied.

sudo service fail2ban restart

And that’s it !

Similar Posts

  • All
  • apache2
  • lamp
  • mariadb
  • php
  • raspberrypi
  • ubuntu
  • wordpress
  • Plex
  • ssl
  • fail2ban
  • nextcloud

Mobeen Syed on October 3, 2022

This tutorial will guide you the procedure to Install Deluge BitTorrent Server, Client and Web Client on Ubuntu 22.04 Desktop/Server.

Mobeen Syed on October 3, 2022

Installation and Setup of Fail2ban Brute force protection on Nextcloud, SSH, FTP etc on Ubuntu or other debian based distributions.
LetsEncrypt Logo - Letsencrypt is used for SSL secure access for Nextcloud

Mobeen Syed on December 8, 2020

Enable and Configure SSL Secure access (https) for NextCloud or any domain you own using LetsEncrypt Free SSL Certificates which are renewable

One Reply to “Fail2Ban Brute force Protection on Nextcloud”

Thank you for this useful guide! – It helps a lot with my Nextcloud – I receive many host attacks in my logs.

Leave a Reply

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