Reputation: 396
Currently I'm working on some basic OpenSSL. I'm confused about the basic behavior of SSL_write and SSL_read. In the documentation it is not clearly explained how the data is encrypted / decrypted. What I mean? Is the SSL_write, once the SSL_CTX is set and file descriptor assigned, by default encrypting the data or calling the encryption function, or does this have to be done by hand? Do I have to call some encryption function explicitly? Is the same true for the SSL_read? I need a deeper understanding of what SSL_write / read do automatically and what not, or sources where I can fall back to if I'm having issues.
Here is an example that I'm working with.
Example:
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
Servlet calls
void Servlet(SSL* ssl)
{
char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
ShowCerts(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
SSL_write(ssl, reply, strlen(reply)); /* send reply */
}
else
ERR_print_errors_fp(stderr);
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
Upvotes: 0
Views: 772
Reputation: 123270
Do I have to call some encryption function explicitly, is the same true for the SSL_read?
No. Encryption is handled within SSL_write
automatically as is decryption in SSL_read
. Both use the SSL
structure which contains the necessary encryption keys once the TLS handshake is finished.
... sources where I can fall back to if I'm having issues
This depends on the issues you have. Both SSL_read
and SSL_write
have documentation. There are also easy to find examples. Being able to use a search engine helps also a lot to find more information. And StackOverflow is a good place to get help if things don't work as expected.
Upvotes: 3