by under
Recently I wrote about how to use OpenSSL to connect to a plain data server, this time I’m modifying the same code to perform encrypted connections. Naturally this is more of an example for how to use the API than production ready code. It’s main purpose is to show the very small difference between using the library as I did last time and how that example can be altered to create a basic SSL client.
The essential changes to the code below are the replacement of the connection function ‘connect_unencrypted(host_and_port)‘ with ‘connect_encrypted(host_and_port, store_path, store_type, &ctx, &ssl)‘ and the introduction of the SSL cleanup step ‘SSL_CTX_free(ctx)‘. All other changes are purely cosmetic; which really shows how simple adding SSL to your application connections can be. Externally you need to provide the root CA certificate for the connection to be verified by. That’s it.
At this point I could warble through the connection function, but you should just read through it yourself and consult the SSL man pages. Note that there is a dreadful buffer overflow possibility in this code and no real error handling, just a bit of logging. This is to keep the example short and also because only you will know what valid handling should take place for each situation when you write your own code.
So take a look and enjoy. To try this out yourself:
Make sure that you have Firefox, GCC and OpenSSL (development sources and libraries) installed.
Copy the following code to a file called ‘main.c‘ in a directory that you will be playing around in.
Compile the code using ‘gcc main.c -o sslclient -lssl‘ if you are on Linux or ‘gcc main.c -o sslclient -lssl-lcrypto‘ if you are on OSX.
Select an SSL (https) web site to connect to and find the Root CA’s certificate name in the site’s certificate.
Either export the appropriate root CA from Firefox or obtain it directly from the CA online in pem format and copy it to a file ‘certificate.pem‘ in the same directory as the ‘sslclient‘ file.
Run the following command:
'./sslclient servername:443 "GET / \r\n\r\n" certificate.pem f e'
Source: