Roundcube alongside Nextcloud


We will run Roundcube in a subfolder alongside and within Nextcloud on your NGINX, enhance security using TOTP (2FA) + fail2ban and finally add functionality using a carddav plugin for Nextcloud contacts.


To run Roundcube (https://your.dedyn.io/emails) alongside and within Nextcloud (as an “external site”) your NGINX configuration has to be modified and enhanced.  But first backup/move your old *.conf files inside the nginx-directories. Please substitute all the red values below properly to your environment.

sudo -s
service nginx stop
mv /etc/nginx/conf.d/gateway.conf /etc/nginx/conf.d/gateway.conf.bak
mv /etc/nginx/conf.d/nextcloud.conf /etc/nginx/conf.d/nextcloud.conf.bak
mv /etc/nginx/ssl.conf /etc/nginx/ssl.conf.bak
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Then create a new /etc/nginx/ssl.conf:

ssl_certificate /etc/letsencrypt/live/YOUR.DEDYN.IO/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/YOUR.DEDYN.IO/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/YOUR.DEDYN.IO/fullchain.pem;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
ssl_protocols TLSv1.2;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK:!AES128';
ssl_prefer_server_ciphers on;
ssl_ecdh_curve secp384r1;
ssl_stapling on;
ssl_stapling_verify on;

Then create a new /etc/nginx/header.conf:

add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Robots-Tag none;
add_header X-Download-Options noopen;
add_header X-Permitted-Cross-Domain-Policies none;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "same-origin" always;

Then create a new /etc/nginx/optimization.conf:

fastcgi_buffers 64 64K;
fastcgi_buffer_size 256k;
fastcgi_busy_buffers_size 3840K;
fastcgi_cache_key $http_cookie$request_method$host$request_uri;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
gzip on;
gzip_vary on;
gzip_comp_level 4;
gzip_min_length 256;
gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
gzip_disable "MSIE [1-6]\.";

Then create a new /etc/nginx/php_optimization.conf:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param modHeadersAvailable true;
fastcgi_param front_controller_active true;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
fastcgi_cache_valid 404 1m;
fastcgi_cache_valid any 1h;
fastcgi_cache_methods GET HEAD;

Then create a new /etc/nginx/proxy.conf:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_connect_timeout 3600;
proxy_send_timeout 3600;
proxy_read_timeout 3600;
proxy_redirect off;
proxy_buffering off;
proxy_max_temp_file_size 1024m;

Then change your /etc/nginx/nginx.conf to this:

user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
 worker_connections 1024;
 multi_accept on;
 use epoll;
}
http {
 server_names_hash_bucket_size 64;
 upstream php-handler {
 server unix:/run/php/php7.1-fpm.sock;
 }
 include /etc/nginx/mime.types;
 include /etc/nginx/proxy.conf;
 include /etc/nginx/ssl.conf;
 include /etc/nginx/header.conf;
 include /etc/nginx/optimization.conf;
 default_type application/octet-stream;
 log_format main '$remote_addr - $remote_user [$time_local] "$request" '
 '$status $body_bytes_sent "$http_referer" '
 '"$http_user_agent" "$http_x_forwarded_for" '
 '"$host" sn="$server_name" '
 'rt=$request_time '
 'ua="$upstream_addr" us="$upstream_status" '
 'ut="$upstream_response_time" ul="$upstream_response_length" '
 'cs=$upstream_cache_status' ;
 access_log /var/log/nginx/access.log main;
 sendfile on;
 send_timeout 3600;
 tcp_nopush on;
 tcp_nodelay on;
 open_file_cache max=500 inactive=10m;
 open_file_cache_errors on;
 keepalive_timeout 65;
 reset_timedout_connection on;
 server_tokens off;
 resolver 192.168.2.1;
 resolver_timeout 10s;
 include /etc/nginx/conf.d/*.conf;
}

Now create/modify the new /etc/nginx/conf.d/nextcloud.conf (no ‘gateway.conf’ is needed anymore!):

######################
#     NEXTCLOUD      #
######################
fastcgi_cache_path /usr/local/tmp/cache levels=1:2 keys_zone=NEXTCLOUD:100m inactive=60m;
map $request_uri $skip_cache {
 default 1;
 ~*/thumbnail.php 0;
 ~*/apps/galleryplus/ 0;
 ~*/apps/gallery/ 0;
}
server {
 listen 80 default_server;
 server_name YOUR.DEDYN.IO;
 location ^~ /.well-known/acme-challenge {
 proxy_pass http://127.0.0.1:81;
 }
 location / {
 return 301 https://$host$request_uri;
 }
}
server {
 listen 443 ssl http2 default_server;
 server_name YOUR.DEDYN.IO;
 root /var/www/nextcloud/;
 access_log /var/log/nginx/nextcloud.access.log main;
 error_log /var/log/nginx/nextcloud.error.log warn;
 location = /robots.txt {
 allow all;
 log_not_found off;
 access_log off;
 }
 location = /.well-known/carddav {
 return 301 $scheme://$host/remote.php/dav;
 }
 location = /.well-known/caldav {
 return 301 $scheme://$host/remote.php/dav;
 }
 client_max_body_size 10240M;
 location / {
 rewrite ^ /index.php$uri;
 }
 location ^~ /emails/ {
 proxy_pass http://127.0.0.1:83;
 }
 location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
 deny all;
 }
 location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
 deny all;
 }
 location ~ ^/(?:index|ip|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
 fastcgi_split_path_info ^(.+\.php)(/.*)$;
 include fastcgi_params;
 include php_optimization.conf;
 fastcgi_pass php-handler;
 fastcgi_param HTTPS on;
 fastcgi_cache_bypass $skip_cache;
 fastcgi_no_cache $skip_cache;
 fastcgi_cache NEXTCLOUD;
 }
 location ~ ^/(?:updater|ocs-provider)(?:$|/) {
 try_files $uri/ =404;
 index index.php;
 }
 location ~ \.(?:css|js|woff|svg|gif)$ {
 try_files $uri /index.php$uri$is_args$args;
 add_header Cache-Control "public, max-age=15778463";
 access_log off;
 expires 30d;
 }
 location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
 try_files $uri /index.php$uri$is_args$args;
 access_log off;
 expires 30d;
 }
}

