Repository navigation
Expand file tree
/
Copy pathPwfClient.cpp
More file actions
1203 lines (1112 loc) · 46.3 KB
/
Copy pathPwfClient.cpp
File metadata and controls
1203 lines (1112 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "PwfClient.h"
#include "ProductionPolicy.h"
#include "ServerPublicKey.h"
#include <windows.h>
#include <bcrypt.h>
#include <wincrypt.h>
#include <winhttp.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <stdexcept>
#include <utility>
#include <vector>
namespace
{
using ByteVector = std::vector<unsigned char>;
class InternetHandle
{
public:
explicit InternetHandle(HINTERNET handle = nullptr) : handle_(handle) {}
~InternetHandle() { if (handle_) WinHttpCloseHandle(handle_); }
InternetHandle(const InternetHandle&) = delete;
InternetHandle& operator=(const InternetHandle&) = delete;
operator HINTERNET() const { return handle_; }
bool Valid() const { return handle_ != nullptr; }
void Reset(HINTERNET handle)
{
if (handle_) WinHttpCloseHandle(handle_);
handle_ = handle;
}
private:
HINTERNET handle_;
};
void CheckNt(NTSTATUS status, const char* operation)
{
if (status < 0)
throw std::runtime_error(std::string(operation) + " failed (NTSTATUS " +
std::to_string(static_cast<long>(status)) + ").");
}
void ThrowLastError(const char* operation)
{
throw std::runtime_error(std::string(operation) + " failed (Windows error " +
std::to_string(GetLastError()) + ").");
}
// No connection at all: offline, DNS, firewall, proxy or TLS.
void ThrowNetworkError(const char* operation)
{
throw PwfNetworkError("Cannot reach the license server: " + std::string(operation) +
" failed (Windows error " + std::to_string(GetLastError()) + ").");
}
constexpr char NetworkLostMessage[] =
"Cannot reach the license server. Please check your connection and sign in again.";
constexpr char ClockSkewMessage[] =
"Cannot verify your license because this computer's date and time are wrong. "
"Correct them and sign in again.";
constexpr int TooManyRequests = 429;
constexpr DWORD RetryDelayMilliseconds = 300; // before the second try of a request with no reply
constexpr std::size_t MaxResetReason = 255; // characters, as the server counts them
std::string JsonText(const nlohmann::json& object, const char* key)
{
if (object.is_object() && object.contains(key) && object[key].is_string())
return object[key].get<std::string>();
return {};
}
// The server's clock refusal: "reason": "CLOCK_SKEW", or the older plain
// CRYPTO_ERROR whose message says the request expired.
bool IsClockRefusal(const PwfResponse& reply)
{
if (JsonText(reply.data, "reason") == "CLOCK_SKEW")
return true;
std::string message = reply.Message();
std::transform(message.begin(), message.end(), message.begin(),
[](unsigned char character) { return static_cast<char>(std::tolower(character)); });
return reply.ErrorCode() == "CRYPTO_ERROR" && message.find("expired") != std::string::npos;
}
// At most `limit` characters (code points) of UTF-8 text, never cut inside one.
std::string TruncateUtf8(const std::string& text, std::size_t limit)
{
std::size_t characters = 0;
for (std::size_t index = 0; index < text.size(); ++index)
{
const bool startsCharacter = (static_cast<unsigned char>(text[index]) & 0xC0) != 0x80;
if (startsCharacter && ++characters > limit)
return text.substr(0, index);
}
return text;
}
std::string TrimAscii(const std::string& text)
{
const auto first = text.find_first_not_of(" \t\r\n");
if (first == std::string::npos)
return {};
return text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1);
}
DWORD ToDword(std::size_t value)
{
if (value > std::numeric_limits<DWORD>::max())
throw std::runtime_error("Payload is too large.");
return static_cast<DWORD>(value);
}
std::wstring Utf8ToWide(const std::string& value)
{
if (value.empty())
return {};
const int required = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), nullptr, 0);
if (required <= 0)
ThrowLastError("UTF-8 conversion");
std::wstring result(static_cast<std::size_t>(required), L'\0');
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), result.data(), required) <= 0)
ThrowLastError("UTF-8 conversion");
return result;
}
std::string WideToUtf8(const std::wstring& value)
{
if (value.empty())
return {};
const int required = WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()),
nullptr, 0, nullptr, nullptr);
if (required <= 0)
ThrowLastError("UTF-16 conversion");
std::string result(static_cast<std::size_t>(required), '\0');
if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), result.data(), required, nullptr, nullptr) <= 0)
ThrowLastError("UTF-16 conversion");
return result;
}
ByteVector Sha256(const std::string& value)
{
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_HASH_HANDLE hash = nullptr;
ByteVector hashObject;
ByteVector digest;
try
{
CheckNt(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0),
"Opening SHA-256");
DWORD objectSize = 0;
DWORD digestSize = 0;
DWORD copied = 0;
CheckNt(BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&objectSize), sizeof(objectSize), &copied, 0),
"Reading SHA-256 object size");
CheckNt(BCryptGetProperty(algorithm, BCRYPT_HASH_LENGTH,
reinterpret_cast<PUCHAR>(&digestSize), sizeof(digestSize), &copied, 0),
"Reading SHA-256 digest size");
hashObject.resize(objectSize);
digest.resize(digestSize);
CheckNt(BCryptCreateHash(algorithm, &hash, hashObject.data(), objectSize,
nullptr, 0, 0), "Creating SHA-256 hash");
CheckNt(BCryptHashData(hash,
reinterpret_cast<PUCHAR>(const_cast<char*>(value.data())), ToDword(value.size()), 0),
"Hashing SHA-256 data");
CheckNt(BCryptFinishHash(hash, digest.data(), digestSize, 0),
"Finishing SHA-256 hash");
}
catch (...)
{
if (hash) BCryptDestroyHash(hash);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
throw;
}
BCryptDestroyHash(hash);
BCryptCloseAlgorithmProvider(algorithm, 0);
return digest;
}
ByteVector HmacSha256(const ByteVector& key, const std::string& message)
{
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_HASH_HANDLE hash = nullptr;
ByteVector hashObject;
ByteVector digest;
try
{
CheckNt(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr,
BCRYPT_ALG_HANDLE_HMAC_FLAG), "Opening HMAC-SHA256");
DWORD objectSize = 0;
DWORD digestSize = 0;
DWORD copied = 0;
CheckNt(BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&objectSize), sizeof(objectSize), &copied, 0),
"Reading HMAC object size");
CheckNt(BCryptGetProperty(algorithm, BCRYPT_HASH_LENGTH,
reinterpret_cast<PUCHAR>(&digestSize), sizeof(digestSize), &copied, 0),
"Reading HMAC digest size");
hashObject.resize(objectSize);
digest.resize(digestSize);
CheckNt(BCryptCreateHash(algorithm, &hash, hashObject.data(), objectSize,
const_cast<PUCHAR>(key.data()), ToDword(key.size()), 0), "Creating HMAC hash");
CheckNt(BCryptHashData(hash,
reinterpret_cast<PUCHAR>(const_cast<char*>(message.data())),
ToDword(message.size()), 0), "Hashing HMAC data");
CheckNt(BCryptFinishHash(hash, digest.data(), digestSize, 0), "Finishing HMAC hash");
}
catch (...)
{
if (hash) BCryptDestroyHash(hash);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
throw;
}
BCryptDestroyHash(hash);
BCryptCloseAlgorithmProvider(algorithm, 0);
return digest;
}
std::string HexLower(const ByteVector& bytes)
{
static constexpr char digits[] = "0123456789abcdef";
std::string result;
result.resize(bytes.size() * 2);
for (std::size_t index = 0; index < bytes.size(); ++index)
{
result[index * 2] = digits[(bytes[index] >> 4) & 0x0F];
result[index * 2 + 1] = digits[bytes[index] & 0x0F];
}
return result;
}
bool ConstantTimeEquals(const std::string& left, const std::string& right)
{
const std::size_t maximum = (std::max)(left.size(), right.size());
unsigned int difference = static_cast<unsigned int>(left.size() ^ right.size());
for (std::size_t index = 0; index < maximum; ++index)
{
const unsigned char a = index < left.size() ?
static_cast<unsigned char>(left[index]) : 0;
const unsigned char b = index < right.size() ?
static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(right[index]))) : 0;
difference |= static_cast<unsigned int>(a ^ b);
}
return difference == 0;
}
std::string Base64Encode(const ByteVector& bytes)
{
DWORD characters = 0;
if (!CryptBinaryToStringA(bytes.data(), ToDword(bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &characters))
ThrowLastError("Base64 encoding");
std::string result(characters, '\0');
if (!CryptBinaryToStringA(bytes.data(), ToDword(bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, result.data(), &characters))
ThrowLastError("Base64 encoding");
if (!result.empty() && result.back() == '\0')
result.pop_back();
return result;
}
ByteVector Base64Decode(const std::string& value)
{
DWORD bytes = 0;
if (!CryptStringToBinaryA(value.data(), ToDword(value.size()), CRYPT_STRING_BASE64,
nullptr, &bytes, nullptr, nullptr))
ThrowLastError("Base64 decoding");
ByteVector result(bytes);
if (!CryptStringToBinaryA(value.data(), ToDword(value.size()), CRYPT_STRING_BASE64,
result.data(), &bytes, nullptr, nullptr))
ThrowLastError("Base64 decoding");
result.resize(bytes);
return result;
}
ByteVector AesCbcEncrypt(const ByteVector& key, const ByteVector& iv, const std::string& plain)
{
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_KEY_HANDLE aesKey = nullptr;
ByteVector keyObject;
ByteVector output;
try
{
CheckNt(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_AES_ALGORITHM, nullptr, 0),
"Opening AES");
CheckNt(BCryptSetProperty(algorithm, BCRYPT_CHAINING_MODE,
reinterpret_cast<PUCHAR>(const_cast<wchar_t*>(BCRYPT_CHAIN_MODE_CBC)),
sizeof(BCRYPT_CHAIN_MODE_CBC), 0), "Selecting AES-CBC");
DWORD objectSize = 0;
DWORD copied = 0;
CheckNt(BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&objectSize), sizeof(objectSize), &copied, 0),
"Reading AES object size");
keyObject.resize(objectSize);
CheckNt(BCryptGenerateSymmetricKey(algorithm, &aesKey, keyObject.data(), objectSize,
const_cast<PUCHAR>(key.data()), ToDword(key.size()), 0), "Creating AES key");
DWORD outputSize = 0;
ByteVector ivCopy = iv;
CheckNt(BCryptEncrypt(aesKey,
reinterpret_cast<PUCHAR>(const_cast<char*>(plain.data())), ToDword(plain.size()),
nullptr, ivCopy.data(), ToDword(ivCopy.size()), nullptr, 0, &outputSize,
BCRYPT_BLOCK_PADDING), "Sizing AES ciphertext");
output.resize(outputSize);
ivCopy = iv;
CheckNt(BCryptEncrypt(aesKey,
reinterpret_cast<PUCHAR>(const_cast<char*>(plain.data())), ToDword(plain.size()),
nullptr, ivCopy.data(), ToDword(ivCopy.size()), output.data(), outputSize,
&outputSize, BCRYPT_BLOCK_PADDING), "Encrypting AES ciphertext");
output.resize(outputSize);
}
catch (...)
{
if (aesKey) BCryptDestroyKey(aesKey);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
throw;
}
BCryptDestroyKey(aesKey);
BCryptCloseAlgorithmProvider(algorithm, 0);
return output;
}
std::string AesCbcDecrypt(const ByteVector& key, const ByteVector& iv, const ByteVector& cipher)
{
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_KEY_HANDLE aesKey = nullptr;
ByteVector keyObject;
ByteVector output;
try
{
CheckNt(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_AES_ALGORITHM, nullptr, 0),
"Opening AES");
CheckNt(BCryptSetProperty(algorithm, BCRYPT_CHAINING_MODE,
reinterpret_cast<PUCHAR>(const_cast<wchar_t*>(BCRYPT_CHAIN_MODE_CBC)),
sizeof(BCRYPT_CHAIN_MODE_CBC), 0), "Selecting AES-CBC");
DWORD objectSize = 0;
DWORD copied = 0;
CheckNt(BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&objectSize), sizeof(objectSize), &copied, 0),
"Reading AES object size");
keyObject.resize(objectSize);
CheckNt(BCryptGenerateSymmetricKey(algorithm, &aesKey, keyObject.data(), objectSize,
const_cast<PUCHAR>(key.data()), ToDword(key.size()), 0), "Creating AES key");
DWORD outputSize = 0;
ByteVector ivCopy = iv;
CheckNt(BCryptDecrypt(aesKey, const_cast<PUCHAR>(cipher.data()), ToDword(cipher.size()),
nullptr, ivCopy.data(), ToDword(ivCopy.size()), nullptr, 0, &outputSize,
BCRYPT_BLOCK_PADDING), "Sizing AES plaintext");
output.resize(outputSize);
ivCopy = iv;
CheckNt(BCryptDecrypt(aesKey, const_cast<PUCHAR>(cipher.data()), ToDword(cipher.size()),
nullptr, ivCopy.data(), ToDword(ivCopy.size()), output.data(), outputSize,
&outputSize, BCRYPT_BLOCK_PADDING), "Decrypting AES plaintext");
output.resize(outputSize);
}
catch (...)
{
if (aesKey) BCryptDestroyKey(aesKey);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
throw;
}
BCryptDestroyKey(aesKey);
BCryptCloseAlgorithmProvider(algorithm, 0);
return std::string(output.begin(), output.end());
}
std::string ReadHardwareId()
{
HKEY key = nullptr;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", 0,
KEY_READ | KEY_WOW64_64KEY, &key) == ERROR_SUCCESS)
{
DWORD type = 0;
DWORD bytes = 0;
if (RegQueryValueExW(key, L"MachineGuid", nullptr, &type, nullptr, &bytes) == ERROR_SUCCESS &&
(type == REG_SZ || type == REG_EXPAND_SZ) && bytes >= sizeof(wchar_t))
{
std::vector<wchar_t> value(bytes / sizeof(wchar_t) + 1, L'\0');
if (RegQueryValueExW(key, L"MachineGuid", nullptr, &type,
reinterpret_cast<LPBYTE>(value.data()), &bytes) == ERROR_SUCCESS)
{
RegCloseKey(key);
std::wstring wide(value.data());
if (!wide.empty())
return WideToUtf8(wide);
}
}
RegCloseKey(key);
}
std::array<wchar_t, MAX_COMPUTERNAME_LENGTH + 1> name{};
DWORD length = static_cast<DWORD>(name.size());
if (GetComputerNameW(name.data(), &length) && length > 0)
return WideToUtf8(std::wstring(name.data(), length));
return "unknown-host";
}
bool EndsSession(const std::string& code)
{
static const std::array<const char*, 22> codes = {
"BANNED", "PAUSED", "EXPIRED", "HWID_RESET", "MAINTENANCE",
"SESSION_REVOKED", "SESSION_EXPIRED", "SESSION_MISMATCH", "NETWORK_LOST",
"KEY_BANNED", "KEY_PAUSED", "KEY_EXPIRED", "KEY_REVOKED", "KEY_NOT_FOUND",
"HWID_MISMATCH", "SESSION_NOT_FOUND", "APP_DISABLED", "INVALID_KEY",
"REVOKED", "DISABLED", "ACCOUNT_BANNED", "ACCOUNT_EXPIRED"
};
return std::any_of(codes.begin(), codes.end(),
[&code](const char* value) { return code == value; });
}
}
namespace {
bool VerifyServerSignature(const std::string& material, const std::string& encodedSignature)
{
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_KEY_HANDLE key = nullptr;
bool valid = false;
try {
ByteVector blob = Base64Decode(PwfServerPublicKey);
ByteVector signature = Base64Decode(encodedSignature);
ByteVector digest = Sha256(material);
CheckNt(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_RSA_ALGORITHM, nullptr, 0), "Opening RSA");
CheckNt(BCryptImportKeyPair(algorithm, nullptr, BCRYPT_RSAPUBLIC_BLOB, &key,
blob.data(), ToDword(blob.size()), 0), "Importing server public key");
BCRYPT_PKCS1_PADDING_INFO padding{ BCRYPT_SHA256_ALGORITHM };
valid = BCryptVerifySignature(key, &padding, digest.data(), ToDword(digest.size()),
signature.data(), ToDword(signature.size()), BCRYPT_PAD_PKCS1) >= 0;
} catch (...) { valid = false; }
if (key) BCryptDestroyKey(key);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
return valid;
}
}
class PwfClient::CryptoEnvelope
{
public:
explicit CryptoEnvelope(const std::string& appSecret)
: encryptionKey_(Sha256("enc:" + appSecret)),
macKey_(Sha256("mac:" + appSecret))
{
}
// This computer's clock, shifted to match the server's (0 normally).
std::int64_t Now() const
{
return static_cast<std::int64_t>(std::time(nullptr)) + clockOffset_.load();
}
std::int64_t ClockOffset() const { return clockOffset_.load(); }
void SetClockOffset(std::int64_t seconds) { clockOffset_ = seconds; }
std::string Encrypt(const std::string& plainJson) const
{
ByteVector iv(16);
CheckNt(BCryptGenRandom(nullptr, iv.data(), ToDword(iv.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG), "Generating AES IV");
ByteVector cipher = AesCbcEncrypt(encryptionKey_, iv, plainJson);
ByteVector combined = iv;
combined.insert(combined.end(), cipher.begin(), cipher.end());
const std::string payload = Base64Encode(combined);
const std::int64_t timestamp = Now();
const std::string signature = HexLower(HmacSha256(macKey_, payload + std::to_string(timestamp)));
return nlohmann::json{
{"p", payload},
{"t", timestamp},
{"s", signature}
}.dump();
}
std::string Decrypt(const std::string& envelopeJson) const
{
nlohmann::json envelope;
try
{
envelope = nlohmann::json::parse(envelopeJson);
}
catch (const std::exception&)
{
throw std::runtime_error("Invalid encrypted-envelope JSON.");
}
if (!envelope.is_object() || !envelope.contains("p") || !envelope["p"].is_string() ||
!envelope.contains("t") || !envelope["t"].is_number_integer() ||
!envelope.contains("s") || !envelope["s"].is_string())
throw std::runtime_error("Invalid encrypted-envelope format.");
const std::string payload = envelope["p"].get<std::string>();
const std::int64_t timestamp = envelope["t"].get<std::int64_t>();
const std::string receivedSignature = envelope["s"].get<std::string>();
const std::string expectedSignature =
HexLower(HmacSha256(macKey_, payload + std::to_string(timestamp)));
if (!ConstantTimeEquals(expectedSignature, receivedSignature))
throw std::runtime_error(
"HMAC verification failed - check the application secret and response integrity.");
if (std::llabs(Now() - timestamp) > 300)
throw std::runtime_error(
"The encrypted response timestamp is outside the accepted window; check the system clock.");
ByteVector combined = Base64Decode(payload);
if (combined.size() <= 16 || (combined.size() - 16) % 16 != 0)
throw std::runtime_error("Malformed encrypted payload.");
ByteVector iv(combined.begin(), combined.begin() + 16);
ByteVector cipher(combined.begin() + 16, combined.end());
return AesCbcDecrypt(encryptionKey_, iv, cipher);
}
static bool LooksLikeEnvelope(const std::string& body)
{
const nlohmann::json value = nlohmann::json::parse(body, nullptr, false);
return value.is_object() && value.contains("p") && value.contains("t") && value.contains("s");
}
private:
ByteVector encryptionKey_;
ByteVector macKey_;
std::atomic<std::int64_t> clockOffset_{ 0 };
};
bool PwfResponse::Success() const
{
return data.is_object() && data.value("success", false);
}
std::string PwfResponse::ErrorCode() const
{
if (data.is_object() && data.contains("error_code") && data["error_code"].is_string())
return data["error_code"].get<std::string>();
return {};
}
std::string PwfResponse::Message() const
{
if (data.is_object() && data.contains("message") && data["message"].is_string())
return data["message"].get<std::string>();
return {};
}
PwfResponse PwfResponse::Parse(const std::string& body)
{
PwfResponse response;
response.rawJson = body;
response.data = nlohmann::json::parse(body, nullptr, false);
if (response.data.is_discarded() || !response.data.is_object())
throw std::runtime_error("The license server returned a body that is not a JSON object.");
return response;
}
PwfClient::PwfClient(
std::string appSecret,
std::string baseUrl,
int timeoutMilliseconds,
int maxHeartbeatFailures,
int maxRateLimitedBeats)
: appSecret_(std::move(appSecret)),
baseUrl_(std::move(baseUrl)),
hardwareId_(ReadHardwareId()),
timeoutMilliseconds_(timeoutMilliseconds),
maxHeartbeatFailures_(maxHeartbeatFailures),
maxRateLimitedBeats_(maxRateLimitedBeats)
{
pwf_policy::ValidateOrigin(baseUrl_);
if (appSecret_.empty())
throw std::invalid_argument("The application secret is required.");
// Zero would leave an unreachable server (or a proxy answering 429 forever)
// keeping the app running.
if (maxHeartbeatFailures_ < 1 || maxRateLimitedBeats_ < 1)
throw std::invalid_argument("The heartbeat failure budgets must be at least 1.");
while (!baseUrl_.empty() && baseUrl_.back() == '/')
baseUrl_.pop_back();
crypto_ = std::make_unique<CryptoEnvelope>(appSecret_);
}
PwfClient::~PwfClient()
{
StopHeartbeat();
}
PwfResponse PwfClient::Login(const std::string& licenseKey)
{
if (licenseKey.empty())
throw std::invalid_argument("The license key is required.");
PwfResponse response = SendEnvelope(L"/api/auth/login.php", {
{"license_key", licenseKey},
{"hwid", hardwareId_}
});
if (response.Success())
{
const std::string session = response.data.value("session_id", std::string{});
if (session.empty())
throw std::runtime_error("The login reply did not contain a session ID.");
std::lock_guard<std::mutex> lock(stateMutex_);
sessionId_ = session;
licenseKey_ = licenseKey;
if (response.data.contains("heartbeat_interval") &&
response.data["heartbeat_interval"].is_number_integer())
{
const int interval = response.data["heartbeat_interval"].get<int>();
if (interval > 0)
heartbeatSeconds_ = (std::max)(5, interval);
}
}
return response;
}
PwfResponse PwfClient::Heartbeat()
{
std::string session;
std::string license;
{
std::lock_guard<std::mutex> lock(stateMutex_);
session = sessionId_;
license = licenseKey_;
}
if (session.empty())
throw std::runtime_error("Not signed in; call Login before Heartbeat.");
return SendEnvelope(L"/api/auth/heartbeat.php", {
{"session_id", session},
{"license_key", license},
{"hwid", hardwareId_}
});
}
PwfResponse PwfClient::Logout()
{
StopHeartbeat();
std::string session;
std::string license;
{
std::lock_guard<std::mutex> lock(stateMutex_);
session = sessionId_;
license = licenseKey_;
}
if (session.empty())
throw std::runtime_error("Not signed in.");
try
{
PwfResponse response = SendEnvelope(L"/api/auth/logout.php", {
{"session_id", session},
{"license_key", license}
});
std::lock_guard<std::mutex> lock(stateMutex_);
sessionId_.clear();
licenseKey_.clear();
return response;
}
catch (...)
{
std::lock_guard<std::mutex> lock(stateMutex_);
sessionId_.clear();
licenseKey_.clear();
throw;
}
}
PwfResponse PwfClient::ResetHardwareId(const std::string& licenseKey, const std::string& reason)
{
const std::string key = TrimAscii(licenseKey);
if (key.empty())
throw std::invalid_argument("The license key is required.");
std::string text = TrimAscii(reason);
if (text.empty())
text = "Reset from app";
return SendPlain(L"/api/customer/reset-hwid.php", {
{"key", key},
{"reason", TruncateUtf8(text, MaxResetReason)}
});
}
// ── Customer accounts ──
// These endpoints speak plain JSON (no envelope); every reply is still checked against
// the server's signature in HttpPost, like all others.
PwfResponse PwfClient::RegisterAccount(const std::string& username, const std::string& password,
const std::string& email)
{
if (TrimAscii(username).empty())
throw std::invalid_argument("The username is required.");
if (password.empty())
throw std::invalid_argument("The password is required.");
return SendPlain(L"/api/auth/account-register.php", {
{"username", TrimAscii(username)},
{"password", password},
{"email", TrimAscii(email)}
});
}
PwfResponse PwfClient::RegisterAccountWithKey(const std::string& username, const std::string& password,
const std::string& licenseKey, const std::string& email)
{
if (TrimAscii(username).empty())
throw std::invalid_argument("The username is required.");
if (password.empty())
throw std::invalid_argument("The password is required.");
if (TrimAscii(licenseKey).empty())
throw std::invalid_argument("The license key is required.");
return SendPlain(L"/api/auth/account-register.php", {
{"username", TrimAscii(username)},
{"password", password},
{"email", TrimAscii(email)},
{"license_key", TrimAscii(licenseKey)}
});
}
PwfResponse PwfClient::AccountLogin(const std::string& username, const std::string& password)
{
if (TrimAscii(username).empty())
throw std::invalid_argument("The username is required.");
PwfResponse response = SendPlain(L"/api/auth/account-login.php", {
{"username", TrimAscii(username)},
{"password", password},
{"hwid", hardwareId_}
});
if (response.Success())
{
const std::string session = response.data.value("session_id", std::string{});
if (session.empty())
throw std::runtime_error("The account login reply did not contain a session ID.");
std::lock_guard<std::mutex> lock(stateMutex_);
sessionId_ = session;
// An account session is "user:<id>" on the server, not a key: no key from an
// earlier Login may ride along, or the heartbeat is refused (SESSION_MISMATCH).
licenseKey_ = JsonText(response.data, "license_key");
if (response.data.contains("heartbeat_interval") &&
response.data["heartbeat_interval"].is_number_integer())
{
const int interval = response.data["heartbeat_interval"].get<int>();
if (interval > 0)
heartbeatSeconds_ = (std::max)(5, interval);
}
}
return response;
}
PwfResponse PwfClient::ChangeAccountPassword(const std::string& username, const std::string& currentPassword,
const std::string& newPassword)
{
if (TrimAscii(username).empty())
throw std::invalid_argument("The username is required.");
if (newPassword.empty())
throw std::invalid_argument("The new password is required.");
return SendPlain(L"/api/auth/change-password.php", {
{"username", TrimAscii(username)},
{"current_password", currentPassword},
{"new_password", newPassword}
});
}
PwfResponse PwfClient::RedeemKey(const std::string& username, const std::string& password,
const std::string& licenseKey)
{
if (TrimAscii(username).empty())
throw std::invalid_argument("The username is required.");
if (password.empty())
throw std::invalid_argument("The password is required.");
if (TrimAscii(licenseKey).empty())
throw std::invalid_argument("The license key is required.");
return SendPlain(L"/api/auth/account-redeem.php", {
{"username", TrimAscii(username)},
{"password", password},
{"license_key", TrimAscii(licenseKey)}
});
}
PwfResponse PwfClient::RedeemKey(const std::string& licenseKey)
{
if (TrimAscii(licenseKey).empty())
throw std::invalid_argument("The license key is required.");
std::string session;
{
std::lock_guard<std::mutex> lock(stateMutex_);
session = sessionId_;
}
if (session.empty())
throw std::runtime_error("No account is signed in; call AccountLogin first, or pass the username and password.");
return SendPlain(L"/api/auth/account-redeem.php", {
{"session_id", session},
{"license_key", TrimAscii(licenseKey)}
});
}
void PwfClient::StartHeartbeat()
{
StopHeartbeat();
if (!IsSignedIn())
throw std::runtime_error("Not signed in; call Login before StartHeartbeat.");
stopHeartbeat_ = false;
heartbeatThread_ = std::thread(&PwfClient::HeartbeatLoop, this);
}
void PwfClient::StopHeartbeat()
{
stopHeartbeat_ = true;
heartbeatWake_.notify_all();
if (heartbeatThread_.joinable() && heartbeatThread_.get_id() != std::this_thread::get_id())
heartbeatThread_.join();
}
void PwfClient::SetSessionEndedCallback(SessionEndedCallback callback)
{
std::lock_guard<std::mutex> lock(stateMutex_);
sessionEnded_ = std::move(callback);
}
void PwfClient::SetAutoCorrectClock(bool enabled)
{
autoCorrectClock_ = enabled;
}
std::int64_t PwfClient::ClockOffsetSeconds() const
{
return crypto_->ClockOffset();
}
bool PwfClient::IsSignedIn() const
{
std::lock_guard<std::mutex> lock(stateMutex_);
return !sessionId_.empty();
}
std::string PwfClient::SessionId() const
{
std::lock_guard<std::mutex> lock(stateMutex_);
return sessionId_;
}
std::string PwfClient::HardwareId() const
{
return hardwareId_;
}
int PwfClient::HeartbeatSeconds() const
{
std::lock_guard<std::mutex> lock(stateMutex_);
return heartbeatSeconds_;
}
// POST an encrypted envelope. A plain failure (a bad app secret, a rate limit) comes
// back as a failed reply; a plain SUCCESS throws PwfSecurityError. When the server
// refuses this computer's clock it sends its own time: shift by the difference and
// send the request once more.
PwfResponse PwfClient::SendEnvelope(const std::wstring& path, const nlohmann::json& body)
{
PwfResponse reply = SendEnvelopeOnce(path, body);
if (autoCorrectClock_ && TryCorrectClock(reply))
reply = SendEnvelopeOnce(path, body);
return reply;
}
PwfResponse PwfClient::SendEnvelopeOnce(const std::wstring& path, const nlohmann::json& body)
{
const HttpReply http = HttpPost(path, crypto_->Encrypt(body.dump()));
if (CryptoEnvelope::LooksLikeEnvelope(http.body))
{
PwfResponse response = PwfResponse::Parse(crypto_->Decrypt(http.body));
response.isEnveloped = true;
response.statusCode = http.status;
return response;
}
PwfResponse response = ParseReply(http);
// Encrypted endpoints seal EVERY reply once the request is verified; only refusals
// before that point travel as plain JSON. A plain success therefore came from a
// proxy, a hosts-file redirect or a fake server, and accepting it would let any of
// them unlock the application.
if (response.Success())
throw PwfSecurityError("The license server's reply was not encrypted, so it cannot be trusted.");
return response;
}
// POST unencrypted JSON, for the endpoints that do not use the envelope.
PwfResponse PwfClient::SendPlain(const std::wstring& path, const nlohmann::json& body)
{
return ParseReply(HttpPost(path, body.dump()));
}
PwfResponse PwfClient::ParseReply(const HttpReply& http)
{
if (http.body.empty())
throw PwfHttpError(http.status, "The license server returned HTTP " +
std::to_string(http.status) + " with an empty body.");
PwfResponse response;
try
{
response = PwfResponse::Parse(http.body);
}
catch (const std::runtime_error&)
{
// An HTML error page from a proxy or CDN is the usual cause.
throw PwfHttpError(http.status, "The license server returned a body that is not JSON (HTTP " +
std::to_string(http.status) + "). Check the base URL.");
}
response.statusCode = http.status;
// The API answers its own refusals with {success, error_code, message}. Anything
// else with a failing status is a transport problem, not an answer: a wrong app
// secret (HTTP 401 {"detail": ...}) or a CDN page.
if (http.status >= 400 && !response.data.contains("success"))
{
const std::string detail = JsonText(response.data, "detail");
throw PwfHttpError(http.status, "The license server returned HTTP " +
std::to_string(http.status) + (detail.empty() ? std::string(".") : ": " + detail));
}
return response;
}
bool PwfClient::TryCorrectClock(const PwfResponse& reply)
{
// The server's plain refusal for a timestamp outside its window carries
// "reason": "CLOCK_SKEW" and "server_time" (unix seconds). It never sends that
// refusal encrypted, so only a plain reply qualifies.
if (reply.isEnveloped || JsonText(reply.data, "reason") != "CLOCK_SKEW")
return false;
const auto serverTime = reply.data.find("server_time");
if (serverTime == reply.data.end() || !serverTime->is_number_integer() ||
serverTime->get<std::int64_t>() <= 0)
return false;
crypto_->SetClockOffset(serverTime->get<std::int64_t>() -
static_cast<std::int64_t>(std::time(nullptr)));
return true;
}
// 1.4: pwfauth.com first; when it gives no reply at all, the same request goes to the backup name
// pwfauth.net (same server, same signing key). Used only when the request certainly never reached
// a server (the name does not resolve, no connection, TLS refused), or on a timeout before this client
// ever got a reply. Once the backup answers, this client stays on it. A reply, even an error reply,
// is never sent to the other name.
PwfClient::HttpReply PwfClient::HttpPost(const std::wstring& path, const std::string& body) const
{
pwf_policy::ValidateOrigin(baseUrl_);
const int first = activeOrigin_.load();
for (int i = first; ; ++i)
{
unsigned long sendError = 0;
try
{
HttpReply reply = HttpPostTo(pwf_policy::Origins[i], path, body, sendError);
if (i != first)
activeOrigin_.store(i);
answered_.store(true);
return reply;
}
catch (const PwfNetworkError&)
{
const bool neverSent = sendError == ERROR_WINHTTP_NAME_NOT_RESOLVED ||
sendError == ERROR_WINHTTP_CANNOT_CONNECT ||
sendError == ERROR_WINHTTP_SECURE_FAILURE ||
sendError == ERROR_WINHTTP_CONNECTION_ERROR;
const bool silent = sendError == ERROR_WINHTTP_TIMEOUT && !answered_.load();
if (i + 1 >= pwf_policy::OriginCount || !(neverSent || silent))
throw;
}
}
}
PwfClient::HttpReply PwfClient::HttpPostTo(const std::string& origin, const std::wstring& path,
const std::string& body, unsigned long& sendError) const
{
ByteVector nonceBytes(32);
CheckNt(BCryptGenRandom(nullptr, nonceBytes.data(), ToDword(nonceBytes.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG), "Generating response nonce");
const std::string nonce = HexLower(nonceBytes);
const std::wstring url = Utf8ToWide(origin) + path;
URL_COMPONENTS parts{};
parts.dwStructSize = sizeof(parts);
parts.dwSchemeLength = static_cast<DWORD>(-1);
parts.dwHostNameLength = static_cast<DWORD>(-1);
parts.dwUrlPathLength = static_cast<DWORD>(-1);
parts.dwExtraInfoLength = static_cast<DWORD>(-1);
if (!WinHttpCrackUrl(url.c_str(), 0, 0, &parts))
ThrowLastError("Parsing the PWF Auth URL");
const std::wstring host(parts.lpszHostName, parts.dwHostNameLength);
std::wstring requestPath(parts.lpszUrlPath, parts.dwUrlPathLength);
if (parts.dwExtraInfoLength > 0)
requestPath.append(parts.lpszExtraInfo, parts.dwExtraInfoLength);
InternetHandle session(WinHttpOpen(
L"PwfAuthCpp/1.4 (+https://pwfauth.com)",
WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
0));
if (!session.Valid())
ThrowLastError("Opening the HTTP session");
WinHttpSetTimeouts(session, timeoutMilliseconds_, timeoutMilliseconds_,
timeoutMilliseconds_, timeoutMilliseconds_);