Home // How to Secure Nextcloud: Guide to Protecting Your Data

How to Secure Nextcloud: Guide to Protecting Your Data

0 36 minutes read
| Published on: August 30, 2023 | Last updated on: September 4, 2023

Nextcloud offers a powerful platform for data synchronization and collaboration. However, to secure Nextcloud is paramount to ensure the integrity and safety of your data. In this guide, we’ll explore various strategies and tools to help you secure your Nextcloud installation.

Implementing Geoblocking to Secure Nextcloud

Geoblocking restricts access to Nextcloud based on geographic location, adding a sophisticated layer of protection to your Nextcloud instance. By limiting unauthorized access from specific regions, geoblocking enhances security in several key ways. Here’s how you can set up geoblocking at both the Nextcloud and OS levels, along with an explanation of why it’s an essential security measure:

  1. Preventing Access from High-Risk Locations: Certain regions may be known for higher levels of cybercriminal activity. By blocking access from these locations, you minimize the risk of attacks originating from those areas.
  2. Compliance with Legal and Regulatory Requirements: Some jurisdictions have specific data protection laws that require businesses to restrict access to data based on geographic locations. Geoblocking helps in adhering to these legal obligations.
  3. Protection Against Brute-Force Attacks: By limiting access to specific regions where your organization operates or where legitimate users reside, you reduce the surface area for potential brute-force attacks.
  4. Reducing Bandwidth and Resource Abuse: Unwanted traffic from regions that are not relevant to your Nextcloud instance can consume valuable bandwidth and resources. Geoblocking can minimize unnecessary consumption and improve the performance for legitimate users.
  5. Customized User Experience: Geoblocking allows for a more tailored user experience by directing users from specific regions to localized versions of Nextcloud or providing content specific to their location.
  6. Enhanced Monitoring and Analytics: Tracking access attempts from different regions can provide insights into potential threats and allow for proactive security measures. Geoblocking logs can be analyzed to detect patterns indicative of malicious activity.
  7. Integration with Other Security Measures: Geoblocking can be part of a multi-layered security strategy, working in conjunction with firewalls, two-factor authentication, and other security protocols to create a robust defense against unauthorized access.

By implementing geoblocking, you not only secure Nextcloud but also demonstrate a commitment to safeguarding user data and adhering to best practices in cybersecurity. Whether you choose to apply geoblocking at the Nextcloud level using the Geoblocker app or at the OS level using tools like GeoIP, the enhanced security measures will contribute to a more resilient and reliable Nextcloud environment.

Using the Geoblocker App

The Geoblocker app in Nextcloud provides an easy way to restrict access based on geographic locations.

Install the Geoblocker App

  1. Navigate to the Apps menu in Nextcloud.
  2. Search for “Geoblocker” and click “Download and enable.”
  3. Go to Settings > Security to configure the Geoblocker.

Configure the Geoblocker App

  1. Select the geographical regions to allow or block.
  2. Choose the blocking method, such as blocking login or all access.
  3. Configure logging to keep track of blocked attempts.
  4. Save the settings.

OS-Level Geoblocking

Implementing geoblocking at the operating system level can provide additional protection. This can be achieved using tools like geoip with iptables.

Configure Firewall with GeoIP

Here’s a step-by-step guide for setting up geoblocking using GeoIP on a Linux system:

  1. Install the GeoIP module:
   sudo apt-get install xtables-addons-common
  1. Download the GeoIP database:
   sudo /usr/lib/xtables-addons/xt_geoip_dl
  1. Build the GeoIP database:
   sudo /usr/lib/xtables-addons/xt_geoip_build /usr/share/xt_geoip
  1. Add rules to block or allow specific countries: To block access from a specific country (e.g., Russia – RU):
   sudo iptables -A INPUT -m geoip --src-cc RU -j DROP

To allow access only from specific countries (e.g., United States – US, Canada – CA):

   sudo iptables -A INPUT -m geoip ! --src-cc US,CA -j DROP
  1. Save the iptables rules to make them persistent across reboots:
   sudo iptables-save > /etc/iptables/rules.v4

Two-Factor Authentication (2FA)