Now create the new /etc/nginx/conf.d/roundcube.conf:

######################
#     Roundcube      # 
######################
server {
 server_name 127.0.0.1 default_server;
 listen 127.0.0.1:83;
 root /var/www/;
 client_max_body_size 1024M;
 index index.php;
 access_log /var/log/nginx/email.access.log main;
 error_log /var/log/nginx/email.error.log warn;
 charset utf-8;
 location /emails/ {
 try_files $uri $uri/ index.php;
 }
 location ~ ^/emails/(README|INSTALL|LICENSE|CHANGELOG|UPGRADING)$ {
 deny all;
 }
 location ~ ^/emails/(bin|SQL|config|temp|logs)/ {
 deny all;
 }
 location ~* \.php$ {
 fastcgi_split_path_info ^(.+\.php)(/.*)$;
 include fastcgi_params;
 include php_optimization.conf;
 fastcgi_pass php-handler;
 fastcgi_param HTTPS on;
 fastcgi_index index.php;
 try_files $uri =404;
 }
}

For comparison and validation you see the /etc/nginx/conf.d/letsencrypt.conf:

######################
#    letsencrypt     # 
######################

server {
listen 127.0.0.1:81 default_server;
server_name 127.0.0.1;
charset utf-8;
access_log /var/log/nginx/le.access.log main;
error_log /var/log/nginx/le.error.log warn;
location ^~ /.well-known/acme-challenge {
default_type text/plain;
root /var/www/letsencrypt;
}
}

Validate your NGINX configuration

nginx -t

and if no errors will appear just restart NGINX.

service nginx restart

