Exemplo n.º 1
0
    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:
                pass
                #good
        bobPreKey = PreKeyBundle(bobIdentityKeyStore.getLocalRegistrationId(), 1,
                                              31337, bobPreKeyPair.getPublicKey(),
                                              22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                              bobIdentityKeyStore.getIdentityKeyPair().getPublicKey())

        aliceSessionBuilder.processPreKeyBundle(bobPreKey)
Exemplo n.º 2
0
        def onSuccess(resultNode, getKeysEntity):
            entity_ = ResultGetKeysIqProtocolEntity.fromProtocolTreeNode(resultNode)
            resultJids = entity_.getJids()
            successJids = []
            errorJids = {}  # jid -> exception

            for jid in getKeysEntity.getJids():
                if jid not in resultJids:
                    self.skipEncJids.append(jid)
                    continue

                recipient_id = jid.split('@')[0]
                preKeyBundle = entity_.getPreKeyBundleFor(jid)
                sessionBuilder = SessionBuilder(self.store, self.store, self.store, self.store, recipient_id, 1)
                try:
                    sessionBuilder.processPreKeyBundle(preKeyBundle)
                    successJids.append(jid)
                except UntrustedIdentityException as e:
                    if self.getProp(PROP_IDENTITY_AUTOTRUST, False):
                        logger.warning("Autotrusting identity for %s" % e.getName())
                        self.store.saveIdentity(e.getName(), e.getIdentityKey())
                        successJids.append(jid)
                    else:
                        errorJids[jid] = e
                        logger.error(e)
                        logger.warning("Ignoring message with untrusted identity")

                resultClbk(successJids, errorJids)
Exemplo n.º 3
0
        def onSuccess(resultNode, getKeysEntity):
            entity = ResultGetKeysIqProtocolEntity.fromProtocolTreeNode(resultNode)
            resultJids = entity.getJids()
            successJids = []
            errorJids = {} #jid -> exception

            for jid in getKeysEntity.getJids():
                if jid not in resultJids:
                    self.skipEncJids.append(jid)
                    continue

                recipient_id = jid.split('@')[0]
                preKeyBundle = entity.getPreKeyBundleFor(jid)
                sessionBuilder = SessionBuilder(self.store, self.store, self.store, self.store, recipient_id, 1)
                try:
                    sessionBuilder.processPreKeyBundle(preKeyBundle)
                    successJids.append(jid)
                except UntrustedIdentityException as e:
                    if self.getProp(PROP_IDENTITY_AUTOTRUST, False):
                        logger.warning("Autotrusting identity for %s" % e.getName())
                        self.store.saveIdentity(e.getName(), e.getIdentityKey())
                        successJids.append(jid)
                    else:
                        errorJids[jid] = e
                        logger.error(e)
                        logger.warning("Ignoring message with untrusted identity")

                resultClbk(successJids, errorJids)
Exemplo n.º 4
0
 def create_session(self, username, prekeybundle, autotrust=False):
     """
     :param username:
     :type username: str
     :param prekeybundle:
     :type prekeybundle: PreKeyBundle
     :return:
     :rtype:
     """
     logger.debug("create_session(username=%s, prekeybundle=[omitted], autotrust=%s)" % (username, autotrust))
     session_builder = SessionBuilder(self._store, self._store, self._store, self._store, username, 1)
     try:
         session_builder.processPreKeyBundle(prekeybundle)
     except UntrustedIdentityException as ex:
         if autotrust:
             self.trust_identity(ex.getName(), ex.getIdentityKey())
         else:
             raise exceptions.UntrustedIdentityException(ex.getName(), ex.getIdentityKey())
Exemplo n.º 5
0
    def onGetKeysResult(self, resultNode, getKeysEntity, processPendingFn):
        entity = ResultGetKeysIqProtocolEntity.fromProtocolTreeNode(resultNode)

        resultJids = entity.getJids()
        for jid in getKeysEntity.getJids():

            if jid not in resultJids:
                self.skipEncJids.append(jid)
                self.processPendingMessages(jid)
                continue

            recipient_id = jid.split('@')[0]
            preKeyBundle = entity.getPreKeyBundleFor(jid)

            sessionBuilder = SessionBuilder(self.store, self.store, self.store,
                                               self.store, recipient_id, 1)
            sessionBuilder.processPreKeyBundle(preKeyBundle)

            processPendingFn(jid)
Exemplo n.º 6
0
    def onGetKeysResult(self, resultNode, getKeysEntity, processPendingFn):
        entity = ResultGetKeysIqProtocolEntity.fromProtocolTreeNode(resultNode)

        resultJids = entity.getJids()
        for jid in getKeysEntity.getJids():

            if jid not in resultJids:
                self.skipEncJids.append(jid)
                self.processPendingMessages(jid)
                continue

            recipient_id = jid.split('@')[0]
            preKeyBundle = entity.getPreKeyBundleFor(jid)

            sessionBuilder = SessionBuilder(self.store, self.store, self.store,
                                               self.store, recipient_id, 1)
            sessionBuilder.processPreKeyBundle(preKeyBundle)

            processPendingFn(jid)
