SSL handshake with a web server using Memory BIOs?

doa379 doa379 at
Mon Oct 25 20:45:38 UTC 2021

Suppose the TLS layer is initialized in the form:

  SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  BIO *r = BIO_new(BIO_s_mem());
  BIO *w = BIO_new(BIO_s_mem());
  SSL *ssl = SSL_new(ctx);
  SSL_set_bio(ssl, r, w);

I want to use BIO so that I can control IO to/from the TCP layer 
underneath using standard system-esque calls (connect(), 
read(), write() on a socket fd).

The transfer itself is carried out through SSL_write() then followed by 
BIO_read(), and BIO_write() followed by SSL_read() in/from the 
respective BIO *w, *r.

This is all fine and dandy but how should the manual handshake be 

Something akin to:

  char buffer[1024];
  while (!SSL_is_init_finished(ssl))
    int nbytes;
    if ((nbytes = BIO_read(w, buffer, sizeof buffer)) > 0)
      write(fd, buffer, nbytes);
    else if ((nbytes = read(fd, buffer, sizeof buffer)) > 0)
      BIO_write(r, buffer, nbytes);

Such a handshake can be put in wherever the server/client needs to 
connect, eg called during initialization.

The handshake works fine when the client-server is on a localhost. 
However when connecting to a web server the handshake takes long to 
return and doesn't do the handshake either. So the question is, what 
further provisions need to be made to connect to a non-local web server? 
Or perhaps the above handshake should be integral to BIO_write() and 
BIO_read() calls. I'm not sure, I have not looked at the actual 
library sources as what SSL_() precisely does. Anyone care to send some 
info my way in this particular case..?

More information about the openssl-users mailing list