0

The following command prints the SHA1 Fingerprint of the host mentioned

openssl s_client -connect hostname:port | openssl x509 -fingerprint -noout

To do the same action to be done using c++, I am using ssl API

#include"openssl/ssl.h"
#include"openssl/bio.h"
#include "openssl/err.h"

#include<iostream>

using namespace std;

int main()
{    
    SSL_CTX * ctx = SSL_CTX_new(SSLv23_client_method());
    SSL * ssl;
    BIO * bio;

    SSL_library_init();

    bio = BIO_new_ssl_connect(ctx);

    BIO_set_conn_hostname(bio, "hostname:port");//Correct hostname and port is used

    if(BIO_do_connect(bio) <= 0)
    {
        cout << "success";
    }
    BIO_get_ssl(bio, & ssl);

    X509 *x509 = NULL;

    x509 = SSL_get_certificate( ssl );//Crashing point

    return 1;
}

The Application crashes in

x509 = SSL_get_certificate( ssl );

Any Idea why it crashes?

arumuga abinesh
  • 111
  • 1
  • 7
  • Also see the example [TLS Client](http://wiki.openssl.org/index.php/SSL/TLS_Client) on the OpenSSL wiki. – jww Sep 04 '14 at 17:06

1 Answers1

1

Quoting from the manpage:

BIO_do_connect() attempts to connect the supplied BIO. It returns 1 if the connection was established successfully. A zero or negative value is returned if the connection could not be established,...

However, your code checks for a zero or negative value and then wrongly prints "success" and continues. As a consequence, BIO_get_ssl(bio, & ssl); most probably fails and leaves ssl pointing to NULL, leading to a crash in the next line.

oxygene
  • 621
  • 4
  • 14