RatDon
RatDon

Reputation: 3543

SSL_connect succeeding but returning -1

I'm trying to do a https connection over TLSv1.2. Context creation and everything is fine which I've not included in the below code.

if(https)    //block 1
{
   int ssl_err = 0;
   int ssl_rc = 0;
   ssl_fd = SSL_new(ctx);   /* create new SSL connection state */
   if(ssl_fd)    //block 2
   {
       printf("Failure in SSL state creation.");
       ssl_err = -1;
   }
   if(ssl_err == 0)    //block 3
   {
       SSL_set_fd(ssl_fd, fd);   /* attach the socket descriptor */
       ERR_clear_error();
       ssl_rc = SSL_connect(ssl_fd);   /* perform the connection*/
       printf("Failure in SSL connection %d returned.\n", ssl_rc);
       if ( ssl_rc == -1 )    //block 4
           ssl_err = -1;
   }
   if ( ssl_err == -1 )    //block 5
   {
       printf("Failure in SSL connection.\n");
       SSL_free(ssl_fd);
       shutdown(fd, 2);
       abort();
   }
}

In the code above, it's showing output as

Failure in SSL connection -1 returned.
Failure in SSL connection.

I've checked the packets file. Immediately (in 200 microseconds) after sending the client hello, it is going to if block 5 and sending a FIN request which kept me worried to find the error which I couldn't as without server's response, the SSL_connect is returning with error.

I commented if block 5 and tested. To my surprise, since the shutdown is not called, the SSL handshake is happening and data transfer over TLSv1.2 is going on till the end. That means SSL_connect is actually succeeding but somehow it's happening async. But in this way, I can't report if actually there is some errors in the SSL handshaking.

Can anyone help me with this behaviour?
Whether it's actually doing the handshake asynchronously? If yes, why it's returning -1 immediately. Shouldn't it wait for the handshake to complete before putting -1?

Upvotes: 0

Views: 458

Answers (1)

Pras
Pras

Reputation: 4044

As you mentioned you have non-blocking sockets. In that case if SSL_connect() returns -1you need to call SSL_get_error(), check what it returns SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, then call SSL_connect() again after checking the underlying socket is ready for read/write with select()

Upvotes: 3

Related Questions