Bash: Examining each certificate in a yaml file using sed and openssl

YAML is a popular syntax for configuration, and it is common to have certificate definitions embedded in these files.

But since the cert is typically Base64 PEM encoded, it means you can’t easily view its attributes (subject, expiration date, etc) and so you are left with the manual task of copy-pasting it out, saving as .crt, and then opening with a cert viewer or openssl.

Using sed and openssl, you can easily pull these certs out and quickly look at the most critical properties.

Example YAML

Below is an abbreviated yaml we will use for this article, test.yml.  I have this same file (but with real Base64 PEM encoded certs) in github.

root:
  keya: aaa
  keyb: bbbb
  cert1: |
    -----BEGIN CERTIFICATE-----
    c1
    c2
    -----END CERTIFICATE-----
  anotherlevel:
    keyc: ccc
    cert2: |
      -----BEGIN CERTIFICATE-----
      c3
      c4
      -----END CERTIFICATE-----
    keyd: ddd

Pull out all certs

The first stage is to pull out all certificates, removing any space indentation.  All certs are sent to a single PEM file.

sed -ne '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' test.yml | sed 's/^\s*//' > allcerts.pem

Count number of certs

Next, we count the number of certs pulled.

certcount=$(grep -e "-----BEGIN CERTIFICATE-----" allcerts.pem | wc -l)

Use openssl to view each cert

Finally, we iterate through each cert saved, and use openssl to show the Subject and expiration date of each.

for index in $(seq 1 $certcount); do
  echo "==== cert $index"
  awk "/-----BEGIN CERTIFICATE-----/{i++}i==$index" allcerts.pem > $index.crt
  openssl x509 -in $index.crt -text -noout | grep -E "Subject:|Not After :"
  rm $index.crt
done

Here is the full script for parse_certs.sh found on my github.

 

REFERENCES

man page, sed

stackoverflow, sed to select lines between markers which may occur multiple times

stackoverflow, display only n’th match of grep

shellhacks, get ssl certificate from server site using openssl

stackexchange, grep lines between start and end pattern

serverfault, displaying remote ssl certificate using cli

 

NOTES

Getting cert chain of site

echo | openssl s_client -showcerts -servername google.com -connect google.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > certificate-chain.crt

verify that certificate and CA root are valid pairing

openssl verify -CAfile myCA.crt my.crt