Skip to content

Instantly share code, notes, and snippets.

@richeney
Created January 19, 2022 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save richeney/a8515410a404311fc9d4c421c784364d to your computer and use it in GitHub Desktop.
Save richeney/a8515410a404311fc9d4c421c784364d to your computer and use it in GitHub Desktop.
Bash crontab script to import PEM certs downloaded by the Azure Keyvault extension
#!/usr/bin/env bash
################################################################
# Search for certs downloaded by the Azure Key Vault Extension,
# convert from PEM to DER format and update the CA certificates.
#
# Designed to be run as root from crontab.
# Will be silent if no files are converted.
################################################################
error()
{
[[ -n "$@" ]] && echo "ERROR: $@" >&2
exit 1
}
umask 077
declare -i converted=0
[[ "$(/usr/bin/whoami)" != "root" ]] && error "$0 must be run as root."
[[ -x /usr/bin/openssl ]] || error "$0 requires openssl"
# The certs are downloaded as PEM files. The symbolic links are named
# <keyvaultName>.<certName> and point to the versioned files.
files=$(find /var/lib/waagent/Microsoft.Azure.KeyVault.Store -type l)
for pem in $files
do
basename=${pem##*/}
keyvault=${basename%.*}
cert=${basename#*.}
[[ "$pem" != "/var/lib/waagent/Microsoft.Azure.KeyVault.Store/$keyvault.$cert" ]] && error "Unexpected filename: $pem"
der=/usr/local/share/ca-certificates/$keyvault.$cert.crt
if [[ ! -f "$der" || "$pem" -nt "$der" ]]
then
[[ -f "$der" ]] && echo "Certificate $cert from keyvault $keyvault has been updated."
[[ ! -f "$der" ]] && echo "New certificate $cert downloaded from keyvault $keyvault."
echo "openssl x509 -in $pem --outform der -out $der"
openssl x509 -in $pem --outform der -out $der || error "Failed to convert from PEM to DER."
let converted=converted+1
fi
done
if [[ $converted -gt 0 ]]
then
echo "Converted $converted certificate(s). Running update-ca-certificates..."
update-ca-certificates || error "Failed to update CA certificates."
fi
exit 0
@richeney
Copy link
Author

I'm no expert on certificates, so if there is a flaw in this then please let me know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment