Coverage Report

Created: 2026-08-31 06:25

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