Refactor PGP key generation

Extract new fingerprint from generation command output;
Verify that the generation has suceeded;
Verify that the current key fingerprint actually exists;
This commit is contained in:
David Duque 2021-03-07 18:32:21 +00:00
parent 966ded762e
commit 0a7d7c41d1
No known key found for this signature in database
GPG key ID: 913FE0F2477D7D6B

View file

@ -13,20 +13,42 @@ export GNUPGHOME # Dump into the environment so that gpg uses it as homedir
# Install gnupg
apt_install gnupg
if [ "$(gpg --list-secret-keys 2> /dev/null)" = "" -o "${PGPKEY-}" = "" ]; then
echo "No keypair found. Generating daemon's PGP keypair..."
function gpg_keygen {
# Generates a private key.
gpg --generate-key --batch << EOF;
%no-protection
Key-Type: RSA
Key-Length: 4096
Key-Usage: sign,encrypt,auth
Name-Real: Power Mail-in-a-Box Management Daemon
Name-Email: administrator@${PRIMARY_HOSTNAME}
Name-Email: noreply-daemon@${PRIMARY_HOSTNAME}
Expire-Date: 180d
%commit
EOF
}
# Generate a new key if:
# - There isn't a fingerprint on /etc/mailinabox.conf
# - The configured fingerprint doesn't actually exist
if [ "${PGPKEY-}" = "" -o "$(gpg --list-secret-keys 2> /dev/null | grep ${PGPKEY-})" = "" ]; then
echo "No keypair found. Generating daemon's PGP keypair..."
FPR_TMP=$(gpg_keygen 2>&1)
if [ $? -ne 0 ]; then
echo ""
echo "Key generation failed!" 1>&2
echo "============================" 1>&2
echo $FPR_TMP 1>&2
echo "============================" 1>&2
exit 1
fi
FPR=$(echo $FPR_TMP | sed -r 's/.*([0-9A-F]{40}).*/\1/g')
echo "Generated key $FPR"
chown -R root:root $GNUPGHOME
# Remove the old key fingerprint if it exists, and add the new one
# Remove the old key fingerprint from the configuration if it exists, and add the new one
echo "$(cat /etc/mailinabox.conf | grep -v "PGPKEY")" > /etc/mailinabox.conf
echo "PGPKEY=$(gpg --list-secret-keys --with-colons | grep fpr | head -n 1 | sed 's/fpr//g' | sed 's/://g')" >> /etc/mailinabox.conf
echo "PGPKEY=$FPR" >> /etc/mailinabox.conf
fi