+# grep issuer cert uri from certificate
+get_issuer_cert_uri() {
+ certificate="${1}"
+ openssl x509 -in "${certificate}" -noout -text | (grep 'CA Issuers - URI:' | cut -d':' -f2-) || true
+}
+
+# walk certificate chain, retrieving all intermediate certificates
+walk_chain() {
+ local certificate
+ certificate="${1}"
+
+ local issuer_cert_uri
+ issuer_cert_uri="${2:-}"
+ if [[ -z "${issuer_cert_uri}" ]]; then issuer_cert_uri="$(get_issuer_cert_uri "${certificate}")"; fi
+ if [[ -n "${issuer_cert_uri}" ]]; then
+ # create temporary files
+ local tmpcert
+ local tmpcert_raw
+ tmpcert_raw="$(_mktemp)"
+ tmpcert="$(_mktemp)"
+
+ # download certificate
+ http_request get "${issuer_cert_uri}" > "${tmpcert_raw}"
+
+ # PEM
+ if grep -q "BEGIN CERTIFICATE" "${tmpcert_raw}"; then mv "${tmpcert_raw}" "${tmpcert}"
+ # DER
+ elif openssl x509 -in "${tmpcert_raw}" -inform DER -out "${tmpcert}" -outform PEM 2> /dev/null > /dev/null; then :
+ # PKCS7
+ elif openssl pkcs7 -in "${tmpcert_raw}" -inform DER -out "${tmpcert}" -outform PEM -print_certs 2> /dev/null > /dev/null; then :
+ # Unknown certificate type
+ else _exiterr "Unknown certificate type in chain"
+ fi
+
+ local next_issuer_cert_uri
+ next_issuer_cert_uri="$(get_issuer_cert_uri "${tmpcert}")"
+ if [[ -n "${next_issuer_cert_uri}" ]]; then
+ printf "\n%s\n" "${issuer_cert_uri}"
+ cat "${tmpcert}"
+ walk_chain "${tmpcert}" "${next_issuer_cert_uri}"
+ fi
+ rm -f "${tmpcert}" "${tmpcert_raw}"
+ fi
+}
+