Secure ssl socket

Secure ssl socket

Following code helps in converting a normal socket to secure socket where chats are secured with ssl.  send and recv calls to socket would be replaced with ssl_read and ssl_write calls.

In other words , chat won’t be in clear text to outside world and SSL will act as tunnel through which data is transported.

Server-side code :

SOCKET sock = socket(nFamily, nType, IPPROTO_IP);

if (INVALID_SOCKET != sock)

{

if (uOptions & SO_REUSEADDR)

{

// Inform Windows Sockets provider that a bind on a socket should not be disallowed

// because the desired address is already in use by another socket

BOOL optval = TRUE;

if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof( BOOL ) ) )

{

closesocket( sock );

return false;

}

}

// Associate a local address with the socket

SockAddrIn sockAddr;

sockAddr.CreateFrom(strHost, strServiceName, nFamily);

if ( SOCKET_ERROR == bind(sock, sockAddr, sockAddr.Size()))

{

closesocket( sock );

return false;

}

// Listen to the socket, only valid for connection socket

if (SOCK_STREAM == nType)

{

if ( SOCKET_ERROR == listen(sock, SOMAXCONN))

{

closesocket( sock );

return false;

}

}

SSL_CTX *ctx;

CRYPTO_malloc_init();                    // Initialize malloc, free, etc for OpenSSL’sFssl use

SSL_library_init();                      // Initialize OpenSSL’s SSL libraries

SSL_load_error_strings();         // Load SSL error strings

ERR_load_BIO_strings();                  // Load BIO error strings

OpenSSL_add_all_algorithms();     // Load all available encryption algorithms

SSL_METHOD* meth = (SSL_METHOD*)SSLv23_server_method();

ctx=SSL_CTX_new(SSLv23_server_method());

if ( ctx == NULL )

{

ERR_print_errors_fp(stderr);

abort();

}

/* set the local certificate from CertFile */

if ( SSL_CTX_use_certificate_file(ctx, “D:/work/ssl/ServerSocket_demo/ServerSocket/SSL/server.crt”, SSL_FILETYPE_PEM) <= 0 )

{

ERR_print_errors_fp(stderr);

abort();

}

/* set the private key from KeyFile (may be the same as CertFile) */

if ( SSL_CTX_use_PrivateKey_file(ctx, “D:/work/ssl/ServerSocket_demo/ServerSocket/SSL/private_key.pem”, SSL_FILETYPE_PEM) <= 0 )

{

ERR_print_errors_fp(stderr);

abort();

}

/* verify private key */

if ( !SSL_CTX_check_private_key(ctx) )

{

fprintf(stderr, “Private key does not match the public certificate\n”);

abort();

}

SetSSLContext(ctx);//Set m_sslCtx=ctx , so that can be retrived while reading or writing from socket

Sock=accept(sock, 0, 0); // waits for connect call from client

if (sock != INVALID_SOCKET)

{

SSL *ssl;

ssl = SSL_new(m_sslCtx);              /* get new SSL state with context */

SSL_set_fd(ssl, sock);

char buf[1024];

char reply[1024];

int  bytes;

const char* demoText=”<html><body><pre>%s</pre></body></html>\n\n”;

if ( SSL_accept(ssl) == -1 )     /* do SSL-protocol accept */

ERR_print_errors_fp(stderr);

else

{

/* 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,demoText, buf);   /* construct reply */

SSL_write(ssl, reply, strlen(reply)); /* send reply */

SetSSL(ssl);

}

else

ERR_print_errors_fp(stderr);

}

Client code :

SOCKET sock = socket(nFamily, nType, 0);

if (INVALID_SOCKET != sock)

{

// Associate a local address with the socket

SockAddrIn sockAddr;

if (false == sockAddr.CreateFrom(NULL, TEXT(“0”), nFamily))

{

closesocket( sock );

return false;

}

if ( SOCKET_ERROR == bind(sock, sockAddr, sockAddr.Size() ))

{

closesocket( sock );

return false;

}

sockAddr.CreateFrom( strDestination, strServiceName );

if (SOCKET_ERROR == connect( sock, sockAddr, sockAddr.Size()))

{

closesocket( sock );

return false;

}

SSL_library_init();

SSL_CTX *ctx;

OpenSSL_add_all_algorithms();  /* Load cryptos, et.al. */

SSL_load_error_strings();   /* Bring in and register error messages */

SSL_METHOD* meth = (SSL_METHOD*)SSLv23_client_method();

ctx=SSL_CTX_new(meth);

//ctx = SSL_CTX_new(meth);   /* Create new context */

if ( ctx == NULL )

{

ERR_print_errors_fp(stderr);

abort();

}

SetSSLContext(ctx);

SSL * ssl = SSL_new(ctx);      /* create new SSL connection state */

SSL_set_fd(ssl, sock);

char buf[1024];

int bytes;

if ( SSL_connect(ssl) == -1 )   /* perform the connection */

ERR_print_errors_fp(stderr);

else

{   char *msg = “Hello???”;

printf(“Connected with %s encryption\n”, SSL_get_cipher(ssl));

//ShowCertsClient(ssl);        /* get any certs */

SSL_write(ssl, msg, strlen(msg));   /* encrypt & send message */

bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */

buf[bytes] = 0;

printf(“Received: \”%s\”\n”, buf);

SetSSL(ssl);

}

Difference between SSL and TLS ?

TLS is just higher version of SSL . SSL 3.1 is renamed to TLS1.1 and SSL3.2 to TLS1.2 .

With every increase in version , security is further enhanced.

Related Article

4 thoughts on “Secure ssl socket”

    1. im trying to develop a secure ssl server with certs with openssl for my own application and learning purposes. any help would be
      greatly appreciated. something exactly like the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *