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 "../../utils.h"
40
41#include "../../log.h"
42#define TAG WINPR_TAG("sspi.NTLM")
43
44#ifndef MIN
45#define MIN(a, b) ((a) < (b)) ? (a) : (b)
46#endif
47
48#define WINPR_KEY "Software\\%s\\WinPR\\NTLM"
49
50#define check_context(ctx) check_context_((ctx), __FILE__, __func__, __LINE__)
51
52WINPR_ATTR_NODISCARD
53static BOOL check_context_(NTLM_CONTEXT* context, const char* file, const char* fkt, size_t line)
54{
55 BOOL rc = TRUE;
56 wLog* log = WLog_Get(TAG);
57 const DWORD log_level = WLOG_ERROR;
58
59 if (!context)
60 {
61 if (WLog_IsLevelActive(log, log_level))
62 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context");
63
64 return FALSE;
65 }
66
67 if (!context->RecvRc4Seal)
68 {
69 if (WLog_IsLevelActive(log, log_level))
70 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context->RecvRc4Seal");
71 rc = FALSE;
72 }
73 if (!context->SendRc4Seal)
74 {
75 if (WLog_IsLevelActive(log, log_level))
76 WLog_PrintTextMessage(log, log_level, line, file, fkt, "invalid context->SendRc4Seal");
77 rc = FALSE;
78 }
79
80 if (!context->SendSigningKey)
81 {
82 if (WLog_IsLevelActive(log, log_level))
83 WLog_PrintTextMessage(log, log_level, line, file, fkt,
84 "invalid context->SendSigningKey");
85 rc = FALSE;
86 }
87 if (!context->RecvSigningKey)
88 {
89 if (WLog_IsLevelActive(log, log_level))
90 WLog_PrintTextMessage(log, log_level, line, file, fkt,
91 "invalid context->RecvSigningKey");
92 rc = FALSE;
93 }
94 if (!context->SendSealingKey)
95 {
96 if (WLog_IsLevelActive(log, log_level))
97 WLog_PrintTextMessage(log, log_level, line, file, fkt,
98 "invalid context->SendSealingKey");
99 rc = FALSE;
100 }
101 if (!context->RecvSealingKey)
102 {
103 if (WLog_IsLevelActive(log, log_level))
104 WLog_PrintTextMessage(log, log_level, line, file, fkt,
105 "invalid context->RecvSealingKey");
106 rc = FALSE;
107 }
108 return rc;
109}
110
111WINPR_ATTR_MALLOC(free, 1)
112static char* get_computer_name(COMPUTER_NAME_FORMAT type, size_t* pSize)
113{
114 DWORD nSize = 0;
115
116 if (pSize)
117 *pSize = 0;
118
119 if (GetComputerNameExA(type, nullptr, &nSize))
120 return nullptr;
121
122 if (GetLastError() != ERROR_MORE_DATA)
123 return nullptr;
124
125 char* computerName = calloc(1, nSize);
126
127 if (!computerName)
128 return nullptr;
129
130 if (!GetComputerNameExA(type, computerName, &nSize))
131 {
132 free(computerName);
133 return nullptr;
134 }
135
136 if (pSize)
137 *pSize = nSize;
138 return computerName;
139}
140
141WINPR_ATTR_NODISCARD
142SECURITY_STATUS ntlm_SetContextWorkstationX(NTLM_CONTEXT* context, BOOL unicode, const void* data,
143 size_t length)
144{
145 WINPR_ASSERT(context);
146 ntlm_free_unicode_string(&context->Workstation);
147
148 if (length == 0)
149 return SEC_E_OK;
150
151 WINPR_ASSERT(data);
152 if (unicode)
153 context->Workstation = ntlm_from_unicode_string_w(data, length / sizeof(WCHAR));
154 else
155 context->Workstation = ntlm_from_unicode_string_utf8(data, length);
156
157 if (ntlm_is_unicode_string_empty(&context->Workstation))
158 return SEC_E_INSUFFICIENT_MEMORY;
159
160 return SEC_E_OK;
161}
162
163WINPR_ATTR_NODISCARD
164static int ntlm_SetContextWorkstation(NTLM_CONTEXT* context, const char* Workstation)
165{
166 const char* ws = Workstation;
167 CHAR* computerName = nullptr;
168
169 if (!Workstation)
170 {
171 computerName = get_computer_name(ComputerNameNetBIOS, nullptr);
172 if (!computerName)
173 return -1;
174 ws = computerName;
175 }
176
177 const size_t len = strlen(ws);
178 const SECURITY_STATUS status = ntlm_SetContextWorkstationX(context, FALSE, ws, len);
179 free(computerName);
180
181 return (status == SEC_E_OK) ? 1 : -1;
182}
183
184WINPR_ATTR_NODISCARD
185static int ntlm_SetContextServicePrincipalNameW(NTLM_CONTEXT* context, LPWSTR ServicePrincipalName)
186{
187 WINPR_ASSERT(context);
188
189 ntlm_free_unicode_string(&context->ServicePrincipalName);
190 if (!ServicePrincipalName)
191 return 1;
192
193 const size_t len = _wcslen(ServicePrincipalName);
194 context->ServicePrincipalName = ntlm_from_unicode_string_w(ServicePrincipalName, len);
195 if (ntlm_is_unicode_string_empty(&context->ServicePrincipalName))
196 return -1;
197
198 return 1;
199}
200
201WINPR_ATTR_NODISCARD
202static int ntlm_SetContextTargetName(NTLM_CONTEXT* context, char* TargetName)
203{
204 char* name = TargetName;
205 WINPR_ASSERT(context);
206
207 if (!name)
208 {
209 size_t nSize = 0;
210 char* computerName = get_computer_name(ComputerNameNetBIOS, &nSize);
211
212 if (!computerName)
213 return -1;
214
215 if (nSize > MAX_COMPUTERNAME_LENGTH)
216 computerName[MAX_COMPUTERNAME_LENGTH] = '\0';
217
218 name = computerName;
219
220 if (!name)
221 return -1;
222
223 CharUpperA(name);
224 }
225
226 size_t len = 0;
227 sspi_SecBufferFree(&context->TargetName);
228 context->TargetName.pvBuffer = ConvertUtf8ToWCharAlloc(name, &len);
229
230 if (!context->TargetName.pvBuffer || (len > UINT16_MAX / sizeof(WCHAR)))
231 {
232 free(context->TargetName.pvBuffer);
233 context->TargetName.pvBuffer = nullptr;
234
235 if (!TargetName)
236 free(name);
237
238 return -1;
239 }
240
241 context->TargetName.cbBuffer = (USHORT)(len * sizeof(WCHAR));
242
243 if (!TargetName)
244 free(name);
245
246 return 1;
247}
248
249static void ntlm_ContextFree(NTLM_CONTEXT* context)
250{
251 if (!context)
252 return;
253
254 winpr_RC4_Free(context->SendRc4Seal);
255 winpr_RC4_Free(context->RecvRc4Seal);
256 sspi_SecBufferFree(&context->NegotiateMessage);
257 sspi_SecBufferFree(&context->ChallengeMessage);
258 sspi_SecBufferFree(&context->AuthenticateMessage);
259 sspi_SecBufferFree(&context->ChallengeTargetInfo);
260 sspi_SecBufferFree(&context->AuthenticateTargetInfo);
261 sspi_SecBufferFree(&context->TargetName);
262 sspi_SecBufferFree(&context->NtChallengeResponse);
263 sspi_SecBufferFree(&context->LmChallengeResponse);
264 ntlm_free_unicode_string(&context->ServicePrincipalName);
265 ntlm_free_unicode_string(&context->Workstation);
266 ntlm_free_unicode_string(&context->NbComputerName);
267 ntlm_free_unicode_string(&context->NbDomainName);
268 ntlm_free_unicode_string(&context->DnsComputerName);
269 ntlm_free_unicode_string(&context->DnsDomainName);
270
271 ntlm_free_messages(context);
272
273 /* Zero sensitive key material before freeing the context */
274 memset(context->NtlmHash, 0, sizeof(context->NtlmHash));
275 memset(context->NtlmV2Hash, 0, sizeof(context->NtlmV2Hash));
276 memset(context->SessionBaseKey, 0, sizeof(context->SessionBaseKey));
277 memset(context->KeyExchangeKey, 0, sizeof(context->KeyExchangeKey));
278 memset(context->RandomSessionKey, 0, sizeof(context->RandomSessionKey));
279 memset(context->ExportedSessionKey, 0, sizeof(context->ExportedSessionKey));
280 memset(context->EncryptedRandomSessionKey, 0, sizeof(context->EncryptedRandomSessionKey));
281 memset(context->NtProofString, 0, sizeof(context->NtProofString));
282 free(context);
283}
284
285WINPR_ATTR_NODISCARD
286static int ntlm_get_target_computer_name(PUNICODE_STRING pName,
287 WINPR_ATTR_UNUSED COMPUTER_NAME_FORMAT type)
288{
289 WINPR_ASSERT(pName);
290 ntlm_free_unicode_string(pName);
291
292 size_t len = 0;
293 char* name = get_computer_name(ComputerNameNetBIOS, &len);
294 if (!name)
295 return -1;
296
297 CharUpperA(name);
298
299 *pName = ntlm_from_unicode_string_utf8(name, len);
300 free(name);
301
302 return !ntlm_is_unicode_string_empty(pName);
303}
304
305WINPR_ATTR_NODISCARD
306static BOOL ntlm_ContextFillDefaultNames(NTLM_CONTEXT* context)
307{
308 WINPR_ASSERT(context);
309
310 if (ntlm_SetContextWorkstation(context, nullptr) < 0)
311 return FALSE;
312
313 if (ntlm_get_target_computer_name(&context->NbDomainName, ComputerNameNetBIOS) < 0)
314 return FALSE;
315
316 if (ntlm_get_target_computer_name(&context->NbComputerName, ComputerNameNetBIOS) < 0)
317 return FALSE;
318
319 if (ntlm_get_target_computer_name(&context->DnsDomainName, ComputerNameDnsDomain) < 0)
320 return FALSE;
321
322 if (ntlm_get_target_computer_name(&context->DnsComputerName, ComputerNameDnsHostname) < 0)
323 return FALSE;
324 return TRUE;
325}
326
327static BOOL ntlm_try_set_from_registry(HKEY hKey, const char* key, UNICODE_STRING* ustr)
328{
329 WINPR_ASSERT(hKey);
330 WINPR_ASSERT(key);
331
332 UNICODE_STRING str = WINPR_C_ARRAY_INIT;
333
334 WCHAR wkey[64] = WINPR_C_ARRAY_INIT;
335 const SSIZE_T res = ConvertUtf8ToWChar(key, wkey, ARRAYSIZE(wkey));
336 if (res < 0)
337 goto fail;
338 WINPR_ASSERT((size_t)res < ARRAYSIZE(wkey));
339
340 DWORD dwSize = 0;
341 DWORD dwType = 0;
342 if (RegQueryValueExW(hKey, wkey, nullptr, &dwType, nullptr, &dwSize) != ERROR_SUCCESS)
343 goto fail;
344
345 if ((dwSize > UINT16_MAX) || ((dwSize % 2) != 0))
346 goto fail;
347
348 str.Buffer = calloc(dwSize / sizeof(WCHAR) + 1, sizeof(WCHAR));
349 if (!str.Buffer)
350 goto fail;
351 str.Length = WINPR_ASSERTING_INT_CAST(UINT16, dwSize);
352 str.MaximumLength = WINPR_ASSERTING_INT_CAST(UINT16, dwSize);
353
354 const LONG rc = RegQueryValueExW(hKey, wkey, nullptr, &dwType, (BYTE*)str.Buffer, &dwSize);
355 if (rc != ERROR_SUCCESS)
356 goto fail;
357 ntlm_free_unicode_string(ustr);
358 *ustr = str;
359 return TRUE;
360
361fail:
362 ntlm_free_unicode_string(&str);
363 return FALSE;
364}
365
366WINPR_ATTR_NODISCARD
367static BOOL ntlm_ContextFromConfig(NTLM_CONTEXT* context)
368{
369 {
370 WINPR_ASSERT(context);
371
372 char* key = winpr_getApplicatonDetailsRegKey(WINPR_KEY);
373 if (key)
374 {
375 HKEY hKey = nullptr;
376
377 const LONG status =
378 RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
379 free(key);
380
381 if (status == ERROR_SUCCESS)
382 {
383 DWORD dwValue = 0;
384 DWORD dwSize = 0;
385 DWORD dwType = 0;
386
387 if (RegQueryValueEx(hKey, _T("NTLMv2"), nullptr, &dwType, (BYTE*)&dwValue,
388 &dwSize) == ERROR_SUCCESS)
389 context->NTLMv2 = dwValue ? 1 : 0;
390
391 if (RegQueryValueEx(hKey, _T("UseMIC"), nullptr, &dwType, (BYTE*)&dwValue,
392 &dwSize) == ERROR_SUCCESS)
393 context->UseMIC = dwValue ? 1 : 0;
394
395 if (RegQueryValueEx(hKey, _T("SendVersionInfo"), nullptr, &dwType, (BYTE*)&dwValue,
396 &dwSize) == ERROR_SUCCESS)
397 context->SendVersionInfo = dwValue ? 1 : 0;
398
399 if (RegQueryValueEx(hKey, _T("SendSingleHostData"), nullptr, &dwType,
400 (BYTE*)&dwValue, &dwSize) == ERROR_SUCCESS)
401 context->SendSingleHostData = dwValue ? 1 : 0;
402
403 if (RegQueryValueEx(hKey, _T("SendWorkstationName"), nullptr, &dwType,
404 (BYTE*)&dwValue, &dwSize) == ERROR_SUCCESS)
405 context->SendWorkstationName = dwValue ? 1 : 0;
406
407 (void)ntlm_try_set_from_registry(hKey, "WorkstationName", &context->Workstation);
408 (void)ntlm_try_set_from_registry(hKey, "NbDomainName", &context->NbDomainName);
409 (void)ntlm_try_set_from_registry(hKey, "NbComputerName", &context->NbComputerName);
410 (void)ntlm_try_set_from_registry(hKey, "DnsDomainName", &context->DnsDomainName);
411 (void)ntlm_try_set_from_registry(hKey, "DnsComputerName",
412 &context->DnsComputerName);
413
414 RegCloseKey(hKey);
415 }
416 }
417 }
418
419 HKEY hKey = nullptr;
420 const LONG status =
421 RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\LSA"), 0,
422 KEY_READ | KEY_WOW64_64KEY, &hKey);
423
424 if (status == ERROR_SUCCESS)
425 {
426 DWORD dwType = 0;
427 DWORD dwSize = 0;
428 DWORD dwValue = 0;
429 if (RegQueryValueEx(hKey, _T("SuppressExtendedProtection"), nullptr, &dwType,
430 (BYTE*)&dwValue, &dwSize) == ERROR_SUCCESS)
431 context->SuppressExtendedProtection = dwValue ? 1 : 0;
432
433 RegCloseKey(hKey);
434 }
435
436 /*
437 * Extended Protection is enabled by default in Windows 7,
438 * but enabling it in WinPR breaks TS Gateway at this point
439 */
440 context->SuppressExtendedProtection = FALSE;
441 return TRUE;
442}
443
444WINPR_ATTR_MALLOC(ntlm_ContextFree, 1)
445static NTLM_CONTEXT* ntlm_ContextNew(void)
446{
447 NTLM_CONTEXT* context = (NTLM_CONTEXT*)calloc(1, sizeof(NTLM_CONTEXT));
448
449 if (!context)
450 return nullptr;
451
452 context->NTLMv2 = TRUE;
453 context->UseMIC = FALSE;
454 context->SendVersionInfo = TRUE;
455 context->SendSingleHostData = FALSE;
456 context->SendWorkstationName = TRUE;
457 context->NegotiateKeyExchange = TRUE;
458 context->UseSamFileDatabase = TRUE;
459
460 context->NegotiateFlags = 0;
461 context->LmCompatibilityLevel = 3;
462 ntlm_change_state(context, NTLM_STATE_INITIAL);
463 FillMemory(context->MachineID, sizeof(context->MachineID), 0xAA);
464
465 if (context->NTLMv2)
466 context->UseMIC = TRUE;
467
468 if (!ntlm_ContextFillDefaultNames(context))
469 goto fail;
470 if (!ntlm_ContextFromConfig(context))
471 goto fail;
472
473 return context;
474
475fail:
476 ntlm_ContextFree(context);
477 return nullptr;
478}
479
480WINPR_ATTR_NODISCARD
481static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
482 WINPR_ATTR_UNUSED SEC_WCHAR* pszPrincipal, WINPR_ATTR_UNUSED SEC_WCHAR* pszPackage,
483 ULONG fCredentialUse, WINPR_ATTR_UNUSED void* pvLogonID, void* pAuthData,
484 SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
485 WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
486{
487 if ((fCredentialUse != SECPKG_CRED_OUTBOUND) && (fCredentialUse != SECPKG_CRED_INBOUND) &&
488 (fCredentialUse != SECPKG_CRED_BOTH))
489 {
490 return SEC_E_INVALID_PARAMETER;
491 }
492
493 SSPI_CREDENTIALS* credentials = sspi_CredentialsNew();
494
495 if (!credentials)
496 return SEC_E_INTERNAL_ERROR;
497
498 credentials->fCredentialUse = fCredentialUse;
499 credentials->pGetKeyFn = pGetKeyFn;
500 credentials->pvGetKeyArgument = pvGetKeyArgument;
501
502#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
503 SEC_WINPR_NTLM_SETTINGS* settingsV1 = nullptr;
504#endif
505 SEC_WINPR_NTLM_SETTINGS_V2* settingsV2 = nullptr;
506 if (pAuthData)
507 {
508 UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData);
509
510 if (sspi_CopyAuthIdentity(&(credentials->identity),
511 (const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData) < 0)
512 {
513 sspi_CredentialsFree(credentials);
514 return SEC_E_INVALID_PARAMETER;
515 }
516
517#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
518 if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED)
519 settingsV1 = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->ntlmSettings);
520#endif
521
522 if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED_v2)
523 {
524 const SEC_WINNT_AUTH_IDENTITY_WINPR_V2* auth =
525 (const SEC_WINNT_AUTH_IDENTITY_WINPR_V2*)pAuthData;
526 WINPR_ASSERT(auth);
527 if (auth->version < SEC_WINNT_AUTH_IDENTITY_WINPR_V2_REVISION_1)
528 return SEC_E_INVALID_PARAMETER;
529 settingsV2 = auth->ntlmSettingsV2;
530 }
531 }
532
533#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
534 if (settingsV1)
535 {
536 if (settingsV1->samFile)
537 {
538 if (!sspi_CloneSecSettingsString(&credentials->ntlmSettingsV2->samFile,
539 settingsV1->samFile))
540 {
541 sspi_CredentialsFree(credentials);
542 return SEC_E_INSUFFICIENT_MEMORY;
543 }
544 }
545 credentials->ntlmSettingsV2->hashCallback = settingsV1->hashCallback;
546 credentials->ntlmSettingsV2->hashCallbackArg = settingsV1->hashCallbackArg;
547 }
548#endif
549
550 if (settingsV2)
551 {
552 sspi_FreeSecNtlmSettings(credentials->ntlmSettingsV2);
553 credentials->ntlmSettingsV2 = sspi_CloneSecNtlmSettings(settingsV2);
554 if (!credentials->ntlmSettingsV2)
555 {
556 sspi_CredentialsFree(credentials);
557 return SEC_E_INVALID_PARAMETER;
558 }
559 }
560
561 sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials);
562 sspi_SecureHandleSetPackageId(phCredential, SSPI_PACKAGE_NTLM);
563 return SEC_E_OK;
564}
565
566WINPR_ATTR_NODISCARD
567static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
568 SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
569 void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
570 PTimeStamp ptsExpiry)
571{
572 SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY;
573 SEC_WCHAR* principal = nullptr;
574 SEC_WCHAR* package = nullptr;
575
576 if (pszPrincipal)
577 {
578 principal = ConvertUtf8ToWCharAlloc(pszPrincipal, nullptr);
579 if (!principal)
580 goto fail;
581 }
582 if (pszPackage)
583 {
584 package = ConvertUtf8ToWCharAlloc(pszPackage, nullptr);
585 if (!package)
586 goto fail;
587 }
588
589 status =
590 ntlm_AcquireCredentialsHandleW(principal, package, fCredentialUse, pvLogonID, pAuthData,
591 pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
592
593fail:
594 free(principal);
595 free(package);
596
597 return status;
598}
599
600WINPR_ATTR_NODISCARD
601static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(PCredHandle phCredential)
602{
603 if (!phCredential)
604 return SEC_E_INVALID_HANDLE;
605
606 SSPI_CREDENTIALS* credentials =
607 (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
608 sspi_SecureHandleInvalidate(phCredential);
609 if (!credentials)
610 return SEC_E_INVALID_HANDLE;
611
612 sspi_CredentialsFree(credentials);
613 return SEC_E_OK;
614}
615
616WINPR_ATTR_NODISCARD
617static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
618 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
619 WINPR_ATTR_UNUSED void* pBuffer)
620{
621 if (ulAttribute == SECPKG_CRED_ATTR_NAMES)
622 {
623 return SEC_E_OK;
624 }
625
626 WLog_ERR(TAG, "TODO: Implement");
627 return SEC_E_UNSUPPORTED_FUNCTION;
628}
629
630WINPR_ATTR_NODISCARD
631static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(PCredHandle phCredential,
632 ULONG ulAttribute, void* pBuffer)
633{
634 return ntlm_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
635}
636
637WINPR_ATTR_NODISCARD
638static SECURITY_STATUS ntml_setUnicodeStringA(UNICODE_STRING* str, const char* val, size_t charlen);
639
643WINPR_ATTR_NODISCARD
644static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
645 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq,
646 WINPR_ATTR_UNUSED ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput,
647 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED PTimeStamp ptsTimeStamp)
648{
649 SECURITY_STATUS status = 0;
650 SSPI_CREDENTIALS* credentials = nullptr;
651 PSecBuffer input_buffer = nullptr;
652 PSecBuffer output_buffer = nullptr;
653
654 /* behave like windows SSPIs that don't want empty context */
655 if (phContext && !phContext->dwLower && !phContext->dwUpper)
656 return SEC_E_INVALID_HANDLE;
657
658 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
659
660 if (!context)
661 {
662 context = ntlm_ContextNew();
663
664 if (!context)
665 return SEC_E_INSUFFICIENT_MEMORY;
666
667 context->server = TRUE;
668
669 if (fContextReq & ASC_REQ_CONFIDENTIALITY)
670 context->confidentiality = TRUE;
671
672 credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
673 context->credentials = credentials;
674 context->SamFile = credentials->ntlmSettingsV2->samFile;
675 context->HashCallback = credentials->ntlmSettingsV2->hashCallback;
676 context->HashCallbackArg = credentials->ntlmSettingsV2->hashCallbackArg;
677
678 if (credentials->ntlmSettingsV2->dnsComputerName)
679 {
680 const SECURITY_STATUS rc = ntml_setUnicodeStringA(
681 &context->DnsComputerName, credentials->ntlmSettingsV2->dnsComputerName,
682 strlen(credentials->ntlmSettingsV2->dnsComputerName));
683 if (SEC_E_OK != rc)
684 return rc;
685 }
686
687 if (credentials->ntlmSettingsV2->dnsDomainName)
688 {
689 const SECURITY_STATUS rc = ntml_setUnicodeStringA(
690 &context->DnsDomainName, credentials->ntlmSettingsV2->dnsDomainName,
691 strlen(credentials->ntlmSettingsV2->dnsDomainName));
692 if (SEC_E_OK != rc)
693 return rc;
694 }
695
696 if (credentials->ntlmSettingsV2->netBiosComputerName)
697 {
698 const SECURITY_STATUS rc = ntml_setUnicodeStringA(
699 &context->NbComputerName, credentials->ntlmSettingsV2->netBiosComputerName,
700 strlen(credentials->ntlmSettingsV2->netBiosComputerName));
701 if (SEC_E_OK != rc)
702 return rc;
703 }
704
705 if (credentials->ntlmSettingsV2->netBiosDomainName)
706 {
707 const SECURITY_STATUS rc = ntml_setUnicodeStringA(
708 &context->NbDomainName, credentials->ntlmSettingsV2->netBiosDomainName,
709 strlen(credentials->ntlmSettingsV2->netBiosDomainName));
710 if (SEC_E_OK != rc)
711 return rc;
712 }
713
714 if (!ntlm_SetContextTargetName(context, credentials->ntlmSettingsV2->targetName))
715 return SEC_E_INVALID_HANDLE;
716 sspi_SecureHandleSetLowerPointer(phNewContext, context);
717 sspi_SecureHandleSetPackageId(phNewContext, SSPI_PACKAGE_NTLM);
718 }
719
720 switch (ntlm_get_state(context))
721 {
722 case NTLM_STATE_INITIAL:
723 {
724 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
725
726 if (!pInput)
727 return SEC_E_INVALID_TOKEN;
728
729 if (pInput->cBuffers < 1)
730 return SEC_E_INVALID_TOKEN;
731
732 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
733
734 if (!input_buffer)
735 return SEC_E_INVALID_TOKEN;
736
737 if (input_buffer->cbBuffer < 1)
738 return SEC_E_INVALID_TOKEN;
739
740 status = ntlm_read_NegotiateMessage(context, input_buffer);
741 if (status != SEC_I_CONTINUE_NEEDED)
742 return status;
743
744 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
745 {
746 if (!pOutput)
747 return SEC_E_INVALID_TOKEN;
748
749 if (pOutput->cBuffers < 1)
750 return SEC_E_INVALID_TOKEN;
751
752 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
753
754 if (!output_buffer->BufferType)
755 return SEC_E_INVALID_TOKEN;
756
757 if (output_buffer->cbBuffer < 1)
758 return SEC_E_INSUFFICIENT_MEMORY;
759
760 return ntlm_write_ChallengeMessage(context, output_buffer);
761 }
762
763 return SEC_E_OUT_OF_SEQUENCE;
764 }
765
766 case NTLM_STATE_AUTHENTICATE:
767 {
768 if (!pInput)
769 return SEC_E_INVALID_TOKEN;
770
771 if (pInput->cBuffers < 1)
772 return SEC_E_INVALID_TOKEN;
773
774 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
775
776 if (!input_buffer)
777 return SEC_E_INVALID_TOKEN;
778
779 if (input_buffer->cbBuffer < 1)
780 return SEC_E_INVALID_TOKEN;
781
782 status = ntlm_read_AuthenticateMessage(context, input_buffer);
783
784 if (pOutput)
785 {
786 for (ULONG i = 0; i < pOutput->cBuffers; i++)
787 {
788 pOutput->pBuffers[i].cbBuffer = 0;
789 pOutput->pBuffers[i].BufferType = SECBUFFER_TOKEN;
790 }
791 }
792
793 return status;
794 }
795
796 default:
797 return SEC_E_OUT_OF_SEQUENCE;
798 }
799}
800
801WINPR_ATTR_NODISCARD
802static SECURITY_STATUS SEC_ENTRY
803ntlm_ImpersonateSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
804{
805 return SEC_E_OK;
806}
807
808WINPR_ATTR_NODISCARD
809static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
810 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq,
811 WINPR_ATTR_UNUSED ULONG Reserved1, WINPR_ATTR_UNUSED ULONG TargetDataRep, PSecBufferDesc pInput,
812 WINPR_ATTR_UNUSED ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput,
813 WINPR_ATTR_UNUSED PULONG pfContextAttr, WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
814{
815 SECURITY_STATUS status = 0;
816 SSPI_CREDENTIALS* credentials = nullptr;
817 PSecBuffer input_buffer = nullptr;
818 PSecBuffer output_buffer = nullptr;
819
820 /* behave like windows SSPIs that don't want empty context */
821 if (phContext && !phContext->dwLower && !phContext->dwUpper)
822 return SEC_E_INVALID_HANDLE;
823
824 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
825
826 if (pInput)
827 {
828 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
829 }
830
831 if (!context)
832 {
833 context = ntlm_ContextNew();
834
835 if (!context)
836 return SEC_E_INSUFFICIENT_MEMORY;
837
838 if (fContextReq & ISC_REQ_CONFIDENTIALITY)
839 context->confidentiality = TRUE;
840
841 credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential);
842 context->credentials = credentials;
843
844 if (ntlm_SetContextServicePrincipalNameW(context, pszTargetName) < 0)
845 {
846 ntlm_ContextFree(context);
847 return SEC_E_INTERNAL_ERROR;
848 }
849
850 sspi_SecureHandleSetLowerPointer(phNewContext, context);
851 sspi_SecureHandleSetPackageId(phNewContext, SSPI_PACKAGE_NTLM);
852 }
853
854 if ((!input_buffer) || (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE))
855 {
856 if (!pOutput)
857 return SEC_E_INVALID_TOKEN;
858
859 if (pOutput->cBuffers < 1)
860 return SEC_E_INVALID_TOKEN;
861
862 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
863
864 if (!output_buffer)
865 return SEC_E_INVALID_TOKEN;
866
867 if (output_buffer->cbBuffer < 1)
868 return SEC_E_INVALID_TOKEN;
869
870 if (ntlm_get_state(context) == NTLM_STATE_INITIAL)
871 ntlm_change_state(context, NTLM_STATE_NEGOTIATE);
872
873 if (ntlm_get_state(context) == NTLM_STATE_NEGOTIATE)
874 return ntlm_write_NegotiateMessage(context, output_buffer);
875
876 return SEC_E_OUT_OF_SEQUENCE;
877 }
878 else
879 {
880 if (!input_buffer)
881 return SEC_E_INVALID_TOKEN;
882
883 if (input_buffer->cbBuffer < 1)
884 return SEC_E_INVALID_TOKEN;
885
886 PSecBuffer channel_bindings = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
887
888 if (channel_bindings)
889 {
890 context->Bindings.BindingsLength = channel_bindings->cbBuffer;
891 context->Bindings.Bindings = (SEC_CHANNEL_BINDINGS*)channel_bindings->pvBuffer;
892 }
893
894 if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE)
895 {
896 status = ntlm_read_ChallengeMessage(context, input_buffer);
897
898 if (status != SEC_I_CONTINUE_NEEDED)
899 return status;
900
901 if (!pOutput)
902 return SEC_E_INVALID_TOKEN;
903
904 if (pOutput->cBuffers < 1)
905 return SEC_E_INVALID_TOKEN;
906
907 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
908
909 if (!output_buffer)
910 return SEC_E_INVALID_TOKEN;
911
912 if (output_buffer->cbBuffer < 1)
913 return SEC_E_INSUFFICIENT_MEMORY;
914
915 if (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE)
916 return ntlm_write_AuthenticateMessage(context, output_buffer);
917 }
918
919 return SEC_E_OUT_OF_SEQUENCE;
920 }
921
922 return SEC_E_OUT_OF_SEQUENCE;
923}
924
928WINPR_ATTR_NODISCARD
929static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
930 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq,
931 ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
932 PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
933{
934 SECURITY_STATUS status = 0;
935 SEC_WCHAR* pszTargetNameW = nullptr;
936
937 if (pszTargetName)
938 {
939 pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, nullptr);
940 if (!pszTargetNameW)
941 return SEC_E_INTERNAL_ERROR;
942 }
943
944 status = ntlm_InitializeSecurityContextW(phCredential, phContext, pszTargetNameW, fContextReq,
945 Reserved1, TargetDataRep, pInput, Reserved2,
946 phNewContext, pOutput, pfContextAttr, ptsExpiry);
947 free(pszTargetNameW);
948 return status;
949}
950
951/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375354 */
952WINPR_ATTR_NODISCARD
953static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
954{
955 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
956 sspi_SecureHandleInvalidate(phContext);
957 ntlm_ContextFree(context);
958 return SEC_E_OK;
959}
960
961SECURITY_STATUS ntlm_computeProofValue(NTLM_CONTEXT* ntlm, SecBuffer* ntproof)
962{
963 BYTE* blob = nullptr;
964 SecBuffer* target = nullptr;
965
966 WINPR_ASSERT(ntlm);
967 WINPR_ASSERT(ntproof);
968
969 target = &ntlm->ChallengeTargetInfo;
970
971 if (!sspi_SecBufferAlloc(ntproof, 36 + target->cbBuffer))
972 return SEC_E_INSUFFICIENT_MEMORY;
973
974 blob = (BYTE*)ntproof->pvBuffer;
975 CopyMemory(blob, ntlm->ServerChallenge, 8); /* Server challenge. */
976 blob[8] = 1; /* Response version. */
977 blob[9] = 1; /* Highest response version understood by the client. */
978 /* Reserved 6B. */
979 CopyMemory(&blob[16], ntlm->Timestamp, 8); /* Time. */
980 CopyMemory(&blob[24], ntlm->ClientChallenge, 8); /* Client challenge. */
981 /* Reserved 4B. */
982 /* Server name. */
983 CopyMemory(&blob[36], target->pvBuffer, target->cbBuffer);
984 return SEC_E_OK;
985}
986
987SECURITY_STATUS ntlm_computeMicValue(NTLM_CONTEXT* ntlm, SecBuffer* micvalue)
988{
989 BYTE* blob = nullptr;
990 ULONG msgSize = 0;
991
992 WINPR_ASSERT(ntlm);
993 WINPR_ASSERT(micvalue);
994
995 msgSize = ntlm->NegotiateMessage.cbBuffer + ntlm->ChallengeMessage.cbBuffer +
996 ntlm->AuthenticateMessage.cbBuffer;
997
998 if (!sspi_SecBufferAlloc(micvalue, msgSize))
999 return SEC_E_INSUFFICIENT_MEMORY;
1000
1001 blob = (BYTE*)micvalue->pvBuffer;
1002 CopyMemory(blob, ntlm->NegotiateMessage.pvBuffer, ntlm->NegotiateMessage.cbBuffer);
1003 blob += ntlm->NegotiateMessage.cbBuffer;
1004 CopyMemory(blob, ntlm->ChallengeMessage.pvBuffer, ntlm->ChallengeMessage.cbBuffer);
1005 blob += ntlm->ChallengeMessage.cbBuffer;
1006 CopyMemory(blob, ntlm->AuthenticateMessage.pvBuffer, ntlm->AuthenticateMessage.cbBuffer);
1007 blob += ntlm->MessageIntegrityCheckOffset;
1008 ZeroMemory(blob, 16);
1009 return SEC_E_OK;
1010}
1011
1012WINPR_ATTR_NODISCARD
1013static bool identityToAuthIdentity(const SEC_WINNT_AUTH_IDENTITY* identity,
1014 SecPkgContext_AuthIdentity* pAuthIdentity)
1015{
1016 WINPR_ASSERT(identity);
1017
1018 if (!pAuthIdentity)
1019 return false;
1020
1021 const SecPkgContext_AuthIdentity empty = WINPR_C_ARRAY_INIT;
1022 *pAuthIdentity = empty;
1023
1024 if ((identity->Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE) != 0)
1025 {
1026 if (identity->UserLength > 0)
1027 {
1028 if (ConvertWCharNToUtf8(identity->User, identity->UserLength, pAuthIdentity->User,
1029 ARRAYSIZE(pAuthIdentity->User)) <= 0)
1030 return false;
1031 }
1032
1033 if (identity->DomainLength > 0)
1034 {
1035 if (ConvertWCharNToUtf8(identity->Domain, identity->DomainLength, pAuthIdentity->Domain,
1036 ARRAYSIZE(pAuthIdentity->Domain)) <= 0)
1037 return false;
1038 }
1039 }
1040 else if ((identity->Flags & SEC_WINNT_AUTH_IDENTITY_ANSI) != 0)
1041 {
1042 if (identity->UserLength > 0)
1043 {
1044 const size_t len = MIN(ARRAYSIZE(pAuthIdentity->User) - 1, identity->UserLength);
1045 strncpy(pAuthIdentity->User, (char*)identity->User, len);
1046 pAuthIdentity->User[len] = '\0';
1047 }
1048
1049 if (identity->DomainLength > 0)
1050 {
1051 const size_t len = MIN(ARRAYSIZE(pAuthIdentity->Domain) - 1, identity->DomainLength);
1052 strncpy(pAuthIdentity->Domain, (char*)identity->Domain, len);
1053 pAuthIdentity->Domain[len] = '\0';
1054 }
1055 }
1056 else
1057 return false;
1058 return true;
1059}
1060
1061WINPR_ATTR_NODISCARD
1062static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesCommon(PCtxtHandle phContext,
1063 ULONG ulAttribute, void* pBuffer)
1064{
1065 if (!phContext)
1066 return SEC_E_INVALID_HANDLE;
1067
1068 if (!pBuffer)
1069 return SEC_E_INSUFFICIENT_MEMORY;
1070
1071 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1072 if (!check_context(context))
1073 return SEC_E_INVALID_HANDLE;
1074
1075 switch (ulAttribute)
1076 {
1077 case SECPKG_ATTR_AUTH_IDENTITY:
1078 {
1080 SSPI_CREDENTIALS* credentials = context->credentials;
1081 if (!credentials)
1082 return SEC_E_INTERNAL_ERROR;
1083 if (!identityToAuthIdentity(&credentials->identity, AuthIdentity))
1084 return SEC_E_INTERNAL_ERROR;
1085 context->UseSamFileDatabase = FALSE;
1086 return SEC_E_OK;
1087 }
1088 case SECPKG_ATTR_SIZES:
1089 {
1090 SecPkgContext_Sizes* ContextSizes = (SecPkgContext_Sizes*)pBuffer;
1091 ContextSizes->cbMaxToken = 2010;
1092 ContextSizes->cbMaxSignature = 16; /* the size of expected signature is 16 bytes */
1093 ContextSizes->cbBlockSize = 0; /* no padding */
1094 ContextSizes->cbSecurityTrailer = 16; /* no security trailer appended in NTLM
1095 contrary to Kerberos */
1096 return SEC_E_OK;
1097 }
1098 case SECPKG_ATTR_AUTH_NTLM_NTPROOF_VALUE:
1099 return ntlm_computeProofValue(context, (SecBuffer*)pBuffer);
1100
1101 case SECPKG_ATTR_AUTH_NTLM_RANDKEY:
1102 {
1103 SecBuffer* randkey = (SecBuffer*)pBuffer;
1104
1105 if (!sspi_SecBufferAlloc(randkey, 16))
1106 return (SEC_E_INSUFFICIENT_MEMORY);
1107
1108 CopyMemory(randkey->pvBuffer, context->EncryptedRandomSessionKey, 16);
1109 return (SEC_E_OK);
1110 }
1111
1112 case SECPKG_ATTR_AUTH_NTLM_MIC:
1113 {
1114 SecBuffer* mic = (SecBuffer*)pBuffer;
1115 NTLM_AUTHENTICATE_MESSAGE* message = &context->AUTHENTICATE_MESSAGE;
1116
1117 if (!sspi_SecBufferAlloc(mic, 16))
1118 return (SEC_E_INSUFFICIENT_MEMORY);
1119
1120 CopyMemory(mic->pvBuffer, message->MessageIntegrityCheck, 16);
1121 return (SEC_E_OK);
1122 }
1123
1124 case SECPKG_ATTR_AUTH_NTLM_MIC_VALUE:
1125 return ntlm_computeMicValue(context, (SecBuffer*)pBuffer);
1126
1127 default:
1128 WLog_ERR(TAG, "TODO: Implement ulAttribute=0x%08" PRIx32, ulAttribute);
1129 return SEC_E_UNSUPPORTED_FUNCTION;
1130 }
1131}
1132
1133/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa379337/ */
1134WINPR_ATTR_NODISCARD
1135static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1136 ULONG ulAttribute, void* pBuffer)
1137{
1138 if (!phContext)
1139 return SEC_E_INVALID_HANDLE;
1140
1141 if (!pBuffer)
1142 return SEC_E_INSUFFICIENT_MEMORY;
1143
1144 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1145 if (!check_context(context))
1146 return SEC_E_INVALID_HANDLE;
1147
1148 switch (ulAttribute)
1149 {
1150 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME:
1151 {
1152 memcpy(pBuffer, context->Workstation.Buffer, context->Workstation.Length);
1153 return SEC_E_OK;
1154 }
1155 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME:
1156 {
1157 memcpy(pBuffer, context->NbDomainName.Buffer, context->NbDomainName.Length);
1158 return SEC_E_OK;
1159 }
1160 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME:
1161 {
1162 memcpy(pBuffer, context->NbComputerName.Buffer, context->NbComputerName.Length);
1163 return SEC_E_OK;
1164 }
1165 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME:
1166 {
1167 memcpy(pBuffer, context->DnsDomainName.Buffer, context->DnsDomainName.Length);
1168 return SEC_E_OK;
1169 }
1170 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME:
1171 {
1172 memcpy(pBuffer, context->DnsComputerName.Buffer, context->DnsComputerName.Length);
1173 return SEC_E_OK;
1174 }
1175
1176 case SECPKG_ATTR_PACKAGE_INFO:
1177 {
1179 size_t size = sizeof(SecPkgInfoW);
1180 SecPkgInfoW* pPackageInfo =
1181 (SecPkgInfoW*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size);
1182
1183 if (!pPackageInfo)
1184 return SEC_E_INSUFFICIENT_MEMORY;
1185
1186 pPackageInfo->fCapabilities = NTLM_SecPkgInfoW.fCapabilities;
1187 pPackageInfo->wVersion = NTLM_SecPkgInfoW.wVersion;
1188 pPackageInfo->wRPCID = NTLM_SecPkgInfoW.wRPCID;
1189 pPackageInfo->cbMaxToken = NTLM_SecPkgInfoW.cbMaxToken;
1190 pPackageInfo->Name = _wcsdup(NTLM_SecPkgInfoW.Name);
1191 pPackageInfo->Comment = _wcsdup(NTLM_SecPkgInfoW.Comment);
1192
1193 if (!pPackageInfo->Name || !pPackageInfo->Comment)
1194 {
1195 sspi_ContextBufferFree(pPackageInfo);
1196 return SEC_E_INSUFFICIENT_MEMORY;
1197 }
1198 PackageInfo->PackageInfo = pPackageInfo;
1199 return SEC_E_OK;
1200 }
1201 default:
1202 return ntlm_QueryContextAttributesCommon(phContext, ulAttribute, pBuffer);
1203 }
1204}
1205
1206WINPR_ATTR_NODISCARD
1207static SECURITY_STATUS utf8len(const UNICODE_STRING* str, void* pBuffer)
1208{
1209 WINPR_ASSERT(str);
1210 WINPR_ASSERT(pBuffer);
1211 ULONG* val = (ULONG*)pBuffer;
1212 const size_t wlen = str->Length / sizeof(WCHAR);
1213 const SSIZE_T rc = ConvertWCharNToUtf8(str->Buffer, wlen, nullptr, 0);
1214 if (rc < 0)
1215 return SEC_E_INVALID_PARAMETER;
1216 *val = WINPR_ASSERTING_INT_CAST(ULONG, rc);
1217 return SEC_E_OK;
1218}
1219
1220WINPR_ATTR_NODISCARD
1221static SECURITY_STATUS utf8str(const UNICODE_STRING* str, void* pBuffer)
1222{
1223 WINPR_ASSERT(str);
1224 WINPR_ASSERT(pBuffer);
1225 ULONG len = 0;
1226
1227 const SECURITY_STATUS status = utf8len(str, &len);
1228 if (status != SEC_E_OK)
1229 return status;
1230 if (len == 0)
1231 return SEC_E_OK;
1232
1233 const size_t wlen = str->Length / sizeof(WCHAR);
1234 const SSIZE_T rc = ConvertWCharNToUtf8(str->Buffer, wlen, pBuffer, (size_t)len);
1235 return rc < 0 ? SEC_E_INVALID_PARAMETER : SEC_E_OK;
1236}
1237
1238WINPR_ATTR_NODISCARD
1239static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1240 ULONG ulAttribute, void* pBuffer)
1241{
1242 if (!phContext)
1243 return SEC_E_INVALID_HANDLE;
1244
1245 if (!pBuffer)
1246 return SEC_E_INSUFFICIENT_MEMORY;
1247
1248 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1249
1250 switch (ulAttribute)
1251 {
1252 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME_LEN:
1253 return utf8len(&context->Workstation, pBuffer);
1254 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME_LEN:
1255 return utf8len(&context->NbDomainName, pBuffer);
1256 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME_LEN:
1257 return utf8len(&context->NbComputerName, pBuffer);
1258 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME_LEN:
1259 return utf8len(&context->DnsDomainName, pBuffer);
1260 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME_LEN:
1261 return utf8len(&context->DnsComputerName, pBuffer);
1262 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME:
1263 return utf8str(&context->Workstation, pBuffer);
1264 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME:
1265 return utf8str(&context->NbDomainName, pBuffer);
1266 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME:
1267 return utf8str(&context->NbComputerName, pBuffer);
1268 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME:
1269 return utf8str(&context->DnsDomainName, pBuffer);
1270 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME:
1271 return utf8str(&context->DnsComputerName, pBuffer);
1272 case SECPKG_ATTR_PACKAGE_INFO:
1273 {
1275 size_t size = sizeof(SecPkgInfoA);
1276 SecPkgInfoA* pPackageInfo =
1277 (SecPkgInfoA*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size);
1278
1279 if (!pPackageInfo)
1280 return SEC_E_INSUFFICIENT_MEMORY;
1281
1282 pPackageInfo->fCapabilities = NTLM_SecPkgInfoA.fCapabilities;
1283 pPackageInfo->wVersion = NTLM_SecPkgInfoA.wVersion;
1284 pPackageInfo->wRPCID = NTLM_SecPkgInfoA.wRPCID;
1285 pPackageInfo->cbMaxToken = NTLM_SecPkgInfoA.cbMaxToken;
1286 pPackageInfo->Name = _strdup(NTLM_SecPkgInfoA.Name);
1287 pPackageInfo->Comment = _strdup(NTLM_SecPkgInfoA.Comment);
1288
1289 if (!pPackageInfo->Name || !pPackageInfo->Comment)
1290 {
1291 sspi_ContextBufferFree(pPackageInfo);
1292 return SEC_E_INSUFFICIENT_MEMORY;
1293 }
1294 PackageInfo->PackageInfo = pPackageInfo;
1295 return SEC_E_OK;
1296 }
1297
1298 default:
1299 return ntlm_QueryContextAttributesCommon(phContext, ulAttribute, pBuffer);
1300 }
1301}
1302
1303WINPR_ATTR_NODISCARD
1304static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesCommon(PCtxtHandle phContext,
1305 ULONG ulAttribute, void* pBuffer,
1306 ULONG cbBuffer)
1307{
1308 if (!phContext)
1309 return SEC_E_INVALID_HANDLE;
1310
1311 if (!pBuffer)
1312 return SEC_E_INVALID_PARAMETER;
1313
1314 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1315 if (!context)
1316 return SEC_E_INVALID_HANDLE;
1317
1318 switch (ulAttribute)
1319 {
1320 case SECPKG_ATTR_AUTH_NTLM_HASH:
1321 {
1323
1324 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmHash))
1325 return SEC_E_INVALID_PARAMETER;
1326
1327 if (AuthNtlmHash->Version == 1)
1328 CopyMemory(context->NtlmHash, AuthNtlmHash->NtlmHash, 16);
1329 else if (AuthNtlmHash->Version == 2)
1330 CopyMemory(context->NtlmV2Hash, AuthNtlmHash->NtlmHash, 16);
1331
1332 return SEC_E_OK;
1333 }
1334
1335 case SECPKG_ATTR_AUTH_NTLM_MESSAGE:
1336 {
1337 SecPkgContext_AuthNtlmMessage* AuthNtlmMessage =
1339
1340 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmMessage))
1341 return SEC_E_INVALID_PARAMETER;
1342
1343 if (AuthNtlmMessage->type == 1)
1344 {
1345 if (!ntlm_SecBufferRealloc(&context->NegotiateMessage, AuthNtlmMessage->length))
1346 return SEC_E_INSUFFICIENT_MEMORY;
1347
1348 CopyMemory(context->NegotiateMessage.pvBuffer, AuthNtlmMessage->buffer,
1349 AuthNtlmMessage->length);
1350 }
1351 else if (AuthNtlmMessage->type == 2)
1352 {
1353 if (!ntlm_SecBufferRealloc(&context->ChallengeMessage, AuthNtlmMessage->length))
1354 return SEC_E_INSUFFICIENT_MEMORY;
1355
1356 CopyMemory(context->ChallengeMessage.pvBuffer, AuthNtlmMessage->buffer,
1357 AuthNtlmMessage->length);
1358 }
1359 else if (AuthNtlmMessage->type == 3)
1360 {
1361 if (!ntlm_SecBufferRealloc(&context->AuthenticateMessage, AuthNtlmMessage->length))
1362 return SEC_E_INSUFFICIENT_MEMORY;
1363
1364 CopyMemory(context->AuthenticateMessage.pvBuffer, AuthNtlmMessage->buffer,
1365 AuthNtlmMessage->length);
1366 }
1367
1368 return SEC_E_OK;
1369 }
1370
1371 case SECPKG_ATTR_AUTH_NTLM_TIMESTAMP:
1372 {
1373 SecPkgContext_AuthNtlmTimestamp* AuthNtlmTimestamp =
1375
1376 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmTimestamp))
1377 return SEC_E_INVALID_PARAMETER;
1378
1379 if (AuthNtlmTimestamp->ChallengeOrResponse)
1380 CopyMemory(context->ChallengeTimestamp, AuthNtlmTimestamp->Timestamp, 8);
1381 else
1382 CopyMemory(context->Timestamp, AuthNtlmTimestamp->Timestamp, 8);
1383
1384 return SEC_E_OK;
1385 }
1386
1387 case SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE:
1388 {
1389 SecPkgContext_AuthNtlmClientChallenge* AuthNtlmClientChallenge =
1391
1392 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmClientChallenge))
1393 return SEC_E_INVALID_PARAMETER;
1394
1395 CopyMemory(context->ClientChallenge, AuthNtlmClientChallenge->ClientChallenge, 8);
1396 return SEC_E_OK;
1397 }
1398
1399 case SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE:
1400 {
1401 SecPkgContext_AuthNtlmServerChallenge* AuthNtlmServerChallenge =
1403
1404 if (cbBuffer < sizeof(SecPkgContext_AuthNtlmServerChallenge))
1405 return SEC_E_INVALID_PARAMETER;
1406
1407 CopyMemory(context->ServerChallenge, AuthNtlmServerChallenge->ServerChallenge, 8);
1408 return SEC_E_OK;
1409 }
1410
1411 default:
1412 WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute);
1413 return SEC_E_UNSUPPORTED_FUNCTION;
1414 }
1415}
1416
1417WINPR_ATTR_NODISCARD
1418static SECURITY_STATUS ntml_setUnicodeStringW(UNICODE_STRING* str, const WCHAR* val, size_t bytelen)
1419{
1420 WINPR_ASSERT(str);
1421 ntlm_free_unicode_string(str);
1422 *str = ntlm_from_unicode_string_w(val, bytelen / sizeof(WCHAR));
1423 if (ntlm_is_unicode_string_empty(str))
1424 return SEC_E_INVALID_PARAMETER;
1425 return SEC_E_OK;
1426}
1427
1428WINPR_ATTR_NODISCARD
1429static SECURITY_STATUS utf16len(const UNICODE_STRING* str, void* pBuffer)
1430{
1431 WINPR_ASSERT(str);
1432 WINPR_ASSERT(pBuffer);
1433 ULONG* val = (ULONG*)pBuffer;
1434 *val = str->Length;
1435 return SEC_E_OK;
1436}
1437
1438WINPR_ATTR_NODISCARD
1439static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesW(PCtxtHandle phContext,
1440 ULONG ulAttribute, void* pBuffer,
1441 ULONG cbBuffer)
1442{
1443 if (!phContext)
1444 return SEC_E_INVALID_HANDLE;
1445
1446 if (!pBuffer)
1447 return SEC_E_INVALID_PARAMETER;
1448
1449 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1450 if (!context)
1451 return SEC_E_INVALID_HANDLE;
1452
1453 switch (ulAttribute)
1454 {
1455 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME_LEN:
1456 return utf16len(&context->Workstation, pBuffer);
1457 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME_LEN:
1458 return utf16len(&context->NbDomainName, pBuffer);
1459 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME_LEN:
1460 return utf16len(&context->NbComputerName, pBuffer);
1461 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME_LEN:
1462 return utf16len(&context->DnsDomainName, pBuffer);
1463 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME_LEN:
1464 return utf16len(&context->DnsComputerName, pBuffer);
1465 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME:
1466 return ntml_setUnicodeStringW(&context->Workstation, pBuffer, cbBuffer);
1467 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME:
1468 return ntml_setUnicodeStringW(&context->NbDomainName, pBuffer, cbBuffer);
1469 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME:
1470 return ntml_setUnicodeStringW(&context->NbComputerName, pBuffer, cbBuffer);
1471 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME:
1472 return ntml_setUnicodeStringW(&context->DnsDomainName, pBuffer, cbBuffer);
1473 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME:
1474 return ntml_setUnicodeStringW(&context->DnsComputerName, pBuffer, cbBuffer);
1475
1476 default:
1477 return ntlm_SetContextAttributesCommon(phContext, ulAttribute, pBuffer, cbBuffer);
1478 }
1479}
1480
1481SECURITY_STATUS ntml_setUnicodeStringA(UNICODE_STRING* str, const char* val, size_t charlen)
1482{
1483 WINPR_ASSERT(str);
1484 ntlm_free_unicode_string(str);
1485 *str = ntlm_from_unicode_string_utf8(val, charlen);
1486 if (ntlm_is_unicode_string_empty(str))
1487 return SEC_E_INVALID_PARAMETER;
1488 return SEC_E_OK;
1489}
1490
1491WINPR_ATTR_NODISCARD
1492static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesA(PCtxtHandle phContext,
1493 ULONG ulAttribute, void* pBuffer,
1494 ULONG cbBuffer)
1495{
1496 if (!phContext)
1497 return SEC_E_INVALID_HANDLE;
1498
1499 if (!pBuffer)
1500 return SEC_E_INVALID_PARAMETER;
1501
1502 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1503 if (!context)
1504 return SEC_E_INVALID_HANDLE;
1505
1506 switch (ulAttribute)
1507 {
1508 case SECPKG_ATTR_AUTH_NTLM_HOSTNAME:
1509 return ntml_setUnicodeStringA(&context->Workstation, pBuffer, cbBuffer);
1510 case SECPKG_ATTR_AUTH_NTLM_NB_DOMAIN_NAME:
1511 return ntml_setUnicodeStringA(&context->NbDomainName, pBuffer, cbBuffer);
1512 case SECPKG_ATTR_AUTH_NTLM_NB_COMPUTER_NAME:
1513 return ntml_setUnicodeStringA(&context->NbComputerName, pBuffer, cbBuffer);
1514 case SECPKG_ATTR_AUTH_NTLM_DNS_DOMAIN_NAME:
1515 return ntml_setUnicodeStringA(&context->DnsDomainName, pBuffer, cbBuffer);
1516 case SECPKG_ATTR_AUTH_NTLM_DNS_COMPUTER_NAME:
1517 return ntml_setUnicodeStringA(&context->DnsComputerName, pBuffer, cbBuffer);
1518 default:
1519 return ntlm_SetContextAttributesCommon(phContext, ulAttribute, pBuffer, cbBuffer);
1520 }
1521}
1522
1523WINPR_ATTR_NODISCARD
1524static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesW(
1525 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1526 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1527{
1528 return SEC_E_UNSUPPORTED_FUNCTION;
1529}
1530
1531WINPR_ATTR_NODISCARD
1532static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesA(
1533 WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1534 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1535{
1536 return SEC_E_UNSUPPORTED_FUNCTION;
1537}
1538
1539WINPR_ATTR_NODISCARD
1540static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
1541{
1542 return SEC_E_OK;
1543}
1544
1545WINPR_ATTR_NODISCARD
1546static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1547 WINPR_ATTR_UNUSED ULONG fQOP,
1548 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1549{
1550 const UINT32 SeqNo = MessageSeqNo;
1551 UINT32 value = 0;
1552 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
1553 BYTE checksum[8] = WINPR_C_ARRAY_INIT;
1554 ULONG version = 1;
1555 PSecBuffer data_buffer = nullptr;
1556 PSecBuffer signature_buffer = nullptr;
1557 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1558 if (!check_context(context))
1559 return SEC_E_INVALID_HANDLE;
1560
1561 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1562 {
1563 SecBuffer* cur = &pMessage->pBuffers[index];
1564
1565 if (cur->BufferType & SECBUFFER_DATA)
1566 data_buffer = cur;
1567 else if (cur->BufferType & SECBUFFER_TOKEN)
1568 signature_buffer = cur;
1569 }
1570
1571 if (!data_buffer)
1572 return SEC_E_INVALID_TOKEN;
1573
1574 if (!signature_buffer)
1575 return SEC_E_INVALID_TOKEN;
1576
1577 if (signature_buffer->cbBuffer < 16)
1578 return SEC_E_INSUFFICIENT_MEMORY;
1579
1580 /* Copy original data buffer */
1581 ULONG length = data_buffer->cbBuffer;
1582 void* data = malloc(length);
1583
1584 if (!data)
1585 return SEC_E_INSUFFICIENT_MEMORY;
1586
1587 CopyMemory(data, data_buffer->pvBuffer, length);
1588 /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */
1589 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1590
1591 BOOL success = FALSE;
1592 {
1593 if (!hmac)
1594 goto hmac_fail;
1595 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1596 goto hmac_fail;
1597
1598 winpr_Data_Write_UINT32(&value, SeqNo);
1599
1600 if (!winpr_HMAC_Update(hmac, (void*)&value, 4))
1601 goto hmac_fail;
1602 if (!winpr_HMAC_Update(hmac, data, length))
1603 goto hmac_fail;
1604 if (!winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH))
1605 goto hmac_fail;
1606 }
1607
1608 success = TRUE;
1609
1610hmac_fail:
1611 winpr_HMAC_Free(hmac);
1612 if (!success)
1613 {
1614 free(data);
1615 return SEC_E_INSUFFICIENT_MEMORY;
1616 }
1617
1618 /* Encrypt message using with RC4, result overwrites original buffer */
1619 if ((data_buffer->BufferType & SECBUFFER_READONLY) == 0)
1620 {
1621 if (context->confidentiality)
1622 {
1623 if (!winpr_RC4_Update(context->SendRc4Seal, length, (BYTE*)data,
1624 (BYTE*)data_buffer->pvBuffer))
1625 {
1626 free(data);
1627 return SEC_E_INSUFFICIENT_MEMORY;
1628 }
1629 }
1630 else
1631 CopyMemory(data_buffer->pvBuffer, data, length);
1632 }
1633
1634#ifdef WITH_DEBUG_NTLM
1635 WLog_DBG(TAG, "Data Buffer (length = %" PRIu32 ")", length);
1636 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1637 WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer);
1638 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1639#endif
1640 free(data);
1641 /* RC4-encrypt first 8 bytes of digest */
1642 if (!winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum))
1643 return SEC_E_INSUFFICIENT_MEMORY;
1644 if ((signature_buffer->BufferType & SECBUFFER_READONLY) == 0)
1645 {
1646 BYTE* signature = signature_buffer->pvBuffer;
1647 /* Concatenate version, ciphertext and sequence number to build signature */
1648 winpr_Data_Write_UINT32(signature, version);
1649 CopyMemory(&signature[4], (void*)checksum, 8);
1650 winpr_Data_Write_UINT32(&signature[12], SeqNo);
1651 }
1652 context->SendSeqNum++;
1653#ifdef WITH_DEBUG_NTLM
1654 WLog_DBG(TAG, "Signature (length = %" PRIu32 ")", signature_buffer->cbBuffer);
1655 winpr_HexDump(TAG, WLOG_DEBUG, signature_buffer->pvBuffer, signature_buffer->cbBuffer);
1656#endif
1657 return SEC_E_OK;
1658}
1659
1660static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage,
1661 ULONG MessageSeqNo,
1662 WINPR_ATTR_UNUSED PULONG pfQOP)
1663{
1664 const UINT32 SeqNo = (UINT32)MessageSeqNo;
1665 UINT32 value = 0;
1666 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
1667 BYTE checksum[8] = WINPR_C_ARRAY_INIT;
1668 UINT32 version = 1;
1669 BYTE expected_signature[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
1670 PSecBuffer data_buffer = nullptr;
1671 PSecBuffer signature_buffer = nullptr;
1672 NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1673 if (!check_context(context))
1674 return SEC_E_INVALID_HANDLE;
1675
1676 for (ULONG index = 0; index < pMessage->cBuffers; index++)
1677 {
1678 if (pMessage->pBuffers[index].BufferType == SECBUFFER_DATA)
1679 data_buffer = &pMessage->pBuffers[index];
1680 else if (pMessage->pBuffers[index].BufferType == SECBUFFER_TOKEN)
1681 signature_buffer = &pMessage->pBuffers[index];
1682 }
1683
1684 if (!data_buffer)
1685 return SEC_E_INVALID_TOKEN;
1686
1687 if (!signature_buffer)
1688 return SEC_E_INVALID_TOKEN;
1689
1690 if (signature_buffer->cbBuffer < 16)
1691 return SEC_E_INVALID_TOKEN;
1692
1693 /* Copy original data buffer */
1694 const ULONG length = data_buffer->cbBuffer;
1695 void* data = malloc(length);
1696
1697 if (!data)
1698 return SEC_E_INSUFFICIENT_MEMORY;
1699
1700 CopyMemory(data, data_buffer->pvBuffer, length);
1701
1702 /* Decrypt message using with RC4, result overwrites original buffer */
1703
1704 if (context->confidentiality)
1705 {
1706 if (!winpr_RC4_Update(context->RecvRc4Seal, length, (BYTE*)data,
1707 (BYTE*)data_buffer->pvBuffer))
1708 {
1709 free(data);
1710 return SEC_E_INSUFFICIENT_MEMORY;
1711 }
1712 }
1713 else
1714 CopyMemory(data_buffer->pvBuffer, data, length);
1715
1716 /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */
1717 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1718
1719 BOOL success = FALSE;
1720 {
1721 if (!hmac)
1722 goto hmac_fail;
1723
1724 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1725 goto hmac_fail;
1726
1727 winpr_Data_Write_UINT32(&value, SeqNo);
1728
1729 if (!winpr_HMAC_Update(hmac, (void*)&value, 4))
1730 goto hmac_fail;
1731 if (!winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer))
1732 goto hmac_fail;
1733 if (!winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH))
1734 goto hmac_fail;
1735
1736 success = TRUE;
1737 }
1738hmac_fail:
1739 winpr_HMAC_Free(hmac);
1740 if (!success)
1741 {
1742 free(data);
1743 return SEC_E_INSUFFICIENT_MEMORY;
1744 }
1745
1746#ifdef WITH_DEBUG_NTLM
1747 WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIu32 ")", length);
1748 winpr_HexDump(TAG, WLOG_DEBUG, data, length);
1749 WLog_DBG(TAG, "Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer);
1750 winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer);
1751#endif
1752 free(data);
1753 /* RC4-encrypt first 8 bytes of digest */
1754 if (!winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum))
1755 return SEC_E_MESSAGE_ALTERED;
1756
1757 /* Concatenate version, ciphertext and sequence number to build signature */
1758 winpr_Data_Write_UINT32(expected_signature, version);
1759 CopyMemory(&expected_signature[4], (void*)checksum, 8);
1760 winpr_Data_Write_UINT32(&expected_signature[12], SeqNo);
1761 context->RecvSeqNum++;
1762
1763 if (memcmp(signature_buffer->pvBuffer, expected_signature, 16) != 0)
1764 {
1765 /* signature verification failed! */
1766 WLog_ERR(TAG, "signature verification failed, something nasty is going on!");
1767#ifdef WITH_DEBUG_NTLM
1768 WLog_ERR(TAG, "Expected Signature:");
1769 winpr_HexDump(TAG, WLOG_ERROR, expected_signature, 16);
1770 WLog_ERR(TAG, "Actual Signature:");
1771 winpr_HexDump(TAG, WLOG_ERROR, (BYTE*)signature_buffer->pvBuffer, 16);
1772#endif
1773 return SEC_E_MESSAGE_ALTERED;
1774 }
1775
1776 return SEC_E_OK;
1777}
1778
1779static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext,
1780 WINPR_ATTR_UNUSED ULONG fQOP,
1781 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1782{
1783 SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
1784 PSecBuffer data_buffer = nullptr;
1785 PSecBuffer sig_buffer = nullptr;
1786 UINT32 seq_no = 0;
1787 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
1788 BYTE checksum[8] = WINPR_C_ARRAY_INIT;
1789
1790 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1791 if (!check_context(context))
1792 return SEC_E_INVALID_HANDLE;
1793
1794 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1795 {
1796 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1797 data_buffer = &pMessage->pBuffers[i];
1798 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1799 sig_buffer = &pMessage->pBuffers[i];
1800 }
1801
1802 if (!data_buffer || !sig_buffer)
1803 return SEC_E_INVALID_TOKEN;
1804
1805 if (sig_buffer->cbBuffer < 16)
1806 return SEC_E_INSUFFICIENT_MEMORY;
1807
1808 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1809
1810 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH))
1811 goto fail;
1812
1813 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1814 if (!winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4))
1815 goto fail;
1816 if (!winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer))
1817 goto fail;
1818 if (!winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH))
1819 goto fail;
1820
1821 if (!winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum))
1822 goto fail;
1823
1824 BYTE* signature = sig_buffer->pvBuffer;
1825 winpr_Data_Write_UINT32(signature, 1L);
1826 CopyMemory(&signature[4], checksum, 8);
1827 winpr_Data_Write_UINT32(&signature[12], seq_no);
1828 sig_buffer->cbBuffer = 16;
1829
1830 status = SEC_E_OK;
1831
1832fail:
1833 winpr_HMAC_Free(hmac);
1834 return status;
1835}
1836
1837WINPR_ATTR_NODISCARD
1838static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1839 PSecBufferDesc pMessage, ULONG MessageSeqNo,
1840 WINPR_ATTR_UNUSED PULONG pfQOP)
1841{
1842 SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
1843 PSecBuffer data_buffer = nullptr;
1844 PSecBuffer sig_buffer = nullptr;
1845 UINT32 seq_no = 0;
1846 BYTE digest[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
1847 BYTE checksum[8] = WINPR_C_ARRAY_INIT;
1848 BYTE signature[16] = WINPR_C_ARRAY_INIT;
1849
1850 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1851 if (!check_context(context))
1852 return SEC_E_INVALID_HANDLE;
1853
1854 for (ULONG i = 0; i < pMessage->cBuffers; i++)
1855 {
1856 if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
1857 data_buffer = &pMessage->pBuffers[i];
1858 else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1859 sig_buffer = &pMessage->pBuffers[i];
1860 }
1861
1862 if (!data_buffer || !sig_buffer || (sig_buffer->cbBuffer < 16))
1863 return SEC_E_INVALID_TOKEN;
1864
1865 WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
1866
1867 if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH))
1868 goto fail;
1869
1870 winpr_Data_Write_UINT32(&seq_no, MessageSeqNo);
1871 if (!winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4))
1872 goto fail;
1873 if (!winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer))
1874 goto fail;
1875 if (!winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH))
1876 goto fail;
1877
1878 if (!winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum))
1879 goto fail;
1880
1881 winpr_Data_Write_UINT32(signature, 1L);
1882 CopyMemory(&signature[4], checksum, 8);
1883 winpr_Data_Write_UINT32(&signature[12], seq_no);
1884
1885 status = SEC_E_OK;
1886 if (memcmp(sig_buffer->pvBuffer, signature, 16) != 0)
1887 status = SEC_E_MESSAGE_ALTERED;
1888
1889fail:
1890 winpr_HMAC_Free(hmac);
1891 return status;
1892}
1893
1894const SecurityFunctionTableA NTLM_SecurityFunctionTableA = {
1895 3, /* dwVersion */
1896 nullptr, /* EnumerateSecurityPackages */
1897 ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
1898 ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */
1899 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1900 nullptr, /* Reserved2 */
1901 ntlm_InitializeSecurityContextA, /* InitializeSecurityContext */
1902 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1903 nullptr, /* CompleteAuthToken */
1904 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1905 nullptr, /* ApplyControlToken */
1906 ntlm_QueryContextAttributesA, /* QueryContextAttributes */
1907 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1908 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1909 ntlm_MakeSignature, /* MakeSignature */
1910 ntlm_VerifySignature, /* VerifySignature */
1911 nullptr, /* FreeContextBuffer */
1912 nullptr, /* QuerySecurityPackageInfo */
1913 nullptr, /* Reserved3 */
1914 nullptr, /* Reserved4 */
1915 nullptr, /* ExportSecurityContext */
1916 nullptr, /* ImportSecurityContext */
1917 nullptr, /* AddCredentials */
1918 nullptr, /* Reserved8 */
1919 nullptr, /* QuerySecurityContextToken */
1920 ntlm_EncryptMessage, /* EncryptMessage */
1921 ntlm_DecryptMessage, /* DecryptMessage */
1922 ntlm_SetContextAttributesA, /* SetContextAttributes */
1923 ntlm_SetCredentialsAttributesA, /* SetCredentialsAttributes */
1924};
1925
1926const SecurityFunctionTableW NTLM_SecurityFunctionTableW = {
1927 3, /* dwVersion */
1928 nullptr, /* EnumerateSecurityPackages */
1929 ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
1930 ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */
1931 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1932 nullptr, /* Reserved2 */
1933 ntlm_InitializeSecurityContextW, /* InitializeSecurityContext */
1934 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1935 nullptr, /* CompleteAuthToken */
1936 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1937 nullptr, /* ApplyControlToken */
1938 ntlm_QueryContextAttributesW, /* QueryContextAttributes */
1939 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1940 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1941 ntlm_MakeSignature, /* MakeSignature */
1942 ntlm_VerifySignature, /* VerifySignature */
1943 nullptr, /* FreeContextBuffer */
1944 nullptr, /* QuerySecurityPackageInfo */
1945 nullptr, /* Reserved3 */
1946 nullptr, /* Reserved4 */
1947 nullptr, /* ExportSecurityContext */
1948 nullptr, /* ImportSecurityContext */
1949 nullptr, /* AddCredentials */
1950 nullptr, /* Reserved8 */
1951 nullptr, /* QuerySecurityContextToken */
1952 ntlm_EncryptMessage, /* EncryptMessage */
1953 ntlm_DecryptMessage, /* DecryptMessage */
1954 ntlm_SetContextAttributesW, /* SetContextAttributes */
1955 ntlm_SetCredentialsAttributesW, /* SetCredentialsAttributes */
1956};
1957
1958const SecPkgInfoA NTLM_SecPkgInfoA = {
1959 0x00082B37, /* fCapabilities */
1960 1, /* wVersion */
1961 0x000A, /* wRPCID */
1962 0x00000B48, /* cbMaxToken */
1963 "NTLM", /* Name */
1964 "NTLM Security Package" /* Comment */
1965};
1966
1967static WCHAR NTLM_SecPkgInfoW_NameBuffer[32] = WINPR_C_ARRAY_INIT;
1968static WCHAR NTLM_SecPkgInfoW_CommentBuffer[32] = WINPR_C_ARRAY_INIT;
1969
1970const SecPkgInfoW NTLM_SecPkgInfoW = {
1971 0x00082B37, /* fCapabilities */
1972 1, /* wVersion */
1973 0x000A, /* wRPCID */
1974 0x00000B48, /* cbMaxToken */
1975 NTLM_SecPkgInfoW_NameBuffer, /* Name */
1976 NTLM_SecPkgInfoW_CommentBuffer /* Comment */
1977};
1978
1979char* ntlm_negotiate_flags_string(char* buffer, size_t size, UINT32 flags)
1980{
1981 if (!buffer || (size == 0))
1982 return buffer;
1983
1984 (void)_snprintf(buffer, size, "[0x%08" PRIx32 "] ", flags);
1985
1986 for (int x = 0; x < 31; x++)
1987 {
1988 const UINT32 mask = 1u << x;
1989 size_t len = strnlen(buffer, size);
1990 if (flags & mask)
1991 {
1992 const char* str = ntlm_get_negotiate_string(mask);
1993 const size_t flen = strlen(str);
1994
1995 if ((len > 0) && (buffer[len - 1] != ' '))
1996 {
1997 if (size - len < 1)
1998 break;
1999 winpr_str_append("|", buffer, size, nullptr);
2000 len++;
2001 }
2002
2003 if (size - len < flen)
2004 break;
2005 winpr_str_append(str, buffer, size, nullptr);
2006 }
2007 }
2008
2009 return buffer;
2010}
2011
2012const char* ntlm_message_type_string(UINT32 messageType)
2013{
2014 switch (messageType)
2015 {
2016 case MESSAGE_TYPE_NEGOTIATE:
2017 return "MESSAGE_TYPE_NEGOTIATE";
2018 case MESSAGE_TYPE_CHALLENGE:
2019 return "MESSAGE_TYPE_CHALLENGE";
2020 case MESSAGE_TYPE_AUTHENTICATE:
2021 return "MESSAGE_TYPE_AUTHENTICATE";
2022 default:
2023 return "MESSAGE_TYPE_UNKNOWN";
2024 }
2025}
2026
2027const char* ntlm_state_string(NTLM_STATE state)
2028{
2029 switch (state)
2030 {
2031 case NTLM_STATE_INITIAL:
2032 return "NTLM_STATE_INITIAL";
2033 case NTLM_STATE_NEGOTIATE:
2034 return "NTLM_STATE_NEGOTIATE";
2035 case NTLM_STATE_CHALLENGE:
2036 return "NTLM_STATE_CHALLENGE";
2037 case NTLM_STATE_AUTHENTICATE:
2038 return "NTLM_STATE_AUTHENTICATE";
2039 case NTLM_STATE_FINAL:
2040 return "NTLM_STATE_FINAL";
2041 default:
2042 return "NTLM_STATE_UNKNOWN";
2043 }
2044}
2045void ntlm_change_state(NTLM_CONTEXT* ntlm, NTLM_STATE state)
2046{
2047 WINPR_ASSERT(ntlm);
2048 WLog_DBG(TAG, "change state from %s to %s", ntlm_state_string(ntlm->state),
2049 ntlm_state_string(state));
2050 ntlm->state = state;
2051}
2052
2053NTLM_STATE ntlm_get_state(NTLM_CONTEXT* ntlm)
2054{
2055 WINPR_ASSERT(ntlm);
2056 return ntlm->state;
2057}
2058
2059BOOL ntlm_reset_cipher_state(PSecHandle phContext)
2060{
2061 NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
2062
2063 if (context)
2064 {
2065 if (!check_context(context))
2066 return FALSE;
2067
2068 winpr_RC4_Free(context->SendRc4Seal);
2069 winpr_RC4_Free(context->RecvRc4Seal);
2070 context->SendRc4Seal = winpr_RC4_New(context->RecvSealingKey, 16);
2071 context->RecvRc4Seal = winpr_RC4_New(context->SendSealingKey, 16);
2072
2073 if (!context->SendRc4Seal)
2074 {
2075 WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal");
2076 return FALSE;
2077 }
2078 if (!context->RecvRc4Seal)
2079 {
2080 WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal");
2081 return FALSE;
2082 }
2083 }
2084
2085 return TRUE;
2086}
2087
2088BOOL NTLM_init(void)
2089{
2090 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Name, NTLM_SecPkgInfoW_NameBuffer,
2091 ARRAYSIZE(NTLM_SecPkgInfoW_NameBuffer));
2092 InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Comment, NTLM_SecPkgInfoW_CommentBuffer,
2093 ARRAYSIZE(NTLM_SecPkgInfoW_CommentBuffer));
2094
2095 return TRUE;
2096}
2097
2098BOOL ntlm_SecBufferRealloc(SecBuffer* buffer, ULONG len)
2099{
2100 sspi_SecBufferFree(buffer);
2101 return sspi_SecBufferAlloc(buffer, len) != nullptr;
2102}