Coverage Report

Created: 2026-11-10 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/core/license.c
Line
Count
Source
1
/*
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * RDP Licensing
4
 *
5
 * Copyright 2011-2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2014 Norbert Federa <norbert.federa@thincast.com>
7
 * Copyright 2018 David Fort <contact@hardening-consulting.com>
8
 * Copyright 2022,2023 Armin Novak <armin.novak@thincast.com>
9
 * Copyright 2022,2023 Thincast Technologies GmbH
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 *     http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23
24
#include <freerdp/config.h>
25
26
#include "settings.h"
27
28
#include <freerdp/license.h>
29
30
#include <winpr/crt.h>
31
#include <winpr/assert.h>
32
#include <winpr/crypto.h>
33
#include <winpr/shell.h>
34
#include <winpr/path.h>
35
#include <winpr/file.h>
36
37
#include <freerdp/log.h>
38
39
#include <freerdp/crypto/certificate.h>
40
41
#include "license.h"
42
43
#include "../crypto/crypto.h"
44
#include "../crypto/certificate.h"
45
46
24.7k
#define LICENSE_TAG FREERDP_TAG("core.license")
47
48
// #define LICENSE_NULL_CLIENT_RANDOM 1
49
// #define LICENSE_NULL_PREMASTER_SECRET 1
50
51
// #define WITH_LICENSE_DECRYPT_CHALLENGE_RESPONSE
52
53
#define PLATFORM_CHALLENGE_RESPONSE_VERSION 0x0100
54
55
/* Upper limits for data exchanged.
56
 * In real situations they are not very large, but protocol wise these could be UINT32_MAX.
57
 * So limit to something larger than actually used but less than the giant limit.
58
 */
59
0
#define LICENSE_MAX_CAL_LENGTH (1ull * UINT16_MAX)
60
0
#define LICENSE_MAX_SCOPE_LENGTH (1ull * UINT16_MAX)
61
0
#define LICENSE_MAX_PRODUCT_ID_LENGTH (1ull * UINT16_MAX)
62
0
#define LICENSE_MAX_COMPANY_NAME_LENGTH (1ull * UINT16_MAX)
63
64
/** @brief Licensing Packet Types */
65
enum LicenseRequestType
66
{
67
  LICENSE_REQUEST = 0x01,
68
  PLATFORM_CHALLENGE = 0x02,
69
  NEW_LICENSE = 0x03,
70
  UPGRADE_LICENSE = 0x04,
71
  LICENSE_INFO = 0x12,
72
  NEW_LICENSE_REQUEST = 0x13,
73
  PLATFORM_CHALLENGE_RESPONSE = 0x15,
74
  ERROR_ALERT = 0xFF
75
};
76
77
/*
78
#define LICENSE_PKT_CS_MASK \
79
    (LICENSE_INFO | NEW_LICENSE_REQUEST | PLATFORM_CHALLENGE_RESPONSE | ERROR_ALERT)
80
#define LICENSE_PKT_SC_MASK \
81
    (LICENSE_REQUEST | PLATFORM_CHALLENGE | NEW_LICENSE | UPGRADE_LICENSE | ERROR_ALERT)
82
#define LICENSE_PKT_MASK (LICENSE_PKT_CS_MASK | LICENSE_PKT_SC_MASK)
83
*/
84
#define LICENSE_PREAMBLE_LENGTH 4
85
86
/* Cryptographic Lengths */
87
88
#define SERVER_RANDOM_LENGTH 32
89
#define MASTER_SECRET_LENGTH 48
90
#define PREMASTER_SECRET_LENGTH 48
91
#define SESSION_KEY_BLOB_LENGTH 48
92
#define MAC_SALT_KEY_LENGTH 16
93
#define LICENSING_ENCRYPTION_KEY_LENGTH 16
94
0
#define HWID_PLATFORM_ID_LENGTH 4
95
// #define HWID_UNIQUE_DATA_LENGTH 16
96
#define HWID_LENGTH 20
97
// #define LICENSING_PADDING_SIZE 8
98
99
/* Preamble Flags */
100
101
// #define PREAMBLE_VERSION_2_0 0x02
102
0
#define PREAMBLE_VERSION_3_0 0x03
103
// #define LicenseProtocolVersionMask 0x0F
104
0
#define EXTENDED_ERROR_MSG_SUPPORTED 0x80
105
106
/** @brief binary Blob Types */
107
enum
108
{
109
  BB_ANY_BLOB = 0x0000,
110
  BB_DATA_BLOB = 0x0001,
111
  BB_RANDOM_BLOB = 0x0002,
112
  BB_CERTIFICATE_BLOB = 0x0003,
113
  BB_ERROR_BLOB = 0x0004,
114
  BB_ENCRYPTED_DATA_BLOB = 0x0009,
115
  BB_KEY_EXCHG_ALG_BLOB = 0x000D,
116
  BB_SCOPE_BLOB = 0x000E,
117
  BB_CLIENT_USER_NAME_BLOB = 0x000F,
118
  BB_CLIENT_MACHINE_NAME_BLOB = 0x0010
119
};
120
121
/* License Key Exchange Algorithms */
122
123
24.7k
#define KEY_EXCHANGE_ALG_RSA 0x00000001
124
125
/** @brief license Error Codes
126
 */
127
enum
128
{
129
  ERR_INVALID_SERVER_CERTIFICATE = 0x00000001,
130
  ERR_NO_LICENSE = 0x00000002,
131
  ERR_INVALID_MAC = 0x00000003,
132
  ERR_INVALID_SCOPE = 0x00000004,
133
  ERR_NO_LICENSE_SERVER = 0x00000006,
134
  STATUS_VALID_CLIENT = 0x00000007,
135
  ERR_INVALID_CLIENT = 0x00000008,
136
  ERR_INVALID_PRODUCT_ID = 0x0000000B,
137
  ERR_INVALID_MESSAGE_LENGTH = 0x0000000C
138
};
139
140
/** @brief state Transition Codes
141
 */
142
enum
143
{
144
  ST_TOTAL_ABORT = 0x00000001,
145
  ST_NO_TRANSITION = 0x00000002,
146
  ST_RESET_PHASE_TO_START = 0x00000003,
147
  ST_RESEND_LAST_MESSAGE = 0x00000004
148
};
149
150
/** @brief Platform Challenge Types
151
 */
152
enum
153
{
154
  WIN32_PLATFORM_CHALLENGE_TYPE = 0x0100,
155
  WIN16_PLATFORM_CHALLENGE_TYPE = 0x0200,
156
  WINCE_PLATFORM_CHALLENGE_TYPE = 0x0300,
157
  OTHER_PLATFORM_CHALLENGE_TYPE = 0xFF00
158
};
159
160
/** @brief License Detail Levels
161
 */
162
enum
163
{
164
  LICENSE_DETAIL_SIMPLE = 0x0001,
165
  LICENSE_DETAIL_MODERATE = 0x0002,
166
  LICENSE_DETAIL_DETAIL = 0x0003
167
};
168
169
/*
170
 * PlatformId:
171
 *
172
 * The most significant byte of the PlatformId field contains the operating system version of the
173
 * client. The second most significant byte of the PlatformId field identifies the ISV that provided
174
 * the client image. The remaining two bytes in the PlatformId field are used by the ISV to identify
175
 * the build number of the operating system.
176
 *
177
 * 0x04010000:
178
 *
179
 * CLIENT_OS_ID_WINNT_POST_52 (0x04000000)
180
 * CLIENT_IMAGE_ID_MICROSOFT  (0x00010000)
181
 */
182
enum
183
{
184
  CLIENT_OS_ID_WINNT_351 = 0x01000000,
185
  CLIENT_OS_ID_WINNT_40 = 0x02000000,
186
  CLIENT_OS_ID_WINNT_50 = 0x03000000,
187
  CLIENT_OS_ID_WINNT_POST_52 = 0x04000000,
188
189
  CLIENT_IMAGE_ID_MICROSOFT = 0x00010000,
190
  CLIENT_IMAGE_ID_CITRIX = 0x00020000,
191
};
192
193
struct rdp_license
194
{
195
  LICENSE_STATE state;
196
  LICENSE_TYPE type;
197
  rdpRdp* rdp;
198
  rdpCertificate* certificate;
199
  BYTE HardwareId[HWID_LENGTH];
200
  BYTE ClientRandom[CLIENT_RANDOM_LENGTH];
201
  BYTE ServerRandom[SERVER_RANDOM_LENGTH];
202
  BYTE MasterSecret[MASTER_SECRET_LENGTH];
203
  BYTE PremasterSecret[PREMASTER_SECRET_LENGTH];
204
  BYTE SessionKeyBlob[SESSION_KEY_BLOB_LENGTH];
205
  BYTE MacSaltKey[MAC_SALT_KEY_LENGTH];
206
  BYTE LicensingEncryptionKey[LICENSING_ENCRYPTION_KEY_LENGTH];
207
  LICENSE_PRODUCT_INFO* ProductInfo;
208
  LICENSE_BLOB* ErrorInfo;
209
  LICENSE_BLOB* LicenseInfo; /* Client -> Server */
210
  LICENSE_BLOB* KeyExchangeList;
211
  LICENSE_BLOB* ServerCertificate;
212
  LICENSE_BLOB* ClientUserName;
213
  LICENSE_BLOB* ClientMachineName;
214
  LICENSE_BLOB* PlatformChallenge;
215
  LICENSE_BLOB* PlatformChallengeResponse;
216
  LICENSE_BLOB* EncryptedPremasterSecret;
217
  LICENSE_BLOB* EncryptedPlatformChallenge;
218
  LICENSE_BLOB* EncryptedPlatformChallengeResponse;
219
  LICENSE_BLOB* EncryptedHardwareId;
220
  LICENSE_BLOB* EncryptedLicenseInfo;
221
  BYTE MACData[LICENSING_ENCRYPTION_KEY_LENGTH];
222
  SCOPE_LIST* ScopeList;
223
  UINT32 PacketHeaderLength;
224
  UINT32 PreferredKeyExchangeAlg;
225
  UINT32 PlatformId;
226
  UINT16 ClientType;
227
  UINT16 LicenseDetailLevel;
228
  BOOL update;
229
  wLog* log;
230
};
231
232
WINPR_ATTR_NODISCARD
233
static BOOL license_send_error_alert(rdpLicense* license, UINT32 dwErrorCode,
234
                                     UINT32 dwStateTransition, const LICENSE_BLOB* info);
235
236
static void license_set_state(rdpLicense* license, LICENSE_STATE state);
237
238
WINPR_ATTR_NODISCARD
239
static const char* license_get_state_string(LICENSE_STATE state);
240
241
WINPR_ATTR_NODISCARD
242
static const char* license_preferred_key_exchange_alg_string(UINT32 alg, char* buffer, size_t size)
243
0
{
244
0
  const char* name = nullptr;
245
246
0
  switch (alg)
247
0
  {
248
0
    case KEY_EXCHANGE_ALG_RSA:
249
0
      name = "KEY_EXCHANGE_ALG_RSA";
250
0
      break;
251
0
    default:
252
0
      name = "KEY_EXCHANGE_ALG_UNKNOWN";
253
0
      break;
254
0
  }
255
256
0
  (void)_snprintf(buffer, size, "%s [0x%08" PRIx32 "]", name, alg);
257
0
  return buffer;
258
0
}
259
260
WINPR_ATTR_NODISCARD
261
static const char* license_request_type_string(UINT32 type)
262
0
{
263
0
  switch (type)
264
0
  {
265
0
    case LICENSE_REQUEST:
266
0
      return "LICENSE_REQUEST";
267
0
    case PLATFORM_CHALLENGE:
268
0
      return "PLATFORM_CHALLENGE";
269
0
    case NEW_LICENSE:
270
0
      return "NEW_LICENSE";
271
0
    case UPGRADE_LICENSE:
272
0
      return "UPGRADE_LICENSE";
273
0
    case LICENSE_INFO:
274
0
      return "LICENSE_INFO";
275
0
    case NEW_LICENSE_REQUEST:
276
0
      return "NEW_LICENSE_REQUEST";
277
0
    case PLATFORM_CHALLENGE_RESPONSE:
278
0
      return "PLATFORM_CHALLENGE_RESPONSE";
279
0
    case ERROR_ALERT:
280
0
      return "ERROR_ALERT";
281
0
    default:
282
0
      return "LICENSE_REQUEST_TYPE_UNKNOWN";
283
0
  }
284
0
}
285
286
WINPR_ATTR_NODISCARD
287
static const char* license_blob_type_string(UINT16 type)
288
0
{
289
0
  switch (type)
290
0
  {
291
0
    case BB_ANY_BLOB:
292
0
      return "BB_ANY_BLOB";
293
0
    case BB_DATA_BLOB:
294
0
      return "BB_DATA_BLOB";
295
0
    case BB_RANDOM_BLOB:
296
0
      return "BB_RANDOM_BLOB";
297
0
    case BB_CERTIFICATE_BLOB:
298
0
      return "BB_CERTIFICATE_BLOB";
299
0
    case BB_ERROR_BLOB:
300
0
      return "BB_ERROR_BLOB";
301
0
    case BB_ENCRYPTED_DATA_BLOB:
302
0
      return "BB_ENCRYPTED_DATA_BLOB";
303
0
    case BB_KEY_EXCHG_ALG_BLOB:
304
0
      return "BB_KEY_EXCHG_ALG_BLOB";
305
0
    case BB_SCOPE_BLOB:
306
0
      return "BB_SCOPE_BLOB";
307
0
    case BB_CLIENT_USER_NAME_BLOB:
308
0
      return "BB_CLIENT_USER_NAME_BLOB";
309
0
    case BB_CLIENT_MACHINE_NAME_BLOB:
310
0
      return "BB_CLIENT_MACHINE_NAME_BLOB";
311
0
    default:
312
0
      return "BB_UNKNOWN";
313
0
  }
314
0
}
315
316
WINPR_ATTR_NODISCARD
317
static wStream* license_send_stream_init(rdpLicense* license, UINT16* sec_flags);
318
319
WINPR_ATTR_NODISCARD
320
static BOOL license_generate_randoms(rdpLicense* license);
321
322
WINPR_ATTR_NODISCARD
323
static BOOL license_generate_keys(rdpLicense* license);
324
325
WINPR_ATTR_NODISCARD
326
static BOOL license_generate_hwid(rdpLicense* license);
327
328
WINPR_ATTR_NODISCARD
329
static BOOL license_encrypt_premaster_secret(rdpLicense* license);
330
331
static void license_free_product_info(LICENSE_PRODUCT_INFO* productInfo);
332
333
WINPR_ATTR_MALLOC(license_free_product_info, 1)
334
static LICENSE_PRODUCT_INFO* license_new_product_info(void);
335
336
WINPR_ATTR_NODISCARD
337
static BOOL license_read_product_info(wLog* log, wStream* s, LICENSE_PRODUCT_INFO* productInfo);
338
339
static void license_free_binary_blob(LICENSE_BLOB* blob);
340
341
WINPR_ATTR_MALLOC(license_free_binary_blob, 1)
342
static LICENSE_BLOB* license_new_binary_blob(UINT16 type);
343
344
WINPR_ATTR_NODISCARD
345
static BOOL license_read_binary_blob_data(wLog* log, LICENSE_BLOB* blob, UINT16 type,
346
                                          const void* data, size_t length);
347
348
WINPR_ATTR_NODISCARD
349
static BOOL license_read_binary_blob(wLog* log, wStream* s, LICENSE_BLOB* blob);
350
351
WINPR_ATTR_NODISCARD
352
static BOOL license_write_binary_blob(wStream* s, const LICENSE_BLOB* blob);
353
354
static void license_free_scope_list(SCOPE_LIST* scopeList);
355
356
WINPR_ATTR_MALLOC(license_free_scope_list, 1)
357
static SCOPE_LIST* license_new_scope_list(void);
358
359
WINPR_ATTR_NODISCARD
360
static BOOL license_scope_list_resize(SCOPE_LIST* scopeList, UINT32 count);
361
362
WINPR_ATTR_NODISCARD
363
static BOOL license_read_scope_list(wLog* log, wStream* s, SCOPE_LIST* scopeList);
364
365
WINPR_ATTR_NODISCARD
366
static BOOL license_write_scope_list(wLog* log, wStream* s, const SCOPE_LIST* scopeList);
367
368
WINPR_ATTR_NODISCARD
369
static BOOL license_read_license_request_packet(rdpLicense* license, wStream* s);
370
371
WINPR_ATTR_NODISCARD
372
static BOOL license_write_license_request_packet(const rdpLicense* license, wStream* s);
373
374
WINPR_ATTR_NODISCARD
375
static BOOL license_read_platform_challenge_packet(rdpLicense* license, wStream* s);
376
377
WINPR_ATTR_NODISCARD
378
static BOOL license_send_platform_challenge_packet(rdpLicense* license);
379
380
WINPR_ATTR_NODISCARD
381
static BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s);
382
383
WINPR_ATTR_NODISCARD
384
static BOOL license_read_error_alert_packet(rdpLicense* license, wStream* s);
385
386
WINPR_ATTR_NODISCARD
387
static BOOL license_write_new_license_request_packet(const rdpLicense* license, wStream* s);
388
389
WINPR_ATTR_NODISCARD
390
static BOOL license_read_new_license_request_packet(rdpLicense* license, wStream* s);
391
392
WINPR_ATTR_NODISCARD
393
static BOOL license_answer_license_request(rdpLicense* license);
394
395
WINPR_ATTR_NODISCARD
396
static BOOL license_send_platform_challenge_response(rdpLicense* license);
397
398
WINPR_ATTR_NODISCARD
399
static BOOL license_read_platform_challenge_response(rdpLicense* license);
400
401
WINPR_ATTR_NODISCARD
402
static BOOL license_read_client_platform_challenge_response(rdpLicense* license, wStream* s);
403
404
WINPR_ATTR_NODISCARD
405
static BOOL license_write_client_platform_challenge_response(rdpLicense* license, wStream* s);
406
407
WINPR_ATTR_NODISCARD
408
static BOOL license_write_server_upgrade_license(const rdpLicense* license, wStream* s);
409
410
WINPR_ATTR_NODISCARD
411
static BOOL license_send_license_info(rdpLicense* license, const LICENSE_BLOB* calBlob,
412
                                      const BYTE* signature, size_t signature_length);
413
414
WINPR_ATTR_NODISCARD
415
static BOOL license_read_license_info(rdpLicense* license, wStream* s);
416
417
WINPR_ATTR_NODISCARD
418
static state_run_t license_client_recv(rdpLicense* license, wStream* s);
419
420
WINPR_ATTR_NODISCARD
421
static state_run_t license_server_recv(rdpLicense* license, wStream* s);
422
423
24.7k
#define PLATFORMID (CLIENT_OS_ID_WINNT_POST_52 | CLIENT_IMAGE_ID_MICROSOFT)
424
425
#ifdef WITH_DEBUG_LICENSE
426
427
WINPR_ATTR_NODISCARD
428
static const char* error_codes(UINT32 idx)
429
{
430
#define EVCASE(x) \
431
  case x:       \
432
    return #x
433
  switch (idx)
434
  {
435
    EVCASE(ERR_INVALID_SERVER_CERTIFICATE);
436
    EVCASE(ERR_NO_LICENSE);
437
    EVCASE(ERR_INVALID_MAC);
438
    EVCASE(ERR_INVALID_SCOPE);
439
    EVCASE(ERR_NO_LICENSE_SERVER);
440
    EVCASE(STATUS_VALID_CLIENT);
441
    EVCASE(ERR_INVALID_CLIENT);
442
    EVCASE(ERR_INVALID_PRODUCT_ID);
443
    EVCASE(ERR_INVALID_MESSAGE_LENGTH);
444
    default:
445
      return "ERR_UNKNOWN";
446
  }
447
}
448
449
WINPR_ATTR_NODISCARD
450
static const char* state_transitions(UINT32 idx)
451
{
452
#define EVCASE(x) \
453
  case x:       \
454
    return #x
455
456
  switch (idx)
457
  {
458
    EVCASE(ST_TOTAL_ABORT);
459
    EVCASE(ST_NO_TRANSITION);
460
    EVCASE(ST_RESET_PHASE_TO_START);
461
    EVCASE(ST_RESEND_LAST_MESSAGE);
462
    default:
463
      return "ST_UNKNOWN";
464
  }
465
}
466
467
static void license_print_product_info(wLog* log, const LICENSE_PRODUCT_INFO* productInfo)
468
{
469
  char* CompanyName = nullptr;
470
  char* ProductId = nullptr;
471
472
  WINPR_ASSERT(productInfo);
473
  WINPR_ASSERT(productInfo->pbCompanyName);
474
  WINPR_ASSERT(productInfo->pbProductId);
475
476
  CompanyName =
477
      ConvertWCharNToUtf8Alloc(WINPR_PACKED_ALIGN_CAST(const WCHAR*, productInfo->pbCompanyName),
478
                               productInfo->cbCompanyName / sizeof(WCHAR), nullptr);
479
  ProductId =
480
      ConvertWCharNToUtf8Alloc(WINPR_PACKED_ALIGN_CAST(const WCHAR*, productInfo->pbProductId),
481
                               productInfo->cbProductId / sizeof(WCHAR), nullptr);
482
  WLog_Print(log, WLOG_INFO, "ProductInfo:");
483
  WLog_Print(log, WLOG_INFO, "\tdwVersion: 0x%08" PRIX32 "", productInfo->dwVersion);
484
  WLog_Print(log, WLOG_INFO, "\tCompanyName: %s", CompanyName);
485
  WLog_Print(log, WLOG_INFO, "\tProductId: %s", ProductId);
486
  free(CompanyName);
487
  free(ProductId);
488
}
489
490
static void license_print_scope_list(wLog* log, const SCOPE_LIST* scopeList)
491
{
492
  WINPR_ASSERT(scopeList);
493
494
  WLog_Print(log, WLOG_INFO, "ScopeList (%" PRIu32 "):", scopeList->count);
495
496
  for (UINT32 index = 0; index < scopeList->count; index++)
497
  {
498
    WINPR_ASSERT(scopeList->array);
499
    const LICENSE_BLOB* scope = scopeList->array[index];
500
    WINPR_ASSERT(scope);
501
502
    WLog_Print(log, WLOG_INFO, "\t%.*s", (int)scope->length, (const char*)scope->data);
503
  }
504
}
505
#endif
506
507
static const char licenseStore[] = "licenses";
508
509
WINPR_ATTR_NODISCARD
510
static BOOL license_ensure_state(rdpLicense* license, LICENSE_STATE state, UINT32 msg)
511
0
{
512
0
  const LICENSE_STATE cstate = license_get_state(license);
513
514
0
  WINPR_ASSERT(license);
515
516
0
  if (cstate != state)
517
0
  {
518
0
    const char* scstate = license_get_state_string(cstate);
519
0
    const char* sstate = license_get_state_string(state);
520
0
    const char* where = license_request_type_string(msg);
521
522
0
    WLog_Print(license->log, WLOG_WARN,
523
0
               "Received [%s], but found invalid licensing state %s, expected %s", where,
524
0
               scstate, sstate);
525
0
    return FALSE;
526
0
  }
527
0
  return TRUE;
528
0
}
529
530
state_run_t license_recv(rdpLicense* license, wStream* s)
531
0
{
532
0
  WINPR_ASSERT(license);
533
0
  WINPR_ASSERT(license->rdp);
534
0
  WINPR_ASSERT(license->rdp->settings);
535
536
0
  if (freerdp_settings_get_bool(license->rdp->settings, FreeRDP_ServerMode))
537
0
    return license_server_recv(license, s);
538
0
  else
539
0
    return license_client_recv(license, s);
540
0
}
541
542
WINPR_ATTR_NODISCARD
543
static BOOL license_check_stream_length(wLog* log, wStream* s, UINT64 expect, const char* where,
544
                                        UINT64 limit)
545
0
{
546
0
  const size_t remain = Stream_GetRemainingLength(s);
547
548
0
  WINPR_ASSERT(where);
549
550
0
  if (remain < expect)
551
0
  {
552
0
    WLog_Print(log, WLOG_WARN, "short %s, expected %" PRIu64 " bytes, got %" PRIuz, where,
553
0
               expect, remain);
554
0
    return FALSE;
555
0
  }
556
0
  if ((limit > 0) && (remain > limit))
557
0
  {
558
0
    WLog_Print(log, WLOG_WARN,
559
0
               "oversized %s, got %" PRIuz " bytes, but size is limited to %" PRIu64 ".", where,
560
0
               remain, limit);
561
0
    return FALSE;
562
0
  }
563
0
  return TRUE;
564
0
}
565
566
WINPR_ATTR_NODISCARD
567
static BOOL license_check_stream_capacity(wLog* log, wStream* s, size_t expect, const char* where)
568
0
{
569
0
  WINPR_ASSERT(where);
570
571
0
  return (Stream_CheckAndLogRequiredCapacityWLogEx(log, WLOG_WARN, s, expect, 1,
572
0
                                                   "%s(%s:%" PRIuz ") %s", __func__, __FILE__,
573
0
                                                   (size_t)__LINE__, where));
574
0
}
575
576
WINPR_ATTR_NODISCARD
577
static BOOL computeCalHash(wLog* log, const char* hostname, char* hashStr, size_t len)
578
0
{
579
0
  WINPR_DIGEST_CTX* sha1 = nullptr;
580
0
  BOOL ret = FALSE;
581
0
  BYTE hash[20] = WINPR_C_ARRAY_INIT;
582
583
0
  WINPR_ASSERT(hostname);
584
0
  WINPR_ASSERT(hashStr);
585
586
0
  if (len < 2 * sizeof(hash) + 1)
587
0
    return FALSE;
588
589
0
  if (!(sha1 = winpr_Digest_New()))
590
0
    goto out;
591
0
  if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
592
0
    goto out;
593
0
  if (!winpr_Digest_Update(sha1, (const BYTE*)hostname, strlen(hostname)))
594
0
    goto out;
595
0
  if (!winpr_Digest_Final(sha1, hash, sizeof(hash)))
596
0
    goto out;
597
598
0
  for (size_t i = 0; i < sizeof(hash); i++, hashStr += 2)
599
0
    (void)sprintf_s(hashStr, 3, "%.2x", hash[i]);
600
601
0
  ret = TRUE;
602
0
out:
603
0
  if (!ret)
604
0
    WLog_Print(log, WLOG_ERROR, "failed to generate SHA1 of hostname '%s'", hostname);
605
0
  winpr_Digest_Free(sha1);
606
0
  return ret;
607
0
}
608
609
WINPR_ATTR_NODISCARD
610
static BOOL saveCal(wLog* log, const rdpSettings* settings, const BYTE* data, size_t length,
611
                    const char* hostname)
612
0
{
613
0
  char hash[41] = WINPR_C_ARRAY_INIT;
614
0
  FILE* fp = nullptr;
615
0
  char* licenseStorePath = nullptr;
616
0
  char filename[MAX_PATH] = WINPR_C_ARRAY_INIT;
617
0
  char filenameNew[MAX_PATH] = WINPR_C_ARRAY_INIT;
618
0
  char* filepath = nullptr;
619
0
  char* filepathNew = nullptr;
620
621
0
  size_t written = 0;
622
0
  BOOL ret = FALSE;
623
0
  const char* path = freerdp_settings_get_string(settings, FreeRDP_ConfigPath);
624
625
0
  WINPR_ASSERT(path);
626
0
  WINPR_ASSERT(data || (length == 0));
627
0
  WINPR_ASSERT(hostname);
628
629
0
  if (!winpr_PathFileExists(path))
630
0
  {
631
0
    if (!winpr_PathMakePath(path, nullptr))
632
0
    {
633
0
      WLog_Print(log, WLOG_ERROR, "error creating directory '%s'", path);
634
0
      goto out;
635
0
    }
636
0
    WLog_Print(log, WLOG_INFO, "creating directory %s", path);
637
0
  }
638
639
0
  if (!(licenseStorePath = GetCombinedPath(path, licenseStore)))
640
0
  {
641
0
    WLog_Print(log, WLOG_ERROR, "Failed to get license store path from '%s' + '%s'", path,
642
0
               licenseStore);
643
0
    goto out;
644
0
  }
645
646
0
  if (!winpr_PathFileExists(licenseStorePath))
647
0
  {
648
0
    if (!winpr_PathMakePath(licenseStorePath, nullptr))
649
0
    {
650
0
      WLog_Print(log, WLOG_ERROR, "error creating directory '%s'", licenseStorePath);
651
0
      goto out;
652
0
    }
653
0
    WLog_Print(log, WLOG_INFO, "creating directory %s", licenseStorePath);
654
0
  }
655
656
0
  if (!computeCalHash(log, hostname, hash, sizeof(hash)))
657
0
    goto out;
658
0
  (void)sprintf_s(filename, sizeof(filename) - 1, "%s.cal", hash);
659
0
  (void)sprintf_s(filenameNew, sizeof(filenameNew) - 1, "%s.cal.new", hash);
660
661
0
  if (!(filepath = GetCombinedPath(licenseStorePath, filename)))
662
0
  {
663
0
    WLog_Print(log, WLOG_ERROR, "Failed to get license file path from '%s' + '%s'", path,
664
0
               filename);
665
0
    goto out;
666
0
  }
667
668
0
  if (!(filepathNew = GetCombinedPath(licenseStorePath, filenameNew)))
669
0
  {
670
0
    WLog_Print(log, WLOG_ERROR, "Failed to get license new file path from '%s' + '%s'", path,
671
0
               filenameNew);
672
0
    goto out;
673
0
  }
674
675
0
  fp = winpr_fopen(filepathNew, "wb");
676
0
  if (!fp)
677
0
  {
678
0
    WLog_Print(log, WLOG_ERROR, "Failed to open license file '%s'", filepathNew);
679
0
    goto out;
680
0
  }
681
682
0
  written = fwrite(data, length, 1, fp);
683
0
  (void)fclose(fp);
684
685
0
  if (written != 1)
686
0
  {
687
0
    WLog_Print(log, WLOG_ERROR, "Failed to write to license file '%s'", filepathNew);
688
0
    winpr_DeleteFile(filepathNew);
689
0
    goto out;
690
0
  }
691
692
0
  ret = winpr_MoveFileEx(filepathNew, filepath, MOVEFILE_REPLACE_EXISTING);
693
0
  if (!ret)
694
0
    WLog_Print(log, WLOG_ERROR, "Failed to move license file '%s' to '%s'", filepathNew,
695
0
               filepath);
696
697
0
out:
698
0
  free(filepathNew);
699
0
  free(filepath);
700
0
  free(licenseStorePath);
701
0
  return ret;
702
0
}
703
704
WINPR_ATTR_MALLOC(free, 1)
705
static BYTE* loadCalFile(wLog* log, const rdpSettings* settings, const char* hostname,
706
                         size_t* dataLen)
707
0
{
708
0
  char* licenseStorePath = nullptr;
709
0
  char calFilename[MAX_PATH] = WINPR_C_ARRAY_INIT;
710
0
  char hash[41] = WINPR_C_ARRAY_INIT;
711
0
  INT64 length = 0;
712
0
  size_t status = 0;
713
0
  FILE* fp = nullptr;
714
0
  BYTE* ret = nullptr;
715
716
0
  WINPR_ASSERT(settings);
717
0
  WINPR_ASSERT(hostname);
718
0
  WINPR_ASSERT(dataLen);
719
720
0
  if (!computeCalHash(log, hostname, hash, sizeof(hash)))
721
0
  {
722
0
    WLog_Print(log, WLOG_ERROR, "%s: unable to compute hostname hash", __func__);
723
0
    return nullptr;
724
0
  }
725
726
0
  (void)sprintf_s(calFilename, sizeof(calFilename) - 1, "%s.cal", hash);
727
728
0
  if (!(licenseStorePath = GetCombinedPath(
729
0
            freerdp_settings_get_string(settings, FreeRDP_ConfigPath), licenseStore)))
730
0
    return nullptr;
731
732
0
  char* calPath = GetCombinedPath(licenseStorePath, calFilename);
733
0
  if (!calPath)
734
0
    goto fail;
735
736
0
  fp = winpr_fopen(calPath, "rb");
737
0
  if (!fp)
738
0
    goto fail;
739
740
0
  if (_fseeki64(fp, 0, SEEK_END) != 0)
741
0
    goto fail;
742
0
  length = _ftelli64(fp);
743
0
  if (_fseeki64(fp, 0, SEEK_SET) != 0)
744
0
    goto fail;
745
0
  if (length < 0)
746
0
    goto fail;
747
748
0
  if ((UINT64)length > LICENSE_MAX_CAL_LENGTH)
749
0
  {
750
0
    WLog_Print(log, WLOG_ERROR,
751
0
               "%s: the file size %" PRId64 " exceeds the CAL size limit of %llu", __func__,
752
0
               length, LICENSE_MAX_CAL_LENGTH);
753
0
    goto fail;
754
0
  }
755
756
0
  ret = (BYTE*)malloc((size_t)length);
757
0
  if (!ret)
758
0
    goto fail;
759
760
0
  status = fread(ret, (size_t)length, 1, fp);
761
0
  if (status == 0)
762
0
    goto fail;
763
764
0
  *dataLen = (size_t)length;
765
766
0
  (void)fclose(fp);
767
0
  free(calPath);
768
0
  free(licenseStorePath);
769
0
  return ret;
770
771
0
fail:
772
0
  free(ret);
773
0
  if (fp)
774
0
    (void)fclose(fp);
775
0
  free(calPath);
776
0
  free(licenseStorePath);
777
0
  return nullptr;
778
0
}
779
780
/**
781
 * Read a licensing preamble.
782
 * msdn{cc240480}
783
 * @param s stream
784
 * @param bMsgType license message type
785
 * @param flags message flags
786
 * @param wMsgSize message size
787
 * @return if the operation completed successfully
788
 */
789
WINPR_ATTR_NODISCARD
790
static BOOL license_read_preamble(wLog* log, wStream* s, BYTE* bMsgType, BYTE* flags,
791
                                  UINT16* wMsgSize)
792
0
{
793
0
  WINPR_ASSERT(bMsgType);
794
0
  WINPR_ASSERT(flags);
795
0
  WINPR_ASSERT(wMsgSize);
796
797
  /* preamble (4 bytes) */
798
0
  if (!license_check_stream_length(log, s, 4, "license preamble", 0))
799
0
    return FALSE;
800
801
0
  Stream_Read_UINT8(s, *bMsgType);  /* bMsgType (1 byte) */
802
0
  Stream_Read_UINT8(s, *flags);     /* flags (1 byte) */
803
0
  Stream_Read_UINT16(s, *wMsgSize); /* wMsgSize (2 bytes) */
804
0
  if (*wMsgSize < 4)
805
0
  {
806
0
    WLog_Print(log, WLOG_WARN,
807
0
               "invalid license preamble::wMsgSize, expected value >= 4, got %" PRIu32,
808
0
               *wMsgSize);
809
0
    return FALSE;
810
0
  }
811
0
  return license_check_stream_length(log, s, *wMsgSize - 4ull, "license preamble::wMsgSize", 0);
812
0
}
813
814
/**
815
 * Write a licensing preamble.
816
 * msdn{cc240480}
817
 * @param s stream
818
 * @param bMsgType license message type
819
 * @param flags message flags
820
 * @param wMsgSize message size
821
 * @return if the operation completed successfully
822
 */
823
WINPR_ATTR_NODISCARD
824
static BOOL license_write_preamble(wStream* s, BYTE bMsgType, BYTE flags, UINT16 wMsgSize)
825
0
{
826
0
  if (!Stream_EnsureRemainingCapacity(s, 4))
827
0
    return FALSE;
828
829
  /* preamble (4 bytes) */
830
0
  Stream_Write_UINT8(s, bMsgType);  /* bMsgType (1 byte) */
831
0
  Stream_Write_UINT8(s, flags);     /* flags (1 byte) */
832
0
  Stream_Write_UINT16(s, wMsgSize); /* wMsgSize (2 bytes) */
833
0
  return TRUE;
834
0
}
835
836
/**
837
 * @brief Initialize a license packet stream.
838
 *
839
 * @param license license module
840
 *
841
 * @return stream or nullptr
842
 */
843
844
wStream* license_send_stream_init(rdpLicense* license, UINT16* sec_flags)
845
0
{
846
0
  WINPR_ASSERT(license);
847
0
  WINPR_ASSERT(license->rdp);
848
0
  WINPR_ASSERT(sec_flags);
849
850
0
  const BOOL do_crypt = license->rdp->do_crypt;
851
852
0
  *sec_flags = SEC_LICENSE_PKT;
853
854
  /*
855
   * Encryption of licensing packets is optional even if the rdp security
856
   * layer is used. If the peer has not indicated that it is capable of
857
   * processing encrypted licensing packets (rdp->do_crypt_license) we turn
858
   * off encryption (via rdp->do_crypt) before initializing the rdp stream
859
   * and re-enable it afterwards.
860
   */
861
862
0
  if (do_crypt)
863
0
  {
864
0
    *sec_flags |= SEC_LICENSE_ENCRYPT_CS;
865
0
    license->rdp->do_crypt = license->rdp->do_crypt_license;
866
0
  }
867
868
0
  wStream* s = rdp_send_stream_init(license->rdp, sec_flags);
869
0
  if (!s)
870
0
    return nullptr;
871
872
0
  license->rdp->do_crypt = do_crypt;
873
0
  license->PacketHeaderLength = (UINT16)Stream_GetPosition(s);
874
0
  if (!Stream_SafeZero(s, LICENSE_PREAMBLE_LENGTH))
875
0
    goto fail;
876
0
  return s;
877
878
0
fail:
879
0
  Stream_Release(s);
880
0
  return nullptr;
881
0
}
882
883
/**
884
 * Send an RDP licensing packet.
885
 * msdn{cc240479}
886
 * @param license license module
887
 * @param s stream
888
 */
889
WINPR_ATTR_NODISCARD
890
static BOOL license_send(rdpLicense* license, wStream* s, BYTE type, UINT16 sec_flags)
891
0
{
892
0
  WINPR_ASSERT(license);
893
0
  WINPR_ASSERT(license->rdp);
894
895
0
  rdpRdp* rdp = license->rdp;
896
0
  WINPR_ASSERT(rdp->settings);
897
898
0
  DEBUG_LICENSE("Sending %s Packet", license_request_type_string(type));
899
0
  const size_t length = Stream_GetPosition(s);
900
0
  WINPR_ASSERT(length >= license->PacketHeaderLength);
901
0
  WINPR_ASSERT(length <= UINT16_MAX + license->PacketHeaderLength);
902
903
0
  const UINT16 wMsgSize = (UINT16)(length - license->PacketHeaderLength);
904
0
  if (!Stream_SetPosition(s, license->PacketHeaderLength))
905
0
    return FALSE;
906
0
  BYTE flags = PREAMBLE_VERSION_3_0;
907
908
  /**
909
   * Using EXTENDED_ERROR_MSG_SUPPORTED here would cause mstsc to crash when
910
   * running in server mode! This flag seems to be incorrectly documented.
911
   */
912
913
0
  if (!rdp->settings->ServerMode)
914
0
    flags |= EXTENDED_ERROR_MSG_SUPPORTED;
915
916
0
  if (!license_write_preamble(s, type, flags, wMsgSize))
917
0
  {
918
0
    Stream_Release(s);
919
0
    return FALSE;
920
0
  }
921
922
#ifdef WITH_DEBUG_LICENSE
923
  WLog_Print(license->log, WLOG_DEBUG, "Sending %s Packet, length %" PRIu16 "",
924
             license_request_type_string(type), wMsgSize);
925
  winpr_HexLogDump(license->log, WLOG_DEBUG, Stream_PointerAs(s, char) - LICENSE_PREAMBLE_LENGTH,
926
                   wMsgSize);
927
#endif
928
0
  if (!Stream_SetPosition(s, length))
929
0
    return FALSE;
930
0
  const BOOL ret = rdp_send(rdp, s, MCS_GLOBAL_CHANNEL_ID, sec_flags);
931
0
  return ret;
932
0
}
933
934
BOOL license_write_server_upgrade_license(const rdpLicense* license, wStream* s)
935
0
{
936
0
  WINPR_ASSERT(license);
937
938
0
  if (!license_write_binary_blob(s, license->EncryptedLicenseInfo))
939
0
    return FALSE;
940
0
  if (!license_check_stream_capacity(license->log, s, sizeof(license->MACData),
941
0
                                     "SERVER_UPGRADE_LICENSE::MACData"))
942
0
    return FALSE;
943
0
  Stream_Write(s, license->MACData, sizeof(license->MACData));
944
0
  return TRUE;
945
0
}
946
947
WINPR_ATTR_NODISCARD
948
static BOOL license_server_send_new_or_upgrade_license(rdpLicense* license, BOOL upgrade)
949
0
{
950
0
  UINT16 sec_flags = 0;
951
0
  wStream* s = license_send_stream_init(license, &sec_flags);
952
0
  const BYTE type = upgrade ? UPGRADE_LICENSE : NEW_LICENSE;
953
954
0
  if (!s)
955
0
    return FALSE;
956
957
0
  if (!license_write_server_upgrade_license(license, s))
958
0
    goto fail;
959
960
0
  return license_send(license, s, type, sec_flags);
961
962
0
fail:
963
0
  Stream_Release(s);
964
0
  return FALSE;
965
0
}
966
967
/**
968
 * Receive an RDP licensing packet.
969
 * msdn{cc240479}
970
 * @param license license module
971
 * @param s stream
972
 * @return if the operation completed successfully
973
 */
974
WINPR_ATTR_NODISCARD
975
static state_run_t license_client_recv_int(rdpLicense* license, wStream* s)
976
0
{
977
0
  BYTE flags = 0;
978
0
  BYTE bMsgType = 0;
979
0
  UINT16 wMsgSize = 0;
980
0
  const size_t length = Stream_GetRemainingLength(s);
981
982
0
  WINPR_ASSERT(license);
983
984
0
  if (!license_read_preamble(license->log, s, &bMsgType, &flags,
985
0
                             &wMsgSize)) /* preamble (4 bytes) */
986
0
    return STATE_RUN_FAILED;
987
988
0
  DEBUG_LICENSE("Receiving %s Packet", license_request_type_string(bMsgType));
989
990
0
  switch (bMsgType)
991
0
  {
992
0
    case LICENSE_REQUEST:
993
      /* Client does not require configuration, so skip this state */
994
0
      if (license_get_state(license) == LICENSE_STATE_INITIAL)
995
0
        license_set_state(license, LICENSE_STATE_CONFIGURED);
996
997
0
      if (!license_ensure_state(license, LICENSE_STATE_CONFIGURED, bMsgType))
998
0
        return STATE_RUN_FAILED;
999
1000
0
      if (!license_read_license_request_packet(license, s))
1001
0
        return STATE_RUN_FAILED;
1002
1003
0
      if (!license_answer_license_request(license))
1004
0
        return STATE_RUN_FAILED;
1005
1006
0
      license_set_state(license, LICENSE_STATE_NEW_REQUEST);
1007
0
      break;
1008
1009
0
    case PLATFORM_CHALLENGE:
1010
0
      if (!license_ensure_state(license, LICENSE_STATE_NEW_REQUEST, bMsgType))
1011
0
        return STATE_RUN_FAILED;
1012
1013
0
      if (!license_read_platform_challenge_packet(license, s))
1014
0
        return STATE_RUN_FAILED;
1015
1016
0
      if (!license_send_platform_challenge_response(license))
1017
0
        return STATE_RUN_FAILED;
1018
0
      license_set_state(license, LICENSE_STATE_PLATFORM_CHALLENGE_RESPONSE);
1019
0
      break;
1020
1021
0
    case NEW_LICENSE:
1022
0
    case UPGRADE_LICENSE:
1023
0
      if (!license_ensure_state(license, LICENSE_STATE_PLATFORM_CHALLENGE_RESPONSE, bMsgType))
1024
0
        return STATE_RUN_FAILED;
1025
0
      if (!license_read_new_or_upgrade_license_packet(license, s))
1026
0
        return STATE_RUN_FAILED;
1027
0
      break;
1028
1029
0
    case ERROR_ALERT:
1030
0
      if (!license_read_error_alert_packet(license, s))
1031
0
        return STATE_RUN_FAILED;
1032
0
      break;
1033
1034
0
    default:
1035
0
      WLog_Print(license->log, WLOG_ERROR, "invalid bMsgType:%" PRIu8 "", bMsgType);
1036
0
      return STATE_RUN_FAILED;
1037
0
  }
1038
1039
0
  if (!tpkt_ensure_stream_consumed(license->log, s, length))
1040
0
    return STATE_RUN_FAILED;
1041
0
  return STATE_RUN_SUCCESS;
1042
0
}
1043
1044
state_run_t license_client_recv(rdpLicense* license, wStream* s)
1045
0
{
1046
0
  state_run_t rc = license_client_recv_int(license, s);
1047
0
  if (state_run_failed(rc))
1048
0
  {
1049
0
    freerdp_set_last_error(license->rdp->context, ERROR_CTX_LICENSE_CLIENT_INVALID);
1050
0
  }
1051
0
  return rc;
1052
0
}
1053
1054
state_run_t license_server_recv(rdpLicense* license, wStream* s)
1055
0
{
1056
0
  state_run_t rc = STATE_RUN_FAILED;
1057
0
  BYTE flags = 0;
1058
0
  BYTE bMsgType = 0;
1059
0
  UINT16 wMsgSize = 0;
1060
0
  const size_t length = Stream_GetRemainingLength(s);
1061
1062
0
  WINPR_ASSERT(license);
1063
1064
0
  if (!license_read_preamble(license->log, s, &bMsgType, &flags,
1065
0
                             &wMsgSize)) /* preamble (4 bytes) */
1066
0
    goto fail;
1067
1068
0
  DEBUG_LICENSE("Receiving %s Packet", license_request_type_string(bMsgType));
1069
1070
0
  switch (bMsgType)
1071
0
  {
1072
0
    case NEW_LICENSE_REQUEST:
1073
0
      if (!license_ensure_state(license, LICENSE_STATE_REQUEST, bMsgType))
1074
0
        goto fail;
1075
0
      if (!license_read_new_license_request_packet(license, s))
1076
0
        goto fail;
1077
      // TODO: Validate if client is allowed
1078
0
      if (!license_send_error_alert(license, ERR_INVALID_MAC, ST_TOTAL_ABORT,
1079
0
                                    license->ErrorInfo))
1080
0
        goto fail;
1081
0
      if (!license_send_platform_challenge_packet(license))
1082
0
        goto fail;
1083
0
      license->update = FALSE;
1084
0
      license_set_state(license, LICENSE_STATE_PLATFORM_CHALLENGE);
1085
0
      break;
1086
0
    case LICENSE_INFO:
1087
0
      if (!license_ensure_state(license, LICENSE_STATE_REQUEST, bMsgType))
1088
0
        goto fail;
1089
0
      if (!license_read_license_info(license, s))
1090
0
        goto fail;
1091
      // TODO: Validate license info
1092
0
      if (!license_send_platform_challenge_packet(license))
1093
0
        goto fail;
1094
0
      license_set_state(license, LICENSE_STATE_PLATFORM_CHALLENGE);
1095
0
      license->update = TRUE;
1096
0
      break;
1097
1098
0
    case PLATFORM_CHALLENGE_RESPONSE:
1099
0
      if (!license_ensure_state(license, LICENSE_STATE_PLATFORM_CHALLENGE, bMsgType))
1100
0
        goto fail;
1101
0
      if (!license_read_client_platform_challenge_response(license, s))
1102
0
        goto fail;
1103
1104
      // TODO: validate challenge response
1105
0
      if (FALSE)
1106
0
      {
1107
0
        if (license_send_error_alert(license, ERR_INVALID_CLIENT, ST_TOTAL_ABORT,
1108
0
                                     license->ErrorInfo))
1109
0
          goto fail;
1110
0
      }
1111
0
      else
1112
0
      {
1113
0
        if (!license_server_send_new_or_upgrade_license(license, license->update))
1114
0
          goto fail;
1115
1116
0
        license->type = LICENSE_TYPE_ISSUED;
1117
0
        license_set_state(license, LICENSE_STATE_COMPLETED);
1118
1119
0
        rc = STATE_RUN_CONTINUE; /* License issued, switch state */
1120
0
      }
1121
0
      break;
1122
1123
0
    case ERROR_ALERT:
1124
0
      if (!license_read_error_alert_packet(license, s))
1125
0
        goto fail;
1126
0
      break;
1127
1128
0
    default:
1129
0
      WLog_Print(license->log, WLOG_ERROR, "invalid bMsgType:%" PRIu8 "", bMsgType);
1130
0
      goto fail;
1131
0
  }
1132
1133
0
  if (!tpkt_ensure_stream_consumed(license->log, s, length))
1134
0
    goto fail;
1135
1136
0
  if (!state_run_success(rc))
1137
0
    rc = STATE_RUN_SUCCESS;
1138
1139
0
fail:
1140
0
  if (state_run_failed(rc))
1141
0
  {
1142
0
    if (flags & EXTENDED_ERROR_MSG_SUPPORTED)
1143
0
    {
1144
0
      if (!license_send_error_alert(license, ERR_INVALID_CLIENT, ST_TOTAL_ABORT, nullptr))
1145
0
      {
1146
0
        WLog_Print(license->log, WLOG_ERROR, "license_send_error_alert failed");
1147
0
      }
1148
0
    }
1149
0
    license_set_state(license, LICENSE_STATE_ABORTED);
1150
0
  }
1151
1152
0
  return rc;
1153
0
}
1154
1155
BOOL license_generate_randoms(rdpLicense* license)
1156
24.7k
{
1157
24.7k
  WINPR_ASSERT(license);
1158
1159
#ifdef LICENSE_NULL_CLIENT_RANDOM
1160
  ZeroMemory(license->ClientRandom, sizeof(license->ClientRandom)); /* ClientRandom */
1161
#else
1162
24.7k
  if (winpr_RAND(license->ClientRandom, sizeof(license->ClientRandom)) < 0) /* ClientRandom */
1163
0
    return FALSE;
1164
24.7k
#endif
1165
1166
24.7k
  if (winpr_RAND(license->ServerRandom, sizeof(license->ServerRandom)) < 0) /* ServerRandom */
1167
0
    return FALSE;
1168
1169
#ifdef LICENSE_NULL_PREMASTER_SECRET
1170
  ZeroMemory(license->PremasterSecret, sizeof(license->PremasterSecret)); /* PremasterSecret */
1171
#else
1172
24.7k
  if (winpr_RAND(license->PremasterSecret, sizeof(license->PremasterSecret)) <
1173
24.7k
      0) /* PremasterSecret */
1174
0
    return FALSE;
1175
24.7k
#endif
1176
24.7k
  return TRUE;
1177
24.7k
}
1178
1179
/**
1180
 * Generate License Cryptographic Keys.
1181
 * @param license license module
1182
 */
1183
WINPR_ATTR_NODISCARD
1184
static BOOL license_generate_keys(rdpLicense* license)
1185
0
{
1186
0
  WINPR_ASSERT(license);
1187
1188
0
  if (
1189
      /* MasterSecret */
1190
0
      !security_master_secret(license->PremasterSecret, sizeof(license->PremasterSecret),
1191
0
                              license->ClientRandom, sizeof(license->ClientRandom),
1192
0
                              license->ServerRandom, sizeof(license->ServerRandom),
1193
0
                              license->MasterSecret, sizeof(license->MasterSecret)) ||
1194
      /* SessionKeyBlob */
1195
0
      !security_session_key_blob(license->MasterSecret, sizeof(license->MasterSecret),
1196
0
                                 license->ClientRandom, sizeof(license->ClientRandom),
1197
0
                                 license->ServerRandom, sizeof(license->ServerRandom),
1198
0
                                 license->SessionKeyBlob, sizeof(license->SessionKeyBlob)))
1199
0
  {
1200
0
    return FALSE;
1201
0
  }
1202
0
  security_mac_salt_key(license->SessionKeyBlob, sizeof(license->SessionKeyBlob),
1203
0
                        license->ClientRandom, sizeof(license->ClientRandom),
1204
0
                        license->ServerRandom, sizeof(license->ServerRandom), license->MacSaltKey,
1205
0
                        sizeof(license->MacSaltKey)); /* MacSaltKey */
1206
0
  const BOOL ret = security_licensing_encryption_key(
1207
0
      license->SessionKeyBlob, sizeof(license->SessionKeyBlob), license->ClientRandom,
1208
0
      sizeof(license->ClientRandom), license->ServerRandom, sizeof(license->ServerRandom),
1209
0
      license->LicensingEncryptionKey,
1210
0
      sizeof(license->LicensingEncryptionKey)); /* LicensingEncryptionKey */
1211
1212
0
  WLog_Print(license->log, WLOG_TRACE, "license keys %s generated", ret ? "successfully" : "NOT");
1213
1214
#ifdef WITH_DEBUG_LICENSE
1215
  WLog_Print(license->log, WLOG_DEBUG, "ClientRandom:");
1216
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->ClientRandom,
1217
                   sizeof(license->ClientRandom));
1218
  WLog_Print(license->log, WLOG_DEBUG, "ServerRandom:");
1219
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->ServerRandom,
1220
                   sizeof(license->ServerRandom));
1221
  WLog_Print(license->log, WLOG_DEBUG, "PremasterSecret:");
1222
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->PremasterSecret,
1223
                   sizeof(license->PremasterSecret));
1224
  WLog_Print(license->log, WLOG_DEBUG, "MasterSecret:");
1225
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->MasterSecret,
1226
                   sizeof(license->MasterSecret));
