Coverage Report

Created: 2026-10-15 06:31

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