Line data Source code
1 : /*
2 : * Famedly Matrix SDK
3 : * Copyright (C) 2019, 2020, 2021 Famedly GmbH
4 : *
5 : * This program is free software: you can redistribute it and/or modify
6 : * it under the terms of the GNU Affero General Public License as
7 : * published by the Free Software Foundation, either version 3 of the
8 : * License, or (at your option) any later version.
9 : *
10 : * This program is distributed in the hope that it will be useful,
11 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 : * GNU Affero General Public License for more details.
14 : *
15 : * You should have received a copy of the GNU Affero General Public License
16 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 : */
18 :
19 : import 'dart:async';
20 : import 'dart:convert';
21 :
22 : import 'package:collection/collection.dart';
23 : import 'package:olm/olm.dart' as olm;
24 :
25 : import 'package:matrix/encryption/encryption.dart';
26 : import 'package:matrix/encryption/utils/base64_unpadded.dart';
27 : import 'package:matrix/encryption/utils/outbound_group_session.dart';
28 : import 'package:matrix/encryption/utils/session_key.dart';
29 : import 'package:matrix/encryption/utils/stored_inbound_group_session.dart';
30 : import 'package:matrix/matrix.dart';
31 : import 'package:matrix/src/utils/run_in_root.dart';
32 :
33 : const megolmKey = EventTypes.MegolmBackup;
34 :
35 : class KeyManager {
36 : final Encryption encryption;
37 :
38 72 : Client get client => encryption.client;
39 : final outgoingShareRequests = <String, KeyManagerKeyShareRequest>{};
40 : final incomingShareRequests = <String, KeyManagerKeyShareRequest>{};
41 : final _inboundGroupSessions = <String, Map<String, SessionKey>>{};
42 : final _outboundGroupSessions = <String, OutboundGroupSession>{};
43 : final Set<String> _loadedOutboundGroupSessions = <String>{};
44 : final Set<String> _requestedSessionIds = <String>{};
45 :
46 24 : KeyManager(this.encryption) {
47 73 : encryption.ssss.setValidator(megolmKey, (String secret) async {
48 1 : final keyObj = olm.PkDecryption();
49 : try {
50 1 : final info = await getRoomKeysBackupInfo(false);
51 2 : if (info.algorithm !=
52 : BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2) {
53 : return false;
54 : }
55 3 : return keyObj.init_with_private_key(base64decodeUnpadded(secret)) ==
56 2 : info.authData['public_key'];
57 : } catch (_) {
58 : return false;
59 : } finally {
60 1 : keyObj.free();
61 : }
62 : });
63 73 : encryption.ssss.setCacheCallback(megolmKey, (String secret) {
64 : // we got a megolm key cached, clear our requested keys and try to re-decrypt
65 : // last events
66 2 : _requestedSessionIds.clear();
67 3 : for (final room in client.rooms) {
68 1 : final lastEvent = room.lastEvent;
69 : if (lastEvent != null &&
70 2 : lastEvent.type == EventTypes.Encrypted &&
71 0 : lastEvent.content['can_request_session'] == true) {
72 0 : final sessionId = lastEvent.content.tryGet<String>('session_id');
73 0 : final senderKey = lastEvent.content.tryGet<String>('sender_key');
74 : if (sessionId != null && senderKey != null) {
75 0 : maybeAutoRequest(
76 0 : room.id,
77 : sessionId,
78 : senderKey,
79 : );
80 : }
81 : }
82 : }
83 : });
84 : }
85 :
86 92 : bool get enabled => encryption.ssss.isSecret(megolmKey);
87 :
88 : /// clear all cached inbound group sessions. useful for testing
89 4 : void clearInboundGroupSessions() {
90 8 : _inboundGroupSessions.clear();
91 : }
92 :
93 23 : Future<void> setInboundGroupSession(
94 : String roomId,
95 : String sessionId,
96 : String senderKey,
97 : Map<String, dynamic> content, {
98 : bool forwarded = false,
99 : Map<String, String>? senderClaimedKeys,
100 : bool uploaded = false,
101 : Map<String, Map<String, int>>? allowedAtIndex,
102 : }) async {
103 23 : final senderClaimedKeys_ = senderClaimedKeys ?? <String, String>{};
104 23 : final allowedAtIndex_ = allowedAtIndex ?? <String, Map<String, int>>{};
105 46 : final userId = client.userID;
106 0 : if (userId == null) return Future.value();
107 :
108 23 : if (!senderClaimedKeys_.containsKey('ed25519')) {
109 46 : final device = client.getUserDeviceKeysByCurve25519Key(senderKey);
110 6 : if (device != null && device.ed25519Key != null) {
111 12 : senderClaimedKeys_['ed25519'] = device.ed25519Key!;
112 : }
113 : }
114 23 : final oldSession = getInboundGroupSession(
115 : roomId,
116 : sessionId,
117 : );
118 46 : if (content['algorithm'] != AlgorithmTypes.megolmV1AesSha2) {
119 : return;
120 : }
121 : late olm.InboundGroupSession inboundGroupSession;
122 : try {
123 23 : inboundGroupSession = olm.InboundGroupSession();
124 : if (forwarded) {
125 6 : inboundGroupSession.import_session(content['session_key']);
126 : } else {
127 46 : inboundGroupSession.create(content['session_key']);
128 : }
129 : } catch (e, s) {
130 0 : inboundGroupSession.free();
131 0 : Logs().e('[LibOlm] Could not create new InboundGroupSession', e, s);
132 0 : return Future.value();
133 : }
134 23 : final newSession = SessionKey(
135 : content: content,
136 : inboundGroupSession: inboundGroupSession,
137 23 : indexes: {},
138 : roomId: roomId,
139 : sessionId: sessionId,
140 : key: userId,
141 : senderKey: senderKey,
142 : senderClaimedKeys: senderClaimedKeys_,
143 : allowedAtIndex: allowedAtIndex_,
144 : );
145 : final oldFirstIndex =
146 2 : oldSession?.inboundGroupSession?.first_known_index() ?? 0;
147 46 : final newFirstIndex = newSession.inboundGroupSession!.first_known_index();
148 : if (oldSession == null ||
149 1 : newFirstIndex < oldFirstIndex ||
150 1 : (oldFirstIndex == newFirstIndex &&
151 3 : newSession.forwardingCurve25519KeyChain.length <
152 2 : oldSession.forwardingCurve25519KeyChain.length)) {
153 : // use new session
154 1 : oldSession?.dispose();
155 : } else {
156 : // we are gonna keep our old session
157 1 : newSession.dispose();
158 : return;
159 : }
160 :
161 : final roomInboundGroupSessions =
162 69 : _inboundGroupSessions[roomId] ??= <String, SessionKey>{};
163 23 : roomInboundGroupSessions[sessionId] = newSession;
164 92 : if (!client.isLogged() || client.encryption == null) {
165 : return;
166 : }
167 :
168 46 : final storeFuture = client.database
169 23 : ?.storeInboundGroupSession(
170 : roomId,
171 : sessionId,
172 23 : inboundGroupSession.pickle(userId),
173 23 : json.encode(content),
174 46 : json.encode({}),
175 23 : json.encode(allowedAtIndex_),
176 : senderKey,
177 23 : json.encode(senderClaimedKeys_),
178 : )
179 46 : .then((_) async {
180 92 : if (!client.isLogged() || client.encryption == null) {
181 : return;
182 : }
183 : if (uploaded) {
184 2 : await client.database
185 1 : ?.markInboundGroupSessionAsUploaded(roomId, sessionId);
186 : }
187 : });
188 46 : final room = client.getRoomById(roomId);
189 : if (room != null) {
190 : // attempt to decrypt the last event
191 7 : final event = room.lastEvent;
192 : if (event != null &&
193 14 : event.type == EventTypes.Encrypted &&
194 6 : event.content['session_id'] == sessionId) {
195 4 : final decrypted = encryption.decryptRoomEventSync(event);
196 4 : if (decrypted.type != EventTypes.Encrypted) {
197 : // Update the last event in memory first
198 2 : room.lastEvent = decrypted;
199 :
200 : // To persist it in database and trigger UI updates:
201 8 : await client.database?.transaction(() async {
202 4 : await client.handleSync(
203 2 : SyncUpdate(
204 : nextBatch: '',
205 2 : rooms: switch (room.membership) {
206 2 : Membership.join =>
207 4 : RoomsUpdate(join: {room.id: JoinedRoomUpdate()}),
208 1 : Membership.ban ||
209 1 : Membership.leave =>
210 4 : RoomsUpdate(leave: {room.id: LeftRoomUpdate()}),
211 0 : Membership.invite =>
212 0 : RoomsUpdate(invite: {room.id: InvitedRoomUpdate()}),
213 0 : Membership.knock =>
214 0 : RoomsUpdate(knock: {room.id: KnockRoomUpdate()}),
215 : },
216 : ),
217 : );
218 : });
219 : }
220 : }
221 : // and finally broadcast the new session
222 14 : room.onSessionKeyReceived.add(sessionId);
223 : }
224 :
225 0 : return storeFuture ?? Future.value();
226 : }
227 :
228 23 : SessionKey? getInboundGroupSession(String roomId, String sessionId) {
229 51 : final sess = _inboundGroupSessions[roomId]?[sessionId];
230 : if (sess != null) {
231 10 : if (sess.sessionId != sessionId && sess.sessionId.isNotEmpty) {
232 : return null;
233 : }
234 : return sess;
235 : }
236 : return null;
237 : }
238 :
239 : /// Attempt auto-request for a key
240 3 : void maybeAutoRequest(
241 : String roomId,
242 : String sessionId,
243 : String? senderKey, {
244 : bool tryOnlineBackup = true,
245 : bool onlineKeyBackupOnly = true,
246 : }) {
247 6 : final room = client.getRoomById(roomId);
248 3 : final requestIdent = '$roomId|$sessionId';
249 : if (room != null &&
250 4 : !_requestedSessionIds.contains(requestIdent) &&
251 4 : !client.isUnknownSession) {
252 : // do e2ee recovery
253 0 : _requestedSessionIds.add(requestIdent);
254 :
255 0 : runInRoot(
256 0 : () async => request(
257 : room,
258 : sessionId,
259 : senderKey,
260 : tryOnlineBackup: tryOnlineBackup,
261 : onlineKeyBackupOnly: onlineKeyBackupOnly,
262 : ),
263 : );
264 : }
265 : }
266 :
267 : /// Loads an inbound group session
268 8 : Future<SessionKey?> loadInboundGroupSession(
269 : String roomId,
270 : String sessionId,
271 : ) async {
272 21 : final sess = _inboundGroupSessions[roomId]?[sessionId];
273 : if (sess != null) {
274 10 : if (sess.sessionId != sessionId && sess.sessionId.isNotEmpty) {
275 : return null; // session_id does not match....better not do anything
276 : }
277 : return sess; // nothing to do
278 : }
279 : final session =
280 15 : await client.database?.getInboundGroupSession(roomId, sessionId);
281 : if (session == null) return null;
282 4 : final userID = client.userID;
283 : if (userID == null) return null;
284 2 : final dbSess = SessionKey.fromDb(session, userID);
285 : final roomInboundGroupSessions =
286 6 : _inboundGroupSessions[roomId] ??= <String, SessionKey>{};
287 2 : if (!dbSess.isValid ||
288 4 : dbSess.sessionId.isEmpty ||
289 4 : dbSess.sessionId != sessionId) {
290 : return null;
291 : }
292 2 : roomInboundGroupSessions[sessionId] = dbSess;
293 : return sess;
294 : }
295 :
296 5 : Map<String, Map<String, bool>> _getDeviceKeyIdMap(
297 : List<DeviceKeys> deviceKeys,
298 : ) {
299 5 : final deviceKeyIds = <String, Map<String, bool>>{};
300 8 : for (final device in deviceKeys) {
301 3 : final deviceId = device.deviceId;
302 : if (deviceId == null) {
303 0 : Logs().w('[KeyManager] ignoring device without deviceid');
304 : continue;
305 : }
306 9 : final userDeviceKeyIds = deviceKeyIds[device.userId] ??= <String, bool>{};
307 6 : userDeviceKeyIds[deviceId] = !device.encryptToDevice;
308 : }
309 : return deviceKeyIds;
310 : }
311 :
312 : /// clear all cached inbound group sessions. useful for testing
313 3 : void clearOutboundGroupSessions() {
314 6 : _outboundGroupSessions.clear();
315 : }
316 :
317 : /// Clears the existing outboundGroupSession but first checks if the participating
318 : /// devices have been changed. Returns false if the session has not been cleared because
319 : /// it wasn't necessary. Otherwise returns true.
320 5 : Future<bool> clearOrUseOutboundGroupSession(
321 : String roomId, {
322 : bool wipe = false,
323 : bool use = true,
324 : }) async {
325 10 : final room = client.getRoomById(roomId);
326 5 : final sess = getOutboundGroupSession(roomId);
327 4 : if (room == null || sess == null || sess.outboundGroupSession == null) {
328 : return true;
329 : }
330 :
331 : if (!wipe) {
332 : // first check if it needs to be rotated
333 : final encryptionContent =
334 6 : room.getState(EventTypes.Encryption)?.parsedRoomEncryptionContent;
335 3 : final maxMessages = encryptionContent?.rotationPeriodMsgs ?? 100;
336 3 : final maxAge = encryptionContent?.rotationPeriodMs ??
337 : 604800000; // default of one week
338 6 : if ((sess.sentMessages ?? maxMessages) >= maxMessages ||
339 3 : sess.creationTime
340 6 : .add(Duration(milliseconds: maxAge))
341 6 : .isBefore(DateTime.now())) {
342 : wipe = true;
343 : }
344 : }
345 :
346 4 : final inboundSess = await loadInboundGroupSession(
347 4 : room.id,
348 8 : sess.outboundGroupSession!.session_id(),
349 : );
350 : if (inboundSess == null) {
351 0 : Logs().e(
352 : 'No inbound session found for outbound group session!',
353 0 : sess.outboundGroupSession?.session_id(),
354 : );
355 : wipe = true;
356 : }
357 :
358 : if (!wipe) {
359 : // next check if the devices in the room changed
360 3 : final devicesToReceive = <DeviceKeys>[];
361 3 : final newDeviceKeys = await room.getUserDeviceKeys();
362 3 : final newDeviceKeyIds = _getDeviceKeyIdMap(newDeviceKeys);
363 : // first check for user differences
364 9 : final oldUserIds = Set.from(sess.devices.keys);
365 6 : final newUserIds = Set.from(newDeviceKeyIds.keys);
366 6 : if (oldUserIds.difference(newUserIds).isNotEmpty) {
367 : // a user left the room, we must wipe the session
368 : wipe = true;
369 : } else {
370 3 : final newUsers = newUserIds.difference(oldUserIds);
371 3 : if (newUsers.isNotEmpty) {
372 : // new user! Gotta send the megolm session to them
373 : devicesToReceive
374 5 : .addAll(newDeviceKeys.where((d) => newUsers.contains(d.userId)));
375 : }
376 : // okay, now we must test all the individual user devices, if anything new got blocked
377 : // or if we need to send to any new devices.
378 : // for this it is enough if we iterate over the old user Ids, as the new ones already have the needed keys in the list.
379 : // we also know that all the old user IDs appear in the old one, else we have already wiped the session
380 5 : for (final userId in oldUserIds) {
381 4 : final oldBlockedDevices = sess.devices.containsKey(userId)
382 2 : ? Set.from(
383 6 : sess.devices[userId]!.entries
384 6 : .where((e) => e.value)
385 2 : .map((e) => e.key),
386 : )
387 : : <String>{};
388 2 : final newBlockedDevices = newDeviceKeyIds.containsKey(userId)
389 2 : ? Set.from(
390 2 : newDeviceKeyIds[userId]!
391 2 : .entries
392 6 : .where((e) => e.value)
393 4 : .map((e) => e.key),
394 : )
395 : : <String>{};
396 : // we don't really care about old devices that got dropped (deleted), we only care if new ones got added and if new ones got blocked
397 : // check if new devices got blocked
398 4 : if (newBlockedDevices.difference(oldBlockedDevices).isNotEmpty) {
399 : wipe = true;
400 : break;
401 : }
402 : // and now add all the new devices!
403 4 : final oldDeviceIds = sess.devices.containsKey(userId)
404 2 : ? Set.from(
405 6 : sess.devices[userId]!.entries
406 6 : .where((e) => !e.value)
407 6 : .map((e) => e.key),
408 : )
409 : : <String>{};
410 2 : final newDeviceIds = newDeviceKeyIds.containsKey(userId)
411 2 : ? Set.from(
412 2 : newDeviceKeyIds[userId]!
413 2 : .entries
414 6 : .where((e) => !e.value)
415 6 : .map((e) => e.key),
416 : )
417 : : <String>{};
418 :
419 : // check if a device got removed
420 4 : if (oldDeviceIds.difference(newDeviceIds).isNotEmpty) {
421 : wipe = true;
422 : break;
423 : }
424 :
425 : // check if any new devices need keys
426 2 : final newDevices = newDeviceIds.difference(oldDeviceIds);
427 2 : if (newDeviceIds.isNotEmpty) {
428 2 : devicesToReceive.addAll(
429 2 : newDeviceKeys.where(
430 10 : (d) => d.userId == userId && newDevices.contains(d.deviceId),
431 : ),
432 : );
433 : }
434 : }
435 : }
436 :
437 : if (!wipe) {
438 : if (!use) {
439 : return false;
440 : }
441 : // okay, we use the outbound group session!
442 3 : sess.devices = newDeviceKeyIds;
443 3 : final rawSession = <String, dynamic>{
444 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
445 3 : 'room_id': room.id,
446 6 : 'session_id': sess.outboundGroupSession!.session_id(),
447 6 : 'session_key': sess.outboundGroupSession!.session_key(),
448 : };
449 : try {
450 5 : devicesToReceive.removeWhere((k) => !k.encryptToDevice);
451 3 : if (devicesToReceive.isNotEmpty) {
452 : // update allowedAtIndex
453 2 : for (final device in devicesToReceive) {
454 4 : inboundSess!.allowedAtIndex[device.userId] ??= <String, int>{};
455 3 : if (!inboundSess.allowedAtIndex[device.userId]!
456 2 : .containsKey(device.curve25519Key) ||
457 0 : inboundSess.allowedAtIndex[device.userId]![
458 0 : device.curve25519Key]! >
459 0 : sess.outboundGroupSession!.message_index()) {
460 : inboundSess
461 5 : .allowedAtIndex[device.userId]![device.curve25519Key!] =
462 2 : sess.outboundGroupSession!.message_index();
463 : }
464 : }
465 3 : await client.database?.updateInboundGroupSessionAllowedAtIndex(
466 2 : json.encode(inboundSess!.allowedAtIndex),
467 1 : room.id,
468 2 : sess.outboundGroupSession!.session_id(),
469 : );
470 : // send out the key
471 2 : await client.sendToDeviceEncryptedChunked(
472 : devicesToReceive,
473 : EventTypes.RoomKey,
474 : rawSession,
475 : );
476 : }
477 : } catch (e, s) {
478 0 : Logs().e(
479 : '[LibOlm] Unable to re-send the session key at later index to new devices',
480 : e,
481 : s,
482 : );
483 : }
484 : return false;
485 : }
486 : }
487 2 : sess.dispose();
488 4 : _outboundGroupSessions.remove(roomId);
489 6 : await client.database?.removeOutboundGroupSession(roomId);
490 : return true;
491 : }
492 :
493 : /// Store an outbound group session in the database
494 5 : Future<void> storeOutboundGroupSession(
495 : String roomId,
496 : OutboundGroupSession sess,
497 : ) async {
498 10 : final userID = client.userID;
499 : if (userID == null) return;
500 15 : await client.database?.storeOutboundGroupSession(
501 : roomId,
502 10 : sess.outboundGroupSession!.pickle(userID),
503 10 : json.encode(sess.devices),
504 10 : sess.creationTime.millisecondsSinceEpoch,
505 : );
506 : }
507 :
508 : final Map<String, Future<OutboundGroupSession>>
509 : _pendingNewOutboundGroupSessions = {};
510 :
511 : /// Creates an outbound group session for a given room id
512 5 : Future<OutboundGroupSession> createOutboundGroupSession(String roomId) async {
513 10 : final sess = _pendingNewOutboundGroupSessions[roomId];
514 : if (sess != null) {
515 : return sess;
516 : }
517 10 : final newSess = _pendingNewOutboundGroupSessions[roomId] =
518 5 : _createOutboundGroupSession(roomId);
519 :
520 : try {
521 : await newSess;
522 : } finally {
523 5 : _pendingNewOutboundGroupSessions
524 15 : .removeWhere((_, value) => value == newSess);
525 : }
526 :
527 : return newSess;
528 : }
529 :
530 : /// Prepares an outbound group session for a given room ID. That is, load it from
531 : /// the database, cycle it if needed and create it if absent.
532 1 : Future<void> prepareOutboundGroupSession(String roomId) async {
533 1 : if (getOutboundGroupSession(roomId) == null) {
534 0 : await loadOutboundGroupSession(roomId);
535 : }
536 1 : await clearOrUseOutboundGroupSession(roomId, use: false);
537 1 : if (getOutboundGroupSession(roomId) == null) {
538 1 : await createOutboundGroupSession(roomId);
539 : }
540 : }
541 :
542 5 : Future<OutboundGroupSession> _createOutboundGroupSession(
543 : String roomId,
544 : ) async {
545 5 : await clearOrUseOutboundGroupSession(roomId, wipe: true);
546 10 : await client.firstSyncReceived;
547 10 : final room = client.getRoomById(roomId);
548 : if (room == null) {
549 0 : throw Exception(
550 0 : 'Tried to create a megolm session in a non-existing room ($roomId)!',
551 : );
552 : }
553 10 : final userID = client.userID;
554 : if (userID == null) {
555 0 : throw Exception(
556 : 'Tried to create a megolm session without being logged in!',
557 : );
558 : }
559 :
560 5 : final deviceKeys = await room.getUserDeviceKeys();
561 5 : final deviceKeyIds = _getDeviceKeyIdMap(deviceKeys);
562 11 : deviceKeys.removeWhere((k) => !k.encryptToDevice);
563 5 : final outboundGroupSession = olm.OutboundGroupSession();
564 : try {
565 5 : outboundGroupSession.create();
566 : } catch (e, s) {
567 0 : outboundGroupSession.free();
568 0 : Logs().e('[LibOlm] Unable to create new outboundGroupSession', e, s);
569 : rethrow;
570 : }
571 5 : final rawSession = <String, dynamic>{
572 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
573 5 : 'room_id': room.id,
574 5 : 'session_id': outboundGroupSession.session_id(),
575 5 : 'session_key': outboundGroupSession.session_key(),
576 : };
577 5 : final allowedAtIndex = <String, Map<String, int>>{};
578 8 : for (final device in deviceKeys) {
579 3 : if (!device.isValid) {
580 0 : Logs().e('Skipping invalid device');
581 : continue;
582 : }
583 9 : allowedAtIndex[device.userId] ??= <String, int>{};
584 12 : allowedAtIndex[device.userId]![device.curve25519Key!] =
585 3 : outboundGroupSession.message_index();
586 : }
587 5 : await setInboundGroupSession(
588 : roomId,
589 5 : rawSession['session_id'],
590 10 : encryption.identityKey!,
591 : rawSession,
592 : allowedAtIndex: allowedAtIndex,
593 : );
594 5 : final sess = OutboundGroupSession(
595 : devices: deviceKeyIds,
596 5 : creationTime: DateTime.now(),
597 : outboundGroupSession: outboundGroupSession,
598 : key: userID,
599 : );
600 : try {
601 10 : await client.sendToDeviceEncryptedChunked(
602 : deviceKeys,
603 : EventTypes.RoomKey,
604 : rawSession,
605 : );
606 5 : await storeOutboundGroupSession(roomId, sess);
607 10 : _outboundGroupSessions[roomId] = sess;
608 16 : final devices = deviceKeys.map((keys) => keys.deviceId).toList();
609 5 : final users = deviceKeys.fold(
610 : <String>{},
611 9 : (users, keys) => users..add(keys.userId),
612 5 : ).toList();
613 20 : await client.database?.transaction(() async {
614 10 : await client.handleSync(
615 5 : SyncUpdate(
616 : nextBatch: '',
617 5 : rooms: RoomsUpdate(
618 5 : join: {
619 5 : roomId: JoinedRoomUpdate(
620 5 : timeline: TimelineUpdate(
621 5 : events: [
622 5 : Event(
623 10 : eventId: 'fake_event_${rawSession['session_id']}',
624 5 : content: {
625 : 'body':
626 10 : 'Encrypted conversation initialized with ${users.join(', ')}',
627 : 'devices': devices,
628 : 'members': users,
629 : },
630 : type: 'sdk.dart.matrix.new_megolm_session',
631 10 : senderId: client.userID!,
632 5 : originServerTs: DateTime.now(),
633 : room: room,
634 : ),
635 : ],
636 : ),
637 : ),
638 : },
639 : ),
640 : ),
641 : );
642 : });
643 : } catch (e, s) {
644 0 : Logs().e(
645 : '[LibOlm] Unable to send the session key to the participating devices',
646 : e,
647 : s,
648 : );
649 0 : sess.dispose();
650 : rethrow;
651 : }
652 : return sess;
653 : }
654 :
655 : /// Get an outbound group session for a room id
656 5 : OutboundGroupSession? getOutboundGroupSession(String roomId) {
657 10 : return _outboundGroupSessions[roomId];
658 : }
659 :
660 : /// Load an outbound group session from database
661 3 : Future<void> loadOutboundGroupSession(String roomId) async {
662 6 : final database = client.database;
663 6 : final userID = client.userID;
664 6 : if (_loadedOutboundGroupSessions.contains(roomId) ||
665 6 : _outboundGroupSessions.containsKey(roomId) ||
666 : database == null ||
667 : userID == null) {
668 : return; // nothing to do
669 : }
670 6 : _loadedOutboundGroupSessions.add(roomId);
671 3 : final sess = await database.getOutboundGroupSession(
672 : roomId,
673 : userID,
674 : );
675 1 : if (sess == null || !sess.isValid) {
676 : return;
677 : }
678 2 : _outboundGroupSessions[roomId] = sess;
679 : }
680 :
681 23 : Future<bool> isCached() async {
682 46 : await client.accountDataLoading;
683 23 : if (!enabled) {
684 : return false;
685 : }
686 46 : await client.userDeviceKeysLoading;
687 69 : return (await encryption.ssss.getCached(megolmKey)) != null;
688 : }
689 :
690 : GetRoomKeysVersionCurrentResponse? _roomKeysVersionCache;
691 : DateTime? _roomKeysVersionCacheDate;
692 :
693 5 : Future<GetRoomKeysVersionCurrentResponse> getRoomKeysBackupInfo([
694 : bool useCache = true,
695 : ]) async {
696 5 : if (_roomKeysVersionCache != null &&
697 3 : _roomKeysVersionCacheDate != null &&
698 : useCache &&
699 1 : DateTime.now()
700 2 : .subtract(Duration(minutes: 5))
701 2 : .isBefore(_roomKeysVersionCacheDate!)) {
702 1 : return _roomKeysVersionCache!;
703 : }
704 15 : _roomKeysVersionCache = await client.getRoomKeysVersionCurrent();
705 10 : _roomKeysVersionCacheDate = DateTime.now();
706 5 : return _roomKeysVersionCache!;
707 : }
708 :
709 1 : Future<void> loadFromResponse(RoomKeys keys) async {
710 1 : if (!(await isCached())) {
711 : return;
712 : }
713 : final privateKey =
714 4 : base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
715 1 : final decryption = olm.PkDecryption();
716 1 : final info = await getRoomKeysBackupInfo();
717 : String backupPubKey;
718 : try {
719 1 : backupPubKey = decryption.init_with_private_key(privateKey);
720 :
721 2 : if (info.algorithm != BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
722 3 : info.authData['public_key'] != backupPubKey) {
723 : return;
724 : }
725 3 : for (final roomEntry in keys.rooms.entries) {
726 1 : final roomId = roomEntry.key;
727 4 : for (final sessionEntry in roomEntry.value.sessions.entries) {
728 1 : final sessionId = sessionEntry.key;
729 1 : final session = sessionEntry.value;
730 1 : final sessionData = session.sessionData;
731 : Map<String, Object?>? decrypted;
732 : try {
733 1 : decrypted = json.decode(
734 1 : decryption.decrypt(
735 1 : sessionData['ephemeral'] as String,
736 1 : sessionData['mac'] as String,
737 1 : sessionData['ciphertext'] as String,
738 : ),
739 : );
740 : } catch (e, s) {
741 0 : Logs().e('[LibOlm] Error decrypting room key', e, s);
742 : }
743 1 : final senderKey = decrypted?.tryGet<String>('sender_key');
744 : if (decrypted != null && senderKey != null) {
745 1 : decrypted['session_id'] = sessionId;
746 1 : decrypted['room_id'] = roomId;
747 1 : await setInboundGroupSession(
748 : roomId,
749 : sessionId,
750 : senderKey,
751 : decrypted,
752 : forwarded: true,
753 : senderClaimedKeys:
754 1 : decrypted.tryGetMap<String, String>('sender_claimed_keys') ??
755 0 : <String, String>{},
756 : uploaded: true,
757 : );
758 : }
759 : }
760 : }
761 : } finally {
762 1 : decryption.free();
763 : }
764 : }
765 :
766 : /// Loads and stores all keys from the online key backup. This may take a
767 : /// while for older and big accounts.
768 1 : Future<void> loadAllKeys() async {
769 1 : final info = await getRoomKeysBackupInfo();
770 3 : final ret = await client.getRoomKeys(info.version);
771 1 : await loadFromResponse(ret);
772 : }
773 :
774 : /// Loads all room keys for a single room and stores them. This may take a
775 : /// while for older and big rooms.
776 1 : Future<void> loadAllKeysFromRoom(String roomId) async {
777 1 : final info = await getRoomKeysBackupInfo();
778 3 : final ret = await client.getRoomKeysByRoomId(roomId, info.version);
779 2 : final keys = RoomKeys.fromJson({
780 1 : 'rooms': {
781 1 : roomId: {
782 5 : 'sessions': ret.sessions.map((k, s) => MapEntry(k, s.toJson())),
783 : },
784 : },
785 : });
786 1 : await loadFromResponse(keys);
787 : }
788 :
789 : /// Loads a single key for the specified room from the online key backup
790 : /// and stores it.
791 1 : Future<void> loadSingleKey(String roomId, String sessionId) async {
792 1 : final info = await getRoomKeysBackupInfo();
793 : final ret =
794 3 : await client.getRoomKeyBySessionId(roomId, sessionId, info.version);
795 2 : final keys = RoomKeys.fromJson({
796 1 : 'rooms': {
797 1 : roomId: {
798 1 : 'sessions': {
799 1 : sessionId: ret.toJson(),
800 : },
801 : },
802 : },
803 : });
804 1 : await loadFromResponse(keys);
805 : }
806 :
807 : /// Request a certain key from another device
808 3 : Future<void> request(
809 : Room room,
810 : String sessionId,
811 : String? senderKey, {
812 : bool tryOnlineBackup = true,
813 : bool onlineKeyBackupOnly = false,
814 : }) async {
815 2 : if (tryOnlineBackup && await isCached()) {
816 : // let's first check our online key backup store thingy...
817 2 : final hadPreviously = getInboundGroupSession(room.id, sessionId) != null;
818 : try {
819 2 : await loadSingleKey(room.id, sessionId);
820 : } catch (err, stacktrace) {
821 0 : if (err is MatrixException && err.errcode == 'M_NOT_FOUND') {
822 0 : Logs().i(
823 : '[KeyManager] Key not in online key backup, requesting it from other devices...',
824 : );
825 : } else {
826 0 : Logs().e(
827 : '[KeyManager] Failed to access online key backup',
828 : err,
829 : stacktrace,
830 : );
831 : }
832 : }
833 : // TODO: also don't request from others if we have an index of 0 now
834 : if (!hadPreviously &&
835 2 : getInboundGroupSession(room.id, sessionId) != null) {
836 : return; // we managed to load the session from online backup, no need to care about it now
837 : }
838 : }
839 : if (onlineKeyBackupOnly) {
840 : return; // we only want to do the online key backup
841 : }
842 : try {
843 : // while we just send the to-device event to '*', we still need to save the
844 : // devices themself to know where to send the cancel to after receiving a reply
845 2 : final devices = await room.getUserDeviceKeys();
846 4 : final requestId = client.generateUniqueTransactionId();
847 2 : final request = KeyManagerKeyShareRequest(
848 : requestId: requestId,
849 : devices: devices,
850 : room: room,
851 : sessionId: sessionId,
852 : );
853 2 : final userList = await room.requestParticipants();
854 4 : await client.sendToDevicesOfUserIds(
855 6 : userList.map<String>((u) => u.id).toSet(),
856 : EventTypes.RoomKeyRequest,
857 2 : {
858 : 'action': 'request',
859 2 : 'body': {
860 2 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
861 4 : 'room_id': room.id,
862 2 : 'session_id': sessionId,
863 2 : if (senderKey != null) 'sender_key': senderKey,
864 : },
865 : 'request_id': requestId,
866 4 : 'requesting_device_id': client.deviceID,
867 : },
868 : );
869 6 : outgoingShareRequests[request.requestId] = request;
870 : } catch (e, s) {
871 0 : Logs().e('[Key Manager] Sending key verification request failed', e, s);
872 : }
873 : }
874 :
875 : Future<void>? _uploadingFuture;
876 :
877 24 : void startAutoUploadKeys() {
878 144 : _uploadKeysOnSync = encryption.client.onSync.stream.listen(
879 48 : (_) async => uploadInboundGroupSessions(skipIfInProgress: true),
880 : );
881 : }
882 :
883 : /// This task should be performed after sync processing but should not block
884 : /// the sync. To make sure that it never gets executed multiple times, it is
885 : /// skipped when an upload task is already in progress. Set `skipIfInProgress`
886 : /// to `false` to await the pending upload task instead.
887 24 : Future<void> uploadInboundGroupSessions({
888 : bool skipIfInProgress = false,
889 : }) async {
890 48 : final database = client.database;
891 48 : final userID = client.userID;
892 : if (database == null || userID == null) {
893 : return;
894 : }
895 :
896 : // Make sure to not run in parallel
897 23 : if (_uploadingFuture != null) {
898 : if (skipIfInProgress) return;
899 : try {
900 0 : await _uploadingFuture;
901 : } finally {
902 : // shouldn't be necessary, since it will be unset already by the other process that started it, but just to be safe, also unset the future here
903 0 : _uploadingFuture = null;
904 : }
905 : }
906 :
907 23 : Future<void> uploadInternal() async {
908 : try {
909 46 : await client.userDeviceKeysLoading;
910 :
911 23 : if (!(await isCached())) {
912 : return; // we can't backup anyways
913 : }
914 5 : final dbSessions = await database.getInboundGroupSessionsToUpload();
915 5 : if (dbSessions.isEmpty) {
916 : return; // nothing to do
917 : }
918 : final privateKey =
919 20 : base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
920 : // decryption is needed to calculate the public key and thus see if the claimed information is in fact valid
921 5 : final decryption = olm.PkDecryption();
922 5 : final info = await getRoomKeysBackupInfo(false);
923 : String backupPubKey;
924 : try {
925 5 : backupPubKey = decryption.init_with_private_key(privateKey);
926 :
927 10 : if (info.algorithm !=
928 : BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
929 15 : info.authData['public_key'] != backupPubKey) {
930 1 : decryption.free();
931 : return;
932 : }
933 4 : final args = GenerateUploadKeysArgs(
934 : pubkey: backupPubKey,
935 4 : dbSessions: <DbInboundGroupSessionBundle>[],
936 : userId: userID,
937 : );
938 : // we need to calculate verified beforehand, as else we pass a closure to an isolate
939 : // with 500 keys they do, however, noticably block the UI, which is why we give brief async suspentions in here
940 : // so that the event loop can progress
941 : var i = 0;
942 8 : for (final dbSession in dbSessions) {
943 : final device =
944 12 : client.getUserDeviceKeysByCurve25519Key(dbSession.senderKey);
945 8 : args.dbSessions.add(
946 4 : DbInboundGroupSessionBundle(
947 : dbSession: dbSession,
948 4 : verified: device?.verified ?? false,
949 : ),
950 : );
951 4 : i++;
952 4 : if (i > 10) {
953 0 : await Future.delayed(Duration(milliseconds: 1));
954 : i = 0;
955 : }
956 : }
957 : final roomKeys =
958 12 : await client.nativeImplementations.generateUploadKeys(args);
959 16 : Logs().i('[Key Manager] Uploading ${dbSessions.length} room keys...');
960 : // upload the payload...
961 12 : await client.putRoomKeys(info.version, roomKeys);
962 : // and now finally mark all the keys as uploaded
963 : // no need to optimze this, as we only run it so seldomly and almost never with many keys at once
964 8 : for (final dbSession in dbSessions) {
965 4 : await database.markInboundGroupSessionAsUploaded(
966 4 : dbSession.roomId,
967 4 : dbSession.sessionId,
968 : );
969 : }
970 : } finally {
971 5 : decryption.free();
972 : }
973 : } catch (e, s) {
974 4 : Logs().e('[Key Manager] Error uploading room keys', e, s);
975 : }
976 : }
977 :
978 46 : _uploadingFuture = uploadInternal();
979 : try {
980 23 : await _uploadingFuture;
981 : } finally {
982 23 : _uploadingFuture = null;
983 : }
984 : }
985 :
986 : /// Handle an incoming to_device event that is related to key sharing
987 23 : Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
988 46 : if (event.type == EventTypes.RoomKeyRequest) {
989 3 : if (event.content['request_id'] is! String) {
990 : return; // invalid event
991 : }
992 3 : if (event.content['action'] == 'request') {
993 : // we are *receiving* a request
994 2 : Logs().i(
995 4 : '[KeyManager] Received key sharing request from ${event.sender}:${event.content['requesting_device_id']}...',
996 : );
997 2 : if (!event.content.containsKey('body')) {
998 2 : Logs().w('[KeyManager] No body, doing nothing');
999 : return; // no body
1000 : }
1001 2 : final body = event.content.tryGetMap<String, Object?>('body');
1002 : if (body == null) {
1003 0 : Logs().w('[KeyManager] Wrong type for body, doing nothing');
1004 : return; // wrong type for body
1005 : }
1006 1 : final roomId = body.tryGet<String>('room_id');
1007 : if (roomId == null) {
1008 0 : Logs().w(
1009 : '[KeyManager] Wrong type for room_id or no room_id, doing nothing',
1010 : );
1011 : return; // wrong type for roomId or no roomId found
1012 : }
1013 4 : final device = client.userDeviceKeys[event.sender]
1014 4 : ?.deviceKeys[event.content['requesting_device_id']];
1015 : if (device == null) {
1016 2 : Logs().w('[KeyManager] Device not found, doing nothing');
1017 : return; // device not found
1018 : }
1019 4 : if (device.userId == client.userID &&
1020 4 : device.deviceId == client.deviceID) {
1021 0 : Logs().i('[KeyManager] Request is by ourself, ignoring');
1022 : return; // ignore requests by ourself
1023 : }
1024 2 : final room = client.getRoomById(roomId);
1025 : if (room == null) {
1026 2 : Logs().i('[KeyManager] Unknown room, ignoring');
1027 : return; // unknown room
1028 : }
1029 1 : final sessionId = body.tryGet<String>('session_id');
1030 : if (sessionId == null) {
1031 0 : Logs().w(
1032 : '[KeyManager] Wrong type for session_id or no session_id, doing nothing',
1033 : );
1034 : return; // wrong type for session_id
1035 : }
1036 : // okay, let's see if we have this session at all
1037 2 : final session = await loadInboundGroupSession(room.id, sessionId);
1038 : if (session == null) {
1039 2 : Logs().i('[KeyManager] Unknown session, ignoring');
1040 : return; // we don't have this session anyways
1041 : }
1042 3 : if (event.content['request_id'] is! String) {
1043 0 : Logs().w(
1044 : '[KeyManager] Wrong type for request_id or no request_id, doing nothing',
1045 : );
1046 : return; // wrong type for request_id
1047 : }
1048 1 : final request = KeyManagerKeyShareRequest(
1049 2 : requestId: event.content.tryGet<String>('request_id')!,
1050 1 : devices: [device],
1051 : room: room,
1052 : sessionId: sessionId,
1053 : );
1054 3 : if (incomingShareRequests.containsKey(request.requestId)) {
1055 0 : Logs().i('[KeyManager] Already processed this request, ignoring');
1056 : return; // we don't want to process one and the same request multiple times
1057 : }
1058 3 : incomingShareRequests[request.requestId] = request;
1059 : final roomKeyRequest =
1060 1 : RoomKeyRequest.fromToDeviceEvent(event, this, request);
1061 4 : if (device.userId == client.userID &&
1062 1 : device.verified &&
1063 1 : !device.blocked) {
1064 2 : Logs().i('[KeyManager] All checks out, forwarding key...');
1065 : // alright, we can forward the key
1066 1 : await roomKeyRequest.forwardKey();
1067 1 : } else if (device.encryptToDevice &&
1068 1 : session.allowedAtIndex
1069 2 : .tryGet<Map<String, Object?>>(device.userId)
1070 2 : ?.tryGet(device.curve25519Key!) !=
1071 : null) {
1072 : // if we know the user may see the message, then we can just forward the key.
1073 : // we do not need to check if the device is verified, just if it is not blocked,
1074 : // as that is the logic we already initially try to send out the room keys.
1075 : final index =
1076 5 : session.allowedAtIndex[device.userId]![device.curve25519Key]!;
1077 2 : Logs().i(
1078 1 : '[KeyManager] Valid foreign request, forwarding key at index $index...',
1079 : );
1080 1 : await roomKeyRequest.forwardKey(index);
1081 : } else {
1082 1 : Logs()
1083 1 : .i('[KeyManager] Asking client, if the key should be forwarded');
1084 2 : client.onRoomKeyRequest
1085 1 : .add(roomKeyRequest); // let the client handle this
1086 : }
1087 0 : } else if (event.content['action'] == 'request_cancellation') {
1088 : // we got told to cancel an incoming request
1089 0 : if (!incomingShareRequests.containsKey(event.content['request_id'])) {
1090 : return; // we don't know this request anyways
1091 : }
1092 : // alright, let's just cancel this request
1093 0 : final request = incomingShareRequests[event.content['request_id']]!;
1094 0 : request.canceled = true;
1095 0 : incomingShareRequests.remove(request.requestId);
1096 : }
1097 46 : } else if (event.type == EventTypes.ForwardedRoomKey) {
1098 : // we *received* an incoming key request
1099 1 : final encryptedContent = event.encryptedContent;
1100 : if (encryptedContent == null) {
1101 2 : Logs().w(
1102 : 'Ignoring an unencrypted forwarded key from a to device message',
1103 1 : event.toJson(),
1104 : );
1105 : return;
1106 : }
1107 3 : final request = outgoingShareRequests.values.firstWhereOrNull(
1108 1 : (r) =>
1109 5 : r.room.id == event.content['room_id'] &&
1110 4 : r.sessionId == event.content['session_id'],
1111 : );
1112 1 : if (request == null || request.canceled) {
1113 : return; // no associated request found or it got canceled
1114 : }
1115 2 : final device = request.devices.firstWhereOrNull(
1116 1 : (d) =>
1117 3 : d.userId == event.sender &&
1118 3 : d.curve25519Key == encryptedContent['sender_key'],
1119 : );
1120 : if (device == null) {
1121 : return; // someone we didn't send our request to replied....better ignore this
1122 : }
1123 : // we add the sender key to the forwarded key chain
1124 3 : if (event.content['forwarding_curve25519_key_chain'] is! List) {
1125 0 : event.content['forwarding_curve25519_key_chain'] = <String>[];
1126 : }
1127 2 : (event.content['forwarding_curve25519_key_chain'] as List)
1128 2 : .add(encryptedContent['sender_key']);
1129 3 : if (event.content['sender_claimed_ed25519_key'] is! String) {
1130 0 : Logs().w('sender_claimed_ed255519_key has wrong type');
1131 : return; // wrong type
1132 : }
1133 : // TODO: verify that the keys work to decrypt a message
1134 : // alright, all checks out, let's go ahead and store this session
1135 1 : await setInboundGroupSession(
1136 2 : request.room.id,
1137 1 : request.sessionId,
1138 1 : device.curve25519Key!,
1139 1 : event.content,
1140 : forwarded: true,
1141 1 : senderClaimedKeys: {
1142 2 : 'ed25519': event.content['sender_claimed_ed25519_key'] as String,
1143 : },
1144 : );
1145 2 : request.devices.removeWhere(
1146 7 : (k) => k.userId == device.userId && k.deviceId == device.deviceId,
1147 : );
1148 3 : outgoingShareRequests.remove(request.requestId);
1149 : // send cancel to all other devices
1150 2 : if (request.devices.isEmpty) {
1151 : return; // no need to send any cancellation
1152 : }
1153 : // Send with send-to-device messaging
1154 1 : final sendToDeviceMessage = {
1155 : 'action': 'request_cancellation',
1156 1 : 'request_id': request.requestId,
1157 2 : 'requesting_device_id': client.deviceID,
1158 : };
1159 1 : final data = <String, Map<String, Map<String, dynamic>>>{};
1160 2 : for (final device in request.devices) {
1161 3 : final userData = data[device.userId] ??= {};
1162 2 : userData[device.deviceId!] = sendToDeviceMessage;
1163 : }
1164 2 : await client.sendToDevice(
1165 : EventTypes.RoomKeyRequest,
1166 2 : client.generateUniqueTransactionId(),
1167 : data,
1168 : );
1169 46 : } else if (event.type == EventTypes.RoomKey) {
1170 46 : Logs().v(
1171 69 : '[KeyManager] Received room key with session ${event.content['session_id']}',
1172 : );
1173 23 : final encryptedContent = event.encryptedContent;
1174 : if (encryptedContent == null) {
1175 2 : Logs().v('[KeyManager] not encrypted, ignoring...');
1176 : return; // the event wasn't encrypted, this is a security risk;
1177 : }
1178 46 : final roomId = event.content.tryGet<String>('room_id');
1179 46 : final sessionId = event.content.tryGet<String>('session_id');
1180 : if (roomId == null || sessionId == null) {
1181 0 : Logs().w(
1182 : 'Either room_id or session_id are not the expected type or missing',
1183 : );
1184 : return;
1185 : }
1186 92 : final sender_ed25519 = client.userDeviceKeys[event.sender]
1187 4 : ?.deviceKeys[event.content['requesting_device_id']]?.ed25519Key;
1188 : if (sender_ed25519 != null) {
1189 0 : event.content['sender_claimed_ed25519_key'] = sender_ed25519;
1190 : }
1191 46 : Logs().v('[KeyManager] Keeping room key');
1192 23 : await setInboundGroupSession(
1193 : roomId,
1194 : sessionId,
1195 23 : encryptedContent['sender_key'],
1196 23 : event.content,
1197 : forwarded: false,
1198 : );
1199 : }
1200 : }
1201 :
1202 : StreamSubscription<SyncUpdate>? _uploadKeysOnSync;
1203 :
1204 21 : void dispose() {
1205 : // ignore: discarded_futures
1206 42 : _uploadKeysOnSync?.cancel();
1207 46 : for (final sess in _outboundGroupSessions.values) {
1208 4 : sess.dispose();
1209 : }
1210 62 : for (final entries in _inboundGroupSessions.values) {
1211 40 : for (final sess in entries.values) {
1212 20 : sess.dispose();
1213 : }
1214 : }
1215 : }
1216 : }
1217 :
1218 : class KeyManagerKeyShareRequest {
1219 : final String requestId;
1220 : final List<DeviceKeys> devices;
1221 : final Room room;
1222 : final String sessionId;
1223 : bool canceled;
1224 :
1225 2 : KeyManagerKeyShareRequest({
1226 : required this.requestId,
1227 : List<DeviceKeys>? devices,
1228 : required this.room,
1229 : required this.sessionId,
1230 : this.canceled = false,
1231 0 : }) : devices = devices ?? [];
1232 : }
1233 :
1234 : class RoomKeyRequest extends ToDeviceEvent {
1235 : KeyManager keyManager;
1236 : KeyManagerKeyShareRequest request;
1237 :
1238 1 : RoomKeyRequest.fromToDeviceEvent(
1239 : ToDeviceEvent toDeviceEvent,
1240 : this.keyManager,
1241 : this.request,
1242 1 : ) : super(
1243 1 : sender: toDeviceEvent.sender,
1244 1 : content: toDeviceEvent.content,
1245 1 : type: toDeviceEvent.type,
1246 : );
1247 :
1248 3 : Room get room => request.room;
1249 :
1250 4 : DeviceKeys get requestingDevice => request.devices.first;
1251 :
1252 1 : Future<void> forwardKey([int? index]) async {
1253 2 : if (request.canceled) {
1254 0 : keyManager.incomingShareRequests.remove(request.requestId);
1255 : return; // request is canceled, don't send anything
1256 : }
1257 1 : final room = this.room;
1258 : final session =
1259 5 : await keyManager.loadInboundGroupSession(room.id, request.sessionId);
1260 1 : if (session?.inboundGroupSession == null) {
1261 0 : Logs().v("[KeyManager] Not forwarding key we don't have");
1262 : return;
1263 : }
1264 :
1265 2 : final message = session!.content.copy();
1266 1 : message['forwarding_curve25519_key_chain'] =
1267 2 : List<String>.from(session.forwardingCurve25519KeyChain);
1268 :
1269 2 : if (session.senderKey.isNotEmpty) {
1270 2 : message['sender_key'] = session.senderKey;
1271 : }
1272 1 : message['sender_claimed_ed25519_key'] =
1273 2 : session.senderClaimedKeys['ed25519'] ??
1274 2 : (session.forwardingCurve25519KeyChain.isEmpty
1275 3 : ? keyManager.encryption.fingerprintKey
1276 : : null);
1277 3 : message['session_key'] = session.inboundGroupSession!.export_session(
1278 2 : index ?? session.inboundGroupSession!.first_known_index(),
1279 : );
1280 : // send the actual reply of the key back to the requester
1281 3 : await keyManager.client.sendToDeviceEncrypted(
1282 2 : [requestingDevice],
1283 : EventTypes.ForwardedRoomKey,
1284 : message,
1285 : );
1286 5 : keyManager.incomingShareRequests.remove(request.requestId);
1287 : }
1288 : }
1289 :
1290 : /// you would likely want to use [NativeImplementations] and
1291 : /// [Client.nativeImplementations] instead
1292 4 : RoomKeys generateUploadKeysImplementation(GenerateUploadKeysArgs args) {
1293 4 : final enc = olm.PkEncryption();
1294 : try {
1295 8 : enc.set_recipient_key(args.pubkey);
1296 : // first we generate the payload to upload all the session keys in this chunk
1297 8 : final roomKeys = RoomKeys(rooms: {});
1298 8 : for (final dbSession in args.dbSessions) {
1299 12 : final sess = SessionKey.fromDb(dbSession.dbSession, args.userId);
1300 4 : if (!sess.isValid) {
1301 : continue;
1302 : }
1303 : // create the room if it doesn't exist
1304 : final roomKeyBackup =
1305 20 : roomKeys.rooms[sess.roomId] ??= RoomKeyBackup(sessions: {});
1306 : // generate the encrypted content
1307 4 : final payload = <String, dynamic>{
1308 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
1309 4 : 'forwarding_curve25519_key_chain': sess.forwardingCurve25519KeyChain,
1310 4 : 'sender_key': sess.senderKey,
1311 4 : 'sender_claimed_keys': sess.senderClaimedKeys,
1312 4 : 'session_key': sess.inboundGroupSession!
1313 12 : .export_session(sess.inboundGroupSession!.first_known_index()),
1314 : };
1315 : // encrypt the content
1316 8 : final encrypted = enc.encrypt(json.encode(payload));
1317 : // fetch the device, if available...
1318 : //final device = args.client.getUserDeviceKeysByCurve25519Key(sess.senderKey);
1319 : // aaaand finally add the session key to our payload
1320 16 : roomKeyBackup.sessions[sess.sessionId] = KeyBackupData(
1321 8 : firstMessageIndex: sess.inboundGroupSession!.first_known_index(),
1322 8 : forwardedCount: sess.forwardingCurve25519KeyChain.length,
1323 4 : isVerified: dbSession.verified, //device?.verified ?? false,
1324 4 : sessionData: {
1325 4 : 'ephemeral': encrypted.ephemeral,
1326 4 : 'ciphertext': encrypted.ciphertext,
1327 4 : 'mac': encrypted.mac,
1328 : },
1329 : );
1330 : }
1331 4 : enc.free();
1332 : return roomKeys;
1333 : } catch (e, s) {
1334 0 : Logs().e('[Key Manager] Error generating payload', e, s);
1335 0 : enc.free();
1336 : rethrow;
1337 : }
1338 : }
1339 :
1340 : class DbInboundGroupSessionBundle {
1341 4 : DbInboundGroupSessionBundle({
1342 : required this.dbSession,
1343 : required this.verified,
1344 : });
1345 :
1346 0 : factory DbInboundGroupSessionBundle.fromJson(Map<dynamic, dynamic> json) =>
1347 0 : DbInboundGroupSessionBundle(
1348 : dbSession:
1349 0 : StoredInboundGroupSession.fromJson(Map.from(json['dbSession'])),
1350 0 : verified: json['verified'],
1351 : );
1352 :
1353 0 : Map<String, Object> toJson() => {
1354 0 : 'dbSession': dbSession.toJson(),
1355 0 : 'verified': verified,
1356 : };
1357 : StoredInboundGroupSession dbSession;
1358 : bool verified;
1359 : }
1360 :
1361 : class GenerateUploadKeysArgs {
1362 4 : GenerateUploadKeysArgs({
1363 : required this.pubkey,
1364 : required this.dbSessions,
1365 : required this.userId,
1366 : });
1367 :
1368 0 : factory GenerateUploadKeysArgs.fromJson(Map<dynamic, dynamic> json) =>
1369 0 : GenerateUploadKeysArgs(
1370 0 : pubkey: json['pubkey'],
1371 0 : dbSessions: (json['dbSessions'] as Iterable)
1372 0 : .map((e) => DbInboundGroupSessionBundle.fromJson(e))
1373 0 : .toList(),
1374 0 : userId: json['userId'],
1375 : );
1376 :
1377 0 : Map<String, Object> toJson() => {
1378 0 : 'pubkey': pubkey,
1379 0 : 'dbSessions': dbSessions.map((e) => e.toJson()).toList(),
1380 0 : 'userId': userId,
1381 : };
1382 :
1383 : String pubkey;
1384 : List<DbInboundGroupSessionBundle> dbSessions;
1385 : String userId;
1386 : }
|