1227
  WLog_Print(license->log, WLOG_DEBUG, "SessionKeyBlob:");
1228
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->SessionKeyBlob,
1229
                   sizeof(license->SessionKeyBlob));
1230
  WLog_Print(license->log, WLOG_DEBUG, "MacSaltKey:");
1231
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->MacSaltKey, sizeof(license->MacSaltKey));
1232
  WLog_Print(license->log, WLOG_DEBUG, "LicensingEncryptionKey:");
1233
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->LicensingEncryptionKey,
1234
                   sizeof(license->LicensingEncryptionKey));
1235
#endif
1236
0
  return ret;
1237
0
}
1238
1239
/**
1240
 * Generate Unique Hardware Identifier (CLIENT_HARDWARE_ID).
1241
 * @param license license module
1242
 */
1243
1244
BOOL license_generate_hwid(rdpLicense* license)
1245
0
{
1246
0
  const BYTE* hashTarget = nullptr;
1247
0
  size_t targetLen = 0;
1248
0
  BYTE macAddress[6] = WINPR_C_ARRAY_INIT;
1249
1250
0
  WINPR_ASSERT(license);
1251
0
  WINPR_ASSERT(license->rdp);
1252
0
  WINPR_ASSERT(license->rdp->settings);
1253
1254
0
  ZeroMemory(license->HardwareId, sizeof(license->HardwareId));
1255
1256
0
  if (license->rdp->settings->OldLicenseBehaviour)
1257
0
  {
1258
0
    hashTarget = macAddress;
1259
0
    targetLen = sizeof(macAddress);
1260
0
  }
1261
0
  else
1262
0
  {
1263
0
    wStream buffer = WINPR_C_ARRAY_INIT;
1264
0
    const char* hostname = license->rdp->settings->ClientHostname;
1265
0
    wStream* s = Stream_StaticInit(&buffer, license->HardwareId, 4);
1266
0
    Stream_Write_UINT32(s, license->PlatformId);
1267
1268
0
    hashTarget = (const BYTE*)hostname;
1269
0
    targetLen = hostname ? strlen(hostname) : 0;
1270
0
  }
1271
1272
  /* Allow FIPS override for use of MD5 here, really this does not have to be MD5 as we are just
1273
   * taking a MD5 hash of the 6 bytes of 0's(macAddress) */
1274
  /* and filling in the Data1-Data4 fields of the CLIENT_HARDWARE_ID structure(from MS-RDPELE
1275
   * section 2.2.2.3.1). This is for RDP licensing packets */
1276
  /* which will already be encrypted under FIPS, so the use of MD5 here is not for sensitive data
1277
   * protection. */
1278
0
  return winpr_Digest_Allow_FIPS(WINPR_MD_MD5, hashTarget, targetLen,
1279
0
                                 &license->HardwareId[HWID_PLATFORM_ID_LENGTH],
1280
0
                                 WINPR_MD5_DIGEST_LENGTH);
1281
0
}
1282
1283
WINPR_ATTR_NODISCARD
1284
static BOOL license_get_server_rsa_public_key(rdpLicense* license)
1285
0
{
1286
0
  rdpSettings* settings = nullptr;
1287
1288
0
  WINPR_ASSERT(license);
1289
0
  WINPR_ASSERT(license->certificate);
1290
0
  WINPR_ASSERT(license->rdp);
1291
1292
0
  settings = license->rdp->settings;
1293
0
  WINPR_ASSERT(settings);
1294
1295
0
  if (license->ServerCertificate->length < 1)
1296
0
  {
1297
0
    if (!freerdp_certificate_read_server_cert(license->certificate, settings->ServerCertificate,
1298
0
                                              settings->ServerCertificateLength))
1299
0
      return FALSE;
1300
0
  }
1301
1302
0
  return TRUE;
1303
0
}
1304
1305
BOOL license_encrypt_premaster_secret(rdpLicense* license)
1306
0
{
1307
0
  WINPR_ASSERT(license);
1308
0
  WINPR_ASSERT(license->certificate);
1309
1310
0
  if (!license_get_server_rsa_public_key(license))
1311
0
    return FALSE;
1312
1313
0
  WINPR_ASSERT(license->EncryptedPremasterSecret);
1314
1315
0
  const rdpCertInfo* info = freerdp_certificate_get_info(license->certificate);
1316
0
  if (!info)
1317
0
  {
1318
0
    WLog_Print(license->log, WLOG_ERROR, "info=%p, license->certificate=%p", (const void*)info,
1319
0
               (void*)license->certificate);
1320
0
    return FALSE;
1321
0
  }
1322
1323
#ifdef WITH_DEBUG_LICENSE
1324
  WLog_Print(license->log, WLOG_DEBUG, "Modulus (%" PRIu32 " bits):", info->ModulusLength * 8);
1325
  winpr_HexLogDump(license->log, WLOG_DEBUG, info->Modulus, info->ModulusLength);
1326
  WLog_Print(license->log, WLOG_DEBUG, "Exponent:");
1327
  winpr_HexLogDump(license->log, WLOG_DEBUG, info->exponent, sizeof(info->exponent));
1328
#endif
1329
1330
0
  BYTE* EncryptedPremasterSecret = (BYTE*)calloc(1, info->ModulusLength);
1331
0
  if (!EncryptedPremasterSecret)
1332
0
  {
1333
0
    WLog_Print(license->log, WLOG_ERROR,
1334
0
               "EncryptedPremasterSecret=%p, info->ModulusLength=%" PRIu32,
1335
0
               (const void*)EncryptedPremasterSecret, info->ModulusLength);
1336
0
    return FALSE;
1337
0
  }
1338
1339
0
  license->EncryptedPremasterSecret->type = BB_RANDOM_BLOB;
1340
0
  license->EncryptedPremasterSecret->length = sizeof(license->PremasterSecret);
1341
0
#ifndef LICENSE_NULL_PREMASTER_SECRET
1342
0
  {
1343
0
    const SSIZE_T length =
1344
0
        crypto_rsa_public_encrypt(license->PremasterSecret, sizeof(license->PremasterSecret),
1345
0
                                  info, EncryptedPremasterSecret, info->ModulusLength);
1346
0
    if ((length < 0) || (length > UINT16_MAX))
1347
0
    {
1348
0
      WLog_Print(license->log, WLOG_ERROR, "RSA public encrypt length=%" PRIdz " < 0 || > %d",
1349
0
                 length, UINT16_MAX);
1350
0
      return FALSE;
1351
0
    }
1352
0
    license->EncryptedPremasterSecret->length = (UINT16)length;
1353
0
  }
1354
0
#endif
1355
0
  license->EncryptedPremasterSecret->data = EncryptedPremasterSecret;
1356
0
  return TRUE;
1357
0
}
1358
1359
WINPR_ATTR_NODISCARD
1360
static BOOL license_rc4_with_licenseKey(const rdpLicense* license, const BYTE* input, size_t len,
1361
                                        LICENSE_BLOB* target)
1362
0
{
1363
0
  WINPR_ASSERT(license);
1364
0
  WINPR_ASSERT(input || (len == 0));
1365
0
  WINPR_ASSERT(target);
1366
0
  WINPR_ASSERT(len <= UINT16_MAX);
1367
1368
0
  WINPR_RC4_CTX* rc4 = winpr_RC4_New_Allow_FIPS(license->LicensingEncryptionKey,
1369
0
                                                sizeof(license->LicensingEncryptionKey));
1370
0
  if (!rc4)
1371
0
  {
1372
0
    WLog_Print(license->log, WLOG_ERROR, "Failed to allocate RC4");
1373
0
    return FALSE;
1374
0
  }
1375
1376
0
  BYTE* buffer = nullptr;
1377
0
  if (len > 0)
1378
0
    buffer = realloc(target->data, len);
1379
0
  if (!buffer)
1380
0
    goto error_buffer;
1381
1382
0
  target->data = buffer;
1383
0
  target->length = (UINT16)len;
1384
1385
0
  if (!winpr_RC4_Update(rc4, len, input, buffer))
1386
0
    goto error_buffer;
1387
1388
0
  winpr_RC4_Free(rc4);
1389
0
  return TRUE;
1390
1391
0
error_buffer:
1392
0
  WLog_Print(license->log, WLOG_ERROR, "Failed to create/update RC4: len=%" PRIuz ", buffer=%p",
1393
0
             len, (const void*)buffer);
1394
0
  winpr_RC4_Free(rc4);
1395
0
  return FALSE;
1396
0
}
1397
1398
/**
1399
 * Encrypt the input using the license key and MAC the input for a signature
1400
 *
1401
 * @param license rdpLicense to get keys and salt from
1402
 * @param input the input data to encrypt and MAC
1403
 * @param len size of input
1404
 * @param target a target LICENSE_BLOB where the encrypted input will be stored
1405
 * @param mac the signature buffer (16 bytes)
1406
 * @return if the operation completed successfully
1407
 */
1408
1409
WINPR_ATTR_NODISCARD
1410
static BOOL license_encrypt_and_MAC(rdpLicense* license, const BYTE* input, size_t len,
1411
                                    LICENSE_BLOB* target, BYTE* mac, size_t mac_length)
1412
0
{
1413
0
  WINPR_ASSERT(license);
1414
0
  return license_rc4_with_licenseKey(license, input, len, target) &&
1415
0
         security_mac_data(license->MacSaltKey, sizeof(license->MacSaltKey), input, len, mac,
1416
0
                           mac_length);
1417
0
}
1418
1419
/**
1420
 * Decrypt the input using the license key and check the MAC
1421
 *
1422
 * @param license rdpLicense to get keys and salt from
1423
 * @param input the input data to decrypt and MAC
1424
 * @param len size of input
1425
 * @param target a target LICENSE_BLOB where the decrypted input will be stored
1426
 * @param packetMac the signature buffer (16 bytes)
1427
 *
1428
 * @return if the operation completed successfully
1429
 */
1430
WINPR_ATTR_NODISCARD
1431
static BOOL license_decrypt_and_check_MAC(rdpLicense* license, const BYTE* input, size_t len,
1432
                                          LICENSE_BLOB* target, const BYTE* packetMac)
1433
0
{
1434
0
  BYTE macData[sizeof(license->MACData)] = WINPR_C_ARRAY_INIT;
1435
1436
0
  WINPR_ASSERT(license);
1437
0
  WINPR_ASSERT(target);
1438
1439
0
  if (freerdp_settings_get_bool(license->rdp->settings, FreeRDP_TransportDumpReplay))
1440
0
  {
1441
0
    WLog_Print(license->log, WLOG_DEBUG, "TransportDumpReplay active, skipping...");
1442
0
    return TRUE;
1443
0
  }
1444
1445
0
  if (!license_rc4_with_licenseKey(license, input, len, target))
1446
0
    return FALSE;
1447
1448
0
  if (!security_mac_data(license->MacSaltKey, sizeof(license->MacSaltKey), target->data, len,
1449
0
                         macData, sizeof(macData)))
1450
0
    return FALSE;
1451
1452
0
  if (memcmp(packetMac, macData, sizeof(macData)) != 0)
1453
0
  {
1454
0
    WLog_Print(license->log, WLOG_ERROR, "packetMac != expectedMac");
1455
0
    return FALSE;
1456
0
  }
1457
0
  return TRUE;
1458
0
}
1459
1460
/**
1461
 * Read Product Information (PRODUCT_INFO).
1462
 * msdn{cc241915}
1463
 * @param s stream
1464
 * @param productInfo product information
1465
 */
1466
1467
BOOL license_read_product_info(wLog* log, wStream* s, LICENSE_PRODUCT_INFO* productInfo)
1468
0
{
1469
0
  WINPR_ASSERT(productInfo);
1470
1471
0
  if (!license_check_stream_length(log, s, 8, "license product info::cbCompanyName", 0))
1472
0
    return FALSE;
1473
1474
0
  Stream_Read_UINT32(s, productInfo->dwVersion);     /* dwVersion (4 bytes) */
1475
0
  Stream_Read_UINT32(s, productInfo->cbCompanyName); /* cbCompanyName (4 bytes) */
1476
1477
  /* Name must be >0, but there is no upper limit defined, use UINT32_MAX */
1478
0
  if ((productInfo->cbCompanyName < 2) || (productInfo->cbCompanyName % 2 != 0))
1479
0
  {
1480
0
    WLog_Print(log, WLOG_WARN, "license product info invalid cbCompanyName %" PRIu32,
1481
0
               productInfo->cbCompanyName);
1482
0
    return FALSE;
1483
0
  }
1484
1485
0
  if (!license_check_stream_length(log, s, productInfo->cbCompanyName,
1486
0
                                   "license product info::CompanyName",
1487
0
                                   LICENSE_MAX_COMPANY_NAME_LENGTH))
1488
0
    return FALSE;
1489
1490
0
  productInfo->pbProductId = nullptr;
1491
0
  productInfo->pbCompanyName = (BYTE*)malloc(productInfo->cbCompanyName);
1492
0
  if (!productInfo->pbCompanyName)
1493
0
    goto out_fail;
1494
0
  Stream_Read(s, productInfo->pbCompanyName, productInfo->cbCompanyName);
1495
1496
0
  if (!license_check_stream_length(log, s, 4, "license product info::cbProductId", 0))
1497
0
    goto out_fail;
1498
1499
0
  Stream_Read_UINT32(s, productInfo->cbProductId); /* cbProductId (4 bytes) */
1500
1501
0
  if ((productInfo->cbProductId < 2) || (productInfo->cbProductId % 2 != 0))
1502
0
  {
1503
0
    WLog_Print(log, WLOG_WARN, "license product info invalid cbProductId %" PRIu32,
1504
0
               productInfo->cbProductId);
1505
0
    goto out_fail;
1506
0
  }
1507
1508
0
  if (!license_check_stream_length(log, s, productInfo->cbProductId,
1509
0
                                   "license product info::ProductId",
1510
0
                                   LICENSE_MAX_PRODUCT_ID_LENGTH))
1511
0
    goto out_fail;
1512
1513
0
  productInfo->pbProductId = (BYTE*)malloc(productInfo->cbProductId);
1514
0
  if (!productInfo->pbProductId)
1515
0
    goto out_fail;
1516
0
  Stream_Read(s, productInfo->pbProductId, productInfo->cbProductId);
1517
0
  return TRUE;
1518
1519
0
out_fail:
1520
0
  free(productInfo->pbCompanyName);
1521
0
  free(productInfo->pbProductId);
1522
0
  productInfo->pbCompanyName = nullptr;
1523
0
  productInfo->pbProductId = nullptr;
1524
0
  return FALSE;
1525
0
}
1526
1527
WINPR_ATTR_NODISCARD
1528
static BOOL license_write_product_info(wLog* log, wStream* s,
1529
                                       const LICENSE_PRODUCT_INFO* productInfo)
1530
0
{
1531
0
  WINPR_ASSERT(productInfo);
1532
1533
0
  if (!license_check_stream_capacity(log, s, 8, "license product info::cbCompanyName"))
1534
0
    return FALSE;
1535
1536
0
  Stream_Write_UINT32(s, productInfo->dwVersion);     /* dwVersion (4 bytes) */
1537
0
  Stream_Write_UINT32(s, productInfo->cbCompanyName); /* cbCompanyName (4 bytes) */
1538
1539
  /* Name must be >0, but there is no upper limit defined, use UINT32_MAX */
1540
0
  if ((productInfo->cbCompanyName < 2) || (productInfo->cbCompanyName % 2 != 0) ||
1541
0
      !productInfo->pbCompanyName)
1542
0
  {
1543
0
    WLog_Print(log, WLOG_WARN, "license product info invalid cbCompanyName %" PRIu32,
1544
0
               productInfo->cbCompanyName);
1545
0
    return FALSE;
1546
0
  }
1547
1548
0
  if (!license_check_stream_capacity(log, s, productInfo->cbCompanyName,
1549
0
                                     "license product info::CompanyName"))
1550
0
    return FALSE;
1551
1552
0
  Stream_Write(s, productInfo->pbCompanyName, productInfo->cbCompanyName);
1553
1554
0
  if (!license_check_stream_capacity(log, s, 4, "license product info::cbProductId"))
1555
0
    return FALSE;
1556
1557
0
  Stream_Write_UINT32(s, productInfo->cbProductId); /* cbProductId (4 bytes) */
1558
1559
0
  if ((productInfo->cbProductId < 2) || (productInfo->cbProductId % 2 != 0) ||
1560
0
      !productInfo->pbProductId)
1561
0
  {
1562
0
    WLog_Print(log, WLOG_WARN, "license product info invalid cbProductId %" PRIu32,
1563
0
               productInfo->cbProductId);
1564
0
    return FALSE;
1565
0
  }
1566
1567
0
  if (!license_check_stream_capacity(log, s, productInfo->cbProductId,
1568
0
                                     "license product info::ProductId"))
1569
0
    return FALSE;
1570
1571
0
  Stream_Write(s, productInfo->pbProductId, productInfo->cbProductId);
1572
0
  return TRUE;
1573
0
}
1574
1575
/**
1576
 * Allocate New Product Information (LICENSE_PRODUCT_INFO).
1577
 * msdn{cc241915}
1578
 * @return new product information
1579
 */
1580
1581
LICENSE_PRODUCT_INFO* license_new_product_info(void)
1582
24.7k
{
1583
24.7k
  LICENSE_PRODUCT_INFO* productInfo =
1584
24.7k
      (LICENSE_PRODUCT_INFO*)calloc(1, sizeof(LICENSE_PRODUCT_INFO));
1585
24.7k
  if (!productInfo)
1586
0
    return nullptr;
1587
24.7k
  return productInfo;
1588
24.7k
}
1589
1590
/**
1591
 * Free Product Information (LICENSE_PRODUCT_INFO).
1592
 * msdn{cc241915}
1593
 * @param productInfo product information
1594
 */
1595
1596
void license_free_product_info(LICENSE_PRODUCT_INFO* productInfo)
1597
24.7k
{
1598
24.7k
  if (productInfo)
1599
24.7k
  {
1600
24.7k
    free(productInfo->pbCompanyName);
1601
24.7k
    free(productInfo->pbProductId);
1602
24.7k
    free(productInfo);
1603
24.7k
  }
1604
24.7k
}
1605
1606
BOOL license_read_binary_blob_data(wLog* log, LICENSE_BLOB* blob, UINT16 wBlobType,
1607
                                   const void* data, size_t length)
1608
0
{
1609
0
  WINPR_ASSERT(blob);
1610
0
  WINPR_ASSERT(length <= UINT16_MAX);
1611
0
  WINPR_ASSERT(data || (length == 0));
1612
1613
0
  blob->length = (UINT16)length;
1614
0
  free(blob->data);
1615
0
  blob->data = nullptr;
1616
1617
0
  if ((blob->type != wBlobType) && (blob->type != BB_ANY_BLOB))
1618
0
  {
1619
0
    WLog_Print(log, WLOG_ERROR, "license binary blob::type expected %s, got %s",
1620
0
               license_blob_type_string(wBlobType), license_blob_type_string(blob->type));
1621
0
  }
1622
1623
  /*
1624
   * Server can choose to not send data by setting length to 0.
1625
   * If so, it may not bother to set the type, so shortcut the warning
1626
   */
1627
0
  if ((blob->type != BB_ANY_BLOB) && (blob->length == 0))
1628
0
  {
1629
0
    WLog_Print(log, WLOG_DEBUG, "license binary blob::type %s, length=0, skipping.",
1630
0
               license_blob_type_string(blob->type));
1631
0
    return TRUE;
1632
0
  }
1633
1634
0
  blob->type = wBlobType;
1635
0
  blob->data = nullptr;
1636
0
  if (blob->length > 0)
1637
0
    blob->data = malloc(blob->length);
1638
0
  if (!blob->data)
1639
0
  {
1640
0
    WLog_Print(log, WLOG_ERROR, "license binary blob::length=%" PRIu16 ", blob::data=%p",
1641
0
               blob->length, (const void*)blob->data);
1642
0
    return FALSE;
1643
0
  }
1644
0
  memcpy(blob->data, data, blob->length); /* blobData */
1645
0
  return TRUE;
1646
0
}
1647
1648
/**
1649
 * Read License Binary Blob (LICENSE_BINARY_BLOB).
1650
 * msdn{cc240481}
1651
 * @param s stream
1652
 * @param blob license binary blob
1653
 */
1654
1655
BOOL license_read_binary_blob(wLog* log, wStream* s, LICENSE_BLOB* blob)
1656
0
{
1657
0
  UINT16 wBlobType = 0;
1658
0
  UINT16 length = 0;
1659
1660
0
  WINPR_ASSERT(blob);
1661
1662
0
  if (!license_check_stream_length(log, s, 4, "license binary blob::type", 0))
1663
0
    return FALSE;
1664
1665
0
  Stream_Read_UINT16(s, wBlobType); /* wBlobType (2 bytes) */
1666
0
  Stream_Read_UINT16(s, length);    /* wBlobLen (2 bytes) */
1667
1668
0
  if (!license_check_stream_length(log, s, length, "license binary blob::length", 0))
1669
0
    return FALSE;
1670
1671
0
  if (!license_read_binary_blob_data(log, blob, wBlobType, Stream_Pointer(s), length))
1672
0
    return FALSE;
1673
1674
0
  return Stream_SafeSeek(s, length);
1675
0
}
1676
1677
/**
1678
 * Write License Binary Blob (LICENSE_BINARY_BLOB).
1679
 * msdn{cc240481}
1680
 * @param s stream
1681
 * @param blob license binary blob
1682
 */
1683
1684
BOOL license_write_binary_blob(wStream* s, const LICENSE_BLOB* blob)
1685
0
{
1686
0
  WINPR_ASSERT(blob);
1687
1688
0
  if (!Stream_EnsureRemainingCapacity(s, blob->length + 4ull))
1689
0
    return FALSE;
1690
1691
0
  Stream_Write_UINT16(s, blob->type);   /* wBlobType (2 bytes) */
1692
0
  Stream_Write_UINT16(s, blob->length); /* wBlobLen (2 bytes) */
1693
1694
0
  if (blob->length > 0)
1695
0
    Stream_Write(s, blob->data, blob->length); /* blobData */
1696
0
  return TRUE;
1697
0
}
1698
1699
WINPR_ATTR_NODISCARD
1700
static BOOL license_write_encrypted_premaster_secret_blob(wLog* log, wStream* s,
1701
                                                          const LICENSE_BLOB* blob,
1702
                                                          UINT32 ModulusLength)
1703
0
{
1704
0
  const UINT32 length = ModulusLength + 8;
1705
1706
0
  WINPR_ASSERT(blob);
1707
0
  WINPR_ASSERT(length <= UINT16_MAX);
1708
1709
0
  if (blob->length > ModulusLength)
1710
0
  {
1711
0
    WLog_Print(log, WLOG_ERROR, "invalid blob");
1712
0
    return FALSE;
1713
0
  }
1714
1715
0
  if (!Stream_EnsureRemainingCapacity(s, length + 4ull))
1716
0
    return FALSE;
1717
0
  Stream_Write_UINT16(s, blob->type);     /* wBlobType (2 bytes) */
1718
0
  Stream_Write_UINT16(s, (UINT16)length); /* wBlobLen (2 bytes) */
1719
1720
0
  if (blob->length > 0)
1721
0
    Stream_Write(s, blob->data, blob->length); /* blobData */
1722
1723
0
  Stream_Zero(s, length - blob->length);
1724
0
  return TRUE;
1725
0
}
1726
1727
WINPR_ATTR_NODISCARD
1728
static BOOL license_read_encrypted_premaster_secret_blob(wLog* log, wStream* s, LICENSE_BLOB* blob,
1729
                                                         UINT32* ModulusLength)
1730
0
{
1731
0
  if (!license_read_binary_blob(log, s, blob))
1732
0
    return FALSE;
1733
0
  WINPR_ASSERT(ModulusLength);
1734
0
  *ModulusLength = blob->length;
1735
0
  return TRUE;
1736
0
}
1737
1738
/**
1739
 * Allocate New License Binary Blob (LICENSE_BINARY_BLOB).
1740
 * msdn{cc240481}
1741
 * @return new license binary blob
1742
 */
1743
1744
LICENSE_BLOB* license_new_binary_blob(UINT16 type)
1745
321k
{
1746
321k
  LICENSE_BLOB* blob = (LICENSE_BLOB*)calloc(1, sizeof(LICENSE_BLOB));
1747
321k
  if (blob)
1748
321k
    blob->type = type;
1749
321k
  return blob;
1750
321k
}
1751
1752
/**
1753
 * Free License Binary Blob (LICENSE_BINARY_BLOB).
1754
 * msdn{cc240481}
1755
 * @param blob license binary blob
1756
 */
1757
1758
void license_free_binary_blob(LICENSE_BLOB* blob)
1759
321k
{
1760
321k
  if (blob)
1761
321k
  {
1762
321k
    free(blob->data);
1763
321k
    free(blob);
1764
321k
  }
1765
321k
}
1766
1767
/**
1768
 * Read License Scope List (SCOPE_LIST).
1769
 * msdn{cc241916}
1770
 * @param s stream
1771
 * @param scopeList scope list
1772
 */
1773
1774
BOOL license_read_scope_list(wLog* log, wStream* s, SCOPE_LIST* scopeList)
1775
0
{
1776
0
  UINT32 scopeCount = 0;
1777
1778
0
  WINPR_ASSERT(scopeList);
1779
1780
0
  if (!license_check_stream_length(log, s, 4, "license scope list", 0))
1781
0
    return FALSE;
1782
1783
0
  Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */
1784
1785
0
  if (!license_check_stream_length(log, s, 4ull * scopeCount, "license scope list::count",
1786
0
                                   LICENSE_MAX_SCOPE_LENGTH))
1787
0
    return FALSE;
1788
1789
0
  if (!license_scope_list_resize(scopeList, scopeCount))
1790
0
    return FALSE;
1791
  /* ScopeArray */
1792
0
  for (UINT32 i = 0; i < scopeCount; i++)
1793
0
  {
1794
0
    if (!license_read_binary_blob(log, s, scopeList->array[i]))
1795
0
      return FALSE;
1796
0
  }
1797
1798
0
  return TRUE;
1799
0
}
1800
1801
BOOL license_write_scope_list(wLog* log, wStream* s, const SCOPE_LIST* scopeList)
1802
0
{
1803
0
  WINPR_ASSERT(scopeList);
1804
1805
0
  if (!license_check_stream_capacity(log, s, 4, "license scope list"))
1806
0
    return FALSE;
1807
1808
0
  Stream_Write_UINT32(s, scopeList->count); /* ScopeCount (4 bytes) */
1809
1810
0
  if (!license_check_stream_capacity(log, s, scopeList->count * 4ull,
1811
0
                                     "license scope list::count"))
1812
0
    return FALSE;
1813
1814
  /* ScopeArray */
1815
0
  WINPR_ASSERT(scopeList->array || (scopeList->count == 0));
1816
0
  for (UINT32 i = 0; i < scopeList->count; i++)
1817
0
  {
1818
0
    const LICENSE_BLOB* element = scopeList->array[i];
1819
1820
0
    if (!license_write_binary_blob(s, element))
1821
0
      return FALSE;
1822
0
  }
1823
1824
0
  return TRUE;
1825
0
}
1826
1827
/**
1828
 * Allocate New License Scope List (SCOPE_LIST).
1829
 * msdn{cc241916}
1830
 * @return new scope list
1831
 */
1832
1833
SCOPE_LIST* license_new_scope_list(void)
1834
24.7k
{
1835
24.7k
  SCOPE_LIST* list = calloc(1, sizeof(SCOPE_LIST));
1836
24.7k
  return list;
1837
24.7k
}
1838
1839
static void license_scope_list_free(SCOPE_LIST* scopeList, UINT32 count)
1840
24.7k
{
1841
24.7k
  WINPR_ASSERT(scopeList);
1842
24.7k
  WINPR_ASSERT(scopeList->array || (scopeList->count == 0));
1843
1844
24.7k
  for (UINT32 x = count; x < scopeList->count; x++)
1845
0
  {
1846
0
    license_free_binary_blob(scopeList->array[x]);
1847
0
    scopeList->array[x] = nullptr;
1848
0
  }
1849
1850
24.7k
  if (count == 0)
1851
24.7k
  {
1852
24.7k
    free((void*)scopeList->array);
1853
24.7k
    scopeList->array = nullptr;
1854
24.7k
  }
1855
24.7k
}
1856
1857
BOOL license_scope_list_resize(SCOPE_LIST* scopeList, UINT32 count)
1858
0
{
1859
0
  license_scope_list_free(scopeList, count);
1860
0
  if (count > 0)
1861
0
  {
1862
0
    LICENSE_BLOB** tmp =
1863
0
        (LICENSE_BLOB**)realloc((void*)scopeList->array, count * sizeof(LICENSE_BLOB*));
1864
0
    if (!tmp)
1865
0
      return FALSE;
1866
0
    scopeList->array = tmp;
1867
0
  }
1868
1869
0
  for (UINT32 x = scopeList->count; x < count; x++)
1870
0
  {
1871
0
    LICENSE_BLOB* blob = license_new_binary_blob(BB_SCOPE_BLOB);
1872
0
    if (!blob)
1873
0
    {
1874
0
      scopeList->count = x;
1875
0
      return FALSE;
1876
0
    }
1877
0
    scopeList->array[x] = blob;
1878
0
  }
1879
1880
0
  scopeList->count = count;
1881
0
  return TRUE;
1882
0
}
1883
1884
/**
1885
 * Free License Scope List (SCOPE_LIST).
1886
 * msdn{cc241916}
1887
 * @param scopeList scope list
1888
 */
1889
1890
void license_free_scope_list(SCOPE_LIST* scopeList)
1891
24.7k
{
1892
24.7k
  if (!scopeList)
1893
0
    return;
1894
1895
24.7k
  license_scope_list_free(scopeList, 0);
1896
24.7k
  free(scopeList);
1897
24.7k
}
1898
1899
BOOL license_send_license_info(rdpLicense* license, const LICENSE_BLOB* calBlob,
1900
                               const BYTE* signature, size_t signature_length)
1901
0
{
1902
0
  WINPR_ASSERT(calBlob);
1903
0
  WINPR_ASSERT(signature);
1904
0
  WINPR_ASSERT(license->certificate);
1905
1906
0
  const rdpCertInfo* info = freerdp_certificate_get_info(license->certificate);
1907
0
  if (!info)
1908
0
    return FALSE;
1909
1910
0
  UINT16 sec_flags = 0;
1911
0
  wStream* s = license_send_stream_init(license, &sec_flags);
1912
0
  if (!s)
1913
0
    return FALSE;
1914
1915
0
  if (!license_check_stream_capacity(license->log, s, 8 + sizeof(license->ClientRandom),
1916
0
                                     "license info::ClientRandom"))
1917
0
    goto error;
1918
1919
0
  Stream_Write_UINT32(s,
1920
0
                      license->PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
1921
0
  Stream_Write_UINT32(s, license->PlatformId);           /* PlatformId (4 bytes) */
1922
1923
  /* ClientRandom (32 bytes) */
1924
0
  Stream_Write(s, license->ClientRandom, sizeof(license->ClientRandom));
1925
1926
  /* Licensing Binary Blob with EncryptedPreMasterSecret: */
1927
0
  if (!license_write_encrypted_premaster_secret_blob(
1928
0
          license->log, s, license->EncryptedPremasterSecret, info->ModulusLength))
1929
0
    goto error;
1930
1931
  /* Licensing Binary Blob with LicenseInfo: */
1932
0
  if (!license_write_binary_blob(s, calBlob))
1933
0
    goto error;
1934
1935
  /* Licensing Binary Blob with EncryptedHWID */
1936
0
  if (!license_write_binary_blob(s, license->EncryptedHardwareId))
1937
0
    goto error;
1938
1939
  /* MACData */
1940
0
  if (!license_check_stream_capacity(license->log, s, signature_length, "license info::MACData"))
1941
0
    goto error;
1942
0
  Stream_Write(s, signature, signature_length);
1943
1944
0
  return license_send(license, s, LICENSE_INFO, sec_flags);
1945
1946
0
error:
1947
0
  Stream_Release(s);
1948
0
  return FALSE;
1949
0
}
1950
1951
WINPR_ATTR_NODISCARD
1952
static BOOL license_check_preferred_alg(rdpLicense* license, UINT32 PreferredKeyExchangeAlg,
1953
                                        const char* where)
1954
0
{
1955
0
  WINPR_ASSERT(license);
1956
0
  WINPR_ASSERT(where);
1957
1958
0
  if (license->PreferredKeyExchangeAlg != PreferredKeyExchangeAlg)
1959
0
  {
1960
0
    char buffer1[64] = WINPR_C_ARRAY_INIT;
1961
0
    char buffer2[64] = WINPR_C_ARRAY_INIT;
1962
0
    WLog_Print(license->log, WLOG_WARN, "%s::PreferredKeyExchangeAlg, expected %s, got %s",
1963
0
               where,
1964
0
               license_preferred_key_exchange_alg_string(license->PreferredKeyExchangeAlg,
1965
0
                                                         buffer1, sizeof(buffer1)),
1966
0
               license_preferred_key_exchange_alg_string(PreferredKeyExchangeAlg, buffer2,
1967
0
                                                         sizeof(buffer2)));
1968
0
    return FALSE;
1969
0
  }
1970
0
  return TRUE;
1971
0
}
1972
1973
BOOL license_read_license_info(rdpLicense* license, wStream* s)
1974
0
{
1975
0
  BOOL rc = FALSE;
1976
0
  UINT32 PreferredKeyExchangeAlg = 0;
1977
1978
0
  WINPR_ASSERT(license);
1979
0
  WINPR_ASSERT(license->certificate);
1980
1981
0
  const rdpCertInfo* info = freerdp_certificate_get_info(license->certificate);
1982
0
  if (!info)
1983
0
    goto error;
1984
1985
  /* ClientRandom (32 bytes) */
1986
0
  if (!license_check_stream_length(license->log, s, 8 + sizeof(license->ClientRandom),
1987
0
                                   "license info", 0))
1988
0
    goto error;
1989
1990
0
  Stream_Read_UINT32(s, PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
1991
0
  if (!license_check_preferred_alg(license, PreferredKeyExchangeAlg, "license info"))
1992
0
    goto error;
1993
0
  Stream_Read_UINT32(s, license->PlatformId); /* PlatformId (4 bytes) */
1994
1995
  /* ClientRandom (32 bytes) */
1996
0
  Stream_Read(s, license->ClientRandom, sizeof(license->ClientRandom));
1997
1998
  /* Licensing Binary Blob with EncryptedPreMasterSecret: */
1999
0
  {
2000
0
    UINT32 ModulusLength = 0;
2001
0
    if (!license_read_encrypted_premaster_secret_blob(
2002
0
            license->log, s, license->EncryptedPremasterSecret, &ModulusLength))
2003
0
      goto error;
2004
2005
0
    if (ModulusLength != info->ModulusLength)
2006
0
    {
2007
0
      WLog_Print(license->log, WLOG_WARN,
2008
0
                 "EncryptedPremasterSecret,::ModulusLength[%" PRIu32
2009
0
                 "] != rdpCertInfo::ModulusLength[%" PRIu32 "]",
2010
0
                 ModulusLength, info->ModulusLength);
2011
0
      goto error;
2012
0
    }
2013
0
  }
2014
2015
  /* Licensing Binary Blob with LicenseInfo: */
2016
0
  if (!license_read_binary_blob(license->log, s, license->LicenseInfo))
2017
0
    goto error;
2018
2019
  /* Licensing Binary Blob with EncryptedHWID */
2020
0
  if (!license_read_binary_blob(license->log, s, license->EncryptedHardwareId))
2021
0
    goto error;
2022
2023
  /* MACData */
2024
0
  if (!license_check_stream_length(license->log, s, sizeof(license->MACData),
2025
0
                                   "license info::MACData", 0))
2026
0
    goto error;
2027
0
  Stream_Read(s, license->MACData, sizeof(license->MACData));
2028
2029
0
  rc = TRUE;
2030
2031
0
error:
2032
0
  return rc;
2033
0
}
2034
2035
/**
2036
 * Read a LICENSE_REQUEST packet.
2037
 * msdn{cc241914}
2038
 * @param license license module
2039
 * @param s stream
2040
 */
2041
2042
BOOL license_read_license_request_packet(rdpLicense* license, wStream* s)
2043
0
{
2044
0
  WINPR_ASSERT(license);
2045
2046
  /* ServerRandom (32 bytes) */
2047
0
  if (!license_check_stream_length(license->log, s, sizeof(license->ServerRandom),
2048
0
                                   "license request", 0))
2049
0
    return FALSE;
2050
2051
0
  Stream_Read(s, license->ServerRandom, sizeof(license->ServerRandom));
2052
2053
  /* ProductInfo */
2054
0
  if (!license_read_product_info(license->log, s, license->ProductInfo))
2055
0
    return FALSE;
2056
2057
  /* KeyExchangeList */
2058
0
  if (!license_read_binary_blob(license->log, s, license->KeyExchangeList))
2059
0
    return FALSE;
2060
2061
  /* ServerCertificate */
2062
0
  if (!license_read_binary_blob(license->log, s, license->ServerCertificate))
2063
0
    return FALSE;
2064
2065
  /* ScopeList */
2066
0
  if (!license_read_scope_list(license->log, s, license->ScopeList))
2067
0
    return FALSE;
2068
2069
  /* Parse Server Certificate */
2070
0
  if (!freerdp_certificate_read_server_cert(license->certificate,
2071
0
                                            license->ServerCertificate->data,
2072
0
                                            license->ServerCertificate->length))
2073
0
    return FALSE;
2074
2075
0
  if (!license_generate_keys(license) || !license_generate_hwid(license) ||
2076
0
      !license_encrypt_premaster_secret(license))
2077
0
    return FALSE;
2078
2079
#ifdef WITH_DEBUG_LICENSE
2080
  WLog_Print(license->log, WLOG_DEBUG, "ServerRandom:");
2081
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->ServerRandom,
2082
                   sizeof(license->ServerRandom));
2083
  license_print_product_info(license->log, license->ProductInfo);
2084
  license_print_scope_list(license->log, license->ScopeList);
2085
#endif
2086
0
  return TRUE;
2087
0
}
2088
2089
BOOL license_write_license_request_packet(const rdpLicense* license, wStream* s)
2090
0
{
2091
0
  WINPR_ASSERT(license);
2092
2093
  /* ServerRandom (32 bytes) */
2094
0
  if (!license_check_stream_capacity(license->log, s, sizeof(license->ServerRandom),
2095
0
                                     "license request"))
2096
0
    return FALSE;
2097
0
  Stream_Write(s, license->ServerRandom, sizeof(license->ServerRandom));
2098
2099
  /* ProductInfo */
2100
0
  if (!license_write_product_info(license->log, s, license->ProductInfo))
2101
0
    return FALSE;
2102
2103
  /* KeyExchangeList */
2104
0
  if (!license_write_binary_blob(s, license->KeyExchangeList))
2105
0
    return FALSE;
2106
2107
  /* ServerCertificate */
2108
0
  if (!license_write_binary_blob(s, license->ServerCertificate))
2109
0
    return FALSE;
2110
2111
  /* ScopeList */
2112
0
  if (!license_write_scope_list(license->log, s, license->ScopeList))
2113
0
    return FALSE;
2114
2115
0
  return TRUE;
2116
0
}
2117
2118
WINPR_ATTR_NODISCARD
2119
static BOOL license_send_license_request_packet(rdpLicense* license)
2120
0
{
2121
0
  UINT16 sec_flags = 0;
2122
0
  wStream* s = license_send_stream_init(license, &sec_flags);
2123
0
  if (!s)
2124
0
    return FALSE;
2125
2126
0
  if (!license_write_license_request_packet(license, s))
2127
0
    goto fail;
2128
2129
0
  return license_send(license, s, LICENSE_REQUEST, sec_flags);
2130
2131
0
fail:
2132
0
  Stream_Release(s);
2133
0
  return FALSE;
2134
0
}
2135
2136
/*
2137
 * Read a PLATFORM_CHALLENGE packet.
2138
 * msdn{cc241921}
2139
 * @param license license module
2140
 * @param s stream
2141
 */
2142
2143
BOOL license_read_platform_challenge_packet(rdpLicense* license, wStream* s)
2144
0
{
2145
0
  BYTE macData[LICENSING_ENCRYPTION_KEY_LENGTH] = WINPR_C_ARRAY_INIT;
2146
2147
0
  WINPR_ASSERT(license);
2148
2149
0
  DEBUG_LICENSE("Receiving Platform Challenge Packet");
2150
2151
0
  if (!license_check_stream_length(license->log, s, 4, "license platform challenge", 0))
2152
0
    return FALSE;
2153
2154
  /* [MS-RDPELE] 2.2.2.4 Server Platform Challenge (SERVER_PLATFORM_CHALLENGE)
2155
   * reserved field */
2156
0
  Stream_Seek_UINT32(s); /* ConnectFlags, Reserved (4 bytes) */
2157
2158
  /* EncryptedPlatformChallenge */
2159
0
  license->EncryptedPlatformChallenge->type = BB_ANY_BLOB;
2160
0
  if (!license_read_binary_blob(license->log, s, license->EncryptedPlatformChallenge))
2161
0
    return FALSE;
2162
0
  license->EncryptedPlatformChallenge->type = BB_ENCRYPTED_DATA_BLOB;
2163
2164
  /* MACData (16 bytes) */
2165
0
  if (!license_check_stream_length(license->log, s, sizeof(macData),
2166
0
                                   "license platform challenge::MAC", 0))
2167
0
    return FALSE;
2168
2169
0
  Stream_Read(s, macData, sizeof(macData));
2170
0
  if (!license_decrypt_and_check_MAC(license, license->EncryptedPlatformChallenge->data,
2171
0
                                     license->EncryptedPlatformChallenge->length,
2172
0
                                     license->PlatformChallenge, macData))
2173
0
    return FALSE;
2174
2175
0
  WLog_Print(license->log, WLOG_TRACE, "platform challenge read");
2176
2177
#ifdef WITH_DEBUG_LICENSE
2178
  WLog_Print(license->log, WLOG_DEBUG, "EncryptedPlatformChallenge:");
2179
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->EncryptedPlatformChallenge->data,
2180
                   license->EncryptedPlatformChallenge->length);
2181
  WLog_Print(license->log, WLOG_DEBUG, "PlatformChallenge:");
2182
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->PlatformChallenge->data,
2183
                   license->PlatformChallenge->length);
2184
  WLog_Print(license->log, WLOG_DEBUG, "MacData:");
2185
  winpr_HexLogDump(license->log, WLOG_DEBUG, macData, sizeof(macData));
2186
#endif
2187
0
  return TRUE;
2188
0
}
2189
2190
BOOL license_send_error_alert(rdpLicense* license, UINT32 dwErrorCode, UINT32 dwStateTransition,
2191
                              const LICENSE_BLOB* info)
2192
0
{
2193
0
  UINT16 sec_flags = 0;
2194
0
  wStream* s = license_send_stream_init(license, &sec_flags);
2195
2196
0
  if (!s)
2197
0
    goto fail;
2198
2199
0
  if (!license_check_stream_capacity(license->log, s, 8, "license error alert"))
2200
0
    goto fail;
2201
0
  Stream_Write_UINT32(s, dwErrorCode);
2202
0
  Stream_Write_UINT32(s, dwStateTransition);
2203
2204
0
  if (info)
2205
0
  {
2206
0
    if (!license_write_binary_blob(s, info))
2207
0
      goto fail;
2208
0
  }
2209
2210
0
  return license_send(license, s, ERROR_ALERT, sec_flags);
2211
0
fail:
2212
0
  Stream_Release(s);
2213
0
  return FALSE;
2214
0
}
2215
2216
BOOL license_send_platform_challenge_packet(rdpLicense* license)
2217
0
{
2218
0
  UINT16 sec_flags = 0;
2219
0
  wStream* s = license_send_stream_init(license, &sec_flags);
2220
2221
0
  if (!s)
2222
0
    goto fail;
2223
2224
0
  DEBUG_LICENSE("Receiving Platform Challenge Packet");
2225
2226
0
  if (!license_check_stream_capacity(license->log, s, 4, "license platform challenge"))
2227
0
    goto fail;
2228
2229
0
  Stream_Zero(s, 4); /* ConnectFlags, Reserved (4 bytes) */
2230
2231
  /* EncryptedPlatformChallenge */
2232
0
  if (!license_write_binary_blob(s, license->EncryptedPlatformChallenge))
2233
0
    goto fail;
2234
2235
  /* MACData (16 bytes) */
2236
0
  if (!license_check_stream_length(license->log, s, sizeof(license->MACData),
2237
0
                                   "license platform challenge::MAC", 0))
2238
0
    goto fail;
2239
2240
0
  Stream_Write(s, license->MACData, sizeof(license->MACData));
2241
2242
0
  return license_send(license, s, PLATFORM_CHALLENGE, sec_flags);
2243
0
fail:
2244
0
  Stream_Release(s);
2245
0
  return FALSE;
2246
0
}
2247
2248
WINPR_ATTR_NODISCARD
2249
static BOOL license_read_encrypted_blob(const rdpLicense* license, wStream* s, LICENSE_BLOB* target)
2250
0
{
2251
0
  UINT16 wBlobType = 0;
2252
0
  UINT16 wBlobLen = 0;
2253
2254
0
  WINPR_ASSERT(license);
2255
0
  WINPR_ASSERT(target);
2256
2257
0
  if (!license_check_stream_length(license->log, s, 4, "license encrypted blob", 0))
2258
0
    return FALSE;
2259
2260
0
  Stream_Read_UINT16(s, wBlobType);
2261
0
  if (wBlobType != BB_ENCRYPTED_DATA_BLOB)
2262
0
  {
2263
0
    WLog_Print(
2264
0
        license->log, WLOG_WARN,
2265
0
        "expecting BB_ENCRYPTED_DATA_BLOB blob, probably a windows 2003 server, continuing...");
2266
0
  }
2267
2268
0
  Stream_Read_UINT16(s, wBlobLen);
2269
2270
0
  BYTE* encryptedData = Stream_Pointer(s);
2271
0
  if (!Stream_SafeSeek(s, wBlobLen))
2272
0
  {
2273
0
    WLog_Print(license->log, WLOG_WARN,
2274
0
               "short license encrypted blob::length, expected %" PRIu16 " bytes, got %" PRIuz,
2275
0
               wBlobLen, Stream_GetRemainingLength(s));
2276
0
    return FALSE;
2277
0
  }
2278
2279
0
  return license_rc4_with_licenseKey(license, encryptedData, wBlobLen, target);
2280
0
}
2281
2282
/**
2283
 * Read a NEW_LICENSE packet.
2284
 * msdn{cc241926}
2285
 * @param license license module
2286
 * @param s stream
2287
 */
2288
2289
BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)
2290
0
{
2291
0
  UINT32 os_major = 0;
2292
0
  UINT32 os_minor = 0;
2293
0
  UINT32 cbScope = 0;
2294
0
  UINT32 cbCompanyName = 0;
2295
0
  UINT32 cbProductId = 0;
2296
0
  UINT32 cbLicenseInfo = 0;
2297
0
  wStream sbuffer = WINPR_C_ARRAY_INIT;
2298
0
  wStream* licenseStream = nullptr;
2299
0
  BOOL ret = FALSE;
2300
0
  BYTE computedMac[16] = WINPR_C_ARRAY_INIT;
2301
0
  const BYTE* readMac = nullptr;
2302
2303
0
  WINPR_ASSERT(license);
2304
2305
0
  DEBUG_LICENSE("Receiving Server New/Upgrade License Packet");
2306
2307
0
  LICENSE_BLOB* calBlob = license_new_binary_blob(BB_DATA_BLOB);
2308
0
  if (!calBlob)
2309
0
    return FALSE;
2310
2311
  /* EncryptedLicenseInfo */
2312
0
  if (!license_read_encrypted_blob(license, s, calBlob))
2313
0
    goto fail;
2314
2315
  /* compute MAC and check it */
2316
0
  readMac = Stream_Pointer(s);
2317
0
  if (!Stream_SafeSeek(s, sizeof(computedMac)))
2318
0
  {
2319
0
    WLog_Print(license->log, WLOG_WARN,
2320
0
               "short license new/upgrade, expected 16 bytes, got %" PRIuz,
2321
0
               Stream_GetRemainingLength(s));
2322
0
    goto fail;
2323
0
  }
2324
2325
0
  if (!security_mac_data(license->MacSaltKey, sizeof(license->MacSaltKey), calBlob->data,
2326
0
                         calBlob->length, computedMac, sizeof(computedMac)))
2327
0
    goto fail;
2328
2329
0
  if (memcmp(computedMac, readMac, sizeof(computedMac)) != 0)
2330
0
  {
2331
0
    WLog_Print(license->log, WLOG_ERROR, "new or upgrade license MAC mismatch");
2332
0
    goto fail;
2333
0
  }
2334
2335
0
  licenseStream = Stream_StaticConstInit(&sbuffer, calBlob->data, calBlob->length);
2336
0
  if (!licenseStream)
2337
0
  {
2338
0
    WLog_Print(license->log, WLOG_ERROR,
2339
0
               "license::blob::data=%p, license::blob::length=%" PRIu16,
2340
0
               (const void*)calBlob->data, calBlob->length);
2341
0
    goto fail;
2342
0
  }
2343
2344
0
  if (!license_check_stream_length(license->log, licenseStream, 8,
2345
0
                                   "license new/upgrade::blob::version", 0))
2346
0
    goto fail;
2347
2348
0
  Stream_Read_UINT16(licenseStream, os_minor);
2349
0
  Stream_Read_UINT16(licenseStream, os_major);
2350
2351
0
  WLog_Print(license->log, WLOG_DEBUG, "Version: %" PRIu16 ".%" PRIu16, os_major, os_minor);
2352
2353
  /* Scope */
2354
0
  Stream_Read_UINT32(licenseStream, cbScope);
2355
0
  if (!license_check_stream_length(license->log, licenseStream, cbScope,
2356
0
                                   "license new/upgrade::blob::scope", LICENSE_MAX_SCOPE_LENGTH))
2357
0
    goto fail;
2358
2359
#ifdef WITH_DEBUG_LICENSE
2360
  WLog_Print(license->log, WLOG_DEBUG, "Scope:");
2361
  winpr_HexLogDump(license->log, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);
2362
#endif
2363
0
  Stream_Seek(licenseStream, cbScope);
2364
2365
  /* CompanyName */
2366
0
  if (!license_check_stream_length(license->log, licenseStream, 4,
2367
0
                                   "license new/upgrade::blob::cbCompanyName", 0))
2368
0
    goto fail;
2369
2370
0
  Stream_Read_UINT32(licenseStream, cbCompanyName);
2371
0
  if (!license_check_stream_length(license->log, licenseStream, cbCompanyName,
2372
0
                                   "license new/upgrade::blob::CompanyName",
2373
0
                                   LICENSE_MAX_COMPANY_NAME_LENGTH))
2374
0
    goto fail;
2375
2376
#ifdef WITH_DEBUG_LICENSE
2377
  WLog_Print(license->log, WLOG_DEBUG, "Company name:");
2378
  winpr_HexLogDump(license->log, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);
2379
#endif
2380
0
  Stream_Seek(licenseStream, cbCompanyName);
2381
2382
  /* productId */
2383
0
  if (!license_check_stream_length(license->log, licenseStream, 4,
2384
0
                                   "license new/upgrade::blob::cbProductId", 0))
2385
0
    goto fail;
2386
2387
0
  Stream_Read_UINT32(licenseStream, cbProductId);
2388
2389
0
  if (!license_check_stream_length(license->log, licenseStream, cbProductId,
2390
0
                                   "license new/upgrade::blob::ProductId",
2391
0
                                   LICENSE_MAX_PRODUCT_ID_LENGTH))
2392
0
    goto fail;
2393
2394
#ifdef WITH_DEBUG_LICENSE
2395
  WLog_Print(license->log, WLOG_DEBUG, "Product id:");
2396
  winpr_HexLogDump(license->log, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);
2397
#endif
2398
0
  Stream_Seek(licenseStream, cbProductId);
2399
2400
  /* licenseInfo */
2401
0
  if (!license_check_stream_length(license->log, licenseStream, 4,
2402
0
                                   "license new/upgrade::blob::cbLicenseInfo", 0))
2403
0
    goto fail;
2404
2405
0
  Stream_Read_UINT32(licenseStream, cbLicenseInfo);
2406
0
  if (!license_check_stream_length(license->log, licenseStream, cbLicenseInfo,
2407
0
                                   "license new/upgrade::blob::LicenseInfo",
2408
0
                                   LICENSE_MAX_CAL_LENGTH))
2409
0
    goto fail;
2410
2411
0
  license->type = LICENSE_TYPE_ISSUED;
2412
0
  license_set_state(license, LICENSE_STATE_COMPLETED);
2413
0
  ret = TRUE;
2414
2415
0
  if (!license->rdp->settings->OldLicenseBehaviour)
2416
0
    ret = saveCal(license->log, license->rdp->settings, Stream_Pointer(licenseStream),
2417
0
                  cbLicenseInfo, license->rdp->settings->ClientHostname);
2418
2419
0
fail:
2420
0
  license_free_binary_blob(calBlob);
2421
0
  return ret;
2422
0
}
2423
2424
/**
2425
 * Read an ERROR_ALERT packet.
2426
 * msdn{cc240482}
2427
 * @param license license module
2428
 * @param s stream
2429
 */
2430
2431
BOOL license_read_error_alert_packet(rdpLicense* license, wStream* s)
2432
0
{
2433
0
  UINT32 dwErrorCode = 0;
2434
0
  UINT32 dwStateTransition = 0;
2435
2436
0
  WINPR_ASSERT(license);
2437
0
  WINPR_ASSERT(license->rdp);
2438
2439
0
  if (!license_check_stream_length(license->log, s, 8ul, "error alert", 0))
2440
0
    return FALSE;
2441
2442
0
  Stream_Read_UINT32(s, dwErrorCode);       /* dwErrorCode (4 bytes) */
2443
0
  Stream_Read_UINT32(s, dwStateTransition); /* dwStateTransition (4 bytes) */
2444
2445
0
  if (!license_read_binary_blob(license->log, s, license->ErrorInfo)) /* bbErrorInfo */
2446
0
    return FALSE;
2447
2448
#ifdef WITH_DEBUG_LICENSE
2449
  WLog_Print(license->log, WLOG_DEBUG, "dwErrorCode: %s, dwStateTransition: %s",
2450
             error_codes(dwErrorCode), state_transitions(dwStateTransition));
2451
#endif
2452
2453
0
  if (dwErrorCode == STATUS_VALID_CLIENT)
2454
0
  {
2455
0
    license->type = LICENSE_TYPE_NONE;
2456
0
    license_set_state(license, LICENSE_STATE_COMPLETED);
2457
0
    return TRUE;
2458
0
  }
2459
2460
0
  switch (dwStateTransition)
2461
0
  {
2462
0
    case ST_TOTAL_ABORT:
2463
0
      license_set_state(license, LICENSE_STATE_ABORTED);
2464
0
      break;
2465
0
    case ST_NO_TRANSITION:
2466
0
      license_set_state(license, LICENSE_STATE_COMPLETED);
2467
0
      break;
2468
0
    case ST_RESET_PHASE_TO_START:
2469
0
      license_set_state(license, LICENSE_STATE_CONFIGURED);
2470
0
      break;
2471
0
    case ST_RESEND_LAST_MESSAGE:
2472
0
      break;
2473
0
    default:
2474
0
      break;
2475
0
  }
2476
2477
0
  return TRUE;
2478
0
}
2479
2480
/**
2481
 * Write a NEW_LICENSE_REQUEST packet.
2482
 * msdn{cc241918}
2483
 * @param license license module
2484
 * @param s stream
2485
 */
2486
2487
BOOL license_write_new_license_request_packet(const rdpLicense* license, wStream* s)
2488
0
{
2489
0
  WINPR_ASSERT(license);
2490
2491
0
  const rdpCertInfo* info = freerdp_certificate_get_info(license->certificate);
2492
0
  if (!info)
2493
0
    return FALSE;
2494
2495
0
  if (!license_check_stream_capacity(license->log, s, 8 + sizeof(license->ClientRandom),
2496
0
                                     "License Request"))
2497
0
    return FALSE;
2498
2499
0
  Stream_Write_UINT32(s,
2500
0
                      license->PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
2501
0
  Stream_Write_UINT32(s, license->PlatformId);           /* PlatformId (4 bytes) */
2502
0
  Stream_Write(s, license->ClientRandom,
2503
0
               sizeof(license->ClientRandom)); /* ClientRandom (32 bytes) */
2504
2505
0
  if (/* EncryptedPremasterSecret */
2506
0
      !license_write_encrypted_premaster_secret_blob(
2507
0
          license->log, s, license->EncryptedPremasterSecret, info->ModulusLength) ||
2508
      /* ClientUserName */
2509
0
      !license_write_binary_blob(s, license->ClientUserName) ||
2510
      /* ClientMachineName */
2511
0
      !license_write_binary_blob(s, license->ClientMachineName))
2512
0
  {
2513
0
    return FALSE;
2514
0
  }
2515
2516
0
  WLog_Print(license->log, WLOG_TRACE, "new license written");
2517
2518
#ifdef WITH_DEBUG_LICENSE
2519
  WLog_Print(license->log, WLOG_DEBUG, "PreferredKeyExchangeAlg: 0x%08" PRIX32 "",
2520
             license->PreferredKeyExchangeAlg);
2521
  WLog_Print(license->log, WLOG_DEBUG, "ClientRandom:");
2522
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->ClientRandom,
2523
                   sizeof(license->ClientRandom));
2524
  WLog_Print(license->log, WLOG_DEBUG, "EncryptedPremasterSecret");
2525
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->EncryptedPremasterSecret->data,
2526
                   license->EncryptedPremasterSecret->length);
2527
  WLog_Print(license->log, WLOG_DEBUG, "ClientUserName (%" PRIu16 "): %s",
2528
             license->ClientUserName->length, (char*)license->ClientUserName->data);
2529
  WLog_Print(license->log, WLOG_DEBUG, "ClientMachineName (%" PRIu16 "): %s",
2530
             license->ClientMachineName->length, (char*)license->ClientMachineName->data);
2531
#endif
2532
0
  return TRUE;
2533
0
}
2534
2535
BOOL license_read_new_license_request_packet(rdpLicense* license, wStream* s)
2536
0
{
2537
0
  UINT32 PreferredKeyExchangeAlg = 0;
2538
2539
0
  WINPR_ASSERT(license);
2540
2541
0
  if (!license_check_stream_length(license->log, s, 8ull + sizeof(license->ClientRandom),
2542
0
                                   "new license request", 0))
2543
0
    return FALSE;
2544
2545
0
  Stream_Read_UINT32(s, PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
2546
0
  if (!license_check_preferred_alg(license, PreferredKeyExchangeAlg, "new license request"))
2547
0
    return FALSE;
2548
2549
0
  Stream_Read_UINT32(s, license->PlatformId); /* PlatformId (4 bytes) */
2550
0
  Stream_Read(s, license->ClientRandom,
2551
0
              sizeof(license->ClientRandom)); /* ClientRandom (32 bytes) */
2552
2553
  /* EncryptedPremasterSecret */
2554
0
  UINT32 ModulusLength = 0;
2555
0
  if (!license_read_encrypted_premaster_secret_blob(
2556
0
          license->log, s, license->EncryptedPremasterSecret, &ModulusLength))
2557
0
    return FALSE;
2558
2559
0
  const rdpCertInfo* info = freerdp_certificate_get_info(license->certificate);
2560
0
  if (!info)
2561
0
    WLog_Print(license->log, WLOG_WARN,
2562
0
               "Missing license certificate, skipping ModulusLength checks");
2563
0
  else if (ModulusLength != info->ModulusLength)
2564
0
  {
2565
0
    WLog_Print(license->log, WLOG_WARN,
2566
0
               "EncryptedPremasterSecret expected to be %" PRIu32 " bytes, but read %" PRIu32
2567
0
               " bytes",
2568
0
               info->ModulusLength, ModulusLength);
2569
0
    return FALSE;
2570
0
  }
2571
2572
  /* ClientUserName */
2573
0
  if (!license_read_binary_blob(license->log, s, license->ClientUserName))
2574
0
    return FALSE;
2575
  /* ClientMachineName */
2576
0
  if (!license_read_binary_blob(license->log, s, license->ClientMachineName))
2577
0
    return FALSE;
2578
2579
0
  return TRUE;
2580
0
}
2581
2582
/**
2583
 * Send a NEW_LICENSE_REQUEST packet.
2584
 * msdn{cc241918}
2585
 * @param license license module
2586
 */
2587
2588
BOOL license_answer_license_request(rdpLicense* license)
2589
0
{
2590
0
  UINT16 sec_flags = 0;
2591
0
  wStream* s = nullptr;
2592
0
  BYTE* license_data = nullptr;
2593
0
  size_t license_size = 0;
2594
0
  BOOL status = 0;
2595
0
  char* username = nullptr;
2596
2597
0
  WINPR_ASSERT(license);
2598
0
  WINPR_ASSERT(license->rdp);
2599
0
  WINPR_ASSERT(license->rdp->settings);
2600
2601
0
  if (!license->rdp->settings->OldLicenseBehaviour)
2602
0
    license_data = loadCalFile(license->log, license->rdp->settings,
2603
0
                               license->rdp->settings->ClientHostname, &license_size);
2604
2605
0
  if (license_data)
2606
0
  {
2607
0
    LICENSE_BLOB* calBlob = nullptr;
2608
0
    BYTE signature[LICENSING_ENCRYPTION_KEY_LENGTH] = WINPR_C_ARRAY_INIT;
2609
2610
0
    DEBUG_LICENSE("Sending Saved License Packet");
2611
2612
0
    WINPR_ASSERT(license->EncryptedHardwareId);
2613
0
    license->EncryptedHardwareId->type = BB_ENCRYPTED_DATA_BLOB;
2614
0
    if (!license_encrypt_and_MAC(license, license->HardwareId, sizeof(license->HardwareId),
2615
0
                                 license->EncryptedHardwareId, signature, sizeof(signature)))
2616
0
    {
2617
0
      free(license_data);
2618
0
      return FALSE;
2619
0
    }
2620
2621
0
    calBlob = license_new_binary_blob(BB_DATA_BLOB);
2622
0
    if (!calBlob)
2623
0
    {
2624
0
      free(license_data);
2625
0
      return FALSE;
2626
0
    }
2627
0
    calBlob->data = license_data;
2628
0
    WINPR_ASSERT(license_size <= UINT16_MAX);
2629
0
    calBlob->length = (UINT16)license_size;
2630
2631
0
    status = license_send_license_info(license, calBlob, signature, sizeof(signature));
2632
0
    license_free_binary_blob(calBlob);
2633
2634
0
    return status;
2635
0
  }
2636
2637
0
  DEBUG_LICENSE("Sending New License Packet");
2638
2639
0
  s = license_send_stream_init(license, &sec_flags);
2640
0
  if (!s)
2641
0
    return FALSE;
2642
0
  if (license->rdp->settings->Username != nullptr)
2643
0
    username = license->rdp->settings->Username;
2644
0
  else
2645
0
    username = "username";
2646
2647
0
  {
2648
0
    WINPR_ASSERT(license->ClientUserName);
2649
0
    const size_t len = strlen(username) + 1;
2650
0
    WINPR_ASSERT(len <= UINT16_MAX);
2651
2652
0
    license->ClientUserName->data = (BYTE*)username;
2653
0
    license->ClientUserName->length = (UINT16)len;
2654
0
  }
2655
2656
0
  {
2657
0
    WINPR_ASSERT(license->ClientMachineName);
2658
0
    const size_t len = strlen(license->rdp->settings->ClientHostname) + 1;
2659
0
    WINPR_ASSERT(len <= UINT16_MAX);
2660
2661
0
    license->ClientMachineName->data = (BYTE*)license->rdp->settings->ClientHostname;
2662
0
    license->ClientMachineName->length = (UINT16)len;
2663
0
  }
2664
0
  status = license_write_new_license_request_packet(license, s);
2665
2666
0
  WINPR_ASSERT(license->ClientUserName);
2667
0
  license->ClientUserName->data = nullptr;
2668
0
  license->ClientUserName->length = 0;
2669
2670
0
  WINPR_ASSERT(license->ClientMachineName);
2671
0
  license->ClientMachineName->data = nullptr;
2672
0
  license->ClientMachineName->length = 0;
2673
2674
0
  if (!status)
2675
0
  {
2676
0
    Stream_Release(s);
2677
0
    return FALSE;
2678
0
  }
2679
2680
0
  return license_send(license, s, NEW_LICENSE_REQUEST, sec_flags);
2681
0
}
2682
2683
/**
2684
 * Send Client Challenge Response Packet.
2685
 * msdn{cc241922}
2686
 * @param license license module
2687
 */
2688
2689
BOOL license_send_platform_challenge_response(rdpLicense* license)
2690
0
{
2691
0
  wStream* challengeRespData = nullptr;
2692
0
  BYTE* buffer = nullptr;
2693
0
  BOOL status = 0;
2694
2695
0
  WINPR_ASSERT(license);
2696
0
  WINPR_ASSERT(license->PlatformChallenge);
2697
0
  WINPR_ASSERT(license->MacSaltKey);
2698
0
  WINPR_ASSERT(license->EncryptedPlatformChallenge);
2699
0
  WINPR_ASSERT(license->EncryptedHardwareId);
2700
2701
0
  DEBUG_LICENSE("Sending Platform Challenge Response Packet");
2702
2703
0
  license->EncryptedPlatformChallenge->type = BB_DATA_BLOB;
2704
2705
  /* prepare the PLATFORM_CHALLENGE_RESPONSE_DATA */
2706
0
  challengeRespData = Stream_New(nullptr, 8 + license->PlatformChallenge->length);
2707
0
  if (!challengeRespData)
2708
0
    return FALSE;
2709
0
  Stream_Write_UINT16(challengeRespData, PLATFORM_CHALLENGE_RESPONSE_VERSION); /* wVersion */
2710
0
  Stream_Write_UINT16(challengeRespData, license->ClientType);                 /* wClientType */
2711
0
  Stream_Write_UINT16(challengeRespData, license->LicenseDetailLevel); /* wLicenseDetailLevel */
2712
0
  Stream_Write_UINT16(challengeRespData, license->PlatformChallenge->length); /* cbChallenge */
2713
0
  Stream_Write(challengeRespData, license->PlatformChallenge->data,
2714
0
               license->PlatformChallenge->length); /* pbChallenge */
2715
0
  Stream_SealLength(challengeRespData);
2716
2717
  /* compute MAC of PLATFORM_CHALLENGE_RESPONSE_DATA + HWID */
2718
0
  const size_t length = Stream_Length(challengeRespData) + sizeof(license->HardwareId);
2719
0
  buffer = (BYTE*)malloc(length);
2720
0
  if (!buffer)
2721
0
  {
2722
0
    Stream_Free(challengeRespData, TRUE);
2723
0
    return FALSE;
2724
0
  }
2725
2726
0
  CopyMemory(buffer, Stream_Buffer(challengeRespData), Stream_Length(challengeRespData));
2727
0
  CopyMemory(&buffer[Stream_Length(challengeRespData)], license->HardwareId,
2728
0
             sizeof(license->HardwareId));
2729
0
  status = security_mac_data(license->MacSaltKey, sizeof(license->MacSaltKey), buffer, length,
2730
0
                             license->MACData, sizeof(license->MACData));
2731
0
  free(buffer);
2732
2733
0
  if (!status)
2734
0
  {
2735
0
    Stream_Free(challengeRespData, TRUE);
2736
0
    return FALSE;
2737
0
  }
2738
2739
0
  license->EncryptedHardwareId->type = BB_ENCRYPTED_DATA_BLOB;
2740
0
  if (!license_rc4_with_licenseKey(license, license->HardwareId, sizeof(license->HardwareId),
2741
0
                                   license->EncryptedHardwareId))
2742
0
  {
2743
0
    Stream_Free(challengeRespData, TRUE);
2744
0
    return FALSE;
2745
0
  }
2746
2747
0
  status = license_rc4_with_licenseKey(license, Stream_Buffer(challengeRespData),
2748
0
                                       Stream_Length(challengeRespData),
2749
0
                                       license->EncryptedPlatformChallengeResponse);
2750
0
  Stream_Free(challengeRespData, TRUE);
2751
0
  if (!status)
2752
0
    return FALSE;
2753
2754
#ifdef WITH_DEBUG_LICENSE
2755
  WLog_Print(license->log, WLOG_DEBUG, "LicensingEncryptionKey:");
2756
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->LicensingEncryptionKey, 16);
2757
  WLog_Print(license->log, WLOG_DEBUG, "HardwareId:");
2758
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->HardwareId, sizeof(license->HardwareId));
2759
  WLog_Print(license->log, WLOG_DEBUG, "EncryptedHardwareId:");
2760
  winpr_HexLogDump(license->log, WLOG_DEBUG, license->EncryptedHardwareId->data,
2761
                   license->EncryptedHardwareId->length);
2762
#endif
2763
0
  UINT16 sec_flags = 0;
2764
0
  wStream* s = license_send_stream_init(license, &sec_flags);
2765
0
  if (!s)
2766
0
    return FALSE;
2767
2768
0
  if (license_write_client_platform_challenge_response(license, s))
2769
0
    return license_send(license, s, PLATFORM_CHALLENGE_RESPONSE, sec_flags);
2770
2771
0
  Stream_Release(s);
2772
0
  return FALSE;
