Coverage Report

Created: 2026-03-04 06:13

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