To get your Roundcube started (https://YOUR.DEDYN.IO/emails), you need to download and install Roundcube:

cd /usr/local/src
wget https://github.com/roundcube/roundcubemail/releases/download/1.3.1/roundcubemail-1.3.1-complete.tar.gz
tar xfz roundcubemail-1.3.1-complete.tar.gz &&  mv roundcubemail-1.3.1 emails
mv emails /var/www/ && chown -R www-data:www-data /var/www/

Call Roundcube in your browser (https://your.dedyn.io/emails/installer/) and walk through the configuration steps. Don’t forget to remove the folder /var/www/emails/installer afterwards.

rm -R /var/www/emails/installer && service nginx restart

Having Roundcube installed (/var/www/emails) we will start harden roundcube using TOTP (2FA). Please ensure having switched into sudo mode and change into roundcube’s plugin directory:

sudo -s
cd /var/www/emails/plugins

Then download the TOTP-app from github:

git clone https://github.com/alexandregz/twofactor_gauthenticator.git

Logout from roundcube and edit the main configuration to enable TOTP:

sudo -u www-data vi ../config/config.inc.php

Add ‘twofactor_gauthenticator’ to the plugins-section:

$config['plugins'] = array('enigma', 'fail2ban', 'twofactor_gauthenticator', 'markasjunk', 'newmail_notifier', 'zipdownload');

Save and quit the file (:wq!) and logon to your roundcube instance. Then activate twofactor_gauthenticator in the settings-panel:

If you paste your Nextcloud secret and apply these settings you may logon to Roundcube using the same 2FA as for Nextcloud. Logout and re-login to roundcube again. From now your account is even more secure using a second factor for authentication.

Logout from roundcube and go ahead witht the implementation of fail2ban to prevent bruteforce attacks. Change to the plugin-directory again:

cd /var/www/emails/plugins

Download and extract the fail2ban-plugin:

wget https://github.com/mattrude/rc-plugin-fail2ban/archive/1.3.zip
unzip 1.3 && rm 1.3.zip

Then rename the plugin to fail2ban:

mv rc-plugin-fail2ban-1.3 fail2ban && chown -R www-data:www-data /var/www/emails

Create the fail2ban configuration for roundcube:

vi /etc/fail2ban/jail.d/roundcube.local

Add the following rows:

[roundcube]
ignoreip = 192.168.2.0/24
enabled = true
port = 80,443
protocol = tcp
maxretry = 3
bantime = 3600
logpath = /var/www/emails/logs/errors

Save and quit the file (:wq!) and create the roundcube filter expressions for fail2ban:

vi /etc/fail2ban/filter.d/roundcube.conf

Add the following rows:

[Definition]
failregex = Login failed for *.* from 127.0.0.1\(X-Real-IP\: <HOST>
ignoreregex =

Restart fail2ban:

service fail2ban restart

Logout from roundcube and edit the main configuration to enable fail2ban:

sudo -u www-data vi ../config/config.inc.php

Add ‘fail2ban’ to the plugins-section:

$config['plugins'] = array('enigma', 'fail2ban', 'twofactor_gauthenticator', 'markasjunk', 'newmail_notifier', 'zipdownload');

Save and quit the file (:wq!) and logon to your roundcube instance. Then verify fail2ban is working as expected.

fail2ban-client status nextcloud && fail2ban-client status roundcube

Re-logon to Nextcloud and roundcube using wrong credentials once. Then open the fail2ban-status again:

fail2ban-client status nextcloud && fail2ban-client status roundcube

If you’ll find e.g. “currently failed: 1” twice your Nextcloud and roundcube was successfully hardened with TOTP and fail2ban. At least we will add Nextcloud contacts to our roundcube instance using the carddav plugin. First logout from roundcube and change to the plugin directory again:

cd /var/www/emails/plugins

Download the plugin and extract it:

wget https://github.com/blind-coder/rcmcarddav/archive/master.zip && unzip master.zip

Rename the directory to carddav and change into that directory:

mv rcmcarddav-master carddav && rm master.zip && cd carddav

Download the binaries using curl:

curl -sS https://getcomposer.org/installer | php

Then execute the following command:

php composer.phar install

Copy the default config:

cp config.inc.php.dist config.inc.php && chown -R www-data:www-data /var/www/emails

Then modify pwstore_scheme to ‘des_key’:

sudo -u www-data vi config.inc.php

Change the ‘pwstore_scheme’-value:

...
$prefs['_GLOBAL']['pwstore_scheme'] = 'des_key';
...

Save and quit the file (:wq!) and edit roundcube’s main configuration:

sudo -u www-data vi ../../config/config.inc.php

Add ‘carddav’ to the plugins-section:

$config['plugins'] = array('carddav', 'enigma', 'fail2ban', 'twofactor_gauthenticator', 'markasjunk', 'newmail_notifier', 'zipdownload');

Save and quit the file (:wq!) and logon to your roundcube instance again. You will find the carddav option in roundcube’s settings panel:

Please fill in your url and your app-password from your Nextcloud. Adjust the carddav settings properly and enjoy your Roundcube beside and as an external site within your Nextcloud.


Have fun and enjoy your Nextcloud!

Carsten Rieger