There is little point in going through all the trouble of setting up and hosting your own private cloud if it is not properly protected.

Running your own service means that you are the sole responsible for its management and security.

Having a vulnerable setup poses the risk of your most private data being exposed which beats the whole purpose of using NextCloud to have control of your sensitive data.

NextCloudPi already offers a number of security features:

brute force protection for NextCloud login and SSH through fail2ban

automatic system security updates

signed SSL certificates by Let’s Encrypt

secure defaults, like HTTPS only and HSTS

On top of that, we are going to install and set up Apache ModSecurity.

ModSecurity is a Web Application Firewall (WAF) that it monitors all requests the web server receives. At the most basic level, it monitors for attack patterns or known possible vulnerabilities and blocks anything suspicious at the web server level.

We are talking serious protection here. It is really restrictive and ruthlessly blocks anything that potentially smells bad to the point that it is 90% going to break your website.

It is a complicated beast that takes patience to set up, as you have to audit each one of the potential vulnerabilities and allow them in the WAF, or ideally, have them fixed in the application.

I will refer you to the links for the gory details. I will just explain what changes I had to go make for NextCloud to work with ModSecurity.

Enable HTTP2 and disable old versions of HTTP

setvar:'tx.allowed_http_versions=HTTP/1.1 HTTP/2.0', \

Enable HTTP operations used by WebDav (PROPFIND)

setvar:'tx.allowed_methods=GET HEAD POST OPTIONS PROPFIND'

Enable anomaly scoring mode

This mode of operation is more flexible, as it allows all rules in the CRS to participate in the decision of denying a request. This is opposed to the traditional mode where the first rule that matches the request results in denial. In this mode rules can affect each other and the result is a more powerful decision engine. See the links below for more information.

Whitelist rules

I tested NextCloud under normal usage and whitelisted those false positives that I know are not result of a hacking attempt. I just used the most basic setup for this first release, the whitelisting process can be done in a more sophisticated way but this is fine for now.

<Directory /var/www/nextcloud/> # VIDEOS SecRuleRemoveById 958291 # Range Header Checks SecRuleRemoveById 981203 # Correlated Attack Attempt # PDF SecRuleRemoveById 950109 # Check URL encodings # ADMIN (webdav) SecRuleRemoveById 960024 # Repeatative Non-Word Chars (heuristic) SecRuleRemoveById 981173 # SQL Injection Character Anomaly Usage SecRuleRemoveById 981204 # Correlated Attack Attempt SecRuleRemoveById 981243 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981245 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981246 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981318 # String Termination/Statement Ending Injection Testing SecRuleRemoveById 973332 # XSS Filters from IE SecRuleRemoveById 973338 # XSS Filters - Category 3 SecRuleRemoveById 981143 # CSRF Protections ( TODO edit LocationMatch filter ) # COMING BACK FROM OLD SESSION SecRuleRemoveById 970903 # Microsoft Office document properties leakage # NOTES APP SecRuleRemoveById 981401 # Content-Type Response Header is Missing and X-Content-Type-Options is either missing or not set to 'nosniff' SecRuleRemoveById 200002 # Failed to parse request body # UPLOADS ( 5 MB max excluding file size ) SecRequestBodyNoFilesLimit 5242880 # GENERAL SecRuleRemoveById 960017 # Host header is a numeric IP address # REGISTERED WARNINGS, BUT DID NOT HAVE TO DISABLE THEM #SecRuleRemoveById 981220 900046 981407 #SecRuleRemoveById 981222 981405 981185 981184 </Directory>

Hide Server Signature

This is not strictly necessary for NextCloud to work with ModSecurity, but it is nice to hide your server version and operating system to potential attackers. Security through obscurity won’t take us far by itself but at least we won’t make it THAT easy to fingerprint us.

<IfModule mod_security2.c> SecServerSignature " " </IfModule>

Usage

This is highly experimental at this point. Most likely as people install different NextCloud Apps things will break, so I recommend to disable it whenever we are changing things, then enable it again with sudo nextcloudpi-config to see that everything is fine.

If anyone finds things that are broken, the place to look is

/var/log/apache2/modsec_audit.log

If people find more rules that need whitelisting, please send a PR or report them on the github issues page of the project. Log captures are normally all we need.

It is disabled by default.

Installation

Get it already made

I have included this in the latest release of my NextCloudPi, a ready to use Raspbian 8 image featuring NextCloud 11, HTTP2, PHP7 and more.

Follow the instructions provided. Once up and running, from your Raspberry Pi write

sudo nextcloudpi-config

Do it yourself

First, clone the repo

git clone https://github.com/nextcloud/nextcloudpi.git

Online installation through SSH

Use the generic software installer with the script modsecurity.sh

./installer.sh modsecurity.sh 192.168.0.130

Adjust to the IP address of your server.

This process is optimized for the Raspberry Pi, but should work in any system that certbot supports. If you are not using the default username and password for the Raspberry Pi, you can specify username and/or password in the command line.

PIUSER=nacho PIPASS=ownyourbits ./installer.sh modecurity.sh 192.168.0.130

Offline installation (Raspbian)

You can do this process offline using QEMU.

