You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 KiB

lang
de-DE, en-US

🔘 Raspberry Pi OS Flashen 🔘 Nextcloud Installation 🔘 Nextcloud Update / Upgrade Fehler 🔘

Nextcloud Installation

Die Anleitung beschreibt die Installation und Konfiguration der aktuellsten Nextcloud-Version auf einem Raspberry Pi.



Hardware und Betriebssystem

Die Installation wurde getestet auf:


ACHTUNG!!!

Mit der Nextcloud-Version 25 werden nur noch 64bit unterstützt.


Hardware

Raspberry Pi

Banana Pi

Betriebssystem auf die SD-Karte spielen

Die neue Version des Betriebssystem Raspberry Pi OS wird ohne den Standardbenutzer pi ausgeliefert!

Der Benutzer pi wurde aus Sicherheitsgründen entfernt. Es muss ein neuer Benutzer bei der ersten Anmeldung angelegt werden.

Eine Screenshotanleitung ist in der Datei flash-raspberry-pi-os.md zu finden.

SSH-Verbindung mit Public Keys einrichten

Es werden keine neuen SSH-Schlüssel für die Verbindung verwendet, sondern es eine YubiKey-Hardwaretoken 🔐 verwendet. Eine ausführliche Anleitung zum Einrichten findet sich auf

Auf dem Client:

# Bekannte Keys entfernen
ssh-keygen -R ip-adresse

# SSH-Verbindung herstellen
ssh pi@ip-adresse

Auf dem Server:

Die Installation des openssh-server ist nicht notwendig, wenn nach dem Flashen des Betriebssystems auf die SD-Karte die Datei ssh angelegt oder der SSH-Dienst über das Menü raspi-config bereits aktiviert wurde.

# OpenSSH Server auf dem neuen Server installieren
sudo apt install openssh-server

Das ~/.ssh-Verzeichnis ist ggf. anzulegen und die Rechte neu zu vergeben.

# .ssh-Verzeichnis anlegen und Rechte anpassen
mkdir .ssh

chmod 0711 ~/.ssh

# Datei für die SSH-Schlüssel anlegen
nano ~/.ssh/authorized_keys

In die neu angelegte Datei authorized_keys kann der Schüssel sehr einfach mit einem Editor, z.B. nano, vim, etc., mit Copy-Past eingefügt werden.

# Den privaten Schlüssel in die Datei neu angelegte Datei authorized_keys kopieren

# Key 1 - Description
ssh-rsa keykeykeykeykeykeykeykeykey

# Key 2 - Description
ssh-rsa keykeykeykeykeykeykeykeykey

# Key 3 - Description
...

Mehrere Schlüssel können fortlaufend in die Datei eingefügt werden. Kommentare können ebenfalls hinterlegt werden und sind mit # am Zeilenanfang zu kommentieren.

Die Rechte für die Datei ~/.ssh/authorized_keys kann angepasst werden, damit eine Änderung der Einträge nur noch mit sudo-Rechten möglich ist.
Diese Einstellung ist abhängig vom gewählten Sicherheitskonzept auf dem Nextcloud-Server.

# Rechte neu setzten
sudo chown root:root ~/.ssh/authorized_keys

sudo chmod 644 ~/.ssh/authorized_keys

# SSH-Dienst neustarten
sudo systemctl restart sshd

Update des Betriebssystems

Das Betriebssystem des Raspberry Pis kann mit dem Befehl gestartet werden:

sudo apt update && sudo apt dist-upgrade && sudo apt autoremove

Installation der benötigten Pakete

Alle benötigten Pakete für die Nextcloud lassen sich installieren mit:

sudo apt install apache2 mariadb-server-10.5 smbclient imagemagick php8.1 php-apcu php-pear php-imagick libapache2-mod-php8.1 

Die PHP-Modula lassen sich mit diesem Befehl installieren

sudo apt update && apt install -y php-common php8.1-{apcu,bcmath,bz2,cli,common,curl,fpm,gd,gmp,igbinary,imagick,intl,memcache,mysql,opcache,readline,redis,smbclient,xml,zip} 

siehe auch

Webserver Apache anpassen

Apache Module aktivieren

sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod env
sudo a2enmod dir
sudo a2enmod mime

Apache Neustart

sudo systemctl restart apache2

Apache aufrufen

Funktionstest. Falls der Webserver läuft wird die index.html im Webbrowser angezeigt. Die Datei liegt im Root-Verzeichnis des Webserver /var/www/html.

http://ip-addresse

MariaDB-Server

MariaDB Server absichern

sudo mysql_secure_installation

Es werden einige Fragen gestellt, die mit Y beantwortet werden können.

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n
 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

MariaDB - Datenbank für Nextcloud anlegen

sudo mariadb

...

CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
Query OK, 1 row affected (0.002 sec)

MariaDB [(none)]> quit;
Bye

Datenbankname: nextcloud

MariaDB - Benutzer anlegen

⚠️ Achtung!!! Das Passwort ist NUR für die Nextcloud-Datenbank und wird später noch benötigt. Also gut merken!

sudo mariadb
CREATE USER nextcloud@localhost identified by 'password';
GRANT ALL PRIVILEGES on nextcloud.* to nextcloud@localhost;

# Optional, falls Probleme bei der Installation auftreten
grant all privileges on nextcloud.* to 'nextcloud'@'localhost' with grant option;

FLUSH privileges;
quit;
  • Benutzername: nextcloud
  • Passwort: durch-benutzer-neu-vergeben

Das Passwort für den Benutzer nextcloud kann gelöscht und wieder mit dem Befehl von oben neu gesetzt werden.

SET PASSWORD FOR 'nextcloud'@localhost = PASSWORD("");

MariaDB - Wichtige Befehle

sudo mariadb

# Alle existierenden Datenbanken auflisten
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| nextcloud          |
| performance_schema |
+--------------------+
4 rows in set (0.007 sec)

# Alle Benutzer des Datenbankservers anzeigen
MariaDB [(none)]> SELECT User FROM mysql.user;
+-------------+
| User        |
+-------------+
| mariadb.sys |
| mysql       |
| nextcloud   |
| root        |
+-------------+
4 rows in set (0.007 sec)

# Benutzer löschen
DROP USER 'nextcloud'@'localhost';

# Datenbank "nextcloud " löschen
DROP DATABASE IF EXISTS nextcloud;

# Berechtigungen für Benutzer nextcloud anzeigen
SHOW GRANTS FOR 'nextcloud'@'localhost';

# Passwort für Benutzer `nextcloud` löschen
SET PASSWORD FOR 'nextcloud'@localhost = PASSWORD("");

Nextcloud Installation starten

Es gibt zwei Optionen Nextcloud zu installieren:

Zu bevorzugen ist nach Möglichkeit die erste Option.

Mit Prüfung der md5sum

Die heruntergeladene Datei wird anhand der md5sum überprüft.

# Wechsel in das Home-Verzeichnis
cd

# Download der aktuellsten Nextcloud-Version
curl https://download.nextcloud.com/server/releases/latest.tar.bz2 > latest.tar.bz2

