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

2324 lines
73 KiB
Markdown

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
lang: de-DE, en-US
---
🔘 [Raspberry Pi OS Flashen](flash-raspberry-pi-os.md) 🔘 [Nextcloud Installation](nextcloud-installation.md) 🔘 [Nextcloud Update / Upgrade Fehler ](nextcloud-upgrade-fehler.md) 🔘
# Nextcloud Installation
Die Anleitung beschreibt die Installation und Konfiguration der aktuellsten Nextcloud-Version auf einem Raspberry Pi.
***
- [Nextcloud Installation](#nextcloud-installation)
- [Hardware und Betriebssystem](#hardware-und-betriebssystem)
- [Hardware](#hardware)
- [Raspberry Pi](#raspberry-pi)
- [Banana Pi](#banana-pi)
- [Betriebssystem auf die SD-Karte spielen](#betriebssystem-auf-die-sd-karte-spielen)
- [SSH-Verbindung mit Public Keys einrichten](#ssh-verbindung-mit-public-keys-einrichten)
- [Update des Betriebssystems](#update-des-betriebssystems)
- [Installation der benötigten Pakete](#installation-der-benötigten-pakete)
- [Webserver Apache anpassen](#webserver-apache-anpassen)
- [Apache Module aktivieren](#apache-module-aktivieren)
- [Apache Neustart](#apache-neustart)
- [Apache aufrufen](#apache-aufrufen)
- [MariaDB-Server](#mariadb-server)
- [MariaDB Server absichern](#mariadb-server-absichern)
- [MariaDB - Datenbank für Nextcloud anlegen](#mariadb---datenbank-für-nextcloud-anlegen)
- [MariaDB - Benutzer anlegen](#mariadb---benutzer-anlegen)
- [MariaDB - Wichtige Befehle](#mariadb---wichtige-befehle)
- [Nextcloud Installation starten](#nextcloud-installation-starten)
- [Mit Prüfung der md5sum](#mit-prüfung-der-md5sum)
- [Ohne Prüfung der md5sum](#ohne-prüfung-der-md5sum)
- [Nextcloud - Ordner und -berechtigungen vergeben](#nextcloud---ordner-und--berechtigungen-vergeben)
- [Nextcloud erster Start](#nextcloud-erster-start)
- [Nextcloud - Konfigurieren](#nextcloud---konfigurieren)
- [Pretty URLs](#pretty-urls)
- [PHP-Speichergrenze](#php-speichergrenze)
- [OPcache](#opcache)
- [Datenverzeichnis und temporäres Upload-Verzeichnis auf externen USB-Stick verschieben](#datenverzeichnis-und-temporäres-upload-verzeichnis-auf-externen-usb-stick-verschieben)
- [Datenverzeichnis](#datenverzeichnis)
- [Temporäres Uploadverzeichnis erstellen](#temporäres-uploadverzeichnis-erstellen)
- [Papierkorb Retention](#papierkorb-retention)
- [CRON aktivieren](#cron-aktivieren)
- [Nextcloud Standarddateien ändern - Skeleton](#nextcloud-standarddateien-ändern---skeleton)
- [Option 1: Eigene Vorlagen definieren](#option-1-eigene-vorlagen-definieren)
- [Option 2: Ganz ohne Vorlagen](#option-2-ganz-ohne-vorlagen)
- [Nextcloud Backup](#nextcloud-backup)
- [Weitere Backup-Möglichkeiten](#weitere-backup-möglichkeiten)
- [Backups nach einer bestimmten Zeit löschen](#backups-nach-einer-bestimmten-zeit-löschen)
- [Kurzform](#kurzform)
- [Langform](#langform)
- [Redis Installieren](#redis-installieren)
- [Redis Installation und Konfiguration](#redis-installation-und-konfiguration)
- [Webserver Rechte auf den Socket gewähren](#webserver-rechte-auf-den-socket-gewähren)
- [Nextcloud anpassen](#nextcloud-anpassen)
- [Redis Fehler](#redis-fehler)
- [Apache - Webserver konfigurieren](#apache---webserver-konfigurieren)
- [index.html anpassen](#indexhtml-anpassen)
- [Let's Encrypt](#lets-encrypt)
- [Option 1: Installation mit pip](#option-1-installation-mit-pip)
- [Option 2: Installation mit snap](#option-2-installation-mit-snap)
- [Neues Let's Encrypt Zertifikate erstellen](#neues-lets-encrypt-zertifikate-erstellen)
- [Aktualisierung eines vorhandenen Let's Encrypt Zertifikats](#aktualisierung-eines-vorhandenen-lets-encrypt-zertifikats)
- [Eintrag als trusted\_domains](#eintrag-als-trusted_domains)
- [Apache2 000-default-le-ssl.conf](#apache2-000-default-le-sslconf)
- [Apache2 meineurl.de.conf](#apache2-meineurldeconf)
- [Nextcloud - Fehlermeldungen](#nextcloud---fehlermeldungen)
- [Ordner-Berechtigungen sind falsch gesetzt](#ordner-berechtigungen-sind-falsch-gesetzt)
- [App-Ordner](#app-ordner)
- [Fehlende PHP-Module](#fehlende-php-module)
- [Fehlende Telefonregion](#fehlende-telefonregion)
- [Webfinger \& Nodeinfo](#webfinger--nodeinfo)
- [Caldav \& Carddav](#caldav--carddav)
- [APCu](#apcu)
- [output buffering](#output-buffering)
- [Server Hardening](#server-hardening)
- [Benutzerverwaltung Raspberry Pi](#benutzerverwaltung-raspberry-pi)
- [Neuen Benutzer anlegen](#neuen-benutzer-anlegen)
- [SSH-Schlüssel für neuen Benutzer anlegen](#ssh-schlüssel-für-neuen-benutzer-anlegen)
- [Benutzer pi deaktivieren bzw. löschen](#benutzer-pi-deaktivieren-bzw-löschen)
- [fail2ban](#fail2ban)
- [fail2ban Benachrichtigungen](#fail2ban-benachrichtigungen)
- [unattended-upgrade](#unattended-upgrade)
- [ufw - Firewall](#ufw---firewall)
- [PHP-Version](#php-version)
- [Logrotate und Logwatch](#logrotate-und-logwatch)
- [Logrotate - Install](#logrotate---install)
- [Konfiguration](#konfiguration)
- [Beispiel](#beispiel)
- [Logrotate für meine Skripte](#logrotate-für-meine-skripte)
- [Logwatch](#logwatch)
- [Logwatch - Installation](#logwatch---installation)
- [Logwatch - Parameters](#logwatch---parameters)
- [Logwatch - Usage](#logwatch---usage)
- [Logwatch - CRON Setup](#logwatch---cron-setup)
- [Zusätzliche Tweaks](#zusätzliche-tweaks)
- [Verzögerter Boot-Vorgang](#verzögerter-boot-vorgang)
- [RTC-Modul DS3231](#rtc-modul-ds3231)
- [Regelmäßiger Neustart des Raspberry Pis](#regelmäßiger-neustart-des-raspberry-pis)
- [Raspberry Pi - E-Mail-Versand einrichten](#raspberry-pi---e-mail-versand-einrichten)
- [Backup SD-Karte](#backup-sd-karte)
- [Backup von Adressbücher und Kalender](#backup-von-adressbücher-und-kalender)
- [Spende](#spende)
- [Disclaimer](#disclaimer)
***
## Hardware und Betriebssystem
Die Installation wurde getestet auf:
***
**ACHTUNG!!!**
**Mit der Nextcloud-Version 25 werden nur noch 64bit unterstützt.**
***
### Hardware
#### Raspberry Pi
- **Hardware**: Raspberry Pi 4 Model B Rev 1.2
- **Betriebssystem**: Raspberry Pi OS - [https://www.raspberrypi.com/software/](https://www.raspberrypi.com/software/)
#### Banana Pi
- **Hardware**: Banana Pi BPI-M64
- **Betriebssystem**: Armbian 2 Bullseye - [https://www.armbian.com/](https://www.armbian.com/)
## 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](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
- 🔗 [https://strobelstefan.de/yubikey/](https://strobelstefan.de/yubikey/)
Auf dem **Client**:
```bash
# 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.
```bash
# OpenSSH Server auf dem neuen Server installieren
sudo apt install openssh-server
```
Das `~/.ssh`-Verzeichnis ist ggf. anzulegen und die Rechte neu zu vergeben.
```bash
# .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.
```bash
# 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.
```bash
# 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:
```bash
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:
```bash
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
```bash
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
- ➡️[PHP-Version aktualisieren](#php-version-aktualisieren)
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/system_requirements.html](https://docs.nextcloud.com/server/latest/admin_manual/installation/system_requirements.html)
## Webserver Apache anpassen
### Apache Module aktivieren
```bash
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod env
sudo a2enmod dir
sudo a2enmod mime
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html](https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html)
### Apache Neustart
```bash
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`.
```bash
http://ip-addresse
```
## MariaDB-Server
### MariaDB Server absichern
```bash
sudo mysql_secure_installation
```
Es werden einige Fragen gestellt, die mit `Y` beantwortet werden können.
```bash
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
```bash
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!***
```bash
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.
```bash
SET PASSWORD FOR 'nextcloud'@localhost = PASSWORD("");
```
### MariaDB - Wichtige Befehle
```bash
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:
- [Mit Prüfung der md5sum](#mit-prüfung-der-md5sum)
- [Ohne Prüfung der md5sum](#ohne-prüfung-der-md5sum)
Zu bevorzugen ist nach Möglichkeit die erste Option.
### Mit Prüfung der md5sum
Die heruntergeladene Datei wird anhand der `md5sum` überprüft.
```bash
# 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.
```bash
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`.
```bash
cd /var/www/html
curl https://download.nextcloud.com/server/releases/latest.tar.bz2 | sudo tar -jxv
```
### Nextcloud - Ordner und -berechtigungen vergeben
```bash
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.
```bash
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.
```bash
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
```bash
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.
```bash
sudo -u www-data php /var/www/html/nextcloud/occ config:system:set htaccess.RewriteBase --value="/nextcloud"
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html?highlight=pretty%20url#pretty-urls](https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html?highlight=pretty%20url#pretty-urls)
### PHP-Speichergrenze
Beim ersten Auruf von Nextcloud wird u.a. diese Meldung ausgegeben.
```text
Die PHP-Speichergrenze liegt unterhalb des empfohlenen Wertes von 512MB.
```
Die Speichergrenze ist inder `php.ini` anzupassen.
```bash
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
```
- 🔗 [Nextcloud Die PHP-Speichergrenze liegt unterhalb des empfohlenen Wertes von 512MB](https://strobelstefan.de/2019/08/19/nextcloud-die-php-speichergrenze-liegt-unterhalb-des-empfohlenen-wertes-von-512mb/)
In diesem Zuge Können gleich noch zwei weitere Werte in der `php.ini` angepasst werden:
```bash
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
```
- 🔗 [Uploading big files > 512MB](https://docs.nextcloud.com/server/stable/admin_manual/configuration_files/big_file_upload_configuration.html)
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html?highlight=output_buffering#configuring-php](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html?highlight=output_buffering#configuring-php)
### OPcache
```bash
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`
```bash
# 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:
```bash
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
```
```bash
# Webserver Apache neustarten
sudo systemctl restart apache2
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/server_tuning.html?highlight=opcache#caching](https://docs.nextcloud.com/server/latest/admin_manual/installation/server_tuning.html?highlight=opcache#caching)
### 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.
```bash
sudo cp /var/www/html/nextcloud/config/config.php ~
sudo -u www-data php /var/www/html/nextcloud/occ maintenance:mode --on
```
siehe 🔗 [APCu](#apcu) bei Fehlermeldung.
UUID ( 🔗 [Universally Unique Identifier](https://de.wikipedia.org/wiki/Universally_Unique_Identifier)](https://de.wikipedia.org/wiki/Universally_Unique_Identifier) ) des angeschlossenen Laufwerks bestimmen:
```bash
sudo blkid
```
⚠️ In diesem Beispiel wird ein **NTFS** formatiertes Speichermedium verwendet.
Bei anderen Formatierungen ist die Zeile in der `/etc/fstab` anzupassen.
```bash
sudo apt install ntfs-3g
```
Eintrag in der `/etc/fstab` erstellen.
```bash
# Mount Point erstellen
sudo mkdir /mnt/data
```
Eintrag in der `/etc/fstab` erstellen:
```bash
sudo nano /etc/fstab
```
Am Ende der Datei `/etc/fstab` die Zeile mit der UUID des USB-Sticks eintragen
```bash
# 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:
```bash
sudo mount /mnt/data
```
#### Datenverzeichnis
Der alte Eintrag `'datadirectory' => '/var/www/html/nextcloud/data',` in der Konfigurationsdatei ist zu ersetzen.
```bash
# 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
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=datadirectory#default-parameters](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=datadirectory#default-parameters)
#### 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.
```bash
# 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
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=datadirectory#all-other-configuration-options](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=datadirectory#all-other-configuration-options)
### Papierkorb Retention
Definiert, wann Ordner und Dateien im Papierkorb endgültig gelöscht werden sollen.
```bash
# Config-Datei bearbeiten
sudo nano /var/www/html/nextcloud/config/config.php
# Eintrag ändern
'trashbin_retention_obligation' => 'auto, 30',
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=trash#deleted-items-trash-bin](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=trash#deleted-items-trash-bin)
### CRON aktivieren
In der Nextcloud Weboberfläche ist die Option "**Einstellungen --> Grundeinstellungen --> Cron**" auszuwählen.
```bash
sudo crontab -u www-data -e
*/5 * * * * php8.1 -f /var/www/html/nextcloud/cron.php
```
Manuelles ausführen mit der Standard PHP-Version:
```bash
sudo -u www-data php -f /var/www/html/nextcloud/cron.php
```
Manuelles ausführen mit Angabe der installierten PHP-Version:
```bash
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](#apcu)
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/background_jobs_configuration.html?highlight=cron#cron-jobs](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/background_jobs_configuration.html?highlight=cron#cron-jobs)
### 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.
```bash
# 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:
```bash
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`:
```bash
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.
```bash
sudo nano /var/www/html/nextcloud/config/config.php
# Eintrag ändern
'skeletondirectory' => '',
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/default_files_configuration.html?highlight=skeleton](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/default_files_configuration.html?highlight=skeleton)
### 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](#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.
```bash
# 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.
```bash
#!/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:
```bash
-rwx------ 1 root root 1.2K Sep 1 19:45 backup-nextcloud.sh
```
```bash
# Rechte setzen
sudo chmod 700 /etc/skripte/backup-nextcloud.sh
```
Skript manuell starten und testen:
```bash
sudo sh /etc/skripte/backup-nextcloud.sh
```
Wenn der Testlauf erfolgreich war, kann der CRON Job angelegt werden:
```bash
sudo crontab -e
# Backup-Skript - täglich im 6:30
30 6 * * * /bin/bash /etc/skripte/backup-nextcloud.sh
```
Aus der offiziellen Nextcloud-Dokumentation
- Backup - 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/maintenance/backup.html](https://docs.nextcloud.com/server/latest/admin_manual/maintenance/backup.html)
- Restore - 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/maintenance/restore.html](https://docs.nextcloud.com/server/latest/admin_manual/maintenance/restore.html)
- Using the occ command - 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/occ_command.html#maintenance-commands-label](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/occ_command.html#maintenance-commands-label)
### 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](#nextcloud-backup))
- 🔗 [Datensicherung für die Nextcloud mit rsync](https://strobelstefan.de/2020/08/19/datensicherung-fuer-die-nextcloud-mit-rsync/)
- 🔗 [Datensicherung für die Nextcloud mit BorgBackup](https://strobelstefan.de/2020/08/07/datensicherung-fuer-die-nextcloud-mit-borgbackup/)
### 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.
```bash
# Neues Datei für Skript anlegen
sudo nano /etc/skripte/autodelete.sh
```
#### Kurzform
Kurz und bündig:
```bash
#!/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](https://codeberg.org/strobelstefan.org/imagebackup) zur Sicherung der SD-Karte auf ein externes Speichermedium zurückgegriffen.
```bash
#!/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
```bash
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.
```bash
# 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
```bash
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](#apcu) beschrieben.
```bash
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.
```bash
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,
```
- 🔗 [https://docs.nextcloud.com/server/22/admin_manual/configuration_server/caching_configuration.html](https://docs.nextcloud.com/server/22/admin_manual/configuration_server/caching_configuration.html)
## Apache - Webserver konfigurieren
### index.html anpassen
```bash
sudo rm /var/www/html.index.html
sudo nano /var/www/html/index.html
```
**Option 1**: Inhalt der `index.html`:
```bash
<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:
```bash
<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.
- 🔗 [Nextcloud und Let's Encrypt](https://strobelstefan.de/2018/04/03/nextcloud-und-lets-encrypt/)
Auf der offiziellen Website des Projekts ist eine detaillierte Installationsanleitung für Let's Encrypt zu finden
- 🔗 [https://certbot.eff.org/](https://certbot.eff.org/)
- 🔗 [https://github.com/certbot/certbot](https://github.com/certbot/certbot)
#### 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!
```bash
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
```bash
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
```bash
sudo certbot --apache
```
Es sind dann noch einige Informationen mit anzugeben, bevor das Zertifikat auf dem neuen Server installiert werden kann.
```bash
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:
```bash
# Testlauf - dry-run
sudo certbot renew --dry-run
# Aktualisierung
sudo certbot renew
```
- 🔗 [Pi-hole Let's Encrypt-Zertifikat für interne IP-Adressen verwenden](https://strobelstefan.de/2021/03/11/pi-hole-lets-encrypt-zertifikat-fuer-interne-ip-adressen-verwenden/)
- 🔗 [https://certbot.eff.org/instructions?ws=apache&os=debianbuster](https://certbot.eff.org/instructions?ws=apache&os=debianbuster)
#### Eintrag als trusted_domains
Die Domain ist in der Konfigurationsdatei von Nextcloud einzutragen:
```bash
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',
),
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=trusted_domains#default-parameters](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=trusted_domains#default-parameters)
### Apache2 000-default-le-ssl.conf
`meineurl.de` ist durch die jeweilige Domain zu ersetzen.
```bash
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`.
```bash
<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.
```bash
sudo systemctl restart apache2
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/harden_server.html](https://docs.nextcloud.com/server/latest/admin_manual/installation/harden_server.html)
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/reverse_proxy_configuration.html](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/reverse_proxy_configuration.html)
### Apache2 meineurl.de.conf
`meineurl.de` ist durch die jeweilige Domain zu ersetzen.
```bash
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.
```bash
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.
```bash
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
```bash
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 {} \;
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/maintenance/manual_upgrade.html](https://docs.nextcloud.com/server/latest/admin_manual/maintenance/manual_upgrade.html)
### App-Ordner
**Fehlermeldung**:
```bash
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**:
```bash
sudo chown -R www-data:www-data /var/www/html/nextcloud/apps
```
### Fehlende PHP-Module
**Fehlermeldung**:
```bash
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**:
```bash
sudo apt install php8.1-bcmath php8.1-gmp
sudo systemctl restart apache2
```
### Fehlende Telefonregion
**Fehlermeldung**:
```bash
Für Deine Installation ist keine Standard-Telefonregion festgelegt
```
**Lösung**:
```bash
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
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=default_phone_region#user-experience](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/config_sample_php_parameters.html?highlight=default_phone_region#user-experience)
### Webfinger & Nodeinfo
**Fehlermeldung**:
```bash
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](#apache2-000-default-le-sslconf)
```bash
sudo nano /etc/apache2/sites-available/000-default-le-ssl.conf
```
In die Datei ist das Snippt einzutragen:
```bash
...
<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:
```bash
sudo nano /var/www/html/.htaccess
```
```bash
<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:
```bash
sudo systemctl restart apache2
```
### Caldav & Carddav
**Fehlermeldung**:
```bash
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](#apache2-000-default-le-sslconf)
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/reverse_proxy_configuration.html](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/reverse_proxy_configuration.html)
- 🔗 [Nextcloud und das lästige Problem mit /.well-known/caldav & /.well-known/carddav](https://strobelstefan.de/2020/03/02/nextcloud-und-das-laestige-problem-mit-well-known-caldav-well-known-carddav/)
### APCu
**Fehlermeldung**:
```bash
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**:
```bash
# 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',
```
- 🔗 [Nextcloud Nach Upgrade auf 21.0.3.1 funktionieren die Cron Jobs und die occ-Befehle nicht mehr](https://strobelstefan.de/2021/07/11/nextcloud-nach-upgrade-auf-21-0-3-1-funktionieren-die-cron-jobs-und-die-occ-befehle-nicht-mehr/)
### output buffering
**Fehlermeldung**:
```bash
PHP configuration option output_buffering must be disabled
```
**Lösung**:
```bash
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
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html?highlight=output_buffering#configuring-php](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html?highlight=output_buffering#configuring-php)
## 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
```bash
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](#ssh-verbindung-mit-public-keys-einrichten) beschrieben.
```bash
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.
```bash
# 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](https://de.wikipedia.org/wiki/Fail2ban)
```bash
sudo apt install fail2ban
```
Konfigurationsdatei für fail2ban dort Anpassungen entsprechend den Anforderungen vornehmen.
```bash
sudo nano /etc/fail2ban/jail.conf
```
- 🔗 [Raspbian und Nextcloud absichern](https://strobelstefan.de/2018/04/03/raspbian-und-nextcloud-absichern/)
`nextcloud.conf` erstellen:
```bash
sudo nano /etc/fail2ban/filter.d/nextcloud.conf
```
Inhalt anpassen:
```bash
[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:
```bash
sudo nano /etc/fail2ban/filter.d/extcloud.local
```
Inhalt anpassen:
```bash
[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:
```bash
sudo systemctl restart fail2ban.service
sudo fail2ban-client status nextcloud
```
- 🔗 [https://docs.nextcloud.com/server/latest/admin_manual/installation/harden_server.html](https://docs.nextcloud.com/server/latest/admin_manual/installation/harden_server.html)
#### fail2ban Benachrichtigungen
Die Konfiguration wird im Abschnitt 🔗 [fail2ban](#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](#raspberry-pi---e-mail-versand-einrichten)
```bash
# 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.
```bash
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
```bash
sudo apt install unattended-upgrades
```
`unattended-upgrades` konfigurieren
```bash
sudo dpkg-reconfigure -plow unattended-upgrades
```
Datei anlegen ...
```bash
sudo nano /etc/apt/apt.conf.d/10periodic
```
... und mit Inhalt füllen.
```bash
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
```
- 🔗 [Raspbian und Nextcloud absichern](https://strobelstefan.de/2018/04/03/raspbian-und-nextcloud-absichern/)
### 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.
```bash
sudo apt install ufw
```
Die erste Regel ist das Freischalten von Port 22 für SSH, damit man immer Zugriff auf den Server bekommt.
```bash
sudo ufw allow 22
```
**IPV6 deaktivieren** (optional)
```bash
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`
```bash
sudo nano /etc/ufw/applications.d/nextcloud_80
```
Inhalt der Datei
```bash
[nextcloud_80]
title=Nextcloud - Port 80
description=Nextcloud - Port 80 for http
ports=80/tcp
```
**Profil 2**: Port 443 - `nextcloud_443`
```bash
sudo nano /etc/ufw/applications.d/nextcloud_443
```
Inhalt der Datei
```bash
[nextcloud_443]
title=Nextcloud - Port 443
description=Nextcloud - Port 443 for https
ports=443/tcp
```
ufw Änderungen einlesen und neustarten:
```bash
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
```
- 🔗 [ufw App Profile für die Nextcloud](https://strobelstefan.de/2021/03/28/ufw-app-profile-fuer-die-nextcloud/)
- 🔗 [Pi-hole mit der ufw-Firewall absichern](https://strobelstefan.de/2021/02/28/pi-hole-mit-der-ufw-firewall-absichern/)
## PHP-Version
siehe dazu [PHP-Fehler](nextcloud-upgrade-fehler.md#php-fehler)
## Logrotate und Logwatch
### Logrotate - Install
```bash
sudo apt install logrotate
# Installierte Version anzeigen
logrotate --version
```
### Konfiguration
Die Konfigurationsdateien werden im Verzeichnis `/etc/logrotate.d/` abgelegt.
```bash
# 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`
- 🔗 [https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04](https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04)
- 🔗 [https://linuxhint.com/logrotate-ubuntu-tutorial/](https://linuxhint.com/logrotate-ubuntu-tutorial/)
#### Beispiel
Es wird eine Dateie für das regelmäßige Löschen für imagebackup.log anglelegt.
```bash
sudo nano /etc/logrotate.d/imagebackup
```
Der Inhalt der Datei kann beispielhaft aussehen:
```bash
/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
```bash
sudo apt install logwatch
```
### Logwatch - Parameters
| Parameter | |
| --------- | ---- |
| `--output stdout|mail|file` | Specifies the output method. (Default: stdout) |
| `--format text|html` | Specifies the output format. (Default: text) |
| `--filename` X | Specifies the output file X. |
| `--detail low|med|high` | Specifies the detail level of the report. (Default: low) |
| `--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
```bash
sudo logwatch --detail low --range today
```
Log in HTML format
```bash
sudo logwatch --detail high --range yesterday --format html --filename ~/logwatch/$(date +%F).html
```
Log sent via e-mail - range yesterday
```bash
sudo logwatch --detail high --range yesterday --format html --mailto email@adresse
```
Log sent via e-mail - range 30 days
```bash
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](#raspberry-pi---e-mail-versand-einrichten)
```bash
sudo crontab -e
```
Add the following line somewhere in the crontab file:
```bash
0 6 * * * /usr/sbin/logwatch --detail med --format html --range yesterday --mailto email@adresse > /dev/null 2>&1
```
- Projektseite 🔗 [https://sourceforge.net/projects/logwatch](https://sourceforge.net/projects/logwatch)
## 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.
```bash
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.
```bash
sudo raspi-config
# Auswählen
3 Interface Options --> P5 I2C
```
Dateien anpassen
```bash
sudo nano /etc/modules
# In Datei eintragen
i2c-dev
i2c-bcm2708
```
I2C-Modul installieren
```bash
sudo apt update && sudo apt install i2c-tools && sudo shutdown -h now
```
Raspberry Pi herunterfahren und das RTC DS3231 anschließen.
```bash
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.
```bash
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
```bash
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
```bash
# 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
```bash
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.
```bash
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
```bash
sudo apt install postfix libsasl2-modules mutt
```
main.cfg editieren
```bash
sudo nano /etc/postfix/main.cf
# Strato - Am Ende der Datei eintragen
relayhost= smtp.strato.de:465
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
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt
# 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
```bash
sudo nano /etc/postfix/sasl_passwd
# Eintrag in der Datei nach dem Schema
E-Mail-Server:Port E-Mail-Adresse:Passwort
# Strato
smtp.strato.de:465 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
```bash
echo 'Test E-Mail' | mutt email@meineadresse.de -s "Test-Email ohne Anhang"
```
E-Mail-Versand testen - *mit* Anhang
```bash
cd
touch datei.txt
echo 'Test-Email mit Anhang' | mutt e-mail-adresse -a /home/pi/datei.txt -s "Test-Email mit Anhang"
```
Wird die Firewall `ufw` verwendet, ist der entsprechende Port für den Versand der E-Mails zu öffnen
```bash
sudo ufw allow out 465
sudo ufw reload
```
### Backup SD-Karte
Komplettes Backup der SD-Karte eines Raspberry Pis mit **imagebackup**
- [https://codeberg.org/strobelstefan.org/imagebackup](https://codeberg.org/strobelstefan.org/imagebackup)
siehe auch:
- 🔗 [Raspberry Pi SD-Karte im Livebetrieb klonen Neue Version](https://strobelstefan.de/2019/10/21/raspberry-pi-sd-karte-im-livebetrieb-klonen-neue-version/)
- 🔗 [Datensicherung für die Nextcloud mit BorgBackup](https://strobelstefan.de/2020/08/07/datensicherung-fuer-die-nextcloud-mit-borgbackup/)
### Backup von Adressbücher und Kalender
Mit einem Shell-Skript lassen sich die Adressbücher und Kalender einer Nextcloud-Installation sichern.
- [https://codeberg.org/strobelstefan.org/kalenderbackup](https://codeberg.org/strobelstefan.org/kalenderbackup)
siehe auch:
- 🔗 [Nextcloud Datensicherung von Kalendern und Adressbüchern automatisch erstellen](https://strobelstefan.de/2020/12/01/nextcloud-datensicherung-von-kalendern-und-adressbuechern-automatisch-erstellen/)
***
## Spende
Hat dir die Anleitung bei der Installation und Konfiguration deiner Nextcloud geholfen, dann kannst du mir gerne einen Kaffee ausgeben. ☕
<a href="https://www.paypal.com/donate?hosted_button_id=BNV5XKAAXK6TJ"><img src="https://img.shields.io/badge/Kaffee%20via-PayPal-blue.svg" /></a> 😊 <a href="https://liberapay.com/strobelstefan.org/donate"><img src="https://img.shields.io/badge/kaffee%20via-liberapay-yellow"></a> 😎 <img src="https://img.shields.io/badge/Kaffee%20via%20-Bitcoin-orange.svg" /> bc1qfuz93hw2fhdvfuxf6mlxlk8zdadvnktppkzqzj 😄
Mehr spannende Beiträge zu Nextcloud findest du auf meiner Website:
🔗 [https://strobelstefan.de/nextcloud/](https://strobelstefan.de/nextcloud/)
🐘 [Mastodon](https://mastodon.social/@strobelstefan) &bull; [![RSS](https://img.shields.io/badge/Follow-RSS-orange)](https://strobelstefan.de/feed/)
***
## 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.
***