2019-02-17 17:39:00 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
"""
|
2019-02-17 17:39:00 +00:00
|
|
|
Slixmpp OMEMO plugin
|
|
|
|
Copyright (C) 2019 Maxime “pep” Buquet <pep@bouah.net>
|
|
|
|
This file is part of slixmpp-omemo.
|
2018-05-11 01:51:37 +00:00
|
|
|
|
|
|
|
See the file LICENSE for copying permission.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Set, Tuple, Union
|
2018-11-18 16:48:16 +00:00
|
|
|
|
2018-11-18 11:00:25 +00:00
|
|
|
import os
|
|
|
|
import json
|
2018-05-14 09:16:54 +00:00
|
|
|
import base64
|
2018-05-14 10:16:14 +00:00
|
|
|
import asyncio
|
2018-12-29 18:00:20 +00:00
|
|
|
from slixmpp.plugins.xep_0060.stanza import Items, EventItems
|
2019-02-17 17:39:00 +00:00
|
|
|
from slixmpp.plugins.base import BasePlugin, register_plugin
|
2018-12-29 17:57:50 +00:00
|
|
|
from slixmpp.exceptions import IqError, IqTimeout
|
2018-11-19 21:04:31 +00:00
|
|
|
from slixmpp.stanza import Message, Iq
|
2018-11-25 22:17:47 +00:00
|
|
|
from slixmpp.jid import JID
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2019-02-17 17:39:00 +00:00
|
|
|
from .version import __version__, __version_info__
|
|
|
|
from .stanza import OMEMO_BASE_NS
|
|
|
|
from .stanza import OMEMO_DEVICES_NS, OMEMO_BUNDLES_NS
|
|
|
|
from .stanza import Bundle, Devices, Device, Encrypted, Key, PreKeyPublic
|
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2018-05-13 11:12:05 +00:00
|
|
|
HAS_OMEMO = True
|
|
|
|
try:
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO1")
|
2018-12-01 18:36:17 +00:00
|
|
|
import omemo.exceptions
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO2")
|
2019-01-31 10:07:29 +00:00
|
|
|
from omemo import SessionManager, ExtendedPublicBundle, DefaultOTPKPolicy
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO3")
|
2018-11-18 11:00:25 +00:00
|
|
|
from omemo.util import generateDeviceID
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO4")
|
|
|
|
from omemo.implementation import JSONFileStorage
|
|
|
|
print("FOO5")
|
2018-11-25 22:20:05 +00:00
|
|
|
from omemo.backends import Backend
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO6")
|
2018-11-18 11:00:25 +00:00
|
|
|
from omemo_backend_signal import BACKEND as SignalBackend
|
2019-02-17 17:39:00 +00:00
|
|
|
print("FOO7")
|
2018-11-19 21:04:31 +00:00
|
|
|
except (ImportError,):
|
2019-02-17 17:39:00 +00:00
|
|
|
class Backend:
|
|
|
|
pass
|
|
|
|
|
|
|
|
class DefaultOTPKPolicy:
|
|
|
|
pass
|
|
|
|
|
|
|
|
class SignalBackend:
|
|
|
|
pass
|
|
|
|
|
2018-05-13 11:12:05 +00:00
|
|
|
HAS_OMEMO = False
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2018-05-23 20:13:06 +00:00
|
|
|
TRUE_VALUES = {True, 'true', '1'}
|
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
def b64enc(data: bytes) -> str:
|
2018-05-14 09:16:54 +00:00
|
|
|
return base64.b64encode(bytes(bytearray(data))).decode('ASCII')
|
|
|
|
|
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
def b64dec(data: str) -> bytes:
|
2018-11-18 23:22:50 +00:00
|
|
|
return base64.b64decode(data)
|
2018-05-14 09:16:54 +00:00
|
|
|
|
|
|
|
|
2018-12-01 18:59:49 +00:00
|
|
|
def _load_device_id(data_dir: str) -> int:
|
|
|
|
filepath = os.path.join(data_dir, 'device_id.json')
|
2018-11-19 21:04:31 +00:00
|
|
|
# Try reading file first, decoding, and if file was empty generate
|
|
|
|
# new DeviceID
|
|
|
|
try:
|
|
|
|
with open(filepath, 'r') as f:
|
|
|
|
did = json.load(f)
|
|
|
|
except (FileNotFoundError, json.JSONDecodeError):
|
|
|
|
did = generateDeviceID()
|
|
|
|
with open(filepath, 'w') as f:
|
|
|
|
json.dump(did, f)
|
|
|
|
|
|
|
|
return did
|
|
|
|
|
|
|
|
|
2018-12-29 06:31:37 +00:00
|
|
|
def _parse_bundle(backend: Backend, bundle: Bundle) -> ExtendedPublicBundle:
|
|
|
|
identity_key = b64dec(bundle['identityKey']['value'].strip())
|
|
|
|
spk = {
|
|
|
|
'id': int(bundle['signedPreKeyPublic']['signedPreKeyId']),
|
|
|
|
'key': b64dec(bundle['signedPreKeyPublic']['value'].strip()),
|
|
|
|
}
|
|
|
|
spk_signature = b64dec(bundle['signedPreKeySignature']['value'].strip())
|
|
|
|
|
|
|
|
otpks = []
|
|
|
|
for prekey in bundle['prekeys']:
|
|
|
|
otpks.append({
|
|
|
|
'id': int(prekey['preKeyId']),
|
|
|
|
'key': b64dec(prekey['value'].strip()),
|
|
|
|
})
|
|
|
|
|
|
|
|
return ExtendedPublicBundle.parse(backend, identity_key, spk, spk_signature, otpks)
|
|
|
|
|
|
|
|
|
2018-12-29 06:34:52 +00:00
|
|
|
def _generate_encrypted_payload(encrypted) -> Encrypted:
|
|
|
|
tag = Encrypted()
|
|
|
|
|
|
|
|
tag['header']['sid'] = str(encrypted['sid'])
|
|
|
|
tag['header']['iv']['value'] = b64enc(encrypted['iv'])
|
|
|
|
tag['payload']['value'] = b64enc(encrypted['payload'])
|
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
for bare_jid, devices in encrypted['keys'].items():
|
|
|
|
for rid, device in devices.items():
|
|
|
|
key = Key()
|
|
|
|
key['value'] = b64enc(device['data'])
|
|
|
|
key['rid'] = str(rid)
|
|
|
|
if device['pre_key']:
|
|
|
|
key['prekey'] = '1'
|
|
|
|
tag['header'].append(key)
|
2018-12-29 06:34:52 +00:00
|
|
|
|
|
|
|
return tag
|
|
|
|
|
|
|
|
|
2018-11-18 11:00:25 +00:00
|
|
|
# XXX: This should probably be moved in plugins/base.py?
|
|
|
|
class PluginCouldNotLoad(Exception): pass
|
|
|
|
|
|
|
|
|
2018-11-19 21:10:41 +00:00
|
|
|
# Generic exception
|
|
|
|
class XEP0384(Exception): pass
|
|
|
|
|
|
|
|
|
|
|
|
class MissingOwnKey(XEP0384): pass
|
|
|
|
|
|
|
|
|
2018-12-01 18:38:02 +00:00
|
|
|
class NoAvailableSession(XEP0384): pass
|
|
|
|
|
|
|
|
|
2018-11-30 18:06:13 +00:00
|
|
|
class EncryptionPrepareException(XEP0384): pass
|
|
|
|
|
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
class UntrustedException(XEP0384): pass
|
|
|
|
|
|
|
|
|
2019-01-31 14:47:12 +00:00
|
|
|
class UndecidedException(XEP0384): pass
|
|
|
|
|
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
class XEP_0384(BasePlugin):
|
|
|
|
|
|
|
|
"""
|
|
|
|
XEP-0384: OMEMO
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = 'xep_0384'
|
|
|
|
description = 'XEP-0384 OMEMO'
|
|
|
|
dependencies = {'xep_0163'}
|
2018-05-14 10:07:32 +00:00
|
|
|
default_config = {
|
2018-12-01 18:59:49 +00:00
|
|
|
'data_dir': None,
|
2019-01-31 10:21:54 +00:00
|
|
|
'storage_backend': None,
|
2019-01-31 10:07:29 +00:00
|
|
|
'otpk_policy': DefaultOTPKPolicy,
|
2019-01-12 18:45:47 +00:00
|
|
|
'omemo_backend': SignalBackend,
|
2018-05-14 10:07:32 +00:00
|
|
|
}
|
|
|
|
|
2018-05-13 11:12:05 +00:00
|
|
|
backend_loaded = HAS_OMEMO
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2019-01-12 18:45:47 +00:00
|
|
|
def plugin_init(self) -> None:
|
2018-05-13 11:12:05 +00:00
|
|
|
if not self.backend_loaded:
|
2018-11-18 11:00:25 +00:00
|
|
|
log.info("xep_0384 cannot be loaded as the backend omemo library "
|
2018-11-19 21:04:31 +00:00
|
|
|
"is not available")
|
2019-01-31 15:28:12 +00:00
|
|
|
raise PluginCouldNotLoad
|
2018-05-13 11:12:05 +00:00
|
|
|
|
2019-01-12 18:36:32 +00:00
|
|
|
if not self.data_dir:
|
|
|
|
log.info("xep_0384 canoot be loaded as there is not data directory "
|
|
|
|
"specified")
|
|
|
|
return None
|
|
|
|
|
2019-01-31 10:21:54 +00:00
|
|
|
storage = self.storage_backend
|
|
|
|
if self.storage_backend is None:
|
|
|
|
storage = JSONFileStorage(self.data_dir)
|
|
|
|
|
2019-01-31 10:27:10 +00:00
|
|
|
otpkpolicy = self.otpk_policy
|
2018-11-18 11:00:25 +00:00
|
|
|
bare_jid = self.xmpp.boundjid.bare
|
2018-12-01 18:59:49 +00:00
|
|
|
self._device_id = _load_device_id(self.data_dir)
|
2018-11-18 11:00:25 +00:00
|
|
|
|
|
|
|
try:
|
2018-11-19 00:37:07 +00:00
|
|
|
self._omemo = SessionManager.create(
|
|
|
|
storage,
|
|
|
|
otpkpolicy,
|
2019-01-12 18:45:47 +00:00
|
|
|
self.omemo_backend,
|
2018-11-19 00:37:07 +00:00
|
|
|
bare_jid,
|
|
|
|
self._device_id,
|
|
|
|
)
|
2018-11-18 11:00:25 +00:00
|
|
|
except:
|
2018-11-18 17:04:58 +00:00
|
|
|
log.error("Couldn't load the OMEMO object; ¯\\_(ツ)_/¯")
|
2018-11-18 11:00:25 +00:00
|
|
|
raise PluginCouldNotLoad
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2018-12-29 06:40:01 +00:00
|
|
|
self.xmpp['xep_0060'].map_node_event(OMEMO_DEVICES_NS, 'omemo_device_list')
|
|
|
|
self.xmpp.add_event_handler('omemo_device_list_publish', self._receive_device_list)
|
2019-01-12 18:45:47 +00:00
|
|
|
return None
|
2018-11-18 16:48:16 +00:00
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
def plugin_end(self):
|
2018-05-13 11:12:05 +00:00
|
|
|
if not self.backend_loaded:
|
|
|
|
return
|
|
|
|
|
2018-12-29 06:40:01 +00:00
|
|
|
self.xmpp.remove_event_handler('omemo_device_list_publish', self._receive_device_list)
|
2018-05-11 01:51:37 +00:00
|
|
|
self.xmpp['xep_0163'].remove_interest(OMEMO_DEVICES_NS)
|
|
|
|
|
|
|
|
def session_bind(self, _jid):
|
2019-01-31 15:28:12 +00:00
|
|
|
if self.backend_loaded:
|
|
|
|
self.xmpp['xep_0163'].add_interest(OMEMO_DEVICES_NS)
|
|
|
|
asyncio.ensure_future(self._set_device_list())
|
|
|
|
asyncio.ensure_future(self._publish_bundle())
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
def my_device_id(self) -> int:
|
2018-05-23 21:19:38 +00:00
|
|
|
return self._device_id
|
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
def _generate_bundle_iq(self) -> Iq:
|
2019-01-12 18:45:47 +00:00
|
|
|
bundle = self._omemo.public_bundle.serialize(self._omemo)
|
2018-05-14 10:21:27 +00:00
|
|
|
|
|
|
|
iq = self.xmpp.Iq(stype='set')
|
|
|
|
publish = iq['pubsub']['publish']
|
|
|
|
publish['node'] = '%s:%d' % (OMEMO_BUNDLES_NS, self._device_id)
|
|
|
|
payload = publish['item']['bundle']
|
2018-11-22 19:53:56 +00:00
|
|
|
signedPreKeyPublic = b64enc(bundle['spk']['key'])
|
2018-05-14 10:21:27 +00:00
|
|
|
payload['signedPreKeyPublic']['value'] = signedPreKeyPublic
|
2018-11-22 19:53:56 +00:00
|
|
|
payload['signedPreKeyPublic']['signedPreKeyId'] = str(bundle['spk']['id'])
|
2018-05-14 10:21:27 +00:00
|
|
|
payload['signedPreKeySignature']['value'] = b64enc(
|
2018-11-22 19:53:56 +00:00
|
|
|
bundle['spk_signature']
|
2018-05-14 10:21:27 +00:00
|
|
|
)
|
2018-11-22 19:53:56 +00:00
|
|
|
identityKey = b64enc(bundle['ik'])
|
2018-05-14 10:21:27 +00:00
|
|
|
payload['identityKey']['value'] = identityKey
|
|
|
|
|
|
|
|
prekeys = []
|
2018-11-22 19:53:56 +00:00
|
|
|
for otpk in bundle['otpks']:
|
2018-05-14 10:21:27 +00:00
|
|
|
prekey = PreKeyPublic()
|
|
|
|
prekey['preKeyId'] = str(otpk['id'])
|
2018-11-22 19:53:56 +00:00
|
|
|
prekey['value'] = b64enc(otpk['key'])
|
2018-05-14 10:21:27 +00:00
|
|
|
prekeys.append(prekey)
|
|
|
|
payload['prekeys'] = prekeys
|
|
|
|
|
|
|
|
return iq
|
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
async def _publish_bundle(self) -> None:
|
2018-11-18 22:45:31 +00:00
|
|
|
if self._omemo.republish_bundle:
|
|
|
|
iq = self._generate_bundle_iq()
|
|
|
|
await iq.send()
|
2018-05-14 10:21:27 +00:00
|
|
|
|
2018-12-30 22:37:28 +00:00
|
|
|
async def _fetch_bundle(self, jid: str, device_id: int) -> Optional[ExtendedPublicBundle]:
|
2018-11-25 22:20:05 +00:00
|
|
|
node = '%s:%d' % (OMEMO_BUNDLES_NS, device_id)
|
2018-12-29 17:57:50 +00:00
|
|
|
try:
|
|
|
|
iq = await self.xmpp['xep_0060'].get_items(jid, node)
|
|
|
|
except (IqError, IqTimeout):
|
|
|
|
return None
|
2018-11-25 22:20:05 +00:00
|
|
|
bundle = iq['pubsub']['items']['item']['bundle']
|
|
|
|
|
2019-01-12 18:45:47 +00:00
|
|
|
return _parse_bundle(self._omemo, bundle)
|
2018-11-25 22:20:05 +00:00
|
|
|
|
2018-12-29 18:00:20 +00:00
|
|
|
async def _fetch_device_list(self, jid: JID) -> None:
|
2019-01-29 17:03:01 +00:00
|
|
|
"""Manually query PEP OMEMO_DEVICES_NS nodes"""
|
2018-12-29 18:00:20 +00:00
|
|
|
jid = JID(jid)
|
|
|
|
iq = await self.xmpp['xep_0060'].get_items(jid, OMEMO_DEVICES_NS)
|
|
|
|
return await self._read_device_list(jid, iq['pubsub']['items'])
|
|
|
|
|
2019-01-29 17:03:01 +00:00
|
|
|
def _store_device_ids(self, jid: str, items: Union[Items, EventItems]) -> None:
|
|
|
|
"""Store Device list"""
|
2018-11-19 21:04:31 +00:00
|
|
|
device_ids = [] # type: List[int]
|
2018-12-29 11:44:37 +00:00
|
|
|
items = list(items)
|
|
|
|
device_ids = [int(d['id']) for d in items[0]['devices']]
|
|
|
|
return self._omemo.newDeviceList(str(jid), device_ids)
|
2018-05-14 10:16:14 +00:00
|
|
|
|
2019-01-29 17:10:10 +00:00
|
|
|
def _receive_device_list(self, msg: Message) -> None:
|
2019-01-29 17:03:01 +00:00
|
|
|
"""Handler for received PEP OMEMO_DEVICES_NS payloads"""
|
2019-01-29 17:10:10 +00:00
|
|
|
asyncio.ensure_future(
|
|
|
|
self._read_device_list(msg['from'],
|
|
|
|
msg['pubsub_event']['items']),
|
|
|
|
)
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2018-12-29 18:00:20 +00:00
|
|
|
async def _read_device_list(self, jid: JID, items: Union[Items, EventItems]) -> None:
|
2019-01-29 17:03:01 +00:00
|
|
|
"""Read items and devices if we need to set the device list again or not"""
|
2018-12-29 18:00:20 +00:00
|
|
|
bare_jid = jid.bare
|
|
|
|
self._store_device_ids(bare_jid, items)
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2019-01-29 17:03:01 +00:00
|
|
|
items = list(items)
|
|
|
|
device_ids = [int(d['id']) for d in items[0]['devices']]
|
2018-11-18 16:48:16 +00:00
|
|
|
|
2018-12-29 18:00:20 +00:00
|
|
|
if bare_jid == self.xmpp.boundjid.bare and \
|
2018-12-30 20:44:11 +00:00
|
|
|
self._device_id not in device_ids:
|
2018-12-29 18:00:20 +00:00
|
|
|
await self._set_device_list()
|
|
|
|
|
|
|
|
return None
|
2018-05-14 10:16:14 +00:00
|
|
|
|
2019-01-29 17:03:01 +00:00
|
|
|
async def _set_device_list(self, device_ids: Optional[Set[int]] = None) -> None:
|
|
|
|
own_jid = self.xmpp.boundjid
|
2018-05-23 21:17:42 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
iq = await self.xmpp['xep_0060'].get_items(
|
2019-01-29 17:03:01 +00:00
|
|
|
own_jid.bare, OMEMO_DEVICES_NS,
|
2018-05-23 21:17:42 +00:00
|
|
|
)
|
|
|
|
items = iq['pubsub']['items']
|
2019-01-29 17:03:01 +00:00
|
|
|
self._store_device_ids(own_jid.bare, items)
|
2018-05-23 21:17:42 +00:00
|
|
|
except IqError as iq_err:
|
|
|
|
if iq_err.condition == "item-not-found":
|
2019-01-29 17:03:01 +00:00
|
|
|
self._store_device_ids(own_jid.bare, [])
|
2018-05-23 21:17:42 +00:00
|
|
|
else:
|
|
|
|
return # XXX: Handle this!
|
2018-05-14 10:16:14 +00:00
|
|
|
|
2019-01-29 17:03:01 +00:00
|
|
|
if device_ids is None:
|
|
|
|
device_ids = self.get_device_list(own_jid)
|
2018-05-14 10:16:14 +00:00
|
|
|
|
|
|
|
devices = []
|
2018-12-30 20:44:11 +00:00
|
|
|
for i in device_ids:
|
2018-05-14 10:16:14 +00:00
|
|
|
d = Device()
|
|
|
|
d['id'] = str(i)
|
|
|
|
devices.append(d)
|
|
|
|
payload = Devices()
|
|
|
|
payload['devices'] = devices
|
|
|
|
|
|
|
|
await self.xmpp['xep_0060'].publish(
|
2019-01-29 17:03:01 +00:00
|
|
|
own_jid.bare, OMEMO_DEVICES_NS, payload=payload,
|
2018-05-14 10:16:14 +00:00
|
|
|
)
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2019-01-29 17:03:01 +00:00
|
|
|
def get_device_list(self, jid: JID) -> List[str]:
|
|
|
|
"""Return active device ids. Always contains our own device id."""
|
|
|
|
return self._omemo.getDevices(jid.bare).get('active', [])
|
2018-11-18 16:48:16 +00:00
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
def trust(self, jid: JID, device_id: int, ik: bytes) -> None:
|
|
|
|
self._omemo.trust(jid.bare, device_id, ik)
|
|
|
|
|
|
|
|
def distrust(self, jid: JID, device_id: int, ik: bytes) -> None:
|
|
|
|
self._omemo.distrust(jid.bare, device_id, ik)
|
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
def is_encrypted(self, msg: Message) -> bool:
|
2018-05-14 10:24:13 +00:00
|
|
|
return msg.xml.find('{%s}encrypted' % OMEMO_BASE_NS) is not None
|
|
|
|
|
2019-01-30 22:11:09 +00:00
|
|
|
def decrypt_message(self, msg: Message, allow_untrusted: bool = False) -> Optional[str]:
|
2018-05-23 20:13:06 +00:00
|
|
|
header = msg['omemo_encrypted']['header']
|
2018-11-18 23:22:50 +00:00
|
|
|
payload = b64dec(msg['omemo_encrypted']['payload']['value'])
|
2018-05-23 20:13:06 +00:00
|
|
|
|
2018-05-23 20:32:29 +00:00
|
|
|
jid = msg['from'].bare
|
2018-12-01 18:13:07 +00:00
|
|
|
sid = int(header['sid'])
|
2018-05-23 20:13:06 +00:00
|
|
|
|
|
|
|
key = header.xml.find("{%s}key[@rid='%s']" % (
|
|
|
|
OMEMO_BASE_NS, self._device_id))
|
|
|
|
if key is None:
|
2018-11-19 21:10:41 +00:00
|
|
|
raise MissingOwnKey("Encrypted message is not for us")
|
2018-05-23 20:13:06 +00:00
|
|
|
|
|
|
|
key = Key(key)
|
2018-11-18 22:54:30 +00:00
|
|
|
isPrekeyMessage = key['prekey'] in TRUE_VALUES
|
2018-11-18 23:22:50 +00:00
|
|
|
message = b64dec(key['value'])
|
|
|
|
iv = b64dec(header['iv']['value'])
|
2018-05-23 20:13:06 +00:00
|
|
|
|
2018-11-19 00:39:56 +00:00
|
|
|
# XXX: 'cipher' is part of KeyTransportMessages and is used when no payload
|
|
|
|
# is passed. We do not implement this yet.
|
2018-12-01 18:38:02 +00:00
|
|
|
try:
|
2018-12-30 21:22:58 +00:00
|
|
|
body = self._omemo.decryptMessage(
|
2018-12-01 18:38:02 +00:00
|
|
|
jid,
|
|
|
|
sid,
|
|
|
|
iv,
|
|
|
|
message,
|
|
|
|
isPrekeyMessage,
|
|
|
|
payload,
|
2019-01-30 22:11:09 +00:00
|
|
|
allow_untrusted=allow_untrusted,
|
2018-12-01 18:38:02 +00:00
|
|
|
)
|
|
|
|
return body
|
2018-12-01 18:57:25 +00:00
|
|
|
except (omemo.exceptions.NoSessionException,):
|
2018-12-01 18:38:02 +00:00
|
|
|
# This might happen when the sender is sending using a session
|
|
|
|
# that we don't know about (deleted session storage, etc.). In
|
|
|
|
# this case we can't decrypt the message and it's going to be lost
|
|
|
|
# in any case, but we want to tell the user, always.
|
2018-12-01 18:57:25 +00:00
|
|
|
raise NoAvailableSession(jid, sid)
|
2018-12-30 21:22:58 +00:00
|
|
|
except (omemo.exceptions.UntrustedException,) as e:
|
2019-01-30 22:17:48 +00:00
|
|
|
raise UntrustedException(e)
|
2018-12-01 18:39:00 +00:00
|
|
|
finally:
|
|
|
|
asyncio.ensure_future(self._publish_bundle())
|
2018-05-23 20:13:06 +00:00
|
|
|
|
2019-01-31 14:47:12 +00:00
|
|
|
async def encrypt_message(
|
|
|
|
self,
|
|
|
|
plaintext: str,
|
|
|
|
recipients: List[JID],
|
|
|
|
expect_problems: Optional[Dict[JID, List[int]]] = None,
|
|
|
|
) -> Encrypted:
|
2018-11-25 22:17:47 +00:00
|
|
|
"""
|
|
|
|
Returns an encrypted payload to be placed into a message.
|
|
|
|
|
|
|
|
The API for getting an encrypted payload consists of trying first
|
|
|
|
and fixing errors progressively. The actual sending happens once the
|
|
|
|
application (us) thinks we're good to go.
|
|
|
|
"""
|
|
|
|
|
|
|
|
recipients = [jid.bare for jid in recipients]
|
2018-11-30 15:42:45 +00:00
|
|
|
bundles = {} # type: Dict[str, Dict[int, ExtendedPublicBundle]]
|
2018-11-25 22:17:47 +00:00
|
|
|
|
2018-12-30 22:37:28 +00:00
|
|
|
old_errors = None # type: Optional[List[Tuple[Exception, Any, Any]]]
|
2018-11-25 22:17:47 +00:00
|
|
|
while True:
|
2018-11-30 18:06:13 +00:00
|
|
|
# Try to encrypt and resolve errors until there is no error at all
|
|
|
|
# or if we hit the same set of errors.
|
2018-12-30 21:22:58 +00:00
|
|
|
errors = [] # type: List[omemo.exceptions.OMEMOException]
|
|
|
|
|
2019-01-31 14:47:12 +00:00
|
|
|
if expect_problems is not None:
|
|
|
|
expect_problems = {jid.bare: did for (jid, did) in expect_problems.items()}
|
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
try:
|
|
|
|
encrypted = self._omemo.encryptMessage(
|
|
|
|
recipients,
|
|
|
|
plaintext.encode('utf-8'),
|
|
|
|
bundles,
|
2019-01-31 14:47:12 +00:00
|
|
|
expect_problems=expect_problems,
|
2018-12-30 21:22:58 +00:00
|
|
|
)
|
|
|
|
return _generate_encrypted_payload(encrypted)
|
|
|
|
except omemo.exceptions.EncryptionProblemsException as e:
|
|
|
|
errors = e.problems
|
2018-11-25 22:17:47 +00:00
|
|
|
|
2018-11-30 18:06:13 +00:00
|
|
|
if errors == old_errors:
|
2018-12-30 21:22:58 +00:00
|
|
|
raise EncryptionPrepareException(errors)
|
2018-11-30 18:06:13 +00:00
|
|
|
|
|
|
|
old_errors = errors
|
|
|
|
|
2018-11-30 17:30:17 +00:00
|
|
|
no_eligible_devices = set() # type: Set[str]
|
2018-12-30 21:22:58 +00:00
|
|
|
for exn in errors:
|
|
|
|
if isinstance(exn, omemo.exceptions.NoDevicesException):
|
|
|
|
await self._fetch_device_list(exn.bare_jid)
|
|
|
|
elif isinstance(exn, omemo.exceptions.MissingBundleException):
|
|
|
|
bundle = await self._fetch_bundle(exn.bare_jid, exn.device)
|
2018-11-25 22:20:05 +00:00
|
|
|
if bundle is not None:
|
2018-12-30 21:22:58 +00:00
|
|
|
devices = bundles.setdefault(exn.bare_jid, {})
|
|
|
|
devices[exn.device] = bundle
|
|
|
|
elif isinstance(exn, omemo.exceptions.UntrustedException):
|
2019-01-31 14:47:12 +00:00
|
|
|
# On UntrustedException, there are two possibilities.
|
|
|
|
# Either trust has not been explicitely set yet, and is
|
|
|
|
# 'undecided', or the device is explicitely not
|
|
|
|
# trusted. When undecided, we need to ask our user to make
|
|
|
|
# a choice. If untrusted, then we can safely tell the
|
|
|
|
# OMEMO lib to not encrypt to this device
|
|
|
|
if self._omemo.getTrustForDevice(exn.bare_jid, exn.device) is None:
|
|
|
|
raise UndecidedException(exn.bare_jid, exn.device, exn.ik)
|
|
|
|
expect_problems.setdefault(exn.bare_jid, []).append(exn.device)
|
2018-12-31 20:51:56 +00:00
|
|
|
elif isinstance(exn, omemo.exceptions.NoEligibleDevicesException):
|
|
|
|
# This error is returned by the library to specify that
|
|
|
|
# encryption is not possible to any device of a user.
|
|
|
|
# This always comes with a more specific exception, (empty
|
|
|
|
# device list, missing bundles, trust issues, etc.).
|
|
|
|
# This does the heavy lifting of state management, and
|
|
|
|
# seeing if it's possible to encrypt at all, or not.
|
|
|
|
# This exception is only passed to the user, that should
|
|
|
|
# decide what to do with it, as there isn't much we can if
|
|
|
|
# other issues can't be resolved.
|
|
|
|
continue
|
2019-02-17 17:39:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
register_plugin(XEP_0384)
|