Click here to Skip to main content
15,896,154 members
Articles / Desktop Programming / Win32
Article

SSL : Convert your Plain Sockets to SSL Sockets in an Easy Way

Rate me:
Please Sign up or sign in to vote.
4.83/5 (21 votes)
14 Mar 2008CPOL3 min read 248.7K   7K   55   82
A simple class that allows you to convert an existing SOCKET handle to SSL under Windows

Includes:

  • SSL class soucre files (SSL.CPP, Z.H, SSL.H)
  • Testing project TEL, telnet client and server with SSL ability.

Introduction

A lot of SSL stuff already exists, but it is in either MFC, NET or some other non-native format. Here is a simple class SSL_SOCKET that allows you to convert an existing SOCKET handle to SSL under Windows. I got much information from the great CSslSocket - SSL/TLS enabled CSocket MFC article, but I need a plain Win32 one

Features

  • x86 / x64 compatible.
  • HTML help.
  • Supports Server and Client.

License

Free, for any kind or freeware, shareware, commercial, or whateverware project, as long as you give me credit for the library in your 'about box' or your application's documentation.

Creating the SSL Client

First, create and connect your socket using the normal socket functions (socket(), and connect()). Then construct an SSL_SOCKET:

C++
// Say that X is a socket
SSL_SOCKET* SX = new SSL_SOCKET(X,0,0);

This creates an SSL_SOCKET object for an SSL_CLIENT. The last parameter to the constructor indicates that the object will create a tempora self-signed certificate to authenticate itself with the SSL server. If you want, you can pass your own PCERT_CONTEXT.

Next step is to call SSL_SOCKET::ClientInit()

C++
// Initialize the Security Session
sX->ClientInit();

