Coverage Report

Created: 2026-09-14 06:32

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