-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathkey_verification.dart
1836 lines (1705 loc) · 56.5 KB
/
key_verification.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:canonical_json/canonical_json.dart';
import 'package:olm/olm.dart' as olm;
import 'package:typed_data/typed_data.dart';
import 'package:matrix/encryption/encryption.dart';
import 'package:matrix/encryption/utils/base64_unpadded.dart';
import 'package:matrix/matrix.dart';
import 'package:matrix/src/utils/crypto/crypto.dart' as uc;
/*
+-------------+ +-----------+
| AliceDevice | | BobDevice |
+-------------+ +-----------+
| |
| (m.key.verification.request) |
|-------------------------------->| (ASK FOR VERIFICATION REQUEST)
| |
| (m.key.verification.ready) |
|<--------------------------------|
| |
| (m.key.verification.start) | we will probably not send this
|<--------------------------------| for simplicities sake
| |
| m.key.verification.start |
|-------------------------------->| (ASK FOR VERIFICATION REQUEST)
| |
| m.key.verification.accept |
|<--------------------------------|
| |
| m.key.verification.key |
|-------------------------------->|
| |
| m.key.verification.key |
|<--------------------------------|
| |
| COMPARE EMOJI / NUMBERS |
| |
| m.key.verification.mac |
|-------------------------------->| success
| |
| m.key.verification.mac |
success |<--------------------------------|
| |
*/
/// QR key verification
/// You create possible methods from `client.verificationMethods` on device A
/// and send a request using `request.start()` which calls `sendRequest()` your client
/// now is in `waitingAccept` state, where ideally your client would now show some
/// waiting indicator.
///
/// On device B you now get a `m.key.verification.request`, you check the
/// `methods` from the request payload and see if anything is possible.
/// If not you cancel the request. (should this be cancelled? couldn't another device handle this?)
/// you the set the state to `askAccept`.
///
/// Your client would now show a button to accept/decline the request.
/// The user can then use `acceptVerification()`to accept the verification which
/// then sends a `m.key.verification.ready`. This also calls `generateQrCode()`
/// in it which populates the `request.qrData` depending on the qr mode.
/// B now sets the state `askChoice`
///
/// On device A you now get the ready event, which setups the `possibleMethods`
/// and `qrData` on A's side. Similarly A now sets their state to `askChoice`
///
/// At his point both sides are on the `askChoice` state.
///
/// BACKWARDS COMPATIBILITY HACK:
/// To work well with sdks prior to QR verification (0.20.5 and older), start will
/// be sent with ready itself if only sas is supported. This avoids weird glare
/// issues faced with start from both sides if clients are not on the same sdk
/// version (0.20.5 vs next)
/// https://matrix.to/#/!KBwfdofYJUmnsVoqwn:famedly.de/$wlHXlLQJdfrqKAF5KkuQrXydwOhY_uyqfH4ReasZqnA?via=neko.dev&via=famedly.de&via=lihotzki.de
/// Here your clients would ideally show a list of the `possibleMethods` and the
/// user can choose one. For QR specifically, you can show the QR code on the
/// device which supports showing the qr code and the device which supports
/// scanning can scan this code.
///
/// Assuming device A scans device B's code, device A would now send a `m.key.verification.start`,
/// you do this using the `continueVerificatio()` method. You can pass
/// `m.reciprocate.v1` or `m.sas.v1` here, and also attach the qrData here.
/// This then calls `verifyQrData()` internally, which sets the `randomSharedSecretForQRCode`
/// to the one from the QR code. Device A is now set to `showQRSuccess` state and shows
/// a green sheild. (Maybe add a text below saying tell device B you scanned the
/// code successfully.)
///
/// (some keys magic happens here, check `verifyQrData()`, `verifyKeysQR()` to know more)
///
/// On device B you get the `m.key.verification.start` event. The secret sent in
/// the start request is then verified, device B is then set to the `confirmQRScan`
/// state. Your device should show a dialog to confirm from B that A's device shows
/// the green shield (is in the done state). Once B confirms this physically, you
/// call the `acceptQRScanConfirmation()` function, which then does some keys
/// magic and sets B's state to `done`.
///
/// A gets the `m.key.verification.done` messsage and sends a done back, both
/// users can now dismiss the verification dialog safely.
enum KeyVerificationState {
askChoice,
askAccept,
askSSSS,
waitingAccept,
askSas,
showQRSuccess, // scanner after QR scan was successfull
confirmQRScan, // shower after getting start
waitingSas,
done,
error
}
enum KeyVerificationMethod { emoji, numbers, qrShow, qrScan, reciprocate }
bool isQrSupported(List knownVerificationMethods, List possibleMethods) {
return knownVerificationMethods.contains(EventTypes.QRShow) &&
possibleMethods.contains(EventTypes.QRScan) ||
knownVerificationMethods.contains(EventTypes.QRScan) &&
possibleMethods.contains(EventTypes.QRShow);
}
List<String> _intersect(List<String>? a, List<dynamic>? b) =>
(b == null || a == null) ? [] : a.where(b.contains).toList();
List<String> _calculatePossibleMethods(
List<String> knownMethods,
List<dynamic> payloadMethods,
) {
final output = <String>[];
final copyKnownMethods = List<String>.from(knownMethods);
final copyPayloadMethods = List.from(payloadMethods);
copyKnownMethods
.removeWhere((element) => !copyPayloadMethods.contains(element));
// remove qr modes for now, check if they are possible and add later
copyKnownMethods.removeWhere((element) => element.startsWith('m.qr_code'));
output.addAll(copyKnownMethods);
if (isQrSupported(knownMethods, payloadMethods)) {
// scan/show combo found, add whichever is known to us to our possible methods.
if (payloadMethods.contains(EventTypes.QRScan) &&
knownMethods.contains(EventTypes.QRShow)) {
output.add(EventTypes.QRShow);
}
if (payloadMethods.contains(EventTypes.QRShow) &&
knownMethods.contains(EventTypes.QRScan)) {
output.add(EventTypes.QRScan);
}
} else {
output.remove(EventTypes.Reciprocate);
}
return output;
}
List<int> _bytesToInt(Uint8List bytes, int totalBits) {
final ret = <int>[];
var current = 0;
var numBits = 0;
for (final byte in bytes) {
for (final bit in [7, 6, 5, 4, 3, 2, 1, 0]) {
numBits++;
current |= ((byte >> bit) & 1) << (totalBits - numBits);
if (numBits >= totalBits) {
ret.add(current);
current = 0;
numBits = 0;
}
}
}
return ret;
}
_KeyVerificationMethod _makeVerificationMethod(
String type,
KeyVerification request,
) {
if (type == EventTypes.Sas) {
return _KeyVerificationMethodSas(request: request);
}
if (type == EventTypes.Reciprocate) {
return _KeyVerificationMethodQRReciprocate(request: request);
}
throw Exception('Unkown method type');
}
class KeyVerification {
String? transactionId;
final Encryption encryption;
Client get client => encryption.client;
final Room? room;
final String userId;
void Function()? onUpdate;
String? get deviceId => _deviceId;
String? _deviceId;
bool startedVerification = false;
_KeyVerificationMethod? _method;
List<String> possibleMethods = [];
List<String> oppositePossibleMethods = [];
Map<String, dynamic>? startPayload;
String? _nextAction;
List<SignableKey> _verifiedDevices = [];
DateTime lastActivity;
String? lastStep;
KeyVerificationState state = KeyVerificationState.waitingAccept;
bool canceled = false;
String? canceledCode;
String? canceledReason;
bool get isDone =>
canceled ||
{KeyVerificationState.error, KeyVerificationState.done}.contains(state);
// qr stuff
QRCode? qrCode;
String? randomSharedSecretForQRCode;
SignableKey? keyToVerify;
KeyVerification({
required this.encryption,
this.room,
required this.userId,
String? deviceId,
this.onUpdate,
}) : _deviceId = deviceId,
lastActivity = DateTime.now();
void dispose() {
Logs().i('[Key Verification] disposing object...');
randomSharedSecretForQRCode = null;
_method?.dispose();
}
static String? getTransactionId(Map<String, dynamic> payload) {
return payload['transaction_id'] ??
(payload['m.relates_to'] is Map
? payload['m.relates_to']['event_id']
: null);
}
List<String> get knownVerificationMethods {
final methods = <String>{};
if (client.verificationMethods.contains(KeyVerificationMethod.numbers) ||
client.verificationMethods.contains(KeyVerificationMethod.emoji)) {
methods.add(EventTypes.Sas);
}
/// `qrCanWork` - qr cannot work if we are verifying another master key but our own is unverified
final qrCanWork = (userId == client.userID) ||
((client.userDeviceKeys[client.userID]?.masterKey?.verified ?? false));
if (client.verificationMethods.contains(KeyVerificationMethod.qrShow) &&
qrCanWork) {
methods.add(EventTypes.QRShow);
methods.add(EventTypes.Reciprocate);
}
if (client.verificationMethods.contains(KeyVerificationMethod.qrScan) &&
qrCanWork) {
methods.add(EventTypes.QRScan);
methods.add(EventTypes.Reciprocate);
}
return methods.toList();
}
/// Once you get a ready event, i.e both sides are in a `askChoice` state,
/// send either `m.reciprocate.v1` or `m.sas.v1` here. If you continue with
/// qr, send the qrData you just scanned
Future<void> continueVerification(
String type, {
Uint8List? qrDataRawBytes,
}) async {
bool qrChecksOut = false;
if (possibleMethods.contains(type)) {
if (qrDataRawBytes != null) {
qrChecksOut = await verifyQrData(qrDataRawBytes);
// after this scanners state is done
}
if (type != EventTypes.Reciprocate || qrChecksOut) {
final method = _method = _makeVerificationMethod(type, this);
await method.sendStart();
if (type == EventTypes.Sas) {
setState(KeyVerificationState.waitingAccept);
}
} else if (type == EventTypes.Reciprocate && !qrChecksOut) {
Logs().e('[KeyVerification] qr did not check out');
await cancel('m.invalid_key');
}
} else {
Logs().e(
'[KeyVerification] tried to continue verification with a unknown method',
);
await cancel('m.unknown_method');
}
}
Future<void> sendRequest() async {
await send(
EventTypes.KeyVerificationRequest,
{
'methods': knownVerificationMethods,
if (room == null) 'timestamp': DateTime.now().millisecondsSinceEpoch,
},
);
startedVerification = true;
setState(KeyVerificationState.waitingAccept);
lastActivity = DateTime.now();
}
Future<void> start() async {
if (room == null) {
transactionId = client.generateUniqueTransactionId();
}
if (encryption.crossSigning.enabled &&
!(await encryption.crossSigning.isCached()) &&
!client.isUnknownSession) {
setState(KeyVerificationState.askSSSS);
_nextAction = 'request';
} else {
await sendRequest();
}
}
bool _handlePayloadLock = false;
QRMode getOurQRMode() {
QRMode mode = QRMode.verifyOtherUser;
if (client.userID == userId) {
if (client.encryption != null &&
client.encryption!.enabled &&
(client.userDeviceKeys[client.userID]?.masterKey?.directVerified ??
false)) {
mode = QRMode.verifySelfTrusted;
} else {
mode = QRMode.verifySelfUntrusted;
}
}
return mode;
}
Future<void> handlePayload(
String type,
Map<String, dynamic> payload, [
String? eventId,
]) async {
if (isDone) {
return; // no need to do anything with already canceled requests
}
while (_handlePayloadLock) {
await Future.delayed(Duration(milliseconds: 50));
}
_handlePayloadLock = true;
Logs().i('[Key Verification] Received type $type: $payload');
try {
var thisLastStep = lastStep;
switch (type) {
case EventTypes.KeyVerificationRequest:
_deviceId ??= payload['from_device'];
transactionId ??= eventId ?? payload['transaction_id'];
// verify the timestamp
final now = DateTime.now();
final verifyTime =
DateTime.fromMillisecondsSinceEpoch(payload['timestamp']);
if (now.subtract(Duration(minutes: 10)).isAfter(verifyTime) ||
now.add(Duration(minutes: 5)).isBefore(verifyTime)) {
// if the request is more than 20min in the past we just silently fail it
// to not generate too many cancels
await cancel(
'm.timeout',
now.subtract(Duration(minutes: 20)).isAfter(verifyTime),
);
return;
}
// ensure we have the other sides keys
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await client.updateUserDeviceKeys(additionalUsers: {userId});
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await cancel('im.fluffychat.unknown_device');
return;
}
}
oppositePossibleMethods = List<String>.from(payload['methods']);
// verify it has a method we can use
possibleMethods = _calculatePossibleMethods(
knownVerificationMethods,
payload['methods'],
);
if (possibleMethods.isEmpty) {
// reject it outright
await cancel('m.unknown_method');
return;
}
setState(KeyVerificationState.askAccept);
break;
case EventTypes.KeyVerificationReady:
if (deviceId == '*') {
_deviceId = payload['from_device']; // gotta set the real device id
transactionId ??= eventId ?? payload['transaction_id'];
// and broadcast the cancel to the other devices
final devices = List<DeviceKeys>.from(
client.userDeviceKeys[userId]?.deviceKeys.values ??
Iterable.empty(),
);
devices.removeWhere(
(d) => {deviceId, client.deviceID}.contains(d.deviceId),
);
final cancelPayload = <String, dynamic>{
'reason': 'Another device accepted the request',
'code': 'm.accepted',
};
makePayload(cancelPayload);
await client.sendToDeviceEncrypted(
devices,
EventTypes.KeyVerificationCancel,
cancelPayload,
);
}
_deviceId ??= payload['from_device'];
// ensure we have the other sides keys
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await client.updateUserDeviceKeys(additionalUsers: {userId});
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await cancel('im.fluffychat.unknown_device');
return;
}
}
oppositePossibleMethods = List<String>.from(payload['methods']);
possibleMethods = _calculatePossibleMethods(
knownVerificationMethods,
payload['methods'],
);
if (possibleMethods.isEmpty) {
// reject it outright
await cancel('m.unknown_method');
return;
}
// as both parties can send a start, the last step being "ready" is race-condition prone
// as such, we better set it *before* we send our start
lastStep = type;
// setup QRData from outgoing request (incoming ready)
qrCode = await generateQrCode();
// play nice with sdks < 0.20.5
// https://matrix.to/#/!KBwfdofYJUmnsVoqwn:famedly.de/$wlHXlLQJdfrqKAF5KkuQrXydwOhY_uyqfH4ReasZqnA?via=neko.dev&via=famedly.de&via=lihotzki.de
if (!isQrSupported(knownVerificationMethods, payload['methods'])) {
if (knownVerificationMethods.contains(EventTypes.Sas)) {
final method = _method =
_makeVerificationMethod(possibleMethods.first, this);
await method.sendStart();
setState(KeyVerificationState.waitingAccept);
}
} else {
// allow user to choose
setState(KeyVerificationState.askChoice);
}
break;
case EventTypes.KeyVerificationStart:
_deviceId ??= payload['from_device'];
transactionId ??= eventId ?? payload['transaction_id'];
if (_method != null) {
// the other side sent us a start, even though we already sent one
if (payload['method'] == _method!.type) {
// same method. Determine priority
final ourEntry = '${client.userID}|${client.deviceID}';
final entries = [ourEntry, '$userId|$deviceId'];
entries.sort();
if (entries.first == ourEntry) {
// our start won, nothing to do
return;
} else {
// the other start won, let's hand off
startedVerification = false; // it is now as if they started
thisLastStep = lastStep =
EventTypes.KeyVerificationRequest; // we fake the last step
_method!.dispose(); // in case anything got created already
}
} else {
// methods don't match up, let's cancel this
await cancel('m.unexpected_message');
return;
}
}
if (!(await verifyLastStep([
EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationReady,
]))) {
return; // abort
}
if (!knownVerificationMethods.contains(payload['method'])) {
await cancel('m.unknown_method');
return;
}
if (lastStep == EventTypes.KeyVerificationRequest) {
if (!possibleMethods.contains(payload['method'])) {
await cancel('m.unknown_method');
return;
}
}
// ensure we have the other sides keys
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await client.updateUserDeviceKeys(additionalUsers: {userId});
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId!] == null) {
await cancel('im.fluffychat.unknown_device');
return;
}
}
_method = _makeVerificationMethod(payload['method'], this);
if (lastStep == null) {
// validate the start time
if (room != null) {
// we just silently ignore in-room-verification starts
await cancel('m.unknown_method', true);
return;
}
// validate the specific payload
if (!_method!.validateStart(payload)) {
await cancel('m.unknown_method');
return;
}
startPayload = payload;
setState(KeyVerificationState.askAccept);
} else {
Logs().i('handling start in method.....');
await _method!.handlePayload(type, payload);
}
break;
case EventTypes.KeyVerificationDone:
if (state == KeyVerificationState.showQRSuccess) {
await send(EventTypes.KeyVerificationDone, {});
setState(KeyVerificationState.done);
}
break;
case EventTypes.KeyVerificationCancel:
canceled = true;
canceledCode = payload['code'];
canceledReason = payload['reason'];
setState(KeyVerificationState.error);
break;
default:
final method = _method;
if (method != null) {
await method.handlePayload(type, payload);
} else {
await cancel('m.invalid_message');
}
break;
}
if (lastStep == thisLastStep) {
lastStep = type;
}
} catch (err, stacktrace) {
Logs().e('[Key Verification] An error occured', err, stacktrace);
await cancel('m.invalid_message');
} finally {
_handlePayloadLock = false;
}
}
void otherDeviceAccepted() {
canceled = true;
canceledCode = 'm.accepted';
canceledReason = 'm.accepted';
setState(KeyVerificationState.error);
}
Future<void> openSSSS({
String? passphrase,
String? recoveryKey,
String? keyOrPassphrase,
bool skip = false,
}) async {
Future<void> next() async {
if (_nextAction == 'request') {
await sendRequest();
} else if (_nextAction == 'done') {
// and now let's sign them all in the background
unawaited(encryption.crossSigning.sign(_verifiedDevices));
setState(KeyVerificationState.done);
} else if (_nextAction == 'showQRSuccess') {
setState(KeyVerificationState.showQRSuccess);
}
}
if (skip) {
await next();
return;
}
final handle = encryption.ssss.open(EventTypes.CrossSigningUserSigning);
await handle.unlock(
passphrase: passphrase,
recoveryKey: recoveryKey,
keyOrPassphrase: keyOrPassphrase,
);
await handle.maybeCacheAll();
await next();
}
/// called when the user accepts an incoming verification
Future<void> acceptVerification() async {
if (!(await verifyLastStep([
EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationStart,
]))) {
return;
}
setState(KeyVerificationState.waitingAccept);
if (lastStep == EventTypes.KeyVerificationRequest) {
final copyKnownVerificationMethods =
List<String>.from(knownVerificationMethods);
// qr code only works when atleast one side has verified master key
if (userId == client.userID) {
if (!(client.userDeviceKeys[client.userID]?.deviceKeys[deviceId]
?.hasValidSignatureChain(verifiedByTheirMasterKey: true) ??
false) &&
!(client.userDeviceKeys[client.userID]?.masterKey?.verified ??
false)) {
copyKnownVerificationMethods
.removeWhere((element) => element.startsWith('m.qr_code'));
copyKnownVerificationMethods.remove(EventTypes.Reciprocate);
// we are removing stuff only using the old possibleMethods should be ok here.
final copyPossibleMethods = List<String>.from(possibleMethods);
possibleMethods = _calculatePossibleMethods(
copyKnownVerificationMethods,
copyPossibleMethods,
);
}
}
// we need to send a ready event
await send(EventTypes.KeyVerificationReady, {
'methods': copyKnownVerificationMethods,
});
// setup QRData from incoming request (outgoing ready)
qrCode = await generateQrCode();
setState(KeyVerificationState.askChoice);
} else {
// we need to send an accept event
await _method!
.handlePayload(EventTypes.KeyVerificationStart, startPayload!);
}
}
/// called when the user rejects an incoming verification
Future<void> rejectVerification() async {
if (isDone) {
return;
}
if (!(await verifyLastStep([
EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationStart,
]))) {
return;
}
await cancel('m.user');
}
/// call this to confirm that your other device has shown a shield and is in
/// `done` state.
Future<void> acceptQRScanConfirmation() async {
if (_method is _KeyVerificationMethodQRReciprocate &&
state == KeyVerificationState.confirmQRScan) {
await (_method as _KeyVerificationMethodQRReciprocate)
.acceptQRScanConfirmation();
}
}
Future<void> acceptSas() async {
if (_method is _KeyVerificationMethodSas) {
await (_method as _KeyVerificationMethodSas).acceptSas();
}
}
Future<void> rejectSas() async {
if (_method is _KeyVerificationMethodSas) {
await (_method as _KeyVerificationMethodSas).rejectSas();
}
}
List<int> get sasNumbers {
if (_method is _KeyVerificationMethodSas) {
return _bytesToInt((_method as _KeyVerificationMethodSas).makeSas(5), 13)
.map((n) => n + 1000)
.toList();
}
return [];
}
List<String> get sasTypes {
if (_method is _KeyVerificationMethodSas) {
return (_method as _KeyVerificationMethodSas).authenticationTypes ?? [];
}
return [];
}
List<KeyVerificationEmoji> get sasEmojis {
if (_method is _KeyVerificationMethodSas) {
final numbers =
_bytesToInt((_method as _KeyVerificationMethodSas).makeSas(6), 6);
return numbers.map((n) => KeyVerificationEmoji(n)).toList().sublist(0, 7);
}
return [];
}
Future<void> maybeRequestSSSSSecrets([int i = 0]) async {
final requestInterval = <int>[10, 60];
if ((!encryption.crossSigning.enabled ||
(encryption.crossSigning.enabled &&
(await encryption.crossSigning.isCached()))) &&
(!encryption.keyManager.enabled ||
(encryption.keyManager.enabled &&
(await encryption.keyManager.isCached())))) {
// no need to request cache, we already have it
return;
}
// ignore: unawaited_futures
encryption.ssss
.maybeRequestAll(_verifiedDevices.whereType<DeviceKeys>().toList());
if (requestInterval.length <= i) {
return;
}
Timer(
Duration(seconds: requestInterval[i]),
() => maybeRequestSSSSSecrets(i + 1),
);
}
Future<void> verifyKeysSAS(
Map<String, String> keys,
Future<bool> Function(String, SignableKey) verifier,
) async {
_verifiedDevices = <SignableKey>[];
final userDeviceKey = client.userDeviceKeys[userId];
if (userDeviceKey == null) {
await cancel('m.key_mismatch');
return;
}
for (final entry in keys.entries) {
final keyId = entry.key;
final verifyDeviceId = keyId.substring('ed25519:'.length);
final keyInfo = entry.value;
final key = userDeviceKey.getKey(verifyDeviceId);
if (key != null) {
if (!(await verifier(keyInfo, key))) {
await cancel('m.key_mismatch');
return;
}
_verifiedDevices.add(key);
}
}
// okay, we reached this far, so all the devices are verified!
var verifiedMasterKey = false;
final wasUnknownSession = client.isUnknownSession;
for (final key in _verifiedDevices) {
await key.setVerified(
true,
false,
); // we don't want to sign the keys juuuust yet
if (key is CrossSigningKey && key.usage.contains('master')) {
verifiedMasterKey = true;
}
}
if (verifiedMasterKey && userId == client.userID) {
// it was our own master key, let's request the cross signing keys
// we do it in the background, thus no await needed here
// ignore: unawaited_futures
maybeRequestSSSSSecrets();
}
await send(EventTypes.KeyVerificationDone, {});
var askingSSSS = false;
if (encryption.crossSigning.enabled &&
encryption.crossSigning.signable(_verifiedDevices)) {
// these keys can be signed! Let's do so
if (await encryption.crossSigning.isCached()) {
// we want to make sure the verification state is correct for the other party after this event is handled.
// Otherwise the verification dialog might be stuck in an unverified but done state for a bit.
await encryption.crossSigning.sign(_verifiedDevices);
} else if (!wasUnknownSession) {
askingSSSS = true;
}
}
if (askingSSSS) {
setState(KeyVerificationState.askSSSS);
_nextAction = 'done';
} else {
setState(KeyVerificationState.done);
}
}
/// shower is true only for reciprocated verifications (shower side)
Future<void> verifyKeysQR(SignableKey key, {bool shower = true}) async {
var verifiedMasterKey = false;
final wasUnknownSession = client.isUnknownSession;
key.setDirectVerified(true);
if (key is CrossSigningKey && key.usage.contains('master')) {
verifiedMasterKey = true;
}
if (verifiedMasterKey && userId == client.userID) {
// it was our own master key, let's request the cross signing keys
// we do it in the background, thus no await needed here
// ignore: unawaited_futures
maybeRequestSSSSSecrets();
}
if (shower) {
await send(EventTypes.KeyVerificationDone, {});
}
final keyList = List<SignableKey>.from([key]);
var askingSSSS = false;
if (encryption.crossSigning.enabled &&
encryption.crossSigning.signable(keyList)) {
// these keys can be signed! Let's do so
if (await encryption.crossSigning.isCached()) {
// we want to make sure the verification state is correct for the other party after this event is handled.
// Otherwise the verification dialog might be stuck in an unverified but done state for a bit.
await encryption.crossSigning.sign(keyList);
} else if (!wasUnknownSession) {
askingSSSS = true;
}
}
if (askingSSSS) {
// no need to worry about shower/scanner here because if scanner was
// verified, ssss is already
setState(KeyVerificationState.askSSSS);
if (shower) {
_nextAction = 'done';
} else {
_nextAction = 'showQRSuccess';
}
} else {
if (shower) {
setState(KeyVerificationState.done);
} else {
setState(KeyVerificationState.showQRSuccess);
}
}
}
Future<bool> verifyActivity() async {
if (lastActivity.add(Duration(minutes: 10)).isAfter(DateTime.now())) {
lastActivity = DateTime.now();
return true;
}
await cancel('m.timeout');
return false;
}
Future<bool> verifyLastStep(List<String?> checkLastStep) async {
if (!(await verifyActivity())) {
return false;
}
if (checkLastStep.contains(lastStep)) {
return true;
}
Logs().e(
'[KeyVerificaton] lastStep mismatch cancelling, expected from ${checkLastStep.toString()} was ${lastStep.toString()}',
);
await cancel('m.unexpected_message');
return false;
}
Future<void> cancel([String code = 'm.unknown', bool quiet = false]) async {
if (!quiet && (deviceId != null || room != null)) {
await send(EventTypes.KeyVerificationCancel, {
'reason': code,
'code': code,
});
}
canceled = true;
canceledCode = code;
setState(KeyVerificationState.error);
}
void makePayload(Map<String, dynamic> payload) {
payload['from_device'] = client.deviceID;
if (transactionId != null) {
if (room != null) {
payload['m.relates_to'] = {
'rel_type': 'm.reference',
'event_id': transactionId,
};
} else {
payload['transaction_id'] = transactionId;
}
}
}
Future<void> send(
String type,
Map<String, dynamic> payload,
) async {
makePayload(payload);
Logs().i('[Key Verification] Sending type $type: $payload');
if (room != null) {
Logs().i('[Key Verification] Sending to $userId in room ${room!.id}...');
if ({EventTypes.KeyVerificationRequest}.contains(type)) {
payload['msgtype'] = type;
payload['to'] = userId;
payload['body'] =
'Attempting verification request. ($type) Apparently your client doesn\'t support this';
type = EventTypes.Message;
}
final newTransactionId = await room!.sendEvent(payload, type: type);
if (transactionId == null) {
transactionId = newTransactionId;
encryption.keyVerificationManager.addRequest(this);
}
} else {
Logs().i('[Key Verification] Sending to $userId device $deviceId...');
if (deviceId == '*') {
if ({
EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationCancel,
}.contains(type)) {
final deviceKeys =
client.userDeviceKeys[userId]?.deviceKeys.values.where(
(deviceKey) => deviceKey.hasValidSignatureChain(
verifiedByTheirMasterKey: true,
),
);
if (deviceKeys != null) {
await client.sendToDeviceEncrypted(
deviceKeys.toList(),
type,
payload,
);
}
} else {
Logs().e(
'[Key Verification] Tried to broadcast and un-broadcastable type: $type',
);
}
} else {
if (client.userDeviceKeys[userId]?.deviceKeys[deviceId] != null) {
await client.sendToDeviceEncrypted(
[client.userDeviceKeys[userId]!.deviceKeys[deviceId]!],
type,
payload,
);
} else {
Logs().e('[Key Verification] Unknown device');
}
}
}
}
void setState(KeyVerificationState newState) {
if (state != KeyVerificationState.error) {
state = newState;
}
onUpdate?.call();
}
static const String prefix = 'MATRIX';
static const int version = 0x02;
Future<bool> verifyQrData(Uint8List qrDataRawBytes) async {
final data = qrDataRawBytes;
// hardcoded stuff + 2 keys + secret
if (data.length < 10 + 32 + 32 + 8 + utf8.encode(transactionId!).length) {
return false;