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 : return roomInboundGroupSessions[sessionId] = dbSess;
293 : }
294 :
295 5 : Map<String, Map<String, bool>> _getDeviceKeyIdMap(
296 : List<DeviceKeys> deviceKeys,
297 : ) {
298 5 : final deviceKeyIds = <String, Map<String, bool>>{};
299 8 : for (final device in deviceKeys) {
300 3 : final deviceId = device.deviceId;
301 : if (deviceId == null) {
302 0 : Logs().w('[KeyManager] ignoring device without deviceid');
303 : continue;
304 : }
305 9 : final userDeviceKeyIds = deviceKeyIds[device.userId] ??= <String, bool>{};
306 6 : userDeviceKeyIds[deviceId] = !device.encryptToDevice;
307 : }
308 : return deviceKeyIds;
309 : }
310 :
311 : /// clear all cached inbound group sessions. useful for testing
312 3 : void clearOutboundGroupSessions() {
313 6 : _outboundGroupSessions.clear();
314 : }
315 :
316 : /// Clears the existing outboundGroupSession but first checks if the participating
317 : /// devices have been changed. Returns false if the session has not been cleared because
318 : /// it wasn't necessary. Otherwise returns true.
319 5 : Future<bool> clearOrUseOutboundGroupSession(
320 : String roomId, {
321 : bool wipe = false,
322 : bool use = true,
323 : }) async {
324 10 : final room = client.getRoomById(roomId);
325 5 : final sess = getOutboundGroupSession(roomId);
326 4 : if (room == null || sess == null || sess.outboundGroupSession == null) {
327 : return true;
328 : }
329 :
330 : if (!wipe) {
331 : // first check if it needs to be rotated
332 : final encryptionContent =
333 6 : room.getState(EventTypes.Encryption)?.parsedRoomEncryptionContent;
334 3 : final maxMessages = encryptionContent?.rotationPeriodMsgs ?? 100;
335 3 : final maxAge = encryptionContent?.rotationPeriodMs ??
336 : 604800000; // default of one week
337 6 : if ((sess.sentMessages ?? maxMessages) >= maxMessages ||
338 3 : sess.creationTime
339 6 : .add(Duration(milliseconds: maxAge))
340 6 : .isBefore(DateTime.now())) {
341 : wipe = true;
342 : }
343 : }
344 :
345 4 : final inboundSess = await loadInboundGroupSession(
346 4 : room.id,
347 8 : sess.outboundGroupSession!.session_id(),
348 : );
349 : if (inboundSess == null) {
350 0 : Logs().w('No inbound megolm session found for outbound session!');
351 0 : assert(inboundSess != null);
352 : wipe = true;
353 : }
354 :
355 : if (!wipe) {
356 : // next check if the devices in the room changed
357 3 : final devicesToReceive = <DeviceKeys>[];
358 3 : final newDeviceKeys = await room.getUserDeviceKeys();
359 3 : final newDeviceKeyIds = _getDeviceKeyIdMap(newDeviceKeys);
360 : // first check for user differences
361 9 : final oldUserIds = sess.devices.keys.toSet();
362 6 : final newUserIds = newDeviceKeyIds.keys.toSet();
363 6 : if (oldUserIds.difference(newUserIds).isNotEmpty) {
364 : // a user left the room, we must wipe the session
365 : wipe = true;
366 : } else {
367 3 : final newUsers = newUserIds.difference(oldUserIds);
368 3 : if (newUsers.isNotEmpty) {
369 : // new user! Gotta send the megolm session to them
370 : devicesToReceive
371 5 : .addAll(newDeviceKeys.where((d) => newUsers.contains(d.userId)));
372 : }
373 : // okay, now we must test all the individual user devices, if anything new got blocked
374 : // or if we need to send to any new devices.
375 : // 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.
376 : // we also know that all the old user IDs appear in the old one, else we have already wiped the session
377 5 : for (final userId in oldUserIds) {
378 4 : final oldBlockedDevices = sess.devices.containsKey(userId)
379 6 : ? sess.devices[userId]!.entries
380 6 : .where((e) => e.value)
381 2 : .map((e) => e.key)
382 2 : .toSet()
383 : : <String>{};
384 2 : final newBlockedDevices = newDeviceKeyIds.containsKey(userId)
385 2 : ? newDeviceKeyIds[userId]!
386 2 : .entries
387 6 : .where((e) => e.value)
388 4 : .map((e) => e.key)
389 2 : .toSet()
390 : : <String>{};
391 : // 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
392 : // check if new devices got blocked
393 4 : if (newBlockedDevices.difference(oldBlockedDevices).isNotEmpty) {
394 : wipe = true;
395 : break;
396 : }
397 : // and now add all the new devices!
398 4 : final oldDeviceIds = sess.devices.containsKey(userId)
399 6 : ? sess.devices[userId]!.entries
400 6 : .where((e) => !e.value)
401 6 : .map((e) => e.key)
402 2 : .toSet()
403 : : <String>{};
404 2 : final newDeviceIds = newDeviceKeyIds.containsKey(userId)
405 2 : ? newDeviceKeyIds[userId]!
406 2 : .entries
407 6 : .where((e) => !e.value)
408 6 : .map((e) => e.key)
409 2 : .toSet()
410 : : <String>{};
411 :
412 : // check if a device got removed
413 4 : if (oldDeviceIds.difference(newDeviceIds).isNotEmpty) {
414 : wipe = true;
415 : break;
416 : }
417 :
418 : // check if any new devices need keys
419 2 : final newDevices = newDeviceIds.difference(oldDeviceIds);
420 2 : if (newDeviceIds.isNotEmpty) {
421 2 : devicesToReceive.addAll(
422 2 : newDeviceKeys.where(
423 10 : (d) => d.userId == userId && newDevices.contains(d.deviceId),
424 : ),
425 : );
426 : }
427 : }
428 : }
429 :
430 : if (!wipe) {
431 : if (!use) {
432 : return false;
433 : }
434 : // okay, we use the outbound group session!
435 3 : sess.devices = newDeviceKeyIds;
436 3 : final rawSession = <String, dynamic>{
437 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
438 3 : 'room_id': room.id,
439 6 : 'session_id': sess.outboundGroupSession!.session_id(),
440 6 : 'session_key': sess.outboundGroupSession!.session_key(),
441 : };
442 : try {
443 5 : devicesToReceive.removeWhere((k) => !k.encryptToDevice);
444 3 : if (devicesToReceive.isNotEmpty) {
445 : // update allowedAtIndex
446 2 : for (final device in devicesToReceive) {
447 4 : inboundSess!.allowedAtIndex[device.userId] ??= <String, int>{};
448 3 : if (!inboundSess.allowedAtIndex[device.userId]!
449 2 : .containsKey(device.curve25519Key) ||
450 0 : inboundSess.allowedAtIndex[device.userId]![
451 0 : device.curve25519Key]! >
452 0 : sess.outboundGroupSession!.message_index()) {
453 : inboundSess
454 5 : .allowedAtIndex[device.userId]![device.curve25519Key!] =
455 2 : sess.outboundGroupSession!.message_index();
456 : }
457 : }
458 3 : await client.database?.updateInboundGroupSessionAllowedAtIndex(
459 2 : json.encode(inboundSess!.allowedAtIndex),
460 1 : room.id,
461 2 : sess.outboundGroupSession!.session_id(),
462 : );
463 : // send out the key
464 2 : await client.sendToDeviceEncryptedChunked(
465 : devicesToReceive,
466 : EventTypes.RoomKey,
467 : rawSession,
468 : );
469 : }
470 : } catch (e, s) {
471 0 : Logs().e(
472 : '[LibOlm] Unable to re-send the session key at later index to new devices',
473 : e,
474 : s,
475 : );
476 : }
477 : return false;
478 : }
479 : }
480 2 : sess.dispose();
481 4 : _outboundGroupSessions.remove(roomId);
482 6 : await client.database?.removeOutboundGroupSession(roomId);
483 : return true;
484 : }
485 :
486 : /// Store an outbound group session in the database
487 5 : Future<void> storeOutboundGroupSession(
488 : String roomId,
489 : OutboundGroupSession sess,
490 : ) async {
491 10 : final userID = client.userID;
492 : if (userID == null) return;
493 15 : await client.database?.storeOutboundGroupSession(
494 : roomId,
495 10 : sess.outboundGroupSession!.pickle(userID),
496 10 : json.encode(sess.devices),
497 10 : sess.creationTime.millisecondsSinceEpoch,
498 : );
499 : }
500 :
501 : final Map<String, Future<OutboundGroupSession>>
502 : _pendingNewOutboundGroupSessions = {};
503 :
504 : /// Creates an outbound group session for a given room id
505 5 : Future<OutboundGroupSession> createOutboundGroupSession(String roomId) async {
506 10 : final sess = _pendingNewOutboundGroupSessions[roomId];
507 : if (sess != null) {
508 : return sess;
509 : }
510 10 : final newSess = _pendingNewOutboundGroupSessions[roomId] =
511 5 : _createOutboundGroupSession(roomId);
512 :
513 : try {
514 : await newSess;
515 : } finally {
516 5 : _pendingNewOutboundGroupSessions
517 15 : .removeWhere((_, value) => value == newSess);
518 : }
519 :
520 : return newSess;
521 : }
522 :
523 : /// Prepares an outbound group session for a given room ID. That is, load it from
524 : /// the database, cycle it if needed and create it if absent.
525 1 : Future<void> prepareOutboundGroupSession(String roomId) async {
526 1 : if (getOutboundGroupSession(roomId) == null) {
527 0 : await loadOutboundGroupSession(roomId);
528 : }
529 1 : await clearOrUseOutboundGroupSession(roomId, use: false);
530 1 : if (getOutboundGroupSession(roomId) == null) {
531 1 : await createOutboundGroupSession(roomId);
532 : }
533 : }
534 :
535 5 : Future<OutboundGroupSession> _createOutboundGroupSession(
536 : String roomId,
537 : ) async {
538 5 : await clearOrUseOutboundGroupSession(roomId, wipe: true);
539 10 : await client.firstSyncReceived;
540 10 : final room = client.getRoomById(roomId);
541 : if (room == null) {
542 0 : throw Exception(
543 0 : 'Tried to create a megolm session in a non-existing room ($roomId)!',
544 : );
545 : }
546 10 : final userID = client.userID;
547 : if (userID == null) {
548 0 : throw Exception(
549 : 'Tried to create a megolm session without being logged in!',
550 : );
551 : }
552 :
553 5 : final deviceKeys = await room.getUserDeviceKeys();
554 5 : final deviceKeyIds = _getDeviceKeyIdMap(deviceKeys);
555 11 : deviceKeys.removeWhere((k) => !k.encryptToDevice);
556 5 : final outboundGroupSession = olm.OutboundGroupSession();
557 : try {
558 5 : outboundGroupSession.create();
559 : } catch (e, s) {
560 0 : outboundGroupSession.free();
561 0 : Logs().e('[LibOlm] Unable to create new outboundGroupSession', e, s);
562 : rethrow;
563 : }
564 5 : final rawSession = <String, dynamic>{
565 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
566 5 : 'room_id': room.id,
567 5 : 'session_id': outboundGroupSession.session_id(),
568 5 : 'session_key': outboundGroupSession.session_key(),
569 : };
570 5 : final allowedAtIndex = <String, Map<String, int>>{};
571 8 : for (final device in deviceKeys) {
572 3 : if (!device.isValid) {
573 0 : Logs().e('Skipping invalid device');
574 : continue;
575 : }
576 9 : allowedAtIndex[device.userId] ??= <String, int>{};
577 12 : allowedAtIndex[device.userId]![device.curve25519Key!] =
578 3 : outboundGroupSession.message_index();
579 : }
580 5 : await setInboundGroupSession(
581 : roomId,
582 5 : rawSession['session_id'],
583 10 : encryption.identityKey!,
584 : rawSession,
585 : allowedAtIndex: allowedAtIndex,
586 : );
587 5 : final sess = OutboundGroupSession(
588 : devices: deviceKeyIds,
589 5 : creationTime: DateTime.now(),
590 : outboundGroupSession: outboundGroupSession,
591 : key: userID,
592 : );
593 : try {
594 10 : await client.sendToDeviceEncryptedChunked(
595 : deviceKeys,
596 : EventTypes.RoomKey,
597 : rawSession,
598 : );
599 5 : await storeOutboundGroupSession(roomId, sess);
600 10 : _outboundGroupSessions[roomId] = sess;
601 : } catch (e, s) {
602 0 : Logs().e(
603 : '[LibOlm] Unable to send the session key to the participating devices',
604 : e,
605 : s,
606 : );
607 0 : sess.dispose();
608 : rethrow;
609 : }
610 : return sess;
611 : }
612 :
613 : /// Get an outbound group session for a room id
614 5 : OutboundGroupSession? getOutboundGroupSession(String roomId) {
615 10 : return _outboundGroupSessions[roomId];
616 : }
617 :
618 : /// Load an outbound group session from database
619 3 : Future<void> loadOutboundGroupSession(String roomId) async {
620 6 : final database = client.database;
621 6 : final userID = client.userID;
622 6 : if (_loadedOutboundGroupSessions.contains(roomId) ||
623 6 : _outboundGroupSessions.containsKey(roomId) ||
624 : database == null ||
625 : userID == null) {
626 : return; // nothing to do
627 : }
628 6 : _loadedOutboundGroupSessions.add(roomId);
629 3 : final sess = await database.getOutboundGroupSession(
630 : roomId,
631 : userID,
632 : );
633 1 : if (sess == null || !sess.isValid) {
634 : return;
635 : }
636 2 : _outboundGroupSessions[roomId] = sess;
637 : }
638 :
639 23 : Future<bool> isCached() async {
640 46 : await client.accountDataLoading;
641 23 : if (!enabled) {
642 : return false;
643 : }
644 46 : await client.userDeviceKeysLoading;
645 69 : return (await encryption.ssss.getCached(megolmKey)) != null;
646 : }
647 :
648 : GetRoomKeysVersionCurrentResponse? _roomKeysVersionCache;
649 : DateTime? _roomKeysVersionCacheDate;
650 :
651 5 : Future<GetRoomKeysVersionCurrentResponse> getRoomKeysBackupInfo([
652 : bool useCache = true,
653 : ]) async {
654 5 : if (_roomKeysVersionCache != null &&
655 3 : _roomKeysVersionCacheDate != null &&
656 : useCache &&
657 1 : DateTime.now()
658 2 : .subtract(Duration(minutes: 5))
659 2 : .isBefore(_roomKeysVersionCacheDate!)) {
660 1 : return _roomKeysVersionCache!;
661 : }
662 15 : _roomKeysVersionCache = await client.getRoomKeysVersionCurrent();
663 10 : _roomKeysVersionCacheDate = DateTime.now();
664 5 : return _roomKeysVersionCache!;
665 : }
666 :
667 1 : Future<void> loadFromResponse(RoomKeys keys) async {
668 1 : if (!(await isCached())) {
669 : return;
670 : }
671 : final privateKey =
672 4 : base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
673 1 : final decryption = olm.PkDecryption();
674 1 : final info = await getRoomKeysBackupInfo();
675 : String backupPubKey;
676 : try {
677 1 : backupPubKey = decryption.init_with_private_key(privateKey);
678 :
679 2 : if (info.algorithm != BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
680 3 : info.authData['public_key'] != backupPubKey) {
681 : return;
682 : }
683 3 : for (final roomEntry in keys.rooms.entries) {
684 1 : final roomId = roomEntry.key;
685 4 : for (final sessionEntry in roomEntry.value.sessions.entries) {
686 1 : final sessionId = sessionEntry.key;
687 1 : final session = sessionEntry.value;
688 1 : final sessionData = session.sessionData;
689 : Map<String, Object?>? decrypted;
690 : try {
691 1 : decrypted = json.decode(
692 1 : decryption.decrypt(
693 1 : sessionData['ephemeral'] as String,
694 1 : sessionData['mac'] as String,
695 1 : sessionData['ciphertext'] as String,
696 : ),
697 : );
698 : } catch (e, s) {
699 0 : Logs().e('[LibOlm] Error decrypting room key', e, s);
700 : }
701 1 : final senderKey = decrypted?.tryGet<String>('sender_key');
702 : if (decrypted != null && senderKey != null) {
703 1 : decrypted['session_id'] = sessionId;
704 1 : decrypted['room_id'] = roomId;
705 1 : await setInboundGroupSession(
706 : roomId,
707 : sessionId,
708 : senderKey,
709 : decrypted,
710 : forwarded: true,
711 : senderClaimedKeys:
712 1 : decrypted.tryGetMap<String, String>('sender_claimed_keys') ??
713 0 : <String, String>{},
714 : uploaded: true,
715 : );
716 : }
717 : }
718 : }
719 : } finally {
720 1 : decryption.free();
721 : }
722 : }
723 :
724 : /// Loads and stores all keys from the online key backup. This may take a
725 : /// while for older and big accounts.
726 1 : Future<void> loadAllKeys() async {
727 1 : final info = await getRoomKeysBackupInfo();
728 3 : final ret = await client.getRoomKeys(info.version);
729 1 : await loadFromResponse(ret);
730 : }
731 :
732 : /// Loads all room keys for a single room and stores them. This may take a
733 : /// while for older and big rooms.
734 1 : Future<void> loadAllKeysFromRoom(String roomId) async {
735 1 : final info = await getRoomKeysBackupInfo();
736 3 : final ret = await client.getRoomKeysByRoomId(roomId, info.version);
737 2 : final keys = RoomKeys.fromJson({
738 1 : 'rooms': {
739 1 : roomId: {
740 5 : 'sessions': ret.sessions.map((k, s) => MapEntry(k, s.toJson())),
741 : },
742 : },
743 : });
744 1 : await loadFromResponse(keys);
745 : }
746 :
747 : /// Loads a single key for the specified room from the online key backup
748 : /// and stores it.
749 1 : Future<void> loadSingleKey(String roomId, String sessionId) async {
750 1 : final info = await getRoomKeysBackupInfo();
751 : final ret =
752 3 : await client.getRoomKeyBySessionId(roomId, sessionId, info.version);
753 2 : final keys = RoomKeys.fromJson({
754 1 : 'rooms': {
755 1 : roomId: {
756 1 : 'sessions': {
757 1 : sessionId: ret.toJson(),
758 : },
759 : },
760 : },
761 : });
762 1 : await loadFromResponse(keys);
763 : }
764 :
765 : /// Request a certain key from another device
766 3 : Future<void> request(
767 : Room room,
768 : String sessionId,
769 : String? senderKey, {
770 : bool tryOnlineBackup = true,
771 : bool onlineKeyBackupOnly = false,
772 : }) async {
773 2 : if (tryOnlineBackup && await isCached()) {
774 : // let's first check our online key backup store thingy...
775 2 : final hadPreviously = getInboundGroupSession(room.id, sessionId) != null;
776 : try {
777 2 : await loadSingleKey(room.id, sessionId);
778 : } catch (err, stacktrace) {
779 0 : if (err is MatrixException && err.errcode == 'M_NOT_FOUND') {
780 0 : Logs().i(
781 : '[KeyManager] Key not in online key backup, requesting it from other devices...',
782 : );
783 : } else {
784 0 : Logs().e(
785 : '[KeyManager] Failed to access online key backup',
786 : err,
787 : stacktrace,
788 : );
789 : }
790 : }
791 : // TODO: also don't request from others if we have an index of 0 now
792 : if (!hadPreviously &&
793 2 : getInboundGroupSession(room.id, sessionId) != null) {
794 : return; // we managed to load the session from online backup, no need to care about it now
795 : }
796 : }
797 : if (onlineKeyBackupOnly) {
798 : return; // we only want to do the online key backup
799 : }
800 : try {
801 : // while we just send the to-device event to '*', we still need to save the
802 : // devices themself to know where to send the cancel to after receiving a reply
803 2 : final devices = await room.getUserDeviceKeys();
804 4 : final requestId = client.generateUniqueTransactionId();
805 2 : final request = KeyManagerKeyShareRequest(
806 : requestId: requestId,
807 : devices: devices,
808 : room: room,
809 : sessionId: sessionId,
810 : );
811 2 : final userList = await room.requestParticipants();
812 4 : await client.sendToDevicesOfUserIds(
813 6 : userList.map<String>((u) => u.id).toSet(),
814 : EventTypes.RoomKeyRequest,
815 2 : {
816 : 'action': 'request',
817 2 : 'body': {
818 2 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
819 4 : 'room_id': room.id,
820 2 : 'session_id': sessionId,
821 2 : if (senderKey != null) 'sender_key': senderKey,
822 : },
823 : 'request_id': requestId,
824 4 : 'requesting_device_id': client.deviceID,
825 : },
826 : );
827 6 : outgoingShareRequests[request.requestId] = request;
828 : } catch (e, s) {
829 0 : Logs().e('[Key Manager] Sending key verification request failed', e, s);
830 : }
831 : }
832 :
833 : Future<void>? _uploadingFuture;
834 :
835 24 : void startAutoUploadKeys() {
836 144 : _uploadKeysOnSync = encryption.client.onSync.stream.listen(
837 48 : (_) async => uploadInboundGroupSessions(skipIfInProgress: true),
838 : );
839 : }
840 :
841 : /// This task should be performed after sync processing but should not block
842 : /// the sync. To make sure that it never gets executed multiple times, it is
843 : /// skipped when an upload task is already in progress. Set `skipIfInProgress`
844 : /// to `false` to await the pending upload task instead.
845 24 : Future<void> uploadInboundGroupSessions({
846 : bool skipIfInProgress = false,
847 : }) async {
848 48 : final database = client.database;
849 48 : final userID = client.userID;
850 : if (database == null || userID == null) {
851 : return;
852 : }
853 :
854 : // Make sure to not run in parallel
855 23 : if (_uploadingFuture != null) {
856 : if (skipIfInProgress) return;
857 : try {
858 0 : await _uploadingFuture;
859 : } finally {
860 : // 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
861 0 : _uploadingFuture = null;
862 : }
863 : }
864 :
865 23 : Future<void> uploadInternal() async {
866 : try {
867 46 : await client.userDeviceKeysLoading;
868 :
869 23 : if (!(await isCached())) {
870 : return; // we can't backup anyways
871 : }
872 5 : final dbSessions = await database.getInboundGroupSessionsToUpload();
873 5 : if (dbSessions.isEmpty) {
874 : return; // nothing to do
875 : }
876 : final privateKey =
877 20 : base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
878 : // decryption is needed to calculate the public key and thus see if the claimed information is in fact valid
879 5 : final decryption = olm.PkDecryption();
880 5 : final info = await getRoomKeysBackupInfo(false);
881 : String backupPubKey;
882 : try {
883 5 : backupPubKey = decryption.init_with_private_key(privateKey);
884 :
885 10 : if (info.algorithm !=
886 : BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
887 15 : info.authData['public_key'] != backupPubKey) {
888 1 : decryption.free();
889 : return;
890 : }
891 4 : final args = GenerateUploadKeysArgs(
892 : pubkey: backupPubKey,
893 4 : dbSessions: <DbInboundGroupSessionBundle>[],
894 : userId: userID,
895 : );
896 : // we need to calculate verified beforehand, as else we pass a closure to an isolate
897 : // with 500 keys they do, however, noticably block the UI, which is why we give brief async suspentions in here
898 : // so that the event loop can progress
899 : var i = 0;
900 8 : for (final dbSession in dbSessions) {
901 : final device =
902 12 : client.getUserDeviceKeysByCurve25519Key(dbSession.senderKey);
903 8 : args.dbSessions.add(
904 4 : DbInboundGroupSessionBundle(
905 : dbSession: dbSession,
906 4 : verified: device?.verified ?? false,
907 : ),
908 : );
909 4 : i++;
910 4 : if (i > 10) {
911 0 : await Future.delayed(Duration(milliseconds: 1));
912 : i = 0;
913 : }
914 : }
915 : final roomKeys =
916 12 : await client.nativeImplementations.generateUploadKeys(args);
917 16 : Logs().i('[Key Manager] Uploading ${dbSessions.length} room keys...');
918 : // upload the payload...
919 12 : await client.putRoomKeys(info.version, roomKeys);
920 : // and now finally mark all the keys as uploaded
921 : // no need to optimze this, as we only run it so seldomly and almost never with many keys at once
922 8 : for (final dbSession in dbSessions) {
923 4 : await database.markInboundGroupSessionAsUploaded(
924 4 : dbSession.roomId,
925 4 : dbSession.sessionId,
926 : );
927 : }
928 : } finally {
929 5 : decryption.free();
930 : }
931 : } catch (e, s) {
932 4 : Logs().e('[Key Manager] Error uploading room keys', e, s);
933 : }
934 : }
935 :
936 46 : _uploadingFuture = uploadInternal();
937 : try {
938 23 : await _uploadingFuture;
939 : } finally {
940 23 : _uploadingFuture = null;
941 : }
942 : }
943 :
944 : /// Handle an incoming to_device event that is related to key sharing
945 23 : Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
946 46 : if (event.type == EventTypes.RoomKeyRequest) {
947 3 : if (event.content['request_id'] is! String) {
948 : return; // invalid event
949 : }
950 3 : if (event.content['action'] == 'request') {
951 : // we are *receiving* a request
952 2 : Logs().i(
953 4 : '[KeyManager] Received key sharing request from ${event.sender}:${event.content['requesting_device_id']}...',
954 : );
955 2 : if (!event.content.containsKey('body')) {
956 2 : Logs().w('[KeyManager] No body, doing nothing');
957 : return; // no body
958 : }
959 2 : final body = event.content.tryGetMap<String, Object?>('body');
960 : if (body == null) {
961 0 : Logs().w('[KeyManager] Wrong type for body, doing nothing');
962 : return; // wrong type for body
963 : }
964 1 : final roomId = body.tryGet<String>('room_id');
965 : if (roomId == null) {
966 0 : Logs().w(
967 : '[KeyManager] Wrong type for room_id or no room_id, doing nothing',
968 : );
969 : return; // wrong type for roomId or no roomId found
970 : }
971 4 : final device = client.userDeviceKeys[event.sender]
972 4 : ?.deviceKeys[event.content['requesting_device_id']];
973 : if (device == null) {
974 2 : Logs().w('[KeyManager] Device not found, doing nothing');
975 : return; // device not found
976 : }
977 4 : if (device.userId == client.userID &&
978 4 : device.deviceId == client.deviceID) {
979 0 : Logs().i('[KeyManager] Request is by ourself, ignoring');
980 : return; // ignore requests by ourself
981 : }
982 2 : final room = client.getRoomById(roomId);
983 : if (room == null) {
984 2 : Logs().i('[KeyManager] Unknown room, ignoring');
985 : return; // unknown room
986 : }
987 1 : final sessionId = body.tryGet<String>('session_id');
988 : if (sessionId == null) {
989 0 : Logs().w(
990 : '[KeyManager] Wrong type for session_id or no session_id, doing nothing',
991 : );
992 : return; // wrong type for session_id
993 : }
994 : // okay, let's see if we have this session at all
995 2 : final session = await loadInboundGroupSession(room.id, sessionId);
996 : if (session == null) {
997 2 : Logs().i('[KeyManager] Unknown session, ignoring');
998 : return; // we don't have this session anyways
999 : }
1000 3 : if (event.content['request_id'] is! String) {
1001 0 : Logs().w(
1002 : '[KeyManager] Wrong type for request_id or no request_id, doing nothing',
1003 : );
1004 : return; // wrong type for request_id
1005 : }
1006 1 : final request = KeyManagerKeyShareRequest(
1007 2 : requestId: event.content.tryGet<String>('request_id')!,
1008 1 : devices: [device],
1009 : room: room,
1010 : sessionId: sessionId,
1011 : );
1012 3 : if (incomingShareRequests.containsKey(request.requestId)) {
1013 0 : Logs().i('[KeyManager] Already processed this request, ignoring');
1014 : return; // we don't want to process one and the same request multiple times
1015 : }
1016 3 : incomingShareRequests[request.requestId] = request;
1017 : final roomKeyRequest =
1018 1 : RoomKeyRequest.fromToDeviceEvent(event, this, request);
1019 4 : if (device.userId == client.userID &&
1020 1 : device.verified &&
1021 1 : !device.blocked) {
1022 2 : Logs().i('[KeyManager] All checks out, forwarding key...');
1023 : // alright, we can forward the key
1024 1 : await roomKeyRequest.forwardKey();
1025 1 : } else if (device.encryptToDevice &&
1026 1 : session.allowedAtIndex
1027 2 : .tryGet<Map<String, Object?>>(device.userId)
1028 2 : ?.tryGet(device.curve25519Key!) !=
1029 : null) {
1030 : // if we know the user may see the message, then we can just forward the key.
1031 : // we do not need to check if the device is verified, just if it is not blocked,
1032 : // as that is the logic we already initially try to send out the room keys.
1033 : final index =
1034 5 : session.allowedAtIndex[device.userId]![device.curve25519Key]!;
1035 2 : Logs().i(
1036 1 : '[KeyManager] Valid foreign request, forwarding key at index $index...',
1037 : );
1038 1 : await roomKeyRequest.forwardKey(index);
1039 : } else {
1040 1 : Logs()
1041 1 : .i('[KeyManager] Asking client, if the key should be forwarded');
1042 2 : client.onRoomKeyRequest
1043 1 : .add(roomKeyRequest); // let the client handle this
1044 : }
1045 0 : } else if (event.content['action'] == 'request_cancellation') {
1046 : // we got told to cancel an incoming request
1047 0 : if (!incomingShareRequests.containsKey(event.content['request_id'])) {
1048 : return; // we don't know this request anyways
1049 : }
1050 : // alright, let's just cancel this request
1051 0 : final request = incomingShareRequests[event.content['request_id']]!;
1052 0 : request.canceled = true;
1053 0 : incomingShareRequests.remove(request.requestId);
1054 : }
1055 46 : } else if (event.type == EventTypes.ForwardedRoomKey) {
1056 : // we *received* an incoming key request
1057 1 : final encryptedContent = event.encryptedContent;
1058 : if (encryptedContent == null) {
1059 2 : Logs().w(
1060 : 'Ignoring an unencrypted forwarded key from a to device message',
1061 1 : event.toJson(),
1062 : );
1063 : return;
1064 : }
1065 3 : final request = outgoingShareRequests.values.firstWhereOrNull(
1066 1 : (r) =>
1067 5 : r.room.id == event.content['room_id'] &&
1068 4 : r.sessionId == event.content['session_id'],
1069 : );
1070 1 : if (request == null || request.canceled) {
1071 : return; // no associated request found or it got canceled
1072 : }
1073 2 : final device = request.devices.firstWhereOrNull(
1074 1 : (d) =>
1075 3 : d.userId == event.sender &&
1076 3 : d.curve25519Key == encryptedContent['sender_key'],
1077 : );
1078 : if (device == null) {
1079 : return; // someone we didn't send our request to replied....better ignore this
1080 : }
1081 : // we add the sender key to the forwarded key chain
1082 3 : if (event.content['forwarding_curve25519_key_chain'] is! List) {
1083 0 : event.content['forwarding_curve25519_key_chain'] = <String>[];
1084 : }
1085 2 : (event.content['forwarding_curve25519_key_chain'] as List)
1086 2 : .add(encryptedContent['sender_key']);
1087 3 : if (event.content['sender_claimed_ed25519_key'] is! String) {
1088 0 : Logs().w('sender_claimed_ed255519_key has wrong type');
1089 : return; // wrong type
1090 : }
1091 : // TODO: verify that the keys work to decrypt a message
1092 : // alright, all checks out, let's go ahead and store this session
1093 1 : await setInboundGroupSession(
1094 2 : request.room.id,
1095 1 : request.sessionId,
1096 1 : device.curve25519Key!,
1097 1 : event.content,
1098 : forwarded: true,
1099 1 : senderClaimedKeys: {
1100 2 : 'ed25519': event.content['sender_claimed_ed25519_key'] as String,
1101 : },
1102 : );
1103 2 : request.devices.removeWhere(
1104 7 : (k) => k.userId == device.userId && k.deviceId == device.deviceId,
1105 : );
1106 3 : outgoingShareRequests.remove(request.requestId);
1107 : // send cancel to all other devices
1108 2 : if (request.devices.isEmpty) {
1109 : return; // no need to send any cancellation
1110 : }
1111 : // Send with send-to-device messaging
1112 1 : final sendToDeviceMessage = {
1113 : 'action': 'request_cancellation',
1114 1 : 'request_id': request.requestId,
1115 2 : 'requesting_device_id': client.deviceID,
1116 : };
1117 1 : final data = <String, Map<String, Map<String, dynamic>>>{};
1118 2 : for (final device in request.devices) {
1119 3 : final userData = data[device.userId] ??= {};
1120 2 : userData[device.deviceId!] = sendToDeviceMessage;
1121 : }
1122 2 : await client.sendToDevice(
1123 : EventTypes.RoomKeyRequest,
1124 2 : client.generateUniqueTransactionId(),
1125 : data,
1126 : );
1127 46 : } else if (event.type == EventTypes.RoomKey) {
1128 46 : Logs().v(
1129 69 : '[KeyManager] Received room key with session ${event.content['session_id']}',
1130 : );
1131 23 : final encryptedContent = event.encryptedContent;
1132 : if (encryptedContent == null) {
1133 2 : Logs().v('[KeyManager] not encrypted, ignoring...');
1134 : return; // the event wasn't encrypted, this is a security risk;
1135 : }
1136 46 : final roomId = event.content.tryGet<String>('room_id');
1137 46 : final sessionId = event.content.tryGet<String>('session_id');
1138 : if (roomId == null || sessionId == null) {
1139 0 : Logs().w(
1140 : 'Either room_id or session_id are not the expected type or missing',
1141 : );
1142 : return;
1143 : }
1144 92 : final sender_ed25519 = client.userDeviceKeys[event.sender]
1145 4 : ?.deviceKeys[event.content['requesting_device_id']]?.ed25519Key;
1146 : if (sender_ed25519 != null) {
1147 0 : event.content['sender_claimed_ed25519_key'] = sender_ed25519;
1148 : }
1149 46 : Logs().v('[KeyManager] Keeping room key');
1150 23 : await setInboundGroupSession(
1151 : roomId,
1152 : sessionId,
1153 23 : encryptedContent['sender_key'],
1154 23 : event.content,
1155 : forwarded: false,
1156 : );
1157 : }
1158 : }
1159 :
1160 : StreamSubscription<SyncUpdate>? _uploadKeysOnSync;
1161 :
1162 21 : void dispose() {
1163 : // ignore: discarded_futures
1164 42 : _uploadKeysOnSync?.cancel();
1165 46 : for (final sess in _outboundGroupSessions.values) {
1166 4 : sess.dispose();
1167 : }
1168 62 : for (final entries in _inboundGroupSessions.values) {
1169 40 : for (final sess in entries.values) {
1170 20 : sess.dispose();
1171 : }
1172 : }
1173 : }
1174 : }
1175 :
1176 : class KeyManagerKeyShareRequest {
1177 : final String requestId;
1178 : final List<DeviceKeys> devices;
1179 : final Room room;
1180 : final String sessionId;
1181 : bool canceled;
1182 :
1183 2 : KeyManagerKeyShareRequest({
1184 : required this.requestId,
1185 : List<DeviceKeys>? devices,
1186 : required this.room,
1187 : required this.sessionId,
1188 : this.canceled = false,
1189 0 : }) : devices = devices ?? [];
1190 : }
1191 :
1192 : class RoomKeyRequest extends ToDeviceEvent {
1193 : KeyManager keyManager;
1194 : KeyManagerKeyShareRequest request;
1195 :
1196 1 : RoomKeyRequest.fromToDeviceEvent(
1197 : ToDeviceEvent toDeviceEvent,
1198 : this.keyManager,
1199 : this.request,
1200 1 : ) : super(
1201 1 : sender: toDeviceEvent.sender,
1202 1 : content: toDeviceEvent.content,
1203 1 : type: toDeviceEvent.type,
1204 : );
1205 :
1206 3 : Room get room => request.room;
1207 :
1208 4 : DeviceKeys get requestingDevice => request.devices.first;
1209 :
1210 1 : Future<void> forwardKey([int? index]) async {
1211 2 : if (request.canceled) {
1212 0 : keyManager.incomingShareRequests.remove(request.requestId);
1213 : return; // request is canceled, don't send anything
1214 : }
1215 1 : final room = this.room;
1216 : final session =
1217 5 : await keyManager.loadInboundGroupSession(room.id, request.sessionId);
1218 1 : if (session?.inboundGroupSession == null) {
1219 0 : Logs().v("[KeyManager] Not forwarding key we don't have");
1220 : return;
1221 : }
1222 :
1223 2 : final message = session!.content.copy();
1224 1 : message['forwarding_curve25519_key_chain'] =
1225 2 : List<String>.from(session.forwardingCurve25519KeyChain);
1226 :
1227 2 : if (session.senderKey.isNotEmpty) {
1228 2 : message['sender_key'] = session.senderKey;
1229 : }
1230 1 : message['sender_claimed_ed25519_key'] =
1231 2 : session.senderClaimedKeys['ed25519'] ??
1232 2 : (session.forwardingCurve25519KeyChain.isEmpty
1233 3 : ? keyManager.encryption.fingerprintKey
1234 : : null);
1235 3 : message['session_key'] = session.inboundGroupSession!.export_session(
1236 2 : index ?? session.inboundGroupSession!.first_known_index(),
1237 : );
1238 : // send the actual reply of the key back to the requester
1239 3 : await keyManager.client.sendToDeviceEncrypted(
1240 2 : [requestingDevice],
1241 : EventTypes.ForwardedRoomKey,
1242 : message,
1243 : );
1244 5 : keyManager.incomingShareRequests.remove(request.requestId);
1245 : }
1246 : }
1247 :
1248 : /// you would likely want to use [NativeImplementations] and
1249 : /// [Client.nativeImplementations] instead
1250 4 : RoomKeys generateUploadKeysImplementation(GenerateUploadKeysArgs args) {
1251 4 : final enc = olm.PkEncryption();
1252 : try {
1253 8 : enc.set_recipient_key(args.pubkey);
1254 : // first we generate the payload to upload all the session keys in this chunk
1255 8 : final roomKeys = RoomKeys(rooms: {});
1256 8 : for (final dbSession in args.dbSessions) {
1257 12 : final sess = SessionKey.fromDb(dbSession.dbSession, args.userId);
1258 4 : if (!sess.isValid) {
1259 : continue;
1260 : }
1261 : // create the room if it doesn't exist
1262 : final roomKeyBackup =
1263 20 : roomKeys.rooms[sess.roomId] ??= RoomKeyBackup(sessions: {});
1264 : // generate the encrypted content
1265 4 : final payload = <String, dynamic>{
1266 : 'algorithm': AlgorithmTypes.megolmV1AesSha2,
1267 4 : 'forwarding_curve25519_key_chain': sess.forwardingCurve25519KeyChain,
1268 4 : 'sender_key': sess.senderKey,
1269 4 : 'sender_claimed_keys': sess.senderClaimedKeys,
1270 4 : 'session_key': sess.inboundGroupSession!
1271 12 : .export_session(sess.inboundGroupSession!.first_known_index()),
1272 : };
1273 : // encrypt the content
1274 8 : final encrypted = enc.encrypt(json.encode(payload));
1275 : // fetch the device, if available...
1276 : //final device = args.client.getUserDeviceKeysByCurve25519Key(sess.senderKey);
1277 : // aaaand finally add the session key to our payload
1278 16 : roomKeyBackup.sessions[sess.sessionId] = KeyBackupData(
1279 8 : firstMessageIndex: sess.inboundGroupSession!.first_known_index(),
1280 8 : forwardedCount: sess.forwardingCurve25519KeyChain.length,
1281 4 : isVerified: dbSession.verified, //device?.verified ?? false,
1282 4 : sessionData: {
1283 4 : 'ephemeral': encrypted.ephemeral,
1284 4 : 'ciphertext': encrypted.ciphertext,
1285 4 : 'mac': encrypted.mac,
1286 : },
1287 : );
1288 : }
1289 4 : enc.free();
1290 : return roomKeys;
1291 : } catch (e, s) {
1292 0 : Logs().e('[Key Manager] Error generating payload', e, s);
1293 0 : enc.free();
1294 : rethrow;
1295 : }
1296 : }
1297 :
1298 : class DbInboundGroupSessionBundle {
1299 4 : DbInboundGroupSessionBundle({
1300 : required this.dbSession,
1301 : required this.verified,
1302 : });
1303 :
1304 0 : factory DbInboundGroupSessionBundle.fromJson(Map<dynamic, dynamic> json) =>
1305 0 : DbInboundGroupSessionBundle(
1306 : dbSession:
1307 0 : StoredInboundGroupSession.fromJson(Map.from(json['dbSession'])),
1308 0 : verified: json['verified'],
1309 : );
1310 :
1311 0 : Map<String, Object> toJson() => {
1312 0 : 'dbSession': dbSession.toJson(),
1313 0 : 'verified': verified,
1314 : };
1315 : StoredInboundGroupSession dbSession;
1316 : bool verified;
1317 : }
1318 :
1319 : class GenerateUploadKeysArgs {
1320 4 : GenerateUploadKeysArgs({
1321 : required this.pubkey,
1322 : required this.dbSessions,
1323 : required this.userId,
1324 : });
1325 :
1326 0 : factory GenerateUploadKeysArgs.fromJson(Map<dynamic, dynamic> json) =>
1327 0 : GenerateUploadKeysArgs(
1328 0 : pubkey: json['pubkey'],
1329 0 : dbSessions: (json['dbSessions'] as Iterable)
1330 0 : .map((e) => DbInboundGroupSessionBundle.fromJson(e))
1331 0 : .toList(),
1332 0 : userId: json['userId'],
1333 : );
1334 :
1335 0 : Map<String, Object> toJson() => {
1336 0 : 'pubkey': pubkey,
1337 0 : 'dbSessions': dbSessions.map((e) => e.toJson()).toList(),
1338 0 : 'userId': userId,
1339 : };
1340 :
1341 : String pubkey;
1342 : List<DbInboundGroupSessionBundle> dbSessions;
1343 : String userId;
1344 : }
|