Verify pem certificate chain using openssl

certificateopensslSecuritysslssl-certificate

I am trying to write a code which receives a pcap file as an input and returns invalid certificates from it.

I have parsed certificate chains, and I'm trying to verify them.
Because I get the certificates chains out of a pcap the chain length are not constant (sometimes they includes only 1 certificate that is selfsigned (and valid)).

Let cert0.pem be the servers certificate and certk.pem the root CAs certificate.

According to my research online I'm trying to verify the certificate as follows:

  1. Create a file certs.pem which contains the certificate chain in the order:
    certk.pem, certk-1.pem,… ,cert0.pem

  2. use the command (ca.pem is a file containing root certificates):

    openssl verify -CAfile ca.pem certs.pem 
    

But sometimes the verification goes wrong even for valid certificates, as in the following output:

C = US, O = GeoTrust Inc., CN = GeoTrust Global CA <br>
error 20 at 0 depth lookup: unable to get local issuer certificate<br> 
error certs.pem: verification failed

please help me, how can I verify the certificate chain ?

Additionally is there a way to add a host name verification in the same line? (I have tried to add "-verify_hostname name" but again, the output was unexpected).

Best Answer

For remote certificate validation the error you mentioned here says that the first local certificate (depth 0) in your chain file that you are trying to verify namely being certk.pem as root CA certificate has to exist / imported in your local client trusted certificates store that you are performing your verification from.

As stated at thawte.com support site:

This is the verification output of the Server Certificate sent by the server. The server sends its complete chain consisting of 2 certificates, one (depth 0) being the server's certificate "CN=www.yourdomain.com" and the other one being the CA certificate "CN=Thawte Server CA". As all root certificates, this certificate is self-signed.

In order to avoid this error, your client must have a local copy of the root CA certificate in their trusted certificate store, either in CAfile of CApath.

ALSO: Consider using -show_chain verify option to view more details and/or errors in your certificate chain. Note that this error behavior is expected and by default when verifying a certificate from a non-trusted CA. You can check for the error codes in the openssl wiki.