Skip to content

Instantly share code, notes, and snippets.

@ykzts
Last active August 10, 2017 06:51
Show Gist options
  • Save ykzts/2afffd5ca7362ee5084ef87e0fdeef73 to your computer and use it in GitHub Desktop.
Save ykzts/2afffd5ca7362ee5084ef87e0fdeef73 to your computer and use it in GitHub Desktop.
#! /bin/sh
# based on https://github.com/h2o/h2o/blob/v2.2.2/share/h2o/fetch-ocsp-response
usage() {
cat <<EOT
Usage: $0 [<options>] <certificate-file>
Options:
--issuer <file> issuer certificate (if omitted, is extracted from the
certificate chain)
--openssl <cmd> openssl command to use (default: "openssl")
--help prints this help
The command issues an OCSP request for given server certificate, verifies the
response and prints the resulting DER.
The command exits 0 if successful, or 75 (EX_TEMPFAIL) on temporary error.
Other exit codes may be returned in case of hard errors.
EOT
exit 0
}
main() {
local cert_fn issuer_fn openssl_cmd=openssl
while [ "$1" != "" ]; do
case $1 in
--issuer)
issuer_fn=$2
shift
;;
--openssl)
openssl_cmd=$2
shift
;;
-*)
usage
;;
*)
cert_fn=$1
esac
shift;
done
if [ "$cert_fn" = "" ]; then
echo no certificate file > /dev/stderr
exit 1
fi
local openssl_version=$($openssl_cmd version)
echo $openssl_version
local ocsp_uri=$($openssl_cmd x509 -in $cert_fn -noout -ocsp_uri)
if [ "$ocsp_uri" = "" ]; then
echo failed to extract ocsp URI from $cert_fn
exit 1
fi
local ocsp_host=$(echo $ocsp_uri | sed -e 's/^https\{0,1\}:\/\/\([^/]*\)/\1/')
if [ "$issuer_fn" = "" ]; then
echo todo
fi
echo sending OCSP request to $ocsp_uri > /dev/stderr
local resp
resp=$($openssl_cmd ocsp \
-issuer $issuer_fn \
-cert $cert_fn \
-url $ocsp_uri \
-header Host $ocsp_host \
-noverify \
-respout $TMPDIR/resp.der)
echo "$resp" > /dev/stderr
if echo "$resp" | grep "Responder Error:"; then
echo responder returned error > /dev/stderr
exit 1
fi
echo verifying the response signature > /dev/stderr
local success
local original_ifs=$IFS
IFS=$'\n'
for args in $(cat <<EOT); do
-VAfile $issuer_fn
-partial_chain -trusted_first -CAfile $issuer_fn
-CAfile $issuer_fn
EOT
if eval "$openssl_cmd ocsp -respin $TMPDIR/resp.der $args" > $TMPDIR/verify.out 2>&1; then
if cat $TMPDIR/verify.out | grep "Response Verify Failure"; then
cat $TMPDIR/verify.out > /dev/stderr
echo try next verify argument options > /dev/stderr
continue
fi
echo "verify OK (used: $args)" > /dev/stderr
success=1
break
fi
done
IFS=$original_ifs
if [ "$success" != 1 ]; then
cat $TMPDIR/verify.out > /dev/stderr
echo failed to verify the response > /dev/stderr
exit 75
fi
cat $TMPDIR/resp.der
exit 0
}
main $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment