xmpp.py 11.8 KB
Newer Older
Philipp Hörist's avatar
Philipp Hörist committed
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
# -*- coding: utf-8 -*-
#
# Copyright 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
#
# This file is part of Gajim-OMEMO plugin.
#
# The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# the Gajim-OMEMO plugin.  If not, see <http://www.gnu.org/licenses/>.
#

""" This module handles all the XMPP logic like creating different kind of
stanza nodes and geting data from stanzas.
"""

import logging
import random
from base64 import b64decode, b64encode

from nbxmpp.protocol import NS_PUBSUB, Iq
from nbxmpp.simplexml import Node

31
32
33
from gajim.common import app  # pylint: disable=import-error
from gajim.common.pep import AbstractPEP  # pylint: disable=import-error
from gajim.plugins.helpers import log_calls  # pylint: disable=import-error
Philipp Hörist's avatar
Philipp Hörist committed
34
35
36
37
38
39
40
41

NS_PUBSUB_EVENT = NS_PUBSUB + '#event'

NS_EME = 'urn:xmpp:eme:0'
NS_OMEMO = 'eu.siacs.conversations.axolotl'
NS_DEVICE_LIST = NS_OMEMO + '.devicelist'
NS_NOTIFY = NS_DEVICE_LIST + '+notify'
NS_BUNDLES = NS_OMEMO + '.bundles:'
42
NS_HINTS = 'urn:xmpp:hints'
Philipp Hörist's avatar
Philipp Hörist committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
log = logging.getLogger('gajim.plugin_system.omemo')


class PublishNode(Node):
    def __init__(self, node_str, data):
        assert node_str is not None and isinstance(data, Node)
        Node.__init__(self, tag='publish', attrs={'node': node_str})
        self.addChild('item').addChild(node=data)


class PubsubNode(Node):
    def __init__(self, data):
        assert isinstance(data, Node)
        Node.__init__(self, tag='pubsub', attrs={'xmlns': NS_PUBSUB})
        self.addChild(node=data)


class DeviceListAnnouncement(Iq):
    def __init__(self, device_list):
        assert isinstance(device_list, list)
        assert len(device_list) > 0
64
        id_ = app.get_an_id()
Philipp Hörist's avatar
Philipp Hörist committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        attrs = {'id': id_}
        Iq.__init__(self, typ='set', attrs=attrs)

        list_node = Node('list', attrs={'xmlns': NS_OMEMO})
        for device in device_list:
            list_node.addChild('device').setAttr('id', device)

        publish = PublishNode(NS_DEVICE_LIST, list_node)
        pubsub = PubsubNode(publish)

        self.addChild(node=pubsub)


class OmemoMessage(Node):
    def __init__(self, msg_dict):
        # , contact_jid, key, iv, payload, dev_id, my_dev_id):
        Node.__init__(self, 'encrypted', attrs={'xmlns': NS_OMEMO})
        header = Node('header', attrs={'sid': msg_dict['sid']})
83
84
85
86
87
88
89
90
        for rid, (key, prekey) in msg_dict['keys'].items():
            if prekey:
                child = header.addChild('key',
                                        attrs={'prekey': 'true', 'rid': rid})
            else:
                child = header.addChild('key',
                                        attrs={'rid': rid})
            child.addData(b64encode(key).decode('utf-8'))
Philipp Hörist's avatar
Philipp Hörist committed
91
92
93
94
95
96
97
98
99
        header.addChild('iv').addData(b64encode(msg_dict['iv']).decode('utf-8'))
        self.addChild(node=header)
        self.addChild('payload').addData(b64encode(msg_dict['payload'])
                                         .decode('utf-8'))


class BundleInformationQuery(Iq):
    def __init__(self, contact_jid, device_id):
        assert isinstance(device_id, int)
100
        id_ = app.get_an_id()
Philipp Hörist's avatar
Philipp Hörist committed
101
102
        attrs = {'id': id_}
        Iq.__init__(self, typ='get', attrs=attrs, to=contact_jid)
103
104
        items = Node('items', attrs={'node': NS_BUNDLES + str(device_id),
                                     'max_items': 1})
