Coverage Report

Created: 2026-05-30 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/sspi/NTLM/ntlm_compute.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * NTLM Security Package (Compute)
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/assert.h>
23
24
#include "ntlm.h"
25
#include "../sspi.h"
26
27
#include <winpr/crt.h>
28
#include <winpr/sam.h>
29
#include <winpr/ntlm.h>
30
#include <winpr/print.h>
31
#include <winpr/crypto.h>
32
#include <winpr/sysinfo.h>
33
34
#include "ntlm_compute.h"
35
36
#include "../../log.h"
37
1.92k
#define TAG WINPR_TAG("sspi.NTLM")
38
39
#define NTLM_CheckAndLogRequiredCapacity(tag, s, nmemb, what)                                    \
40
0
  Stream_CheckAndLogRequiredCapacityEx(tag, WLOG_WARN, s, nmemb, 1, "%s(%s:%" PRIuz ") " what, \
41
0
                                       __func__, __FILE__, (size_t)__LINE__)
42
43
static char NTLM_CLIENT_SIGN_MAGIC[] = "session key to client-to-server signing key magic constant";
44
static char NTLM_SERVER_SIGN_MAGIC[] = "session key to server-to-client signing key magic constant";
45
static char NTLM_CLIENT_SEAL_MAGIC[] = "session key to client-to-server sealing key magic constant";
46
static char NTLM_SERVER_SEAL_MAGIC[] = "session key to server-to-client sealing key magic constant";
47
48
static const BYTE NTLM_NULL_BUFFER[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
49
                                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
50
51
/**
52
 * Populate VERSION structure msdn{cc236654}
53
 * @param versionInfo A pointer to the version struct
54
 *
55
 * @return \b TRUE for success, \b FALSE for failure
56
 */
57
58
BOOL ntlm_get_version_info(NTLM_VERSION_INFO* versionInfo)
59
1.95k
{
60
1.95k
  WINPR_ASSERT(versionInfo);
61
62
#if defined(WITH_WINPR_DEPRECATED)
63
  OSVERSIONINFOA osVersionInfo = WINPR_C_ARRAY_INIT;
64
  osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
65
  if (!GetVersionExA(&osVersionInfo))
66
    return FALSE;
67
  versionInfo->ProductMajorVersion = (UINT8)osVersionInfo.dwMajorVersion;
68
  versionInfo->ProductMinorVersion = (UINT8)osVersionInfo.dwMinorVersion;
69
  versionInfo->ProductBuild = (UINT16)osVersionInfo.dwBuildNumber;
70
#else
71
  /* Always return fixed version number.
72
   *
73
   * ProductVersion is fixed since windows 10 to Major 10, Minor 0
74
   * ProductBuild taken from https://en.wikipedia.org/wiki/Windows_11_version_history
75
   * with most recent (pre) release build number
76
   */
77
1.95k
  versionInfo->ProductMajorVersion = 10;
78
1.95k
  versionInfo->ProductMinorVersion = 0;
79
1.95k
  versionInfo->ProductBuild = 22631;
80
1.95k
#endif
81
1.95k
  ZeroMemory(versionInfo->Reserved, sizeof(versionInfo->Reserved));
82
1.95k
  versionInfo->NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
83
1.95k
  return TRUE;
84
1.95k
}
85
86
/**
87
 * Read VERSION structure. msdn{cc236654}
88
 * @param s A pointer to a stream to read
89
 * @param versionInfo A pointer to the struct to read data to
90
 *
91
 * @return \b TRUE for success, \b FALSE for failure
92
 */
93
94
BOOL ntlm_read_version_info(wStream* s, NTLM_VERSION_INFO* versionInfo)
95
789
{
96
789
  WINPR_ASSERT(s);
97
789
  WINPR_ASSERT(versionInfo);
98
99
789
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 8))
100
8
    return FALSE;
101
102
781
  Stream_Read_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */
103
781
  Stream_Read_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */
104
781
  Stream_Read_UINT16(s, versionInfo->ProductBuild);       /* ProductBuild (2 bytes) */
105
781
  Stream_Read(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */
106
781
  Stream_Read_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */
107
781
  return TRUE;
108
789
}
109
110
/**
111
 * Write VERSION structure. msdn{cc236654}
112
 * @param s A pointer to the stream to write to
113
 * @param versionInfo A pointer to the buffer to read the data from
114
 *
115
 * @return \b TRUE for success, \b FALSE for failure
116
 */
117
118
BOOL ntlm_write_version_info(wStream* s, const NTLM_VERSION_INFO* versionInfo)
119
1.92k
{
120
1.92k
  WINPR_ASSERT(s);
121
1.92k
  WINPR_ASSERT(versionInfo);
122
123
1.92k
  if (!Stream_CheckAndLogRequiredCapacityEx(
124
1.92k
          TAG, WLOG_WARN, s, 5ull + sizeof(versionInfo->Reserved), 1ull,
125
1.92k
          "%s(%s:%" PRIuz ") NTLM_VERSION_INFO", __func__, __FILE__, (size_t)__LINE__))
126
0
    return FALSE;
127
128
1.92k
  Stream_Write_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */
129
1.92k
  Stream_Write_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */
130
1.92k
  Stream_Write_UINT16(s, versionInfo->ProductBuild);       /* ProductBuild (2 bytes) */
131
1.92k
  Stream_Write(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */
132
1.92k
  Stream_Write_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */
133
1.92k
  return TRUE;
134
1.92k
}
135
136
/**
137
 * Print VERSION structure. msdn{cc236654}
138
 * @param versionInfo A pointer to the struct containing the data to print
139
 */
140
#ifdef WITH_DEBUG_NTLM
141
void ntlm_print_version_info(const NTLM_VERSION_INFO* versionInfo)
142
{
143
  WINPR_ASSERT(versionInfo);
144
145
  WLog_VRB(TAG, "VERSION ={");
146
  WLog_VRB(TAG, "\tProductMajorVersion: %" PRIu8 "", versionInfo->ProductMajorVersion);
147
  WLog_VRB(TAG, "\tProductMinorVersion: %" PRIu8 "", versionInfo->ProductMinorVersion);
148
  WLog_VRB(TAG, "\tProductBuild: %" PRIu16 "", versionInfo->ProductBuild);
149
  WLog_VRB(TAG, "\tReserved: 0x%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "", versionInfo->Reserved[0],
150
           versionInfo->Reserved[1], versionInfo->Reserved[2]);
151
  WLog_VRB(TAG, "\tNTLMRevisionCurrent: 0x%02" PRIX8 "", versionInfo->NTLMRevisionCurrent);
152
}
153
#endif
154
155
static BOOL ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge)
156
248
{
157
248
  size_t size = 0;
158
248
  WINPR_ASSERT(s);
159
248
  WINPR_ASSERT(challenge);
160
161
248
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 28))
162
3
    return FALSE;
163
164
245
  Stream_Read_UINT8(s, challenge->RespType);
165
245
  Stream_Read_UINT8(s, challenge->HiRespType);
166
245
  Stream_Read_UINT16(s, challenge->Reserved1);
167
245
  Stream_Read_UINT32(s, challenge->Reserved2);
168
245
  Stream_Read(s, challenge->Timestamp, 8);
169
245
  Stream_Read(s, challenge->ClientChallenge, 8);
170
245
  Stream_Read_UINT32(s, challenge->Reserved3);
171
245
  size = Stream_Length(s) - Stream_GetPosition(s);
172
173
245
  if (size > UINT32_MAX)
174
0
  {
175
0
    WLog_ERR(TAG, "NTLMv2_CLIENT_CHALLENGE::cbAvPairs too large, got %" PRIuz "bytes", size);
176
0
    return FALSE;
177
0
  }
178
179
245
  challenge->cbAvPairs = (UINT32)size;
180
245
  challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs);
181
182
245
  if (!challenge->AvPairs)
183
0
  {
184
0
    WLog_ERR(TAG, "NTLMv2_CLIENT_CHALLENGE::AvPairs failed to allocate %" PRIu32 "bytes",
185
0
             challenge->cbAvPairs);
186
0
    return FALSE;
187
0
  }
188
189
245
  Stream_Read(s, challenge->AvPairs, size);
190
245
  return TRUE;
191
245
}
192
193
static BOOL ntlm_write_ntlm_v2_client_challenge(wStream* s,
194
                                                const NTLMv2_CLIENT_CHALLENGE* challenge)
195
0
{
196
0
  ULONG length = 0;
197
198
0
  WINPR_ASSERT(s);
199
0
  WINPR_ASSERT(challenge);
200
201
0
  if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, 28, "NTLMv2_CLIENT_CHALLENGE"))
202
0
    return FALSE;
203
204
0
  Stream_Write_UINT8(s, challenge->RespType);
205
0
  Stream_Write_UINT8(s, challenge->HiRespType);
206
0
  Stream_Write_UINT16(s, challenge->Reserved1);
207
0
  Stream_Write_UINT32(s, challenge->Reserved2);
208
0
  Stream_Write(s, challenge->Timestamp, 8);
209
0
  Stream_Write(s, challenge->ClientChallenge, 8);
210
0
  Stream_Write_UINT32(s, challenge->Reserved3);
211
0
  length = ntlm_av_pair_list_length(challenge->AvPairs, challenge->cbAvPairs);
212
213
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, length))
214
0
    return FALSE;
215
216
0
  Stream_Write(s, challenge->AvPairs, length);
217
0
  return TRUE;
218
0
}
219
220
BOOL ntlm_read_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response)
221
249
{
222
249
  WINPR_ASSERT(s);
223
249
  WINPR_ASSERT(response);
224
225
249
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 16))
226
1
    return FALSE;
227
228
248
  Stream_Read(s, response->Response, 16);
229
248
  return ntlm_read_ntlm_v2_client_challenge(s, &(response->Challenge));
230
249
}
231
232
BOOL ntlm_write_ntlm_v2_response(wStream* s, const NTLMv2_RESPONSE* response)
233
0
{
234
0
  WINPR_ASSERT(s);
235
0
  WINPR_ASSERT(response);
236
237
0
  if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, 16ull, "NTLMv2_RESPONSE"))
238
0
    return FALSE;
239
240
0
  Stream_Write(s, response->Response, 16);
241
0
  return ntlm_write_ntlm_v2_client_challenge(s, &(response->Challenge));
242
0
}
243
244
/**
245
 * Get current time, in tenths of microseconds since midnight of January 1, 1601.
246
 * @param[out] timestamp 64-bit little-endian timestamp
247
 */
248
249
static void ntlm_current_time(BYTE* timestamp, WINPR_ATTR_UNUSED size_t size)
250
707
{
251
707
  FILETIME ft = WINPR_C_ARRAY_INIT;
252
253
707
  WINPR_ASSERT(timestamp);
254
707
  WINPR_ASSERT(size >= sizeof(ft));
255
256
707
  GetSystemTimeAsFileTime(&ft);
257
707
  CopyMemory(timestamp, &(ft), sizeof(ft));
258
707
}
259
260
/**
261
 * Generate timestamp for AUTHENTICATE_MESSAGE.
262
 *
263
 * @param context A pointer to the NTLM context
264
 */
265
266
void ntlm_generate_timestamp(NTLM_CONTEXT* context)
267
774
{
268
774
  WINPR_ASSERT(context);
269
270
774
  if (memcmp(context->ChallengeTimestamp, NTLM_NULL_BUFFER, 8) != 0)
271
67
    CopyMemory(context->Timestamp, context->ChallengeTimestamp, 8);
272
707
  else
273
707
    ntlm_current_time(context->Timestamp, sizeof(context->Timestamp));
274
774
}
275
276
static BOOL ntlm_fetch_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash)
277
0
{
278
0
  BOOL rc = FALSE;
279
0
  WINPR_SAM_ENTRY* entry = nullptr;
280
281
0
  WINPR_ASSERT(context);
282
0
  WINPR_ASSERT(hash);
283
284
0
  SSPI_CREDENTIALS* credentials = context->credentials;
285
0
  WINPR_SAM* sam = SamOpen(context->SamFile, TRUE);
286
287
0
  if (!sam)
288
0
    goto fail;
289
290
0
  entry = SamLookupUserW(
291
0
      sam, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * sizeof(WCHAR),
292
0
      (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * sizeof(WCHAR));
293
294
0
  if (!entry)
295
0
  {
296
0
    entry = SamLookupUserW(sam, (LPWSTR)credentials->identity.User,
297
0
                           credentials->identity.UserLength * sizeof(WCHAR), nullptr, 0);
298
0
  }
299
300
0
  if (!entry)
301
0
    goto fail;
302
303
#ifdef WITH_DEBUG_NTLM
304
  WLog_VRB(TAG, "NTLM Hash:");
305
  winpr_HexDump(TAG, WLOG_DEBUG, entry->NtHash, 16);
306
#endif
307
0
  rc = NTOWFv2FromHashW(entry->NtHash, (LPWSTR)credentials->identity.User,
308
0
                        credentials->identity.UserLength * sizeof(WCHAR),
309
0
                        (LPWSTR)credentials->identity.Domain,
310
0
                        credentials->identity.DomainLength * sizeof(WCHAR), hash);
311
312
0
fail:
313
0
  SamFreeEntry(sam, entry);
314
0
  SamClose(sam);
315
0
  if (!rc)
316
0
    WLog_ERR(TAG, "Error: Could not find user in SAM database");
317
318
0
  return rc;
319
0
}
320
321
static int hexchar2nibble(WCHAR wc)
322
0
{
323
#if defined(__BIG_ENDIAN__)
324
  union
325
  {
326
    BYTE b[2];
327
    WCHAR w;
328
  } cnv;
329
  cnv.w = wc;
330
  const BYTE b = cnv.b[0];
331
  cnv.b[0] = cnv.b[1];
332
  cnv.b[1] = b;
333
  wc = cnv.w;
334
#endif
335
336
0
  switch (wc)
337
0
  {
338
0
    case L'0':
339
0
    case L'1':
340
0
    case L'2':
341
0
    case L'3':
342
0
    case L'4':
343
0
    case L'5':
344
0
    case L'6':
345
0
    case L'7':
346
0
    case L'8':
347
0
    case L'9':
348
0
      return wc - L'0';
349
0
    case L'a':
350
0
    case L'b':
351
0
    case L'c':
352
0
    case L'd':
353
0
    case L'e':
354
0
    case L'f':
355
0
      return wc - L'a' + 10;
356
0
    case L'A':
357
0
    case L'B':
358
0
    case L'C':
359
0
    case L'D':
360
0
    case L'E':
361
0
    case L'F':
362
0
      return wc - L'A' + 10;
363
0
    default:
364
0
      return -1;
365
0
  }
366
0
}
367
static int ntlm_convert_password_hash(NTLM_CONTEXT* context, BYTE* hash, size_t hashlen)
368
0
{
369
0
  const size_t required_len = 2ull * hashlen;
370
371
0
  WINPR_ASSERT(context);
372
0
  WINPR_ASSERT(hash);
373
374
0
  SSPI_CREDENTIALS* credentials = context->credentials;
375
0
  const ULONG PasswordHashLength = credentials->identity.PasswordLength;
376
377
0
  if (PasswordHashLength != required_len)
378
0
  {
379
0
    WLog_ERR(TAG,
380
0
             "PasswordHash has invalid length %" PRIu32 " must be exactly %" PRIuz " bytes",
381
0
             PasswordHashLength, required_len);
382
0
    return -1;
383
0
  }
384
385
0
  const WCHAR* PasswordHash = credentials->identity.Password;
386
0
  for (size_t x = 0; x < hashlen; x++)
387
0
  {
388
0
    const int hi = hexchar2nibble(PasswordHash[2 * x]);
389
0
    if (hi < 0)
390
0
    {
391
0
      WLog_ERR(TAG, "PasswordHash has an invalid value at position %" PRIuz, 2 * x);
392
0
      return -1;
393
0
    }
394
0
    const int lo = hexchar2nibble(PasswordHash[2 * x + 1]);
395
0
    if (lo < 0)
396
0
    {
397
0
      WLog_ERR(TAG, "PasswordHash has an invalid value at position %" PRIuz, 2 * x + 1);
398
0
      return -1;
399
0
    }
400
0
    const BYTE val = (BYTE)((hi << 4) | lo);
401
0
    hash[x] = val;
402
0
  }
403
404
0
  return 1;
405
0
}
406
407
static BOOL ntlm_compute_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash)
408
940
{
409
940
  WINPR_ASSERT(context);
410
940
  WINPR_ASSERT(hash);
411
412
940
  SSPI_CREDENTIALS* credentials = context->credentials;
413
#ifdef WITH_DEBUG_NTLM
414
415
  if (credentials)
416
  {
417
    WLog_VRB(TAG, "Password (length = %" PRIu32 ")", credentials->identity.PasswordLength * 2);
418
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Password,
419
                  credentials->identity.PasswordLength * 2);
420
    WLog_VRB(TAG, "Username (length = %" PRIu32 ")", credentials->identity.UserLength * 2);
421
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.User,
422
                  credentials->identity.UserLength * 2);
423
    WLog_VRB(TAG, "Domain (length = %" PRIu32 ")", credentials->identity.DomainLength * 2);
424
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Domain,
425
                  credentials->identity.DomainLength * 2);
426
  }
427
  else
428
    WLog_VRB(TAG, "Strange, NTLM_CONTEXT is missing valid credentials...");
429
430
  WLog_VRB(TAG, "Workstation (length = %" PRIu16 ")", context->Workstation.Length);
431
  winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)context->Workstation.Buffer, context->Workstation.Length);
432
  WLog_VRB(TAG, "NTOWFv2, NTLMv2 Hash");
433
  winpr_HexDump(TAG, WLOG_TRACE, context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH);
434
#endif
435
436
940
  if (memcmp(context->NtlmV2Hash, NTLM_NULL_BUFFER, 16) != 0)
437
743
    return TRUE;
438
439
197
  if (!credentials)
440
0
    return FALSE;
441
197
  else if (memcmp(context->NtlmHash, NTLM_NULL_BUFFER, 16) != 0)
442
0
  {
443
0
    return NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User,
444
0
                            credentials->identity.UserLength * 2,
445
0
                            (LPWSTR)credentials->identity.Domain,
446
0
                            credentials->identity.DomainLength * 2, hash);
447
0
  }
448
197
  else if (credentials->identity.Flags & SEC_WINPR_AUTH_IDENTITY_PASSWORD_HASH)
449
0
  {
450
    /* Special case for WinPR: password hash */
451
0
    if (ntlm_convert_password_hash(context, context->NtlmHash, sizeof(context->NtlmHash)) < 0)
452
0
      return FALSE;
453
454
0
    return NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User,
455
0
                            credentials->identity.UserLength * 2,
456
0
                            (LPWSTR)credentials->identity.Domain,
457
0
                            credentials->identity.DomainLength * 2, hash);
458
0
  }
459
197
  else if (credentials->identity.Password)
460
197
  {
461
197
    return NTOWFv2W(
462
197
        (LPWSTR)credentials->identity.Password, credentials->identity.PasswordLength * 2,
463
197
        (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2,
464
197
        (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, hash);
465
197
  }
466
0
  else if (context->HashCallback)
467
0
  {
468
0
    SecBuffer proofValue = WINPR_C_ARRAY_INIT;
469
0
    SecBuffer micValue = WINPR_C_ARRAY_INIT;
470
471
0
    if (ntlm_computeProofValue(context, &proofValue) != SEC_E_OK)
472
0
      return FALSE;
473
474
0
    if (ntlm_computeMicValue(context, &micValue) != SEC_E_OK)
475
0
    {
476
0
      sspi_SecBufferFree(&proofValue);
477
0
      return FALSE;
478
0
    }
479
480
0
    const SECURITY_STATUS ret = context->HashCallback(
481
0
        context->HashCallbackArg, &credentials->identity, &proofValue,
482
0
        context->EncryptedRandomSessionKey, context->AUTHENTICATE_MESSAGE.MessageIntegrityCheck,
483
0
        &micValue, hash);
484
0
    sspi_SecBufferFree(&proofValue);
485
0
    sspi_SecBufferFree(&micValue);
486
0
    return ret == SEC_E_OK;
487
0
  }
488
0
  else if (context->UseSamFileDatabase)
489
0
  {
490
0
    return ntlm_fetch_ntlm_v2_hash(context, hash);
491
0
  }
492
493
0
  return TRUE;
494
197
}
495
496
SECURITY_STATUS ntlm_compute_lm_v2_response(NTLM_CONTEXT* context)
497
470
{
498
470
  BYTE* response = nullptr;
499
470
  BYTE value[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
500
501
470
  WINPR_ASSERT(context);
502
503
470
  if (context->LmCompatibilityLevel < 2)
504
0
  {
505
0
    if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24))
506
0
      return SEC_E_INSUFFICIENT_MEMORY;
507
508
0
    ZeroMemory(context->LmChallengeResponse.pvBuffer, 24);
509
0
    return SEC_E_OK;
510
0
  }
511
512
  /* Compute the NTLMv2 hash */
513
514
470
  if (!ntlm_compute_ntlm_v2_hash(context, context->NtlmV2Hash))
515
0
    return SEC_E_NO_CREDENTIALS;
516
517
  /* Concatenate the server and client challenges */
518
470
  CopyMemory(value, context->ServerChallenge, 8);
519
470
  CopyMemory(&value[8], context->ClientChallenge, 8);
520
521
470
  if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24))
522
0
    return SEC_E_INSUFFICIENT_MEMORY;
523
524
470
  response = (BYTE*)context->LmChallengeResponse.pvBuffer;
525
  /* Compute the HMAC-MD5 hash of the resulting value using the NTLMv2 hash as the key */
526
470
  if (!winpr_HMAC(WINPR_MD_MD5, (void*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, (BYTE*)value,
527
470
                  WINPR_MD5_DIGEST_LENGTH, response, WINPR_MD5_DIGEST_LENGTH))
528
0
    return SEC_E_ALGORITHM_MISMATCH;
529
530
  /* Concatenate the resulting HMAC-MD5 hash and the client challenge, giving us the LMv2 response
531
   * (24 bytes) */
532
470
  CopyMemory(&response[16], context->ClientChallenge, 8);
533
470
  return SEC_E_OK;
534
470
}
535
536
/**
537
 * Compute NTLMv2 Response.
538
 *
539
 * NTLMv2_RESPONSE msdn{cc236653}
540
 * NTLMv2 Authentication msdn{cc236700}
541
 *
542
 * @param context A pointer to the NTLM context
543
 * @return \b TRUE for success, \b FALSE for failure
544
 */
545
546
SECURITY_STATUS ntlm_compute_ntlm_v2_response(NTLM_CONTEXT* context)
547
470
{
548
470
  SecBuffer ntlm_v2_temp = WINPR_C_ARRAY_INIT;
549
470
  SecBuffer ntlm_v2_temp_chal = WINPR_C_ARRAY_INIT;
550
551
470
  WINPR_ASSERT(context);
552
553
470
  PSecBuffer TargetInfo = &context->ChallengeTargetInfo;
554
470
  SECURITY_STATUS ret = SEC_E_INSUFFICIENT_MEMORY;
555
556
470
  if (!sspi_SecBufferAlloc(&ntlm_v2_temp, TargetInfo->cbBuffer + 28))
557
0
    goto exit;
558
559
470
  ZeroMemory(ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
560
470
  {
561
470
    BYTE* blob = (BYTE*)ntlm_v2_temp.pvBuffer;
562
563
    /* Compute the NTLMv2 hash */
564
470
    ret = SEC_E_NO_CREDENTIALS;
565
470
    if (!ntlm_compute_ntlm_v2_hash(context, (BYTE*)context->NtlmV2Hash))
566
0
      goto exit;
567
568
    /* Construct temp */
569
470
    blob[0] = 1; /* RespType (1 byte) */
570
470
    blob[1] = 1; /* HighRespType (1 byte) */
571
    /* Reserved1 (2 bytes) */
572
    /* Reserved2 (4 bytes) */
573
470
    CopyMemory(&blob[8], context->Timestamp, 8);        /* Timestamp (8 bytes) */
574
470
    CopyMemory(&blob[16], context->ClientChallenge, 8); /* ClientChallenge (8 bytes) */
575
    /* Reserved3 (4 bytes) */
576
470
    CopyMemory(&blob[28], TargetInfo->pvBuffer, TargetInfo->cbBuffer);
577
#ifdef WITH_DEBUG_NTLM
578
    WLog_VRB(TAG, "NTLMv2 Response Temp Blob");
579
    winpr_HexDump(TAG, WLOG_TRACE, ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
580
#endif
581
470
  }
582
  /* Concatenate server challenge with temp */
583
470
  ret = SEC_E_INSUFFICIENT_MEMORY;
584
470
  if (!sspi_SecBufferAlloc(&ntlm_v2_temp_chal, ntlm_v2_temp.cbBuffer + 8))
585
0
    goto exit;
586
587
470
  {
588
470
    BYTE* blob = (BYTE*)ntlm_v2_temp_chal.pvBuffer;
589
470
    CopyMemory(blob, context->ServerChallenge, 8);
590
470
    CopyMemory(&blob[8], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
591
470
    if (!winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH,
592
470
                    (BYTE*)ntlm_v2_temp_chal.pvBuffer, ntlm_v2_temp_chal.cbBuffer,
593
470
                    context->NtProofString, WINPR_MD5_DIGEST_LENGTH))
594
0
      goto exit;
595
470
  }
596
597
  /* NtChallengeResponse, Concatenate NTProofStr with temp */
598
599
470
  if (!sspi_SecBufferAlloc(&context->NtChallengeResponse, ntlm_v2_temp.cbBuffer + 16))
600
0
    goto exit;
601
602
470
  {
603
470
    BYTE* blob = (BYTE*)context->NtChallengeResponse.pvBuffer;
604
470
    CopyMemory(blob, context->NtProofString, WINPR_MD5_DIGEST_LENGTH);
605
470
    CopyMemory(&blob[16], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
606
470
  }
607
  /* Compute SessionBaseKey, the HMAC-MD5 hash of NTProofStr using the NTLMv2 hash as the key */
608
470
  if (!winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH,
609
470
                  context->NtProofString, WINPR_MD5_DIGEST_LENGTH, context->SessionBaseKey,
610
470
                  WINPR_MD5_DIGEST_LENGTH))
611
0
    goto exit;
612
470
  ret = SEC_E_OK;
613
470
exit:
614
470
  sspi_SecBufferFree(&ntlm_v2_temp);
615
470
  sspi_SecBufferFree(&ntlm_v2_temp_chal);
616
470
  return ret;
617
470
}
618
619
/**
620
 * Encrypt the given plain text using RC4 and the given key.
621
 * @param key RC4 key
622
 * @param length text length
623
 * @param plaintext plain text
624
 * @param ciphertext cipher text
625
 */
626
627
BOOL ntlm_rc4k(BYTE* key, size_t length, BYTE* plaintext, BYTE* ciphertext)
628
202
{
629
202
  WINPR_RC4_CTX* rc4 = winpr_RC4_New(key, 16);
630
631
202
  if (!rc4)
632
0
    return FALSE;
633
634
202
  const BOOL rc = winpr_RC4_Update(rc4, length, plaintext, ciphertext);
635
202
  winpr_RC4_Free(rc4);
636
202
  return rc;
637
202
}
638
639
/**
640
 * Generate client challenge (8-byte nonce).
641
 * @param context A pointer to the NTLM context
642
 */
643
644
BOOL ntlm_generate_client_challenge(NTLM_CONTEXT* context)
645
663
{
646
663
  WINPR_ASSERT(context);
647
648
  /* ClientChallenge is used in computation of LMv2 and NTLMv2 responses */
649
663
  if (memcmp(context->ClientChallenge, NTLM_NULL_BUFFER, sizeof(context->ClientChallenge)) != 0)
650
0
    return TRUE;
651
652
663
  return winpr_RAND(context->ClientChallenge, sizeof(context->ClientChallenge)) >= 0;
653
663
}
654
655
/**
656
 * Generate server challenge (8-byte nonce).
657
 * @param context A pointer to the NTLM context
658
 */
659
660
BOOL ntlm_generate_server_challenge(NTLM_CONTEXT* context)
661
577
{
662
577
  WINPR_ASSERT(context);
663
664
577
  if (memcmp(context->ServerChallenge, NTLM_NULL_BUFFER, sizeof(context->ServerChallenge)) != 0)
665
0
    return TRUE;
666
667
577
  return winpr_RAND(context->ServerChallenge, sizeof(context->ServerChallenge)) >= 0;
668
577
}
669
670
/**
671
 * Generate KeyExchangeKey (the 128-bit SessionBaseKey). msdn{cc236710}
672
 * @param context A pointer to the NTLM context
673
 */
674
675
BOOL ntlm_generate_key_exchange_key(NTLM_CONTEXT* context)
676
470
{
677
470
  WINPR_ASSERT(context);
678
470
  WINPR_ASSERT(sizeof(context->KeyExchangeKey) == sizeof(context->SessionBaseKey));
679
680
  /* In NTLMv2, KeyExchangeKey is the 128-bit SessionBaseKey */
681
470
  CopyMemory(context->KeyExchangeKey, context->SessionBaseKey, sizeof(context->KeyExchangeKey));
682
470
  return TRUE;
683
470
}
684
685
/**
686
 * Generate RandomSessionKey (16-byte nonce).
687
 * @param context A pointer to the NTLM context
688
 */
689
690
BOOL ntlm_generate_random_session_key(NTLM_CONTEXT* context)
691
197
{
692
197
  WINPR_ASSERT(context);
693
197
  return winpr_RAND(context->RandomSessionKey, sizeof(context->RandomSessionKey)) >= 0;
694
197
}
695
696
/**
697
 * Generate ExportedSessionKey (the RandomSessionKey, exported)
698
 * @param context A pointer to the NTLM context
699
 */
700
701
BOOL ntlm_generate_exported_session_key(NTLM_CONTEXT* context)
702
470
{
703
470
  WINPR_ASSERT(context);
704
470
  WINPR_ASSERT(sizeof(context->ExportedSessionKey) >= sizeof(context->RandomSessionKey));
705
706
470
  CopyMemory(context->ExportedSessionKey, context->RandomSessionKey,
707
470
             sizeof(context->ExportedSessionKey));
708
470
  return TRUE;
709
470
}
710
711
/**
712
 * Encrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key).
713
 * @param context A pointer to the NTLM context
714
 */
715
716
BOOL ntlm_encrypt_random_session_key(NTLM_CONTEXT* context)
717
197
{
718
  /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the
719
   * KeyExchangeKey */
720
197
  WINPR_ASSERT(context);
721
197
  return ntlm_rc4k(context->KeyExchangeKey, 16, context->RandomSessionKey,
722
197
                   context->EncryptedRandomSessionKey);
723
197
}
724
725
/**
726
 * Decrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key).
727
 * @param context A pointer to the NTLM context
728
 */
729
730
BOOL ntlm_decrypt_random_session_key(NTLM_CONTEXT* context)
731
273
{
732
273
  WINPR_ASSERT(context);
733
734
  /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the
735
   * KeyExchangeKey */
736
737
  /**
738
   *  if (NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
739
   *    Set RandomSessionKey to RC4K(KeyExchangeKey,
740
   * AUTHENTICATE_MESSAGE.EncryptedRandomSessionKey) else Set RandomSessionKey to KeyExchangeKey
741
   */
742
273
  if (context->NegotiateKeyExchange)
743
5
  {
744
5
    WINPR_ASSERT(sizeof(context->EncryptedRandomSessionKey) ==
745
5
                 sizeof(context->RandomSessionKey));
746
5
    return ntlm_rc4k(context->KeyExchangeKey, sizeof(context->EncryptedRandomSessionKey),
747
5
                     context->EncryptedRandomSessionKey, context->RandomSessionKey);
748
5
  }
749
268
  else
750
268
  {
751
268
    WINPR_ASSERT(sizeof(context->RandomSessionKey) == sizeof(context->KeyExchangeKey));
752
268
    CopyMemory(context->RandomSessionKey, context->KeyExchangeKey,
753
268
               sizeof(context->RandomSessionKey));
754
268
  }
755
268
  return TRUE;
756
273
}
757
758
/**
759
 * Generate signing key msdn{cc236711}
760
 *
761
 * @param exported_session_key ExportedSessionKey
762
 * @param sign_magic Sign magic string
763
 * @param signing_key Destination signing key
764
 *
765
 * @return \b TRUE for success, \b FALSE for failure
766
 */
767
768
static BOOL ntlm_generate_signing_key(BYTE* exported_session_key, const SecBuffer* sign_magic,
769
                                      BYTE* signing_key)
770
788
{
771
788
  BOOL rc = FALSE;
772
773
788
  WINPR_ASSERT(exported_session_key);
774
788
  WINPR_ASSERT(sign_magic);
775
788
  WINPR_ASSERT(signing_key);
776
777
788
  const size_t length = WINPR_MD5_DIGEST_LENGTH + sign_magic->cbBuffer;
778
788
  BYTE* value = (BYTE*)malloc(length);
779
780
788
  if (!value)
781
0
    goto out;
782
783
  /* Concatenate ExportedSessionKey with sign magic */
784
788
  CopyMemory(value, exported_session_key, WINPR_MD5_DIGEST_LENGTH);
785
788
  CopyMemory(&value[WINPR_MD5_DIGEST_LENGTH], sign_magic->pvBuffer, sign_magic->cbBuffer);
786
787
788
  rc = winpr_Digest(WINPR_MD_MD5, value, length, signing_key, WINPR_MD5_DIGEST_LENGTH);
788
789
788
out:
790
788
  free(value);
791
788
  return rc;
792
788
}
793
794
/**
795
 * Generate client signing key (ClientSigningKey). msdn{cc236711}
796
 * @param context A pointer to the NTLM context
797
 *
798
 * @return \b TRUE for success, \b FALSE for failure
799
 */
800
801
BOOL ntlm_generate_client_signing_key(NTLM_CONTEXT* context)
802
197
{
803
197
  const SecBuffer signMagic = { sizeof(NTLM_CLIENT_SIGN_MAGIC), 0, NTLM_CLIENT_SIGN_MAGIC };
804
805
197
  WINPR_ASSERT(context);
806
197
  return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic,
807
197
                                   context->ClientSigningKey);
808
197
}
809
810
/**
811
 * Generate server signing key (ServerSigningKey). msdn{cc236711}
812
 * @param context A pointer to the NTLM context
813
 *
814
 * @return \b TRUE for success, \b FALSE for failure
815
 */
816
817
BOOL ntlm_generate_server_signing_key(NTLM_CONTEXT* context)
818
197
{
819
197
  const SecBuffer signMagic = { sizeof(NTLM_SERVER_SIGN_MAGIC), 0, NTLM_SERVER_SIGN_MAGIC };
820
821
197
  WINPR_ASSERT(context);
822
197
  return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic,
823
197
                                   context->ServerSigningKey);
824
197
}
825
826
/**
827
 * Generate client sealing key (ClientSealingKey). msdn{cc236712}
828
 * @param context A pointer to the NTLM context
829
 *
830
 * @return \b TRUE for success, \b FALSE for failure
831
 */
832
833
BOOL ntlm_generate_client_sealing_key(NTLM_CONTEXT* context)
834
197
{
835
197
  const SecBuffer sealMagic = { sizeof(NTLM_CLIENT_SEAL_MAGIC), 0, NTLM_CLIENT_SEAL_MAGIC };
836
837
197
  WINPR_ASSERT(context);
838
197
  return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic,
839
197
                                   context->ClientSealingKey);
840
197
}
841
842
/**
843
 * Generate server sealing key (ServerSealingKey). msdn{cc236712}
844
 * @param context A pointer to the NTLM context
845
 *
846
 * @return \b TRUE for success, \b FALSE for failure
847
 */
848
849
BOOL ntlm_generate_server_sealing_key(NTLM_CONTEXT* context)
850
197
{
851
197
  const SecBuffer sealMagic = { sizeof(NTLM_SERVER_SEAL_MAGIC), 0, NTLM_SERVER_SEAL_MAGIC };
852
853
197
  WINPR_ASSERT(context);
854
197
  return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic,
855
197
                                   context->ServerSealingKey);
856
197
}
857
858
/**
859
 * Initialize RC4 stream cipher states for sealing.
860
 * @param context A pointer to the NTLM context
861
 */
862
863
BOOL ntlm_init_rc4_seal_states(NTLM_CONTEXT* context)
864
197
{
865
197
  WINPR_ASSERT(context);
866
197
  if (context->server)
867
0
  {
868
0
    context->SendSigningKey = context->ServerSigningKey;
869
0
    context->RecvSigningKey = context->ClientSigningKey;
870
0
    context->SendSealingKey = context->ClientSealingKey;
871
0
    context->RecvSealingKey = context->ServerSealingKey;
872
0
    context->SendRc4Seal =
873
0
        winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey));
874
0
    context->RecvRc4Seal =
875
0
        winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey));
876
0
  }
877
197
  else
878
197
  {
879
197
    context->SendSigningKey = context->ClientSigningKey;
880
197
    context->RecvSigningKey = context->ServerSigningKey;
881
197
    context->SendSealingKey = context->ServerSealingKey;
882
197
    context->RecvSealingKey = context->ClientSealingKey;
883
197
    context->SendRc4Seal =
884
197
        winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey));
885
197
    context->RecvRc4Seal =
886
197
        winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey));
887
197
  }
888
197
  if (!context->SendRc4Seal)
889
0
  {
890
0
    WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal");
891
0
    return FALSE;
892
0
  }
893
197
  if (!context->RecvRc4Seal)
894
0
  {
895
0
    WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal");
896
0
    return FALSE;
897
0
  }
898
197
  return TRUE;
899
197
}
900
901
BOOL ntlm_compute_message_integrity_check(NTLM_CONTEXT* context, BYTE* mic, UINT32 size)
902
273
{
903
273
  BOOL rc = FALSE;
904
  /*
905
   * Compute the HMAC-MD5 hash of ConcatenationOf(NEGOTIATE_MESSAGE,
906
   * CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE) using the ExportedSessionKey
907
   */
908
273
  WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
909
910
273
  WINPR_ASSERT(context);
911
273
  WINPR_ASSERT(mic);
912
273
  WINPR_ASSERT(size >= WINPR_MD5_DIGEST_LENGTH);
913
914
273
  memset(mic, 0, size);
915
273
  if (!hmac)
916
0
    return FALSE;
917
918
273
  if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->ExportedSessionKey, WINPR_MD5_DIGEST_LENGTH))
919
0
    goto fail;
920
921
273
  if (!winpr_HMAC_Update(hmac, (BYTE*)context->NegotiateMessage.pvBuffer,
922
273
                         context->NegotiateMessage.cbBuffer))
923
0
    goto fail;
924
273
  if (!winpr_HMAC_Update(hmac, (BYTE*)context->ChallengeMessage.pvBuffer,
925
273
                         context->ChallengeMessage.cbBuffer))
926
0
    goto fail;
927
928
273
  if (context->MessageIntegrityCheckOffset > 0)
929
273
  {
930
273
    const BYTE* auth = (BYTE*)context->AuthenticateMessage.pvBuffer;
931
273
    const BYTE data[WINPR_MD5_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
932
273
    const size_t rest = context->MessageIntegrityCheckOffset + sizeof(data);
933
934
273
    if (rest > context->AuthenticateMessage.cbBuffer)
935
8
      goto fail;
936
265
    if (!winpr_HMAC_Update(hmac, &auth[0], context->MessageIntegrityCheckOffset))
937
0
      goto fail;
938
265
    if (!winpr_HMAC_Update(hmac, data, sizeof(data)))
939
0
      goto fail;
940
265
    if (!winpr_HMAC_Update(hmac, &auth[rest], context->AuthenticateMessage.cbBuffer - rest))
941
0
      goto fail;
942
265
  }
943
0
  else
944
0
  {
945
0
    if (!winpr_HMAC_Update(hmac, (BYTE*)context->AuthenticateMessage.pvBuffer,
946
0
                           context->AuthenticateMessage.cbBuffer))
947
0
      goto fail;
948
0
  }
949
265
  rc = winpr_HMAC_Final(hmac, mic, WINPR_MD5_DIGEST_LENGTH);
950
951
273
fail:
952
273
  winpr_HMAC_Free(hmac);
953
273
  return rc;
954
265
}