summaryrefslogtreecommitdiffstats
path: root/scripts/certificate_hook.sh
blob: 7d84ed972399f15163cb6e7000d698f2e52e4103 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/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