# Download der md5-Prüfsumme
curl https://download.nextcloud.com/server/releases/latest.tar.bz2.md5 > latest.tar.bz2.md5

# Vergleich der beiden md5sums
md5sum latest.tar.bz2 && cat latest.tar.bz2.md5

# tar.bz2-Archiv in das Verzeichnis kopieren
sudo cp latest.tar.bz2 /var/www/html/

# Wechsle in das Verzeichnis
cd /var/www/html/

# tar.bz2-Archiv entpacken
sudo tar xfvj latest.tar.bz2

Nach dem Entpacken können die nichtmehr benötigten Dateien entfernt werden.

sudo rm /var/www/html/latest.tar.bz2
rm ~/latest.tar.bz2
rm ~/latest.tar.bz2.md5

Ohne Prüfung der md5sum

Quick und dirty, Installation ohne die Prüfung der md5sum.

cd /var/www/html
curl https://download.nextcloud.com/server/releases/latest.tar.bz2 | sudo tar -jxv 

Nextcloud - Ordner und -berechtigungen vergeben

cd /var/www/html/nextcloud
sudo mkdir -p /var/www/html/nextcloud/data
sudo chown www-data:www-data /var/www/html/nextcloud/data
sudo chmod 750 /var/www/html/nextcloud/data
sudo chown www-data:www-data /var/www/html/nextcloud/config
sudo chown -R www-data:www-data /var/www/html/nextcloud/apps
sudo systemctl restart apache2

Nextcloud erster Start

Erster Aufruf der Nextcloud und Eingabe der erforderlichen Informationen.

http://ip-adresse/nextcloud
  • Benutzername: ist neu zu vergeben
  • Passwort: ist neu zu vergeben
  • Datenverzeichnis: keine Änderung notwendig
  • Datenbank-Benutzer: nextcloud
  • Datenbank-Passwort: siehe oben
  • Datenbank-Name: nextcloud
  • Server: localhost (Portnummer ist keine einzutragen)

Nach der Installation funktioniert ggf. die Weiterleitung auf das Nextcloud-Dashboard nicht korrekt.

http://ip-adresse/nextcloud

Die empfohlenen Apps können gleich installiert werden, wenn die Hardwareanforderungen passen.

Nextcloud - Konfigurieren

Es gibt zwei Möglichkeiten Einträge in die Konfigurationsdatei config.php zu schreiben:

  • Option 1: Die Datei wird mit einem Editor bearbeitet. (die Option wird in dieser Anleitung verwendet.)
  • Option 2: Mit dem occ Kommando lassen sich die Einträge beaeintragenrbeiten. Beispiel:
    • sudo -u www-data php occ config:system:set memcache.local --value="\\OC\\Memcache\\APCu"
    • sudo -u www-data php /var/www/html/nextcloud/occ config:system:set memcache.local --value="\\OC\\Memcache\\APCu"

Pretty URLs

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

# Am Ende der Datei, aber vor ); die Zeile eintragen
'htaccess.RewriteBase' => '/nextcloud',

sudo systemctl restart apache2

Der Eintrag kann auch mithilfe des occ-Befehls erstellt werden.

sudo -u www-data php /var/www/html/nextcloud/occ config:system:set  htaccess.RewriteBase --value="/nextcloud"

PHP-Speichergrenze

Beim ersten Auruf von Nextcloud wird u.a. diese Meldung ausgegeben.

Die PHP-Speichergrenze liegt unterhalb des empfohlenen Wertes von 512MB.

Die Speichergrenze ist inder php.ini anzupassen.

cd /etc/php/8.1/apache2
sudo cp php.ini php.ini-bak
sudo nano /etc/php/8.1/apache2/php.ini

# Eintrag memory_limit anpassen
memory_limit = 512M

sudo systemctl restart apache2

In diesem Zuge Können gleich noch zwei weitere Werte in der php.ini angepasst werden:

sudo nano /etc/php/8.1/apache2/php.ini

upload_max_filesize = 16G
post_max_size = 16G
max_execution_time = 30

sudo systemctl restart apache2

OPcache

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

# Am Ende der Datei, aber vor ); die Zeile eintragen
'memcache.local' => '\\OC\\Memcache\\APCu',

# Webserver Apache 2 neustarten
sudo systemctl restart apache2

Anpassung der php.ini

# Backup der php.ini erstellen
sudo cp /etc/php/8.1/apache2/php.ini /etc/php/8.1/apache2/php.ini-bak

# php.ini bearbeiten
sudo nano /etc/php/8.1/apache2/php.ini

Am Ende der Datei vor ; Local Variables: ist einzutragen:

opcache.enable=1
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.save_comments=1
opcache.revalidate_freq=1
# Webserver Apache neustarten
sudo systemctl restart apache2

Datenverzeichnis und temporäres Upload-Verzeichnis auf externen USB-Stick verschieben

Das Datenverzeichnis und ein temporäres Upload-Verzeichnis werden auf das gleiche, externe Speichermedium, z. B. externe Festplatte, USB-Stick, verschoben.

Dadurch werden die Schreibaktivitäten auf die SD-Karte verringert und ein größeres Speichermedium für das Ablegen der Dateien kann verwendet werden.

Vor der Änderungen ist ein Backup der Nextcloud-Konfigurations-Datei zu erstellen und anschließend die Nextcloud in den Wartungsmodus zu versetzen.

sudo cp /var/www/html/nextcloud/config/config.php ~

sudo -u www-data php /var/www/html/nextcloud/occ maintenance:mode --on

siehe 🔗 APCu bei Fehlermeldung.