Exemplo n.º 7
0
    def build_session(self, recipient_id, device_id, bundle_dict):
        sessionBuilder = SessionBuilder(self.store, self.store, self.store,
                                        self.store, recipient_id, device_id)

        registration_id = self.store.getLocalRegistrationId()

        preKeyPublic = DjbECPublicKey(bundle_dict['preKeyPublic'][1:])

        signedPreKeyPublic = DjbECPublicKey(bundle_dict['signedPreKeyPublic'][
            1:])
        identityKey = IdentityKey(DjbECPublicKey(bundle_dict['identityKey'][
            1:]))

        prekey_bundle = PreKeyBundle(
            registration_id, device_id, bundle_dict['preKeyId'], preKeyPublic,
            bundle_dict['signedPreKeyId'], signedPreKeyPublic,
            bundle_dict['signedPreKeySignature'], identityKey)

        sessionBuilder.processPreKeyBundle(prekey_bundle)
        return self.get_session_cipher(recipient_id, device_id)
Exemplo n.º 8
0
    def build_session(self, recipient_id, device_id, bundle_dict):
        sessionBuilder = SessionBuilder(self.store, self.store, self.store,
                                        self.store, recipient_id, device_id)

        registration_id = self.store.getLocalRegistrationId()

        preKeyPublic = DjbECPublicKey(bundle_dict['preKeyPublic'][1:])

        signedPreKeyPublic = DjbECPublicKey(
            bundle_dict['signedPreKeyPublic'][1:])
        identityKey = IdentityKey(
            DjbECPublicKey(bundle_dict['identityKey'][1:]))

        prekey_bundle = PreKeyBundle(registration_id, device_id,
                                     bundle_dict['preKeyId'], preKeyPublic,
                                     bundle_dict['signedPreKeyId'],
                                     signedPreKeyPublic,
                                     bundle_dict['signedPreKeySignature'],
                                     identityKey)

        sessionBuilder.processPreKeyBundle(prekey_bundle)
        return self.get_session_cipher(recipient_id, device_id)
Exemplo n.º 9
0
    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 != None)

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

        self.assertTrue(bobKeyExchangeMessage != None)

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

        self.assertTrue(response == 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 as uie:
            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID, aliceKeyExchangeMessage.getIdentityKey())
        bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(aliceKeyExchangeMessage)

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

        self.runInteraction(aliceStore, bobStore)
Exemplo n.º 10
0
    def build_session(self, jid, device_id, bundle):
        session = SessionBuilder(self._storage, self._storage, self._storage,
                                 self._storage, jid, device_id)

        registration_id = self._storage.getLocalRegistrationId()

        prekey = bundle.pick_prekey()
        otpk = DjbECPublicKey(prekey['key'][1:])

        spk = DjbECPublicKey(bundle.spk['key'][1:])
        ik = IdentityKey(DjbECPublicKey(bundle.ik[1:]))

        prekey_bundle = PreKeyBundle(registration_id,
                                     device_id,
                                     prekey['id'],
                                     otpk,
                                     bundle.spk['id'],
                                     spk,
                                     bundle.spk_signature,
                                     ik)

        session.processPreKeyBundle(prekey_bundle)
        self._get_session_cipher(jid, device_id)
Exemplo n.º 11
0
def handle_keyexchange(store, who, body):
    messageBytes = binascii.unhexlify(body)
    print("UNWRAPPED >>> [%r]" % binascii.hexlify(messageBytes))

    try:
        sb = SessionBuilder(store, store, store, store, who, 1)
        print("SessionBuilder >>>", sb)

        ke = KeyExchangeMessage(serialized=bytearray(messageBytes))
        print("KeyExchangeMessage >>>", ke)

        response = sb.processKeyExchangeMessage(ke)
        print("RESPONSE >>>", response)

        if response:
            print("RESPONSE >>> %r" % repr(response))
            return binascii.hexlify(response.serialize())

    except Exception as e:
        print("EXCEPTION >>>", e)

        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Exemplo n.º 12
0
def handle_keyexchange(store, who, body):
    messageBytes = binascii.unhexlify(body)
    print("UNWRAPPED >>> [%r]" % binascii.hexlify(messageBytes))

    try:
        sb = SessionBuilder(store, store, store, store, who, 1)
        print("SessionBuilder >>>", sb)

        ke = KeyExchangeMessage(serialized=bytearray(messageBytes))
        print("KeyExchangeMessage >>>", ke)

        response = sb.processKeyExchangeMessage(ke)
        print("RESPONSE >>>", response)

        if response:
            print("RESPONSE >>> %r" % repr(response))
            return binascii.hexlify(response.serialize())

    except Exception as e:
        print("EXCEPTION >>>", e)

        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Exemplo n.º 13
0
def main():
    aliceStore = InMemoryAxolotlStore()
    aliceSessionBuilder = SessionBuilder(aliceStore, aliceStore, aliceStore,
                                         aliceStore, BOB_RECIPIENT_ID, 1)

    raw_ke = input("Enter key exchange: ")
    response = handle_keyexchange(aliceStore, BOB_RECIPIENT_ID,
                                  raw_ke.rstrip())
    print
    print
    print("RESPONSE >>>", response)

    raw_message = input("Enter raw message: ")
    print
    print
    handle_data_msg(aliceStore, BOB_RECIPIENT_ID, raw_message.rstrip())
Exemplo n.º 14
0
 def getSessionBuilder(self, identity):
     """Construct SessionBuilder for given identity"""
     return SessionBuilder(self.store, self.store, self.store, self.store,
                           identity, self.DEFAULT_DEVICE_ID)
Exemplo n.º 15
0
    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    = "L'homme est condamné à être 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() != 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