Keychain – Why Are Some Certificates Missing?

keychainssl

I seem to have a certificate in the keychain that is only sometimes output correctly from security find-certificate on the command line:

security find-certificate -a -p | openssl x509 -text | grep -i comodo

The manual claims that this "Exports all certificates from all keychains". Specifying the system root keychain is no help:

security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain | openssl x509 -text | grep -i comodo

Adding a query suddenly produces a result:

security find-certificate -a -p -c comodo /System/Library/Keychains/SystemRootCertificates.keychain | openssl x509 -text | grep -i comodo

The same query on "all keychains" has no result (this time an error from openssl because the input is now empty):

security find-certificate -a -p -c comodo | openssl x509 -text | grep -i comodo

What is going on?

Best Answer

This is due to a combination of two factors:

  1. Specifying the SystemRootCertificates.keychain is necessary, otherwise a personal keychain is used.
  2. openssl will not parse a stream of multiple keys into a stream of text.

The following runs openssl once per certificate and accomplishes what I was looking for:

security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain \
| awk '/-----BEGIN CERTIFICATE-----/ { cert = "" } \
       { cert = cert $0 "\n" } \
       /-----END CERTIFICATE-----/ { \
           openssl = "openssl x509 -text"; \
           print cert | openssl; \
           close(openssl) \
       }'