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
|
|
|
|
2021-07-13 18:29:14 +00:00
|
|
|
# Not available in Python 3.7, and slixmpp already imports the right things
|
|
|
|
# for me
|
|
|
|
from slixmpp.types import TypedDict
|
2021-07-17 00:54:57 +00:00
|
|
|
from functools import reduce
|
2021-07-13 18:29:14 +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-24 12:23:39 +00:00
|
|
|
from slixmpp.plugins.xep_0004 import Form
|
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__)
|
|
|
|
|
2019-12-29 14:38:51 +00:00
|
|
|
HAS_OMEMO = False
|
|
|
|
HAS_OMEMO_BACKEND = False
|
2018-05-13 11:12:05 +00:00
|
|
|
try:
|
2018-12-01 18:36:17 +00:00
|
|
|
import omemo.exceptions
|
2019-01-31 10:07:29 +00:00
|
|
|
from omemo import SessionManager, ExtendedPublicBundle, DefaultOTPKPolicy
|
2018-11-18 11:00:25 +00:00
|
|
|
from omemo.util import generateDeviceID
|
2019-02-17 18:30:31 +00:00
|
|
|
from omemo.implementations import JSONFileStorage
|
2018-11-25 22:20:05 +00:00
|
|
|
from omemo.backends import Backend
|
2019-12-29 14:38:51 +00:00
|
|
|
HAS_OMEMO = True
|
2018-11-18 11:00:25 +00:00
|
|
|
from omemo_backend_signal import BACKEND as SignalBackend
|
2019-12-29 14:38:51 +00:00
|
|
|
HAS_OMEMO_BACKEND = True
|
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-23 20:13:06 +00:00
|
|
|
TRUE_VALUES = {True, 'true', '1'}
|
2019-08-22 17:43:49 +00:00
|
|
|
PUBLISH_OPTIONS_NODE = 'http://jabber.org/protocol/pubsub#publish-options'
|
2019-10-25 01:06:52 +00:00
|
|
|
PUBSUB_ERRORS = 'http://jabber.org/protocol/pubsub#errors'
|
2018-05-23 20:13:06 +00:00
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2021-07-13 18:29:14 +00:00
|
|
|
class ChainLengths(TypedDict):
|
|
|
|
receiving: List[Tuple[int, int]]
|
|
|
|
sending: List[Tuple[int, int]]
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
2019-08-25 21:19:40 +00:00
|
|
|
|
|
|
|
def fp_from_ik(identity_key: bytes) -> str:
|
2019-08-24 23:56:28 +00:00
|
|
|
"""Convert identityKey to a string representation (fingerprint)"""
|
2021-06-29 00:01:15 +00:00
|
|
|
return "".join("{:02x}".format(octet) for octet in identity_key)
|
2019-08-24 23:56:28 +00:00
|
|
|
|
2018-11-19 21:04:31 +00:00
|
|
|
|
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'])
|
2021-07-13 20:43:40 +00:00
|
|
|
if 'payload' in encrypted:
|
|
|
|
tag['payload']['value'] = b64enc(encrypted['payload'])
|
2018-12-29 06:34:52 +00:00
|
|
|
|
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
|
|
|
|
|
|
|
|
|
2019-02-24 12:23:39 +00:00
|
|
|
def _make_publish_options_form(fields: Dict[str, Any]) -> Form:
|
|
|
|
options = Form()
|
|
|
|
options['type'] = 'submit'
|
|
|
|
options.add_field(
|
|
|
|
var='FORM_TYPE',
|
|
|
|
ftype='hidden',
|
|
|
|
value='http://jabber.org/protocol/pubsub#publish-options',
|
|
|
|
)
|
|
|
|
|
|
|
|
for var, value in fields.items():
|
|
|
|
options.add_field(var=var, value=value)
|
|
|
|
|
|
|
|
return options
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
2019-08-24 22:35:30 +00:00
|
|
|
class EncryptionPrepareException(XEP0384):
|
|
|
|
def __init__(self, errors):
|
|
|
|
self.errors = errors
|
2018-11-30 18:06:13 +00:00
|
|
|
|
|
|
|
|
2019-02-19 00:09:16 +00:00
|
|
|
class UntrustedException(XEP0384):
|
|
|
|
def __init__(self, bare_jid, device, ik):
|
|
|
|
self.bare_jid = JID(bare_jid)
|
|
|
|
self.device = device
|
|
|
|
self.ik = ik
|
2018-12-30 21:22:58 +00:00
|
|
|
|
|
|
|
|
2019-02-19 00:09:16 +00:00
|
|
|
class UndecidedException(XEP0384):
|
|
|
|
def __init__(self, bare_jid, device, ik):
|
|
|
|
self.bare_jid = JID(bare_jid)
|
|
|
|
self.device = device
|
|
|
|
self.ik = ik
|
2019-01-31 14:47:12 +00:00
|
|
|
|
|
|
|
|
2020-03-28 11:28:52 +00:00
|
|
|
class ErroneousPayload(XEP0384):
|
|
|
|
"""To be raised when the payload is not of the form we expect"""
|
|
|
|
|
|
|
|
|
2018-05-11 01:51:37 +00:00
|
|
|
class XEP_0384(BasePlugin):
|
|
|
|
|
|
|
|
"""
|
|
|
|
XEP-0384: OMEMO
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = 'xep_0384'
|
|
|
|
description = 'XEP-0384 OMEMO'
|
2019-02-24 12:23:39 +00:00
|
|
|
dependencies = {'xep_0004', 'xep_0060', '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,
|
2021-07-13 20:43:40 +00:00
|
|
|
'auto_heartbeat': True,
|
2021-07-13 18:29:14 +00:00
|
|
|
'heartbeat_after': 53,
|
|
|
|
# TODO: 'drop_inactive_after': 300,
|
2018-05-14 10:07:32 +00:00
|
|
|
}
|
|
|
|
|
2019-12-29 14:38:51 +00:00
|
|
|
backend_loaded = HAS_OMEMO and HAS_OMEMO_BACKEND
|
2018-05-11 01:51:37 +00:00
|
|
|
|
2019-08-23 22:44:46 +00:00
|
|
|
# OMEMO Bundles used for encryption
|
|
|
|
bundles = {} # type: Dict[str, Dict[int, ExtendedPublicBundle]]
|
|
|
|
|
2021-07-14 08:43:59 +00:00
|
|
|
# Used at startup to prevent publishing device list and bundles multiple times
|
|
|
|
_initial_publish_done = False
|
|
|
|
|
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:
|
2019-12-29 14:38:51 +00:00
|
|
|
log_str = ("xep_0384 cannot be loaded as the backend omemo library "
|
|
|
|
"is not available. ")
|
|
|
|
if not HAS_OMEMO_BACKEND:
|
|
|
|
log_str += ("Make sure you have a python OMEMO backend "
|
|
|
|
"(python-omemo-backend-signal) installed")
|
|
|
|
else:
|
|
|
|
log_str += "Make sure you have the python OMEMO library installed."
|
|
|
|
log.error(log_str)
|
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:
|
2020-03-12 00:30:30 +00:00
|
|
|
raise PluginCouldNotLoad("xep_0384 cannot be loaded as there is "
|
|
|
|
"no data directory specified.")
|
2019-01-12 18:36:32 +00:00
|
|
|
|
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
|
|
|
|
2019-08-22 17:44:21 +00:00
|
|
|
self.xmpp.add_event_handler('session_start', self.session_start)
|
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)
|
2021-07-14 08:43:59 +00:00
|
|
|
|
|
|
|
if self.xmpp.is_connected and not self._initial_publish_done:
|
|
|
|
asyncio.ensure_future(self._initial_publish())
|
|
|
|
|
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
|
|
|
|
|
2019-08-22 17:44:21 +00:00
|
|
|
self.xmpp.remove_event_handler('session_start', self.session_start)
|
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)
|
|
|
|
|
2019-08-23 22:14:41 +00:00
|
|
|
async def session_start(self, _jid):
|
2021-07-14 10:32:36 +00:00
|
|
|
await self._initial_publish()
|
2021-07-14 08:43:59 +00:00
|
|
|
|
|
|
|
async def _initial_publish(self):
|
2021-07-14 10:32:36 +00:00
|
|
|
if self.backend_loaded:
|
2019-01-31 15:28:12 +00:00
|
|
|
self.xmpp['xep_0163'].add_interest(OMEMO_DEVICES_NS)
|
2019-08-23 22:14:41 +00:00
|
|
|
await asyncio.wait([
|
|
|
|
self._set_device_list(),
|
|
|
|
self._publish_bundle(),
|
|
|
|
])
|
2021-07-14 08:43:59 +00:00
|
|
|
self._initial_publish_done = True
|
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
|
|
|
|
|
2021-06-28 23:44:02 +00:00
|
|
|
def my_fingerprint(self) -> str:
|
|
|
|
bundle = self._omemo.public_bundle.serialize(self.omemo_backend)
|
|
|
|
return fp_from_ik(bundle['ik'])
|
|
|
|
|
2019-10-25 01:06:52 +00:00
|
|
|
def _set_node_config(
|
|
|
|
self,
|
|
|
|
node: str,
|
|
|
|
persist_items: bool = True,
|
|
|
|
access_model: Optional[str] = None,
|
|
|
|
) -> asyncio.Future:
|
2019-10-25 01:27:00 +00:00
|
|
|
"""
|
|
|
|
Sets OMEMO devicelist or bundle node configuration.
|
|
|
|
|
|
|
|
This function is meant to be used once we've tried publish options
|
|
|
|
and they came back with precondition-not-met. This means an
|
|
|
|
existing node is not using our defaults.
|
|
|
|
|
2019-10-25 01:36:38 +00:00
|
|
|
By default this function will be overwriting pubsub#persist_items
|
|
|
|
only, leaving pubsub#access_model as it was.
|
2019-10-25 01:27:00 +00:00
|
|
|
|
|
|
|
To be complete, the code using this function should probably
|
|
|
|
set the bundle node to the same access_model as the devicelist
|
|
|
|
node.
|
|
|
|
"""
|
2019-10-25 01:06:52 +00:00
|
|
|
form = Form()
|
|
|
|
form['type'] = 'submit'
|
|
|
|
form.add_field(
|
|
|
|
var='FORM_TYPE',
|
|
|
|
ftype='hidden',
|
|
|
|
value='http://jabber.org/protocol/pubsub#node_config',
|
|
|
|
)
|
|
|
|
if persist_items:
|
|
|
|
form.add_field(
|
|
|
|
var='pubsub#persist_items',
|
|
|
|
ftype='boolean',
|
|
|
|
value=True,
|
|
|
|
)
|
|
|
|
if access_model is not None:
|
|
|
|
form.add_field(
|
|
|
|
var='FORM_TYPE',
|
|
|
|
ftype='text-single',
|
|
|
|
value=access_model,
|
|
|
|
)
|
|
|
|
|
|
|
|
return self.xmpp['xep_0060'].set_node_config(
|
|
|
|
self.xmpp.boundjid.bare,
|
|
|
|
node,
|
|
|
|
form,
|
|
|
|
)
|
|
|
|
|
2020-02-10 23:29:31 +00:00
|
|
|
async def _generate_bundle_iq(self, publish_options: bool = True) -> Iq:
|
2019-02-17 19:15:18 +00:00
|
|
|
bundle = self._omemo.public_bundle.serialize(self.omemo_backend)
|
2018-05-14 10:21:27 +00:00
|
|
|
|
2019-08-22 17:43:49 +00:00
|
|
|
jid = self.xmpp.boundjid
|
2019-08-23 20:36:43 +00:00
|
|
|
disco = await self.xmpp['xep_0030'].get_info(jid.bare)
|
|
|
|
publish_options = PUBLISH_OPTIONS_NODE in disco['disco_info'].get_features()
|
2019-02-24 12:23:39 +00:00
|
|
|
|
2018-05-14 10:21:27 +00:00
|
|
|
iq = self.xmpp.Iq(stype='set')
|
2019-08-22 17:43:49 +00:00
|
|
|
|
2018-05-14 10:21:27 +00:00
|
|
|
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
|
|
|
|
|
2020-02-10 23:29:31 +00:00
|
|
|
if publish_options and publish_options:
|
2019-08-23 22:13:41 +00:00
|
|
|
options = _make_publish_options_form({
|
|
|
|
'pubsub#persist_items': True,
|
|
|
|
'pubsub#access_model': 'open',
|
|
|
|
})
|
|
|
|
iq['pubsub']['publish_options'] = options
|
|
|
|
|
2018-05-14 10:21:27 +00:00
|
|
|
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:
|
2019-08-22 17:43:49 +00:00
|
|
|
iq = await self._generate_bundle_iq()
|
2019-10-25 01:06:52 +00:00
|
|
|
try:
|
|
|
|
await iq.send()
|
|
|
|
except IqError as e:
|
|
|
|
# TODO: Slixmpp should handle pubsub#errors so we don't have to
|
|
|
|
# fish the element ourselves
|
|
|
|
precondition = e.iq['error'].xml.find(
|
|
|
|
'{%s}%s' % (PUBSUB_ERRORS, 'precondition-not-met'),
|
|
|
|
)
|
|
|
|
if precondition is not None:
|
|
|
|
log.debug('The node we tried to publish was already '
|
|
|
|
'existing with a different configuration. '
|
|
|
|
'Trying to configure manually..')
|
2019-10-25 01:27:00 +00:00
|
|
|
# TODO: We should attempt setting this node to the same
|
|
|
|
# access_model as the devicelist node for completness.
|
2020-02-10 23:29:31 +00:00
|
|
|
try:
|
|
|
|
await self._set_node_config(OMEMO_BUNDLES_NS)
|
|
|
|
except IqError:
|
|
|
|
log.debug('Failed to set node to persistent after precondition-not-met')
|
|
|
|
raise
|
|
|
|
iq = await self._generate_bundle_iq(publish_options=False)
|
|
|
|
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-02-23 13:41:56 +00:00
|
|
|
return _parse_bundle(self.omemo_backend, 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"""
|
2019-12-10 16:04:11 +00:00
|
|
|
iq = await self.xmpp['xep_0060'].get_items(jid.full, OMEMO_DEVICES_NS)
|
2018-12-29 18:00:20 +00:00
|
|
|
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)
|
2019-02-27 23:26:52 +00:00
|
|
|
if items:
|
|
|
|
device_ids = [int(d['id']) for d in items[0]['devices']]
|
2018-12-29 11:44:37 +00:00
|
|
|
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(
|
2019-08-24 22:39:03 +00:00
|
|
|
self._read_device_list(msg['from'], msg['pubsub_event']['items']),
|
2019-01-29 17:10:10 +00:00
|
|
|
)
|
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)
|
2019-02-27 09:24:23 +00:00
|
|
|
device_ids = []
|
|
|
|
if 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
|
|
|
|
|
2019-08-23 22:13:41 +00:00
|
|
|
jid = self.xmpp.boundjid
|
|
|
|
disco = await self.xmpp['xep_0030'].get_info(jid.bare)
|
|
|
|
publish_options = PUBLISH_OPTIONS_NODE in disco['disco_info'].get_features()
|
|
|
|
|
2020-01-27 20:32:08 +00:00
|
|
|
options = None
|
2019-08-23 22:13:41 +00:00
|
|
|
if publish_options:
|
|
|
|
options = _make_publish_options_form({
|
|
|
|
'pubsub#persist_items': True,
|
|
|
|
# Everybody will be able to encrypt for us, without having to add
|
|
|
|
# us into their roster. This obviously leaks the number of devices
|
|
|
|
# and the associated metadata of us pushing new device lists every
|
|
|
|
# so often.
|
|
|
|
'pubsub#access_model': 'open',
|
|
|
|
})
|
2019-02-24 12:23:39 +00:00
|
|
|
|
2019-10-25 01:06:52 +00:00
|
|
|
try:
|
|
|
|
await self.xmpp['xep_0060'].publish(
|
|
|
|
own_jid.bare, OMEMO_DEVICES_NS, payload=payload, options=options,
|
|
|
|
)
|
|
|
|
except IqError as e:
|
|
|
|
# TODO: Slixmpp should handle pubsub#errors so we don't have to
|
|
|
|
# fish the element ourselves
|
|
|
|
precondition = e.iq['error'].xml.find(
|
|
|
|
'{%s}%s' % (PUBSUB_ERRORS, 'precondition-not-met'),
|
|
|
|
)
|
|
|
|
if precondition is not None:
|
|
|
|
log.debug('The node we tried to publish was already '
|
|
|
|
'existing with a different configuration. '
|
|
|
|
'Trying to configure manually..')
|
2020-02-10 23:29:31 +00:00
|
|
|
try:
|
|
|
|
await self._set_node_config(OMEMO_DEVICES_NS)
|
|
|
|
except IqError:
|
|
|
|
log.debug('Failed to set node to persistent after precondition-not-met')
|
|
|
|
raise
|
|
|
|
await self.xmpp['xep_0060'].publish(
|
|
|
|
own_jid.bare, OMEMO_DEVICES_NS, payload=payload,
|
|
|
|
)
|
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
|
|
|
|
2021-07-13 18:29:14 +00:00
|
|
|
def _chain_lengths(self, jid: JID) -> ChainLengths:
|
|
|
|
"""
|
|
|
|
Gather receiving and sending chain lengths for all devices (active
|
|
|
|
/ inactive) of a JID.
|
|
|
|
|
|
|
|
Receiving chain length is used to know when to send a heartbeat to
|
|
|
|
signal recipients our device is still active and listening. See:
|
|
|
|
https://xmpp.org/extensions/xep-0384.html#rules
|
|
|
|
|
|
|
|
Sending chain length is used on the other side when a device
|
|
|
|
hasn't been sending us messages and seems inactive.
|
|
|
|
|
|
|
|
# XXX: Only the receiving part is used in this library for the
|
|
|
|
# moment.
|
|
|
|
"""
|
|
|
|
# XXX: This method uses APIs that haven't been made public yet in the
|
|
|
|
# OMEMO library as of 0.12 (9fd7123).
|
|
|
|
|
|
|
|
bare = jid.bare
|
|
|
|
devices = self._omemo.getDevices(bare)
|
|
|
|
active = devices.get('active', set())
|
|
|
|
inactive = devices.get('inactive', set())
|
|
|
|
devices = active.union(inactive)
|
|
|
|
|
|
|
|
lengths: ChainLengths = {'sending': [], 'receiving': []}
|
|
|
|
for did in devices:
|
|
|
|
session = self._omemo._SessionManager__loadSession(bare, did)
|
2021-07-16 19:49:55 +00:00
|
|
|
if session is None:
|
2021-07-17 00:54:57 +00:00
|
|
|
continue
|
2021-07-13 18:29:14 +00:00
|
|
|
skr = session._DoubleRatchet__skr
|
2021-07-17 09:31:36 +00:00
|
|
|
sending = skr.sending_chain_length or 0
|
|
|
|
receiving = skr.receiving_chain_length or 0
|
2021-07-17 00:54:57 +00:00
|
|
|
lengths['sending'].append((did, sending))
|
|
|
|
lengths['receiving'].append((did, receiving))
|
2021-07-13 18:29:14 +00:00
|
|
|
|
|
|
|
return lengths
|
|
|
|
|
2021-07-17 18:18:33 +00:00
|
|
|
def _should_heartbeat(self, jid: JID, prekey: bool) -> bool:
|
|
|
|
"""
|
|
|
|
Internal helper for :py:func:`XEP_0384.should_heartbeat`.
|
|
|
|
|
|
|
|
Returns whether we should send a heartbeat message for JID.
|
|
|
|
|
|
|
|
We check if the message is a prekey message, in which case we
|
|
|
|
assume it's a new session and we want to ACK relatively early.
|
|
|
|
|
|
|
|
Otherwise we look at the number of messages since we have last
|
|
|
|
replied and if above a certain threshold we notify them that we're
|
|
|
|
still active.
|
|
|
|
"""
|
|
|
|
|
|
|
|
receiving_chain_lengths = self._chain_lengths(jid).get('receiving', [])
|
|
|
|
lengths = map(lambda d_l: d_l[1], receiving_chain_lengths)
|
|
|
|
inactive_session = max(lengths, default=0) > self.heartbeat_after
|
|
|
|
|
|
|
|
return prekey or inactive_session
|
|
|
|
|
2021-07-17 16:58:31 +00:00
|
|
|
def should_heartbeat(self, jid: JID, msg: Union[Message, Encrypted]) -> bool:
|
2021-07-13 18:29:14 +00:00
|
|
|
"""
|
|
|
|
Returns whether we should send a heartbeat message for JID.
|
|
|
|
See notes about heartbeat in
|
|
|
|
https://xmpp.org/extensions/xep-0384.html#rules.
|
2021-07-17 00:54:57 +00:00
|
|
|
|
|
|
|
This method will return True when a session among all of the
|
|
|
|
sessions for this JID is not yet confirmed, or if one of the
|
|
|
|
sessions hasn't been answered in a while.
|
2021-07-13 18:29:14 +00:00
|
|
|
"""
|
|
|
|
|
2021-07-17 18:18:33 +00:00
|
|
|
prekey: bool = False
|
2021-07-17 16:58:31 +00:00
|
|
|
|
2021-07-17 18:18:33 +00:00
|
|
|
# Get prekey information from message
|
2021-07-17 16:58:31 +00:00
|
|
|
encrypted = msg
|
|
|
|
if isinstance(msg, Message):
|
|
|
|
encrypted = msg['omemo_encrypted']
|
|
|
|
|
|
|
|
header = encrypted['header']
|
|
|
|
key = header.xml.find("{%s}key[@rid='%s']" % (
|
|
|
|
OMEMO_BASE_NS, self._device_id))
|
2021-07-17 18:18:33 +00:00
|
|
|
# Don't error out. If it's not encrypted to us we don't need to send a
|
|
|
|
# heartbeat.
|
2021-07-17 16:58:31 +00:00
|
|
|
if key is not None:
|
|
|
|
key = Key(key)
|
2021-07-17 18:18:33 +00:00
|
|
|
prekey = key['prekey'] in TRUE_VALUES
|
2021-07-17 16:58:31 +00:00
|
|
|
|
2021-07-17 18:18:33 +00:00
|
|
|
return self._should_heartbeat(jid, prekey)
|
2021-07-13 18:29:14 +00:00
|
|
|
|
2021-07-13 21:48:39 +00:00
|
|
|
async def make_heartbeat(self, jid: JID) -> Message:
|
2021-07-13 20:43:40 +00:00
|
|
|
"""
|
|
|
|
Returns a heartbeat message.
|
|
|
|
|
|
|
|
This is mainly used to tell receiving clients that our device is
|
|
|
|
still active. This is an empty key transport message of which we
|
|
|
|
won't use the generated shared secret.
|
|
|
|
"""
|
|
|
|
|
2021-07-13 21:14:04 +00:00
|
|
|
msg = self.xmpp.make_message(mto=jid)
|
2021-07-17 22:30:07 +00:00
|
|
|
encrypted = await self.encrypt_message(
|
2021-07-13 20:43:40 +00:00
|
|
|
plaintext=None,
|
|
|
|
recipients=[jid],
|
|
|
|
expect_problems=None,
|
2021-07-17 22:30:07 +00:00
|
|
|
_ignore_trust=True,
|
2021-07-13 20:43:40 +00:00
|
|
|
)
|
|
|
|
msg.append(encrypted)
|
|
|
|
return msg
|
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
def trust(self, jid: JID, device_id: int, ik: bytes) -> None:
|
2019-12-13 18:13:39 +00:00
|
|
|
self._omemo.setTrust(jid.bare, device_id, ik, True)
|
2018-12-30 21:22:58 +00:00
|
|
|
|
|
|
|
def distrust(self, jid: JID, device_id: int, ik: bytes) -> None:
|
2019-12-13 18:05:35 +00:00
|
|
|
self._omemo.setTrust(jid.bare, device_id, ik, False)
|
2018-12-30 21:22:58 +00:00
|
|
|
|
2019-08-25 09:48:48 +00:00
|
|
|
def get_trust_for_jid(self, jid: JID) -> Dict[str, List[Optional[Dict[str, Any]]]]:
|
|
|
|
"""
|
|
|
|
Fetches trust for JID. The returned dictionary will contain active
|
|
|
|
and inactive devices. Each of these dict will contain device ids
|
2019-08-25 21:20:13 +00:00
|
|
|
as keys, and a dict with 'key', 'trust' as values that can also be
|
|
|
|
None.
|
2019-08-25 09:48:48 +00:00
|
|
|
|
|
|
|
Example:
|
|
|
|
{
|
|
|
|
'active': {
|
|
|
|
123456: {
|
|
|
|
'key': bytes,
|
|
|
|
'trust': bool,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
'inactive': {
|
|
|
|
234567: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2019-08-25 21:20:13 +00:00
|
|
|
return self._omemo.getTrustForJID(jid.bare)
|
2019-08-24 23:56:28 +00:00
|
|
|
|
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-08-27 21:43:04 +00:00
|
|
|
def decrypt_message(
|
|
|
|
self,
|
|
|
|
encrypted: Encrypted,
|
|
|
|
sender: JID,
|
|
|
|
allow_untrusted: bool = False,
|
|
|
|
) -> Optional[str]:
|
|
|
|
header = encrypted['header']
|
2021-12-14 16:20:16 +00:00
|
|
|
|
|
|
|
payload = None
|
|
|
|
if encrypted['payload']['value'] is not None:
|
|
|
|
payload = b64dec(encrypted['payload']['value'])
|
2019-08-27 21:43:04 +00:00
|
|
|
|
2019-09-02 00:17:19 +00:00
|
|
|
jid = sender.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
|
2020-03-28 11:28:52 +00:00
|
|
|
if key['value'] is None:
|
|
|
|
raise ErroneousPayload('The key element was empty')
|
2018-11-18 23:22:50 +00:00
|
|
|
message = b64dec(key['value'])
|
2020-03-28 11:28:52 +00:00
|
|
|
if header['iv']['value'] is None:
|
|
|
|
raise ErroneousPayload('The iv element was empty')
|
2018-11-18 23:22:50 +00:00
|
|
|
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:
|
2021-12-14 16:20:16 +00:00
|
|
|
if payload is None:
|
|
|
|
self._omemo.decryptRatchetFowardingMessage(
|
|
|
|
jid,
|
|
|
|
sid,
|
|
|
|
iv,
|
|
|
|
message,
|
|
|
|
isPrekeyMessage,
|
|
|
|
allow_untrusted=allow_untrusted,
|
|
|
|
)
|
|
|
|
body = None
|
|
|
|
else:
|
|
|
|
body = self._omemo.decryptMessage(
|
|
|
|
jid,
|
|
|
|
sid,
|
|
|
|
iv,
|
|
|
|
message,
|
|
|
|
isPrekeyMessage,
|
|
|
|
payload,
|
|
|
|
allow_untrusted=allow_untrusted,
|
|
|
|
)
|
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)
|
2019-02-19 00:09:16 +00:00
|
|
|
except (omemo.exceptions.TrustException,) as exn:
|
|
|
|
if exn.problem == 'undecided':
|
|
|
|
raise UndecidedException(exn.bare_jid, exn.device, exn.ik)
|
2019-08-23 10:52:46 +00:00
|
|
|
if exn.problem == 'untrusted':
|
2019-02-19 00:09:16 +00:00
|
|
|
raise UntrustedException(exn.bare_jid, exn.device, exn.ik)
|
|
|
|
raise
|
2018-12-01 18:39:00 +00:00
|
|
|
finally:
|
|
|
|
asyncio.ensure_future(self._publish_bundle())
|
2018-05-23 20:13:06 +00:00
|
|
|
|
2021-07-17 18:18:33 +00:00
|
|
|
if self.auto_heartbeat and self._should_heartbeat(sender, isPrekeyMessage):
|
2021-07-13 21:48:39 +00:00
|
|
|
async def send_heartbeat():
|
2021-07-17 18:18:33 +00:00
|
|
|
log.debug('Sending a heartbeat message')
|
2021-07-13 21:48:39 +00:00
|
|
|
msg = await self.make_heartbeat(JID(jid))
|
|
|
|
msg.send()
|
|
|
|
asyncio.ensure_future(send_heartbeat())
|
2021-07-13 20:43:40 +00:00
|
|
|
|
2021-07-13 21:07:06 +00:00
|
|
|
return body
|
|
|
|
|
2019-01-31 14:47:12 +00:00
|
|
|
async def encrypt_message(
|
|
|
|
self,
|
2021-07-17 22:30:07 +00:00
|
|
|
plaintext: Optional[str],
|
2021-07-13 20:43:40 +00:00
|
|
|
recipients: List[JID],
|
|
|
|
expect_problems: Optional[Dict[JID, List[int]]] = None,
|
2021-07-17 22:30:07 +00:00
|
|
|
_ignore_trust: bool = False,
|
2019-01-31 14:47:12 +00:00
|
|
|
) -> 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.
|
2021-07-17 22:30:07 +00:00
|
|
|
|
|
|
|
If `plaintext` is specified, this will generate a full OMEMO payload. If
|
|
|
|
not, if `_ignore_trust` is True, this will generate a ratchet forwarding
|
|
|
|
message, and otherwise it will generate a key transport message.
|
|
|
|
|
|
|
|
These are rather technical details to the user and fiddling with
|
|
|
|
parameters else than `plaintext` and `recipients` should be rarely
|
|
|
|
needed.
|
2018-11-25 22:17:47 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
recipients = [jid.bare for jid in recipients]
|
|
|
|
|
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]
|
|
|
|
|
2020-03-11 00:32:39 +00:00
|
|
|
if expect_problems is None:
|
|
|
|
expect_problems = {}
|
|
|
|
|
|
|
|
expect_problems = {jid.bare: did for (jid, did) in expect_problems.items()}
|
2019-01-31 14:47:12 +00:00
|
|
|
|
2018-12-30 21:22:58 +00:00
|
|
|
try:
|
2021-07-13 20:43:40 +00:00
|
|
|
if plaintext is not None:
|
|
|
|
encrypted = self._omemo.encryptMessage(
|
|
|
|
recipients,
|
2021-07-17 22:30:07 +00:00
|
|
|
plaintext.encode('utf-8'),
|
|
|
|
self.bundles,
|
|
|
|
expect_problems=expect_problems,
|
|
|
|
)
|
|
|
|
elif _ignore_trust:
|
|
|
|
encrypted = self._omemo.encryptRatchetForwardingMessage(
|
|
|
|
recipients,
|
2021-07-13 20:43:40 +00:00
|
|
|
self.bundles,
|
|
|
|
expect_problems=expect_problems,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
encrypted = self._omemo.encryptKeyTransportMessage(
|
|
|
|
recipients,
|
|
|
|
self.bundles,
|
|
|
|
expect_problems=expect_problems,
|
|
|
|
)
|
2018-12-30 21:22:58 +00:00
|
|
|
return _generate_encrypted_payload(encrypted)
|
2020-03-11 00:33:10 +00:00
|
|
|
except omemo.exceptions.EncryptionProblemsException as exception:
|
|
|
|
errors = exception.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-12-30 21:22:58 +00:00
|
|
|
for exn in errors:
|
|
|
|
if isinstance(exn, omemo.exceptions.NoDevicesException):
|
2019-12-10 16:04:11 +00:00
|
|
|
await self._fetch_device_list(JID(exn.bare_jid))
|
2018-12-30 21:22:58 +00:00
|
|
|
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:
|
2019-08-23 22:44:46 +00:00
|
|
|
devices = self.bundles.setdefault(exn.bare_jid, {})
|
2018-12-30 21:22:58 +00:00
|
|
|
devices[exn.device] = bundle
|
2019-02-19 00:09:16 +00:00
|
|
|
elif isinstance(exn, omemo.exceptions.TrustException):
|
|
|
|
# On TrustException, there are two possibilities.
|
2019-01-31 14:47:12 +00:00
|
|
|
# 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
|
2019-02-19 00:09:16 +00:00
|
|
|
if exn.problem == 'undecided':
|
2019-01-31 14:47:12 +00:00
|
|
|
raise UndecidedException(exn.bare_jid, exn.device, exn.ik)
|
2019-12-09 16:46:05 +00:00
|
|
|
distrusted_jid = JID(exn.bare_jid)
|
|
|
|
expect_problems.setdefault(distrusted_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
|
2019-12-22 03:08:54 +00:00
|
|
|
# decide what to do with it, as there isn't much we can do if
|
2018-12-31 20:51:56 +00:00
|
|
|
# other issues can't be resolved.
|
|
|
|
continue
|
2019-02-17 17:39:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
register_plugin(XEP_0384)
|