xref: /lighttpd1.4/doc/scripts/cert-staple.sh (revision 70b1af06)
1#!/bin/sh
2
3CERT_PEM="$1"   # input (cert.pem)
4CHAIN_PEM="$2"  # input (chain.pem)
5OCSP_DER="$3"   # output symlink (staple.der)
6
7OCSP_TMP=""     # temporary file
8
9if [[ -z "$CERT_PEM" ]] || [[ -z "$CHAIN_PEM" ]] || [[ -z "$OCSP_DER" ]] \
10   || [[ ! -f "$CERT_PEM" ]] || [[ ! -f "$CHAIN_PEM" ]]; then
11    echo 1>&2 "usage: cert-staple.sh cert.pem chain.pem staple.der"
12    exit 1
13fi
14
15function errexit {
16    [[ -n "$OCSP_TMP" ]] && rm -f "$OCSP_TMP"
17    exit 1
18}
19
20# get URI of OCSP responder from certificate
21OCSP_URI=$(openssl x509 -in "$CERT_PEM" -ocsp_uri -noout)
22[[ $? = 0 ]] && [[ -n "$OCSP_URI" ]] || exit 1
23
24# get OCSP response from OCSP responder
25OCSP_TMP="$OCSP_DER.$$"
26OCSP_RESP=$(openssl ocsp -issuer "$CHAIN_PEM" -cert "$CERT_PEM" -respout "$OCSP_TMP" -noverify -no_nonce -url "$OCSP_URI")
27[[ $? = 0 ]] || errexit
28
29# parse OCSP response from OCSP responder
30#
31#$CERT_PEM: good
32#        This Update: Jun  5 21:00:00 2020 GMT
33#        Next Update: Jun 12 21:00:00 2020 GMT
34
35ocsp_status="$(printf %s "$OCSP_RESP" | head -1)"
36[[ "$ocsp_status" = "$CERT_PEM: good" ]] || errexit
37
38next_update="$(printf %s "$OCSP_RESP" | grep 'Next Update:')"
39next_date="$(printf %s "$next_update" | sed 's/.*Next Update: //')"
40[[ -n "$next_date" ]] || errexit
41ocsp_expire=$(date -d "$next_date" +%s)
42
43# validate OCSP response
44ocsp_verify=$(openssl ocsp -issuer "$CHAIN_PEM" -cert "$CERT_PEM" -respin "$OCSP_TMP" -no_nonce -out /dev/null 2>&1)
45[[ "$ocsp_verify" = "Response verify OK" ]] || errexit
46
47# rename and update symlink to install OCSP response to be used in OCSP stapling
48OCSP_OUT="$OCSP_DER.$ocsp_expire"
49mv "$OCSP_TMP" "$OCSP_OUT" || errexit
50OCSP_TMP=""
51ln -sf "${OCSP_OUT##*/}" "$OCSP_DER" || errexit
52
53# debug: display text output of OCSP .der file
54#openssl ocsp -respin "$OCSP_DER" -resp_text -noverify
55
56# remove old OCSP responses which have expired
57now=$(date +%s)
58for i in "$OCSP_DER".*; do
59    ts="${i#${OCSP_DER}.}"
60    if [[ -n "$ts" ]] && [[ "$ts" -lt "$now" ]]; then
61        rm -f "$i"
62    fi
63done
64