Two-Factor Authentication (2FA) adds an indispensable layer of security to Nextcloud by requiring two separate forms of identification for user authentication. This multi-step verification process ensures that even if a password is compromised, an attacker would still need access to the second form of identification, such as a mobile device or a hardware token, to gain entry. Here’s why implementing 2FA is a crucial security measure for Nextcloud:

  1. Protection Against Password Breaches: In an age where password breaches are common, relying solely on passwords can leave your Nextcloud instance vulnerable. 2FA adds an additional barrier, making unauthorized access more challenging.
  2. Mitigation of Phishing Attacks: Even if a user’s credentials are stolen through phishing, the attacker would need physical access to the second authentication factor (e.g., a mobile phone), rendering the stolen credentials useless by themselves.
  3. Enhanced User Accountability: With 2FA, you can ensure that only authorized individuals have access to specific resources, enhancing the accountability of users within your organization.

Enable 2FA in Nextcloud

Here’s how to set up 2FA in Nextcloud, focusing on TOTP (Time-based One-Time Password) but also mentioning other supported 2FA methods.

Navigate to Security Settings

  1. Log in as an administrator to your Nextcloud instance.
  2. Go to Settings > Security.

Enable TOTP

  1. Find the “Two-Factor TOTP Provider” section.
  2. Click “Enable.”

TOTP works with various authenticator apps, such as Google Authenticator or Authy, on smartphones.

Other Supported 2FA Methods

Nextcloud also supports other 2FA methods like U2F (Universal 2nd Factor) and SMS. These can be enabled similarly to TOTP and require corresponding hardware or services.

Suspicious Login Detection

This feature uses machine learning to detect and warn about suspicious login attempts.

Setting Up Suspicious Login Detection

  • Install the Suspicious Login app from the Nextcloud app store.
  • Configure the app to set up notification methods and sensitivity.

Implementing Strong Password Policies

Password policies enforce strong passwords, reducing the risk of brute-force attacks.

Read about managing users and passwords on Ubuntu

Configure Password Policies in Nextcloud

  • Go to Security settings in Nextcloud admin.
  • Set password length, complexity, and expiration rules.

OS-Level Password Policies

  • Configure PAM (Pluggable Authentication Module) to enforce strong passwords at the system level.

OS-Level Security Measures to Secure Nextcloud

Securing Nextcloud is not just about configuring the application itself; the underlying operating system must also be fortified. Here are some essential OS-level security practices.

Discover more about basic Linux commands

Regular Updates

Keeping the OS and all installed software up to date is vital to ensure that known vulnerabilities are patched.

Steps to Automate Updates on Ubuntu

  1. Install the unattended-upgrades package:
   sudo apt-get install unattended-upgrades
  1. Configure unattended-upgrades by editing /etc/apt/apt.conf.d/50unattended-upgrades.
  2. Enable automatic updates:
   sudo dpkg-reconfigure --priority=low unattended-upgrades
  1. Verify that updates are working by checking the log files in /var/log/unattended-upgrades.

Firewall Configuration

A well-configured firewall is a primary defense against unauthorized access.

Using UFW on Ubuntu
  1. Install UFW (Uncomplicated Firewall):
   sudo apt-get install ufw
  1. Allow necessary ports (e.g., 80 for HTTP, 443 for HTTPS):
   sudo ufw allow 80,443/tcp
  1. Enable UFW:
   sudo ufw enable
  1. Verify the rules:
   sudo ufw status

Secure SSH Access to Secure Nextcloud

Securing SSH (Secure Shell) access is a crucial step in minimizing the risk of unauthorized remote access to the server where Nextcloud is hosted. Here’s a comprehensive guide to enhancing SSH security.

Learn how to use SSH

Use SSH Keys

Using SSH keys instead of passwords adds an extra layer of security.

Generate an SSH Key Pair
  1. Open a terminal on your local machine.
  2. Generate an SSH key pair with the ssh-keygen command:
   ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

This will create a 4096-bit RSA key pair.

  1. Secure the private key by setting a strong passphrase when prompted.
Add the Public Key to the Server
  1. Copy the public key to the server using the ssh-copy-id command:
   ssh-copy-id user@server

Replace user@server with your username and server’s IP address or hostname.

  1. Verify the key-based authentication by SSHing into the server:
   ssh user@server

