13 #include "tlsschannel.h"
22 :
TLSBase( th, server ), m_cleanedup( true )
40 std::string data_copy = data;
43 SecBufferDesc buffer_desc;
44 DWORD cbIoBufferLength = m_sizes.cbHeader + m_sizes.cbMaximumMessage + m_sizes.cbTrailer;
46 PBYTE e_iobuffer =
static_cast<PBYTE
>( LocalAlloc( LMEM_FIXED, cbIoBufferLength ) );
48 if( e_iobuffer == NULL )
56 PBYTE e_message = e_iobuffer + m_sizes.cbHeader;
59 const size_t size = ( data_copy.size() > m_sizes.cbMaximumMessage )
60 ? m_sizes.cbMaximumMessage
62 memcpy( e_message, data_copy.data(), size );
63 if( data_copy.size() > m_sizes.cbMaximumMessage )
64 data_copy.erase( 0, m_sizes.cbMaximumMessage );
68 buffer[0].pvBuffer = e_iobuffer;
69 buffer[0].cbBuffer = m_sizes.cbHeader;
70 buffer[0].BufferType = SECBUFFER_STREAM_HEADER;
72 buffer[1].pvBuffer = e_message;
73 buffer[1].cbBuffer = size;
74 buffer[1].BufferType = SECBUFFER_DATA;
76 buffer[2].pvBuffer =
static_cast<char*
>(buffer[1].pvBuffer) + buffer[1].cbBuffer;
77 buffer[2].cbBuffer = m_sizes.cbTrailer;
78 buffer[2].BufferType = SECBUFFER_STREAM_TRAILER;
80 buffer[3].BufferType = SECBUFFER_EMPTY;
82 buffer_desc.ulVersion = SECBUFFER_VERSION;
83 buffer_desc.cBuffers = 4;
84 buffer_desc.pBuffers = buffer;
86 SECURITY_STATUS e_status = EncryptMessage( &m_context, 0, &buffer_desc, 0 );
87 if( SUCCEEDED( e_status ) )
89 std::string encrypted( reinterpret_cast<const char*>(e_iobuffer),
90 buffer[0].cbBuffer + buffer[1].cbBuffer + buffer[2].cbBuffer );
96 LocalFree( e_iobuffer );
103 while( data_copy.size() > 0 );
104 LocalFree( e_iobuffer );
120 SecBufferDesc buffer_desc;
121 DWORD cbIoBufferLength = m_sizes.cbHeader + m_sizes.cbMaximumMessage + m_sizes.cbTrailer;
122 bool wantNewBufferSize =
false;
124 PBYTE e_iobuffer =
static_cast<PBYTE
>( LocalAlloc( LMEM_FIXED, cbIoBufferLength ) );
125 if( e_iobuffer == NULL )
133 SECURITY_STATUS e_status;
137 if( wantNewBufferSize )
139 e_iobuffer =
static_cast<PBYTE
>( LocalReAlloc( e_iobuffer, cbIoBufferLength, 0 ) );
140 wantNewBufferSize =
false;
144 memcpy( e_iobuffer, m_buffer.data(), m_buffer.size() >
145 cbIoBufferLength ? cbIoBufferLength : m_buffer.size() );
147 buffer[0].pvBuffer = e_iobuffer;
148 buffer[0].cbBuffer =
static_cast<unsigned long>( m_buffer.size() > cbIoBufferLength
151 buffer[0].BufferType = SECBUFFER_DATA;
152 buffer[1].cbBuffer = buffer[2].cbBuffer = buffer[3].cbBuffer = 0;
153 buffer[1].BufferType = buffer[2].BufferType = buffer[3].BufferType = SECBUFFER_EMPTY;
155 buffer_desc.ulVersion = SECBUFFER_VERSION;
156 buffer_desc.cBuffers = 4;
157 buffer_desc.pBuffers = buffer;
159 unsigned long processed_data = buffer[0].cbBuffer;
160 e_status = DecryptMessage( &m_context, &buffer_desc, 0, 0 );
167 SecBuffer* pDataBuffer = NULL;
168 SecBuffer* pExtraBuffer = NULL;
169 for(
int i = 1; i < 4; i++ )
171 if( pDataBuffer == NULL && buffer[i].BufferType == SECBUFFER_DATA )
173 pDataBuffer = &buffer[i];
176 if( pExtraBuffer == NULL && buffer[i].BufferType == SECBUFFER_EXTRA )
178 pExtraBuffer = &buffer[i];
181 if( e_status == SEC_E_OK )
183 std::string decrypted( reinterpret_cast<const char*>( pDataBuffer->pvBuffer ),
184 pDataBuffer->cbBuffer );
186 if( pExtraBuffer == NULL )
188 m_buffer.erase( 0, processed_data );
193 m_buffer.erase( 0, processed_data - pExtraBuffer->cbBuffer );
196 cbIoBufferLength = m_sizes.cbHeader + m_sizes.cbMaximumMessage + m_sizes.cbTrailer;
197 wantNewBufferSize =
true;
200 else if( e_status == SEC_E_INCOMPLETE_MESSAGE )
202 if( cbIoBufferLength < 200000 && m_buffer.size() > cbIoBufferLength )
204 cbIoBufferLength += 1000;
205 wantNewBufferSize =
true;
209 cbIoBufferLength = m_sizes.cbHeader + m_sizes.cbMaximumMessage + m_sizes.cbTrailer;
210 wantNewBufferSize =
true;
223 while( m_buffer.size() != 0 );
224 LocalFree( e_iobuffer );
228 handshakeStage( data );
245 DeleteSecurityContext( &m_context );
246 FreeCredentialsHandle( &m_credHandle );
258 SECURITY_STATUS error;
263 SCHANNEL_CRED tlscred;
264 ULONG request = ISC_REQ_ALLOCATE_MEMORY
265 | ISC_REQ_CONFIDENTIALITY
266 | ISC_REQ_EXTENDED_ERROR
268 | ISC_REQ_REPLAY_DETECT
269 | ISC_REQ_SEQUENCE_DETECT
271 | ISC_REQ_MANUAL_CRED_VALIDATION;
274 memset( &tlscred, 0,
sizeof( SCHANNEL_CRED ) );
275 tlscred.dwVersion = SCHANNEL_CRED_VERSION;
276 tlscred.grbitEnabledProtocols = SP_PROT_TLS1;
278 error = AcquireCredentialsHandle( 0,
280 SECPKG_CRED_OUTBOUND,
288 if( error != SEC_E_OK )
297 obuf[0].cbBuffer = 0;
298 obuf[0].pvBuffer = 0;
299 obuf[0].BufferType = SECBUFFER_TOKEN;
301 obufs.ulVersion = SECBUFFER_VERSION;
303 obufs.pBuffers = obuf;
305 SEC_CHAR* hname =
const_cast<char*
>( m_server.c_str() );
307 error = InitializeSecurityContextA( &m_credHandle,
312 SECURITY_NETWORK_DREP,
321 if( error == SEC_I_CONTINUE_NEEDED )
325 std::string senddata( static_cast<char*>(obuf[0].pvBuffer), obuf[0].cbBuffer );
326 FreeContextBuffer( obuf[0].pvBuffer );
339 void SChannel::handshakeStage(
const std::string& data )
344 SECURITY_STATUS error;
347 SecBuffer ibuf[2], obuf[1];
348 SecBufferDesc ibufs, obufs;
349 ULONG request = ISC_REQ_ALLOCATE_MEMORY
350 | ISC_REQ_CONFIDENTIALITY
351 | ISC_REQ_EXTENDED_ERROR
353 | ISC_REQ_REPLAY_DETECT
354 | ISC_REQ_SEQUENCE_DETECT
356 | ISC_REQ_MANUAL_CRED_VALIDATION;
358 SEC_CHAR* hname =
const_cast<char*
>( m_server.c_str() );
363 ibuf[0].cbBuffer =
static_cast<unsigned long>( m_buffer.size() );
364 ibuf[0].pvBuffer =
static_cast<void*
>(
const_cast<char*
>( m_buffer.c_str() ) );
366 ibuf[1].cbBuffer = 0;
367 ibuf[1].pvBuffer = 0;
368 obuf[0].cbBuffer = 0;
369 obuf[0].pvBuffer = 0;
371 ibuf[0].BufferType = SECBUFFER_TOKEN;
372 ibuf[1].BufferType = SECBUFFER_EMPTY;
373 obuf[0].BufferType = SECBUFFER_EMPTY;
375 ibufs.ulVersion = obufs.ulVersion = SECBUFFER_VERSION;
378 ibufs.pBuffers = ibuf;
379 obufs.pBuffers = obuf;
388 error = InitializeSecurityContextA( &m_credHandle,
401 if( error == SEC_E_OK )
404 if( ibuf[1].BufferType == SECBUFFER_EXTRA )
406 m_buffer.erase( 0, m_buffer.size() - ibuf[1].cbBuffer );
419 else if( error == SEC_I_CONTINUE_NEEDED )
428 if( obuf[0].cbBuffer != 0 && obuf[0].pvBuffer != NULL )
430 std::string senddata( static_cast<char*>(obuf[0].pvBuffer), obuf[0].cbBuffer );
431 FreeContextBuffer( obuf[0].pvBuffer );
435 if( ibuf[1].BufferType == SECBUFFER_EXTRA )
437 m_buffer.erase( 0, m_buffer.size() - ibuf[1].cbBuffer );
441 if( obuf[0].cbBuffer == 0 )
450 else if( error == SEC_I_INCOMPLETE_CREDENTIALS )
454 else if( error == SEC_E_INCOMPLETE_MESSAGE )
470 #ifdef HAVE_WINTLS_CHANNEL_BINDING
479 #ifdef HAVE_WINTLS_CHANNEL_BINDING // see ../config.h.win if the following doesn't compile
480 SecPkgContext_Bindings buf;
481 if( QueryContextAttributes( &m_context, SECPKG_ATTR_UNIQUE_BINDINGS, &buf ) == SEC_E_OK )
483 return std::string( buf->Bindings[buf->Bindings.dwApplicationDataOffset], buf->Bindings.cbApplicationDataLength );
493 void SChannel::setSizes()
495 if( QueryContextAttributes( &m_context, SECPKG_ATTR_STREAM_SIZES, &m_sizes ) == SEC_E_OK )
507 int SChannel::filetime2int( FILETIME t )
510 FileTimeToSystemTime(&t, &stUTC);
512 ts.tm_year = stUTC.wYear - 1900;
513 ts.tm_mon = stUTC.wMonth - 1;
514 ts.tm_mday = stUTC.wDay;
515 ts.tm_hour = stUTC.wHour;
516 ts.tm_min = stUTC.wMinute;
517 ts.tm_sec = stUTC.wSecond;
520 if ( (unixtime = mktime(&ts)) == -1 )
522 return (
int)unixtime;
525 void SChannel::validateCert()
528 HTTPSPolicyCallbackData policyHTTPS;
529 CERT_CHAIN_POLICY_PARA policyParameter;
530 CERT_CHAIN_POLICY_STATUS policyStatus;
532 PCCERT_CONTEXT remoteCertContext = NULL;
533 PCCERT_CHAIN_CONTEXT chainContext = NULL;
534 CERT_CHAIN_PARA chainParameter;
535 PSTR serverName =
const_cast<char*
>( m_server.c_str() );
537 PWSTR uServerName = NULL;
538 DWORD csizeServerName;
541 szOID_PKIX_KP_SERVER_AUTH,
542 szOID_SERVER_GATED_CRYPTO,
545 DWORD cUsages =
sizeof( Usages ) /
sizeof( LPSTR );
550 if( QueryContextAttributes( &m_context, SECPKG_ATTR_REMOTE_CERT_CONTEXT,
551 (PVOID)&remoteCertContext ) != SEC_E_OK )
560 csizeServerName = MultiByteToWideChar( CP_ACP, 0, serverName, -1, NULL, 0 );
561 uServerName =
reinterpret_cast<WCHAR *
>( LocalAlloc( LMEM_FIXED,
562 csizeServerName *
sizeof( WCHAR ) ) );
563 if( uServerName == NULL )
570 csizeServerName = MultiByteToWideChar( CP_ACP, 0, serverName, -1, uServerName, csizeServerName );
571 if( csizeServerName == 0 )
578 ZeroMemory( &chainParameter,
sizeof( chainParameter ) );
579 chainParameter.cbSize =
sizeof( chainParameter );
580 chainParameter.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
581 chainParameter.RequestedUsage.Usage.cUsageIdentifier = cUsages;
582 chainParameter.RequestedUsage.Usage.rgpszUsageIdentifier = Usages;
584 if( !CertGetCertificateChain( NULL, remoteCertContext, NULL, remoteCertContext->hCertStore,
585 &chainParameter, 0, NULL, &chainContext ) )
593 ZeroMemory( &policyHTTPS,
sizeof( HTTPSPolicyCallbackData ) );
594 policyHTTPS.cbStruct =
sizeof( HTTPSPolicyCallbackData );
595 policyHTTPS.dwAuthType = AUTHTYPE_SERVER;
596 policyHTTPS.fdwChecks = 0;
597 policyHTTPS.pwszServerName = uServerName;
599 memset( &policyParameter, 0,
sizeof( policyParameter ) );
600 policyParameter.cbSize =
sizeof( policyParameter );
601 policyParameter.pvExtraPolicyPara = &policyHTTPS;
603 memset( &policyStatus, 0,
sizeof( policyStatus ) );
604 policyStatus.cbSize =
sizeof( policyStatus );
606 if( !CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL, chainContext, &policyParameter,
614 if( policyStatus.dwError )
623 if( chainContext ) CertFreeCertificateChain( chainContext );
624 m_certInfo.
chain = valid;
627 void SChannel::connectionInfos()
629 SecPkgContext_ConnectionInfo conn_info;
631 memset( &conn_info, 0,
sizeof( conn_info ) );
633 if( QueryContextAttributes( &m_context, SECPKG_ATTR_CONNECTION_INFO, &conn_info ) == SEC_E_OK )
635 switch( conn_info.dwProtocol )
637 case SP_PROT_TLS1_CLIENT:
640 case SP_PROT_SSL3_CLIENT:
647 switch( conn_info.aiCipher )
650 m_certInfo.
cipher =
"3DES";
653 m_certInfo.
cipher =
"AES_128";
656 m_certInfo.
cipher =
"AES_256";
659 m_certInfo.
cipher =
"DES";
662 m_certInfo.
cipher =
"RC2";
665 m_certInfo.
cipher =
"RC4";
671 switch( conn_info.aiHash )
674 m_certInfo.
mac =
"MD5";
677 m_certInfo.
mac =
"SHA";
685 void SChannel::certData()
687 PCCERT_CONTEXT remoteCertContext = NULL;
688 CHAR certString[1000];
691 if( QueryContextAttributes( &m_context, SECPKG_ATTR_REMOTE_CERT_CONTEXT,
692 (PVOID)&remoteCertContext ) != SEC_E_OK )
698 m_certInfo.
date_from = filetime2int( remoteCertContext->pCertInfo->NotBefore );
699 m_certInfo.
date_to = filetime2int( remoteCertContext->pCertInfo->NotAfter );
701 if( !CertNameToStrA( remoteCertContext->dwCertEncodingType,
702 &remoteCertContext->pCertInfo->Subject,
703 CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG,
704 certString,
sizeof( certString ) ) )
708 m_certInfo.
server = certString;
710 if( !CertNameToStrA( remoteCertContext->dwCertEncodingType,
711 &remoteCertContext->pCertInfo->Issuer,
712 CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG,
713 certString,
sizeof( certString ) ) )
717 m_certInfo.
issuer = certString;
720 void SChannel::setCertinfos()
728 void SChannel::print_error(
int errorcode,
const char* place )
730 printf(
"Win error at %s.\n", place );
734 printf(
"\tValue:\tSEC_E_OK\n" );
735 printf(
"\tDesc:\tNot really an error. Everything is fine.\n" );
737 case SEC_E_INSUFFICIENT_MEMORY:
738 printf(
"\tValue:\tSEC_E_INSUFFICIENT_MEMORY\n" );
739 printf(
"\tDesc:\tThere is not enough memory available to complete the requested action.\n" );
741 case SEC_E_INTERNAL_ERROR:
742 printf(
"\tValue:\tSEC_E_INTERNAL_ERROR\n" );
743 printf(
"\tDesc:\tAn error occurred that did not map to an SSPI error code.\n" );
745 case SEC_E_NO_CREDENTIALS:
746 printf(
"\tValue:\tSEC_E_NO_CREDENTIALS\n" );
747 printf(
"\tDesc:\tNo credentials are available in the security package.\n" );
749 case SEC_E_NOT_OWNER:
750 printf(
"\tValue:\tSEC_E_NOT_OWNER\n" );
751 printf(
"\tDesc:\tThe caller of the function does not have the necessary credentials.\n" );
753 case SEC_E_SECPKG_NOT_FOUND:
754 printf(
"\tValue:\tSEC_E_SECPKG_NOT_FOUND\n" );
755 printf(
"\tDesc:\tThe requested security package does not exist. \n" );
757 case SEC_E_UNKNOWN_CREDENTIALS:
758 printf(
"\tValue:\tSEC_E_UNKNOWN_CREDENTIALS\n" );
759 printf(
"\tDesc:\tThe credentials supplied to the package were not recognized.\n" );
761 case SEC_E_INCOMPLETE_MESSAGE:
762 printf(
"\tValue:\tSEC_E_INCOMPLETE_MESSAGE\n" );
763 printf(
"\tDesc:\tData for the whole message was not read from the wire.\n" );
765 case SEC_E_INVALID_HANDLE:
766 printf(
"\tValue:\tSEC_E_INVALID_HANDLE\n" );
767 printf(
"\tDesc:\tThe handle passed to the function is invalid.\n" );
769 case SEC_E_INVALID_TOKEN:
770 printf(
"\tValue:\tSEC_E_INVALID_TOKEN\n" );
771 printf(
"\tDesc:\tThe error is due to a malformed input token, such as a token "
772 "corrupted in transit...\n" );
774 case SEC_E_LOGON_DENIED:
775 printf(
"\tValue:\tSEC_E_LOGON_DENIED\n" );
776 printf(
"\tDesc:\tThe logon failed.\n" );
778 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
779 printf(
"\tValue:\tSEC_E_NO_AUTHENTICATING_AUTHORITY\n" );
780 printf(
"\tDesc:\tNo authority could be contacted for authentication...\n" );
782 case SEC_E_TARGET_UNKNOWN:
783 printf(
"\tValue:\tSEC_E_TARGET_UNKNOWN\n" );
784 printf(
"\tDesc:\tThe target was not recognized.\n" );
786 case SEC_E_UNSUPPORTED_FUNCTION:
787 printf(
"\tValue:\tSEC_E_UNSUPPORTED_FUNCTION\n" );
788 printf(
"\tDesc:\tAn invalid context attribute flag (ISC_REQ_DELEGATE or "
789 "ISC_REQ_PROMPT_FOR_CREDS)...\n" );
791 case SEC_E_WRONG_PRINCIPAL:
792 printf(
"\tValue:\tSEC_E_WRONG_PRINCIPAL\n" );
793 printf(
"\tDesc:\tThe principal that received the authentication request "
794 "is not the same as the...\n" );
796 case SEC_I_COMPLETE_AND_CONTINUE:
797 printf(
"\tValue:\tSEC_I_COMPLETE_AND_CONTINUE\n" );
798 printf(
"\tDesc:\tThe client must call CompleteAuthToken and then pass the output...\n" );
800 case SEC_I_COMPLETE_NEEDED:
801 printf(
"\tValue:\tSEC_I_COMPLETE_NEEDED\n" );
802 printf(
"\tDesc:\tThe client must finish building the message and then "
803 "call the CompleteAuthToken function.\n" );
805 case SEC_I_CONTINUE_NEEDED:
806 printf(
"\tValue:\tSEC_I_CONTINUE_NEEDED\n" );
807 printf(
"\tDesc:\tThe client must send the output token to the server "
808 "and wait for a return token...\n" );
810 case SEC_I_INCOMPLETE_CREDENTIALS:
811 printf(
"\tValue:\tSEC_I_INCOMPLETE_CREDENTIALS\n" );
812 printf(
"\tDesc:\tThe server has requested client authentication, "
813 "and the supplied credentials either...\n" );
816 printf(
"\tValue:\t%d\n", errorcode );
817 printf(
"\tDesc:\tUnknown error code.\n" );
824 #endif // HAVE_WINTLS