2

My objective is to test whether a certain root certification authority is trusted by the active user. I currently have a working solution that I managed to piece together using several other answers1,2, but it seems very convoluted to me, so I'm asking for alternative (or at least, simplified) suggestions from people who (unlike me) know what they're doing.

I am assuming that this will be executed by a non-privileged user (i.e. one that cannot install new packages), so I would like to use utilities that are likely bundled with most unix/linux distros (unlike e.g. certutil). For this reason, the current solution uses awk, grep and openssl, which seem quite universal.

Another thing I should note is that I'm not concerned with the possible security implications that might arise from testing certificates the way I do.

Here's my current code:

awk -v cmd='openssl x509 -noout -issuer' '/BEGIN/{close(cmd)};{print | cmd}'
   < /etc/ssl/certs/ca-certificates.crt 
   | grep -F 'issuer=C = US, O = company, CN = localhost, OU = engineering'

It uses awk in conjunction with openssl to iterate over all existing certificates, outputting their Issuer, then piping it to grep to test whether the required line exists.

The output I'm getting in the case of a positive match is the string I'm looking for, even though all I need is a binary answer (true/false, yes/no, 1/0, ...).

Any suggestion on how to achieve my goal in a simpler and/or more universal fashion?

Dev-iL
  • 22,722
  • 7
  • 53
  • 89

1 Answers1

2

You can spare the call to awk by processing all the certificates using openssl alone. According to this answer on Server Fault the following will use an intermediate conversion to provide the same amount of information (i.e. the issuer for each certificate in the input file) which can be filtered for the data you're looking for:

openssl crl2pkcs7 -nocrl -certfile /etc/ssl/certs/ca-certificates.crt \
   | openssl pkcs7 -print_certs -noout \
   | grep '^issuer=/C=US/O=company/CN=localhost/OU=engineering'

I find this an improvement because it doesn't use a bulky call to awk (which would also be another dependency), and the output of pkcs7 seems much more machine-readable than the whitespace-ridden original output from x509.

Note that you can use the return value of the above grep call to tell whether the given root CA is trusted:

openssl crl2pkcs7 -nocrl -certfile /etc/ssl/certs/ca-certificates.crt \
   | openssl pkcs7 -print_certs -noout \
   | grep -q '^issuer=/C=US/O=company/CN=localhost/OU=engineering' && echo 'Certificate found!'
Andras Deak
  • 27,857
  • 8
  • 66
  • 96