Working with the OpenSSL library in c, what is the best way to load a complete certificate chain from a PEM file into memory? The input is a single PEM file with 1..n certificates concatenated, the output should be a STACK_OF(X509)*.
For single certificates, the easiest way to load them is as follows:
SSL_CTX *sslctx = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_use_certificate_file(sslctx, "certificate.pem", SSL_FILETYPE_PEM);
SSL *ssl = SSL_new(sslctx);
X509 *crt = SSL_get_certificate(ssl);
(error handling, resource freeing and reference counting omitted for clarity; using C99 syntax; “easy” meaning “avoiding lower level BIO and ASN.1 APIs”)
However, for complete certificate chains, SSL_CTX_use_certificate_chain_file() can be used to load them into the SSL_CTX and the first certificate can then be retrieved using SSL_get_certificate(), but there seems to be no API function to retrieve the rest of the certificate chain from an SSL context.
So what is the best way to load a certificate chain from a file?
The function
SSL_CTX_use_certificate_chain_fileputs the certificate intoSSL_CTX::certand all additional certificates in the chain (additional CA cetrificates) intoSSL_CTX::extra_certswhich type isSTACK_OF(X509)*, so to get your additional chain:I could not find any macro or function that can give you the
extra_cetsfield without accessing it directly inSSL_CTXstructure, but looking at the OpenSSL code they do access it directly everywhere.