forked from Syndace/python-omemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_sessionmanager.py
1054 lines (830 loc) · 31.4 KB
/
test_sessionmanager.py
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
import pytest
import cProfile
import logging
import os
import time
logging.basicConfig(level = logging.DEBUG)
import omemo
from omemo import SessionManager
from omemo.exceptions import *
from omemo_backend_signal import BACKEND as SignalBackend
from asyncinmemorystorage import AsyncInMemoryStorage
from syncinmemorystorage import SyncInMemoryStorage
from deletingotpkpolicy import DeletingOTPKPolicy
from keepingotpkpolicy import KeepingOTPKPolicy
from example_data import *
from example_data import (
ALICE_BARE_JID as A_JID,
BOB_BARE_JID as B_JID,
CHARLIE_BARE_JID as C_JID,
DAVE_BARE_JID as D_JID,
ALICE_DEVICE_ID as A_DID,
BOB_DEVICE_ID as B_DID,
CHARLIE_DEVICE_ID as C_DID,
DAVE_DEVICE_ID as D_DID,
ALICE_DEVICE_IDS as A_DIDS,
BOB_DEVICE_IDS as B_DIDS,
CHARLIE_DEVICE_IDS as C_DIDS,
DAVE_DEVICE_IDS as D_DIDS
)
def assertPromiseFulfilled(promise):
assert isinstance(promise, omemo.promise.Promise)
while not promise.done: time.sleep(.01)
assert promise.fulfilled
return promise.value
def assertPromiseFulfilledOrRaise(promise):
assert isinstance(promise, omemo.promise.Promise)
while not promise.done: time.sleep(.01)
if promise.fulfilled:
return promise.value
raise promise.reason
def assertPromiseRejected(promise):
assert isinstance(promise, omemo.promise.Promise)
while not promise.done: time.sleep(.01)
assert promise.rejected
return promise.reason
def overrideOwnData(st_sync, st_async, jid, did):
done = False
def cb(success, value):
assert success
done = True
st_sync.storeOwnData(None, jid, did)
st_async.storeOwnData(cb, jid, did)
while not cb: pass
def getDevices(sm_sync, sm_async, jid, inactive, active):
inactive = set(inactive)
active = set(active)
devices_sync = sm_sync.getDevices(jid)
devices_async = assertPromiseFulfilled(sm_async.getDevices(jid))
assert set(devices_sync ["inactive"].keys()) == inactive
assert set(devices_async["inactive"].keys()) == inactive
assert devices_sync ["active"] == active
assert devices_async["active"] == active
def newDeviceList(sm_sync, sm_async, jid, devices):
sm_sync.newDeviceList(jid, devices)
assertPromiseFulfilled(sm_async.newDeviceList(jid, devices))
def createSessionManagers(st_sync = None, st_async = None, expect = None):
if st_sync == None:
st_sync = SyncInMemoryStorage()
if st_async == None:
st_async = AsyncInMemoryStorage()
try:
sm_sync = SessionManager.create(
st_sync,
DeletingOTPKPolicy,
SignalBackend,
A_JID,
A_DID
)
except Exception as e:
assert expect != None
assert isinstance(e, expect)
sm_async_promise = SessionManager.create(
st_async,
DeletingOTPKPolicy,
SignalBackend,
A_JID,
A_DID
)
if expect == None:
sm_async = assertPromiseFulfilled(sm_async_promise)
else:
assert isinstance(assertPromiseRejected(sm_async_promise), expect)
if expect == None:
assert isinstance(sm_sync, SessionManager)
assert isinstance(sm_async, SessionManager)
return st_sync, sm_sync, st_async, sm_async
def createOtherSessionManagers(jid, dids, other_dids, otpk_policy = None):
if otpk_policy == None:
otpk_policy = DeletingOTPKPolicy
sms_sync = {}
sms_async = {}
for did in dids:
st_sync = SyncInMemoryStorage()
st_async = AsyncInMemoryStorage()
sm_sync = SessionManager.create(st_sync, otpk_policy, SignalBackend, jid, did)
sm_async = assertPromiseFulfilled(SessionManager.create(
st_async,
otpk_policy,
SignalBackend,
jid,
did
))
assert isinstance(sm_sync, SessionManager)
assert isinstance(sm_async, SessionManager)
for other_jid in other_dids:
newDeviceList(sm_sync, sm_async, other_jid, other_dids[other_jid])
sms_sync[did] = sm_sync
sms_async[did] = sm_async
return sms_sync, sms_async
def trust(sm_sync, sm_async, sms_sync, sms_async, jid_to_trust, devices_to_trust):
try:
for device in devices_to_trust:
ik_sync = sms_sync [device].public_bundle.ik
ik_async = sms_async[device].public_bundle.ik
sm_sync.trust(jid_to_trust, device, ik_sync)
assertPromiseFulfilled(sm_async.trust(jid_to_trust, device, ik_async))
except TypeError:
ik_sync = sms_sync .public_bundle.ik
ik_async = sms_async.public_bundle.ik
sm_sync.trust(jid_to_trust, devices_to_trust, ik_sync)
assertPromiseFulfilled(sm_async.trust(jid_to_trust, devices_to_trust, ik_async))
def distrust(sm_sync, sm_async, sms_sync, sms_async, jid_to_trust, devices_to_trust):
try:
for device in devices_to_trust:
ik_sync = sms_sync [device].public_bundle.ik
ik_async = sms_async[device].public_bundle.ik
sm_sync.distrust(jid_to_trust, device, ik_sync)
assertPromiseFulfilled(sm_async.distrust(jid_to_trust, device, ik_async))
except TypeError:
ik_sync = sms_sync .public_bundle.ik
ik_async = sms_async.public_bundle.ik
sm_sync.distrust(jid_to_trust, devices_to_trust, ik_sync)
assertPromiseFulfilled(sm_async.distrust(
jid_to_trust,
devices_to_trust,
ik_async
))
def messageEncryption(
pass_bundles = None,
trust_devices = None,
pass_devices = True,
expect_problems = None,
expected_problems = None,
trust_alice = True,
allow_untrusted_decryption = False,
expect_untrusted_decryption = None
):
if pass_bundles == None:
pass_bundles = set(B_DIDS)
else:
pass_bundles = set(pass_bundles)
if trust_devices == None:
trust_devices = set(B_DIDS)
else:
trust_devices = set(trust_devices)
if expect_problems == None:
expect_problems = set()
else:
expect_problems = set(expect_problems)
st_sync, sm_sync, st_async, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
B_DIDS,
{ A_JID: [ A_DID ] }
)
if pass_devices:
newDeviceList(sm_sync, sm_async, B_JID, B_DIDS)
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, trust_devices)
if trust_alice:
for b_did in B_DIDS:
trust(b_sms_sync[b_did], b_sms_async[b_did], sm_sync, sm_async, A_JID, A_DID)
bundles_sync = {
did: b_sms_sync[did].public_bundle
for did in B_DIDS
if did in pass_bundles
}
bundles_async = {
did: b_sms_async[did].public_bundle
for did in B_DIDS
if did in pass_bundles
}
problems_sync = []
problems_async = []
msg = "single message".encode("UTF-8")
try:
encrypted_sync = sm_sync.encryptMessage(
[ B_JID ],
msg,
{ B_JID: bundles_sync },
{ B_JID: expect_problems }
)
except EncryptionProblemsException as e:
problems_sync = e.problems
try:
encrypted_async = assertPromiseFulfilledOrRaise(sm_async.encryptMessage(
[ B_JID ],
msg,
{ B_JID: bundles_async },
{ B_JID: expect_problems }
))
except EncryptionProblemsException as e:
problems_async = e.problems
if expected_problems == None:
successes_sync = set(encrypted_sync ["keys"][B_JID].keys())
successes_async = set(encrypted_async["keys"][B_JID].keys())
expected_successes = set(B_DIDS) - expect_problems
assert expected_successes == successes_sync == successes_async
for did in expected_successes:
try:
# Check that the pre_key flag is set correctly
expect_pre_key = did in bundles_sync
assert encrypted_sync["keys"][B_JID][did]["pre_key"] == expect_pre_key
decrypted_sync = b_sms_sync[did].decryptMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][did]["data"],
encrypted_sync["keys"][B_JID][did]["pre_key"],
encrypted_sync["payload"],
allow_untrusted = allow_untrusted_decryption
)
assert expect_untrusted_decryption == None
except TrustException as e:
assert e == TrustException(
A_JID,
A_DID,
sm_sync.public_bundle.ik,
expect_untrusted_decryption
)
try:
# Check that the pre_key flag is set correctly
expect_pre_key = did in bundles_async
assert encrypted_async["keys"][B_JID][did]["pre_key"] == expect_pre_key
decrypted_async = assertPromiseFulfilledOrRaise(
b_sms_async[did].decryptMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][did]["data"],
encrypted_async["keys"][B_JID][did]["pre_key"],
encrypted_async["payload"],
allow_untrusted = allow_untrusted_decryption
)
)
assert expect_untrusted_decryption == None
except TrustException as e:
assert expect_untrusted_decryption
assert e == TrustException(
A_JID,
A_DID,
sm_async.public_bundle.ik,
expect_untrusted_decryption
)
if expect_untrusted_decryption == None:
assert decrypted_sync == decrypted_async == msg
else:
assert len(problems_sync) == len(problems_async) == len(expected_problems)
zipped = zip(problems_sync, problems_async, expected_problems)
for problem_sync, problem_async, problem_expected in zipped:
if isinstance(problem_expected, TrustException):
problem_expected_sync = TrustException(
problem_expected.bare_jid,
problem_expected.device,
sm_sync.public_bundle.ik
if problem_expected.bare_jid == A_JID else
b_sms_sync[problem_expected.device].public_bundle.ik,
problem_expected.problem
)
problem_expected_async = TrustException(
problem_expected.bare_jid,
problem_expected.device,
sm_async.public_bundle.ik
if problem_expected.bare_jid == A_JID else
b_sms_async[problem_expected.device].public_bundle.ik,
problem_expected.problem
)
assert problem_sync == problem_expected_sync
assert problem_async == problem_expected_async
else:
assert problem_sync == problem_async == problem_expected
def test_create():
st_sync, _, st_async, _ = createSessionManagers()
# Create using the same storage with the same information
createSessionManagers(st_sync, st_async)
# Replace the device id
overrideOwnData(st_sync, st_async, A_JID, B_DID)
# This time, the create call should raise an InconsistentInfoException
createSessionManagers(st_sync, st_async, InconsistentInfoException)
# Replace the jid
overrideOwnData(st_sync, st_async, B_JID, A_DID)
# This time, the create call should raise an InconsistentInfoException
createSessionManagers(st_sync, st_async, InconsistentInfoException)
# Replace both the device id and the jid
overrideOwnData(st_sync, st_async, B_JID, B_DID)
# This time, the create call should raise an InconsistentInfoException
createSessionManagers(st_sync, st_async, InconsistentInfoException)
# Go back to the original data
overrideOwnData(st_sync, st_async, A_JID, A_DID)
# Create using the same storage with the same information
createSessionManagers(st_sync, st_async)
def test_bundle_serialization():
_, sm_sync, _, sm_async = createSessionManagers()
bundle_sync = sm_sync.public_bundle
bundle_async = sm_async.public_bundle
sb = SignalBackend
ex = omemo.ExtendedPublicBundle
assert ex.parse(sb, **bundle_sync.serialize(sb)) == bundle_sync
assert ex.parse(sb, **bundle_async.serialize(sb)) == bundle_async
def test_deviceList():
_, sm_sync, _, sm_async = createSessionManagers()
getDevices(sm_sync, sm_async, None, [], [ A_DID ])
getDevices(sm_sync, sm_async, A_JID, [], [ A_DID ])
newDeviceList(sm_sync, sm_async, A_JID, A_DIDS)
getDevices(sm_sync, sm_async, A_JID, [], A_DIDS)
newDeviceList(sm_sync, sm_async, A_JID, A_DIDS[:2])
getDevices(sm_sync, sm_async, A_JID, A_DIDS[2:], A_DIDS[:2])
newDeviceList(sm_sync, sm_async, A_JID, [])
getDevices(sm_sync, sm_async, A_JID, set(A_DIDS) - set([ A_DID ]), [ A_DID ])
def test_messageEncryption():
messageEncryption()
def test_messageEncryption_missingBundle():
messageEncryption(pass_bundles = B_DIDS[:2], expected_problems = [
MissingBundleException(B_JID, B_DIDS[2])
])
def test_messageEncryption_allBundlesMissing():
messageEncryption(pass_bundles = [], expected_problems = [
MissingBundleException(B_JID, B_DIDS[0]),
MissingBundleException(B_JID, B_DIDS[1]),
MissingBundleException(B_JID, B_DIDS[2]),
NoEligibleDevicesException(B_JID)
])
def test_messageEncryption_untrustedDevice():
messageEncryption(trust_devices = B_DIDS[:2], expected_problems = [
TrustException(B_JID, B_DIDS[2], "placeholder", "undecided") # TODO
])
def test_messageEncryption_noTrustedDevices():
messageEncryption(trust_devices = [], expected_problems = [
TrustException(B_JID, B_DIDS[0], "placeholder", "undecided"), # TODO
TrustException(B_JID, B_DIDS[1], "placeholder", "undecided"), # TODO
TrustException(B_JID, B_DIDS[2], "placeholder", "undecided"), # TODO
NoEligibleDevicesException(B_JID)
])
def test_messageEncryption_noDevices():
messageEncryption(pass_devices = False, expected_problems = [
NoDevicesException(B_JID)
])
def test_messageEncryption_expectProblems():
messageEncryption(
pass_bundles = B_DIDS[:2],
trust_devices = B_DIDS[1:],
expected_problems = [
MissingBundleException(B_JID, B_DIDS[2]),
TrustException(B_JID, B_DIDS[0], "placeholder", "undecided") # TODO
]
)
messageEncryption(
pass_bundles = B_DIDS[:2],
trust_devices = B_DIDS[1:],
expect_problems = [ B_DIDS[0], B_DIDS[2] ]
)
def encryptBigFile(encryptor, name):
location = os.path.dirname(os.path.abspath(__file__))
plaintext_path = os.path.join(location, "confidential.txt")
encrypted_path = os.path.join(location, "confidential_encrypted_" + name + ".txt")
with open(plaintext_path, "rb") as src, open(encrypted_path, "wb") as dest:
while True:
block = src.read(1024)
if len(block) == 0:
dest.write(encryptor.finalize())
break
dest.write(encryptor.update(block))
def decryptBigFile(decryptor, name):
location = os.path.dirname(os.path.abspath(__file__))
plaintext_path = os.path.join(location, "confidential.txt")
encrypted_path = os.path.join(location, "confidential_encrypted_" + name + ".txt")
decrypted_path = os.path.join(location, "confidential_decrypted_" + name + ".txt")
with open(encrypted_path, "rb") as src, open(decrypted_path, "wb") as dest:
while True:
block = src.read(1024)
if len(block) == 0:
dest.write(decryptor.finalize())
break
dest.write(decryptor.update(block))
os.remove(encrypted_path)
with open(plaintext_path, "rb") as src, open(decrypted_path, "rb") as dest:
while True:
plaintext_block = src.read(1024)
decrypted_block = dest.read(1024)
assert plaintext_block == decrypted_block
if len(plaintext_block) == len(decrypted_block) == 0:
break
os.remove(decrypted_path)
def test_keyTransportMessage():
_, sm_sync, _, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] }
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
b_sm_sync = b_sms_sync [B_DID]
b_sm_async = b_sms_async[B_DID]
encrypted_sync = sm_sync.encryptKeyTransportMessage(
[ B_JID ],
lambda encryptor: encryptBigFile(encryptor, "sync"),
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
encrypted_async = assertPromiseFulfilled(sm_async.encryptKeyTransportMessage(
[ B_JID ],
lambda encryptor: encryptBigFile(encryptor, "async"),
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
decryptor_sync = b_sm_sync.decryptKeyTransportMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][B_DID]["data"],
encrypted_sync["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
)
decryptor_async = assertPromiseFulfilledOrRaise(b_sm_async.decryptKeyTransportMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][B_DID]["data"],
encrypted_async["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
))
decryptBigFile(decryptor_sync, "sync")
decryptBigFile(decryptor_async, "async")
def test_ratchetForwardingMessage():
_, sm_sync, _, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] }
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
# This should not require trusting the devices.
#trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
b_sm_sync = b_sms_sync [B_DID]
b_sm_async = b_sms_async[B_DID]
encrypted_sync = sm_sync.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
encrypted_async = assertPromiseFulfilled(sm_async.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
b_sm_sync.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][B_DID]["data"],
encrypted_sync["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
)
assertPromiseFulfilledOrRaise(b_sm_async.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][B_DID]["data"],
encrypted_async["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
))
def test_messageDecryption_noTrust():
messageEncryption(trust_alice = False, expect_untrusted_decryption = "undecided")
def test_messageDecryption_noTrust_allowUntrusted():
messageEncryption(trust_alice = False, allow_untrusted_decryption = True)
def test_messageDecryption_noSession():
_, sm_sync, _, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] }
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
b_sm_sync = b_sms_sync [B_DID]
b_sm_async = b_sms_async[B_DID]
sm_sync.encryptMessage(
[ B_JID ],
"first message".encode("UTF-8"),
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
assertPromiseFulfilled(sm_async.encryptMessage(
[ B_JID ],
"first message".encode("UTF-8"),
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
encrypted_sync = sm_sync.encryptMessage(
[ B_JID ],
"second message".encode("UTF-8")
)
encrypted_async = assertPromiseFulfilled(sm_async.encryptMessage(
[ B_JID ],
"second message".encode("UTF-8")
))
try:
decrypted_sync = b_sm_sync.decryptMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][B_DID]["data"],
encrypted_sync["keys"][B_JID][B_DID]["pre_key"],
encrypted_sync["payload"]
)
assert False
except NoSessionException as e:
assert e == NoSessionException(A_JID, A_DID)
try:
decrypted_async = assertPromiseFulfilledOrRaise(b_sm_async.decryptMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][B_DID]["data"],
encrypted_async["keys"][B_JID][B_DID]["pre_key"],
encrypted_async["payload"]
))
assert False
except NoSessionException as e:
assert e == NoSessionException(A_JID, A_DID)
def otpkPolicyTest(otpk_policy, expect_exception):
_, sm_sync, _, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] },
otpk_policy = otpk_policy
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
b_sm_sync = b_sms_sync [B_DID]
b_sm_async = b_sms_async[B_DID]
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
trust(b_sm_sync, b_sm_async, sm_sync, sm_async, A_JID, A_DID)
pre_key_message_sync = sm_sync.encryptMessage(
[ B_JID ],
"first message".encode("UTF-8"),
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
pre_key_message_async = assertPromiseFulfilled(sm_async.encryptMessage(
[ B_JID ],
"first message".encode("UTF-8"),
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
params_sync = [
A_JID,
A_DID,
pre_key_message_sync["iv"],
pre_key_message_sync["keys"][B_JID][B_DID]["data"],
pre_key_message_sync["keys"][B_JID][B_DID]["pre_key"],
pre_key_message_sync["payload"]
]
params_async = [
A_JID,
A_DID,
pre_key_message_async["iv"],
pre_key_message_async["keys"][B_JID][B_DID]["data"],
pre_key_message_async["keys"][B_JID][B_DID]["pre_key"],
pre_key_message_async["payload"]
]
b_sm_sync.decryptMessage(*params_sync)
assertPromiseFulfilled(b_sm_async.decryptMessage(*params_async))
try:
b_sm_sync.decryptMessage(*params_sync)
assert not expect_exception
except KeyExchangeException as e:
assert expect_exception
assert e == KeyExchangeException(A_JID, A_DID, "unused")
try:
assertPromiseFulfilledOrRaise(b_sm_async.decryptMessage(*params_async))
assert not expect_exception
except KeyExchangeException as e:
assert expect_exception
assert e == KeyExchangeException(A_JID, A_DID, "unused")
def test_otpkPolicy_deleting():
otpkPolicyTest(DeletingOTPKPolicy, True)
def test_otpkPolicy_keeping():
otpkPolicyTest(KeepingOTPKPolicy, False)
def test_trustRetrieval():
_, sm_sync, _, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] }
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
assert sm_sync.getTrustForDevice(B_JID, B_DID) == None
assert assertPromiseFulfilled(sm_async.getTrustForDevice(B_JID, B_DID)) == None
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
assert sm_sync.getTrustForDevice(B_JID, B_DID) == {
"key": b_sms_sync[B_DID].public_bundle.ik,
"trusted": True
}
assert assertPromiseFulfilled(sm_async.getTrustForDevice(B_JID, B_DID)) == {
"key": b_sms_async[B_DID].public_bundle.ik,
"trusted": True
}
distrust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
assert sm_sync.getTrustForDevice(B_JID, B_DID) == {
"key": b_sms_sync[B_DID].public_bundle.ik,
"trusted": False
}
assert assertPromiseFulfilled(sm_async.getTrustForDevice(B_JID, B_DID)) == {
"key": b_sms_async[B_DID].public_bundle.ik,
"trusted": False
}
assert sm_sync.getTrustForJID(B_JID) == {
"active": {
B_DID: {
"key": b_sms_sync[B_DID].public_bundle.ik,
"trusted": False
}
},
"inactive": {}
}
assert assertPromiseFulfilled(sm_async.getTrustForJID(B_JID)) == {
"active": {
B_DID: {
"key": b_sms_async[B_DID].public_bundle.ik,
"trusted": False
}
},
"inactive": {}
}
def test_serialization():
st_sync, sm_sync, st_async, sm_async = createSessionManagers()
b_sms_sync, b_sms_async = createOtherSessionManagers(
B_JID,
[ B_DID ],
{ A_JID: [ A_DID ] }
)
newDeviceList(sm_sync, sm_async, B_JID, [ B_DID ])
trust(sm_sync, sm_async, b_sms_sync, b_sms_async, B_JID, [ B_DID ])
b_sm_sync = b_sms_sync [B_DID]
b_sm_async = b_sms_async[B_DID]
encrypted_sync = sm_sync.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
encrypted_async = assertPromiseFulfilled(sm_async.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
b_sm_sync.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][B_DID]["data"],
encrypted_sync["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
)
assertPromiseFulfilledOrRaise(b_sm_async.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][B_DID]["data"],
encrypted_async["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
))
# After this code is done, there is an updated state and a session in the cache.
# Create new SessionManagers using the storage of the old one and check, whether the
# state and the session are still usable.
_, sm_sync, _, sm_async = createSessionManagers(
st_sync = st_sync,
st_async = st_async
)
encrypted_sync = sm_sync.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_sync.public_bundle } }
)
encrypted_async = assertPromiseFulfilled(sm_async.encryptRatchetForwardingMessage(
[ B_JID ],
{ B_JID: { B_DID: b_sm_async.public_bundle } }
))
b_sm_sync.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_sync["iv"],
encrypted_sync["keys"][B_JID][B_DID]["data"],
encrypted_sync["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
)
assertPromiseFulfilledOrRaise(b_sm_async.decryptRatchetForwardingMessage(
A_JID,
A_DID,
encrypted_async["iv"],
encrypted_async["keys"][B_JID][B_DID]["data"],
encrypted_async["keys"][B_JID][B_DID]["pre_key"],
allow_untrusted = True
))
def test_stresstest_sync():
# Create 100 random JIDs with 10 random devices each
devices = {}
main_jid = None
main_did = None
while len(devices) < 100:
jid = generateRandomJID()
if main_jid == None:
main_jid = jid
devices[jid] = set()
while len(devices[jid]) < 10:
did = omemo.util.generateDeviceID(devices[jid])
if main_did == None:
main_did = did
devices[jid].add(did)
sms = {}
for jid in devices:
sms[jid] = {}
for did in devices[jid]:
# Create a SessionManager for that jid+did
sms[jid][did] = SessionManager.create(
SyncInMemoryStorage(),
DeletingOTPKPolicy,
SignalBackend,
jid,
did
)
bundles = {}
for jid in devices:
bundles[jid] = {}
for did in devices[jid]:
bundles[jid][did] = sms[jid][did].public_bundle
main = sms[main_jid][main_did]
# Tell the main SessionManager about all of the other jids and devices
for jid in devices:
main.newDeviceList(jid, devices[jid])
# Tell the main SessionManager to trust all other jids and devices
for jid in devices:
for did in devices[jid]:
main.trust(jid, did, sms[jid][did].public_bundle.ik)
cProfile.runctx("""
main.encryptMessage(
list(devices.keys()),
"This is a stresstest!".encode("UTF-8"),
bundles = bundles
)
""", {}, {
"main": main,
"devices": devices,
"bundles": bundles
})
# If the code reaches this point, the stress test has passed
assert True
def test_stresstest_async():
# Create 100 random JIDs with 10 random devices each
devices = {}
main_jid = None
main_did = None
while len(devices) < 100:
jid = generateRandomJID()
if main_jid == None:
main_jid = jid
devices[jid] = set()
while len(devices[jid]) < 10:
did = omemo.util.generateDeviceID(devices[jid])
if main_did == None:
main_did = did
devices[jid].add(did)
sms = {}
for jid in devices:
sms[jid] = {}
for did in devices[jid]:
# Create a SessionManager for that jid+did
sms[jid][did] = assertPromiseFulfilled(SessionManager.create(
AsyncInMemoryStorage(),
DeletingOTPKPolicy,
SignalBackend,
jid,
did
))
bundles = {}
for jid in devices:
bundles[jid] = {}