You should be prompted for the passphrase of your private key, not the user’s password.

Disable Root Login and Change SSH Port

Disabling root login and changing the default SSH port adds additional security layers.

Edit the SSH Configuration File
  1. Open the SSH configuration file on the server:
   sudo nano /etc/ssh/sshd_config
  1. Disable root login by finding the line with PermitRootLogin and setting it to no:
   PermitRootLogin no

If the line doesn’t exist, add it.

  1. Change the SSH port by finding the line with Port and setting it to a non-default value, like 2222:
   Port 2222

If the line doesn’t exist, add it.

  1. Save the file and exit the editor.
Restart SSH to Apply Changes
  1. Restart the SSH service to apply the changes:
   sudo systemctl restart ssh
  1. Verify the new configuration by SSHing into the server with the new port:
   ssh -p 2222 user@server

Harden PHP Configuration to Secure Nextcloud

Nextcloud runs on PHP, so securing PHP is an essential part of hardening Nextcloud.

Find out how to install PHP on Ubuntu

Disable Unnecessary PHP Functions
  1. Edit the php.ini file (location depends on the PHP version).
  2. Find or add the disable_functions line:
   disable_functions = exec,passthru,shell_exec,system
  1. Restart the web server to apply the changes.
Set Appropriate Permissions
  1. Set the correct owner for Nextcloud files:
   sudo chown -R www-data:www-data /var/www/nextcloud
  1. Set secure file permissions:
   sudo find /var/www/nextcloud -type f -exec chmod 0640 {} \;
   sudo find /var/www/nextcloud -type d -exec chmod 0750 {} \;

Protecting Nextcloud from Malware

Use Nextcloud’s Antivirus App to Secure Nextcloud

Nextcloud offers an antivirus app that integrates with ClamAV, a popular open-source antivirus engine. This combination allows for continuous scanning of uploaded files and periodic scans of existing data.

Install and Configure ClamAV

Install ClamAV and ClamAV Daemon
  1. Update the package lists:
   sudo apt-get update
  1. Install ClamAV and ClamAV Daemon:
   sudo apt-get install clamav clamav-daemon
Update ClamAV’s Signatures
  1. Update the virus database to ensure that ClamAV can detect the latest threats:
   sudo freshclam
  1. Enable automatic updates by editing /etc/clamav/freshclam.conf and setting:
   Checks 24

This will update the virus signatures 24 times a day.

Install the Antivirus App for Files in Nextcloud

  1. Log in to Nextcloud as an administrator.
  2. Go to the Apps menu.
  3. Search for “Antivirus for files” in the search bar.
  4. Click “Download and enable” to install the app.

Configure the Antivirus App to Use ClamAV

  1. Go to Settings > Security in Nextcloud.
  2. Find the “Antivirus Configuration” section.
  3. Select “Daemon (Socket)” as the mode to connect to ClamAV.
  4. Set the hostname and port (usually localhost and 3310).
  5. Choose the desired action for infected files, such as “Only log” or “Delete file.”
  6. Save the settings.

Regularly Scan for Malware

  1. Open a terminal on the server.
  2. Run a recursive scan on Nextcloud’s data directory:
   sudo clamscan -r /path/to/nextcloud/data

Replace /path/to/nextcloud/data with the actual path to Nextcloud’s data directory.

  1. Consider setting up a cron job to automate regular scans. For example, to run a scan every day at 3:00 AM:
   0 3 * * * sudo clamscan -r /path/to/nextcloud/data >/dev/null 2>&1

Edit the cron table with sudo crontab -e and add the above line.

Protecting the System from Malware

Use Intrusion Detection Systems (IDS) to Enhance Security

Intrusion Detection Systems (IDS) play a vital role in securing Nextcloud installations and Linux servers by monitoring and analyzing network traffic for suspicious activities. Implementing IDS solutions like Fail2Ban, Snort, and Suricata can provide robust protection against various threats, including brute-force attacks, malware, and unauthorized access attempts. Here’s an overview of these tools:


Fail2Ban is an intrusion prevention software that protects Linux servers from brute-force and dictionary attacks. It operates by:

  1. Monitoring Logs: Fail2Ban scans system logs for patterns indicating failed login attempts or suspicious behavior.
  2. Banning Offenders: Upon detecting repeated failures from an IP address, Fail2Ban temporarily bans the address, preventing further access.
  3. Customizable Rules: Administrators can configure custom rules, defining the number of failed attempts allowed and the duration of the ban.
  4. Integration with Firewalls: It works seamlessly with iptables and other firewall management tools, enabling swift response to threats.
Install Fail2Ban
  1. Update the package lists:
   sudo apt-get update
  1. Install Fail2Ban:
   sudo apt-get install fail2ban
Configure Fail2Ban for Nextcloud
  1. Create a custom filter for Nextcloud by creating a file /etc/fail2ban/filter.d/nextcloud.conf with the following content:
   failregex={"reqId":".*","remoteAddr":"<HOST>","app":"core","message":"Login failed: '.*' \(Remote IP: '<HOST>'\)"
   ignoreregex =
  1. Create a jail configuration for Nextcloud by editing /etc/fail2ban/jail.local and adding:
   enabled  = true
   filter   = nextcloud
   port     = 80,443
   logpath  = /path/to/nextcloud/data/nextcloud.log
   maxretry = 3
   bantime  = 3600

Adjust the logpath to the actual path of your Nextcloud log file.

  1. Restart Fail2Ban to apply the changes:
   sudo systemctl restart fail2ban

Learn about additional security with Fail2Ban or learn more about Fail2Ban


Snort is a well-known open-source network intrusion detection system (NIDS) that offers real-time traffic analysis and packet logging. Key features include:

  1. Signature-Based Detection: Snort uses predefined signatures to identify known threats in network traffic.
  2. Anomaly Detection: It can also detect unusual patterns or behavior that may signify an attack, even if the signature is unknown.
  3. Extensible: Snort’s community and commercial support provide a rich set of plugins, rules, and configurations to tailor its behavior.
  4. Scalable: Suitable for various environments, from small businesses to large enterprises, providing consistent protection.


Suricata is another open-source network IDS, Intrusion Prevention System (IPS), and Network Security Monitoring engine. Its features are:

  1. Multi-Threading: Suricata is designed to utilize multi-core CPUs efficiently, offering high performance.
  2. Protocol Analysis: It provides deep inspection of many protocols, including HTTP, TLS, and DNS, allowing for detailed analysis.
  3. Flexible Rule System: Suricata’s powerful and adaptable rule system enables custom detection logic, adapting to specific threats and environments.
  4. Integration with Threat Intelligence: Suricata can integrate with various threat intelligence feeds, enhancing its ability to detect emerging threats.

Use Linux Malware Detect (LMD)

Linux Malware Detect (LMD) is a malware scanner specifically designed to detect and remove malware on Linux systems.

Download and Install LMD

  1. Download LMD:
   wget http://www.rfxn.com/downloads/maldetect-current.tar.gz
  1. Extract the archive:
   tar -xvf maldetect-current.tar.gz
  1. Navigate to the extracted directory:
   cd maldetect-*
  1. Install LMD:
   sudo ./install.sh

Configure LMD

  1. Edit the configuration file /usr/local/maldetect/conf.maldet.
  2. Set the email alerts, daily update checks, and other preferences as needed.
  3. Configure the scan options, such as scan depth and file types.

Run a Scan

  1. Run a manual scan on a specific directory:
   sudo maldet -a /path/to/scan

Set Up Daily Scans with Cron

  1. Edit the cron file for LMD:
   sudo crontab -e
  1. Add a daily scan job, for example:
   0 2 * * * /usr/local/sbin/maldet -a /path/to/scan >/dev/null 2>&1

This will run a scan every day at 2:00 AM.


Securing Nextcloud requires a multifaceted approach, encompassing both application-level and OS-level measures. By implementing geoblocking, 2FA, suspicious login detection, strong password policies, and robust OS-level security practices, administrators can build a secure and resilient Nextcloud environment.

For further details on any of these topics, always refer to Nextcloud’s official documentation and consult with security professionals as needed.


Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Copyright @2022-2024 All Right Reserved – PCPlanet

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. You understand and give your consent that your IP address and browser information might be processed by the security plugins installed on this site. By clicking “Accept”, you consent to the use of ALL the cookies.
Accept Read More

Privacy & Cookies Policy