Home > Articles > Security > Network Security

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Writing a Secure Client

Writing an SSL client that connects to a secure server is very similar, changing only a few lines of the client code. The server is easier to build first, because you can test it with standard browsers. On the other hand, you have to use a working SSL server (typically custom-built) to verify client functionality. Some parts appear to be identical to the server's equivalent, but note the single difference (in bold).

SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();   /* load & register cryptos */
SSL_load_error_strings();     /* load all error messages */
method = SSLv2_client_method();   /* create client instance */
ctx = SSL_CTX_new(method);         /* create context */

The only difference is the call to make a client instance using SSLv2_client_method(). After setting up the SSL library, you need to create the socket. Again, the client socket code is essentially a standard TCP socket that finds and connects to a server.

/*---Standard TCP Client---*/
int sd;
struct hostent *host;
struct sockaddr_in addr;

host = gethostbyname(hostname); /* convert hostname ‡ IP addr */
sd = socket(PF_INET, SOCK_STREAM, 0);  /* create TCP socket */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);     /* set the desired port */
addr.sin_addr.s_addr = *(long*)(host->h_addr); /* and address */
connect(sd, (struct sockaddr*)&addr, sizeof(addr));/* connect */

At this point, the client has succeeded in connecting to the TCP side of the server. Like the server, it must perform the SSL handshaking to complete the transition to a secure channel. The client's handshaking code changes only the last line of the server's code. The client uses the counterpart to SSL_accept(), called SSL_connect().

SSL *ssl;
ssl = SSL_new(ctx);    /* create new SSL connection state */
SSL_set_fd(ssl, server);   /* attach the socket descriptor */
SSL_connect(ssl);          /* perform the connection */
SSL_free(ssl);              /* release SSL state */

During the session, the client uses SSL_read()/SSL_write(), and when done it releases the session resources with SSL_free().

  • + Share This
  • 🔖 Save To Your Account