Philipp Hörist's avatar
Philipp Hörist committed
105
106
107
108
109
110
        pubsub = PubsubNode(items)
        self.addChild(node=pubsub)


class BundleInformationAnnouncement(Iq):
    def __init__(self, state_bundle, device_id):
111
        id_ = app.get_an_id()
Philipp Hörist's avatar
Philipp Hörist committed
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
        attrs = {'id': id_}
        Iq.__init__(self, typ='set', attrs=attrs)
        bundle_node = self.make_bundle_node(state_bundle)
        publish = PublishNode(NS_BUNDLES + str(device_id), bundle_node)
        pubsub = PubsubNode(publish)
        self.addChild(node=pubsub)

    def make_bundle_node(self, state_bundle):
        result = Node('bundle', attrs={'xmlns': NS_OMEMO})
        prekey_pub_node = result.addChild(
            'signedPreKeyPublic',
            attrs={'signedPreKeyId': state_bundle['signedPreKeyId']})
        prekey_pub_node.addData(state_bundle['signedPreKeyPublic']
                                .decode('utf-8'))

        prekey_sig_node = result.addChild('signedPreKeySignature')
        prekey_sig_node.addData(state_bundle['signedPreKeySignature']
                                .decode('utf-8'))

        identity_key_node = result.addChild('identityKey')
        identity_key_node.addData(state_bundle['identityKey'].decode('utf-8'))
        prekeys = result.addChild('prekeys')

        for key in state_bundle['prekeys']:
            prekeys.addChild('preKeyPublic',
                             attrs={'preKeyId': key[0]}) \
                             .addData(key[1].decode('utf-8'))
        return result


class DevicelistQuery(Iq):
143
    def __init__(self, contact_jid):
144
        id_ = app.get_an_id()
Philipp Hörist's avatar
Philipp Hörist committed
145
146
        attrs = {'id': id_}
        Iq.__init__(self, typ='get', attrs=attrs, to=contact_jid)
147
        items = Node('items', attrs={'node': NS_DEVICE_LIST, 'max_items': 1})
Philipp Hörist's avatar
Philipp Hörist committed
148
149
150
151
152
        pubsub = PubsubNode(items)
        self.addChild(node=pubsub)


class DevicelistPEP(AbstractPEP):
153
    type_ = 'omemo-devicelist'
Philipp Hörist's avatar
Philipp Hörist committed
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
    namespace = NS_DEVICE_LIST

    def _extract_info(self, items):
        return ({}, [])


@log_calls('OmemoPlugin')
def unpack_device_bundle(bundle, device_id):
    pubsub = bundle.getTag('pubsub', namespace=NS_PUBSUB)
    if not pubsub:
        log.warning('OMEMO device bundle has no pubsub node')
        return
    items = pubsub.getTag('items', attrs={'node': NS_BUNDLES + str(device_id)})
    if not items:
        log.warning('OMEMO device bundle has no items node')
        return

    item = items.getTag('item', namespace=NS_PUBSUB)
    if not item:
        log.warning('OMEMO device bundle has no item node')
        return

    bundle = item.getTag('bundle', namespace=NS_OMEMO)
    if not bundle:
        log.warning('OMEMO device bundle has no bundle node')
        return

    signed_prekey_node = bundle.getTag('signedPreKeyPublic',
                                       namespace=NS_OMEMO)
    if not signed_prekey_node:
        log.warning('OMEMO device bundle has no signedPreKeyPublic node')
        return

    result = {}
    result['signedPreKeyPublic'] = decode_data(signed_prekey_node)
    if not result['signedPreKeyPublic']:
        log.warning('OMEMO device bundle has no signedPreKeyPublic data')
        return

    if not signed_prekey_node.getAttr('signedPreKeyId'):
        log.warning('OMEMO device bundle has no signedPreKeyId')
        return
    result['signedPreKeyId'] = int(signed_prekey_node.getAttr(
        'signedPreKeyId'))

    signed_signature_node = bundle.getTag('signedPreKeySignature',
                                          namespace=NS_OMEMO)
    if not signed_signature_node:
        log.warning('OMEMO device bundle has no signedPreKeySignature node')
        return

    result['signedPreKeySignature'] = decode_data(signed_signature_node)
    if not result['signedPreKeySignature']:
        log.warning('OMEMO device bundle has no signedPreKeySignature data')
        return

    identity_key_node = bundle.getTag('identityKey', namespace=NS_OMEMO)
    if not identity_key_node:
        log.warning('OMEMO device bundle has no identityKey node')
        return

    result['identityKey'] = decode_data(identity_key_node)
    if not result['identityKey']:
        log.warning('OMEMO device bundle has no identityKey data')
        return

    prekeys = bundle.getTag('prekeys', namespace=NS_OMEMO)
    if not prekeys or len(prekeys.getChildren()) == 0:
        log.warning('OMEMO device bundle has no prekys')
        return

    picked_key_node = random.SystemRandom().choice(prekeys.getChildren())

    if not picked_key_node.getAttr('preKeyId'):
        log.warning('OMEMO PreKey has no id set')
        return
    result['preKeyId'] = int(picked_key_node.getAttr('preKeyId'))

    result['preKeyPublic'] = decode_data(picked_key_node)
    if not result['preKeyPublic']:
        return
    return result


