-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathencryption.ts
More file actions
661 lines (566 loc) · 19.3 KB
/
encryption.ts
File metadata and controls
661 lines (566 loc) · 19.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
import { type Model, Q } from '@nozbe/watermelondb';
import EJSON from 'ejson';
import { deleteAsync } from 'expo-file-system';
import {
pbkdf2Hash,
aesEncrypt,
aesDecrypt,
randomBytes,
rsaGenerateKeys,
rsaImportKey,
rsaExportKey,
type JWK,
calculateFileChecksum,
aesGcmDecrypt,
aesGcmEncrypt
} from '@rocket.chat/mobile-crypto';
import { sampleSize } from 'lodash';
import {
type IMessage,
type IServerAttachment,
type ISubscription,
type TMessageModel,
type TSendFileMessageFileInfo,
type TSubscriptionModel,
type TThreadMessageModel,
type TThreadModel
} from '../../definitions';
import {
E2E_BANNER_TYPE,
E2E_MESSAGE_TYPE,
E2E_PRIVATE_KEY,
E2E_PUBLIC_KEY,
E2E_RANDOM_PASSWORD_KEY,
E2E_STATUS
} from '../constants/keys';
import database from '../database';
import { getSubscriptionByRoomId } from '../database/services/Subscription';
import log from '../methods/helpers/log';
import protectedFunction from '../methods/helpers/protectedFunction';
import UserPreferences from '../methods/userPreferences';
import { compareServerVersion } from '../methods/helpers';
import {
e2eSetUserPublicAndPrivateKeys,
e2eRequestSubscriptionKeys,
fetchUsersWaitingForGroupKey,
provideUsersSuggestedGroupKeys
} from '../services/restApi';
import { store } from '../store/auxStore';
import { MAX_CONCURRENT_QUEUE } from './constants';
import type { IDecryptionFileQueue, TDecryptFile } from './definitions';
import Deferred from './helpers/deferred';
import EncryptionRoom from './room';
import {
decryptAESCTR,
joinVectorData,
utf8ToBuffer,
bufferToB64,
bufferToHex,
bufferToUtf8,
b64ToBuffer,
parsePrivateKey,
generatePassphrase
} from './utils';
const ROOM_KEY_EXCHANGE_SIZE = 10;
class Encryption {
ready: boolean;
privateKey: string | null;
publicKey: string | null;
readyPromise: Deferred;
userId: string | null;
roomInstances: Record<string, EncryptionRoom>;
decryptionFileQueue: IDecryptionFileQueue[];
decryptionFileQueueActiveCount: number;
keyDistributionInterval: ReturnType<typeof setInterval> | null;
constructor() {
this.userId = '';
this.ready = false;
this.privateKey = null;
this.publicKey = null;
this.roomInstances = {};
this.readyPromise = new Deferred();
this.readyPromise
.then(() => {
this.ready = true;
})
.catch(() => {
this.ready = false;
});
this.decryptionFileQueue = [];
this.decryptionFileQueueActiveCount = 0;
this.keyDistributionInterval = null;
}
// Initialize Encryption client
initialize = (userId: string) => {
this.userId = userId;
this.roomInstances = {};
// Don't await these promises
// so they can run parallelized
this.decryptPendingSubscriptions();
this.decryptPendingMessages();
this.initiateKeyDistribution();
// Mark Encryption client as ready
this.readyPromise.resolve();
};
get establishing() {
const { banner, enabled } = store.getState().encryption;
// If the password was not inserted yet
if (!enabled || banner === E2E_BANNER_TYPE.REQUEST_PASSWORD) {
// We can't decrypt/encrypt, so, reject this try
return Promise.reject();
}
// Wait the client ready state
return this.readyPromise;
}
// Stop Encryption client
stop = () => {
this.userId = null;
this.privateKey = null;
this.publicKey = null;
this.roomInstances = {};
// Cancel ongoing encryption/decryption requests
this.readyPromise.reject();
// Reset Deferred
this.ready = false;
this.readyPromise = new Deferred();
this.readyPromise
.then(() => {
this.ready = true;
})
.catch(() => {
this.ready = false;
});
};
stopRoom = (rid: string) => {
delete this.roomInstances[rid];
};
// When a new participant join and request a new room encryption key
provideRoomKeyToUser = async (keyId: string, rid: string) => {
// If the client is not ready
if (!this.ready) {
try {
// Wait for ready status
await this.establishing;
} catch {
// If it can't be initialized (missing password)
// return and don't provide a key
return;
}
}
const roomE2E = await this.getRoomInstance(rid);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return;
}
return roomE2E.provideKeyToUser(keyId);
};
// Persist keys on UserPreferences
persistKeys = async (server: string, publicKey: JWK, privateKey: string) => {
const privateJWK = JSON.parse(privateKey);
this.privateKey = await rsaImportKey(privateJWK);
this.publicKey = EJSON.stringify(publicKey);
UserPreferences.setString(`${server}-${E2E_PUBLIC_KEY}`, this.publicKey);
UserPreferences.setString(`${server}-${E2E_PRIVATE_KEY}`, privateKey);
};
// Could not obtain public-private keypair from server.
createKeys = async (userId: string, server: string) => {
// Generate new keys
const key = await rsaGenerateKeys(2048);
// Cast these keys to the properly server format
const publicKey = await rsaExportKey(key.public);
const privateKey = await rsaExportKey(key.private);
// Persist these new keys
this.persistKeys(server, publicKey, EJSON.stringify(privateKey));
// Create a password to encode the private key
const password = await this.createRandomPassword(server);
// Encode the private key
const encodedPrivateKey = await this.encodePrivateKey(EJSON.stringify(privateKey), password, userId);
// Send the new keys to the server
await e2eSetUserPublicAndPrivateKeys(EJSON.stringify(publicKey), encodedPrivateKey);
// Request e2e keys of all encrypted rooms
await e2eRequestSubscriptionKeys();
};
// Encode a private key before send it to the server
encodePrivateKey = async (privateKey: string, password: string, userId: string) => {
// TODO: get the appropriate server version
const { version } = store.getState().server;
const isV2 = compareServerVersion(version, 'greaterThanOrEqualTo', '7.13.0');
const salt = isV2 ? `v2:${userId}:mobile` : userId;
const keyBase64 = await this.generateMasterKey(password, salt, isV2 ? 100000 : 1000);
const ivB64 = isV2 ? await randomBytes(12) : await randomBytes(16);
const ivArrayBuffer = b64ToBuffer(ivB64);
const keyHex = bufferToHex(b64ToBuffer(keyBase64));
const ivHex = bufferToHex(ivArrayBuffer);
if (isV2) {
const ciphertextB64 = await aesGcmEncrypt(bufferToB64(utf8ToBuffer(privateKey)), keyHex, ivHex);
return EJSON.stringify({ iv: ivB64, ciphertext: ciphertextB64, salt, iterations: 100000 });
}
// v1
const data = b64ToBuffer(await aesEncrypt(bufferToB64(utf8ToBuffer(privateKey)), keyHex, ivHex));
return EJSON.stringify(new Uint8Array(joinVectorData(ivArrayBuffer, data)));
};
// Decode a private key fetched from server
decodePrivateKey = async (privateKey: string, password: string, userId: string) => {
const { iv: ivBuffer, ciphertext: ciphertextBuffer, iterations, version, salt } = parsePrivateKey(privateKey, userId);
const ciphertextB64 = bufferToB64(ciphertextBuffer);
const ivHex = bufferToHex(ivBuffer);
const keyBase64 = await this.generateMasterKey(password, salt, iterations);
const keyHex = bufferToHex(b64ToBuffer(keyBase64));
let privKeyBase64;
if (version === 'v2') {
privKeyBase64 = await aesGcmDecrypt(ciphertextB64, keyHex, ivHex);
} else {
privKeyBase64 = await aesDecrypt(ciphertextB64, keyHex, ivHex);
}
return bufferToUtf8(b64ToBuffer(privKeyBase64));
};
// Generate a user master key, this is based on salt and a password
generateMasterKey = async (password: string, salt: string, iterations: number): Promise<string> => {
const hash = 'SHA256';
const keyLen = 32;
const passwordBase64 = bufferToB64(utf8ToBuffer(password));
const saltBase64 = bufferToB64(utf8ToBuffer(salt));
const masterKeyBase64 = await pbkdf2Hash(passwordBase64, saltBase64, iterations, keyLen, hash);
return masterKeyBase64;
};
// Create a random password to local created keys
createRandomPassword = async (server: string) => {
const password = await generatePassphrase();
UserPreferences.setString(`${server}-${E2E_RANDOM_PASSWORD_KEY}`, password);
return password;
};
changePassword = async (server: string, password: string) => {
// Cast key to the format server is expecting
const privateKey = await rsaExportKey(this.privateKey as string);
// Encode the private key
const encodedPrivateKey = await this.encodePrivateKey(EJSON.stringify(privateKey), password, this.userId as string);
// This public key is already encoded using EJSON.stringify in the `persistKeys` method
const publicKey = UserPreferences.getString(`${server}-${E2E_PUBLIC_KEY}`);
if (!publicKey) {
throw new Error('Public key not found in local storage, password not changed');
}
// Only send force param for newer worspace versions
const { version } = store.getState().server;
let force = false;
if (compareServerVersion(version, 'greaterThanOrEqualTo', '6.10.0')) {
force = true;
}
// Send the new keys to the server
await e2eSetUserPublicAndPrivateKeys(publicKey, encodedPrivateKey, force);
};
// get a encryption room instance
getRoomInstance = async (rid: string) => {
try {
// Prevent handshake again
if (this.roomInstances[rid]) {
await this.roomInstances[rid].handshake();
return this.roomInstances[rid];
}
this.roomInstances[rid] = new EncryptionRoom(rid, this.userId as string);
const roomE2E = this.roomInstances[rid];
// Start Encryption Room instance handshake
await roomE2E.handshake();
return roomE2E;
} catch (e) {
log(e);
return null;
}
};
deleteRoomInstance = (rid: string) => {
delete this.roomInstances[rid];
};
// Logic to decrypt all pending messages/threads/threadMessages
// after initialize the encryption client
decryptPendingMessages = async (roomId?: string) => {
const db = database.active;
const messagesCollection = db.get('messages');
const threadsCollection = db.get('threads');
const threadMessagesCollection = db.get('thread_messages');
// e2e status is null or 'pending' and message type is 'e2e'
const whereClause = [Q.where('t', E2E_MESSAGE_TYPE), Q.or(Q.where('e2e', null), Q.where('e2e', E2E_STATUS.PENDING))];
// decrypt messages of a room
if (roomId) {
whereClause.push(Q.where('rid', roomId));
}
try {
// Find all messages/threads/threadsMessages that have pending e2e status
const messagesToDecrypt = await messagesCollection.query(...whereClause).fetch();
const threadsToDecrypt = await threadsCollection.query(...whereClause).fetch();
const threadMessagesToDecrypt = await threadMessagesCollection.query(...whereClause).fetch();
// Concat messages/threads/threadMessages
let toDecrypt: (TThreadModel | TThreadMessageModel | TMessageModel)[] = [
...messagesToDecrypt,
...threadsToDecrypt,
...threadMessagesToDecrypt
];
toDecrypt = (await Promise.all(
toDecrypt.map(async message => {
const { t, msg, tmsg, attachments, content } = message;
let newMessage: Partial<TMessageModel> = {};
if (message.subscription) {
const { id: rid } = message.subscription;
// WM Object -> Plain Object
newMessage = await this.decryptMessage({
t,
rid,
msg: msg as string,
tmsg,
attachments,
content
} as IMessage);
}
try {
return message.prepareUpdate(
protectedFunction((m: TMessageModel) => {
Object.assign(m, newMessage);
})
);
} catch {
return null;
}
})
)) as (TThreadModel | TThreadMessageModel)[];
await db.write(async () => {
await db.batch(toDecrypt);
});
} catch (e) {
log(e);
}
};
// Logic to decrypt all pending subscriptions
// after initialize the encryption client
decryptPendingSubscriptions = async () => {
const db = database.active;
const subCollection = db.get('subscriptions');
try {
// Find all rooms that can have a lastMessage encrypted
// If we select only encrypted rooms we can miss some room that changed their encrypted status
const subsEncrypted = await subCollection.query(Q.where('e2e_key_id', Q.notEq(null)), Q.where('encrypted', true)).fetch();
/**
* Filter out subscriptions that already have their lastMessage decrypted.
* We fetch updated subscriptions from server and decrypt them later.
*/
const subsEncryptedToDecrypt = subsEncrypted.filter(
sub => sub.lastMessage?.t === E2E_MESSAGE_TYPE && sub.lastMessage?.e2e !== E2E_STATUS.DONE
);
const preparedSubscriptions: (Model | null)[] = await Promise.all(
subsEncryptedToDecrypt.map(async (sub: TSubscriptionModel) => {
const newSub = await this.decryptSubscription(sub);
try {
return sub.prepareUpdate(
protectedFunction((m: TSubscriptionModel) => {
if (newSub?.lastMessage) {
m.lastMessage = newSub.lastMessage;
}
})
);
} catch {
return null;
}
})
);
await db.write(async () => {
await db.batch(preparedSubscriptions.filter((record): record is Model => record !== null));
});
} catch (e) {
log(e);
}
};
async getSuggestedE2EEKeys(usersWaitingForE2EKeys: Record<string, { _id: string; public_key: string }[]>) {
const roomIds = Object.keys(usersWaitingForE2EKeys);
return Object.fromEntries(
// @ts-ignore
(
await Promise.all(
roomIds.map(async room => {
const roomE2E = await this.getRoomInstance(room);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return;
}
const usersWithKeys = await roomE2E.encryptGroupKeyForParticipantsWaitingForTheKeys(usersWaitingForE2EKeys[room]);
if (!usersWithKeys) {
return;
}
return [room, usersWithKeys];
})
)
).filter(Boolean)
);
}
async getSample(roomIds: string[], limit = 3): Promise<string[]> {
if (limit === 0) {
return [];
}
const randomRoomIds = sampleSize(roomIds, ROOM_KEY_EXCHANGE_SIZE);
const sampleIds: string[] = [];
for await (const roomId of randomRoomIds) {
const roomE2E = await this.getRoomInstance(roomId);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
continue;
}
sampleIds.push(roomId);
}
if (!sampleIds.length && roomIds.length > limit) {
return this.getSample(roomIds, limit - 1);
}
return sampleIds;
}
initiateKeyDistribution = async () => {
if (this.keyDistributionInterval) {
return;
}
const keyDistribution = async () => {
const db = database.active;
const subCollection = db.get('subscriptions');
try {
const subscriptions = await subCollection.query(Q.where('users_waiting_for_e2e_keys', Q.notEq(null)));
if (subscriptions) {
const filteredSubs = subscriptions
.filter(sub => sub.usersWaitingForE2EKeys && !sub.usersWaitingForE2EKeys.some(user => user.userId === this.userId))
.map(sub => sub.rid);
const sampleIds = await this.getSample(filteredSubs);
if (!sampleIds.length) {
return;
}
const result = await fetchUsersWaitingForGroupKey(sampleIds);
if (!result.success || !Object.keys(result.usersWaitingForE2EKeys).length) {
return;
}
const userKeysWithRooms = await this.getSuggestedE2EEKeys(result.usersWaitingForE2EKeys);
if (!Object.keys(userKeysWithRooms).length) {
return;
}
await provideUsersSuggestedGroupKeys(userKeysWithRooms);
}
} catch (e) {
log(e);
}
};
await keyDistribution();
this.keyDistributionInterval = setInterval(keyDistribution, 10000);
};
// Creating the instance is enough to generate room e2ee key
encryptSubscription = (rid: string) => this.getRoomInstance(rid as string);
// Decrypt a subscription lastMessage
decryptSubscription = async (subscription: Partial<ISubscription>) => {
const { rid } = subscription;
const roomE2E = await this.getRoomInstance(rid as string);
return roomE2E?.decryptSubscription(subscription);
};
// Encrypt a message
encryptMessage = async (message: IMessage) => {
const { rid } = message;
const db = database.active;
const subCollection = db.get('subscriptions');
try {
// Find the subscription
const subRecord = await subCollection.find(rid);
// Subscription is not encrypted at the moment
if (!subRecord.encrypted) {
// Send a non encrypted message
return message;
}
const roomE2E = await this.getRoomInstance(rid);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return message;
}
return roomE2E.encrypt(message);
} catch {
// Subscription not found
// or client can't be initialized (missing password)
}
// Send a non encrypted message
return message;
};
// Decrypt a message
decryptMessage = async (message: IMessage) => {
const { t, e2e } = message;
// Prevent create a new instance if this room was encrypted sometime ago
if (t !== E2E_MESSAGE_TYPE || e2e === E2E_STATUS.DONE) {
return message;
}
const { rid } = message;
const roomE2E = await this.getRoomInstance(rid);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return message;
}
return roomE2E.decrypt(message);
};
decryptFileContent = async (file: IServerAttachment) => {
const roomE2E = await this.getRoomInstance(file.rid);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return file;
}
return roomE2E.decryptFileContent(file);
};
encryptFile = async (rid: string, file: TSendFileMessageFileInfo) => {
const subscription = await getSubscriptionByRoomId(rid);
if (!subscription) {
throw new Error('Subscription not found');
}
const { E2E_Enable_Encrypt_Files } = store.getState().settings;
if (!subscription.encrypted || (E2E_Enable_Encrypt_Files !== undefined && !E2E_Enable_Encrypt_Files)) {
// Send a non encrypted message
return { file };
}
const roomE2E = await this.getRoomInstance(rid);
if (!roomE2E || !roomE2E?.hasSessionKey()) {
return { file };
}
return roomE2E.encryptFile(rid, file);
};
decryptFile: TDecryptFile = async (_messageId, path, encryption, originalChecksum) => {
const decryptedFile = await decryptAESCTR(path, encryption.key.k, encryption.iv);
if (decryptedFile) {
const checksum = await calculateFileChecksum(decryptedFile);
if (checksum !== originalChecksum) {
await deleteAsync(decryptedFile);
return null;
}
}
return decryptedFile;
};
addFileToDecryptFileQueue: TDecryptFile = (messageId, path, encryption, originalChecksum) =>
new Promise((resolve, reject) => {
this.decryptionFileQueue.push({
params: [messageId, path, encryption, originalChecksum],
resolve,
reject
});
this.processFileQueue();
});
async processFileQueue() {
if (this.decryptionFileQueueActiveCount >= MAX_CONCURRENT_QUEUE || this.decryptionFileQueue.length === 0) {
return;
}
const queueItem = this.decryptionFileQueue.shift();
// FIXME: TS not getting decryptionFileQueue is not empty. TS 5.5 fix?
if (!queueItem) {
return;
}
const { params, resolve, reject } = queueItem;
this.decryptionFileQueueActiveCount += 1;
try {
const result = await this.decryptFile(...params);
resolve(result);
} catch (error) {
reject(error);
} finally {
this.decryptionFileQueueActiveCount -= 1;
this.processFileQueue();
}
}
// Decrypt multiple messages
decryptMessages = (messages: Partial<IMessage>[]) =>
Promise.all(messages.map((m: Partial<IMessage>) => this.decryptMessage(m as IMessage)));
// Decrypt multiple subscriptions
decryptSubscriptions = (subscriptions: ISubscription[]) => {
if (!this.ready) {
return subscriptions;
}
return Promise.all(subscriptions.map(s => this.decryptSubscription(s)));
};
// Decrypt multiple files
decryptFiles = (files: IServerAttachment[]) => Promise.all(files.map(f => this.decryptFileContent(f)));
}
const encryption = new Encryption();
export default encryption;