This also calls SSL_SOCKET::ClientLoop() to initialize the SSL Session. (If you don't want to initialize the SSL session at this time, call ClientInit(true) and then later call ClientLoop()). Once the loop returns 0 (success), you can then use the following functions:

  • int SSL_SOCKET:: s_send(char* b, int sz); // Sends data, returns 0 or -1 on error (like normal send()).
  • int SSL_SOCKET:: s_ssend(char* b, int sz); // Sends data, returns 0 or -1 on error (like normal send()). Does not return until all the bytes have been sent or an error occurs.
  • int SSL_SOCKET:: s_recv(char* b, int sz); // Receives data, returns 0 or -1 on error (like normal recv()).
  • int SSL_SOCKET:: s_ssend(char* b, int sz); // Receives data, returns 0 or -1 on error (like normal recv()). Does not return until all the bytes have been received or an error occurs.

If you like, you can call also send_p, ssend_p, recv_p, rrecv_p to send/receive raw bytes (without messaging encryption/decryption), if you can encrypt/decrypt the stuff yourself.

Polite shutdown of the client connection is calling SSL_SOCKET :: ClientOff() before calling closesocket().

Creating the SSL Server

First, create and accept your socket using the normal socket functions (socket(), bind(), listen() and accept()). Then construct a SSL_SOCKET:

C++
// Say that X is a socket
SSL_SOCKET* SX = new SSL_SOCKET(X,1,0);

This creates an SSL_SOCKET object for a SSL_CLIENT. The last parameter to the constructor indicates that the object will create a tempora self-signed certificate to authenticate itself with the SSL server. If you want, you can pass your own PCERT_CONTEXT. Note that some clients will test the certificate and reject it or warn it, so you may want to pass a trusted certificate.

Next step is to call SSL_SOCKET::ServerInit()

C++
// Initialize the Security Session
sX->ServerInit();

This also calls SSL_SOCKET::ServerLoop() to initialize the SSL Session. (If you don't want to initialize the SSL session at this time, call ServerInit(true) and then later call ServerLoop()). Once the loop returns 0 (success), you can then use the send/recv functions discussed above.

Shutdown the server by calling SSL_Socket :: ServerOff().

Other Features

These are some features I'd like to implement in the future:

  • Certificate verification (not yet completed)
  • Documentation (SSL.CHM) is pending.

Please leave your questions and comments!

History

  • March 13, 2007 - Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Greece Greece
I'm working in C++, PHP , Java, Windows, iOS, Android and Web (HTML/Javascript/CSS).

I 've a PhD in Digital Signal Processing and Artificial Intelligence and I specialize in Pro Audio and AI applications.

My home page: https://www.turbo-play.com

Comments and Discussions

 
QuestionSome implementation missing Pin
dyvim18-Aug-11 23:05
dyvim18-Aug-11 23:05 
AnswerRe: Some implementation missing Pin
Michael Chourdakis19-Aug-11 9:16
mvaMichael Chourdakis19-Aug-11 9:16 
QuestionLink for Windows 7 version no longer works Pin
dyvim18-Aug-11 4:05
dyvim18-Aug-11 4:05 
AnswerRe: Link for Windows 7 version no longer works Pin
Michael Chourdakis19-Aug-11 9:14
mvaMichael Chourdakis19-Aug-11 9:14 
GeneralCorrection for buggy Microsoft TLS implimentation Pin
Member 371720410-Jun-11 10:57
Member 371720410-Jun-11 10:57 
GeneralRe: Correction for buggy Microsoft TLS implimentation Pin
cin197921-Mar-12 5:05
cin197921-Mar-12 5:05 
GeneralRe: Correction for buggy Microsoft TLS implimentation Pin
Member 371720421-Mar-12 23:11
Member 371720421-Mar-12 23:11 
GeneralCorrection of bug under Windows 7/Windows Server 2008 Pin
IDRASSI Mounir24-Oct-10 13:00
IDRASSI Mounir24-Oct-10 13:00 
Hi all,

The current source (and the more recent version at http://www.turboirc.com/temp/ssl.rar[^])doesn't work for TLS connections under Windows 7/Windows Server 2008 due to a bug in the way the function DecryptMessage is used.
Actually, the code, and specifically the method SSL_SOCKET::s_recv, doesn't handle correctly the case where DecryptMessage succeeds but returns an empty SECBUFFER_DATA buffer and a non-empty SECBUFFER_EXTRA. In this case, the code now simply returns 0 provoking a connection break, whereas it should loop in order to call DecryptMessage a second time to retrieve plain data.

Here is the corrected version of SSL_SOCKET::s_recv :
int SSL_SOCKET :: s_recv(char* b,int sz)
   {
   SecPkgContext_StreamSizes Sizes;
   SECURITY_STATUS ss = 0;
   ss = QueryContextAttributes(&hCtx,SECPKG_ATTR_STREAM_SIZES,&Sizes);
   if (FAILED(ss))
      return -1;

   int TotalR = 0;
   int pI = 0;
   SecBuffer Buffers[5] = {0};
   SecBuffer *     pDataBuffer;
   SecBuffer *     pExtraBuffer;
   Z<char> mmsg(Sizes.cbMaximumMessage*10);

   if (PendingRecvDataSize)
      {
      if (sz <= PendingRecvDataSize)
         {
         memcpy(b,PendingRecvData,sz);
         
         // 
         Z<char> dj(PendingRecvDataSize);
         memcpy(dj,PendingRecvData,PendingRecvDataSize);
         memcpy(PendingRecvData,dj + sz,PendingRecvDataSize - sz);
         PendingRecvDataSize -= sz;
         return sz;
         }
      // else , occupied already
      memcpy(b,PendingRecvData,PendingRecvDataSize);
      sz = PendingRecvDataSize;
      PendingRecvDataSize = 0;
      return sz;
      }

   for(;;)
      {
      unsigned int dwMessage = Sizes.cbMaximumMessage;
      
      if (dwMessage > Sizes.cbMaximumMessage)
         dwMessage = Sizes.cbMaximumMessage;

      int rval = 0;
      if (ExtraDataSize)
         {
         memcpy(mmsg + pI,ExtraData,ExtraDataSize);
         pI += ExtraDataSize;
         ExtraDataSize = 0;
         }
      else
         {
         rval = recv_p(mmsg + pI,dwMessage);
         if (rval == 0 || rval == -1)
            return rval;
         pI += rval;
         }

      Buffers[0].pvBuffer     = mmsg;
      Buffers[0].cbBuffer     = pI;
      Buffers[0].BufferType   = SECBUFFER_DATA;

      Buffers[1].BufferType   = SECBUFFER_EMPTY;
      Buffers[2].BufferType   = SECBUFFER_EMPTY;
      Buffers[3].BufferType   = SECBUFFER_EMPTY;

      sbin.ulVersion = SECBUFFER_VERSION;
      sbin.pBuffers = Buffers;
      sbin.cBuffers = 4;

      ss = DecryptMessage(&hCtx,&sbin,0,NULL);
      if (ss == SEC_E_INCOMPLETE_MESSAGE)
         continue;
      if (ss != SEC_E_OK && ss != SEC_I_RENEGOTIATE && ss != SEC_I_CONTEXT_EXPIRED)
         return -1;

      pDataBuffer  = NULL;
      pExtraBuffer = NULL;
      for (int i = 0; i < 4; i++) 
         {
         if (pDataBuffer == NULL && Buffers[i].BufferType == SECBUFFER_DATA) 
            {
            pDataBuffer = &Buffers[i];
            }
         if (pExtraBuffer == NULL && Buffers[i].BufferType == SECBUFFER_EXTRA) 
            {
            pExtraBuffer = &Buffers[i];
            }
         }
      if (pExtraBuffer)
         {
         ExtraDataSize = pExtraBuffer->cbBuffer;
         ExtraData.Resize(ExtraDataSize + 10);
         memcpy(ExtraData,pExtraBuffer->pvBuffer,ExtraDataSize);
         pI = 0;
         }

      if (ss == SEC_I_RENEGOTIATE)
         {
         ss = ClientLoop();
         if (FAILED(ss))
            return -1;
         }   

      if (pDataBuffer == 0)
         break;
      else if ( (pDataBuffer->cbBuffer == 0) && ExtraDataSize)
         {
         // BUG under Windows 7/Server 2008
         // DecryptMessage needs to be called a second time
         // in order to get the plain data
         continue;
         }         

      TotalR = pDataBuffer->cbBuffer;
      if (TotalR <= sz)
         {
         memcpy(b,pDataBuffer->pvBuffer,TotalR);
         }
      else
         {
         TotalR = sz;
         memcpy(b,pDataBuffer->pvBuffer,TotalR);
         PendingRecvDataSize = pDataBuffer->cbBuffer - TotalR;
         PendingRecvData.Resize(PendingRecvDataSize + 100);
         PendingRecvData.clear();
         memcpy(PendingRecvData,(char*)pDataBuffer->pvBuffer + TotalR,PendingRecvDataSize);
         }
      break;
      }
   return TotalR;
   }


I hope this will help.

Cheers,
--
Mounir IDRASSI
IDRIX
http://www.idrix.fr[^]
GeneralRe: Correction of bug under Windows 7/Windows Server 2008 Pin
Michael Chourdakis25-Oct-10 4:46
mvaMichael Chourdakis25-Oct-10 4:46 
GeneralMessage Closed Pin
28-Jan-22 0:37
Member 1526517628-Jan-22 0:37 
GeneralProblem with Windows 7 Pin
ksutariya14-Oct-10 1:09
ksutariya14-Oct-10 1:09 
QuestionCould i use this on mobile? Pin
latell12-Oct-10 21:10
latell12-Oct-10 21:10 
AnswerRe: Could i use this on mobile? Pin
Michael Chourdakis13-Oct-10 19:11
mvaMichael Chourdakis13-Oct-10 19:11 
GeneralVerifySessionCertificate Pin
Mark Tutt17-Jun-10 4:32
Mark Tutt17-Jun-10 4:32 
GeneralRe: VerifySessionCertificate Pin
Michael Chourdakis17-Jun-10 4:54
mvaMichael Chourdakis17-Jun-10 4:54 
GeneralRe: VerifySessionCertificate Pin
Mark Tutt17-Jun-10 5:31
Mark Tutt17-Jun-10 5:31 
GeneralRe: VerifySessionCertificate Pin
Michael Chourdakis17-Jun-10 6:59
mvaMichael Chourdakis17-Jun-10 6:59 
GeneralWindows 7 Pin
Ville Kangas7-Apr-10 7:48
Ville Kangas7-Apr-10 7:48 
GeneralRe: Windows 7 Pin
Michael Chourdakis7-Apr-10 8:13
mvaMichael Chourdakis7-Apr-10 8:13 
GeneralRe: Windows 7 Pin
fvalerin10-May-13 12:50
fvalerin10-May-13 12:50 
QuestionQuestions about: AcquireCredentialsHandle Pin
piecesofcheese5-Mar-10 9:19
piecesofcheese5-Mar-10 9:19 
GeneralDocumentation Pin
vitorsei29-Oct-09 3:46
vitorsei29-Oct-09 3:46 
QuestionFor Mobile ??? Pin
STentando8-Sep-09 7:44
STentando8-Sep-09 7:44 
AnswerRe: For Mobile ??? Pin
Rett Pop14-Feb-10 5:43
Rett Pop14-Feb-10 5:43 
GeneralSSL Delay Pin
BeerFizz31-Jul-09 6:52
BeerFizz31-Jul-09 6:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.