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
|
/*
WhatsApp plugin for Miranda NG
Copyright © 2019-22 George Hazan
*/
#include "stdafx.h"
void WhatsAppProto::OnAccountSync(const WANode &node)
{
m_arDevices.destroy();
for (auto &it : node.getChild("devices")->getChildren())
if (it->title == "device")
m_arDevices.insert(new WADevice(it->getAttr("jid"), it->getAttrInt("key-index")));
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnIqBlockList(const WANode &node)
{
for (auto &it : node.getChild("list")->getChildren()) {
auto *pUser = AddUser(it->getAttr("jid"), false);
Contact::Hide(pUser->hContact);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnIqCountPrekeys(const WANode &node)
{
int iCount = node.getChild("count")->getAttrInt("value");
if (iCount < 5)
UploadMorePrekeys();
}
void WhatsAppProto::UploadMorePrekeys()
{
WANodeIq iq(IQ::SET, "encrypt");
auto regId = encodeBigEndian(getDword(DBKEY_REG_ID));
iq.addChild("registration")->content.append(regId.c_str(), regId.size());
iq.addChild("type")->content.append(KEY_BUNDLE_TYPE, 1);
iq.addChild("identity")->content.append(m_signalStore.signedIdentity.pub);
const int PORTION = 10;
m_signalStore.generatePrekeys(PORTION);
int iStart = getDword(DBKEY_PREKEY_UPLOAD_ID, 1);
auto *n = iq.addChild("list");
for (int i = 0; i < PORTION; i++) {
auto *nKey = n->addChild("key");
int keyId = iStart + i;
auto encId = encodeBigEndian(keyId, 3);
nKey->addChild("id")->content.append(encId.c_str(), encId.size());
nKey->addChild("value")->content.append(getBlob(CMStringA(FORMAT, "PreKey%dPublic", keyId)));
}
setDword(DBKEY_PREKEY_UPLOAD_ID, iStart + PORTION);
auto *skey = iq.addChild("skey");
auto encId = encodeBigEndian(m_signalStore.preKey.keyid, 3);
skey->addChild("id")->content.append(encId.c_str(), encId.size());
skey->addChild("value")->content.append(m_signalStore.preKey.pub);
skey->addChild("signature")->content.append(m_signalStore.preKey.signature);
WSSendNode(iq, &WhatsAppProto::OnIqDoNothing);
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnIqDoNothing(const WANode &)
{
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnNotifyEncrypt(const WANode &node)
{
auto *pszFrom = node.getAttr("from");
if (!mir_strcmp(pszFrom, S_WHATSAPP_NET)) {
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnReceiveInfo(const WANode &node)
{
if (auto *pChild = node.getFirstChild()) {
if (pChild->title == "offline") {
debugLogA("Processed %d offline events", pChild->getAttrInt("count"));
if (m_arCollections.getCount() == 0) {
m_impl.m_resyncApp.Stop();
m_impl.m_resyncApp.Start(1000);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnReceiveMessage(const WANode &node)
{
auto *msgId = node.getAttr("id");
auto *msgType = node.getAttr("type");
auto *msgFrom = node.getAttr("from");
auto *category = node.getAttr("category");
auto *recipient = node.getAttr("recipient");
auto *participant = node.getAttr("participant");
if (msgType == nullptr || msgFrom == nullptr || msgId == nullptr) {
debugLogA("bad message received: <%s> <%s> <%s>", msgType, msgFrom, msgId);
return;
}
WAMSG type;
WAJid jid(msgFrom);
CMStringA szAuthor, szChatId;
if (node.getAttr("offline"))
type.bOffline = true;
// message from one user to another
if (jid.isUser()) {
if (recipient) {
if (m_szJid != msgFrom) {
debugLogA("strange message: with recipient, but not from me");
return;
}
szChatId = recipient;
}
else szChatId = msgFrom;
type.bPrivateChat = true;
szAuthor = msgFrom;
}
else if (jid.isGroup()) {
if (!participant) {
debugLogA("strange message: from group, but without participant");
return;
}
type.bGroupChat = true;
szAuthor = participant;
szChatId = msgFrom;
}
else if (jid.isBroadcast()) {
if (!participant) {
debugLogA("strange message: from group, but without participant");
return;
}
bool bIsMe = m_szJid == participant;
if (jid.isStatusBroadcast()) {
if (bIsMe)
type.bDirectStatus = true;
else
type.bOtherStatus = true;
}
else {
if (bIsMe)
type.bPeerBroadcast = true;
else
type.bOtherBroadcast = true;
}
szChatId = msgFrom;
szAuthor = participant;
}
else {
debugLogA("invalid message type");
return;
}
CMStringA szSender = (type.bPrivateChat) ? szAuthor : szChatId;
bool bFromMe = (m_szJid == msgFrom);
if (!bFromMe && participant)
bFromMe = m_szJid == participant;
auto *pKey = new proto::MessageKey();
pKey->set_remotejid(szChatId);
pKey->set_id(msgId);
pKey->set_fromme(bFromMe);
if (participant)
pKey->set_participant(participant);
proto::WebMessageInfo msg;
msg.set_allocated_key(pKey);
msg.set_messagetimestamp(_atoi64(node.getAttr("t")));
msg.set_pushname(node.getAttr("notify"));
if (bFromMe)
msg.set_status(proto::WebMessageInfo_Status_SERVER_ACK);
int iDecryptable = 0;
for (auto &it: node.getChildren()) {
if (it->title == "verified_name") {
proto::VerifiedNameCertificate cert;
cert << it->content;
proto::VerifiedNameCertificate::Details details;
details.ParseFromString(cert.details());
msg.set_verifiedbizname(details.verifiedname());
continue;
}
if (it->title != "enc" || it->content.length() == 0)
continue;
SignalBuffer msgBody;
auto *pszType = it->getAttr("type");
try {
if (!mir_strcmp(pszType, "pkmsg") || !mir_strcmp(pszType, "msg")) {
CMStringA szUser = (WAJid(szSender).isUser()) ? szSender : szAuthor;
msgBody = m_signalStore.decryptSignalProto(szUser, pszType, it->content);
}
else if (!mir_strcmp(pszType, "skmsg")) {
msgBody = m_signalStore.decryptGroupSignalProto(szSender, szAuthor, it->content);
}
else throw "Invalid e2e type";
if (!msgBody)
throw "Invalid e2e message";
iDecryptable++;
proto::Message encMsg;
encMsg.ParseFromArray(msgBody.data(), msgBody.len());
if (encMsg.devicesentmessage().has_message())
msg.set_allocated_message(new proto::Message(encMsg.devicesentmessage().message()));
else
msg.set_allocated_message(new proto::Message(encMsg));
if (encMsg.has_senderkeydistributionmessage())
m_signalStore.processSenderKeyMessage(encMsg.senderkeydistributionmessage());
ProcessMessage(type, msg);
msg.clear_message();
// send receipt
const char *pszReceiptType = nullptr, *pszReceiptTo = participant;
if (!mir_strcmp(category, "peer"))
pszReceiptType = "peer_msg";
else if (bFromMe) {
// message was sent by me from a different device
pszReceiptType = "sender";
if (WAJid(szChatId).isUser())
pszReceiptTo = szAuthor;
}
else if (!m_hServerConn)
pszReceiptType = "inactive";
SendReceipt(szChatId, pszReceiptTo, msgId, pszReceiptType);
}
catch (const char *) {
}
if (!iDecryptable) {
debugLogA("Nothing to decrypt");
return;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnStreamError(const WANode &node)
{
m_bTerminated = true;
if (auto *pszCode = node.getAttr("code")) {
switch (atoi(pszCode)) {
case 401:
debugLogA("Connection logged out from another device, exiting");
break;
case 408:
debugLogA("Connection lost, exiting");
break;
case 411:
debugLogA("Conflict between two devices, exiting");
break;
case 428:
debugLogA("Connection forcibly closed by the server, exiting");
break;
case 440:
debugLogA("Connection replaced from another device, exiting");
break;
case 515:
debugLogA("Server required to restart immediately, leaving thread");
m_bRespawn = true;
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnIqResult(const WANode &node)
{
if (auto *pszId = node.getAttr("id"))
for (auto &it: m_arPacketQueue)
if (it->szPacketId == pszId)
(this->*it->pHandler)(node);
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnIqPairDevice(const WANode &node)
{
WSSendNode(WANodeIq(IQ::RESULT) << CHAR_PARAM("id", node.getAttr("id")));
if (auto *pRef = node.getChild("pair-device")->getChild("ref")) {
ShowQrCode(pRef->getBody());
}
else {
debugLogA("OnIqPairDevice: got reply without ref, exiting");
ShutdownSession();
}
}
void WhatsAppProto::OnIqPairSuccess(const WANode &node)
{
CloseQrDialog();
auto *pRoot = node.getChild("pair-success");
try {
if (auto *pPlatform = pRoot->getChild("platform"))
debugLogA("Got response from platform: %s", pPlatform->getBody().c_str());
if (auto *pBiz = pRoot->getChild("biz"))
if (auto *pszName = pBiz->getAttr("name"))
setUString("Nick", pszName);
if (auto *pDevice = pRoot->getChild("device")) {
if (auto *pszJid = pDevice->getAttr("jid")) {
WAJid jid(pszJid);
m_szJid = jid.user + "@" + jid.server;
setUString(DBKEY_ID, m_szJid);
setDword(DBKEY_DEVICE_ID, jid.device);
}
}
else throw "OnIqPairSuccess: got reply without device info, exiting";
if (auto *pIdentity = pRoot->getChild("device-identity")) {
proto::ADVSignedDeviceIdentityHMAC payload;
if (!payload.ParseFromArray(pIdentity->content.data(), (int)pIdentity->content.length()))
throw "OnIqPairSuccess: got reply with invalid identity, exiting";
auto &hmac = payload.hmac();
auto &details = payload.details();
{
// check details signature using HMAC
uint8_t signature[32];
unsigned int out_len = sizeof(signature);
MBinBuffer secret(getBlob(DBKEY_SECRET_KEY));
HMAC(EVP_sha256(), secret.data(), (int)secret.length(), (BYTE *)details.c_str(), (int)details.size(), signature, &out_len);
if (memcmp(hmac.c_str(), signature, sizeof(signature)))
throw "OnIqPairSuccess: got reply with invalid details signature, exiting";
}
proto::ADVSignedDeviceIdentity account;
if (!account.ParseFromString(details))
throw "OnIqPairSuccess: got reply with invalid account, exiting";
auto &deviceDetails = account.details();
auto &accountSignature = account.accountsignature();
auto &accountSignatureKey = account.accountsignaturekey();
{
MBinBuffer buf;
buf.append("\x06\x00", 2);
buf.append(deviceDetails.c_str(), deviceDetails.size());
buf.append(m_signalStore.signedIdentity.pub);
ec_public_key key = {};
memcpy(key.data, accountSignatureKey.c_str(), sizeof(key.data));
if (1 != curve_verify_signature(&key, (BYTE *)buf.data(), buf.length(), (BYTE *)accountSignature.c_str(), accountSignature.size()))
throw "OnIqPairSuccess: got reply with invalid account signature, exiting";
}
debugLogA("Received valid account signature");
{
MBinBuffer buf;
buf.append("\x06\x01", 2);
buf.append(deviceDetails.c_str(), deviceDetails.size());
buf.append(m_signalStore.signedIdentity.pub);
buf.append(accountSignatureKey.c_str(), accountSignatureKey.size());
signal_buffer *result;
ec_private_key key = {};
memcpy(key.data, m_signalStore.signedIdentity.priv.data(), m_signalStore.signedIdentity.priv.length());
if (curve_calculate_signature(m_signalStore.CTX(), &result, &key, (BYTE *)buf.data(), buf.length()) != 0)
throw "OnIqPairSuccess: cannot calculate account signature, exiting";
account.set_devicesignature(result->data, result->len);
signal_buffer_free(result);
}
setDword("SignalDeviceId", 0);
{
MBinBuffer key;
if (accountSignatureKey.size() == 32)
key.append(KEY_BUNDLE_TYPE, 1);
key.append(accountSignatureKey.c_str(), accountSignatureKey.size());
db_set_blob(0, m_szModuleName, "SignalIdentifierKey", key.data(), (int)key.length());
}
account.clear_accountsignaturekey();
MBinBuffer accountEnc(account.ByteSize());
account.SerializeToArray(accountEnc.data(), (int)accountEnc.length());
db_set_blob(0, m_szModuleName, "WAAccount", accountEnc.data(), (int)accountEnc.length());
proto::ADVDeviceIdentity deviceIdentity;
deviceIdentity.ParseFromString(deviceDetails);
WANodeIq reply(IQ::RESULT); reply << CHAR_PARAM("id", node.getAttr("id"));
WANode *nodePair = reply.addChild("pair-device-sign");
WANode *nodeDeviceIdentity = nodePair->addChild("device-identity");
nodeDeviceIdentity->addAttr("key-index", deviceIdentity.keyindex());
nodeDeviceIdentity->content.append(accountEnc.data(), accountEnc.length());
WSSendNode(reply);
}
else throw "OnIqPairSuccess: got reply without identity, exiting";
}
catch (const char *pErrMsg) {
debugLogA(pErrMsg);
ShutdownSession();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnProcessHandshake(const void *pData, int cbLen)
{
proto::HandshakeMessage msg;
if (!msg.ParseFromArray(pData, cbLen)) {
debugLogA("Error parsing data, exiting");
LBL_Error:
ShutdownSession();
return;
}
auto &static_ = msg.serverhello().static_();
auto &payload_ = msg.serverhello().payload();
auto &ephemeral_ = msg.serverhello().ephemeral();
m_noise->updateHash(ephemeral_.c_str(), ephemeral_.size());
m_noise->mixIntoKey(m_noise->ephemeral.priv.data(), ephemeral_.c_str());
MBinBuffer decryptedStatic = m_noise->decrypt(static_.c_str(), static_.size());
m_noise->mixIntoKey(m_noise->ephemeral.priv.data(), decryptedStatic.data());
MBinBuffer decryptedCert = m_noise->decrypt(payload_.c_str(), payload_.size());
proto::CertChain cert; cert.ParseFromArray(decryptedCert.data(), (int)decryptedCert.length());
proto::CertChain::NoiseCertificate::Details details; details.ParseFromString(cert.intermediate().details());
if (details.issuerserial() != 0) {
debugLogA("Invalid certificate serial number, exiting");
goto LBL_Error;
}
MBinBuffer encryptedPub = m_noise->encrypt(m_noise->noiseKeys.pub.data(), m_noise->noiseKeys.pub.length());
m_noise->mixIntoKey(m_noise->noiseKeys.priv.data(), ephemeral_.c_str());
// create reply
proto::ClientPayload node;
MFileVersion v;
Miranda_GetFileVersion(&v);
// not received our jid from server? generate registration packet then
if (m_szJid.IsEmpty()) {
uint8_t appVersion[16];
mir_md5_hash((BYTE *)APP_VERSION, sizeof(APP_VERSION) - 1, appVersion);
auto *pAppVersion = new proto::DeviceProps_AppVersion();
pAppVersion->set_primary(v[0]);
pAppVersion->set_secondary(v[1]);
pAppVersion->set_tertiary(v[2]);
pAppVersion->set_quaternary(v[3]);
proto::DeviceProps pCompanion;
pCompanion.set_os("Miranda NG");
pCompanion.set_allocated_version(pAppVersion);
pCompanion.set_platformtype(proto::DeviceProps_PlatformType_DESKTOP);
pCompanion.set_requirefullsync(false);
MBinBuffer buf(pCompanion.ByteSize());
pCompanion.SerializeToArray(buf.data(), (int)buf.length());
auto *pPairingData = new proto::ClientPayload_DevicePairingRegistrationData();
pPairingData->set_deviceprops(buf.data(), buf.length());
pPairingData->set_buildhash(appVersion, sizeof(appVersion));
pPairingData->set_eregid(encodeBigEndian(getDword(DBKEY_REG_ID)));
pPairingData->set_ekeytype(KEY_BUNDLE_TYPE);
pPairingData->set_eident(m_signalStore.signedIdentity.pub.data(), m_signalStore.signedIdentity.pub.length());
pPairingData->set_eskeyid(encodeBigEndian(m_signalStore.preKey.keyid));
pPairingData->set_eskeyval(m_signalStore.preKey.pub.data(), m_signalStore.preKey.pub.length());
pPairingData->set_eskeysig(m_signalStore.preKey.signature.data(), m_signalStore.preKey.signature.length());
node.set_allocated_devicepairingdata(pPairingData);
node.set_passive(false);
}
// generate login packet
else {
WAJid jid(m_szJid);
node.set_username(_atoi64(jid.user));
node.set_device(getDword(DBKEY_DEVICE_ID));
node.set_passive(true);
}
auto *pUserVersion = new proto::ClientPayload_UserAgent_AppVersion();
pUserVersion->set_primary(2);
pUserVersion->set_secondary(2230);
pUserVersion->set_tertiary(15);
auto *pUserAgent = new proto::ClientPayload_UserAgent();
pUserAgent->set_allocated_appversion(pUserVersion);
pUserAgent->set_platform(proto::ClientPayload_UserAgent_Platform_WEB);
pUserAgent->set_releasechannel(proto::ClientPayload_UserAgent_ReleaseChannel_RELEASE);
pUserAgent->set_mcc("000");
pUserAgent->set_mnc("000");
pUserAgent->set_osversion("0.1");
pUserAgent->set_osbuildnumber("0.1");
pUserAgent->set_manufacturer("");
pUserAgent->set_device("Desktop");
pUserAgent->set_localelanguageiso6391("en");
pUserAgent->set_localecountryiso31661alpha2("US");
auto *pWebInfo = new proto::ClientPayload_WebInfo();
pWebInfo->set_websubplatform(proto::ClientPayload_WebInfo_WebSubPlatform_WEB_BROWSER);
node.set_connecttype(proto::ClientPayload_ConnectType_WIFI_UNKNOWN);
node.set_connectreason(proto::ClientPayload_ConnectReason_USER_ACTIVATED);
node.set_allocated_useragent(pUserAgent);
node.set_allocated_webinfo(pWebInfo);
MBinBuffer payload(node.ByteSize());
node.SerializeToArray(payload.data(), (int)payload.length());
MBinBuffer payloadEnc = m_noise->encrypt(payload.data(), payload.length());
auto *pFinish = new proto::HandshakeMessage_ClientFinish();
pFinish->set_payload(payloadEnc.data(), payloadEnc.length());
pFinish->set_static_(encryptedPub.data(), encryptedPub.length());
proto::HandshakeMessage handshake;
handshake.set_allocated_clientfinish(pFinish);
WSSend(handshake);
m_noise->finish();
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnServerSync(const WANode &node)
{
OBJLIST<WACollection> task(1);
for (auto &it : node.getChildren())
if (it->title == "collection")
task.insert(new WACollection(it->getAttr("name"), it->getAttrInt("version")));
ResyncServer(task);
}
void WhatsAppProto::ResyncAll()
{
OBJLIST<WACollection> task(1);
task.insert(new WACollection("regular", 11));
task.insert(new WACollection("regular_high", 9));
task.insert(new WACollection("regular_low", 11));
task.insert(new WACollection("critical_block", 11));
task.insert(new WACollection("critical_unblock_low", 11));
ResyncServer(task);
}
void WhatsAppProto::ResyncServer(const OBJLIST<WACollection> &task)
{
WANodeIq iq(IQ::SET, "w:sync:app:state");
auto *pList = iq.addChild("sync");
for (auto &it : task) {
auto *pCollection = m_arCollections.find(it);
if (pCollection == nullptr)
m_arCollections.insert(pCollection = new WACollection(it->szName, 0));
if (pCollection->version < it->version) {
auto *pNode = pList->addChild("collection");
*pNode << CHAR_PARAM("name", it->szName) << INT_PARAM("version", pCollection->version)
<< CHAR_PARAM("return_snapshot", (!pCollection->version) ? "true" : "false");
}
}
if (pList->getFirstChild() != nullptr)
WSSendNode(iq, &WhatsAppProto::OnIqServerSync);
}
void WhatsAppProto::OnIqServerSync(const WANode &node)
{
for (auto &coll : node.getChild("sync")->getChildren()) {
if (coll->title != "collection")
continue;
auto *pszName = coll->getAttr("name");
auto *pCollection = FindCollection(pszName);
if (pCollection == nullptr) {
pCollection = new WACollection(pszName, 0);
m_arCollections.insert(pCollection);
}
int dwVersion = 0;
CMStringW wszSnapshotPath(GetTmpFileName("collection", pszName));
if (auto *pSnapshot = coll->getChild("snapshot")) {
proto::ExternalBlobReference body;
body << pSnapshot->content;
if (!body.has_directpath() || !body.has_mediakey()) {
debugLogA("Invalid snapshot data, skipping");
continue;
}
MBinBuffer buf = DownloadEncryptedFile(directPath2url(body.directpath().c_str()), body.mediakey(), "App State");
if (!buf.data()) {
debugLogA("Invalid downloaded snapshot data, skipping");
continue;
}
proto::SyncdSnapshot snapshot;
snapshot << buf;
dwVersion = snapshot.version().version();
if (dwVersion > pCollection->version) {
auto &hash = snapshot.mac();
pCollection->hash.assign(hash.c_str(), hash.size());
for (auto &it : snapshot.records())
ParsePatch(pCollection, it, true);
}
}
if (auto *pPatchList = coll->getChild("patches")) {
for (auto &it : pPatchList->getChildren()) {
proto::SyncdPatch patch;
patch << it->content;
dwVersion = patch.version().version();
if (dwVersion > pCollection->version)
for (auto &jt : patch.mutations())
ParsePatch(pCollection, jt.record(), jt.operation() == proto::SyncdMutation_SyncdOperation::SyncdMutation_SyncdOperation_SET);
}
}
CMStringA szSetting(FORMAT, "Collection_%s", pszName);
// setDword(szSetting, dwVersion);
JSONNode jsonRoot, jsonMap;
for (auto &it : pCollection->indexValueMap)
jsonMap << CHAR_PARAM(ptrA(mir_base64_encode(it.first.c_str(), it.first.size())), ptrA(mir_base64_encode(it.second.c_str(), it.second.size())));
jsonRoot << INT_PARAM("version", dwVersion) << JSON_PARAM("indexValueMap", jsonMap);
string2file(jsonRoot.write(), GetTmpFileName("collection", CMStringA(pszName) + ".json"));
}
}
static char sttMutationInfo[] = "WhatsApp Mutation Keys";
void WhatsAppProto::ParsePatch(WACollection *pColl, const ::proto::SyncdRecord &rec, bool bSet)
{
int id = decodeBigEndian(rec.keyid().id());
auto &index = rec.index().blob();
auto &value = rec.value().blob();
MBinBuffer key(getBlob(CMStringA(FORMAT, "AppSyncKey%d", id)));
if (!key.data()) {
debugLogA("No key with id=%d to decode a patch");
return;
}
struct
{
uint8_t indexKey[32];
uint8_t encKey[32];
uint8_t macKey[32];
uint8_t snapshotMacKey[32];
uint8_t patchMacKey[32];
} mutationKeys;
HKDF(EVP_sha256(), (BYTE *)"", 0, key.data(), key.length(), (BYTE *)sttMutationInfo, sizeof(sttMutationInfo) - 1, (BYTE*)&mutationKeys, sizeof(mutationKeys));
MBinBuffer decoded = aesDecrypt(EVP_aes_256_cbc(), mutationKeys.encKey, (uint8_t *)value.c_str(), value.c_str() + 16, value.size() - 32);
if (!decoded.data()) {
debugLogA("Unable to decode patch with key id=%d", id);
return;
}
proto::SyncActionData data;
data << decoded;
debugLogA("Applying patch for %s: %d -> %d", pColl->szName.get(), pColl->version, data.version());
if (bSet) {
auto &patchIndex = data.index();
auto &patchVal = data.value();
debugLogA("Got patch: %s", patchVal.Utf8DebugString().c_str());
pColl->indexValueMap[index] = value.substr(0, value.size() - 32);
}
else pColl->indexValueMap.erase(index);
pColl->version = data.version();
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::OnSuccess(const WANode &)
{
OnLoggedIn();
WSSendNode(WANodeIq(IQ::SET, "passive") << XCHILD("active"), &WhatsAppProto::OnIqDoNothing);
}
/////////////////////////////////////////////////////////////////////////////////////////
void WhatsAppProto::InitPersistentHandlers()
{
m_arPersistent.insert(new WAPersistentHandler("iq", "set", "md", "pair-device", &WhatsAppProto::OnIqPairDevice));
m_arPersistent.insert(new WAPersistentHandler("iq", "set", "md", "pair-success", &WhatsAppProto::OnIqPairSuccess));
m_arPersistent.insert(new WAPersistentHandler("notification", "encrypt", 0, 0, &WhatsAppProto::OnNotifyEncrypt));
m_arPersistent.insert(new WAPersistentHandler("notification", "account_sync", 0, 0, &WhatsAppProto::OnAccountSync));
m_arPersistent.insert(new WAPersistentHandler("notification", "server_sync", 0, 0, &WhatsAppProto::OnServerSync));
m_arPersistent.insert(new WAPersistentHandler("ib", 0, 0, 0, &WhatsAppProto::OnReceiveInfo));
m_arPersistent.insert(new WAPersistentHandler("message", 0, 0, 0, &WhatsAppProto::OnReceiveMessage));
m_arPersistent.insert(new WAPersistentHandler("stream:error", 0, 0, 0, &WhatsAppProto::OnStreamError));
m_arPersistent.insert(new WAPersistentHandler("success", 0, 0, 0, &WhatsAppProto::OnSuccess));
m_arPersistent.insert(new WAPersistentHandler(0, "result", 0, 0, &WhatsAppProto::OnIqResult));
}
|