2773
0
}
2774
2775
BOOL license_read_platform_challenge_response(WINPR_ATTR_UNUSED rdpLicense* license)
2776
0
{
2777
0
  WINPR_ASSERT(license);
2778
0
  WINPR_ASSERT(license->PlatformChallenge);
2779
0
  WINPR_ASSERT(license->MacSaltKey);
2780
0
  WINPR_ASSERT(license->EncryptedPlatformChallenge);
2781
0
  WINPR_ASSERT(license->EncryptedHardwareId);
2782
2783
0
  DEBUG_LICENSE("Receiving Platform Challenge Response Packet");
2784
2785
#if defined(WITH_LICENSE_DECRYPT_CHALLENGE_RESPONSE)
2786
  BOOL rc = FALSE;
2787
  LICENSE_BLOB* dblob = license_new_binary_blob(BB_ANY_BLOB);
2788
  if (!dblob)
2789
    return FALSE;
2790
2791
  wStream sbuffer = WINPR_C_ARRAY_INIT;
2792
  UINT16 wVersion = 0;
2793
  UINT16 cbChallenge = 0;
2794
  const BYTE* pbChallenge = nullptr;
2795
  LICENSE_BLOB* blob = license->EncryptedPlatformChallengeResponse;
2796
2797
  if (!license_rc4_with_licenseKey(license, blob->data, blob->length, dblob))
2798
    goto fail;
2799
2800
  wStream* s = Stream_StaticConstInit(&sbuffer, dblob->data, dblob->length);
2801
  if (!license_check_stream_length(s, 8, "PLATFORM_CHALLENGE_RESPONSE_DATA", 0))
2802
    goto fail;
2803
2804
  Stream_Read_UINT16(s, wVersion);
2805
  if (wVersion != PLATFORM_CHALLENGE_RESPONSE_VERSION)
2806
  {
2807
    WLog_Print(license->log, WLOG_WARN,
2808
               "Invalid PLATFORM_CHALLENGE_RESPONSE_DATA::wVersion 0x%04" PRIx16
2809
               ", expected 0x04" PRIx16,
2810
               wVersion, PLATFORM_CHALLENGE_RESPONSE_VERSION);
2811
    goto fail;
2812
  }
2813
  Stream_Read_UINT16(s, license->ClientType);
2814
  Stream_Read_UINT16(s, license->LicenseDetailLevel);
2815
  Stream_Read_UINT16(s, cbChallenge);
2816
2817
  if (!license_check_stream_length(s, cbChallenge,
2818
                                   "PLATFORM_CHALLENGE_RESPONSE_DATA::pbChallenge", 0))
2819
    goto fail;
2820
2821
  pbChallenge = Stream_Pointer(s);
2822
  if (!license_read_binary_blob_data(license->PlatformChallengeResponse, BB_DATA_BLOB,
2823
                                     pbChallenge, cbChallenge))
2824
    goto fail;
2825
  if (!Stream_SafeSeek(s, cbChallenge))
2826
    goto fail;
2827
2828
  rc = TRUE;
2829
fail:
2830
  license_free_binary_blob(dblob);
2831
  return rc;
2832
#else
2833
0
  return TRUE;
2834
0
#endif
2835
0
}
2836
2837
BOOL license_write_client_platform_challenge_response(rdpLicense* license, wStream* s)
2838
0
{
2839
0
  WINPR_ASSERT(license);
2840
2841
0
  if (!license_write_binary_blob(s, license->EncryptedPlatformChallengeResponse))
2842
0
    return FALSE;
2843
0
  if (!license_write_binary_blob(s, license->EncryptedHardwareId))
2844
0
    return FALSE;
2845
0
  if (!license_check_stream_capacity(license->log, s, sizeof(license->MACData),
2846
0
                                     "CLIENT_PLATFORM_CHALLENGE_RESPONSE::MACData"))
2847
0
    return FALSE;
2848
0
  Stream_Write(s, license->MACData, sizeof(license->MACData));
2849
0
  return TRUE;
2850
0
}
2851
2852
BOOL license_read_client_platform_challenge_response(rdpLicense* license, wStream* s)
2853
0
{
2854
0
  WINPR_ASSERT(license);
2855
2856
0
  if (!license_read_binary_blob(license->log, s, license->EncryptedPlatformChallengeResponse))
2857
0
    return FALSE;
2858
0
  if (!license_read_binary_blob(license->log, s, license->EncryptedHardwareId))
2859
0
    return FALSE;
2860
0
  if (!license_check_stream_length(license->log, s, sizeof(license->MACData),
2861
0
                                   "CLIENT_PLATFORM_CHALLENGE_RESPONSE::MACData", 0))
2862
0
    return FALSE;
2863
0
  Stream_Read(s, license->MACData, sizeof(license->MACData));
2864
0
  return license_read_platform_challenge_response(license);
2865
0
}
2866
2867
/**
2868
 * Send Server License Error - Valid Client Packet.
2869
 * msdn{cc241922}
2870
 *
2871
 * @param rdp A pointer to the context to use
2872
 *
2873
 * @return \b TRUE for success, \b FALSE otherwise
2874
 */
2875
2876
BOOL license_send_valid_client_error_packet(rdpRdp* rdp)
2877
0
{
2878
0
  WINPR_ASSERT(rdp);
2879
0
  rdpLicense* license = rdp->license;
2880
0
  WINPR_ASSERT(license);
2881
2882
0
  license->state = LICENSE_STATE_COMPLETED;
2883
0
  license->type = LICENSE_TYPE_NONE;
2884
0
  return license_send_error_alert(license, STATUS_VALID_CLIENT, ST_NO_TRANSITION,
2885
0
                                  license->ErrorInfo);
2886
0
}
2887
2888
/**
2889
 * Instantiate new license module.
2890
 * @param rdp RDP module
2891
 * @return new license module
2892
 */
2893
2894
rdpLicense* license_new(rdpRdp* rdp)
2895
24.7k
{
2896
24.7k
  WINPR_ASSERT(rdp);
2897
2898
24.7k
  rdpLicense* license = (rdpLicense*)calloc(1, sizeof(rdpLicense));
2899
24.7k
  if (!license)
2900
0
    return nullptr;
2901
24.7k
  license->log = WLog_Get(LICENSE_TAG);
2902
24.7k
  WINPR_ASSERT(license->log);
2903
2904
24.7k
  license->PlatformId = PLATFORMID;
2905
24.7k
  license->ClientType = OTHER_PLATFORM_CHALLENGE_TYPE;
2906
24.7k
  license->LicenseDetailLevel = LICENSE_DETAIL_DETAIL;
2907
24.7k
  license->PreferredKeyExchangeAlg = KEY_EXCHANGE_ALG_RSA;
2908
24.7k
  license->rdp = rdp;
2909
2910
24.7k
  license_set_state(license, LICENSE_STATE_INITIAL);
2911
24.7k
  if (!(license->certificate = freerdp_certificate_new()))
2912
0
    goto out_error;
2913
24.7k
  if (!(license->ProductInfo = license_new_product_info()))
2914
0
    goto out_error;
2915
24.7k
  if (!(license->ErrorInfo = license_new_binary_blob(BB_ERROR_BLOB)))
2916
0
    goto out_error;
2917
24.7k
  if (!(license->LicenseInfo = license_new_binary_blob(BB_DATA_BLOB)))
2918
0
    goto out_error;
2919
24.7k
  if (!(license->KeyExchangeList = license_new_binary_blob(BB_KEY_EXCHG_ALG_BLOB)))
2920
0
    goto out_error;
2921
24.7k
  if (!(license->ServerCertificate = license_new_binary_blob(BB_CERTIFICATE_BLOB)))
2922
0
    goto out_error;
2923
24.7k
  if (!(license->ClientUserName = license_new_binary_blob(BB_CLIENT_USER_NAME_BLOB)))
2924
0
    goto out_error;
2925
24.7k
  if (!(license->ClientMachineName = license_new_binary_blob(BB_CLIENT_MACHINE_NAME_BLOB)))
2926
0
    goto out_error;
2927
24.7k
  if (!(license->PlatformChallenge = license_new_binary_blob(BB_ANY_BLOB)))
2928
0
    goto out_error;
2929
24.7k
  if (!(license->PlatformChallengeResponse = license_new_binary_blob(BB_ANY_BLOB)))
2930
0
    goto out_error;
2931
24.7k
  if (!(license->EncryptedPlatformChallenge = license_new_binary_blob(BB_ANY_BLOB)))
2932
0
    goto out_error;
2933
24.7k
  if (!(license->EncryptedPlatformChallengeResponse =
2934
24.7k
            license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB)))
2935
0
    goto out_error;
2936
24.7k
  if (!(license->EncryptedPremasterSecret = license_new_binary_blob(BB_ANY_BLOB)))
2937
0
    goto out_error;
2938
24.7k
  if (!(license->EncryptedHardwareId = license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB)))
2939
0
    goto out_error;
2940
24.7k
  if (!(license->EncryptedLicenseInfo = license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB)))
2941
0
    goto out_error;
2942
24.7k
  if (!(license->ScopeList = license_new_scope_list()))
2943
0
    goto out_error;
2944
2945
24.7k
  if (!license_generate_randoms(license))
2946
0
    goto out_error;
2947
2948
24.7k
  return license;
2949
2950
0
out_error:
2951
0
  WINPR_PRAGMA_DIAG_PUSH
2952
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2953
0
  license_free(license);
2954
0
  WINPR_PRAGMA_DIAG_POP
2955
0
  return nullptr;
2956
24.7k
}
2957
2958
/**
2959
 * Free license module.
2960
 * @param license license module to be freed
2961
 */
2962
2963
void license_free(rdpLicense* license)
2964
24.7k
{
2965
24.7k
  if (license)
2966
24.7k
  {
2967
24.7k
    freerdp_certificate_free(license->certificate);
2968
24.7k
    license_free_product_info(license->ProductInfo);
2969
24.7k
    license_free_binary_blob(license->ErrorInfo);
2970
24.7k
    license_free_binary_blob(license->LicenseInfo);
2971
24.7k
    license_free_binary_blob(license->KeyExchangeList);
2972
24.7k
    license_free_binary_blob(license->ServerCertificate);
2973
24.7k
    license_free_binary_blob(license->ClientUserName);
2974
24.7k
    license_free_binary_blob(license->ClientMachineName);
2975
24.7k
    license_free_binary_blob(license->PlatformChallenge);
2976
24.7k
    license_free_binary_blob(license->PlatformChallengeResponse);
2977
24.7k
    license_free_binary_blob(license->EncryptedPlatformChallenge);
2978
24.7k
    license_free_binary_blob(license->EncryptedPlatformChallengeResponse);
2979
24.7k
    license_free_binary_blob(license->EncryptedPremasterSecret);
2980
24.7k
    license_free_binary_blob(license->EncryptedHardwareId);
2981
24.7k
    license_free_binary_blob(license->EncryptedLicenseInfo);
2982
24.7k
    license_free_scope_list(license->ScopeList);
2983
24.7k
    free(license);
2984
24.7k
  }
2985
24.7k
}
2986
2987
LICENSE_STATE license_get_state(const rdpLicense* license)
2988
0
{
2989
0
  WINPR_ASSERT(license);
2990
0
  return license->state;
2991
0
}
2992
2993
LICENSE_TYPE license_get_type(const rdpLicense* license)
2994
0
{
2995
0
  WINPR_ASSERT(license);
2996
0
  return license->type;
2997
0
}
2998
2999
void license_set_state(rdpLicense* license, LICENSE_STATE state)
3000
24.7k
{
3001
24.7k
  WINPR_ASSERT(license);
3002
24.7k
  license->state = state;
3003
24.7k
  switch (state)
3004
24.7k
  {
3005
0
    case LICENSE_STATE_COMPLETED:
3006
0
      break;
3007
0
    case LICENSE_STATE_ABORTED:
3008
24.7k
    default:
3009
24.7k
      license->type = LICENSE_TYPE_INVALID;
3010
24.7k
      break;
3011
24.7k
  }
3012
24.7k
}
3013
3014
const char* license_get_state_string(LICENSE_STATE state)
3015
0
{
3016
0
  switch (state)
3017
0
  {
3018
0
    case LICENSE_STATE_INITIAL:
3019
0
      return "LICENSE_STATE_INITIAL";
3020
0
    case LICENSE_STATE_CONFIGURED:
3021
0
      return "LICENSE_STATE_CONFIGURED";
3022
0
    case LICENSE_STATE_REQUEST:
3023
0
      return "LICENSE_STATE_REQUEST";
3024
0
    case LICENSE_STATE_NEW_REQUEST:
3025
0
      return "LICENSE_STATE_NEW_REQUEST";
3026
0
    case LICENSE_STATE_PLATFORM_CHALLENGE:
3027
0
      return "LICENSE_STATE_PLATFORM_CHALLENGE";
3028
0
    case LICENSE_STATE_PLATFORM_CHALLENGE_RESPONSE:
3029
0
      return "LICENSE_STATE_PLATFORM_CHALLENGE_RESPONSE";
3030
0
    case LICENSE_STATE_COMPLETED:
3031
0
      return "LICENSE_STATE_COMPLETED";
3032
0
    case LICENSE_STATE_ABORTED:
3033
0
      return "LICENSE_STATE_ABORTED";
3034
0
    default:
3035
0
      return "LICENSE_STATE_UNKNOWN";
3036
0
  }
3037
0
}
3038
3039
BOOL license_server_send_request(rdpLicense* license)
3040
0
{
3041
0
  if (!license_ensure_state(license, LICENSE_STATE_CONFIGURED, LICENSE_REQUEST))
3042
0
    return FALSE;
3043
0
  if (!license_send_license_request_packet(license))
3044
0
    return FALSE;
3045
0
  license_set_state(license, LICENSE_STATE_REQUEST);
3046
0
  return TRUE;
3047
0
}
3048
3049
WINPR_ATTR_NODISCARD
3050
static BOOL license_set_string(wLog* log, const char* what, const char* value, BYTE** bdst,
3051
                               UINT32* dstLen)
3052
0
{
3053
0
  WINPR_ASSERT(what);
3054
0
  WINPR_ASSERT(value);
3055
0
  WINPR_ASSERT(bdst);
3056
0
  WINPR_ASSERT(dstLen);
3057
3058
0
  union
3059
0
  {
3060
0
    WCHAR** w;
3061
0
    BYTE** b;
3062
0
  } cnv;
3063
0
  cnv.b = bdst;
3064
3065
0
  size_t len = 0;
3066
0
  *cnv.w = ConvertUtf8ToWCharAlloc(value, &len);
3067
0
  if (!*cnv.w || (len > UINT32_MAX / sizeof(WCHAR)))
3068
0
  {
3069
0
    WLog_Print(log, WLOG_ERROR, "license->ProductInfo: %s == %p || %" PRIuz " > UINT32_MAX",
3070
0
               what, (void*)(*cnv.w), len);
3071
0
    return FALSE;
3072
0
  }
3073
0
  *dstLen = (UINT32)(len * sizeof(WCHAR));
3074
0
  return TRUE;
3075
0
}
3076
3077
BOOL license_server_configure(rdpLicense* license)
3078
0
{
3079
0
  wStream* s = nullptr;
3080
0
  UINT32 algs[] = { KEY_EXCHANGE_ALG_RSA };
3081
3082
0
  WINPR_ASSERT(license);
3083
0
  WINPR_ASSERT(license->rdp);
3084
3085
0
  const rdpSettings* settings = license->rdp->settings;
3086
3087
0
  const char* CompanyName =
3088
0
      freerdp_settings_get_string(settings, FreeRDP_ServerLicenseCompanyName);
3089
3090
0
  const char* ProductName =
3091
0
      freerdp_settings_get_string(settings, FreeRDP_ServerLicenseProductName);
3092
0
  const UINT32 ProductVersion =
3093
0
      freerdp_settings_get_uint32(settings, FreeRDP_ServerLicenseProductVersion);
3094
0
  const UINT32 issuerCount =
3095
0
      freerdp_settings_get_uint32(settings, FreeRDP_ServerLicenseProductIssuersCount);
3096
3097
0
  const void* ptr = freerdp_settings_get_pointer(settings, FreeRDP_ServerLicenseProductIssuers);
3098
0
  const char** issuers = WINPR_REINTERPRET_CAST(ptr, const void*, const char**);
3099
3100
0
  WINPR_ASSERT(CompanyName);
3101
0
  WINPR_ASSERT(ProductName);
3102
0
  WINPR_ASSERT(ProductVersion > 0);
3103
0
  WINPR_ASSERT(issuers || (issuerCount == 0));
3104
3105
0
  if (!license_ensure_state(license, LICENSE_STATE_INITIAL, LICENSE_REQUEST))
3106
0
    return FALSE;
3107
3108
0
  license->ProductInfo->dwVersion = ProductVersion;
3109
0
  if (!license_set_string(license->log, "pbCompanyName", CompanyName,
3110
0
                          &license->ProductInfo->pbCompanyName,
3111
0
                          &license->ProductInfo->cbCompanyName))
3112
0
    return FALSE;
3113
3114
0
  if (!license_set_string(license->log, "pbProductId", ProductName,
3115
0
                          &license->ProductInfo->pbProductId, &license->ProductInfo->cbProductId))
3116
0
    return FALSE;
3117
3118
0
  if (!license_read_binary_blob_data(license->log, license->KeyExchangeList,
3119
0
                                     BB_KEY_EXCHG_ALG_BLOB, algs, sizeof(algs)))
3120
0
    return FALSE;
3121
3122
0
  if (!freerdp_certificate_read_server_cert(license->certificate, settings->ServerCertificate,
3123
0
                                            settings->ServerCertificateLength))
3124
0
    return FALSE;
3125
3126
0
  s = Stream_New(nullptr, 1024);
3127
0
  if (!s)
3128
0
    return FALSE;
3129
0
  else
3130
0
  {
3131
0
    BOOL r = FALSE;
3132
0
    SSIZE_T res =
3133
0
        freerdp_certificate_write_server_cert(license->certificate, CERT_CHAIN_VERSION_2, s);
3134
0
    if (res >= 0)
3135
0
      r = license_read_binary_blob_data(license->log, license->ServerCertificate,
3136
0
                                        BB_CERTIFICATE_BLOB, Stream_Buffer(s),
3137
0
                                        Stream_GetPosition(s));
3138
3139
0
    Stream_Free(s, TRUE);
3140
0
    if (!r)
3141
0
      return FALSE;
3142
0
  }
3143
3144
0
  if (!license_scope_list_resize(license->ScopeList, issuerCount))
3145
0
    return FALSE;
3146
0
  for (size_t x = 0; x < issuerCount; x++)
3147
0
  {
3148
0
    LICENSE_BLOB* blob = license->ScopeList->array[x];
3149
0
    const char* name = issuers[x];
3150
0
    const size_t length = strnlen(name, UINT16_MAX) + 1;
3151
0
    if ((length == 0) || (length > UINT16_MAX))
3152
0
    {
3153
0
      WLog_Print(license->log, WLOG_WARN,
3154
0
                 "Invalid issuer at position %" PRIuz ": length 0 < %" PRIuz " <= %d"
3155
0
                 " ['%s']",
3156
0
                 x, length, UINT16_MAX, name);
3157
0
      return FALSE;
3158
0
    }
3159
0
    if (!license_read_binary_blob_data(license->log, blob, BB_SCOPE_BLOB, name, length))
3160
0
      return FALSE;
3161
0
  }
3162
3163
0
  license_set_state(license, LICENSE_STATE_CONFIGURED);
3164
0
  return TRUE;
3165
0
}
3166
3167
rdpLicense* license_get(rdpContext* context)
3168
0
{
3169
0
  WINPR_ASSERT(context);
3170
0
  WINPR_ASSERT(context->rdp);
3171
0
  return context->rdp->license;
3172
0
}