Ravi Chandra
Ravi Chandra

Reputation: 21

How to Get Peer certificate using SSL_CTX object

My intention is to verify OU ("Organizational unit") in peer certificate. Using libCurl for HTTPs client.

I have SSL_CTX object with me during HTTPs client session, which is received from callback function registered to "CURLOPT_SSL_CTX_FUNCTION" How do I get Peer certificate (Server's ceritificate) from SSL_CTX?

Here is the C# code I am trying to implement in C:

Easy.SSLContextFunction sf = new Easy.SSLContextFunction(SSLContextFunctionCallback);
curlCode = easy.SetOpt(CURLoption.CURLOPT_SSL_CTX_FUNCTION, sf); 
...

CURLcode SSLContextFunctionCallback(SSLContext ctx, object extraData) 
{
    CURLcode retCode = CURLcode.CURLE_OK;
    IntPtr context = ctx.Context;
    retCode = ApsVerifyPeer(context); return retCode; 
}

I need to implement ApsVerifyPeer function in C/C++ to read peer certificate and verify OU field in certificate, where I have SSL context (SSL_CTX). Could you share your thoughts.

Upvotes: 2

Views: 3509

Answers (1)

jww
jww

Reputation: 102426

How do I get Peer certificate (Server's ceritificate) from SSL_CTX?

You get it from the SSL*, and not the SSL_CTX* object. That's because its specific to the connection or session.

You use SSL_get_peer_certificate to retrieve the peer certificate for the connection or session.

Note that the X509* returned can be NULL if the peer did not use a certificate (like with a server and an anonymous protocol).

If you do get a X509* back, then be sure to call X509_free on it. The X509 object is reference counted, and it will leak memory otherwise (I've ssen a lot of these leaks over the years because folks were not aware its reference counted).


My intention is to verify OU ("Organizational unit") in peer certificate

I think you have to be careful here. The OU is not guaranteed to be unique. I think the only guarantee is it will be unique within an organization at its level in the DIT tree. That is, within an organization its guaranteed you will find no more than one OU for "Technology" at level 1 (and you can find another at level 2). However, two different organizations, each with an OU of "Technology," will produce at least one incorrect result that you won't detect.

I think you need to use the {Issuer DN, Cert SerialNumber} pair because its unique. You might be able to use the KEYIDs - that is, the {Issuer Key Id, Subject Key Id}, but you have to be careful because the same subject public key can be used in multiple certificates.

You might also be able to use the Subject DN, but its probably only going to be unique within one particular PKI. So you might be able to get away with {Issuer DN, Subject DN} pairs.

And all of this is predicated on a path that chains back to something you trust.

You might want to read RFC 4158, Internet X.509 Public Key Infrastructure: Certification Path Building. It talks about these sorts of things.

Upvotes: 2

Related Questions