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