File: test_sessionbuilder.py

package info (click to toggle)
python-axolotl 0.2.3-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 592 kB
  • sloc: python: 2,962; makefile: 3
file content (334 lines) | stat: -rw-r--r-- 17,070 bytes parent folder | download
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
# -*- coding: utf-8 -*-

import unittest
import time
import sys

from ..invalidkeyexception import InvalidKeyException
from ..sessionbuilder import SessionBuilder
from ..sessioncipher import SessionCipher
from ..ecc.curve import Curve
from ..protocol.ciphertextmessage import CiphertextMessage
from ..protocol.whispermessage import WhisperMessage
from ..protocol.prekeywhispermessage import PreKeyWhisperMessage
from ..state.prekeybundle import PreKeyBundle
from ..tests.inmemoryaxolotlstore import InMemoryAxolotlStore
from ..state.prekeyrecord import PreKeyRecord
from ..state.signedprekeyrecord import SignedPreKeyRecord
from ..tests.inmemoryidentitykeystore import InMemoryIdentityKeyStore
from ..protocol.keyexchangemessage import KeyExchangeMessage
from ..untrustedidentityexception import UntrustedIdentityException


class SessionBuilderTest(unittest.TestCase):
    ALICE_RECIPIENT_ID = 5
    BOB_RECIPIENT_ID = 2

    def test_basicPreKeyV2(self):
        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID,
                                             1)

        bobStore = InMemoryAxolotlStore()
        bobPreKeyPair = Curve.generateKeyPair()
        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337, bobPreKeyPair.getPublicKey(),
                                 0, None, None, bobStore.getIdentityKeyPair().getPublicKey())

        try:
            aliceSessionBuilder.processPreKeyBundle(bobPreKey)
            raise AssertionError("Should fail with missing unsigned prekey!");
        except InvalidKeyException:
            # good
            pass

        return

    def test_basicPreKeyV3(self):
        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID,
                                             1)

        bobStore = InMemoryAxolotlStore()
        bobPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                            bobSignedPreKeyPair.getPublicKey().serialize())

        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337, bobPreKeyPair.getPublicKey(),
                                 22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                 bobStore.getIdentityKeyPair().getPublicKey())

        aliceSessionBuilder.processPreKeyBundle(bobPreKey)
        self.assertTrue(aliceStore.containsSession(self.__class__.BOB_RECIPIENT_ID, 1))
        self.assertTrue(aliceStore.loadSession(self.__class__.BOB_RECIPIENT_ID,
                                               1).getSessionState().getSessionVersion() == 3)

        originalMessage = b"L'homme est condamne a etre libre"
        aliceSessionCipher = SessionCipher(aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           self.__class__.BOB_RECIPIENT_ID,
                                           1)
        outgoingMessage = aliceSessionCipher.encrypt(originalMessage)

        self.assertTrue(outgoingMessage.getType() == CiphertextMessage.PREKEY_TYPE)

        incomingMessage = PreKeyWhisperMessage(serialized=outgoingMessage.serialize())
        bobStore.storePreKey(31337, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))
        bobStore.storeSignedPreKey(22, SignedPreKeyRecord(22,
                                                          int(time.time() * 1000),
                                                          bobSignedPreKeyPair,
                                                          bobSignedPreKeySignature))

        bobSessionCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)

        plaintext = bobSessionCipher.decryptPkmsg(incomingMessage)
        self.assertEqual(originalMessage, plaintext)
        # @@TODO: in callback assertion
        # self.assertFalse(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))

        self.assertTrue(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))

        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID,
                                             1).getSessionState().getSessionVersion() == 3)
        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID,
                                             1).getSessionState().getAliceBaseKey() is not None)
        self.assertEqual(originalMessage, plaintext)

        bobOutgoingMessage = bobSessionCipher.encrypt(originalMessage)
        self.assertTrue(bobOutgoingMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        alicePlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobOutgoingMessage.serialize()))

        self.assertEqual(alicePlaintext, originalMessage)

        self.runInteraction(aliceStore, bobStore)

        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID,
                                             1)
        aliceSessionCipher = SessionCipher(aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           self.__class__.BOB_RECIPIENT_ID,
                                           1)

        bobPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                            bobSignedPreKeyPair.getPublicKey().serialize())
        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31338, bobPreKeyPair.getPublicKey(),
                                 23, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                 bobStore.getIdentityKeyPair().getPublicKey())

        bobStore.storePreKey(31338, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))
        bobStore.storeSignedPreKey(23, SignedPreKeyRecord(23,
                                                          int(time.time() * 1000),
                                                          bobSignedPreKeyPair,
                                                          bobSignedPreKeySignature))
        aliceSessionBuilder.processPreKeyBundle(bobPreKey)

        outgoingMessage = aliceSessionCipher.encrypt(originalMessage)

        try:
            plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage))
            raise AssertionError("shouldn't be trusted!")
        except Exception:
            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID,
                                  PreKeyWhisperMessage(serialized=outgoingMessage.serialize()).getIdentityKey())

        plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage.serialize()))

        self.assertEqual(plaintext, originalMessage)

        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337,
                                 Curve.generateKeyPair().getPublicKey(), 23, bobSignedPreKeyPair.getPublicKey(),
                                 bobSignedPreKeySignature, aliceStore.getIdentityKeyPair().getPublicKey())
        try:
            aliceSessionBuilder.process(bobPreKey)
            raise AssertionError("shouldn't be trusted!")
        except Exception:
            # good
            pass

    def test_badSignedPreKeySignature(self):
        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore, aliceStore, aliceStore, aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID, 1)

        bobIdentityKeyStore = InMemoryIdentityKeyStore()

        bobPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeySignature = Curve.calculateSignature(bobIdentityKeyStore.getIdentityKeyPair().getPrivateKey(),
                                                            bobSignedPreKeyPair.getPublicKey().serialize())

        for i in range(0, len(bobSignedPreKeySignature) * 8):
            modifiedSignature = bytearray(bobSignedPreKeySignature[:])
            modifiedSignature[int(i/8)] ^= 0x01 << (i % 8)

            bobPreKey = PreKeyBundle(bobIdentityKeyStore.getLocalRegistrationId(), 1, 31337,
                                     bobPreKeyPair.getPublicKey(), 22, bobSignedPreKeyPair.getPublicKey(),
                                     modifiedSignature, bobIdentityKeyStore.getIdentityKeyPair().getPublicKey())

            try:
                aliceSessionBuilder.processPreKeyBundle(bobPreKey)
            except Exception:
                # good
                pass
        bobPreKey = PreKeyBundle(bobIdentityKeyStore.getLocalRegistrationId(), 1, 31337,
                                 bobPreKeyPair.getPublicKey(), 22, bobSignedPreKeyPair.getPublicKey(),
                                 bobSignedPreKeySignature, bobIdentityKeyStore.getIdentityKeyPair().getPublicKey())

        aliceSessionBuilder.processPreKeyBundle(bobPreKey)

    def test_basicKeyExchange(self):
        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID,
                                             1)

        bobStore = InMemoryAxolotlStore()
        bobSessionBuilder = SessionBuilder(bobStore,
                                           bobStore,
                                           bobStore,
                                           bobStore,
                                           self.__class__.ALICE_RECIPIENT_ID,
                                           1)

        aliceKeyExchangeMessage = aliceSessionBuilder.processInitKeyExchangeMessage()
        self.assertTrue(aliceKeyExchangeMessage is not None)

        aliceKeyExchangeMessageBytes = aliceKeyExchangeMessage.serialize()
        bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(KeyExchangeMessage(
            serialized=aliceKeyExchangeMessageBytes))

        self.assertTrue(bobKeyExchangeMessage is not None)

        bobKeyExchangeMessageBytes = bobKeyExchangeMessage.serialize()
        response = aliceSessionBuilder.processKeyExchangeMessage(KeyExchangeMessage(
            serialized=bobKeyExchangeMessageBytes))

        self.assertTrue(response is None)
        self.assertTrue(aliceStore.containsSession(self.__class__.BOB_RECIPIENT_ID, 1))
        self.assertTrue(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))

        self.runInteraction(aliceStore, bobStore)

        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             aliceStore,
                                             self.__class__.BOB_RECIPIENT_ID,
                                             1)
        aliceKeyExchangeMessage = aliceSessionBuilder.processInitKeyExchangeMessage()

        try:
            bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(aliceKeyExchangeMessage)
            raise AssertionError("This identity shouldn't be trusted!")
        except UntrustedIdentityException:
            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID, aliceKeyExchangeMessage.getIdentityKey())
        bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(aliceKeyExchangeMessage)

        self.assertTrue(aliceSessionBuilder.processKeyExchangeMessage(bobKeyExchangeMessage) == None)

        self.runInteraction(aliceStore, bobStore)

    def runInteraction(self, aliceStore, bobStore):
        """
        :type aliceStore: AxolotlStore
        :type  bobStore: AxolotlStore
        """
        aliceSessionCipher = SessionCipher(aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           aliceStore,
                                           self.__class__.BOB_RECIPIENT_ID,
                                           1)
        bobSessionCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)

        originalMessage = b"smert ze smert"
        aliceMessage = aliceSessionCipher.encrypt(originalMessage)

        self.assertTrue(aliceMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        plaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceMessage.serialize()))

        self.assertEqual(plaintext, originalMessage)

        bobMessage = bobSessionCipher.encrypt(originalMessage)

        self.assertTrue(bobMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        plaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobMessage.serialize()))

        self.assertEqual(plaintext, originalMessage)

        for i in range(0, 10):
            loopingMessage = b"What do we mean by saying that existence precedes essence? " \
                             b"We mean that man first of all exists, encounters himself, " \
                             b"surges up in the world--and defines himself aftward. %d" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))

            self.assertEqual(loopingPlaintext, loopingMessage)

        for i in range(0, 10):
            loopingMessage = b"What do we mean by saying that existence precedes essence? " \
                 b"We mean that man first of all exists, encounters himself, " \
                 b"surges up in the world--and defines himself aftward. %d" % i
            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)

            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))

            self.assertEqual(loopingPlaintext, loopingMessage)

        aliceOutOfOrderMessages = []

        for i in range(0, 10):
            loopingMessage = b"What do we mean by saying that existence precedes essence? " \
                 b"We mean that man first of all exists, encounters himself, " \
                 b"surges up in the world--and defines himself aftward. %d" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            aliceOutOfOrderMessages.append((loopingMessage, aliceLoopingMessage))

        for i in range(0, 10):
            loopingMessage = b"What do we mean by saying that existence precedes essence? " \
                 b"We mean that man first of all exists, encounters himself, " \
                 b"surges up in the world--and defines himself aftward. %d" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))

            self.assertEqual(loopingPlaintext, loopingMessage)

        for i in range(0, 10):
            loopingMessage = b"You can only desire based on what you know: %d" % i
            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)

            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))

            self.assertEqual(loopingPlaintext, loopingMessage)

        for aliceOutOfOrderMessage in aliceOutOfOrderMessages:
            outOfOrderPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(
                serialized=aliceOutOfOrderMessage[1].serialize()))

            self.assertEqual(outOfOrderPlaintext, aliceOutOfOrderMessage[0])