GnuPG-encrypted mail forwarding for remote systems

Ever since I started using Fail2ban and Logwatch to monitor unauthorized login attempts and system logs on my server, I have been looking for an easy way to regularly receive encrypted status reports from both programmes by email. After playing around with gpg-mailgate for some time (useful tutorial here), I decided to opt for a simpler solution and told both programmes to send their reports to a specific user on my system. These messages are then retrieved by a simple cron script and emailed to me at regular intervals. Here is how I did it.px.gif

Import your gpg public key on the remote system via gpg --import <your key file>, and create a directory /var/mailbackup for backups. Then create a script /etc/cron.hourly/00mailencrypt with the following content (don't forget to replace the placeholders with the correct values for your set-up) and mark it executable.

#!/bin/bash
if [ -s /var/mail/<user name> ]
then <a href="https://stefan.angrick.me/tag:file" class="hashtag"><span>#</span><span class="p-category">file</span></a> has data cp /var/mail/<user name> /var/mailbackup/mailbackup$(date +%y%m%d-%H%M)
gpg -ea -r <email address> -o - /var/mail/<user name> | mail -s "mail report" <email address>
echo -n "" > /var/mail/<user name>
fi

Cron will now regularly check /var/mail/<user name> for new messages, encrypt them and send them to the designated email address.