Home > Articles > Operating Systems, Server > Microsoft Servers

📄 Contents

  1. SSPI and Windows 2000 Security Architecture
  2. Sample Project: Using SSPI to Kerberize Applications
  3. Summary
  4. References
  • Print
  • + Share This
From the author of

Sample Project: Using SSPI to Kerberize Applications

In this SSPI sample project, we will define a few C++ classes to hide complexities of using SSPI and Kerberos to kerberize applications. As you will see, the classes are designed to facilitate the authentication and secure messaging in a socket-based client/server application. In our sample project, we follow the steps we outlined earlier on how to use SSPI. Note that all the code listings show parts of the C++ classes. While reading the code, keep in mind that error handling is often omitted for brevity. The complete project can be found on the companion CD-ROM.

Let's first look at the CKerberostop-level class. The constructor for this class loads the secur32.dll library, the default security provider, and then gets a pointer to the security provider function table, finds the Kerberos package, and uses the maximum token size of the package to initialize buffers used later during the authentication step. In Kerberos, SSP_NAME and KERB_PACKAGE are defined as secur32.dll and ker-beros, respectively, and SECURITY_ENTRYPOINTis set to InitSecurityInterface.

Listing 11-1 CKerberosClass

//-------------------------------------------------------------- 
// CKerberos - Constructor to load Kerberos package and
// initialize vars
//--------------------------------------------------------------
CKerberos::CKerberos() 
{ 
    FARPROC            pInit;
    SECURITY_STATUS    ss;
    PsecPkgInfo        pkgInfo;

    m_pInBuf = NULL;
    m_pOutBuf = NULL;	  
    m_hLib = NULL;	 
    // Load and initialize the default ssp
    //	 
    m_hLib = LoadLibrary (SSP_NAME);
    pInit = GetProcAddress (m_hLib, SECURITY_ENTRYPOINT);
    m_pFuncTbl = (PSecurityFunctionTable) pInit ();
    // Query for Kerberos package
    //
    ss = m_pFuncTbl->QuerySecurityPackageInfo (KERB_PACKAGE,
    Package may not exist", ss); 
    } 

    // Initialize vars
    //
    m_cbMaxToken = pkgInfo->cbMaxToken;
    m_pFuncTbl->FreeContextBuffer (pkgInfo); 
    m_pInBuf = (PBYTE) malloc (m_cbMaxToken);
    m_pOutBuf = (PBYTE) malloc (m_cbMaxToken);
    m_pkgName = KERB_PACKAGE;
    m_fHaveCtxtHandle = false;
    m_fHaveCredHandle = false;
    m_reqCtxtAttrs = 0; 
} 

We derive two classes from CKerberos: CKerberosClient and CKerberosServer. After loading the default security provider and setting up variables through the CKerberos constructor, each class's constructor calls the AcquireCredentialsHandle function to get a handle to the logged-on user's credentials. The first argument to this function is NULLbecause we want to use the credentials of the current logged-on user. We have to pass the name of the package we want to use-second argument-and the usage type to get the correct type of credentials. CKerberosClient uses SEKPKG_ CRED_OUTBOUND for the credential usage, whereas CKerberosServer uses SEKPKG_ CRED_BOTHto be able to do delegation if needed later. NULLis passed for arguments that are not used by the Kerberos package or that we are not interested in.

Listing 11-2 CKerberosClientClass

//--------------------------------------------------------------
// CKerberosClient - Constructor to get credential handles
//--------------------------------------------------------------
CKerberosClient::CKerberosClient(LONG ctxtAttrs)
{
    SECURITY_STATUS ss; 

    ss = m_pFuncTbl->AcquireCredentialsHandle (
             NULL, // Use current principal
             m_pkgName, // Set to "kerberos"
             SECPKG_CRED_OUTBOUND,
             NULL,
             NULL,
             NULL,
             NULL, 
             m_hCred, // Handle to the credentials
             m_credLifetime);
    if (SEC_E_OK != ss){
          throw CKerberosErr ("AcquireCredentialsHandle failed",
                    ss);
    }
    m_fHaveCredHandle = true;
    m_reqCtxtAttrs = ctxtAttrs; 
}

