I recently wanted to build my own client-server system by using BSD sockets. After some point I wanted to include SSL to encrypt the data transfer. I followed this tutorial and the code compiles fine with Xcode (added linker flags: -lssl -lcrypto), but I keep getting EXC_BAD_ACCESS all the time once the program reaches the SSL_CTX_use_certificate_file() call. You can see the used code below.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
int main(int argc, const char * argv[])
{
SSL_METHOD *method = NULL;
SSL_CTX *ctx = NULL;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = SSLv2_server_method();
ctx = SSL_CTX_new(method);
SSL_CTX_use_certificate_file(ctx, "/Users/steve/certificate.pem", SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx, "/Users/steve/key.pem", SSL_FILETYPE_PEM);
printf("Hello, World!\n");
return EXIT_SUCCESS;
}
If the program can’t find the certificate at the specified path it doesn’t crash but I wont have any SSL encryption of course. Could there be a problem with the certificate itself? I simply generated one with openssl by using the following commands:
# generate the key
$ openssl genrsa -out key.pem 1024
# generate request
$ openssl req -new -key key.pem -out request.pem
# fill in all the stuff ...
# generate certificate
$ openssl x509 -req -days 30 -in request.pem -signkey key.pem -out certificate.pem
Any idea?
Update: There actually are some warnings showing up when compiling with the OS X Deployment Target set to 10.7 or later, because all of this SSL stuff shows up as deprecated. Are there any recommended alternative practices to secure sockets with SSL?
The problem is that you need to call
SSL_library_init, see the modification inside the code (It’s also a good practice to always handle errors from functions that we call :-):