FreeRDP
Loading...
Searching...
No Matches
sspi/NTLM/ntlm.c
1
20#include <winpr/config.h>
21
22#include <winpr/crt.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>
32
33#include "ntlm.h"
34#include "ntlm_export.h"
35#include "../sspi.h"
36
37#include "ntlm_message.h"
38
39#include "../../log.h"
40#define TAG WINPR_TAG("sspi.NTLM")
41
42#define WINPR_KEY "Software\\" WINPR_VENDOR_STRING "\\" WINPR_PRODUCT_STRING "\\WinPR\\NTLM"
43
44static char* NTLM_PACKAGE_NAME = "NTLM";
45
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)
48{
49 BOOL rc = TRUE;
50 wLog* log = WLog_Get(TAG);
51 const DWORD log_level = WLOG_ERROR;
52
53 if (!context)
54 {
55 if (WLog_IsLevelActive(log, log_level))
56 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context");
57
58 return FALSE;
59 }
60
61 if (!context->RecvRc4Seal)
62 {
63 if (WLog_IsLevelActive(log, log_level))
64 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context->RecvRc4Seal");
65 rc = FALSE;
66 }
67 if (!context->SendRc4Seal)
68 {
69 if (WLog_IsLevelActive(log, log_level))
70 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context->SendRc4Seal");
71 rc = FALSE;
72 }
73
74 if (!context->SendSigningKey)
75 {
76 if (WLog_IsLevelActive(log, log_level))
77 WLog_PrintTextMessage(log, log_level, line, file, fkt,
78 "invalid context->SendSigningKey");
79 rc = FALSE;
80 }
81 if (!context->RecvSigningKey)
82 {
83 if (WLog_IsLevelActive(log, log_level))
84 WLog_PrintTextMessage(log, log_level, line, file, fkt,
85 "invalid context->RecvSigningKey");
86 rc = FALSE;
87 }
88 if (!context->SendSealingKey)
89 {
90 if (WLog_IsLevelActive(log, log_level))
91 WLog_PrintTextMessage(log, log_level, line, file, fkt,
92 "invalid context->SendSealingKey");
93 rc = FALSE;
94 }
95 if (!context->RecvSealingKey)
96 {
97 if (WLog_IsLevelActive(log, log_level))
98 WLog_PrintTextMessage(log, log_level, line, file, fkt,
99 "invalid context->RecvSealingKey");
100 rc = FALSE;
101 }
102 return rc;
103}
104
105static char* get_name(COMPUTER_NAME_FORMAT type)
106{
107 DWORD nSize = 0;
108
109 if (GetComputerNameExA(type, NULL, &nSize))
110 return NULL;
111
112 if (GetLastError() != ERROR_MORE_DATA)
113 return NULL;
114
115 char* computerName = calloc(1, nSize);
116
117 if (!computerName)
118 return NULL;
119
120 if (!GetComputerNameExA(type, computerName, &nSize))
121 {
122 free(computerName);
123 return NULL;
124 }
125
126 return computerName;
127}
128
129static int ntlm_SetContextWorkstation(NTLM_CONTEXT* context, char* Workstation)
130{
131 char* ws = Workstation;
132 CHAR* computerName = NULL;
133
134 WINPR_ASSERT(context);
135
136 if (!Workstation)
137 {
138 computerName = get_name(ComputerNameNetBIOS);
139 if (!computerName)
140 return -1;
141 ws = computerName;
142 }
143
144 size_t len = 0;
145 context->Workstation.Buffer = ConvertUtf8ToWCharAlloc(ws, &len);
146
147 free(computerName);
148
149 if (!context->Workstation.Buffer || (len > UINT16_MAX / sizeof(WCHAR)))
150 return -1;
151
152 context->Workstation.Length = (USHORT)(len * sizeof(WCHAR));
153 return 1;
154}
155
156static int ntlm_SetContextServicePrincipalNameW(NTLM_CONTEXT* context, LPWSTR ServicePrincipalName)
157{
158 WINPR_ASSERT(context);
159
160 if (!ServicePrincipalName)
161 {
162 context->ServicePrincipalName.Buffer = NULL;
163 context->ServicePrincipalName.Length = 0;
164 return 1;
165 }
166
167 context->ServicePrincipalName.Length = (USHORT)(_wcslen(ServicePrincipalName) * 2);
168 context->ServicePrincipalName.Buffer = (PWSTR)malloc(context->ServicePrincipalName.Length + 2);
169
170 if (!context->ServicePrincipalName.Buffer)
171 return -1;
172
173 memcpy(context->ServicePrincipalName.Buffer, ServicePrincipalName,
174 context->ServicePrincipalName.Length + 2);
175 return 1;
176}
177
178static int ntlm_SetContextTargetName(NTLM_CONTEXT* context, char* TargetName)
179{
180 char* name = TargetName;
181 DWORD nSize = 0;
182 CHAR* computerName = NULL;
183
184 WINPR_ASSERT(context);
185
186 if (!name)
187 {
188 if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) ||
189 GetLastError() != ERROR_MORE_DATA)
190 return -1;
191
192 computerName = calloc(nSize, sizeof(CHAR));
193
194 if (!computerName)
195 return -1;
196
197 if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize))
198 {
199 free(computerName);
200 return -1;
201 }
202
203 if (nSize > MAX_COMPUTERNAME_LENGTH)
204 computerName[MAX_COMPUTERNAME_LENGTH] = '\0';
205
206 name = computerName;
207
208 if (!name)
209 return -1;
210
211 CharUpperA(name);
212 }
213
214 size_t len = 0;
215 context->TargetName.pvBuffer = ConvertUtf8ToWCharAlloc(name, &len);
216
217 if (!context->TargetName.pvBuffer || (len > UINT16_MAX / sizeof(WCHAR)))
218 {
219 free(context->TargetName.pvBuffer);
220 context->TargetName.pvBuffer = NULL;
221
222 if (!TargetName)
223 free(name);
224
225 return -1;
226 }
227
228 context->TargetName.cbBuffer = (USHORT)(len * sizeof(WCHAR));
229
230 if (!TargetName)
231 free(name);
232
233 return 1;
234}
235
236static NTLM_CONTEXT* ntlm_ContextNew(void)
237{
238 HKEY hKey = 0;
239 LONG status = 0;
240 DWORD dwType = 0;
241 DWORD dwSize = 0;
242 DWORD dwValue = 0;
243 NTLM_CONTEXT* context = (NTLM_CONTEXT*)calloc(1, sizeof(NTLM_CONTEXT));
244
245 if (!context)
246 return NULL;
247
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);
256
257 if (status == ERROR_SUCCESS)
258 {
259 if (RegQueryValueEx(hKey, _T("NTLMv2"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
260 ERROR_SUCCESS)
261 context->NTLMv2 = dwValue ? 1 : 0;
262
263 if (RegQueryValueEx(hKey, _T("UseMIC"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
264 ERROR_SUCCESS)
265 context->UseMIC = dwValue ? 1 : 0;
266
267 if (RegQueryValueEx(hKey, _T("SendVersionInfo"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) ==
268 ERROR_SUCCESS)
269 context->SendVersionInfo = dwValue ? 1 : 0;
270
271 if (RegQueryValueEx(hKey, _T("SendSingleHostData"), NULL, &dwType, (BYTE*)&dwValue,
272 &dwSize) == ERROR_SUCCESS)
273 context->SendSingleHostData = dwValue ? 1 : 0;
274
275 if (RegQueryValueEx(hKey, _T("SendWorkstationName"), NULL, &dwType, (BYTE*)&dwValue,
276 &dwSize) == ERROR_SUCCESS)
277 context->SendWorkstationName = dwValue ? 1 : 0;
278
279 if (RegQueryValueEx(hKey, _T("WorkstationName"), NULL, &dwType, NULL, &dwSize) ==
280 ERROR_SUCCESS)
281 {
282 char* workstation = (char*)malloc(dwSize + 1);
283
284 if (!workstation)
285 {
286 free(context);
287 return NULL;
288 }
289
290 status = RegQueryValueExA(hKey, "WorkstationName", NULL, &dwType, (BYTE*)workstation,
291 &dwSize);
292 if (status != ERROR_SUCCESS)
293 WLog_WARN(TAG, "Key ''WorkstationName' not found");
294 workstation[dwSize] = '\0';
295
296 if (ntlm_SetContextWorkstation(context, workstation) < 0)
297 {
298 free(workstation);
299 free(context);
300 return NULL;
301 }
302
303 free(workstation);
304 }
305
306 RegCloseKey(hKey);
307 }
308
309 /*
310 * Extended Protection is enabled by default in Windows 7,
311 * but enabling it in WinPR breaks TS Gateway at this point
312 */
313 context->SuppressExtendedProtection = FALSE;
314 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\LSA"), 0,
315 KEY_READ | KEY_WOW64_64KEY, &hKey);
316
317 if (status == ERROR_SUCCESS)
318 {
319 if (RegQueryValueEx(hKey, _T("SuppressExtendedProtection"), NULL, &dwType, (BYTE*)&dwValue,
320 &dwSize) == ERROR_SUCCESS)
321 context->SuppressExtendedProtection = dwValue ? 1 : 0;
322
323 RegCloseKey(hKey);
324 }
325
326 context->NegotiateFlags = 0;
327 context->LmCompatibilityLevel = 3;
328 ntlm_change_state(context, NTLM_STATE_INITIAL);
329 FillMemory(context->MachineID, sizeof(context->MachineID), 0xAA);
330
331 if (context->NTLMv2)
332 context->UseMIC = TRUE;
333
334 return context;
335}
336
337static void ntlm_ContextFree(NTLM_CONTEXT* context)
338{
339 if (!context)
340 return;
341
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);
353 free(context);
354}
355
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,
360 WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
361{
362 SEC_WINPR_NTLM_SETTINGS* settings = NULL;
363
364 if ((fCredentialUse != SECPKG_CRED_OUTBOUND) && (fCredentialUse != SECPKG_CRED_INBOUND) &&
365 (fCredentialUse != SECPKG_CRED_BOTH))
366 {
367 return SEC_E_INVALID_PARAMETER;
368 }
369
370 SSPI_CREDENTIALS* credentials = sspi_CredentialsNew();
371
372 if (!credentials)
373 return SEC_E_INTERNAL_ERROR;
374
375 credentials->fCredentialUse = fCredentialUse;
376 credentials->pGetKeyFn = pGetKeyFn;
377 credentials->pvGetKeyArgument = pvGetKeyArgument;
378
379 if (pAuthData)
380 {
381 UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData);
382
383 sspi_CopyAuthIdentity(&(credentials->identity),
384 (const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData);
385
386 if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED)
387 settings = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->ntlmSettings);
388 }
389
390 if (settings)
391 {
392 if (settings->samFile)
393 {
394 credentials->ntlmSettings.samFile = _strdup(settings->samFile);
395 if (!credentials->ntlmSettings.samFile)
396 {
397 sspi_CredentialsFree(credentials);
398 return SEC_E_INSUFFICIENT_MEMORY;
399 }
400 }
401 credentials->ntlmSettings.hashCallback = settings->hashCallback;
402 credentials->ntlmSettings.hashCallbackArg = settings->hashCallbackArg;
403 }
404
405 sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials);
406 sspi_SecureHandleSetUpperPointer(phCredential, (void*)NTLM_PACKAGE_NAME);
407 return SEC_E_OK;
408}
409
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,
413 PTimeStamp ptsExpiry)
414{
415 SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY;
416 SEC_WCHAR* principal = NULL;
417 SEC_WCHAR* package = NULL;
418
419 if (pszPrincipal)
420 {
421 principal = ConvertUtf8ToWCharAlloc(pszPrincipal, NULL);
422 if (!principal)
423 goto fail;
424 }
425 if (pszPackage)
426 {
427 package = ConvertUtf8ToWCharAlloc(pszPackage, NULL);
428 if (!package)
429 goto fail;
430 }
431
432 status =
433 ntlm_AcquireCredentialsHandleW(principal, package, fCredentialUse, pvLogonID, pAuthData,
434 pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
435
436fail:
437 free(principal);
438 free(package);
439
440 return status;
441}
442
443static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(PCredHandle phCredential)
444{
445 if (!phCredential)
446 return SEC_E_INVALID_HANDLE;
447
448 SSPI_CREDENTIALS* credentials =
449 (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
450
451 if (!credentials)
452 return SEC_E_INVALID_HANDLE;
453
454 sspi_CredentialsFree(credentials);
455 return SEC_E_OK;
456}
457
458static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
459 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
460 WINPR_ATTR_UNUSED void* pBuffer)
461{
462 if (ulAttribute == SECPKG_CRED_ATTR_NAMES)
463 {
464 return SEC_E_OK;
465 }
466
467 WLog_ERR(TAG, "TODO: Implement");
468 return SEC_E_UNSUPPORTED_FUNCTION;
469}
470
471static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(PCredHandle phCredential,
472 ULONG ulAttribute, void* pBuffer)
473{
474 return ntlm_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
475}
476
480static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
481 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq,
482 WINPR_ATTR_UNUSED ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput,
483 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED PTimeStamp ptsTimeStamp)
484{
485 SECURITY_STATUS status = 0;
486 SSPI_CREDENTIALS* credentials = NULL;
487 PSecBuffer input_buffer = NULL;
488 PSecBuffer output_buffer = NULL;
489
490 /* behave like windows SSPIs that don't want empty context */
491 if (phContext && !phContext->dwLower && !phContext->dwUpper)
492 return SEC_E_INVALID_HANDLE;
493
494 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
495
496 if (!context)
497 {
498 context = ntlm_ContextNew();
499
500 if (!context)
501 return SEC_E_INSUFFICIENT_MEMORY;
502
503 context->server = TRUE;
504
505 if (fContextReq & ASC_REQ_CONFIDENTIALITY)
506 context->confidentiality = TRUE;
507
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;
513
514 ntlm_SetContextTargetName(context, NULL);
515 sspi_SecureHandleSetLowerPointer(phNewContext, context);
516 sspi_SecureHandleSetUpperPointer(phNewContext, (void*)NTLM_PACKAGE_NAME);
517 }
518
519 switch (ntlm_get_state(context))
520 {
521 case NTLM_STATE_INITIAL:
522 {
523 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
524
525 if (!pInput)
526 return SEC_E_INVALID_TOKEN;
527
528 if (pInput->cBuffers < 1)
529 return SEC_E_INVALID_TOKEN;
530
531 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
532
533 if (!input_buffer)
534 return SEC_E_INVALID_TOKEN;
535
536 if (input_buffer->cbBuffer < 1)
537 return SEC_E_INVALID_TOKEN;
538
539 status = ntlm_read_NegotiateMessage(context, input_buffer);
540 if (status != SEC_I_CONTINUE_NEEDED)
541 return status;
542
543 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
544 {
545 if (!pOutput)
546 return SEC_E_INVALID_TOKEN;
547
548 if (pOutput->cBuffers < 1)
549 return SEC_E_INVALID_TOKEN;
550
551 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
552
553 if (!output_buffer->BufferType)
554 return SEC_E_INVALID_TOKEN;
555
556 if (output_buffer->cbBuffer < 1)
557 return SEC_E_INSUFFICIENT_MEMORY;
558
559 return ntlm_write_ChallengeMessage(context, output_buffer);
560 }
561
562 return SEC_E_OUT_OF_SEQUENCE;
563 }
564
565 case NTLM_STATE_AUTHENTICATE:
566 {
567 if (!pInput)
568 return SEC_E_INVALID_TOKEN;
569
570 if (pInput->cBuffers < 1)
571 return SEC_E_INVALID_TOKEN;
572
573 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
574
575 if (!input_buffer)
576 return SEC_E_INVALID_TOKEN;
577
578 if (input_buffer->cbBuffer < 1)
579 return SEC_E_INVALID_TOKEN;
580
581 status = ntlm_read_AuthenticateMessage(context, input_buffer);
582
583 if (pOutput)
584 {
585 for (ULONG i = 0; i < pOutput->cBuffers; i++)
586 {
587 pOutput->pBuffers[i].cbBuffer = 0;
588 pOutput->pBuffers[i].BufferType = SECBUFFER_TOKEN;
589 }
590 }
591
592 return status;
593 }
594
595 default:
596 return SEC_E_OUT_OF_SEQUENCE;
597 }
598}
599
600static SECURITY_STATUS SEC_ENTRY
601ntlm_ImpersonateSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
602{
603 return SEC_E_OK;
604}
605
606static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
607 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq,
608 WINPR_ATTR_UNUSED ULONG Reserved1, WINPR_ATTR_UNUSED ULONG TargetDataRep, PSecBufferDesc pInput,
609 WINPR_ATTR_UNUSED ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput,
610 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
611{
612 SECURITY_STATUS status = 0;
613 SSPI_CREDENTIALS* credentials = NULL;
614 PSecBuffer input_buffer = NULL;
615 PSecBuffer output_buffer = NULL;
616
617 /* behave like windows SSPIs that don't want empty context */
618 if (phContext && !phContext->dwLower && !phContext->dwUpper)
619 return SEC_E_INVALID_HANDLE;
620
621 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
622
623 if (pInput)
624 {
625 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
626 }
627
628 if (!context)
629 {
630 context = ntlm_ContextNew();
631
632 if (!context)
633 return SEC_E_INSUFFICIENT_MEMORY;
634
635 if (fContextReq & ISC_REQ_CONFIDENTIALITY)
636 context->confidentiality = TRUE;
637
638 credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
639 context->credentials = credentials;
640
641 if (context->Workstation.Length < 1)
642 {
643 if (ntlm_SetContextWorkstation(context, NULL) < 0)
644 {
645 ntlm_ContextFree(context);
646 return SEC_E_INTERNAL_ERROR;
647 }
648 }
649
650 if (ntlm_SetContextServicePrincipalNameW(context, pszTargetName) < 0)
651 {
652 ntlm_ContextFree(context);
653 return SEC_E_INTERNAL_ERROR;
654 }
655
656 sspi_SecureHandleSetLowerPointer(phNewContext, context);
657 sspi_SecureHandleSetUpperPointer(phNewContext, NTLM_SSP_NAME);
658 }
659
660 if ((!input_buffer) || (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE))
661 {
662 if (!pOutput)
663 return SEC_E_INVALID_TOKEN;
664
665 if (pOutput->cBuffers < 1)
666 return SEC_E_INVALID_TOKEN;
667
668 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
669
670 if (!output_buffer)
671 return SEC_E_INVALID_TOKEN;
672
673 if (output_buffer->cbBuffer < 1)
674 return SEC_E_INVALID_TOKEN;
675
676 if (ntlm_get_state(context) == NTLM_STATE_INITIAL)
677 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
678
679 if (ntlm_get_state(context) == NTLM_STATE_NEGOTIATE)
680 return ntlm_write_NegotiateMessage(context, output_buffer);
681
682 return SEC_E_OUT_OF_SEQUENCE;
683 }
684 else
685 {
686 if (!input_buffer)
687 return SEC_E_INVALID_TOKEN;
688
689 if (input_buffer->cbBuffer < 1)
690 return SEC_E_INVALID_TOKEN;
691
692 PSecBuffer channel_bindings = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
693
694 if (channel_bindings)
695 {
696 context->Bindings.BindingsLength = channel_bindings->cbBuffer;
697 context->Bindings.Bindings = (SEC_CHANNEL_BINDINGS*)channel_bindings->pvBuffer;
698 }
699
700 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
701 {
702 status = ntlm_read_ChallengeMessage(context, input_buffer);
703
704 if (status != SEC_I_CONTINUE_NEEDED)
705 return status;
706
707 if (!pOutput)
708 return SEC_E_INVALID_TOKEN;
709
710 if (pOutput->cBuffers < 1)
711 return SEC_E_INVALID_TOKEN;
712
713 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
714
715 if (!output_buffer)
716 return SEC_E_INVALID_TOKEN;
717
718 if (output_buffer->cbBuffer < 1)
719 return SEC_E_INSUFFICIENT_MEMORY;
720
721 if (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE)
722 return ntlm_write_AuthenticateMessage(context, output_buffer);
723 }
724
725 return SEC_E_OUT_OF_SEQUENCE;
726 }
727
728 return SEC_E_OUT_OF_SEQUENCE;
729}
730
734static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
735 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq,
736 ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
737 PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
738{
739 SECURITY_STATUS status = 0;
740 SEC_WCHAR* pszTargetNameW = NULL;
741
742 if (pszTargetName)
743 {
744 pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, NULL);
745 if (!pszTargetNameW)
746 return SEC_E_INTERNAL_ERROR;
747 }
748
749 status = ntlm_InitializeSecurityContextW(phCredential, phContext, pszTargetNameW, fContextReq,
750 Reserved1, TargetDataRep, pInput, Reserved2,
751 phNewContext, pOutput, pfContextAttr, ptsExpiry);
752 free(pszTargetNameW);
753 return status;
754}
755
756/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375354 */
757
758static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
759{
760 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
761 ntlm_ContextFree(context);
762 return SEC_E_OK;
763}
764
765SECURITY_STATUS ntlm_computeProofValue(NTLM_CONTEXT* ntlm, SecBuffer* ntproof)
766{
767 BYTE* blob = NULL;
768 SecBuffer* target = NULL;
769
770 WINPR_ASSERT(ntlm);
771 WINPR_ASSERT(ntproof);
772
773 target = &ntlm->ChallengeTargetInfo;
774
775 if (!sspi_SecBufferAlloc(ntproof, 36 + target->cbBuffer))
776 return SEC_E_INSUFFICIENT_MEMORY;
777
778 blob = (BYTE*)ntproof->pvBuffer;
779 CopyMemory(blob, ntlm->ServerChallenge, 8); /* Server challenge. */
780 blob[8] = 1; /* Response version. */
781 blob[9] = 1; /* Highest response version understood by the client. */
782 /* Reserved 6B. */
783 CopyMemory(&blob[16], ntlm->Timestamp, 8); /* Time. */
784 CopyMemory(&blob[24], ntlm->ClientChallenge, 8); /* Client challenge. */
785 /* Reserved 4B. */
786 /* Server name. */
787 CopyMemory(&blob[36], target->pvBuffer, target->cbBuffer);
788 return SEC_E_OK;
789}
790
791SECURITY_STATUS ntlm_computeMicValue(NTLM_CONTEXT* ntlm, SecBuffer* micvalue)
792{
793 BYTE* blob = NULL;
794 ULONG msgSize = 0;
795
796 WINPR_ASSERT(ntlm);
797 WINPR_ASSERT(micvalue);
798
799 msgSize = ntlm->NegotiateMessage.cbBuffer + ntlm->ChallengeMessage.cbBuffer +
800 ntlm->AuthenticateMessage.cbBuffer;
801
802 if (!sspi_SecBufferAlloc(micvalue, msgSize))
803 return SEC_E_INSUFFICIENT_MEMORY;
804
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);
813 return SEC_E_OK;
814}
815
816/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa379337/ */
817
818static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
819 ULONG ulAttribute, void* pBuffer)
820{
821 if (!phContext)
822 return SEC_E_INVALID_HANDLE;
823
824 if (!pBuffer)
825 return SEC_E_INSUFFICIENT_MEMORY;
826
827 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
828 if (!check_context(context))
829 return SEC_E_INVALID_HANDLE;
830
831 if (ulAttribute == SECPKG_ATTR_SIZES)
832 {
833 SecPkgContext_Sizes* ContextSizes = (SecPkgContext_Sizes*)pBuffer;
834 ContextSizes->cbMaxToken = 2010;
835 ContextSizes->cbMaxSignature = 16; /* the size of expected signature is 16 bytes */
836 ContextSizes->cbBlockSize = 0; /* no padding */
837 ContextSizes->cbSecurityTrailer = 16; /* no security trailer appended in NTLM
838 contrary to Kerberos */
839 return SEC_E_OK;
840 }
841 else if (ulAttribute == SECPKG_ATTR_AUTH_IDENTITY)
842 {
843 SSPI_CREDENTIALS* credentials = NULL;
844 const SecPkgContext_AuthIdentity empty = { 0 };
846
847 WINPR_ASSERT(AuthIdentity);
848 *AuthIdentity = empty;
849
850 context->UseSamFileDatabase = FALSE;
851 credentials = context->credentials;
852
853 if (credentials->identity.UserLength > 0)
854 {
855 if (ConvertWCharNToUtf8(credentials->identity.User, credentials->identity.UserLength,
856 AuthIdentity->User, ARRAYSIZE(AuthIdentity->User)) <= 0)
857 return SEC_E_INTERNAL_ERROR;
858 }
859
860 if (credentials->identity.DomainLength > 0)
861 {
862 if (ConvertWCharNToUtf8(credentials->identity.Domain,
863 credentials->identity.DomainLength, AuthIdentity->Domain,
864 ARRAYSIZE(AuthIdentity->Domain)) <= 0)
865 return SEC_E_INTERNAL_ERROR;
866 }
867
868 return SEC_E_OK;
869 }
870 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_NTPROOF_VALUE)
871 {
872 return ntlm_computeProofValue(context, (SecBuffer*)pBuffer);
873 }
874 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_RANDKEY)
875 {
876 SecBuffer* randkey = NULL;
877 randkey = (SecBuffer*)pBuffer;
878
879 if (!sspi_SecBufferAlloc(randkey, 16))
880 return (SEC_E_INSUFFICIENT_MEMORY);
881
882 CopyMemory(randkey->pvBuffer, context->EncryptedRandomSessionKey, 16);
883 return (SEC_E_OK);
884 }
885 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC)
886 {
887 SecBuffer* mic = (SecBuffer*)pBuffer;
888 NTLM_AUTHENTICATE_MESSAGE* message = &context->AUTHENTICATE_MESSAGE;
889
890 if (!sspi_SecBufferAlloc(mic, 16))
891 return (SEC_E_INSUFFICIENT_MEMORY);
892
893 CopyMemory(mic->pvBuffer, message->MessageIntegrityCheck, 16);
894 return (SEC_E_OK);
895 }
896 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC_VALUE)
897 {
898 return ntlm_computeMicValue(context, (SecBuffer*)pBuffer);
899 }
900
901 WLog_ERR(TAG, "TODO: Implement ulAttribute=0x%08" PRIx32, ulAttribute);
902 return SEC_E_UNSUPPORTED_FUNCTION;
903}
904
905static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
906 ULONG ulAttribute, void* pBuffer)
907{
908 return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
909}
910
911static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesW(PCtxtHandle phContext,
912 ULONG ulAttribute, void* pBuffer,
913 ULONG cbBuffer)
914{
915 if (!phContext)
916 return SEC_E_INVALID_HANDLE;
917
918 if (!pBuffer)
919 return SEC_E_INVALID_PARAMETER;
920
921 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
922 if (!context)
923 return SEC_E_INVALID_HANDLE;
924
925 if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_HASH)
926 {
928
929 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmHash))
930 return SEC_E_INVALID_PARAMETER;
931
932 if (AuthNtlmHash->Version == 1)
933 CopyMemory(context->NtlmHash, AuthNtlmHash->NtlmHash, 16);
934 else if (AuthNtlmHash->Version == 2)
935 CopyMemory(context->NtlmV2Hash, AuthNtlmHash->NtlmHash, 16);
936
937 return SEC_E_OK;
938 }
939 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MESSAGE)
940 {
942
943 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmMessage))
944 return SEC_E_INVALID_PARAMETER;
945
946 if (AuthNtlmMessage->type == 1)
947 {
948 sspi_SecBufferFree(&context->NegotiateMessage);
949
950 if (!sspi_SecBufferAlloc(&context->NegotiateMessage, AuthNtlmMessage->length))
951 return SEC_E_INSUFFICIENT_MEMORY;
952
953 CopyMemory(context->NegotiateMessage.pvBuffer, AuthNtlmMessage->buffer,
954 AuthNtlmMessage->length);
955 }
956 else if (AuthNtlmMessage->type == 2)
957 {
958 sspi_SecBufferFree(&context->ChallengeMessage);
959
960 if (!sspi_SecBufferAlloc(&context->ChallengeMessage, AuthNtlmMessage->length))
961 return SEC_E_INSUFFICIENT_MEMORY;
962
963 CopyMemory(context->ChallengeMessage.pvBuffer, AuthNtlmMessage->buffer,
964 AuthNtlmMessage->length);
965 }
966 else if (AuthNtlmMessage->type == 3)
967 {
968 sspi_SecBufferFree(&context->AuthenticateMessage);
969
970 if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, AuthNtlmMessage->length))
971 return SEC_E_INSUFFICIENT_MEMORY;
972
973 CopyMemory(context->AuthenticateMessage.pvBuffer, AuthNtlmMessage->buffer,
974 AuthNtlmMessage->length);
975 }
976
977 return SEC_E_OK;
978 }
979 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_TIMESTAMP)
980 {
981 SecPkgContext_AuthNtlmTimestamp* AuthNtlmTimestamp =
983
984 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmTimestamp))
985 return SEC_E_INVALID_PARAMETER;
986
987 if (AuthNtlmTimestamp->ChallengeOrResponse)
988 CopyMemory(context->ChallengeTimestamp, AuthNtlmTimestamp->Timestamp, 8);
989 else
990 CopyMemory(context->Timestamp, AuthNtlmTimestamp->Timestamp, 8);
991
992 return SEC_E_OK;
993 }
994 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE)
995 {
996 SecPkgContext_AuthNtlmClientChallenge* AuthNtlmClientChallenge =
998
999 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmClientChallenge))
1000 return SEC_E_INVALID_PARAMETER;
1001
1002 CopyMemory(context->ClientChallenge, AuthNtlmClientChallenge->ClientChallenge, 8);
1003 return SEC_E_OK;
1004 }
1005 else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE)
1006 {
1007 SecPkgContext_AuthNtlmServerChallenge* AuthNtlmServerChallenge =
1009
1010 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmServerChallenge))
1011 return SEC_E_INVALID_PARAMETER;
1012
1013 CopyMemory(context->ServerChallenge, AuthNtlmServerChallenge->ServerChallenge, 8);
1014 return SEC_E_OK;
1015 }
1016
1017 WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute);
1018 return SEC_E_UNSUPPORTED_FUNCTION;
1019}
1020
1021static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesA(PCtxtHandle phContext,
1022 ULONG ulAttribute, void* pBuffer,
1023 ULONG cbBuffer)
1024{
1025 return ntlm_SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer);
1026}
1027
1028static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesW(
1029 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1030 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1031{
1032 return SEC_E_UNSUPPORTED_FUNCTION;
1033}
1034
1035static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesA(
1036 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1037 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1038{
1039 return SEC_E_UNSUPPORTED_FUNCTION;
1040}
1041
1042static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
1043{
1044 return SEC_E_OK;
1045}
1046
1047static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1048 WINPR_ATTR_UNUSED ULONG fQOP,
1049 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1050{
1051 const UINT32 SeqNo = MessageSeqNo;
1052 UINT32 value = 0;
1053 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1054 BYTE checksum[8] = { 0 };
1055 ULONG version = 1;
1056 PSecBuffer data_buffer = NULL;
1057 PSecBuffer signature_buffer = NULL;
1058 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1059 if (!check_context(context))
1060 return SEC_E_INVALID_HANDLE;
1061
1062 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1063 {
1064 SecBuffer* cur = &pMessage->pBuffers[index];
1065
1066 if (cur->BufferType & SECBUFFER_DATA)
1067 data_buffer = cur;
1068 else if (cur->BufferType & SECBUFFER_TOKEN)
1069 signature_buffer = cur;
1070 }
1071
1072 if (!data_buffer)
1073 return SEC_E_INVALID_TOKEN;
1074
1075 if (!signature_buffer)
1076 return SEC_E_INVALID_TOKEN;
1077
1078 /* Copy original data buffer */
1079 ULONG length = data_buffer->cbBuffer;
1080 void* data = malloc(length);
1081
1082 if (!data)
1083 return SEC_E_INSUFFICIENT_MEMORY;
1084
1085 CopyMemory(data, data_buffer->pvBuffer, length);
1086 /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */
1087 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1088
1089 if (hmac &&
1090 winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1091 {
1092 winpr_Data_Write_UINT32(&value, SeqNo);
1093 winpr_HMAC_Update(hmac, (void*)&value, 4);
1094 winpr_HMAC_Update(hmac, data, length);
1095 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1096 winpr_HMAC_Free(hmac);
1097 }
1098 else
1099 {
1100 winpr_HMAC_Free(hmac);
1101 free(data);
1102 return SEC_E_INSUFFICIENT_MEMORY;
1103 }
1104
1105 /* Encrypt message using with RC4, result overwrites original buffer */
1106 if ((data_buffer->BufferType & SECBUFFER_READONLY) == 0)
1107 {
1108 if (context->confidentiality)
1109 winpr_RC4_Update(context->SendRc4Seal, length, (BYTE*)data,
1110 (BYTE*)data_buffer->pvBuffer);
1111 else
1112 CopyMemory(data_buffer->pvBuffer, data, length);
1113 }
1114
1115#ifdef WITH_DEBUG_NTLM
1116 WLog_DBG(TAG, "Data Buffer (length = %" PRIuz ")", length);
1117 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1118 WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer);
1119 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1120#endif
1121 free(data);
1122 /* RC4-encrypt first 8 bytes of digest */
1123 winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum);
1124 if ((signature_buffer->BufferType & SECBUFFER_READONLY) == 0)
1125 {
1126 BYTE* signature = signature_buffer->pvBuffer;
1127 /* Concatenate version, ciphertext and sequence number to build signature */
1128 winpr_Data_Write_UINT32(signature, version);
1129 CopyMemory(&signature[4], (void*)checksum, 8);
1130 winpr_Data_Write_UINT32(&signature[12], SeqNo);
1131 }
1132 context->SendSeqNum++;
1133#ifdef WITH_DEBUG_NTLM
1134 WLog_DBG(TAG, "Signature (length = %" PRIu32 ")", signature_buffer->cbBuffer);
1135 winpr_HexDump(TAG, WLOG_DEBUG, signature_buffer->pvBuffer, signature_buffer->cbBuffer);
1136#endif
1137 return SEC_E_OK;
1138}
1139
1140static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage,
1141 ULONG MessageSeqNo,
1142 WINPR_ATTR_UNUSED PULONG pfQOP)
1143{
1144 const UINT32 SeqNo = (UINT32)MessageSeqNo;
1145 UINT32 value = 0;
1146 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1147 BYTE checksum[8] = { 0 };
1148 UINT32 version = 1;
1149 BYTE expected_signature[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1150 PSecBuffer data_buffer = NULL;
1151 PSecBuffer signature_buffer = NULL;
1152 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1153 if (!check_context(context))
1154 return SEC_E_INVALID_HANDLE;
1155
1156 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1157 {
1158 if (pMessage->pBuffers[index].BufferType == SECBUFFER_DATA)
1159 data_buffer = &pMessage->pBuffers[index];
1160 else if (pMessage->pBuffers[index].BufferType == SECBUFFER_TOKEN)
1161 signature_buffer = &pMessage->pBuffers[index];
1162 }
1163
1164 if (!data_buffer)
1165 return SEC_E_INVALID_TOKEN;
1166
1167 if (!signature_buffer)
1168 return SEC_E_INVALID_TOKEN;
1169
1170 /* Copy original data buffer */
1171 const ULONG length = data_buffer->cbBuffer;
1172 void* data = malloc(length);
1173
1174 if (!data)
1175 return SEC_E_INSUFFICIENT_MEMORY;
1176
1177 CopyMemory(data, data_buffer->pvBuffer, length);
1178
1179 /* Decrypt message using with RC4, result overwrites original buffer */
1180
1181 if (context->confidentiality)
1182 winpr_RC4_Update(context->RecvRc4Seal, length, (BYTE*)data, (BYTE*)data_buffer->pvBuffer);
1183 else
1184 CopyMemory(data_buffer->pvBuffer, data, length);
1185
1186 /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */
1187 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1188
1189 if (hmac &&
1190 winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1191 {
1192 winpr_Data_Write_UINT32(&value, SeqNo);
1193 winpr_HMAC_Update(hmac, (void*)&value, 4);
1194 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1195 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1196 winpr_HMAC_Free(hmac);
1197 }
1198 else
1199 {
1200 winpr_HMAC_Free(hmac);
1201 free(data);
1202 return SEC_E_INSUFFICIENT_MEMORY;
1203 }
1204
1205#ifdef WITH_DEBUG_NTLM
1206 WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIuz ")", length);
1207 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1208 WLog_DBG(TAG, "Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer);
1209 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1210#endif
1211 free(data);
1212 /* RC4-encrypt first 8 bytes of digest */
1213 winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum);
1214 /* Concatenate version, ciphertext and sequence number to build signature */
1215 winpr_Data_Write_UINT32(expected_signature, version);
1216 CopyMemory(&expected_signature[4], (void*)checksum, 8);
1217 winpr_Data_Write_UINT32(&expected_signature[12], SeqNo);
1218 context->RecvSeqNum++;
1219
1220 if (memcmp(signature_buffer->pvBuffer, expected_signature, 16) != 0)
1221 {
1222 /* signature verification failed! */
1223 WLog_ERR(TAG, "signature verification failed, something nasty is going on!");
1224#ifdef WITH_DEBUG_NTLM
1225 WLog_ERR(TAG, "Expected Signature:");
1226 winpr_HexDump(TAG, WLOG_ERROR, expected_signature, 16);
1227 WLog_ERR(TAG, "Actual Signature:");
1228 winpr_HexDump(TAG, WLOG_ERROR, (BYTE*)signature_buffer->pvBuffer, 16);
1229#endif
1230 return SEC_E_MESSAGE_ALTERED;
1231 }
1232
1233 return SEC_E_OK;
1234}
1235
1236static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext,
1237 WINPR_ATTR_UNUSED ULONG fQOP,
1238 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1239{
1240 PSecBuffer data_buffer = NULL;
1241 PSecBuffer sig_buffer = NULL;
1242 UINT32 seq_no = 0;
1243 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1244 BYTE checksum[8] = { 0 };
1245
1246 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1247 if (!check_context(context))
1248 return SEC_E_INVALID_HANDLE;
1249
1250 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1251 {
1252 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1253 data_buffer = &pMessage->pBuffers[i];
1254 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1255 sig_buffer = &pMessage->pBuffers[i];
1256 }
1257
1258 if (!data_buffer || !sig_buffer)
1259 return SEC_E_INVALID_TOKEN;
1260
1261 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1262
1263 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1264 {
1265 winpr_HMAC_Free(hmac);
1266 return SEC_E_INTERNAL_ERROR;
1267 }
1268
1269 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1270 winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4);
1271 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1272 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1273 winpr_HMAC_Free(hmac);
1274
1275 winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum);
1276
1277 BYTE* signature = sig_buffer->pvBuffer;
1278 winpr_Data_Write_UINT32(signature, 1L);
1279 CopyMemory(&signature[4], checksum, 8);
1280 winpr_Data_Write_UINT32(&signature[12], seq_no);
1281 sig_buffer->cbBuffer = 16;
1282
1283 return SEC_E_OK;
1284}
1285
1286static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1287 PSecBufferDesc pMessage, ULONG MessageSeqNo,
1288 WINPR_ATTR_UNUSED PULONG pfQOP)
1289{
1290 PSecBuffer data_buffer = NULL;
1291 PSecBuffer sig_buffer = NULL;
1292 UINT32 seq_no = 0;
1293 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 };
1294 BYTE checksum[8] = { 0 };
1295 BYTE signature[16] = { 0 };
1296
1297 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1298 if (!check_context(context))
1299 return SEC_E_INVALID_HANDLE;
1300
1301 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1302 {
1303 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1304 data_buffer = &pMessage->pBuffers[i];
1305 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1306 sig_buffer = &pMessage->pBuffers[i];
1307 }
1308
1309 if (!data_buffer || !sig_buffer)
1310 return SEC_E_INVALID_TOKEN;
1311
1312 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1313
1314 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1315 {
1316 winpr_HMAC_Free(hmac);
1317 return SEC_E_INTERNAL_ERROR;
1318 }
1319
1320 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1321 winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4);
1322 winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer);
1323 winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH);
1324 winpr_HMAC_Free(hmac);
1325
1326 winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum);
1327
1328 winpr_Data_Write_UINT32(signature, 1L);
1329 CopyMemory(&signature[4], checksum, 8);
1330 winpr_Data_Write_UINT32(&signature[12], seq_no);
1331
1332 if (memcmp(sig_buffer->pvBuffer, signature, 16) != 0)
1333 return SEC_E_MESSAGE_ALTERED;
1334
1335 return SEC_E_OK;
1336}
1337
1338const SecurityFunctionTableA NTLM_SecurityFunctionTableA = {
1339 3, /* dwVersion */
1340 NULL, /* EnumerateSecurityPackages */
1341 ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
1342 ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */
1343 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1344 NULL, /* Reserved2 */
1345 ntlm_InitializeSecurityContextA, /* InitializeSecurityContext */
1346 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1347 NULL, /* CompleteAuthToken */
1348 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1349 NULL, /* ApplyControlToken */
1350 ntlm_QueryContextAttributesA, /* QueryContextAttributes */
1351 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1352 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1353 ntlm_MakeSignature, /* MakeSignature */
1354 ntlm_VerifySignature, /* VerifySignature */
1355 NULL, /* FreeContextBuffer */
1356 NULL, /* QuerySecurityPackageInfo */
1357 NULL, /* Reserved3 */
1358 NULL, /* Reserved4 */
1359 NULL, /* ExportSecurityContext */
1360 NULL, /* ImportSecurityContext */
1361 NULL, /* AddCredentials */
1362 NULL, /* Reserved8 */
1363 NULL, /* QuerySecurityContextToken */
1364 ntlm_EncryptMessage, /* EncryptMessage */
1365 ntlm_DecryptMessage, /* DecryptMessage */
1366 ntlm_SetContextAttributesA, /* SetContextAttributes */
1367 ntlm_SetCredentialsAttributesA, /* SetCredentialsAttributes */
1368};
1369
1370const SecurityFunctionTableW NTLM_SecurityFunctionTableW = {
1371 3, /* dwVersion */
1372 NULL, /* EnumerateSecurityPackages */
1373 ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
1374 ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */
1375 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1376 NULL, /* Reserved2 */
1377 ntlm_InitializeSecurityContextW, /* InitializeSecurityContext */
1378 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1379 NULL, /* CompleteAuthToken */
1380 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1381 NULL, /* ApplyControlToken */
1382 ntlm_QueryContextAttributesW, /* QueryContextAttributes */
1383 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1384 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1385 ntlm_MakeSignature, /* MakeSignature */
1386 ntlm_VerifySignature, /* VerifySignature */
1387 NULL, /* FreeContextBuffer */
1388 NULL, /* QuerySecurityPackageInfo */
1389 NULL, /* Reserved3 */
1390 NULL, /* Reserved4 */
1391 NULL, /* ExportSecurityContext */
1392 NULL, /* ImportSecurityContext */
1393 NULL, /* AddCredentials */
1394 NULL, /* Reserved8 */
1395 NULL, /* QuerySecurityContextToken */
1396 ntlm_EncryptMessage, /* EncryptMessage */
1397 ntlm_DecryptMessage, /* DecryptMessage */
1398 ntlm_SetContextAttributesW, /* SetContextAttributes */
1399 ntlm_SetCredentialsAttributesW, /* SetCredentialsAttributes */
1400};
1401
1402const SecPkgInfoA NTLM_SecPkgInfoA = {
1403 0x00082B37, /* fCapabilities */
1404 1, /* wVersion */
1405 0x000A, /* wRPCID */
1406 0x00000B48, /* cbMaxToken */
1407 "NTLM", /* Name */
1408 "NTLM Security Package" /* Comment */
1409};
1410
1411static WCHAR NTLM_SecPkgInfoW_NameBuffer[32] = { 0 };
1412static WCHAR NTLM_SecPkgInfoW_CommentBuffer[32] = { 0 };
1413
1414const SecPkgInfoW NTLM_SecPkgInfoW = {
1415 0x00082B37, /* fCapabilities */
1416 1, /* wVersion */
1417 0x000A, /* wRPCID */
1418 0x00000B48, /* cbMaxToken */
1419 NTLM_SecPkgInfoW_NameBuffer, /* Name */
1420 NTLM_SecPkgInfoW_CommentBuffer /* Comment */
1421};
1422
1423char* ntlm_negotiate_flags_string(char* buffer, size_t size, UINT32 flags)
1424{
1425 if (!buffer || (size == 0))
1426 return buffer;
1427
1428 (void)_snprintf(buffer, size, "[0x%08" PRIx32 "] ", flags);
1429
1430 for (int x = 0; x < 31; x++)
1431 {
1432 const UINT32 mask = 1 << x;
1433 size_t len = strnlen(buffer, size);
1434 if (flags & mask)
1435 {
1436 const char* str = ntlm_get_negotiate_string(mask);
1437 const size_t flen = strlen(str);
1438
1439 if ((len > 0) && (buffer[len - 1] != ' '))
1440 {
1441 if (size - len < 1)
1442 break;
1443 winpr_str_append("|", buffer, size, NULL);
1444 len++;
1445 }
1446
1447 if (size - len < flen)
1448 break;
1449 winpr_str_append(str, buffer, size, NULL);
1450 }
1451 }
1452
1453 return buffer;
1454}
1455
1456const char* ntlm_message_type_string(UINT32 messageType)
1457{
1458 switch (messageType)
1459 {
1460 case MESSAGE_TYPE_NEGOTIATE:
1461 return "MESSAGE_TYPE_NEGOTIATE";
1462 case MESSAGE_TYPE_CHALLENGE:
1463 return "MESSAGE_TYPE_CHALLENGE";
1464 case MESSAGE_TYPE_AUTHENTICATE:
1465 return "MESSAGE_TYPE_AUTHENTICATE";
1466 default:
1467 return "MESSAGE_TYPE_UNKNOWN";
1468 }
1469}
1470
1471const char* ntlm_state_string(NTLM_STATE state)
1472{
1473 switch (state)
1474 {
1475 case NTLM_STATE_INITIAL:
1476 return "NTLM_STATE_INITIAL";
1477 case NTLM_STATE_NEGOTIATE:
1478 return "NTLM_STATE_NEGOTIATE";
1479 case NTLM_STATE_CHALLENGE:
1480 return "NTLM_STATE_CHALLENGE";
1481 case NTLM_STATE_AUTHENTICATE:
1482 return "NTLM_STATE_AUTHENTICATE";
1483 case NTLM_STATE_FINAL:
1484 return "NTLM_STATE_FINAL";
1485 default:
1486 return "NTLM_STATE_UNKNOWN";
1487 }
1488}
1489void ntlm_change_state(NTLM_CONTEXT* ntlm, NTLM_STATE state)
1490{
1491 WINPR_ASSERT(ntlm);
1492 WLog_DBG(TAG, "change state from %s to %s", ntlm_state_string(ntlm->state),
1493 ntlm_state_string(state));
1494 ntlm->state = state;
1495}
1496
1497NTLM_STATE ntlm_get_state(NTLM_CONTEXT* ntlm)
1498{
1499 WINPR_ASSERT(ntlm);
1500 return ntlm->state;
1501}
1502
1503BOOL ntlm_reset_cipher_state(PSecHandle phContext)
1504{
1505 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1506
1507 if (context)
1508 {
1509 check_context(context);
1510 winpr_RC4_Free(context->SendRc4Seal);
1511 winpr_RC4_Free(context->RecvRc4Seal);
1512 context->SendRc4Seal = winpr_RC4_New(context->RecvSealingKey, 16);
1513 context->RecvRc4Seal = winpr_RC4_New(context->SendSealingKey, 16);
1514
1515 if (!context->SendRc4Seal)
1516 {
1517 WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal");
1518 return FALSE;
1519 }
1520 if (!context->RecvRc4Seal)
1521 {
1522 WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal");
1523 return FALSE;
1524 }
1525 }
1526
1527 return TRUE;
1528}
1529
1530BOOL NTLM_init(void)
1531{
1532 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Name, NTLM_SecPkgInfoW_NameBuffer,
1533 ARRAYSIZE(NTLM_SecPkgInfoW_NameBuffer));
1534 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Comment, NTLM_SecPkgInfoW_CommentBuffer,
1535 ARRAYSIZE(NTLM_SecPkgInfoW_CommentBuffer));
1536
1537 return TRUE;
1538}