I would want my C/C++ client to authenticate the server via SSL.
I first downloaded the certificate file from the server with
openssl s_client -showcerts -connect www.openssl.org:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > mycertfile.pem
Then in my application I do the following API invocations (pseudo code):
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
// New context saying we are a client, and using SSL 2 or 3
ctx = SSL_CTX_new(SSLv23_client_method());
// load the certificate
if(!SSL_CTX_load_verify_locations(ctx, "mycertfile.pem", 0))
...
// Create an SSL struct for the connection
ssl = SSL_new(ctx);
// Connect the SSL struct to our pre-existing TCP/IP socket connection
if (!SSL_set_fd(ssl, sd))
...
// Initiate SSL handshake
if(SSL_connect(ssl) != 1)
...
// form this point onwards the SSL connection is established and works
// perfectly, I would be able to send and receive encrypted data
// **Crucial point now**
// Get certificate (it works)
X509 *cert = SSL_get_peer_certificate(ssl);
if(cert) {
// the below API returns code 19
const long cert_res = SSL_get_verify_result(ssl);
if(cert_res == X509_V_OK) {
printf("Certificate verified!\n");
}
X509_free(cert);
}
Above code works fine if I don't mind checking the certificate and I'm just interested in an encrypted connection.
Problem with it is that when I try to verify the authenticity of the server, I do get the certificate from SSL_get_peer_certificate
but then the verification of results doesn't work even if I've just downloaded the certificate 5 minutes before.
What am I doing wrong?
All this is on Ubuntu 12.04.03 x86-64 with gcc and openssl.
Thanks, Ema