@log_calls('OmemoPlugin')
def unpack_encrypted(encrypted_node):
    """ Unpacks the encrypted node, decodes the data and returns a msg_dict.
    """
    if not encrypted_node.getNamespace() == NS_OMEMO:
        log.warning("Encrypted node with wrong NS")
        return

    header_node = encrypted_node.getTag('header', namespace=NS_OMEMO)
    if not header_node:
        log.warning("OMEMO message without header")
        return

    if not header_node.getAttr('sid'):
        log.warning("OMEMO message without sid in header")
        return

    sid = int(header_node.getAttr('sid'))

    iv_node = header_node.getTag('iv', namespace=NS_OMEMO)
    if not iv_node:
        log.warning("OMEMO message without iv")
        return

    iv = decode_data(iv_node)
    if not iv:
        log.warning("OMEMO message without iv data")

    payload_node = encrypted_node.getTag('payload', namespace=NS_OMEMO)
    payload = None
    if payload_node:
        payload = decode_data(payload_node)

    key_nodes = header_node.getTags('key')
    if len(key_nodes) < 1:
        log.warning("OMEMO message without keys")
        return

    keys = {}
    for kn in key_nodes:
        rid = kn.getAttr('rid')
        if not rid:
            log.warning('Omemo key without rid')
            continue

        if not kn.getData():
            log.warning('Omemo key without data')
            continue

        keys[int(rid)] = decode_data(kn)

    result = {'sid': sid, 'iv': iv, 'keys': keys, 'payload': payload}
    return result


def unpack_device_list_update(stanza, account):
    """ Unpacks the device list from a stanza

        Parameters
        ----------
        stanza

        Returns
        -------
        [int]
            List of device ids or empty list if nothing found
    """
    event_node = stanza.getTag('event', namespace=NS_PUBSUB_EVENT)
    if not event_node:
        event_node = stanza.getTag('pubsub', namespace=NS_PUBSUB)
    result = []

    if not event_node:
        log.warning(account + ' => Device list update event node empty!')
        return result

    items = event_node.getTag('items', {'node': NS_DEVICE_LIST})
    if not items or len(items.getChildren()) != 1:
Philipp Hörist's avatar
Philipp Hörist committed
316
        log.warning(
Philipp Hörist's avatar
Philipp Hörist committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
            account +
            ' => Device list update items node empty or not omemo device update')
        return result

    list_node = items.getChildren()[0].getTag('list')
    if not list_node or len(list_node.getChildren()) == 0:
        log.warning(account + ' => Device list update list node empty!')
        return result

    devices_nodes = list_node.getChildren()

    for dn in devices_nodes:
        _id = dn.getAttr('id')
        if _id:
            result.append(int(_id))

    return result


def decode_data(node):
    """ Fetch the data from specified node and b64decode it. """
    data = node.getData()

    if not data:
        log.warning("No node data")
        return
    try:
        return b64decode(data)
    except:
        log.warning('b64decode broken')
        return


def successful(stanza):
    """ Check if stanza type is result.  """
    return stanza.getAttr('type') == 'result'