UUID ( 🔗 Universally Unique Identifier](https://de.wikipedia.org/wiki/Universally_Unique_Identifier) ) des angeschlossenen Laufwerks bestimmen:

sudo blkid

⚠️ In diesem Beispiel wird ein NTFS formatiertes Speichermedium verwendet.
Bei anderen Formatierungen ist die Zeile in der /etc/fstab anzupassen.

sudo apt install ntfs-3g

Eintrag in der /etc/fstab erstellen.

# Mount Point erstellen
sudo mkdir /mnt/data

Eintrag in der /etc/fstab erstellen:

sudo nano /etc/fstab

Am Ende der Datei /etc/fstab die Zeile mit der UUID des USB-Sticks eintragen

# Data-Verzeichnis der Nextcloud
UUID=xcxcxcxcxcxcxc /mnt/data ntfs-3g utf8,dmask=007,fmask=007,umask=007,uid=www-data,gid=www-data 0

Das Laufwerk lässt sich anschließend sofort einhängen:

sudo mount /mnt/data

Datenverzeichnis

Der alte Eintrag 'datadirectory' => '/var/www/html/nextcloud/data', in der Konfigurationsdatei ist zu ersetzen.

# Ordner erstellen
sudo mkdir -p /mnt/data/nc-data

# Config-Datei bearbeiten
sudo nano /var/www/html/nextcloud/config/config.php

# Eintrag ändern
'datadirectory' => '/mnt/data/nc-data/data',

# Ordner und Dateien verschieben
sudo mv -v /var/www/html/nextcloud/data /mnt/data/nc-data

# Nextcloud Wartungsmodus AUS
sudo -u www-data php /var/www/html/nextcloud/occ maintenance:mode --off

Temporäres Uploadverzeichnis erstellen

Die Dateien werden während des Uploadvorgangs in dieses Verzeichnis gespeichert. Erst wenn 100% der Datei hochgeladen wurden, wird diese automatisch in das Datenverzeichnis verschoben.

# Nextcloud Wartungsmodus AN
sudo -u www-data php /var/www/html/nextcloud/occ maintenance:mode --on

# Ordner erstellen
sudo mkdir -p /mnt/data/nc-tmp

# Config-Datei bearbeiten
sudo nano /var/www/html/nextcloud/config/config.php

# Eintrag ändern
'tempdirectory' => '/mnt/data/nc-tmp',

# Nextcloud Wartungsmodus AUS
sudo -u www-data php /var/www/html/nextcloud/occ maintenance:mode --off

Papierkorb Retention

Definiert, wann Ordner und Dateien im Papierkorb endgültig gelöscht werden sollen.

# Config-Datei bearbeiten
sudo nano /var/www/html/nextcloud/config/config.php

# Eintrag ändern
'trashbin_retention_obligation' => 'auto, 30',

CRON aktivieren

In der Nextcloud Weboberfläche ist die Option "Einstellungen --> Grundeinstellungen --> Cron" auszuwählen.

sudo crontab -u www-data -e

*/5  *  *  *  * php8.1 -f /var/www/html/nextcloud/cron.php

Manuelles ausführen mit der Standard PHP-Version:

sudo -u www-data php -f /var/www/html/nextcloud/cron.php

Manuelles ausführen mit Angabe der installierten PHP-Version:

sudo -u www-data php8.1 -f /var/www/html/nextcloud/cron.php

oder

sudo -u www-data php8.1 -f /var/www/html/nextcloud/cron.php

Damit die CRON Jobs korrekt laufen, ist eine Einstellung in der Konfigurationsdatei von APCu vorzunehmen. ➡️ APCu

Nextcloud Standarddateien ändern - Skeleton

Skeleton sind Dokumente, die jedem neuen Benutzer der Nextcloud automatisch angezeigt werden.

Option 1: Eigene Vorlagen definieren

Nextcloud legt jedem neuen Benutzer standardmäßig Dateien in seinen Dateiordner.

Es können eigene Dateien und Ordner definiert werden, die in einem neuen Verzeichnis abgelegt werden.

# Standard-Skeleton anzeigen
cd /var/www/html/nextcloud/core/skeleton

ls

 Documents             'Nextcloud Manual.pdf'   Photos                          Templates
'Nextcloud intro.mp4'   Nextcloud.png          'Reasons to use Nextcloud.pdf'

Neues Skeleton-Verzeichnis im neuen Datenverzeichnis /mnt/data/nc-data anlegen und Vorlagen erstellen:

sudo mkdir /mnt/data/nc-data/data/skeleton-neu

In dieses neue Verzeichnis sind alle Vorlagen abzuspeichern. Werden neue Benutzer angelegt, werden diesen automatisch die Skeleton-Dateien ihr Verzeichnis kopiert.

Anpassung der config.php:

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

# Eintrag ändern
'skeletondirectory' => '/mnt/data/nc-data/data/skeleton-neu',

Option 2: Ganz ohne Vorlagen

Sollen keine Vorlagen verwendet und dem Benutzer ein leeres Verzeichnis erstellt werden, dann ist der Eintrag in der Config-Datei leer zu lassen.

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

 # Eintrag ändern
'skeletondirectory' => '',

Nextcloud Backup

Das einfachste durchzuführende Backup ist mithilfe eines Bash-Skripts und eines Cron Jobs. Dadurch kann die Datensicherung zu definierten Zeiten und selbstständig gestartet werden.

Die zu sichernden Quellen sind dabei:

  • Konfigurationsdateien - /var/www/html/nextcloud/config
  • Datenverzeichnis - /mnt/data/nc-data
  • MariaDB Datenbank nextcloud
  • Themes-Verzeichnis (optional, wenn Anpassungen vorgenommen wurden) - var/www/html/nextcloud/themes

Das Ziel auf dem die Backups landen sollen, sollte ein separates Speichermedium (Festplatte, USB-Stick, NAS, FRITZ!Box, etc.)sein.

Das Einbinden des Speichermediums erfolgt wie bereits in Abschnitt 🔗 Datenverzeichnis und temporäres Upload-Verzeichnis auf externen USB-Stick verschieben beschrieben.

⚠️ In diesem Beispiel wird ein NTFS formatiertes Speichermedium verwendet.
Bei anderen Formatierungen ist der Wert ntfs-3g in der /etc/fstab anzupassen.

# UUID ermitteln
sudo blkid

sudo nano /etc/fstab

# Data-Verzeichnis der Nextcloud
UUID=xcxcxcxcxcxcxc /mnt/nextcloud-backup ntfs-3g utf8,dmask=007,fmask=007,umask=007,uid=www-data,gid=www-data,noatime 0

# Mount Point setzen für Speichermedium
sudo mkdir /mnt/nextcloud-backup

# Neuer Ordner für Skripte anlegen
sudo mkdir /etc/skripte

# Bash Skript anlegen
sudo nano /etc/skripte/backup-nextcloud.sh

Inhalt der Datei backup-nextcloud.sh. Das Passwort für die Datenbanksicherung ist anzupassen.

#!/usr/bin/env bash

# Creates backups of Nextcloud instance
# 1. config directory
# 2. data directory
# 3. data base dump
#
# Copyright by Stefan Strobel
# https://www.strobelstefan.org

# Wechsel in das Nextcloud-Verzeichnis
cd /var/www/html/nextcloud

# Aktiviere den Maintenance Mode für Nextcloud - Keine User Anmeldung mehr möglich!
sudo -u www-data php occ maintenance:mode --on

# Sichere die Config-Datei
sudo tar -cpzf /mnt/nextcloud-backup/Nextcloud_Config_`date +"%Y%m%d%H"`.tar.gz -C /var/www/html/nextcloud/config .

# Sichere das gesamte Verzeichnis /data
sudo tar -cpzf /mnt/nextcloud-backup/Nextcloud_Data_`date +"%Y%m%d%H"`.tar.gz -C /var/www/html/nextcloud/data/ .

# Erstelle ein Datenbanksicherung
mysqldump --default-character-set=utf8mb4 --single-transaction -h localhost -u nextcloud -passwort nextcloud > /mnt/nextcloud-backup/nextcloud-sqlbkp_`date +"%Y%m%d"`.bak

# Entferne den Maintenance Mode für Nextcloud - User Anmeldungen sind wieder möglich!
sudo -u www-data php occ maintenance:mode --off

Die Rechte für das Skript sind auf die folgenden Werte zu setzen:

-rwx------ 1 root root 1.2K Sep  1 19:45 backup-nextcloud.sh
# Rechte setzen
sudo chmod 700 /etc/skripte/backup-nextcloud.sh

Skript manuell starten und testen:

sudo sh /etc/skripte/backup-nextcloud.sh

Wenn der Testlauf erfolgreich war, kann der CRON Job angelegt werden:

sudo crontab -e

# Backup-Skript - täglich im 6:30
30 6 * * * /bin/bash /etc/skripte/backup-nextcloud.sh

Aus der offiziellen Nextcloud-Dokumentation

Weitere Backup-Möglichkeiten

Es gibt noch weitere Möglichkeiten, um die Konfigurationsdateien und das Datenverzeichnis der eigenen Nextcloud zu sichern.

⚠️ Die Datenbank wird dabei nicht berücksichtigt! ⚠️

Soll diese ebenfalls über eine der folgenden Möglichkeiten gesichert werden, muss eine Datenbankdump zuvor erstellt und in eines der Verzeichnisse gespeichert werden. ( 🔗 Nextcloud Backup)

Backups nach einer bestimmten Zeit löschen

Die Backups können über die Zeit die Speicherkapazität des Speichermediums auslasten, deshalb können ältere Backups nach einer definierten Zeit automatisch gelöscht werden.

Dazu eignet sich ebenfalls ein Bash-Skript, dass mithilfe eines Cron Jobs zu einer festgelegten Zeit startet.

# Neues Datei für Skript anlegen
sudo nano /etc/skripte/autodelete.sh

Kurzform

Kurz und bündig:

#!/usr/bin/env bash

#
# This scripts deletes the backup files of the Nextcloud installation that are older than x days

find /mnt/nextcloud-backup/* -mtime +40 -exec rm {} \;

Langform

In dieser Variante wird geprüft, ob das Backup-Speichermedium eingebunden ist, bevor die Dateien gelöscht werden.
Dabei wird auf die beiden Skripte

  • storage-mount.sh
  • storage-umount.sh

meines 🔗 imagebackup.sh zur Sicherung der SD-Karte auf ein externes Speichermedium zurückgegriffen.

#!/usr/bin/env bash

#
# This scripts deletes the backup files of the Nextcloud installation that are older than x days
#
# Copyright by Stefan Strobel
# https://www.strobelstefan.org


###################################
# Variables
###################################

# Script name
MAINSCRIPT=$(basename -- "$0")

# PWD of script
SCRIPTPWD="/etc/skripte/"

# Storage device as defined in your /etc/fstab.
MOUNTPOINT='/mnt/nextcloud-backup'

# Email address where the log file should be sent to
EMAIL="adresse@e-mail.de"

#Log File location and name
LOGFILE="/var/log/autodelete.log"


###################################
# Log File
###################################

	echo "" >> ${LOGFILE}
	echo "" >> ${LOGFILE}
	echo "" >> ${LOGFILE}

if test -f "${LOGFILE}"
	then
		echo "++++++++++++++++++++++++++" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Start ${MAINSCRIPT} on $(hostname)" >> ${LOGFILE}
		echo "++++++++++++++++++++++++++" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Log File already exists!" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Log File location: ${LOGFILE}" >> ${LOGFILE}

	else
		touch ${LOGFILE}

		echo "++++++++++++++++++++++++++" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Start ${MAINSCRIPT} on $(hostname)" >> ${LOGFILE}
		echo "++++++++++++++++++++++++++" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Log File newly created!" >> ${LOGFILE}
		echo "$(date +%Y-%m-%d_%H-%M-%S) - Log File location: ${LOGFILE}" >> ${LOGFILE}
fi

	echo "" >> ${LOGFILE}


###################################
# MOUNTPOINT Section - Check Mount point Availability
###################################
# Calls the script storage-mount.sh 
# and passes relevant variables

/bin/bash ${SCRIPTPWD}storage-mount.sh "${MOUNTPOINT}" "${EMAIL}" "${LOGFILE}" "${MAINSCRIPT}" >> ${LOGFILE}


###################################
# Delete Old Files
###################################

find ${MOUNTPOINT}* -mtime +40 -exec rm {} \;  >> ${LOGFILE}


###################################
# UMOUNT Section - Unmount Storage Device
###################################
# Calls the script storage-umount.sh 
# and passes relevant variables

/bin/bash ${SCRIPTPWD}storage-umount.sh "${MOUNTPOINT}" "${EMAIL}" "${LOGFILE}" "${MAINSCRIPT}" >> ${LOGFILE}

exit 0

Redis Installieren

Redis Installation und Konfiguration

sudo apt install redis-server php-redis

Redis lässt sich mit einem Passwort absichern. Der Passworthash wird in der redis.conf und der config.php eingetragen.

passwort ist durch ein eigenes Passwort zu ersetzen.

# Passworthash erstellen
echo passwort | sha256sum

sudo nano /etc/redis/redis.conf

# Ersetzen
# unixsocketperm 700
unixsocketperm 770

# maxclients 10000
maxclients 100

# requirepass foobared
requirepass passwort

Webserver Rechte auf den Socket gewähren

sudo usermod -aG redis www-data
sudo service redis-server restart

# Redis Service anzeigen
ps ax | grep redis

Nextcloud anpassen

Es wird auch APCu verwendet. Die Konfiguration ist im Abschnitt 🔗 APCu beschrieben.

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

'memcache.local' => '\OC\Memcache\APCu',
'memcache.distributed' => '\OC\Memcache\Redis',
'memcache.locking' => '\OC\Memcache\Redis',
'redis' => [
     'host'     => '/var/run/redis/redis-server.sock',
     'port'     => 6379,
     'dbindex'  => 0,
     'password' => '<hier den obigen Redis-Hash eintragen>',
     'timeout'  => 1.5,
],

Redis Fehler

Der Host wird nicht richtig erkannt, die Nextcloud Weboberfläche ist nicht mehr erreichbar.

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

# Alter Eintrag
     'host'     => '/var/run/redis/redis-server.sock',
     'port'     => 6379,

# Neuer Eintrag
     'host'     => '127.0.0.1',
     'port'     => 6379,

Apache - Webserver konfigurieren

index.html anpassen

sudo rm /var/www/html.index.html
sudo nano /var/www/html/index.html

Option 1: Inhalt der index.html:

<html>
<head>
<title>Are you looking for something?</title>
</head>
<body>
Are you looking for something?<br>
Maybe it is not here.<br>
Please contact your administrator for assistance.
</body>
</html>

Option 2: Inhalt der index.html mit Redirect:

<html>
<head>
<title>Redirect</title>
<meta http-equiv="refresh" content="0; URL=https://meineurl.de/nextcloud">
<meta name="keywords" content="automatic redirection">
</head>
<body>
If your browser doesn't automatically go there within a few seconds,
you may want to go to the destination manually.
</body>
</html>

Let's Encrypt

⚠️ Let's Encrypt verwendet für die Zertifikatserstellung den Port 80. Ist dieser nicht erreichbar, dann schlägt die Zertifikatserstellung und -erneuerung fehl.

Auf der offiziellen Website des Projekts ist eine detaillierte Installationsanleitung für Let's Encrypt zu finden

Option 1: Installation mit pip

Die erste Option verwendet pip (= Python Package Index).

Für die Installation und Konfiguration sind die beiden Optionen zu wählen:

  • Software: Apache
  • System: pip

ACHTUNG!!! Zwingend auf der Projektseite die Beschreibung und evtl. Aktualisierungen dieser Anleitung nachschlagen!

sudo apt update && sudo apt install python3 python3-venv libaugeas0
sudo python3 -m venv /opt/certbot/
sudo /opt/certbot/bin/pip install --upgrade pip
sudo /opt/certbot/bin/pip install certbot certbot-apache
sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot
sudo certbot --apache

Option 2: Installation mit snap

sudo apt update && sudo apt dist-upgrade
sudo apt install snapd
sudo reboot
sudo snap install core
sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Neues Let's Encrypt Zertifikate erstellen

sudo certbot --apache

Es sind dann noch einige Informationen mit anzugeben, bevor das Zertifikat auf dem neuen Server installiert werden kann.

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): email@adresse.de

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: n
Account registered.
Please enter the domain name(s) you would like on your certificate (comma and/or
space separated) (Enter 'c' to cancel): meineurl.de
Requesting a certificate for meineurl.de

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/meineurl.de/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/meineurl.de/privkey.pem
This certificate expires on 2023-06-17.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for meineurl.de to /etc/apache2/sites-available/000-default-le-ssl.conf
Congratulations! You have successfully enabled HTTPS on https://meineurl.de

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Aktualisierung eines vorhandenen Let's Encrypt Zertifikats

⚠️ Port 80 muss geöffnet sein und für den Server erreichbar sein. Die Aktualisierung des Let's Encrypt Zertifikats ist unabhängig der gewählten Installationsoption.

Die Aktualisierung des Zertifikats erfolgt mit dem Befehl:

# Testlauf - dry-run
sudo certbot renew --dry-run

# Aktualisierung
sudo certbot renew

Eintrag als trusted_domains

Die Domain ist in der Konfigurationsdatei von Nextcloud einzutragen:

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

# meineurl.de mit fortlaufender Nummerierung eintragen
  'trusted_domains' => 
  array (
    0 => '192.168.xxx.yyy',
    1 => 'meineurl.de',
  ),

Apache2 000-default-le-ssl.conf

meineurl.de ist durch die jeweilige Domain zu ersetzen.

cd /etc/apache2/sites-available/

sudo cp 000-default-le-ssl.conf 000-default-le-ssl.conf-bak

sudo rm /etc/apache2/sites-available/000-default-le-ssl.conf

sudo nano /etc/apache2/sites-available/000-default-le-ssl.conf

Inhalt der Datei 000-default-le-ssl.conf.

<IfModule mod_ssl.c>

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ServerName meineurl.de
</VirtualHost>

<VirtualHost *:443>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

    <IfModule mod_headers.c>
      Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; strict-origin; preload"
      Redirect 301 /.well-known/carddav /nextcloud/remote.php/dav
      Redirect 301 /.well-known/caldav /nextcloud/remote.php/dav
      Redirect 301 /.well-known/webfinger /nextcloud/index.php/.well-known/webfinger
      Redirect 301 /.well-known/nodeinfo /nextcloud/index.php/.well-known/nodeinfo
    </IfModule>


        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf


ServerName meineurl.de
SSLCertificateFile /etc/letsencrypt/live/meineurl.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/meineurl.de/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Im Anschluss ist der Webserver neuzustarten.

sudo systemctl restart apache2

Apache2 meineurl.de.conf

meineurl.de ist durch die jeweilige Domain zu ersetzen.

sudo nano /etc/apache2/sites-available/meineurl.de.conf

<VirtualHost *:80>
   ServerName meineurl.de
   Redirect permanent / https://meineurl.de/nextcloud
</VirtualHost>

<VirtualHost *:443>
   ServerName meineurl.dehnextcloud
   Redirect permanent / meineurl.de/nextcloud
    <IfModule mod_headers.c>
      Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; preload"
    </IfModule>
</VirtualHost>

Der Webserver is neu zu starten.

sudo systemctl restart apache2

Nextcloud - Fehlermeldungen

Ordner-Berechtigungen sind falsch gesetzt

Die Ordnerberechtigungen sind nicht korrekt gesetzt und der Webserver-Benutzer www-data erhält keinen Schreibzugriff auf die Nextcloud-Verzeichnisse.

Dieser Fehler hat für den Betrieb der Nextcloud keine Auswirkungen. Steht jedoch ein Update an, müssen in die aufgelisteten Ordner neue Dateien geschrieben oder bestehende Dateien geändert werden.

Check for write permissions
The following places can not be written to:

    /var/www/html/nextcloud/updater/../version.php
    /var/www/html/nextcloud/updater/../public.php
    /var/www/html/nextcloud/updater/../cron.php
    /var/www/html/nextcloud/updater/../occ
    /var/www/html/nextcloud/updater/../.htaccess
    /var/www/html/nextcloud/updater/../remote.php
    /var/www/html/nextcloud/updater/../.user.ini
    /var/www/html/nextcloud/updater/../status.php
    /var/www/html/nextcloud/updater/../robots.txt
    /var/www/html/nextcloud/updater/../console.php
    /var/www/html/nextcloud/updater/../index.php
    /var/www/html/nextcloud/updater/../COPYING
    /var/www/html/nextcloud/updater/../AUTHORS
    /var/www/html/nextcloud/updater/../index.html

Abhilfe schafft das Setzen der richtigen Zugriffsrechte

sudo chown -R www-data:www-data /var/www/html/nextcloud
sudo find /var/www/html/nextcloud/ -type d -exec chmod 750 {} \;
sudo find /var/www/html/nextcloud/ -type f -exec chmod 640 {} \;

App-Ordner

Fehlermeldung:

Einige App-Ordner haben einen anderen Besitzer als der Benutzer des Webservers (`www-data`). Dies kann der Fall sein, wenn Apps manuell installiert wurden. Prüfe die Berechtigungen der folgenden App-Ordner:

...

Lösung:

sudo chown -R www-data:www-data /var/www/html/nextcloud/apps

Fehlende PHP-Module

Fehlermeldung:

Dieser Installation fehlen einige empfohlene PHP-Module. Für bessere Leistung und bessere Kompatibilität wird dringend empfohlen, diese zu installieren.
    bcmath
    gmp

Lösung:

sudo apt install php8.1-bcmath php8.1-gmp
sudo systemctl restart apache2

Fehlende Telefonregion

Fehlermeldung:

Für Deine Installation ist keine Standard-Telefonregion festgelegt

Lösung:

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

# Am Ende der Datei, aber vor ); die Zeile eintragen
'default_phone_region' => 'DE',

sudo systemctl restart apache2

Webfinger & Nodeinfo

Fehlermeldung:

Dein Webserver ist nicht richtig konfiguriert, um "/.well-known/webfinger" aufzulösen.
Dein Webserver ist nicht richtig konfiguriert, um "/.well-known/nodeinfo" aufzulösen.

Lösung:

siehe 🔗 Apache2 000-default-le-ssl.conf

sudo nano /etc/apache2/sites-available/000-default-le-ssl.conf

In die Datei ist das Snippt einzutragen:


...

<VirtualHost *:443>

...

	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html

  <IfModule mod_headers.c>
   Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; strict-origin; preload"
   Redirect 301 /.well-known/carddav /nextcloud/remote.php/dav
   Redirect 301 /.well-known/caldav /nextcloud/remote.php/dav
   Redirect 301 /.well-known/webfinger /nextcloud/index.php/.well-known/webfinger
   Redirect 301 /.well-known/nodeinfo /nextcloud/index.php/.well-known/nodeinfo
  </IfModule>

...  

Zusätzlich dazu ist in der .htaccess-Datei im Hauptverzeichnise des Webservers das Snipt einzufügen:

sudo nano /var/www/html/.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^\.well-known/host-meta /nextcloud/public.php?service=host-meta [QSA,L]
  RewriteRule ^\.well-known/host-meta\.json /nextcloud/public.php?service=host-meta-json [QSA,L]
  RewriteRule ^\.well-known/webfinger /nextcloud/public.php?service=webfinger [QSA,L]
  RewriteRule ^\.well-known/carddav /nextcloud/remote.php/dav/ [R=301,L]
  RewriteRule ^\.well-known/caldav /nextcloud/remote.php/dav/ [R=301,L]
</IfModule>

Webserver nach der Änderung neustarten:

sudo systemctl restart apache2

Caldav & Carddav

Fehlermeldung:

Dein Webserver ist nicht richtig konfiguriert, um "/.well-known/caldav" aufzulösen.
Dein Webserver ist nicht richtig konfiguriert, um "/.well-known/carddav" aufzulösen.

Lösung:

siehe Apache2 000-default-le-ssl.conf

APCu

Fehlermeldung:

An unhandled exception has been thrown:
OC\HintException: [0]: Memcache \OC\Memcache\APCu not available for local cache (Is the matching PHP module installed and enabled?)

Lösung:

# apcu.ini editieren
sudo nano /etc/php/8.1/mods-available/apcu.ini

# Am Ende der Datei eintragen
apc.enable_cli=1

# Webserver neustarten
sudo systemctl restart apache2

# Nextcloud config.php editieren
sudo nano /var/www/htmls/nextcloud/config.php

# Zeile einfügen
'memcache.local' => '\OC\Memcache\APCu',

output buffering

Fehlermeldung:

PHP configuration option output_buffering must be disabled

Lösung:

sudo nano /etc/php/8.1/apache2/php.ini

# Eintrag auskommentieren
; output_buffering = 4096

# Eintrag einfügen und output_buffering ausschalten
output_buffering = off

sudo systemctl restart apache2

Server Hardening

Benutzerverwaltung Raspberry Pi

⚠️ Diese Anleitung stellt nur einen Auszug der Möglichkeiten der Benutzerverwaltung dar. Bitte zwingend auf die eigenen Anforderungen abstimmen!

Neuen Benutzer anlegen

sudo adduser <benutzer>
sudo usermod -aG sudo <benutzer>
sudo usermod -aG users <benutzer>

# Wird eine eigene Gruppe für die SSH-Anmeldung verwendet ist der neue Benutzer dort zwingend hinzuzufügen.

# Benutzer wechseln
su - <benutzer>

# Passwort vergeben
passwd

SSH-Schlüssel für neuen Benutzer anlegen

Es sind die SSH-Schlüssel für den neuen Benutzer anzulegen, wie in Abschnitt 🔗 SSH-Verbindung mit Public Keys einrichten beschrieben.

mkdir ~/.ssh
chmod 0711 ~/.ssh

# Den SSH-Key in die Datei kopieren
sudo nano ~/.ssh/authorized_keys

# Alternativ kann auch mit ssh-copy-id der öffentliche Schlüssel vom eigenen Client übertragen werden
ssh-copy-id -i ~/.ssh/id_rsa.pub benutzer@neuer-server

# Rechte neu setzten
sudo chown root:root ~/.ssh/authorized_keys
sudo chmod 644 ~/.ssh/authorized_keys
sudo systemctl restart sshd

Benutzer pi deaktivieren bzw. löschen

⚠️ Bevor ein bestehender Benutzer auf dem System deaktiviert oder gelöscht wird, unbedingt prüfen, ob

  • SSH-Zugriff möglich ist
  • der neue Benutzer Mitglied der Gruppe sudo ist und auch wirklich sudo-Befehle ausführen kann.

Ist beides möglich, kann der Benutzer deaktiviert bzw. gelöscht werden.

# Anzeige der Benutzerdaten
chage -l pi

# Bevorzugete Option
chsh -s /usr/sbin/nologin pi

# Lock Account
sudo passwd -l pi

# Unlock Account
sudo passwd -u pi

# Benutzeranmeldung sperren
sudo usermod -L pi

# Benutzer 
sudo deluser pi

# Benutzer inkl. Home-Verzeichnis löschen
sudo deluser --remove-home pi

fail2ban

Was ist fail2ban?
🔗 https://de.wikipedia.org/wiki/Fail2ban

sudo apt install fail2ban

Konfigurationsdatei für fail2ban dort Anpassungen entsprechend den Anforderungen vornehmen.

sudo nano /etc/fail2ban/jail.conf

nextcloud.conf erstellen:

sudo nano /etc/fail2ban/filter.d/nextcloud.conf

Inhalt anpassen:

[Definition]
_groupsre = (?:(?:,?\s*"\w+":(?:"[^"]+"|\w+))*)
failregex = ^\{%(_groupsre)s,?\s*"remoteAddr":"<HOST>"%(_groupsre)s,?\s*"message":"Login failed:
            ^\{%(_groupsre)s,?\s*"remoteAddr":"<HOST>"%(_groupsre)s,?\s*"message":"Trusted domain error.
datepattern = ,?\s*"time"\s*:\s*"%%Y-%%m-%%d[T ]%%H:%%M:%%S(%%z)?"

nextcloud.local-Datei erstellen:

sudo nano /etc/fail2ban/filter.d/extcloud.local

Inhalt anpassen:

[nextcloud]
backend = auto
enabled = true
port = 80,443
protocol = tcp
filter = nextcloud
maxretry = 3
bantime = 86400
findtime = 43200
logpath = /mnt/data/nc-data/data/nextcloud.log

fail2ban neu starten und Status der Konfiguration ansehen:

sudo systemctl restart fail2ban.service
sudo fail2ban-client status nextcloud

fail2ban Benachrichtigungen

Die Konfiguration wird im Abschnitt 🔗 fail2ban beschrieben und ist Voraussetzung für den Versand der Benachrichtigungen.

fail2ban kann auch E-Mail mit Nachrichten zu bestimmten Ereignissen an eine definierte E-Mail-Adresse senden. 🔗 Raspberry Pi - E-Mail-Versand einrichten

# Backup der Datei anlegen
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.conf.bak

# Datei bearbeiten
sudo nano /etc/fail2ban/jail.conf

# Die Zeilen in der Datei sind anzupassen
...
destemail = email@meineadresse.de
...
sender = email@meineadresse.de
...
mta = mail
...
# action = %(action_)s
action = %(action_mwl)s
...

sudo systemctl restart fail2ban.service

E-Mail-Versand beim Neustarten des Raspberry Pis ausschalten.

sudo nano /etc/fail2ban/action.d/mail-buffered.local

# In die Datei kopieren
[Definition]
actionstart =
actionstop =

# Dummy-Dateien anlegen
sudo cp /etc/fail2ban/action.d/mail-buffered.local /etc/fail2ban/action.d/mail.local
sudo cp /etc/fail2ban/action.d/mail-buffered.local /etc/fail2ban/action.d/mail-whois-lines.local
sudo cp /etc/fail2ban/action.d/mail-buffered.local /etc/fail2ban/action.d/mail-whois.local
sudo cp /etc/fail2ban/action.d/mail-buffered.local /etc/fail2ban/action.d/sendmail-buffered.local
sudo cp /etc/fail2ban/action.d/mail-buffered.local /etc/fail2ban/action.d/sendmail-common.local

sudo systemctl restart fail2ban.service

unattended-upgrade

sudo apt install unattended-upgrades

unattended-upgrades konfigurieren

sudo dpkg-reconfigure -plow unattended-upgrades

Datei anlegen ...

sudo nano /etc/apt/apt.conf.d/10periodic

... und mit Inhalt füllen.

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";

ufw - Firewall

⚠️ Werden Ports über die Firewall geschlossen, ist ggf. eine SSH-Anmeldung am Server nicht mehr möglich. Der Port 22 sollte deshalb unbedingt geöffnet bleiben!

Ist der Server über SSH nicht mehr erreichbar, kann der Raspberry Pi an einen Monitor angeschlossen werden und eine normale Benutzeranmeldung durchgeführt werden. Es sollte hier unbedingt das Tastaturlayout über sudo raspi-config auf "Deutsch" gesetzt werden, um die Anmeldeinformationen, insbesondere das Passwort, ohne Probleme eingeben zu können.
Standardmäßig verwendet der Pi ein englisches Tastaturlayout, was insbesondere bei der Eingabe von Sonderzeichen mit einem deutschen Layout eine kleine oder große Herausforderung darstellt.

sudo apt install ufw

IPV6 deaktivieren (optional)

sudo nano /etc/default/ufw

# Zeile alt
IPV6=yes

# Zeile neu
IPV6=no

Zwei Profile sind in /etc/ufw/applications.d/ anzulegen.

Profil 1: Port 80 - nextcloud_80

sudo nano /etc/ufw/applications.d/nextcloud_80

Inhalt der Datei

[nextcloud_80]
title=Nextcloud - Port 80
description=Nextcloud - Port 80 for http
ports=80/tcp

Profil 2: Port 443 - nextcloud_443

sudo nano /etc/ufw/applications.d/nextcloud_443

Inhalt der Datei

[nextcloud_443]
title=Nextcloud - Port 443
description=Nextcloud - Port 443 for https
ports=443/tcp

ufw Änderungen einlesen und neustarten:

sudo ufw allow 22
sudo ufw app update nextcloud_443
sudo ufw app update nextcloud_80
sudo ufw allow nextcloud_80
sudo ufw allow nextcloud_443
sudo ufw enable
sudo ufw reload
sudo ufw app list

PHP-Version

siehe dazu PHP-Fehler

Logrotate und Logwatch

Logrotate - Install

sudo apt install logrotate

# Installierte Version anzeigen
logrotate --version

Konfiguration

Die Hauptkonfigurationsdatei /etc/logrotate. Dort werden die globalen Einstellungen konfiguriert.

# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# use date as a suffix of the rotated file
#dateext

# uncomment this if you want your log files compressed
compress

# packages drop log rotation information into this directory
include /etc/logrotate.d

# system-specific logs may be also be configured here.
  • weekly: rotates the log files once a week
  • su root syslog: will archive the logs using the specific user (root) and group (syslog) to prevent issues with permissions
  • rotate 4: makes sure that four old versions of the file are saved. Rotates a given log four times before deleting it, so this keeps four weeks of logs online.
  • create: The old file is saved under a new name and a new file is created
  • compress: compress causes logrotate to compress log files to save space. This is done using gzip by default, but you can specify another program
  • include: This important option makes sure that the content of the directory /etc/logrotate.d is included. In this directory, files exist that specify how to handle some individual log files.
  • dateext: Archive old versions of log files adding a date extension like YYYYMMDD instead of simply adding a number. The extension may be configured using the dateformat and dateyesterday options.

Die Konfigurationsdateien für die Programme liegen im Verzeichnis /etc/logrotate.d und werden tw. nach deren Installation automatisch dort angelegt. Die Konfigurationsdateien können anschließend angepasst werden, um die globalen Vorgaben aus /etc/logrotate.conf zu überschreiben.

  • rotate x - keep x log files (x = number of log files)
  • hourly, daily, weekly, monthly, yearly - rotate interval
  • compress: compress the rotated files.
  • missingok: dont write an error message if the log file is missing.
  • notifempty - dont rotate the log file if it is empty
  • compress - compress archive
  • delaycompress - This command is useful if you want to compress the archived logs, but want to delay the compression. When delaycompress is active, an archived log is compressed the next time that the log is rotated. This can be important when you have a program that might still write to its old log file for a time after a fresh one is rotated in. Note that delaycompress works only if you have compress in your configuration.

Weitere Informationen finden sich in manpage man logrotate

Beispiel

/var/log/imagebackup.log {
        rotate 4
        daily
        missingok
        notifempty
        compress
        delaycompress
        sharedscripts
        endscript
}

Logrotate für meine Skripte

Für folgende Skripte ist ein eigens Logrotate-Profil nach dem obigen Veispiel zu erstellen:

  • imagebackup.sh
  • kalenderbackup.sh
  • nextcloudbackup.sh

Logwatch

Das Open Source Tool logwatch erstellt einen kurzen, übersichtlichen Check über die Logs eines Linux-basierten Servers. Es bietet eine gute und transparente Anlaufstelle und es ermöglicht, sich vorgefilterte Meldungen anzeigen zu lassen (z.B. Festplatte voll, fehlerhafte Anmeldungen an sicherheitsrelevanten Diensten oder um einfach nach dem Status der letzten installierten oder veränderten Pakete in der Paketverwaltung zu sehen).

Logwatch - Installation

sudo apt install logwatch

Logwatch - Parameters

Parameter
`--output stdout mail
`--format text html`
--filename X Specifies the output file X.
`--detail low med
--mailto X Sends the generated report by mail to the address X. (requires an installed MTA)
--range today Specifies the time period to report on (see logwatch --range help).

Logwatch - Usage

Logwatch should be run with high permissions otherwise the tool won´t get access to system logs.

Log from current day

sudo logwatch --detail low --range today 

Log in HTML format

sudo logwatch --detail high --range yesterday --format html --filename ~/logwatch/$(date +%F).html 

Log sent via e-mail - range yesterday

sudo logwatch --detail high --range yesterday --format html --mailto email@adresse

Log sent via e-mail - range 30 days

sudo logwatch --detail low --range 'between 30 days ago and yesterday' --mailto email@adresse 

Logwatch - CRON Setup

Damit auch die E-Mail-Nachrichten versendet werden können, muss Postfix / mutt auf dem System installiert sein. ➡️ Raspberry Pi - E-Mail-Versand einrichten

sudo crontab -e

Add the following line somewhere in the crontab file:

0 6 * * *  /usr/sbin/logwatch --detail med --format html --range yesterday --mailto email@adresse > /dev/null 2>&1

Zusätzliche Tweaks

Verzögerter Boot-Vorgang

Werden am Raspberry Pi externe Festplatten angeschlossen, dann werden diese u.U. nicht während des Boot-Vorgangs eingebunden, da die Zeit zum Starten für die Datenspeicher zu gering ist. Das Problem kann ggf. bei etwas älteren, konventionellen Festplatte auftreten. Bei neuen SSD-Platten und konventionellen Platten ist diese Einstellung normalerweise nicht notwendig.
Im Standard gewährt der Pi 2 Sekunden zum Erkennen der Festplatten, dann wird das Betriebssystem gestartet.

sudo nano /boot/config.txt

# Am Ende der Datei eintragen
program_usb_timeout=1

# Weiterer Eintrag in der Datei
# The command instructs to wait for a given number of seconds in start.elf 
# before loading the kernel.
boot_delay=30

RTC-Modul DS3231

RTC steht für Real Time Clock und hilft dem Raspberry Pi nach einem Neustart die eingestellte Zeit nicht zu verlieren, da der kleine Einplatinenrechner über keine eingebaute Batterie verfügt.

Das RTC-Modul DS3231 ist auf den GPIOs anzubringen und anschließend zu aktivieren.

sudo raspi-config

# Auswählen
3 Interface Options --> P5 I2C

Dateien anpassen

sudo nano /etc/modules

# In Datei eintragen
i2c-dev
i2c-bcm2708

I2C-Modul installieren

sudo apt update && sudo apt install i2c-tools && sudo shutdown -h now

Raspberry Pi herunterfahren und das RTC DS3231 anschließen.

sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- -- 

Wird "68" ausgegeben wurde das DS3231 erkannt und kann verwendet werden.

echo ds3231 0x68 | sudo tee /sys/class/i2c-adapter/i2c-1/new_device

# Ausgabe, wenn RTC-Modul erfolgreich erkannt wurde
ds3231 0x68

Einstellung bei jedem Neustart laden

sudo nano /etc/rc.local

# Zeile VOR "exit 0" einfügen
echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device

Uhrzeit prüfen

# Uhrzeit überprüfen
sudo hwclock
2021-10-09 14:27:07.410247+02:00

# Uhr einstellen
sudo hwclock -w

Nicht mehr benötigte Komponenten abschalten

sudo update-rc.d ntp disable
sudo update-rc.d fake-hwclock disable

Regelmäßiger Neustart des Raspberry Pis

Ein regelmäßiger Neustart des Raspberry Pis ist ggf. sinnvoll und kann mit einem CRON automatisiert werden.

sudo crontab -e

# Reboots the system every Wednesday at 6:05 a.m.
0 6 * * 3 /sbin/shutdown -r +5

Raspberry Pi - E-Mail-Versand einrichten

Pakete installieren

sudo apt install postfix libsasl2-modules mutt

main.cfg editieren

sudo nano /etc/postfix/main.cf

# Strato - Am Ende der Datei eintragen
relayhost= smtp.strato.de:587
smtp_sasl_auth_enable = yes
sender_canonical_maps = hash:/etc/postfix/sender_canonical
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_use_tls = yes
smtp_enforce_tls = no
smtp_tls_enforce_peername = no
smtpd_tls_security_level = may

# GMail - Am Ende der Datei eintragen
relayhost= smtp.gmail.com:587
smtp_sasl_auth_enable = yes
sender_canonical_maps = hash:/etc/postfix/sender_canonical  # Absender definieren
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd     # Passwort des E-Mail-Kontos
smtp_sasl_security_options = noanonymous
smtp_use_tls = yes
smtp_enforce_tls = no
smtp_tls_enforce_peername = no
smtpd_tls_security_level = may

Zugangsdaten und Absender konfigurieren

sudo nano /etc/postfix/sasl_passwd

# Eintrag in der Datei nach dem Schema
E-Mail-Server:Port E-Mail-Adresse:Passwort


sudo nano /etc/postfix/sender_canonical

# Einträge nach dem Schema 
pi email@meineadresse.de
user1 email@meineadresse.de
user2 email@meineadresse.de


sudo postmap /etc/postfix/sasl_passwd
sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db

sudo postmap /etc/postfix/sender_canonical
sudo chown root:root /etc/postfix/sender_canonical /etc/postfix/sender_canonical.db
sudo chmod 0600 /etc/postfix/sender_canonical /etc/postfix/sender_canonical.db

sudo systemctl restart postfix

E-Mail-Versand testen - ohne Anhang

echo 'Test E-Mail' | mutt email@meineadresse.de -s "Test-Email ohne Anhang"

E-Mail-Versand testen - mit Anhang

cd
touch datei.txt

echo 'Test-Email mit Anhang' | mutt e-mail-adresse -a /home/pi/datei.txt -s "Test-Email mit Anhang"

Backup SD-Karte

Komplettes Backup der SD-Karte eines Raspberry Pis mit imagebackup

siehe auch:

Backup von Adressbücher und Kalender

Mit einem Shell-Skript lassen sich die Adressbücher und Kalender einer Nextcloud-Installation sichern.

siehe auch:


Spende

Hat dir die Anleitung bei der Installation und Konfiguration deiner Nextcloud geholfen, dann kannst du mir gerne einen Kaffee ausgeben.

😊 😎 bc1qfuz93hw2fhdvfuxf6mlxlk8zdadvnktppkzqzj 😄

Mehr spannende Beiträge zu Nextcloud findest du auf meiner Website:
🔗 https://strobelstefan.de/nextcloud/

🐘 MastodonRSS


Disclaimer

Die hier geschilderten Arbeitsweisen basieren auf meiner persönlichen Erfahrung und meinen persönlichen Gedankengängen. Ich übernehme keine Garantie für die Resultate; Ausprobieren und Implementieren der beschriebenen Vorgehensweisen erfolgt ausschließlich auf eigene Verantwortung und Gefahr.

Bitte erstellt deshalb vor jeder Änderung an eurem System oder Konfiguration ein Backup, damit ihr im Fall der Fälle eine Wiederherstellung durchführen könnt.