Coverage Report

Created: 2024-05-20 06:11

/src/FreeRDP/winpr/libwinpr/sspi/NTLM/ntlm_compute.c
Line
Count
Source (jump to first uncovered line)
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
0
#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
0
{
60
0
  WINPR_ASSERT(versionInfo);
61
62
#if defined(WITH_WINPR_DEPRECATED)
63
  OSVERSIONINFOA osVersionInfo = { 0 };
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
0
  versionInfo->ProductMajorVersion = 10;
78
0
  versionInfo->ProductMinorVersion = 0;
79
0
  versionInfo->ProductBuild = 22631;
80
0
#endif
81
0
  ZeroMemory(versionInfo->Reserved, sizeof(versionInfo->Reserved));
82
0
  versionInfo->NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
83
0
  return TRUE;
84
0
}
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
0
{
96
0
  WINPR_ASSERT(s);
97
0
  WINPR_ASSERT(versionInfo);
98
99
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 8))
100
0
    return FALSE;
101
102
0
  Stream_Read_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */
103
0
  Stream_Read_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */
104
0
  Stream_Read_UINT16(s, versionInfo->ProductBuild);       /* ProductBuild (2 bytes) */
105
0
  Stream_Read(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */
106
0
  Stream_Read_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */
107
0
  return TRUE;
108
0
}
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
0
{
120
0
  WINPR_ASSERT(s);
121
0
  WINPR_ASSERT(versionInfo);
122
123
0
  if (!Stream_CheckAndLogRequiredCapacityEx(
124
0
          TAG, WLOG_WARN, s, 5ull + sizeof(versionInfo->Reserved), 1ull,
125
0
          "%s(%s:%" PRIuz ") NTLM_VERSION_INFO", __func__, __FILE__, (size_t)__LINE__))
126
0
    return FALSE;
127
128
0
  Stream_Write_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */
129
0
  Stream_Write_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */
130
0
  Stream_Write_UINT16(s, versionInfo->ProductBuild);       /* ProductBuild (2 bytes) */
131
0
  Stream_Write(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */
132
0
  Stream_Write_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */
133
0
  return TRUE;
134
0
}
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
0
{
157
0
  size_t size = 0;
158
0
  WINPR_ASSERT(s);
159
0
  WINPR_ASSERT(challenge);
160
161
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 28))
162
0
    return FALSE;
163
164
0
  Stream_Read_UINT8(s, challenge->RespType);
165
0
  Stream_Read_UINT8(s, challenge->HiRespType);
166
0
  Stream_Read_UINT16(s, challenge->Reserved1);
167
0
  Stream_Read_UINT32(s, challenge->Reserved2);
168
0
  Stream_Read(s, challenge->Timestamp, 8);
169
0
  Stream_Read(s, challenge->ClientChallenge, 8);
170
0
  Stream_Read_UINT32(s, challenge->Reserved3);
171
0
  size = Stream_Length(s) - Stream_GetPosition(s);
172
173
0
  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
0
  challenge->cbAvPairs = (UINT32)size;
180
0
  challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs);
181
182
0
  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
0
  Stream_Read(s, challenge->AvPairs, size);
190
0
  return TRUE;
191
0
}
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
0
{
222
0
  WINPR_ASSERT(s);
223
0
  WINPR_ASSERT(response);
224
225
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 16))
226
0
    return FALSE;
227
228
0
  Stream_Read(s, response->Response, 16);
229
0
  return ntlm_read_ntlm_v2_client_challenge(s, &(response->Challenge));
230
0
}
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
void ntlm_current_time(BYTE* timestamp)
250
0
{
251
0
  FILETIME ft = { 0 };
252
253
0
  WINPR_ASSERT(timestamp);
254
255
0
  GetSystemTimeAsFileTime(&ft);
256
0
  CopyMemory(timestamp, &(ft), sizeof(ft));
257
0
}
258
259
/**
260
 * Generate timestamp for AUTHENTICATE_MESSAGE.
261
 *
262
 * @param context A pointer to the NTLM context
263
 */
264
265
void ntlm_generate_timestamp(NTLM_CONTEXT* context)
266
0
{
267
0
  WINPR_ASSERT(context);
268
269
0
  if (memcmp(context->ChallengeTimestamp, NTLM_NULL_BUFFER, 8) != 0)
270
0
    CopyMemory(context->Timestamp, context->ChallengeTimestamp, 8);
271
0
  else
272
0
    ntlm_current_time(context->Timestamp);
273
0
}
274
275
static BOOL ntlm_fetch_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash)
276
0
{
277
0
  BOOL rc = FALSE;
278
0
  WINPR_SAM* sam = NULL;
279
0
  WINPR_SAM_ENTRY* entry = NULL;
280
0
  SSPI_CREDENTIALS* credentials = NULL;
281
282
0
  WINPR_ASSERT(context);
283
0
  WINPR_ASSERT(hash);
284
285
0
  credentials = context->credentials;
286
0
  sam = SamOpen(context->SamFile, TRUE);
287
288
0
  if (!sam)
289
0
    goto fail;
290
291
0
  entry = SamLookupUserW(
292
0
      sam, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * sizeof(WCHAR),
293
0
      (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * sizeof(WCHAR));
294
295
0
  if (!entry)
296
0
  {
297
0
    entry = SamLookupUserW(sam, (LPWSTR)credentials->identity.User,
298
0
                           credentials->identity.UserLength * sizeof(WCHAR), NULL, 0);
299
0
  }
300
301
0
  if (!entry)
302
0
    goto fail;
303
304
#ifdef WITH_DEBUG_NTLM
305
  WLog_VRB(TAG, "NTLM Hash:");
306
  winpr_HexDump(TAG, WLOG_DEBUG, entry->NtHash, 16);
307
#endif
308
0
  NTOWFv2FromHashW(entry->NtHash, (LPWSTR)credentials->identity.User,
309
0
                   credentials->identity.UserLength * sizeof(WCHAR),
310
0
                   (LPWSTR)credentials->identity.Domain,
311
0
                   credentials->identity.DomainLength * sizeof(WCHAR), (BYTE*)hash);
312
313
0
  rc = TRUE;
314
315
0
fail:
316
0
  SamFreeEntry(sam, entry);
317
0
  SamClose(sam);
318
0
  if (!rc)
319
0
    WLog_ERR(TAG, "Error: Could not find user in SAM database");
320
321
0
  return rc;
322
0
}
323
324
static int ntlm_convert_password_hash(NTLM_CONTEXT* context, BYTE* hash)
325
0
{
326
0
  char PasswordHash[32] = { 0 };
327
0
  INT64 PasswordHashLength = 0;
328
0
  SSPI_CREDENTIALS* credentials = NULL;
329
330
0
  WINPR_ASSERT(context);
331
0
  WINPR_ASSERT(hash);
332
333
0
  credentials = context->credentials;
334
  /* Password contains a password hash of length (PasswordLength -
335
   * SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) */
336
0
  PasswordHashLength = credentials->identity.PasswordLength - SSPI_CREDENTIALS_HASH_LENGTH_OFFSET;
337
338
0
  WINPR_ASSERT(PasswordHashLength >= 0);
339
0
  WINPR_ASSERT((size_t)PasswordHashLength < ARRAYSIZE(PasswordHash));
340
0
  if (ConvertWCharNToUtf8(credentials->identity.Password, PasswordHashLength, PasswordHash,
341
0
                          ARRAYSIZE(PasswordHash)) <= 0)
342
0
    return -1;
343
344
0
  CharUpperBuffA(PasswordHash, (DWORD)PasswordHashLength);
345
346
0
  for (size_t i = 0; i < ARRAYSIZE(PasswordHash); i += 2)
347
0
  {
348
0
    BYTE hn =
349
0
        (BYTE)(PasswordHash[i] > '9' ? PasswordHash[i] - 'A' + 10 : PasswordHash[i] - '0');
350
0
    BYTE ln = (BYTE)(PasswordHash[i + 1] > '9' ? PasswordHash[i + 1] - 'A' + 10
351
0
                                               : PasswordHash[i + 1] - '0');
352
0
    hash[i / 2] = (BYTE)((hn << 4) | ln);
353
0
  }
354
355
0
  return 1;
356
0
}
357
358
static BOOL ntlm_compute_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash)
359
0
{
360
0
  SSPI_CREDENTIALS* credentials = NULL;
361
362
0
  WINPR_ASSERT(context);
363
0
  WINPR_ASSERT(hash);
364
365
0
  credentials = context->credentials;
366
#ifdef WITH_DEBUG_NTLM
367
368
  if (credentials)
369
  {
370
    WLog_VRB(TAG, "Password (length = %" PRIu32 ")", credentials->identity.PasswordLength * 2);
371
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Password,
372
                  credentials->identity.PasswordLength * 2);
373
    WLog_VRB(TAG, "Username (length = %" PRIu32 ")", credentials->identity.UserLength * 2);
374
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.User,
375
                  credentials->identity.UserLength * 2);
376
    WLog_VRB(TAG, "Domain (length = %" PRIu32 ")", credentials->identity.DomainLength * 2);
377
    winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Domain,
378
                  credentials->identity.DomainLength * 2);
379
  }
380
  else
381
    WLog_VRB(TAG, "Strange, NTLM_CONTEXT is missing valid credentials...");
382
383
  WLog_VRB(TAG, "Workstation (length = %" PRIu16 ")", context->Workstation.Length);
384
  winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)context->Workstation.Buffer, context->Workstation.Length);
385
  WLog_VRB(TAG, "NTOWFv2, NTLMv2 Hash");
386
  winpr_HexDump(TAG, WLOG_TRACE, context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH);
387
#endif
388
389
0
  if (memcmp(context->NtlmV2Hash, NTLM_NULL_BUFFER, 16) != 0)
390
0
    return TRUE;
391
392
0
  if (!credentials)
393
0
    return FALSE;
394
0
  else if (memcmp(context->NtlmHash, NTLM_NULL_BUFFER, 16) != 0)
395
0
  {
396
0
    NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User,
397
0
                     credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain,
398
0
                     credentials->identity.DomainLength * 2, (BYTE*)hash);
399
0
  }
400
0
  else if (credentials->identity.PasswordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET)
401
0
  {
402
    /* Special case for WinPR: password hash */
403
0
    if (ntlm_convert_password_hash(context, context->NtlmHash) < 0)
404
0
      return FALSE;
405
406
0
    NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User,
407
0
                     credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain,
408
0
                     credentials->identity.DomainLength * 2, (BYTE*)hash);
409
0
  }
410
0
  else if (credentials->identity.Password)
411
0
  {
412
0
    NTOWFv2W((LPWSTR)credentials->identity.Password, credentials->identity.PasswordLength * 2,
413
0
             (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2,
414
0
             (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2,
415
0
             (BYTE*)hash);
416
0
  }
417
0
  else if (context->HashCallback)
418
0
  {
419
0
    int ret = 0;
420
0
    SecBuffer proofValue;
421
0
    SecBuffer micValue;
422
423
0
    if (ntlm_computeProofValue(context, &proofValue) != SEC_E_OK)
424
0
      return FALSE;
425
426
0
    if (ntlm_computeMicValue(context, &micValue) != SEC_E_OK)
427
0
    {
428
0
      sspi_SecBufferFree(&proofValue);
429
0
      return FALSE;
430
0
    }
431
432
0
    ret = context->HashCallback(context->HashCallbackArg, &credentials->identity, &proofValue,
433
0
                                context->EncryptedRandomSessionKey,
434
0
                                context->AUTHENTICATE_MESSAGE.MessageIntegrityCheck, &micValue,
435
0
                                hash);
436
0
    sspi_SecBufferFree(&proofValue);
437
0
    sspi_SecBufferFree(&micValue);
438
0
    return ret ? TRUE : FALSE;
439
0
  }
440
0
  else if (context->UseSamFileDatabase)
441
0
  {
442
0
    return ntlm_fetch_ntlm_v2_hash(context, hash);
443
0
  }
444
445
0
  return TRUE;
446
0
}
447
448
BOOL ntlm_compute_lm_v2_response(NTLM_CONTEXT* context)
449
0
{
450
0
  BYTE* response = NULL;
451
0
  BYTE value[WINPR_MD5_DIGEST_LENGTH] = { 0 };
452
453
0
  WINPR_ASSERT(context);
454
455
0
  if (context->LmCompatibilityLevel < 2)
456
0
  {
457
0
    if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24))
458
0
      return FALSE;
459
460
0
    ZeroMemory(context->LmChallengeResponse.pvBuffer, 24);
461
0
    return TRUE;
462
0
  }
463
464
  /* Compute the NTLMv2 hash */
465
466
0
  if (!ntlm_compute_ntlm_v2_hash(context, context->NtlmV2Hash))
467
0
    return FALSE;
468
469
  /* Concatenate the server and client challenges */
470
0
  CopyMemory(value, context->ServerChallenge, 8);
471
0
  CopyMemory(&value[8], context->ClientChallenge, 8);
472
473
0
  if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24))
474
0
    return FALSE;
475
476
0
  response = (BYTE*)context->LmChallengeResponse.pvBuffer;
477
  /* Compute the HMAC-MD5 hash of the resulting value using the NTLMv2 hash as the key */
478
0
  winpr_HMAC(WINPR_MD_MD5, (void*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, (BYTE*)value,
479
0
             WINPR_MD5_DIGEST_LENGTH, (BYTE*)response, WINPR_MD5_DIGEST_LENGTH);
480
  /* Concatenate the resulting HMAC-MD5 hash and the client challenge, giving us the LMv2 response
481
   * (24 bytes) */
482
0
  CopyMemory(&response[16], context->ClientChallenge, 8);
483
0
  return TRUE;
484
0
}
485
486
/**
487
 * Compute NTLMv2 Response.
488
 *
489
 * NTLMv2_RESPONSE msdn{cc236653}
490
 * NTLMv2 Authentication msdn{cc236700}
491
 *
492
 * @param context A pointer to the NTLM context
493
 * @return \b TRUE for success, \b FALSE for failure
494
 */
495
496
BOOL ntlm_compute_ntlm_v2_response(NTLM_CONTEXT* context)
497
0
{
498
0
  BYTE* blob = NULL;
499
0
  SecBuffer ntlm_v2_temp = { 0 };
500
0
  SecBuffer ntlm_v2_temp_chal = { 0 };
501
0
  PSecBuffer TargetInfo = NULL;
502
503
0
  WINPR_ASSERT(context);
504
505
0
  TargetInfo = &context->ChallengeTargetInfo;
506
0
  BOOL ret = FALSE;
507
508
0
  if (!sspi_SecBufferAlloc(&ntlm_v2_temp, TargetInfo->cbBuffer + 28))
509
0
    goto exit;
510
511
0
  ZeroMemory(ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
512
0
  blob = (BYTE*)ntlm_v2_temp.pvBuffer;
513
514
  /* Compute the NTLMv2 hash */
515
0
  if (!ntlm_compute_ntlm_v2_hash(context, (BYTE*)context->NtlmV2Hash))
516
0
    goto exit;
517
518
  /* Construct temp */
519
0
  blob[0] = 1; /* RespType (1 byte) */
520
0
  blob[1] = 1; /* HighRespType (1 byte) */
521
  /* Reserved1 (2 bytes) */
522
  /* Reserved2 (4 bytes) */
523
0
  CopyMemory(&blob[8], context->Timestamp, 8);        /* Timestamp (8 bytes) */
524
0
  CopyMemory(&blob[16], context->ClientChallenge, 8); /* ClientChallenge (8 bytes) */
525
  /* Reserved3 (4 bytes) */
526
0
  CopyMemory(&blob[28], TargetInfo->pvBuffer, TargetInfo->cbBuffer);
527
#ifdef WITH_DEBUG_NTLM
528
  WLog_VRB(TAG, "NTLMv2 Response Temp Blob");
529
  winpr_HexDump(TAG, WLOG_TRACE, ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
530
#endif
531
532
  /* Concatenate server challenge with temp */
533
534
0
  if (!sspi_SecBufferAlloc(&ntlm_v2_temp_chal, ntlm_v2_temp.cbBuffer + 8))
535
0
    goto exit;
536
537
0
  blob = (BYTE*)ntlm_v2_temp_chal.pvBuffer;
538
0
  CopyMemory(blob, context->ServerChallenge, 8);
539
0
  CopyMemory(&blob[8], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
540
0
  winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH,
541
0
             (BYTE*)ntlm_v2_temp_chal.pvBuffer, ntlm_v2_temp_chal.cbBuffer,
542
0
             context->NtProofString, WINPR_MD5_DIGEST_LENGTH);
543
544
  /* NtChallengeResponse, Concatenate NTProofStr with temp */
545
546
0
  if (!sspi_SecBufferAlloc(&context->NtChallengeResponse, ntlm_v2_temp.cbBuffer + 16))
547
0
    goto exit;
548
549
0
  blob = (BYTE*)context->NtChallengeResponse.pvBuffer;
550
0
  CopyMemory(blob, context->NtProofString, WINPR_MD5_DIGEST_LENGTH);
551
0
  CopyMemory(&blob[16], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer);
552
  /* Compute SessionBaseKey, the HMAC-MD5 hash of NTProofStr using the NTLMv2 hash as the key */
553
0
  winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH,
554
0
             context->NtProofString, WINPR_MD5_DIGEST_LENGTH, context->SessionBaseKey,
555
0
             WINPR_MD5_DIGEST_LENGTH);
556
0
  ret = TRUE;
557
0
exit:
558
0
  sspi_SecBufferFree(&ntlm_v2_temp);
559
0
  sspi_SecBufferFree(&ntlm_v2_temp_chal);
560
0
  return ret;
561
0
}
562
563
/**
564
 * Encrypt the given plain text using RC4 and the given key.
565
 * @param key RC4 key
566
 * @param length text length
567
 * @param plaintext plain text
568
 * @param ciphertext cipher text
569
 */
570
571
void ntlm_rc4k(BYTE* key, size_t length, BYTE* plaintext, BYTE* ciphertext)
572
0
{
573
0
  WINPR_RC4_CTX* rc4 = winpr_RC4_New(key, 16);
574
575
0
  if (rc4)
576
0
  {
577
0
    winpr_RC4_Update(rc4, length, plaintext, ciphertext);
578
0
    winpr_RC4_Free(rc4);
579
0
  }
580
0
}
581
582
/**
583
 * Generate client challenge (8-byte nonce).
584
 * @param context A pointer to the NTLM context
585
 */
586
587
void ntlm_generate_client_challenge(NTLM_CONTEXT* context)
588
0
{
589
0
  WINPR_ASSERT(context);
590
591
  /* ClientChallenge is used in computation of LMv2 and NTLMv2 responses */
592
0
  if (memcmp(context->ClientChallenge, NTLM_NULL_BUFFER, sizeof(context->ClientChallenge)) == 0)
593
0
    winpr_RAND(context->ClientChallenge, sizeof(context->ClientChallenge));
594
0
}
595
596
/**
597
 * Generate server challenge (8-byte nonce).
598
 * @param context A pointer to the NTLM context
599
 */
600
601
void ntlm_generate_server_challenge(NTLM_CONTEXT* context)
602
0
{
603
0
  WINPR_ASSERT(context);
604
605
0
  if (memcmp(context->ServerChallenge, NTLM_NULL_BUFFER, sizeof(context->ServerChallenge)) == 0)
606
0
    winpr_RAND(context->ServerChallenge, sizeof(context->ServerChallenge));
607
0
}
608
609
/**
610
 * Generate KeyExchangeKey (the 128-bit SessionBaseKey). msdn{cc236710}
611
 * @param context A pointer to the NTLM context
612
 */
613
614
void ntlm_generate_key_exchange_key(NTLM_CONTEXT* context)
615
0
{
616
0
  WINPR_ASSERT(context);
617
0
  WINPR_ASSERT(sizeof(context->KeyExchangeKey) == sizeof(context->SessionBaseKey));
618
619
  /* In NTLMv2, KeyExchangeKey is the 128-bit SessionBaseKey */
620
0
  CopyMemory(context->KeyExchangeKey, context->SessionBaseKey, sizeof(context->KeyExchangeKey));
621
0
}
622
623
/**
624
 * Generate RandomSessionKey (16-byte nonce).
625
 * @param context A pointer to the NTLM context
626
 */
627
628
void ntlm_generate_random_session_key(NTLM_CONTEXT* context)
629
0
{
630
0
  WINPR_ASSERT(context);
631
0
  winpr_RAND(context->RandomSessionKey, sizeof(context->RandomSessionKey));
632
0
}
633
634
/**
635
 * Generate ExportedSessionKey (the RandomSessionKey, exported)
636
 * @param context A pointer to the NTLM context
637
 */
638
639
void ntlm_generate_exported_session_key(NTLM_CONTEXT* context)
640
0
{
641
0
  WINPR_ASSERT(context);
642
643
0
  CopyMemory(context->ExportedSessionKey, context->RandomSessionKey,
644
0
             sizeof(context->ExportedSessionKey));
645
0
}
646
647
/**
648
 * Encrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key).
649
 * @param context A pointer to the NTLM context
650
 */
651
652
void ntlm_encrypt_random_session_key(NTLM_CONTEXT* context)
653
0
{
654
  /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the
655
   * KeyExchangeKey */
656
0
  WINPR_ASSERT(context);
657
0
  ntlm_rc4k(context->KeyExchangeKey, 16, context->RandomSessionKey,
658
0
            context->EncryptedRandomSessionKey);
659
0
}
660
661
/**
662
 * Decrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key).
663
 * @param context A pointer to the NTLM context
664
 */
665
666
void ntlm_decrypt_random_session_key(NTLM_CONTEXT* context)
667
0
{
668
0
  WINPR_ASSERT(context);
669
670
  /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the
671
   * KeyExchangeKey */
672
673
  /**
674
   *  if (NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
675
   *    Set RandomSessionKey to RC4K(KeyExchangeKey,
676
   * AUTHENTICATE_MESSAGE.EncryptedRandomSessionKey) else Set RandomSessionKey to KeyExchangeKey
677
   */
678
0
  if (context->NegotiateKeyExchange)
679
0
  {
680
0
    WINPR_ASSERT(sizeof(context->EncryptedRandomSessionKey) ==
681
0
                 sizeof(context->RandomSessionKey));
682
0
    ntlm_rc4k(context->KeyExchangeKey, sizeof(context->EncryptedRandomSessionKey),
683
0
              context->EncryptedRandomSessionKey, context->RandomSessionKey);
684
0
  }
685
0
  else
686
0
  {
687
0
    WINPR_ASSERT(sizeof(context->RandomSessionKey) == sizeof(context->KeyExchangeKey));
688
0
    CopyMemory(context->RandomSessionKey, context->KeyExchangeKey,
689
0
               sizeof(context->RandomSessionKey));
690
0
  }
691
0
}
692
693
/**
694
 * Generate signing key msdn{cc236711}
695
 *
696
 * @param exported_session_key ExportedSessionKey
697
 * @param sign_magic Sign magic string
698
 * @param signing_key Destination signing key
699
 *
700
 * @return \b TRUE for success, \b FALSE for failure
701
 */
702
703
static BOOL ntlm_generate_signing_key(BYTE* exported_session_key, const SecBuffer* sign_magic,
704
                                      BYTE* signing_key)
705
0
{
706
0
  BOOL rc = FALSE;
707
0
  size_t length = 0;
708
0
  BYTE* value = NULL;
709
710
0
  WINPR_ASSERT(exported_session_key);
711
0
  WINPR_ASSERT(sign_magic);
712
0
  WINPR_ASSERT(signing_key);
713
714
0
  length = WINPR_MD5_DIGEST_LENGTH + sign_magic->cbBuffer;
715
0
  value = (BYTE*)malloc(length);
716
717
0
  if (!value)
718
0
    goto out;
719
720
  /* Concatenate ExportedSessionKey with sign magic */
721
0
  CopyMemory(value, exported_session_key, WINPR_MD5_DIGEST_LENGTH);
722
0
  CopyMemory(&value[WINPR_MD5_DIGEST_LENGTH], sign_magic->pvBuffer, sign_magic->cbBuffer);
723
724
0
  rc = winpr_Digest(WINPR_MD_MD5, value, length, signing_key, WINPR_MD5_DIGEST_LENGTH);
725
726
0
out:
727
0
  free(value);
728
0
  return rc;
729
0
}
730
731
/**
732
 * Generate client signing key (ClientSigningKey). msdn{cc236711}
733
 * @param context A pointer to the NTLM context
734
 *
735
 * @return \b TRUE for success, \b FALSE for failure
736
 */
737
738
BOOL ntlm_generate_client_signing_key(NTLM_CONTEXT* context)
739
0
{
740
0
  const SecBuffer signMagic = { sizeof(NTLM_CLIENT_SIGN_MAGIC), 0, NTLM_CLIENT_SIGN_MAGIC };
741
742
0
  WINPR_ASSERT(context);
743
0
  return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic,
744
0
                                   context->ClientSigningKey);
745
0
}
746
747
/**
748
 * Generate server signing key (ServerSigningKey). msdn{cc236711}
749
 * @param context A pointer to the NTLM context
750
 *
751
 * @return \b TRUE for success, \b FALSE for failure
752
 */
753
754
BOOL ntlm_generate_server_signing_key(NTLM_CONTEXT* context)
755
0
{
756
0
  const SecBuffer signMagic = { sizeof(NTLM_SERVER_SIGN_MAGIC), 0, NTLM_SERVER_SIGN_MAGIC };
757
758
0
  WINPR_ASSERT(context);
759
0
  return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic,
760
0
                                   context->ServerSigningKey);
761
0
}
762
763
/**
764
 * Generate client sealing key (ClientSealingKey). msdn{cc236712}
765
 * @param context A pointer to the NTLM context
766
 *
767
 * @return \b TRUE for success, \b FALSE for failure
768
 */
769
770
BOOL ntlm_generate_client_sealing_key(NTLM_CONTEXT* context)
771
0
{
772
0
  const SecBuffer sealMagic = { sizeof(NTLM_CLIENT_SEAL_MAGIC), 0, NTLM_CLIENT_SEAL_MAGIC };
773
774
0
  WINPR_ASSERT(context);
775
0
  return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic,
776
0
                                   context->ClientSealingKey);
777
0
}
778
779
/**
780
 * Generate server sealing key (ServerSealingKey). msdn{cc236712}
781
 * @param context A pointer to the NTLM context
782
 *
783
 * @return \b TRUE for success, \b FALSE for failure
784
 */
785
786
BOOL ntlm_generate_server_sealing_key(NTLM_CONTEXT* context)
787
0
{
788
0
  const SecBuffer sealMagic = { sizeof(NTLM_SERVER_SEAL_MAGIC), 0, NTLM_SERVER_SEAL_MAGIC };
789
790
0
  WINPR_ASSERT(context);
791
0
  return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic,
792
0
                                   context->ServerSealingKey);
793
0
}
794
795
/**
796
 * Initialize RC4 stream cipher states for sealing.
797
 * @param context A pointer to the NTLM context
798
 */
799
800
BOOL ntlm_init_rc4_seal_states(NTLM_CONTEXT* context)
801
0
{
802
0
  WINPR_ASSERT(context);
803
0
  if (context->server)
804
0
  {
805
0
    context->SendSigningKey = context->ServerSigningKey;
806
0
    context->RecvSigningKey = context->ClientSigningKey;
807
0
    context->SendSealingKey = context->ClientSealingKey;
808
0
    context->RecvSealingKey = context->ServerSealingKey;
809
0
    context->SendRc4Seal =
810
0
        winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey));
811
0
    context->RecvRc4Seal =
812
0
        winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey));
813
0
  }
814
0
  else
815
0
  {
816
0
    context->SendSigningKey = context->ClientSigningKey;
817
0
    context->RecvSigningKey = context->ServerSigningKey;
818
0
    context->SendSealingKey = context->ServerSealingKey;
819
0
    context->RecvSealingKey = context->ClientSealingKey;
820
0
    context->SendRc4Seal =
821
0
        winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey));
822
0
    context->RecvRc4Seal =
823
0
        winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey));
824
0
  }
825
0
  if (!context->SendRc4Seal)
826
0
  {
827
0
    WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal");
828
0
    return FALSE;
829
0
  }
830
0
  if (!context->RecvRc4Seal)
831
0
  {
832
0
    WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal");
833
0
    return FALSE;
834
0
  }
835
0
  return TRUE;
836
0
}
837
838
BOOL ntlm_compute_message_integrity_check(NTLM_CONTEXT* context, BYTE* mic, UINT32 size)
839
0
{
840
0
  BOOL rc = FALSE;
841
  /*
842
   * Compute the HMAC-MD5 hash of ConcatenationOf(NEGOTIATE_MESSAGE,
843
   * CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE) using the ExportedSessionKey
844
   */
845
0
  WINPR_HMAC_CTX* hmac = winpr_HMAC_New();
846
847
0
  WINPR_ASSERT(context);
848
0
  WINPR_ASSERT(mic);
849
0
  WINPR_ASSERT(size >= WINPR_MD5_DIGEST_LENGTH);
850
851
0
  memset(mic, 0, size);
852
0
  if (!hmac)
853
0
    return FALSE;
854
855
0
  if (winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->ExportedSessionKey, WINPR_MD5_DIGEST_LENGTH))
856
0
  {
857
0
    winpr_HMAC_Update(hmac, (BYTE*)context->NegotiateMessage.pvBuffer,
858
0
                      context->NegotiateMessage.cbBuffer);
859
0
    winpr_HMAC_Update(hmac, (BYTE*)context->ChallengeMessage.pvBuffer,
860
0
                      context->ChallengeMessage.cbBuffer);
861
862
0
    if (context->MessageIntegrityCheckOffset > 0)
863
0
    {
864
0
      const BYTE* auth = (BYTE*)context->AuthenticateMessage.pvBuffer;
865
0
      const BYTE data[WINPR_MD5_DIGEST_LENGTH] = { 0 };
866
0
      const size_t rest = context->MessageIntegrityCheckOffset + sizeof(data);
867
868
0
      WINPR_ASSERT(rest <= context->AuthenticateMessage.cbBuffer);
869
0
      winpr_HMAC_Update(hmac, &auth[0], context->MessageIntegrityCheckOffset);
870
0
      winpr_HMAC_Update(hmac, data, sizeof(data));
871
0
      winpr_HMAC_Update(hmac, &auth[rest], context->AuthenticateMessage.cbBuffer - rest);
872
0
    }
873
0
    else
874
0
    {
875
0
      winpr_HMAC_Update(hmac, (BYTE*)context->AuthenticateMessage.pvBuffer,
876
0
                        context->AuthenticateMessage.cbBuffer);
877
0
    }
878
0
    winpr_HMAC_Final(hmac, mic, WINPR_MD5_DIGEST_LENGTH);
879
0
    rc = TRUE;
880
0
  }
881
882
0
  winpr_HMAC_Free(hmac);
883
0
  return rc;
884
0
}