Both constructors of these derived classes take an argument that specifies the requested context attributes. The caller applications should use the appropriate context attributes flags when using these classes.

Listing 11-3 KerberosServerClass

//--------------------------------------------------------------
// CKerberosServer - Constructor to get credential handles 
//--------------------------------------------------------------
CKerberosServer::CKerberosServer(LONG ctxtAttrs) 
{
    SECURITY_STATUS ss; 

    ss = m_pFuncTbl->AcquireCredentialsHandle (
             NULL, // Use current user
             m_pkgName, // Set to "kerberos"
             SECPKG_CRED_BOTH,
             NULL,
             NULL,
             NULL,
             NULL, 
             m_hCred, // Handle to the credentials
             m_credLifetime
             ); 
    if (SEC_E_OK != ss){
          throw CKerberosErr ("AcquireCredentialsHandle failed",
                ss); 
    }

    m_reqCtxtAttrs = ctxtAttrs; 
    m_fHaveCredHandle = true; 
}

The Authenticate method of each class goes through the process of building the security token and sending it to the other side until the authentication is completed or failed. The security token is built by calling InitializeSecurityContext when in the CKerberosClient::Authenticate method. In the first call to InitializeSecurityContext, we do not use any input buffer, as there is no information received from the server to pass to this function yet. The client keeps calling this function until the return code specifies that there is no need to do so anymore. In subsequent calls to the function, we pass the security token we receive from the server in inSecBuffDesc. The security package uses the content of this buffer to build the security context and to authenticate the server if needed. The output buffer in outSecBuffDesc is the security token, under construction, we send to the server so that it can authenticate the client. By default, in Kerberos, the server authenticates the client. By requesting mutual authentication, a client is asking Kerberos to authenticate the server too. It is up to the client to terminate a connection if mutual authentication never took place, as shown in the following listing.

Listing 11-4 Client-Side Authentication

//-------------------------------------------------------------- 
// Authenticate - Authenticate the connection (client side) 
//                Target is the SPN of the service or the 
//                "domain\\username" of the service account
//--------------------------------------------------------------
void CKerberosClient::Authenticate(SOCKET s, SEC_CHAR *target)
{
    SECURITY_STATUS ss; 
    SecBufferDesc          outSecBufDesc; 
    SecBuffer        outSecBuf;
    SecBufferDesc          inSecBufDesc;
    SecBuffer        inSecBuf;
    BOOL                   done = false;
    DWORD                        cbIn;

    // prepare output buffer
    //
    outSecBufDesc.ulVersion = 0;
    outSecBufDesc.cBuffers = 1;
    outSecBufDesc.pBuffers = &outSecBuf;
    outSecBuf.cbBuffer = m_cbMaxToken;
    outSecBuf.BufferType = SECBUFFER_TOKEN;
    outSecBuf.pvBuffer = m_pOutBuf; 

    while (!done){
          ss = m_pFuncTbl->InitializeSecurityContext (
                           &m_hCred,
                           m_fHaveCtxtHandle ? &m_hCtxt : NULL,
                           target,
                           // context requirements
                           m_reqCtxtAttrs, 
                           0,      // reserved1
                           SECURITY_NATIVE_DREP,
                           m_fHaveCtxtHandle ? &inSecBufDesc : NULL, 
                           0, 
                           &m_hCtxt,
                           &outSecBufDesc,
                           &m_ctxtAttr,
                           &m_ctxtLifetime
                           );
          if (!SEC_SUCCESS (ss)){
               throw CKerberosErr ("InitializeSecurityContext
                                 failed", ss); 
          } 
          m_fHaveCtxtHandle = TRUE;
          done = !((SEC_I_CONTINUE_NEEDED == ss) ||
          (SEC_I_COMPLETE_AND_CONTINUE == ss)); 

          // Send to the server if we have anything to send
          //
          if (outSecBuf.cbBuffer){
              SendMsg (s, m_pOutBuf, outSecBuf.cbBuffer);
          }
          if (!done){
              RecvMsg (s, m_pInBuf, m_cbMaxToken, &cbIn);
          }
          // Prepare input buffer for next round
          //
          inSecBufDesc.ulVersion = 0;
          inSecBufDesc.cBuffers = 1;
          inSecBufDesc.pBuffers = &inSecBuf;
          inSecBuf.cbBuffer = cbIn;
          inSecBuf.BufferType = SECBUFFER_TOKEN;
          inSecBuf.pvBuffer = m_pInBuf;
          // Reset the size on output buffer. We reuse it.
          //
          outSecBuf.cbBuffer = m_cbMaxToken; 
        } 
    } 
    // Check if we did mutual attribute if requested.
    // CheckCtxtAttr throws an exception if the attribute
    // is not set
    if (m_reqCtxtAttrs & ISC_RET_MUTUAL_AUTH){
          CheckCtxtAttr (ISC_RET_MUTUAL_AUTH); 
    } 
}

As far as the server part is concerned, after a request is received from the client for authentication, the server starts the process by setting up the security buffers and calling the AcceptSecurityContext function. This is very similar to the client's Authenticatemethod. Note that both the client and the server Authenticatemethod take a socket argument as the first argument. The socket connection should be set up before using these methods by the caller applications. We use blocking sockets for simplicity.

We have defined an application-level protocol to send and to receive messages between the client and the server in our SendMsgand RecvMsgfunctions. In our simple protocol, which is suitable for TCP connections, we always send the size of the message first. See the sample code on the CD-ROM for more information on these functions and others not shown here.

Listing 11-5 Server-Side Authentication

//--------------------------------------------------------------
// Authenticate - Authenticate the connection (server side)
//--------------------------------------------------------------
void CKerberosServer::Authenticate(SOCKET s)
{ 
    SECURITY_STATUS    ss;
    SecBufferDesc            outSecBufDesc;
    SecBuffer          outSecBuf;
    SecBufferDesc            inSecBufDesc;
    SecBuffer          inSecBuf;
    BOOL                    done = false;
    DWORD                   cbIn;

    // Prepare output buffer
    //
    outSecBufDesc.ulVersion = 0;
    outSecBufDesc.cBuffers = 1;
    outSecBufDesc.pBuffers = &outSecBuf;
    outSecBuf.cbBuffer = m_cbMaxToken;
    outSecBuf.BufferType = SECBUFFER_TOKEN;
    outSecBuf.pvBuffer = m_pOutBuf; 
    while (!done){ 
         // Get the security buffer from the client 
         //
         RecvMsg (s, m_pInBuf, m_cbMaxToken, &cbIn);
         // prepare input buffer for second round 
         //
         inSecBufDesc.ulVersion = 0;
         inSecBufDesc.cBuffers = 1;
         inSecBufDesc.pBuffers = &inSecBuf;
         inSecBuf.cbBuffer = cbIn;
         inSecBuf.BufferType = SECBUFFER_TOKEN;
         inSecBuf.pvBuffer = m_pInBuf;
        // Reset the size on output buffer. We reuse it.
        //
         outSecBuf.cbBuffer = m_cbMaxToken; 

         ss = m_pFuncTbl->AcceptSecurityContext (
                &m_hCred,
                m_fHaveCtxtHandle ? &m_hCtxt : NULL,
                &inSecBufDesc,
                m_reqCtxtAttrs,
                SECURITY_NATIVE_DREP, 
                &m_hCtxt,
                &outSecBufDesc,
                &m_ctxtAttr,
                &m_ctxtLifetime
                );
         if (!SEC_SUCCESS (ss)){
               throw CKerberosErr ("AcceptSecurityContext failed",
                       ss);
         }
         m_fHaveCtxtHandle = TRUE;
         done = !((SEC_I_CONTINUE_NEEDED == ss) ||
                 (SEC_I_COMPLETE_AND_CONTINUE == ss)); 
         // Send to the client if we have anything to send 
         //
         if (outSecBuf.cbBuffer){
            SendMsg (s, m_pOutBuf, outSecBuf.cbBuffer);
         }
    }
} 

After establishing a secure connection, the client and the server can start exchanging secure messages. The CKerberos class defines four methods for secure messaging: SendSignedMsg, RecvSignedMsg, SendEncryptedMsg, and RecvEncryptedMsg. These methods should be used only if appropriate flags are passed to the constructors; otherwise, exceptions are raised.

To sign a message, two security buffers need to be allocated: one to keep the message and one for the signature itself. The size of the buffer needed to keep the signature is specified in the SECPKG_ATTR_SIZES structure, which we query by using the QuerySecurityAttributesfunction.

Listing 11-6 Sending a Signed Message

//-------------------------------------------------------------- 
// SendSignedMsg - Send a signed message. First send the message
// and then the signature.
//--------------------------------------------------------------
void CKerberos::SendSignedMsg (SOCKET s, PBYTE pBuf,
DWORD cbBuf)
{
   SECURITY_STATUS           ss;
   SecPkgContext_Sizes       ctxtSizes;
   SecBufferDesc             secBufDesc;
   SecBuffer                 secBufs[2];

   ss = m_pFuncTbl->QueryContextAttributes(
               &m_hCtxt,
               SECPKG_ATTR_SIZES,
               &ctxtSizes); 
   if (ctxtSizes.cbMaxSignature == 0){
         throw CKerberosErr("Message signing not supported");
   }
   secBufDesc.cBuffers = 2;
   secBufDesc.pBuffers = secBufs;
   secBufDesc.ulVersion = SECBUFFER_VERSION;
   secBufs[0].BufferType = SECBUFFER_DATA;
   secBufs[0].cbBuffer = cbBuf;
   secBufs[0].pvBuffer = pBuf; 

   // Build a security buffer for the message signature.
   //
   secBufs[1].BufferType = SECBUFFER_TOKEN;
   secBufs[1].cbBuffer = ctxtSizes.cbMaxSignature;
   secBufs[1].pvBuffer = (void *)malloc (
                                  ctxtSizes.cbMaxSignature);
   // Sign the message 
   //
   ss = m_pFuncTbl->MakeSignature(
                    &m_hCtxt, 
                   0,     // No quality of service in Kerberos
                   &secBufDesc,
                   0);    // We don't use sequence numbers 

   if (!SEC_SUCCESS(ss)){
             throw CKerberosErr ("MakeSignature failed" , ss);
   }
   // Send the message first
   //
   SendMsg(s, (BYTE *)secBufs[0].pvBuffer,
                            secBufs[0].cbBuffer); 
                          . 
   // Send the signature next. That is our 
   // protocol 
   SendMsg(s, (BYTE *)secBufs[1].pvBuffer,
                            secBufs[1].cbBuffer);
   free (secBufs[1].pvBuffer); 
} 

The security buffer that keeps the message has the SECBUFFER_DATA type. The second buffer, which keeps the signature, is of SECBUFFER_TOKENtype and should have a size equal to cbMaxSignature. After setting up the buffers, we sign the message. Our protocol is to send the message size first and then the message itself, in the same order in which we receive them in the RecvSignedMsg function. Note that no quality of service is supported by Kerberos.

If you request out-of-sequence packet detection in any of the constructors, you can pass a sequence number to the MakeSignature call. If you do so, the security package will keep this information in the signature and will report an error if you receive an out-of-sequence packet when verifying the signature. The security package does this by comparing the sequence number in the signature with the one you provide in the VerfiySignaturefunction. The application is responsible for maintaining the sequence numbers.

To verify the signature, after receiving the signature and the message, we allocate two security buffers and initialize the SECBUFFER_TOKENwith the received signature. The SECBUFFER_DATA keeps the message. The security buffers are put in the security buffer description and passed to the VerifySignaturefunction.

Listing 11-7 Receiving a Signed Message

//-------------------------------------------------------------- 
// RecvSignedMsg - Receive a signed message sent by calling 
//                 SendSignedMsg. 
//--------------------------------------------------------------
PBYTE CKerberos::RecvSignedMsg (SOCKET s, DWORD *cbBuf) 
{ 
   PBYTE             pBuf;
   PBYTE             sigBuf;
   DWORD             sigBufSize;
   SECURITY_STATUS   ss;
   SecBufferDesc     secBufDesc;
   SecBuffer         secBuf[2];
   DWORD             cbRead;
   ULONG             fQOP;

   // Receive the message size first
   //
   RecvBytes(s, (PBYTE) cbBuf, sizeof (*cbBuf), &cbRead);

   pBuf = (PBYTE) malloc (*cbBuf);
   // Receive the message	
   //
   RecvBytes(s, pBuf, *cbBuf, &cbRead);
   // Receive the signature size first
   //
   RecvBytes(s, (PBYTE) &sigBufSize,
                    sizeof (sigBufSize),&cbRead);
   sigBuf = (PBYTE) malloc (sigBufSize);
   // Receive the signature
   //
   RecvBytes(s, sigBuf, sigBufSize, &cbRead);
   // Build the input buffer descriptor
   //
   secBufDesc.cBuffers = 2;
   secBufDesc.pBuffers = secBuf;
   secBufDesc.ulVersion = SECBUFFER_VERSION;
   // Build the security buffer for message
   //
   secBuf[0].BufferType = SECBUFFER_DATA;
   secBuf[0].cbBuffer = *cbBuf;
   secBuf[0].pvBuffer = pBuf;
   // Build the security buffer for signature
   //
   secBuf[1].BufferType = SECBUFFER_TOKEN; 
   secBuf[1].cbBuffer = sigBufSize;
   secBuf[1].pvBuffer = sigBuf;
   // Verify the signature 
   //
   ss = m_pFuncTbl->VerifySignature(&m_hCtxt,
                           &secBufDesc, 
                      0, // no sequence number used
                      &fQOP); 

   if(SEC_SUCCESS(ss)){ 
      // OK. Return the message
       return pBuf;
   }
   else if(ss == SEC_E_MESSAGE_ALTERED){
           throw CKerberosErr("The message was tampered with");
   }
   else if (ss == SEC_E_OUT_OF_SEQUENCE ){
            throw CKerberosErr("The message is out of sequence.");
   }
   else{
            throw CKerberosErr("VerifySignature failed with unknown
            error");
   }
} 

To read the message and the signature, we first read the size of the message and the signature, allocate enough memory, and then read the message and the signature. We also read the message first and then the signature because that is the order in which the SendSignedMsgfunction sends them.

Message encryption and decryption work in a similar way. The difference is in the way we set up the security buffers. To encrypt a message, we first query the security context for the encryption-related size information. We then use this information to set up three security buffers: one to keep the trailer, one to keep the message to be encrypted, and one for the padding. The types of these buffers are SECBUFFER_ TOKEN, SECBUFFER_DATA, and SECBUFFER_PADDING, respectively. The message is encrypted in place. We then collect all the data and send it to the other side.

Listing 11-8 Sending an Encrypted Message

//--------------------------------------------------------------
// SendEncryptedMsg - Encrypt a message and send the encrypted 
//                         message 
//--------------------------------------------------------------
void CKerberos::SendEncryptedMsg (SOCKET s, PBYTE pBuf,
             DWORD cbBuf) 
{ 
   SECURITY_STATUS      ss;
   SecBuffer            inSecBuf, outSecBuf;
   SecBuffer            secBufs[3];
   SecBufferDesc        secBufDesc;
   SecPkgContext_Sizes  sizes;

   ss = m_pFuncTbl->QueryContextAttributes(
             &m_hCtxt,
             SECPKG_ATTR_SIZES,
             &sizes);

   if(SEC_E_OK != ss){
             throw CKerberosErr("Error reading SECPKG_ATTR_SIZES", 
                     ss); 
   } 

   // Prepare buffers to encrypt the message
   // secBufDesc.cBuffers = 3;
   secBufDesc.pBuffers = secBufs;
   secBufDesc.ulVersion = SECBUFFER_VERSION;
   inSecBuf.pvBuffer = pBuf;
   inSecBuf.cbBuffer = cbBuf; 
   secBufs[0].cbBuffer = sizes.cbSecurityTrailer;
   secBufs[0].BufferType = SECBUFFER_TOKEN;
   secBufs[0].pvBuffer = malloc(sizes.cbSecurityTrailer);
   secBufs[1].BufferType = SECBUFFER_DATA;
   secBufs[1].cbBuffer = inSecBuf.cbBuffer;
   secBufs[1].pvBuffer = malloc(secBufs[1].cbBuffer); 

   memcpy(secBufs[1].pvBuffer, inSecBuf.pvBuffer, 
              inSecBuf.cbBuffer); 

   secBufs[2].BufferType = SECBUFFER_PADDING;
   secBufs[2].cbBuffer = sizes.cbBlockSize;
   secBufs[2].pvBuffer = malloc(secBufs[2].cbBuffer); 

   // Encrypt the message
   //
   ss = m_pFuncTbl->EncryptMessage(&m_hCtxt, 0, &secBufDesc, 0); 

   if (ss != SEC_E_OK){
      throw CKerberosErr(" EncryptMessage failed", ss);
   }
   // Create the mesage to send
   //
   outSecBuf.cbBuffer = secBufs[0].cbBuffer +
   secBufs[1].cbBuffer + secBufs[2].cbBuffer;
   outSecBuf.pvBuffer = malloc(outSecBuf.cbBuffer); 

   memcpy(outSecBuf.pvBuffer, secBufs[0].pvBuffer,
      secBufs[0].cbBuffer);
   memcpy((PUCHAR) outSecBuf.pvBuffer + (int)
      secBufs[0].cbBuffer, secBufs[1].pvBuffer,
      secBufs[1].cbBuffer);
   memcpy((PUCHAR) outSecBuf.pvBuffer +
   secBufs[0].cbBuffer + secBufs[1].cbBuffer, 
          secBufs[2].pvBuffer, 
          secBufs[2].cbBuffer); 

   free (secBufs[0].pvBuffer);
   free (secBufs[1].pvBuffer);
   free (secBufs[2].pvBuffer);
   // Send everything to the server
   // 
   SendMsg(s, (PBYTE) outSecBuf.pvBuffer, outSecBuf.cbBuffer); 
   free(outSecBuf.pvBuffer); 
}

To decrypt a message, we first receive the encrypted message. Because we don't know the size of the message, we first read the size information, allocate enough memory, and then receive the encrypted message. To do the decryption, we need to set up two security buffers this time: one to keep the encrypted message and one to hold the result of the decryption process. The types of these buffers are SECBUFFER_STREAM and SECBUFFER_DATA, respectively. We then call the decryption function.

Listing 11-9 Receiving an Encrypted Message

//-------------------------------------------------------- 
// RecvEncryptedMsg - Receive an encrypted message sent by
// SendEncryptedMsg
//--------------------------------------------------------
PBYTE CKerberos::RecvEncryptedMsg (SOCKET s, DWORD *cbBuf)
{ 
   SECURITY_STATUS      ss;
   SecBuffer            secBufs[2];
   SecBufferDesc        secBufDesc;
   PBYTE                pBuf;
   DWORD                cbRead;
   ULONG                qop;

   // Receive the encrypted message size first
   //
   RecvBytes(s, (PBYTE) cbBuf, sizeof (*cbBuf), &cbRead);
   pBuf = (PBYTE) malloc (*cbBuf);
   // Recieve the encrypted message
   //
   RecvBytes(s, pBuf, *cbBuf, &cbRead);
   // Build the security buffers for decryption
   //
   secBufDesc.cBuffers = 2;
   secBufDesc.pBuffers = secBufs;
   secBufDesc.ulVersion = SECBUFFER_VERSION;
   // Keep the encrypted message here
   //
   secBufs[0].BufferType = SECBUFFER_STREAM;
   secBufs[0].pvBuffer = pBuf;
   secBufs[0].cbBuffer = *cbBuf;
   // Buffer to keep the decrypted message
   secBufs[1].BufferType = SECBUFFER_DATA;
   secBufs[1].cbBuffer = 0;
   secBufs[1].pvBuffer = NULL; 

   ss = m_pFuncTbl->DecryptMessage(&m_hCtxt, 
                                   &secBufDesc, 
                                   0,  // no sequence number
                                   &qop);
   if (ss != SEC_E_OK){
      free (pBuf);
      throw CKerberosErr("DecryptMessage failed", ss);
   }
   *cbBuf = secBufs[1].cbBuffer;
   return ((PBYTE) (secBufs[1].pvBuffer));
} 

The CKerberosServer class has other methods to impersonate the client, to stop impersonation, to display security context attributes, and so on. Refer to the source code on the companion CD-ROM for more information and for the example code on how to use these classes.

  • + Share This
  • 🔖 Save To Your Account