Coverage Report

Created: 2026-04-12 07:03

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