20#include <winpr/config.h>
23#include <winpr/assert.h>
24#include <winpr/sspi.h>
25#include <winpr/print.h>
26#include <winpr/string.h>
27#include <winpr/tchar.h>
28#include <winpr/sysinfo.h>
29#include <winpr/registry.h>
30#include <winpr/endian.h>
31#include <winpr/build-config.h>
34#include "ntlm_export.h"
37#include "ntlm_message.h"
40#define TAG WINPR_TAG("sspi.NTLM")
42#define WINPR_KEY "Software\\" WINPR_VENDOR_STRING "\\" WINPR_PRODUCT_STRING "\\WinPR\\NTLM"
44static char* NTLM_PACKAGE_NAME =
"NTLM";
46#define check_context(ctx) check_context_((ctx), __FILE__, __func__, __LINE__)
47static BOOL check_context_(
NTLM_CONTEXT* context,
const char* file,
const char* fkt,
size_t line)
50 wLog* log = WLog_Get(TAG);
51 const DWORD log_level = WLOG_ERROR;
55 if (WLog_IsLevelActive(log, log_level))
56 WLog_PrintTextMessage(log, log_level, line, file, fkt,
"invalid context");
61 if (!context->RecvRc4Seal)
63 if (WLog_IsLevelActive(log, log_level))
64 WLog_PrintTextMessage(log, log_level, line, file, fkt,
"invalid context->RecvRc4Seal");
67 if (!context->SendRc4Seal)
69 if (WLog_IsLevelActive(log, log_level))
70 WLog_PrintTextMessage(log, log_level, line, file, fkt,
"invalid context->SendRc4Seal");
74 if (!context->SendSigningKey)
76 if (WLog_IsLevelActive(log, log_level))
77 WLog_PrintTextMessage(log, log_level, line, file, fkt,
78 "invalid context->SendSigningKey");
81 if (!context->RecvSigningKey)
83 if (WLog_IsLevelActive(log, log_level))
84 WLog_PrintTextMessage(log, log_level, line, file, fkt,
85 "invalid context->RecvSigningKey");
88 if (!context->SendSealingKey)
90 if (WLog_IsLevelActive(log, log_level))
91 WLog_PrintTextMessage(log, log_level, line, file, fkt,
92 "invalid context->SendSealingKey");
95 if (!context->RecvSealingKey)
97 if (WLog_IsLevelActive(log, log_level))
98 WLog_PrintTextMessage(log, log_level, line, file, fkt,
99 "invalid context->RecvSealingKey");
105static char* get_name(COMPUTER_NAME_FORMAT type)
109 if (GetComputerNameExA(type, NULL, &nSize))
112 if (GetLastError() != ERROR_MORE_DATA)
115 char* computerName = calloc(1, nSize);
120 if (!GetComputerNameExA(type, computerName, &nSize))
129static int ntlm_SetContextWorkstation(
NTLM_CONTEXT* context,
char* Workstation)
131 char* ws = Workstation;
132 CHAR* computerName = NULL;
134 WINPR_ASSERT(context);
138 computerName = get_name(ComputerNameNetBIOS);
145 context->Workstation.Buffer = ConvertUtf8ToWCharAlloc(ws, &len);
149 if (!context->Workstation.Buffer || (len > UINT16_MAX /
sizeof(WCHAR)))
152 context->Workstation.Length = (USHORT)(len *
sizeof(WCHAR));
156static int ntlm_SetContextServicePrincipalNameW(
NTLM_CONTEXT* context, LPWSTR ServicePrincipalName)
158 WINPR_ASSERT(context);
160 if (!ServicePrincipalName)
162 context->ServicePrincipalName.Buffer = NULL;
163 context->ServicePrincipalName.Length = 0;
167 context->ServicePrincipalName.Length = (USHORT)(_wcslen(ServicePrincipalName) * 2);
168 context->ServicePrincipalName.Buffer = (PWSTR)malloc(context->ServicePrincipalName.Length + 2);
170 if (!context->ServicePrincipalName.Buffer)
173 memcpy(context->ServicePrincipalName.Buffer, ServicePrincipalName,
174 context->ServicePrincipalName.Length + 2);
178static int ntlm_SetContextTargetName(
NTLM_CONTEXT* context,
char* TargetName)
180 char* name = TargetName;
182 CHAR* computerName = NULL;
184 WINPR_ASSERT(context);
188 if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) ||
189 GetLastError() != ERROR_MORE_DATA)
192 computerName = calloc(nSize,
sizeof(CHAR));
197 if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize))
203 if (nSize > MAX_COMPUTERNAME_LENGTH)
204 computerName[MAX_COMPUTERNAME_LENGTH] =
'\0';
215 context->TargetName.pvBuffer = ConvertUtf8ToWCharAlloc(name, &len);
217 if (!context->TargetName.pvBuffer || (len > UINT16_MAX /
sizeof(WCHAR)))
219 free(context->TargetName.pvBuffer);
220 context->TargetName.pvBuffer = NULL;
228 context->TargetName.cbBuffer = (USHORT)(len *
sizeof(WCHAR));
248 context->NTLMv2 = TRUE;
249 context->UseMIC = FALSE;
250 context->SendVersionInfo = TRUE;
251 context->SendSingleHostData = FALSE;
252 context->SendWorkstationName = TRUE;
253 context->NegotiateKeyExchange = TRUE;
254 context->UseSamFileDatabase = TRUE;
255 status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, WINPR_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
257 if (status == ERROR_SUCCESS)
259 if (RegQueryValueEx(hKey, _T(
"NTLMv2"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
261 context->NTLMv2 = dwValue ? 1 : 0;
263 if (RegQueryValueEx(hKey, _T(
"UseMIC"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
265 context->UseMIC = dwValue ? 1 : 0;
267 if (RegQueryValueEx(hKey, _T(
"SendVersionInfo"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
269 context->SendVersionInfo = dwValue ? 1 : 0;
271 if (RegQueryValueEx(hKey, _T(
"SendSingleHostData"), NULL, &dwType, (BYTE*)&dwValue,
272 &dwSize) == ERROR_SUCCESS)
273 context->SendSingleHostData = dwValue ? 1 : 0;
275 if (RegQueryValueEx(hKey, _T(
"SendWorkstationName"), NULL, &dwType, (BYTE*)&dwValue,
276 &dwSize) == ERROR_SUCCESS)
277 context->SendWorkstationName = dwValue ? 1 : 0;
279 if (RegQueryValueEx(hKey, _T(
"WorkstationName"), NULL, &dwType, NULL, &dwSize) ==
282 char* workstation = (
char*)malloc(dwSize + 1);
290 status = RegQueryValueExA(hKey,
"WorkstationName", NULL, &dwType, (BYTE*)workstation,
292 if (status != ERROR_SUCCESS)
293 WLog_WARN(TAG,
"Key ''WorkstationName' not found");
294 workstation[dwSize] =
'\0';
296 if (ntlm_SetContextWorkstation(context, workstation) < 0)
313 context->SuppressExtendedProtection = FALSE;
314 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(
"System\\CurrentControlSet\\Control\\LSA"), 0,
315 KEY_READ | KEY_WOW64_64KEY, &hKey);
317 if (status == ERROR_SUCCESS)
319 if (RegQueryValueEx(hKey, _T(
"SuppressExtendedProtection"), NULL, &dwType, (BYTE*)&dwValue,
320 &dwSize) == ERROR_SUCCESS)
321 context->SuppressExtendedProtection = dwValue ? 1 : 0;
326 context->NegotiateFlags = 0;
327 context->LmCompatibilityLevel = 3;
328 ntlm_change_state(context, NTLM_STATE_INITIAL);
329 FillMemory(context->MachineID,
sizeof(context->MachineID), 0xAA);
332 context->UseMIC = TRUE;
342 winpr_RC4_Free(context->SendRc4Seal);
343 winpr_RC4_Free(context->RecvRc4Seal);
344 sspi_SecBufferFree(&context->NegotiateMessage);
345 sspi_SecBufferFree(&context->ChallengeMessage);
346 sspi_SecBufferFree(&context->AuthenticateMessage);
347 sspi_SecBufferFree(&context->ChallengeTargetInfo);
348 sspi_SecBufferFree(&context->TargetName);
349 sspi_SecBufferFree(&context->NtChallengeResponse);
350 sspi_SecBufferFree(&context->LmChallengeResponse);
351 free(context->ServicePrincipalName.Buffer);
352 free(context->Workstation.Buffer);
356static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
357 WINPR_ATTR_UNUSED SEC_WCHAR* pszPrincipal, WINPR_ATTR_UNUSED SEC_WCHAR* pszPackage,
358 ULONG fCredentialUse, WINPR_ATTR_UNUSED
void* pvLogonID,
void* pAuthData,
359 SEC_GET_KEY_FN pGetKeyFn,
void* pvGetKeyArgument,
PCredHandle phCredential,
364 if ((fCredentialUse != SECPKG_CRED_OUTBOUND) && (fCredentialUse != SECPKG_CRED_INBOUND) &&
365 (fCredentialUse != SECPKG_CRED_BOTH))
367 return SEC_E_INVALID_PARAMETER;
373 return SEC_E_INTERNAL_ERROR;
375 credentials->fCredentialUse = fCredentialUse;
376 credentials->pGetKeyFn = pGetKeyFn;
377 credentials->pvGetKeyArgument = pvGetKeyArgument;
381 UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData);
383 sspi_CopyAuthIdentity(&(credentials->identity),
386 if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED)
392 if (settings->samFile)
394 credentials->ntlmSettings.samFile = _strdup(settings->samFile);
395 if (!credentials->ntlmSettings.samFile)
397 sspi_CredentialsFree(credentials);
398 return SEC_E_INSUFFICIENT_MEMORY;
401 credentials->ntlmSettings.hashCallback = settings->hashCallback;
402 credentials->ntlmSettings.hashCallbackArg = settings->hashCallbackArg;
405 sspi_SecureHandleSetLowerPointer(phCredential, (
void*)credentials);
406 sspi_SecureHandleSetUpperPointer(phCredential, (
void*)NTLM_PACKAGE_NAME);
410static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
411 SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse,
void* pvLogonID,
412 void* pAuthData, SEC_GET_KEY_FN pGetKeyFn,
void* pvGetKeyArgument,
PCredHandle phCredential,
415 SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY;
416 SEC_WCHAR* principal = NULL;
417 SEC_WCHAR*
package = NULL;
421 principal = ConvertUtf8ToWCharAlloc(pszPrincipal, NULL);
427 package = ConvertUtf8ToWCharAlloc(pszPackage, NULL);
433 ntlm_AcquireCredentialsHandleW(principal, package, fCredentialUse, pvLogonID, pAuthData,
434 pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
443static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
PCredHandle phCredential)
446 return SEC_E_INVALID_HANDLE;
452 return SEC_E_INVALID_HANDLE;
454 sspi_CredentialsFree(credentials);
458static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
459 WINPR_ATTR_UNUSED
PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
460 WINPR_ATTR_UNUSED
void* pBuffer)
462 if (ulAttribute == SECPKG_CRED_ATTR_NAMES)
467 WLog_ERR(TAG,
"TODO: Implement");
468 return SEC_E_UNSUPPORTED_FUNCTION;
471static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
PCredHandle phCredential,
472 ULONG ulAttribute,
void* pBuffer)
474 return ntlm_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
480static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
483 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED
PTimeStamp ptsTimeStamp)
485 SECURITY_STATUS status = 0;
491 if (phContext && !phContext->dwLower && !phContext->dwUpper)
492 return SEC_E_INVALID_HANDLE;
498 context = ntlm_ContextNew();
501 return SEC_E_INSUFFICIENT_MEMORY;
503 context->server = TRUE;
505 if (fContextReq & ASC_REQ_CONFIDENTIALITY)
506 context->confidentiality = TRUE;
508 credentials = (
SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
509 context->credentials = credentials;
510 context->SamFile = credentials->ntlmSettings.samFile;
511 context->HashCallback = credentials->ntlmSettings.hashCallback;
512 context->HashCallbackArg = credentials->ntlmSettings.hashCallbackArg;
514 ntlm_SetContextTargetName(context, NULL);
515 sspi_SecureHandleSetLowerPointer(phNewContext, context);
516 sspi_SecureHandleSetUpperPointer(phNewContext, (
void*)NTLM_PACKAGE_NAME);
519 switch (ntlm_get_state(context))
521 case NTLM_STATE_INITIAL:
523 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
526 return SEC_E_INVALID_TOKEN;
528 if (pInput->cBuffers < 1)
529 return SEC_E_INVALID_TOKEN;
531 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
534 return SEC_E_INVALID_TOKEN;
536 if (input_buffer->cbBuffer < 1)
537 return SEC_E_INVALID_TOKEN;
539 status = ntlm_read_NegotiateMessage(context, input_buffer);
540 if (status != SEC_I_CONTINUE_NEEDED)
543 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
546 return SEC_E_INVALID_TOKEN;
548 if (pOutput->cBuffers < 1)
549 return SEC_E_INVALID_TOKEN;
551 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
553 if (!output_buffer->BufferType)
554 return SEC_E_INVALID_TOKEN;
556 if (output_buffer->cbBuffer < 1)
557 return SEC_E_INSUFFICIENT_MEMORY;
559 return ntlm_write_ChallengeMessage(context, output_buffer);
562 return SEC_E_OUT_OF_SEQUENCE;
565 case NTLM_STATE_AUTHENTICATE:
568 return SEC_E_INVALID_TOKEN;
570 if (pInput->cBuffers < 1)
571 return SEC_E_INVALID_TOKEN;
573 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
576 return SEC_E_INVALID_TOKEN;
578 if (input_buffer->cbBuffer < 1)
579 return SEC_E_INVALID_TOKEN;
581 status = ntlm_read_AuthenticateMessage(context, input_buffer);
585 for (ULONG i = 0; i < pOutput->cBuffers; i++)
587 pOutput->pBuffers[i].cbBuffer = 0;
588 pOutput->pBuffers[i].BufferType = SECBUFFER_TOKEN;
596 return SEC_E_OUT_OF_SEQUENCE;
600static SECURITY_STATUS SEC_ENTRY
601ntlm_ImpersonateSecurityContext(WINPR_ATTR_UNUSED
PCtxtHandle phContext)
606static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
608 WINPR_ATTR_UNUSED ULONG Reserved1, WINPR_ATTR_UNUSED ULONG TargetDataRep,
PSecBufferDesc pInput,
610 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED
PTimeStamp ptsExpiry)
612 SECURITY_STATUS status = 0;
618 if (phContext && !phContext->dwLower && !phContext->dwUpper)
619 return SEC_E_INVALID_HANDLE;
625 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
630 context = ntlm_ContextNew();
633 return SEC_E_INSUFFICIENT_MEMORY;
635 if (fContextReq & ISC_REQ_CONFIDENTIALITY)
636 context->confidentiality = TRUE;
638 credentials = (
SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
639 context->credentials = credentials;
641 if (context->Workstation.Length < 1)
643 if (ntlm_SetContextWorkstation(context, NULL) < 0)
645 ntlm_ContextFree(context);
646 return SEC_E_INTERNAL_ERROR;
650 if (ntlm_SetContextServicePrincipalNameW(context, pszTargetName) < 0)
652 ntlm_ContextFree(context);
653 return SEC_E_INTERNAL_ERROR;
656 sspi_SecureHandleSetLowerPointer(phNewContext, context);
657 sspi_SecureHandleSetUpperPointer(phNewContext, NTLM_SSP_NAME);
660 if ((!input_buffer) || (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE))
663 return SEC_E_INVALID_TOKEN;
665 if (pOutput->cBuffers < 1)
666 return SEC_E_INVALID_TOKEN;
668 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
671 return SEC_E_INVALID_TOKEN;
673 if (output_buffer->cbBuffer < 1)
674 return SEC_E_INVALID_TOKEN;
676 if (ntlm_get_state(context) == NTLM_STATE_INITIAL)
677 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
679 if (ntlm_get_state(context) == NTLM_STATE_NEGOTIATE)
680 return ntlm_write_NegotiateMessage(context, output_buffer);
682 return SEC_E_OUT_OF_SEQUENCE;
687 return SEC_E_INVALID_TOKEN;
689 if (input_buffer->cbBuffer < 1)
690 return SEC_E_INVALID_TOKEN;
692 PSecBuffer channel_bindings = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
694 if (channel_bindings)
696 context->Bindings.BindingsLength = channel_bindings->cbBuffer;
700 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
702 status = ntlm_read_ChallengeMessage(context, input_buffer);
704 if (status != SEC_I_CONTINUE_NEEDED)
708 return SEC_E_INVALID_TOKEN;
710 if (pOutput->cBuffers < 1)
711 return SEC_E_INVALID_TOKEN;
713 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
716 return SEC_E_INVALID_TOKEN;
718 if (output_buffer->cbBuffer < 1)
719 return SEC_E_INSUFFICIENT_MEMORY;
721 if (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE)
722 return ntlm_write_AuthenticateMessage(context, output_buffer);
725 return SEC_E_OUT_OF_SEQUENCE;
728 return SEC_E_OUT_OF_SEQUENCE;
734static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
736 ULONG Reserved1, ULONG TargetDataRep,
PSecBufferDesc pInput, ULONG Reserved2,
739 SECURITY_STATUS status = 0;
740 SEC_WCHAR* pszTargetNameW = NULL;
744 pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, NULL);
746 return SEC_E_INTERNAL_ERROR;
749 status = ntlm_InitializeSecurityContextW(phCredential, phContext, pszTargetNameW, fContextReq,
750 Reserved1, TargetDataRep, pInput, Reserved2,
751 phNewContext, pOutput, pfContextAttr, ptsExpiry);
752 free(pszTargetNameW);
758static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(
PCtxtHandle phContext)
761 ntlm_ContextFree(context);
771 WINPR_ASSERT(ntproof);
773 target = &ntlm->ChallengeTargetInfo;
775 if (!sspi_SecBufferAlloc(ntproof, 36 + target->cbBuffer))
776 return SEC_E_INSUFFICIENT_MEMORY;
778 blob = (BYTE*)ntproof->pvBuffer;
779 CopyMemory(blob, ntlm->ServerChallenge, 8);
783 CopyMemory(&blob[16], ntlm->Timestamp, 8);
784 CopyMemory(&blob[24], ntlm->ClientChallenge, 8);
787 CopyMemory(&blob[36], target->pvBuffer, target->cbBuffer);
797 WINPR_ASSERT(micvalue);
799 msgSize = ntlm->NegotiateMessage.cbBuffer + ntlm->ChallengeMessage.cbBuffer +
800 ntlm->AuthenticateMessage.cbBuffer;
802 if (!sspi_SecBufferAlloc(micvalue, msgSize))
803 return SEC_E_INSUFFICIENT_MEMORY;
805 blob = (BYTE*)micvalue->pvBuffer;
806 CopyMemory(blob, ntlm->NegotiateMessage.pvBuffer, ntlm->NegotiateMessage.cbBuffer);
807 blob += ntlm->NegotiateMessage.cbBuffer;
808 CopyMemory(blob, ntlm->ChallengeMessage.pvBuffer, ntlm->ChallengeMessage.cbBuffer);
809 blob += ntlm->ChallengeMessage.cbBuffer;
810 CopyMemory(blob, ntlm->AuthenticateMessage.pvBuffer, ntlm->AuthenticateMessage.cbBuffer);
811 blob += ntlm->MessageIntegrityCheckOffset;
812 ZeroMemory(blob, 16);
818static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(
PCtxtHandle phContext,
819 ULONG ulAttribute,
void* pBuffer)
822 return SEC_E_INVALID_HANDLE;
825 return SEC_E_INSUFFICIENT_MEMORY;
828 if (!check_context(context))
829 return SEC_E_INVALID_HANDLE;
831 if (ulAttribute == SECPKG_ATTR_SIZES)
834 ContextSizes->cbMaxToken = 2010;
835 ContextSizes->cbMaxSignature = 16;
836 ContextSizes->cbBlockSize = 0;
837 ContextSizes->cbSecurityTrailer = 16;
841 else if (ulAttribute == SECPKG_ATTR_AUTH_IDENTITY)
847 WINPR_ASSERT(AuthIdentity);
848 *AuthIdentity = empty;
850 context->UseSamFileDatabase = FALSE;
851 credentials = context->credentials;
853 if (credentials->identity.UserLength > 0)
855 if (ConvertWCharNToUtf8(credentials->identity.User, credentials->identity.UserLength,
856 AuthIdentity->User, ARRAYSIZE(AuthIdentity->User)) <= 0)
857 return SEC_E_INTERNAL_ERROR;
860 if (credentials->identity.DomainLength > 0)
862 if (ConvertWCharNToUtf8(credentials->identity.Domain,
863 credentials->identity.DomainLength, AuthIdentity->Domain,
864 ARRAYSIZE(AuthIdentity->Domain)) <= 0)
865 return SEC_E_INTERNAL_ERROR;
870 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_NTPROOF_VALUE)
872 return ntlm_computeProofValue(context, (
SecBuffer*)pBuffer);
874 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_RANDKEY)
879 if (!sspi_SecBufferAlloc(randkey, 16))
880 return (SEC_E_INSUFFICIENT_MEMORY);
882 CopyMemory(randkey->pvBuffer, context->EncryptedRandomSessionKey, 16);
885 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC)
890 if (!sspi_SecBufferAlloc(mic, 16))
891 return (SEC_E_INSUFFICIENT_MEMORY);
893 CopyMemory(mic->pvBuffer, message->MessageIntegrityCheck, 16);
896 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC_VALUE)
898 return ntlm_computeMicValue(context, (
SecBuffer*)pBuffer);
900 else if (ulAttribute == SECPKG_ATTR_PACKAGE_INFO)
905 (
SecPkgInfoA*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size);
908 return SEC_E_INSUFFICIENT_MEMORY;
910 pPackageInfo->fCapabilities = NTLM_SecPkgInfoA.fCapabilities;
911 pPackageInfo->wVersion = NTLM_SecPkgInfoA.wVersion;
912 pPackageInfo->wRPCID = NTLM_SecPkgInfoA.wRPCID;
913 pPackageInfo->cbMaxToken = NTLM_SecPkgInfoA.cbMaxToken;
914 pPackageInfo->Name = _strdup(NTLM_SecPkgInfoA.Name);
915 pPackageInfo->Comment = _strdup(NTLM_SecPkgInfoA.Comment);
917 if (!pPackageInfo->Name || !pPackageInfo->Comment)
919 sspi_ContextBufferFree(pPackageInfo);
920 return SEC_E_INSUFFICIENT_MEMORY;
922 PackageInfo->PackageInfo = pPackageInfo;
926 WLog_ERR(TAG,
"TODO: Implement ulAttribute=0x%08" PRIx32, ulAttribute);
927 return SEC_E_UNSUPPORTED_FUNCTION;
930static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(
PCtxtHandle phContext,
931 ULONG ulAttribute,
void* pBuffer)
933 return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
936static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesW(
PCtxtHandle phContext,
937 ULONG ulAttribute,
void* pBuffer,
941 return SEC_E_INVALID_HANDLE;
944 return SEC_E_INVALID_PARAMETER;
948 return SEC_E_INVALID_HANDLE;
950 if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_HASH)
955 return SEC_E_INVALID_PARAMETER;
957 if (AuthNtlmHash->Version == 1)
958 CopyMemory(context->NtlmHash, AuthNtlmHash->NtlmHash, 16);
959 else if (AuthNtlmHash->Version == 2)
960 CopyMemory(context->NtlmV2Hash, AuthNtlmHash->NtlmHash, 16);
964 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MESSAGE)
969 return SEC_E_INVALID_PARAMETER;
971 if (AuthNtlmMessage->type == 1)
973 sspi_SecBufferFree(&context->NegotiateMessage);
975 if (!sspi_SecBufferAlloc(&context->NegotiateMessage, AuthNtlmMessage->length))
976 return SEC_E_INSUFFICIENT_MEMORY;
978 CopyMemory(context->NegotiateMessage.pvBuffer, AuthNtlmMessage->buffer,
979 AuthNtlmMessage->length);
981 else if (AuthNtlmMessage->type == 2)
983 sspi_SecBufferFree(&context->ChallengeMessage);
985 if (!sspi_SecBufferAlloc(&context->ChallengeMessage, AuthNtlmMessage->length))
986 return SEC_E_INSUFFICIENT_MEMORY;
988 CopyMemory(context->ChallengeMessage.pvBuffer, AuthNtlmMessage->buffer,
989 AuthNtlmMessage->length);
991 else if (AuthNtlmMessage->type == 3)
993 sspi_SecBufferFree(&context->AuthenticateMessage);
995 if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, AuthNtlmMessage->length))
996 return SEC_E_INSUFFICIENT_MEMORY;
998 CopyMemory(context->AuthenticateMessage.pvBuffer, AuthNtlmMessage->buffer,
999 AuthNtlmMessage->length);
1004 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_TIMESTAMP)
1010 return SEC_E_INVALID_PARAMETER;
1012 if (AuthNtlmTimestamp->ChallengeOrResponse)
1013 CopyMemory(context->ChallengeTimestamp, AuthNtlmTimestamp->Timestamp, 8);
1015 CopyMemory(context->Timestamp, AuthNtlmTimestamp->Timestamp, 8);
1019 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE)
1025 return SEC_E_INVALID_PARAMETER;
1027 CopyMemory(context->ClientChallenge, AuthNtlmClientChallenge->ClientChallenge, 8);
1030 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE)
1036 return SEC_E_INVALID_PARAMETER;
1038 CopyMemory(context->ServerChallenge, AuthNtlmServerChallenge->ServerChallenge, 8);
1042 WLog_ERR(TAG,
"TODO: Implement ulAttribute=%08" PRIx32, ulAttribute);
1043 return SEC_E_UNSUPPORTED_FUNCTION;
1046static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesA(
PCtxtHandle phContext,
1047 ULONG ulAttribute,
void* pBuffer,
1050 return ntlm_SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer);
1053static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesW(
1054 WINPR_ATTR_UNUSED
PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1055 WINPR_ATTR_UNUSED
void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1057 return SEC_E_UNSUPPORTED_FUNCTION;
1060static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesA(
1061 WINPR_ATTR_UNUSED
PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1062 WINPR_ATTR_UNUSED
void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1064 return SEC_E_UNSUPPORTED_FUNCTION;
1067static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(WINPR_ATTR_UNUSED
PCtxtHandle phContext)
1072static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(
PCtxtHandle phContext,
1073 WINPR_ATTR_UNUSED ULONG fQOP,
1076 const UINT32 SeqNo = MessageSeqNo;
1078 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1079 BYTE checksum[8] = { 0 };
1084 if (!check_context(context))
1085 return SEC_E_INVALID_HANDLE;
1087 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1089 SecBuffer* cur = &pMessage->pBuffers[index];
1091 if (cur->BufferType & SECBUFFER_DATA)
1093 else if (cur->BufferType & SECBUFFER_TOKEN)
1094 signature_buffer = cur;
1098 return SEC_E_INVALID_TOKEN;
1100 if (!signature_buffer)
1101 return SEC_E_INVALID_TOKEN;
1104 ULONG length = data_buffer->cbBuffer;
1105 void* data = malloc(length);
1108 return SEC_E_INSUFFICIENT_MEMORY;
1110 CopyMemory(data, data_buffer->pvBuffer, length);
1112 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1115 winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1117 winpr_Data_Write_UINT32(&value, SeqNo);
1118 winpr_HMAC_Update(hmac, (
void*)&value, 4);
1119 winpr_HMAC_Update(hmac, data, length);
1120 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1121 winpr_HMAC_Free(hmac);
1125 winpr_HMAC_Free(hmac);
1127 return SEC_E_INSUFFICIENT_MEMORY;
1131 if ((data_buffer->BufferType & SECBUFFER_READONLY) == 0)
1133 if (context->confidentiality)
1134 winpr_RC4_Update(context->SendRc4Seal, length, (BYTE*)data,
1135 (BYTE*)data_buffer->pvBuffer);
1137 CopyMemory(data_buffer->pvBuffer, data, length);
1140#ifdef WITH_DEBUG_NTLM
1141 WLog_DBG(TAG,
"Data Buffer (length = %" PRIuz
")", length);
1142 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1143 WLog_DBG(TAG,
"Encrypted Data Buffer (length = %" PRIu32
")", data_buffer->cbBuffer);
1144 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1148 winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum);
1149 if ((signature_buffer->BufferType & SECBUFFER_READONLY) == 0)
1151 BYTE* signature = signature_buffer->pvBuffer;
1153 winpr_Data_Write_UINT32(signature, version);
1154 CopyMemory(&signature[4], (
void*)checksum, 8);
1155 winpr_Data_Write_UINT32(&signature[12], SeqNo);
1157 context->SendSeqNum++;
1158#ifdef WITH_DEBUG_NTLM
1159 WLog_DBG(TAG,
"Signature (length = %" PRIu32
")", signature_buffer->cbBuffer);
1160 winpr_HexDump(TAG, WLOG_DEBUG, signature_buffer->pvBuffer, signature_buffer->cbBuffer);
1167 WINPR_ATTR_UNUSED PULONG pfQOP)
1169 const UINT32 SeqNo = (UINT32)MessageSeqNo;
1171 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1172 BYTE checksum[8] = { 0 };
1174 BYTE expected_signature[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1178 if (!check_context(context))
1179 return SEC_E_INVALID_HANDLE;
1181 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1183 if (pMessage->pBuffers[index].BufferType == SECBUFFER_DATA)
1184 data_buffer = &pMessage->pBuffers[index];
1185 else if (pMessage->pBuffers[index].BufferType == SECBUFFER_TOKEN)
1186 signature_buffer = &pMessage->pBuffers[index];
1190 return SEC_E_INVALID_TOKEN;
1192 if (!signature_buffer)
1193 return SEC_E_INVALID_TOKEN;
1196 const ULONG length = data_buffer->cbBuffer;
1197 void* data = malloc(length);
1200 return SEC_E_INSUFFICIENT_MEMORY;
1202 CopyMemory(data, data_buffer->pvBuffer, length);
1206 if (context->confidentiality)
1207 winpr_RC4_Update(context->RecvRc4Seal, length, (BYTE*)data, (BYTE*)data_buffer->pvBuffer);
1209 CopyMemory(data_buffer->pvBuffer, data, length);
1212 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1215 winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1217 winpr_Data_Write_UINT32(&value, SeqNo);
1218 winpr_HMAC_Update(hmac, (
void*)&value, 4);
1219 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1220 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1221 winpr_HMAC_Free(hmac);
1225 winpr_HMAC_Free(hmac);
1227 return SEC_E_INSUFFICIENT_MEMORY;
1230#ifdef WITH_DEBUG_NTLM
1231 WLog_DBG(TAG,
"Encrypted Data Buffer (length = %" PRIuz
")", length);
1232 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1233 WLog_DBG(TAG,
"Data Buffer (length = %" PRIu32
")", data_buffer->cbBuffer);
1234 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1238 winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum);
1240 winpr_Data_Write_UINT32(expected_signature, version);
1241 CopyMemory(&expected_signature[4], (
void*)checksum, 8);
1242 winpr_Data_Write_UINT32(&expected_signature[12], SeqNo);
1243 context->RecvSeqNum++;
1245 if (memcmp(signature_buffer->pvBuffer, expected_signature, 16) != 0)
1248 WLog_ERR(TAG,
"signature verification failed, something nasty is going on!");
1249#ifdef WITH_DEBUG_NTLM
1250 WLog_ERR(TAG,
"Expected Signature:");
1251 winpr_HexDump(TAG, WLOG_ERROR, expected_signature, 16);
1252 WLog_ERR(TAG,
"Actual Signature:");
1253 winpr_HexDump(TAG, WLOG_ERROR, (BYTE*)signature_buffer->pvBuffer, 16);
1255 return SEC_E_MESSAGE_ALTERED;
1261static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(
PCtxtHandle phContext,
1262 WINPR_ATTR_UNUSED ULONG fQOP,
1268 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1269 BYTE checksum[8] = { 0 };
1271 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1272 if (!check_context(context))
1273 return SEC_E_INVALID_HANDLE;
1275 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1277 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1278 data_buffer = &pMessage->pBuffers[i];
1279 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1280 sig_buffer = &pMessage->pBuffers[i];
1283 if (!data_buffer || !sig_buffer)
1284 return SEC_E_INVALID_TOKEN;
1286 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1288 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1290 winpr_HMAC_Free(hmac);
1291 return SEC_E_INTERNAL_ERROR;
1294 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1295 winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4);
1296 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1297 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1298 winpr_HMAC_Free(hmac);
1300 winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum);
1302 BYTE* signature = sig_buffer->pvBuffer;
1303 winpr_Data_Write_UINT32(signature, 1L);
1304 CopyMemory(&signature[4], checksum, 8);
1305 winpr_Data_Write_UINT32(&signature[12], seq_no);
1306 sig_buffer->cbBuffer = 16;
1311static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(
PCtxtHandle phContext,
1313 WINPR_ATTR_UNUSED PULONG pfQOP)
1318 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1319 BYTE checksum[8] = { 0 };
1320 BYTE signature[16] = { 0 };
1322 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1323 if (!check_context(context))
1324 return SEC_E_INVALID_HANDLE;
1326 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1328 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1329 data_buffer = &pMessage->pBuffers[i];
1330 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1331 sig_buffer = &pMessage->pBuffers[i];
1334 if (!data_buffer || !sig_buffer)
1335 return SEC_E_INVALID_TOKEN;
1337 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1339 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1341 winpr_HMAC_Free(hmac);
1342 return SEC_E_INTERNAL_ERROR;
1345 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1346 winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4);
1347 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1348 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1349 winpr_HMAC_Free(hmac);
1351 winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum);
1353 winpr_Data_Write_UINT32(signature, 1L);
1354 CopyMemory(&signature[4], checksum, 8);
1355 winpr_Data_Write_UINT32(&signature[12], seq_no);
1357 if (memcmp(sig_buffer->pvBuffer, signature, 16) != 0)
1358 return SEC_E_MESSAGE_ALTERED;
1366 ntlm_QueryCredentialsAttributesA,
1367 ntlm_AcquireCredentialsHandleA,
1368 ntlm_FreeCredentialsHandle,
1370 ntlm_InitializeSecurityContextA,
1371 ntlm_AcceptSecurityContext,
1373 ntlm_DeleteSecurityContext,
1375 ntlm_QueryContextAttributesA,
1376 ntlm_ImpersonateSecurityContext,
1377 ntlm_RevertSecurityContext,
1379 ntlm_VerifySignature,
1389 ntlm_EncryptMessage,
1390 ntlm_DecryptMessage,
1391 ntlm_SetContextAttributesA,
1392 ntlm_SetCredentialsAttributesA,
1398 ntlm_QueryCredentialsAttributesW,
1399 ntlm_AcquireCredentialsHandleW,
1400 ntlm_FreeCredentialsHandle,
1402 ntlm_InitializeSecurityContextW,
1403 ntlm_AcceptSecurityContext,
1405 ntlm_DeleteSecurityContext,
1407 ntlm_QueryContextAttributesW,
1408 ntlm_ImpersonateSecurityContext,
1409 ntlm_RevertSecurityContext,
1411 ntlm_VerifySignature,
1421 ntlm_EncryptMessage,
1422 ntlm_DecryptMessage,
1423 ntlm_SetContextAttributesW,
1424 ntlm_SetCredentialsAttributesW,
1433 "NTLM Security Package"
1436static WCHAR NTLM_SecPkgInfoW_NameBuffer[32] = { 0 };
1437static WCHAR NTLM_SecPkgInfoW_CommentBuffer[32] = { 0 };
1444 NTLM_SecPkgInfoW_NameBuffer,
1445 NTLM_SecPkgInfoW_CommentBuffer
1448char* ntlm_negotiate_flags_string(
char* buffer,
size_t size, UINT32 flags)
1450 if (!buffer || (size == 0))
1453 (void)_snprintf(buffer, size,
"[0x%08" PRIx32
"] ", flags);
1455 for (
int x = 0; x < 31; x++)
1457 const UINT32 mask = 1 << x;
1458 size_t len = strnlen(buffer, size);
1461 const char* str = ntlm_get_negotiate_string(mask);
1462 const size_t flen = strlen(str);
1464 if ((len > 0) && (buffer[len - 1] !=
' '))
1468 winpr_str_append(
"|", buffer, size, NULL);
1472 if (size - len < flen)
1474 winpr_str_append(str, buffer, size, NULL);
1481const char* ntlm_message_type_string(UINT32 messageType)
1483 switch (messageType)
1485 case MESSAGE_TYPE_NEGOTIATE:
1486 return "MESSAGE_TYPE_NEGOTIATE";
1487 case MESSAGE_TYPE_CHALLENGE:
1488 return "MESSAGE_TYPE_CHALLENGE";
1489 case MESSAGE_TYPE_AUTHENTICATE:
1490 return "MESSAGE_TYPE_AUTHENTICATE";
1492 return "MESSAGE_TYPE_UNKNOWN";
1496const char* ntlm_state_string(NTLM_STATE state)
1500 case NTLM_STATE_INITIAL:
1501 return "NTLM_STATE_INITIAL";
1502 case NTLM_STATE_NEGOTIATE:
1503 return "NTLM_STATE_NEGOTIATE";
1504 case NTLM_STATE_CHALLENGE:
1505 return "NTLM_STATE_CHALLENGE";
1506 case NTLM_STATE_AUTHENTICATE:
1507 return "NTLM_STATE_AUTHENTICATE";
1508 case NTLM_STATE_FINAL:
1509 return "NTLM_STATE_FINAL";
1511 return "NTLM_STATE_UNKNOWN";
1514void ntlm_change_state(
NTLM_CONTEXT* ntlm, NTLM_STATE state)
1517 WLog_DBG(TAG,
"change state from %s to %s", ntlm_state_string(ntlm->state),
1518 ntlm_state_string(state));
1519 ntlm->state = state;
1528BOOL ntlm_reset_cipher_state(
PSecHandle phContext)
1530 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1534 check_context(context);
1535 winpr_RC4_Free(context->SendRc4Seal);
1536 winpr_RC4_Free(context->RecvRc4Seal);
1537 context->SendRc4Seal = winpr_RC4_New(context->RecvSealingKey, 16);
1538 context->RecvRc4Seal = winpr_RC4_New(context->SendSealingKey, 16);
1540 if (!context->SendRc4Seal)
1542 WLog_ERR(TAG,
"Failed to allocate context->SendRc4Seal");
1545 if (!context->RecvRc4Seal)
1547 WLog_ERR(TAG,
"Failed to allocate context->RecvRc4Seal");
1557 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Name, NTLM_SecPkgInfoW_NameBuffer,
1558 ARRAYSIZE(NTLM_SecPkgInfoW_NameBuffer));
1559 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Comment, NTLM_SecPkgInfoW_CommentBuffer,
1560 ARRAYSIZE(NTLM_SecPkgInfoW_CommentBuffer));