system/scripts/certificate_hook.sh

85 lines
2.5 KiB
Bash
Executable File

#!/bin/sh
#to-do: make this universal / not specific to a certain service
set -C
#set -e
set -u
certname="irc.casa"
mailto="system@lysergic.dev"
#hosts="dericom01 deriweb01"
hosts="dericom01"
OUTPUT="/var/log/lysergic/certificate-scripts/$certname.log"
crt="/etc/ssl/lego/certificates/$certname.crt"
key="/etc/ssl/lego/certificates/$certname.key"
destdir="/etc/ssl/irc/"
#crtdest="/etc/ssl/irc/crt"
#keydest="/etc/ssl/irc/key"
sshuser="brain"
sshkey="/home/brain/.ssh/id_lysergic"
sshopts=" -qi $sshkey"
cn=`openssl x509 -in $crt -noout -text | grep "CN ="`
alt=`openssl x509 -in $crt -noout -text | grep "DNS:"`
notbefore=`openssl x509 -in $crt -noout -text | grep "Not Before"`
notafter=`openssl x509 -in $crt -noout -text | grep "Not After"`
fp_crt=`openssl x509 -fingerprint -sha256 -noout -in $crt`
install () {
local host="$1"
local source="$2"
local target="$sshuser@$host:$3"
echo "$host: Installing $target ..." >> $OUTPUT
scp $sshopts "$source" "$target" >> $OUTPUT 2>&1
}
reload () {
local host="$1"
local service="$2"
echo "$host: Reloading $service ..." >> $OUTPUT
ssh $sshopts "$sshuser:$host" "/usr/bin/sudo /usr/bin/systemctl reload $service.service" >> $OUTPUT 2>&1
}
check () {
local host="$1"
local port="$2"
echo "Performing self-check [$host:$port]..." >> $OUTPUT
local fp_remote=`openssl s_client -connect "$host":"$port" < /dev/null 2>/dev/null | openssl x509 -fingerprint -sha256 -noout -in /dev/stdin`
echo "Remote fingerprint: $fp_crt" >> $OUTPUT
if [ "$fp_crt" = "$fp_crt" ]; then
echo "MATCHES!" >> $OUTPUT
else
echo "VERIFICATION FAILED. Manual intervention is required." >> $OUTPUT
fi
}
echo "Last renewal happened on `date`" >| $OUTPUT
echo "$cn" >> $OUTPUT
echo "$alt" >> $OUTPUT
echo "$notbefore" >> $OUTPUT
echo "$notafter" | grep "Not After" >> $OUTPUT
echo "Installing files ..." >> $OUTPUT
for host in $hosts
do
install "$host" "$crt" "$destdir"
install "$host" "$key" "$destdir"
done
# do we really need this certificate on the webserver?
#install "$crt" "deriweb01" "$crtdest"
#install "$key" "deriweb01" "$keydest"
echo "Reloading services ..." >> $OUTPUT
reload "dericom01" "ergo"
#reload nginx deriweb01
echo "Initializing self-checks ... " >> $OUTPUT
check "irc.liberta.casa" "6697"
#check "katyusha.liberta.casa" "443"
echo "OK!" >> $OUTPUT
echo "IRC certificates have been renewed." | mail -s "[Certificate Deployment] $certname - `date`" $mailto < $OUTPUT