Coverage Report

Created: 2026-10-15 06:31

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