Extract the SD card and copy the image to your computer (adjust sdx).

sudo dd if=/dev/sdx of=my_rpi.img bs=4M

Then,

./installer.sh modsecurity.sh 192.168.0.130 my_rpi.img

Once done, you can copy it back (adjust sdx ).

sudo dd if=my_rpi.img if=/dev/sdx bs=4M

Code

#!/bin/bash # modsecurity WAF installation on Raspbian # Tested with 2017-03-02-raspbian-jessie-lite.img # # Copyleft 2017 by Ignacio Nunez Hernanz <nacho _a_t_ ownyourbits _d_o_t_ com> # GPL licensed (see end of file) * Use at your own risk! # # Usage: # # ./installer.sh modsecurity.sh <IP> (<img>) # # See installer.sh instructions for details # # More at ownyourbits.com # ACTIVE_=no NCDIR_=/var/www/nextcloud/ DESCRIPTION="modsecurity: Web Application Firewall for extra security (experimental)" install() { apt-get update apt-get install -y --no-install-recommends libapache2-mod-security2 modsecurity-crs # COPY RULES cd /usr/share/modsecurity-crs/base_rules/ for ruleFile in * ; do sudo ln -s /usr/share/modsecurity-crs/base_rules/$ruleFile /etc/modsecurity/$ruleFile ; done cd /usr/share/modsecurity-crs/optional_rules/ for ruleFile in * ; do sudo ln -s /usr/share/modsecurity-crs/optional_rules/$ruleFile /etc/modsecurity/$ruleFile ; done rm /etc/modsecurity/modsecurity_crs_16_session_hijacking.conf # https://github.com/SpiderLabs/owasp-modsecurity-crs/commit/e2fbef4ce89fed0c4dd338002b9a090dd2f6491d # CONFIGURE cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf sed -i 's|SecTmpDir .*|SecTmpDir /var/cache/modsecurity/|' /etc/modsecurity/modsecurity.conf sed -i 's|SecDataDir .*|SecDataDir /var/cache/modsecurity/|' /etc/modsecurity/modsecurity.conf cp /usr/share/modsecurity-crs/modsecurity_crs_10_setup.conf /etc/modsecurity/modsecurity_crs_10_setup.conf patch /etc/modsecurity/modsecurity_crs_10_setup.conf <<<'66,67c66 < SecDefaultAction "phase:1,deny,log" < SecDefaultAction "phase:2,deny,log" --- > SecDefaultAction "phase:2,pass,log" 152c151 < #SecAction \ --- > SecAction \ 278c277 < setvar:'\''tx.allowed_methods=GET HEAD POST OPTIONS'\'', \ --- > setvar:'\''tx.allowed_methods=GET HEAD POST OPTIONS PROPFIND'\'', \ 280c279 < setvar:'\''tx.allowed_http_versions=HTTP/0.9 HTTP/1.0 HTTP/1.1'\'', \ --- > setvar:'\''tx.allowed_http_versions=HTTP/1.1 HTTP/2.0'\'', \' cat >> /etc/modsecurity/modsecurity_crs_99_whitelist.conf <<EOF <Directory $NCDIR_> # VIDEOS SecRuleRemoveById 958291 # Range Header Checks SecRuleRemoveById 981203 # Correlated Attack Attempt # PDF SecRuleRemoveById 950109 # Check URL encodings # ADMIN (webdav) SecRuleRemoveById 960024 # Repeatative Non-Word Chars (heuristic) SecRuleRemoveById 981173 # SQL Injection Character Anomaly Usage SecRuleRemoveById 981204 # Correlated Attack Attempt SecRuleRemoveById 981243 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981245 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981246 # PHPIDS - Converted SQLI Filters SecRuleRemoveById 981318 # String Termination/Statement Ending Injection Testing SecRuleRemoveById 973332 # XSS Filters from IE SecRuleRemoveById 973338 # XSS Filters - Category 3 SecRuleRemoveById 981143 # CSRF Protections ( TODO edit LocationMatch filter ) # COMING BACK FROM OLD SESSION SecRuleRemoveById 970903 # Microsoft Office document properties leakage </Directory> EOF cat >> /etc/apache2/apache2.conf <<EOF <IfModule mod_security2.c> SecServerSignature " " </IfModule> EOF } configure() { [[ $ACTIVE_ == "yes" ]] && local STATE=On || local STATE=Off sed -i "s|SecRuleEngine .*|SecRuleEngine $STATE|" /etc/modsecurity/modsecurity.conf service apache2 restart } cleanup() { apt-get autoremove -y apt-get clean rm /var/lib/apt/lists/* -r rm -f /home/pi/.bash_history systemctl disable ssh } # License # # This script is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This script is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this script; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, # Boston, MA 02111-1307 USA

github

References

http://blog.modsecurity.org/2010/11/advanced-topic-of-the-week-traditional-vs-anomaly-scoring-detection-modes.html

https://samhobbs.co.uk/2016/03/getting-started-apache-modsecurity-debian-and-ubuntu

https://samhobbs.co.uk/2015/09/example-whitelisting-rules-apache-modsecurity-and-owasp-core-rule-set

https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual