omemo/0000755000175500017550000000000013623023766011734 5ustar debacledebacleomemo/gtk/0000755000175500017550000000000013623023766012521 5ustar debacledebacleomemo/gtk/key.py0000644000175500017550000002736013623023766013673 0ustar debacledebacle# Copyright (C) 2018 Philipp Hörist # # This file is part of Gajim. # # Gajim 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; version 3 only. # # Gajim 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 Gajim. If not, see . import logging import binascii import textwrap from gi.repository import Gtk from gi.repository import GdkPixbuf from gajim.common import app from gajim.plugins.plugins_i18n import _ from omemo.gtk.util import DialogButton, ButtonAction from omemo.gtk.util import NewConfirmationDialog from omemo.gtk.util import Trust log = logging.getLogger('gajim.plugin_system.omemo') TRUST_DATA = { Trust.NOT_TRUSTED: ('dialog-error-symbolic', _('Not Trusted'), 'error-color'), Trust.UNKNOWN: ('security-low-symbolic', _('Not Decided'), 'warning-color'), Trust.VERIFIED: ('security-high-symbolic', _('Trusted'), 'success-color') } class KeyDialog(Gtk.Dialog): def __init__(self, plugin, contact, transient, windowinstances, groupchat=False): flags = Gtk.DialogFlags.DESTROY_WITH_PARENT super().__init__(_('OMEMO Fingerprints'), None, flags) self.set_transient_for(transient) self.set_resizable(True) self.set_default_size(-1, 400) self.get_style_context().add_class('omemo-key-dialog') self._groupchat = groupchat self._contact = contact self._windowinstances = windowinstances self._account = self._contact.account.name self._plugin = plugin self._con = plugin.connections[self._account] self.omemostate = self._plugin.get_omemo(self._account) self._own_jid = app.get_jid_from_account(self._account) # Header jid = self._contact.jid self._header = Gtk.Label(_('Fingerprints for %s') % jid) self._header.get_style_context().add_class('bold') self._header.get_style_context().add_class('dim-label') # Fingerprints list self._listbox = Gtk.ListBox() self._listbox.set_selection_mode(Gtk.SelectionMode.NONE) self._scrolled = Gtk.ScrolledWindow() self._scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self._scrolled.add(self._listbox) # Own fingerprint self._label = Gtk.Label(_('Own Fingerprint')) self._label.get_style_context().add_class('bold') self._label.get_style_context().add_class('dim-label') self._omemo_logo = Gtk.Image() omemo_img_path = self._plugin.local_file_path('omemo.png') omemo_pixbuf = GdkPixbuf.Pixbuf.new_from_file(omemo_img_path) self._omemo_logo.set_from_pixbuf(omemo_pixbuf) ownfpr = binascii.hexlify(self.omemostate.store.getIdentityKeyPair() .getPublicKey().serialize()).decode('utf-8') ownfpr_format = KeyRow._format_fingerprint(ownfpr[2:]) self._ownfpr = Gtk.Label(ownfpr_format) self._ownfpr.get_style_context().add_class('omemo-mono') self._ownfpr.set_selectable(True) self._ownfpr_box = Gtk.Box(spacing=12) self._ownfpr_box.set_halign(Gtk.Align.CENTER) self._ownfpr_box.pack_start(self._omemo_logo, True, True, 0) self._ownfpr_box.pack_start(self._ownfpr, True, True, 0) box = self.get_content_area() box.set_orientation(Gtk.Orientation.VERTICAL) box.set_spacing(12) box.pack_start(self._header, False, True, 0) box.pack_start(self._scrolled, True, True, 0) box.pack_start(self._label, False, True, 0) box.pack_start(self._ownfpr_box, False, True, 0) self.update() self.connect('destroy', self._on_destroy) self.show_all() def update(self): self._listbox.foreach(lambda row: self._listbox.remove(row)) self._load_fingerprints(self._own_jid) self._load_fingerprints(self._contact.jid, self._groupchat is True) def _load_fingerprints(self, contact_jid, groupchat=False): from axolotl.state.sessionrecord import SessionRecord state = self.omemostate if groupchat: contact_jids = [] for nick in self._con.groupchat[contact_jid]: real_jid = self._con.groupchat[contact_jid][nick] if real_jid == self._own_jid: continue contact_jids.append(real_jid) session_db = state.store.getSessionsFromJids(contact_jids) else: session_db = state.store.getSessionsFromJid(contact_jid) for item in session_db: _id, jid, deviceid, record, active = item active = bool(active) identity_key = SessionRecord(serialized=record). \ getSessionState().getRemoteIdentityKey() fpr = binascii.hexlify(identity_key.getPublicKey().serialize()).decode('utf-8') fpr = fpr[2:] trust = state.store.isTrustedIdentity(jid, identity_key) log.info('Load: %s %s', fpr, trust) self._listbox.add(KeyRow(jid, deviceid, fpr, trust, active)) def _on_destroy(self, *args): del self._windowinstances['dialog'] class KeyRow(Gtk.ListBoxRow): def __init__(self, jid, deviceid, fpr, trust, active): Gtk.ListBoxRow.__init__(self) self.set_activatable(False) self.active = active self.trust = trust self.jid = jid self.deviceid = deviceid box = Gtk.Box() box.set_spacing(12) self._trust_button = TrustButton(self) box.add(self._trust_button) label_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) jid_label = Gtk.Label(jid) jid_label.get_style_context().add_class('dim-label') jid_label.set_selectable(False) jid_label.set_halign(Gtk.Align.START) jid_label.set_valign(Gtk.Align.START) jid_label.set_hexpand(True) label_box.add(jid_label) fingerprint = Gtk.Label( label=self._format_fingerprint(fpr)) fingerprint.get_style_context().add_class('omemo-mono') if not active: fingerprint.get_style_context().add_class('omemo-inactive-color') fingerprint.set_selectable(True) fingerprint.set_halign(Gtk.Align.START) fingerprint.set_valign(Gtk.Align.START) fingerprint.set_hexpand(True) label_box.add(fingerprint) box.add(label_box) self.add(box) self.show_all() def delete_fingerprint(self, *args): def _remove(): state = self.get_toplevel().omemostate record = state.store.loadSession(self.jid, self.deviceid) identity_key = record.getSessionState().getRemoteIdentityKey() state.store.deleteSession(self.jid, self.deviceid) state.store.deleteIdentity(self.jid, identity_key) self.get_parent().remove(self) self.destroy() buttons = { Gtk.ResponseType.CANCEL: DialogButton(_('Cancel')), Gtk.ResponseType.OK: DialogButton(_('Delete'), _remove, ButtonAction.DESTRUCTIVE), } NewConfirmationDialog( _('Delete Fingerprint'), _('Doing so will permanently delete this Fingerprint'), buttons, transient_for=self.get_toplevel()) def set_trust(self): icon_name, tooltip, css_class = TRUST_DATA[self.trust] image = self._trust_button.get_child() image.set_from_icon_name(icon_name, Gtk.IconSize.MENU) image.get_style_context().add_class(css_class) image.set_tooltip_text(tooltip) state = self.get_toplevel().omemostate record = state.store.loadSession(self.jid, self.deviceid) identity_key = record.getSessionState().getRemoteIdentityKey() state.store.setTrust(identity_key, self.trust) @staticmethod def _format_fingerprint(fingerprint): fplen = len(fingerprint) wordsize = fplen // 8 buf = '' for w in range(0, fplen, wordsize): buf += '{0} '.format(fingerprint[w:w + wordsize]) buf = textwrap.fill(buf, width=36) return buf.rstrip().upper() class TrustButton(Gtk.MenuButton): def __init__(self, row): Gtk.MenuButton.__init__(self) self._row = row self._css_class = '' self.set_popover(TrustPopver(row)) self.set_valign(Gtk.Align.CENTER) self.update() def update(self): icon_name, tooltip, css_class = TRUST_DATA[self._row.trust] image = self.get_child() image.set_from_icon_name(icon_name, Gtk.IconSize.MENU) # Remove old color from icon image.get_style_context().remove_class(self._css_class) if not self._row.active: css_class = 'omemo-inactive-color' tooltip = '%s - %s' % (_('Inactive'), tooltip) image.get_style_context().add_class(css_class) self._css_class = css_class self.set_tooltip_text(tooltip) class TrustPopver(Gtk.Popover): def __init__(self, row): Gtk.Popover.__init__(self) self._row = row self._listbox = Gtk.ListBox() self._listbox.set_selection_mode(Gtk.SelectionMode.NONE) if row.trust != Trust.VERIFIED: self._listbox.add(VerifiedOption()) if row.trust != Trust.NOT_TRUSTED: self._listbox.add(NotTrustedOption()) self._listbox.add(DeleteOption()) self.add(self._listbox) self._listbox.show_all() self._listbox.connect('row-activated', self._activated) self.get_style_context().add_class('omemo-trust-popover') def _activated(self, listbox, row): self.popdown() if row.type_ is None: self._row.delete_fingerprint() else: self._row.trust = row.type_ self._row.set_trust() self.get_relative_to().update() self.update() def update(self): self._listbox.foreach(lambda row: self._listbox.remove(row)) if self._row.trust != Trust.VERIFIED: self._listbox.add(VerifiedOption()) if self._row.trust != Trust.NOT_TRUSTED: self._listbox.add(NotTrustedOption()) self._listbox.add(DeleteOption()) class MenuOption(Gtk.ListBoxRow): def __init__(self): Gtk.ListBoxRow.__init__(self) box = Gtk.Box() box.set_spacing(6) image = Gtk.Image.new_from_icon_name(self.icon, Gtk.IconSize.MENU) label = Gtk.Label(label=self.label) image.get_style_context().add_class(self.color) box.add(image) box.add(label) self.add(box) self.show_all() class VerifiedOption(MenuOption): type_ = Trust.VERIFIED icon = 'security-high-symbolic' label = _('Trusted') color = 'success-color' def __init__(self): MenuOption.__init__(self) class NotTrustedOption(MenuOption): type_ = Trust.NOT_TRUSTED icon = 'dialog-error-symbolic' label = _('Not Trusted') color = 'error-color' def __init__(self): MenuOption.__init__(self) class DeleteOption(MenuOption): type_ = None icon = 'user-trash-symbolic' label = _('Delete') color = '' def __init__(self): MenuOption.__init__(self) omemo/gtk/util.py0000644000175500017550000000454613623023766014061 0ustar debacledebacle# This file is part of Gajim-OMEMO. # # Gajim-OMEMO 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; version 3 only. # # 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 Gajim-OMEMO. If not, see . from collections import namedtuple from enum import IntEnum from enum import Enum from gi.repository import Gtk DialogButton = namedtuple('DialogButton', 'text callback action') DialogButton.__new__.__defaults__ = (None, None) # type: ignore class ButtonAction(Enum): DESTRUCTIVE = 'destructive-action' SUGGESTED = 'suggested-action' class Trust(IntEnum): NOT_TRUSTED = 0 VERIFIED = 1 UNKNOWN = 2 class NewConfirmationDialog(Gtk.MessageDialog): def __init__(self, text, sec_text, buttons, transient_for=None): Gtk.MessageDialog.__init__(self, transient_for=transient_for, message_type=Gtk.MessageType.QUESTION, text=text) self._buttons = buttons for response, button in buttons.items(): self.add_button(button.text, response) if button.action is not None: widget = self.get_widget_for_response(response) widget.get_style_context().add_class(button.action.value) self.format_secondary_markup(sec_text) self.connect('response', self._on_response) self.run() def _on_response(self, dialog, response): if response == Gtk.ResponseType.DELETE_EVENT: # Look if DELETE_EVENT is mapped to another response response = self._buttons.get(response, None) if response is None: # If DELETE_EVENT was not mapped we assume CANCEL response = Gtk.ResponseType.CANCEL button = self._buttons.get(response, None) if button is None: self.destroy() return if button.callback is not None: button.callback() self.destroy() omemo/gtk/config.py0000644000175500017550000002074613623023766014351 0ustar debacledebacle''' Copyright 2015 Bahtiar `kalkin-` Gadimov Copyright 2015 Daniel Gultsch Copyright 2016 Philipp Hörist 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 . ''' import binascii import logging import os import textwrap from enum import IntEnum, unique from gi.repository import GdkPixbuf from gajim.common import app from gajim.common import configpaths from gajim.plugins.gui import GajimPluginConfigDialog from gajim.plugins.helpers import get_builder log = logging.getLogger('gajim.plugin_system.omemo') PILLOW = False try: import qrcode PILLOW = True except ImportError as error: log.debug(error) log.error('python-qrcode or dependencies of it are not available') @unique class State(IntEnum): UNTRUSTED = 0 TRUSTED = 1 UNDECIDED = 2 class OMEMOConfigDialog(GajimPluginConfigDialog): def init(self): # pylint: disable=attribute-defined-outside-init path = self.plugin.local_file_path('gtk/config.ui') self._ui = get_builder(path) image_path = self.plugin.local_file_path('omemo.png') self._ui.image.set_from_file(image_path) try: self.disabled_accounts = self.plugin.config['DISABLED_ACCOUNTS'] except KeyError: self.plugin.config['DISABLED_ACCOUNTS'] = [] self.disabled_accounts = self.plugin.config['DISABLED_ACCOUNTS'] log.debug('Disabled Accounts:') log.debug(self.disabled_accounts) self.device_model = self._ui.get_object('deviceid_store') self.disabled_acc_store = self._ui.get_object('disabled_account_store') self.account_store = self._ui.get_object('account_store') self.active_acc_view = self._ui.get_object('active_accounts_view') self.disabled_acc_view = self._ui.get_object('disabled_accounts_view') box = self.get_content_area() box.pack_start(self._ui.get_object('notebook1'), True, True, 0) self._ui.connect_signals(self) self.plugin_active = False def on_run(self): for plugin in app.plugin_manager.active_plugins: log.debug(type(plugin)) if type(plugin).__name__ == 'OmemoPlugin': self.plugin_active = True break self.update_account_store() self.update_account_combobox() self.update_disabled_account_view() def is_in_accountstore(self, account): for row in self.account_store: if row[0] == account: return True return False def update_account_store(self): for account in sorted(app.contacts.get_accounts()): if account in self.disabled_accounts: continue if account == 'Local': continue if not self.is_in_accountstore(account): self.account_store.append(row=(account,)) def update_account_combobox(self): if self.plugin_active is False: return if len(self.account_store) > 0: self._ui.get_object('account_combobox').set_active(0) else: self.account_combobox_changed_cb( self._ui.get_object('account_combobox')) def account_combobox_changed_cb(self, box, *args): self.update_context_list() def get_qrcode(self, jid, sid, fingerprint): file_name = 'omemo_{}.png'.format(jid) path = os.path.join( configpaths.get('MY_DATA'), file_name) ver_string = 'xmpp:{}?omemo-sid-{}={}'.format(jid, sid, fingerprint) log.debug('Verification String: ' + ver_string) if os.path.exists(path): return path qr = qrcode.QRCode(version=None, error_correction=2, box_size=4, border=1) qr.add_data(ver_string) qr.make(fit=True) img = qr.make_image() img.save(path) return path def update_disabled_account_view(self): self.disabled_acc_store.clear() for account in self.disabled_accounts: self.disabled_acc_store.append(row=(account,)) def activate_accounts_btn_clicked(self, button, *args): mod, paths = self.disabled_acc_view.get_selection().get_selected_rows() for path in paths: it = mod.get_iter(path) account = mod.get(it, 0) if account[0] in self.disabled_accounts and \ not self.is_in_accountstore(account[0]): self.account_store.append(row=(account[0],)) self.disabled_accounts.remove(account[0]) self.update_disabled_account_view() self.plugin.config['DISABLED_ACCOUNTS'] = self.disabled_accounts self.update_account_combobox() def disable_accounts_btn_clicked(self, button, *args): mod, paths = self.active_acc_view.get_selection().get_selected_rows() for path in paths: it = mod.get_iter(path) account = mod.get(it, 0) if account[0] not in self.disabled_accounts and \ self.is_in_accountstore(account[0]): self.disabled_accounts.append(account[0]) self.account_store.remove(it) self.update_disabled_account_view() self.plugin.config['DISABLED_ACCOUNTS'] = self.disabled_accounts self.update_account_combobox() def cleardevice_button_clicked_cb(self, button, *args): active = self._ui.get_object('account_combobox').get_active() account = self.account_store[active][0] self.plugin.connections[account].publish_own_devices_list(new=True) self.update_context_list() def refresh_button_clicked_cb(self, button, *args): self.update_context_list() def update_context_list(self): self.device_model.clear() self.qrcode = self._ui.get_object('qrcode') self.qrinfo = self._ui.get_object('qrinfo') if len(self.account_store) == 0: self._ui.get_object('ID').set_markup('') self._ui.get_object('fingerprint_label').set_markup('') self._ui.get_object('refresh').set_sensitive(False) self._ui.get_object('cleardevice_button').set_sensitive(False) self._ui.get_object('qrcode').clear() return active = self._ui.get_object('account_combobox').get_active() account = self.account_store[active][0] # Set buttons active self._ui.get_object('refresh').set_sensitive(True) if account == 'Local': self._ui.get_object('cleardevice_button').set_sensitive(False) else: self._ui.get_object('cleardevice_button').set_sensitive(True) # Set FPR Label and DeviceID state = self.plugin.get_omemo(account) deviceid = state.own_device_id self._ui.get_object('ID').set_markup('%s' % deviceid) ownfpr = binascii.hexlify(state.store.getIdentityKeyPair() .getPublicKey().serialize()).decode('utf-8') human_ownfpr = self.human_hash(ownfpr[2:]) self._ui.get_object('fingerprint_label').set_markup('%s' % human_ownfpr) # Set Device ID List for item in state.own_devices: self.device_model.append([item]) # Set QR Verification Code if PILLOW: path = self.get_qrcode( app.get_jid_from_account(account), deviceid, ownfpr[2:]) pixbuf = GdkPixbuf.Pixbuf.new_from_file(path) self.qrcode.set_from_pixbuf(pixbuf) self.qrcode.show() self.qrinfo.hide() else: self.qrcode.hide() self.qrinfo.show() def human_hash(self, fpr): fpr = fpr.upper() fplen = len(fpr) wordsize = fplen // 8 buf = '' for w in range(0, fplen, wordsize): buf += '{0} '.format(fpr[w:w + wordsize]) buf = textwrap.fill(buf, width=36) return buf.rstrip() omemo/gtk/progress.ui0000644000175500017550000001232513623023766014727 0ustar debacledebacle True 18 Download False center-on-parent True go-down dialog 250 True False 12 True False end True False 2 4 3 gtk-cancel True True True False True False True 2 False False end 0 True False OMEMO 6 False True 0 True False 8 4 8 8 True False True False True 1 True False 4 4 8 8 True False 0.10000000149 True False True 2 omemo/gtk/__init__.py0000644000175500017550000000000013623023766014620 0ustar debacledebacleomemo/gtk/progress.py0000644000175500017550000000337313623023766014745 0ustar debacledebacle# Copyright (C) 2018 Philipp Hörist # # This file is part of Gajim. # # Gajim 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; version 3 only. # # Gajim 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 Gajim. If not, see . from gajim.plugins.helpers import get_builder class ProgressWindow: def __init__(self, plugin, window, event): self._plugin = plugin self._event = event path = self._plugin.local_file_path('gtk/progress.ui') self._ui = get_builder(path) self._ui.progress_dialog.set_transient_for(window) self._ui.progressbar.set_text("") self._ui.progress_dialog.show_all() image_path = self._plugin.local_file_path('omemo.png') self._ui.image.set_from_file(image_path) self._ui.connect_signals(self) self._seen = 0 def set_text(self, text): self._ui.label.set_markup('%s' % text) return False def update_progress(self, seen, total): self._seen += seen pct = (self._seen / float(total)) * 100.0 self._ui.progressbar.set_fraction(self._seen / float(total)) self._ui.progressbar.set_text(str(int(pct)) + "%") return False def close_dialog(self, *args): self._ui.progress_dialog.destroy() return False def on_destroy(self, *args): self._event.set() omemo/gtk/style.css0000644000175500017550000000110613623023766014371 0ustar debacledebacle.omemo-dark-success-color { color: darker(@success_color); } .omemo-inactive-color { color: @insensitive_fg_color; } .omemo-mono { font-size: 12px; font-family: monospace; } .omemo-key-dialog > box { margin: 18px; } .omemo-key-dialog scrolledwindow row { border-bottom: 1px solid; border-color: @unfocused_borders; padding: 10px 20px 10px 10px; } .omemo-key-dialog scrolledwindow row:last-child { border-bottom: 0px} .omemo-key-dialog scrolledwindow { border: 1px solid; border-color:@unfocused_borders; } .omemo-trust-popover row { padding: 10px 15px 10px 10px; } omemo/gtk/config.ui0000644000175500017550000006532713623023766014342 0ustar debacledebacle True True True False 18 vertical 6 False True 6 False 6 end False False 0 False start 6 True False True start For verification via QR-Code you have to install True False True 0 True False start python-qrcode True True True 1 False False 0 False True 0 True False start 6 12 True False end Acc_ount True account_combobox 0 0 200 True False True start account_store 0 1 0 True False end 6 Own _Fingerprint True fingerprint_label 0 1 200 30 True False start 6 True True 1 1 True False end Own _Device ID True ID 0 2 200 30 True False start True 0 1 2 False True Scan this QR-Code with your mobile device for easy verification start 6 6 gtk-missing-image 1 1 3 True False OMEMO start 0 3 True False start Note: Fingerprints of your contacts are managed in the message window. True 1 4 False True 1 True False Own Fingerprints False True False 18 vertical 6 25 True False center Published Devices False True 0 True True center never 300 True False deviceid_store 0 horizontal Device ID True 0 True True 1 True False center 6 12 _Clear Devices True True True This clears your device list from the server. Clearing the device list helps you to remove unused devices from the encryption process. It is advised to go online with all of your actively used devices after clearing. True False False 0 gtk-refresh 160 True True True True False False 1 False True 2 1 True False Clear Devices 1 False True False 18 vertical 6 True False warning False 6 end False False 0 False 30 True False You have to restart Gajim for changes to take effect ! False True 0 False False 0 False True 0 True False 6 12 True 200 True True out True True True account_store horizontal Active Accounts 0.5 0 0 0 True True out True True True disabled_account_store horizontal Disabled Accounts 0.5 0 1 0 _Disable Account True True True center True 0 1 _Enable Account True True True center True 1 1 False True 1 2 True False Disable Accounts 2 False omemo/xmpp.py0000644000175500017550000002427313623023766013302 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Bahtiar `kalkin-` Gadimov # # 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 . # """ 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 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 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:' NS_HINTS = 'urn:xmpp:hints' log = logging.getLogger('gajim.plugin_system.omemo') 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 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']}) 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')) 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) id_ = app.get_an_id() attrs = {'id': id_} Iq.__init__(self, typ='get', attrs=attrs, to=contact_jid) items = Node('items', attrs={'node': NS_BUNDLES + str(device_id), 'max_items': 1}) pubsub = PubsubNode(items) self.addChild(node=pubsub) class DevicelistQuery(Iq): def __init__(self, contact_jid): id_ = app.get_an_id() attrs = {'id': id_} Iq.__init__(self, typ='get', attrs=attrs, to=contact_jid) items = Node('items', attrs={'node': NS_DEVICE_LIST, 'max_items': 1}) pubsub = PubsubNode(items) self.addChild(node=pubsub) class DevicelistPEP(AbstractPEP): type_ = 'omemo-devicelist' namespace = NS_DEVICE_LIST def _extract_info(self, items): return ({}, []) def make_bundle(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 @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: log.warning( 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' omemo/omemoplugin.py0000644000175500017550000003033213623023766014642 0ustar debacledebacle# -*- coding: utf-8 -*- ''' Copyright 2015 Bahtiar `kalkin-` Gadimov Copyright 2015 Daniel Gultsch Copyright 2016 Philipp Hörist 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 . ''' import logging import binascii import threading from enum import IntEnum, unique from pathlib import Path from gi.repository import GLib from gi.repository import Gtk from gi.repository import Gdk from gajim import dialogs from gajim.common import app, ged from gajim.common.pep import SUPPORTED_PERSONAL_USER_EVENTS from gajim.plugins import GajimPlugin from gajim.plugins.plugins_i18n import _ from gajim.groupchat_control import GroupchatControl from omemo.xmpp import DevicelistPEP from omemo.gtk.key import KeyDialog from omemo.gtk.config import OMEMOConfigDialog CRYPTOGRAPHY_MISSING = 'You are missing Python-Cryptography' AXOLOTL_MISSING = 'You are missing Python-Axolotl or use an outdated version' PROTOBUF_MISSING = 'OMEMO cant import Google Protobuf, you can find help in ' \ 'the GitHub Wiki' ERROR_MSG = '' log = logging.getLogger('gajim.plugin_system.omemo') try: from omemo import file_crypto except Exception as error: log.exception(error) ERROR_MSG = CRYPTOGRAPHY_MISSING try: import google.protobuf except Exception as error: log.error(error) ERROR_MSG = PROTOBUF_MISSING try: import axolotl except Exception as error: log.error(error) ERROR_MSG = AXOLOTL_MISSING if not ERROR_MSG: try: from omemo.omemo_connection import OMEMOConnection except Exception as error: log.error(error) ERROR_MSG = 'Error: %s' % error # pylint: disable=no-init # pylint: disable=attribute-defined-outside-init @unique class UserMessages(IntEnum): QUERY_DEVICES = 0 NO_FINGERPRINTS = 1 class OmemoPlugin(GajimPlugin): def init(self): """ Init """ if ERROR_MSG: self.activatable = False self.available_text = ERROR_MSG self.config_dialog = None return self.encryption_name = 'OMEMO' self.allow_groupchat = True self.events_handlers = { 'signed-in': (ged.PRECORE, self.signed_in), } self.config_dialog = OMEMOConfigDialog(self) self.gui_extension_points = { 'hyperlink_handler': (self._file_decryption, None), 'encrypt' + self.encryption_name: (self._encrypt_message, None), 'gc_encrypt' + self.encryption_name: ( self._gc_encrypt_message, None), 'decrypt': (self._message_received, None), 'send_message' + self.encryption_name: ( self.before_sendmessage, None), 'encryption_dialog' + self.encryption_name: ( self.on_encryption_button_clicked, None), 'encryption_state' + self.encryption_name: ( self.encryption_state, None), 'update_caps': (self._update_caps, None)} SUPPORTED_PERSONAL_USER_EVENTS.append(DevicelistPEP) self.disabled_accounts = [] self.windowinstances = {} self.connections = {} self.config_default_values = {'DISABLED_ACCOUNTS': ([], ''), } for account in self.config['DISABLED_ACCOUNTS']: self.disabled_accounts.append(account) # add aesgcm:// uri scheme to config schemes = app.config.get('uri_schemes') if 'aesgcm://' not in schemes.split(): schemes += ' aesgcm://' app.config.set('uri_schemes', schemes) self._load_css() def _load_css(self): path = Path(__file__).parent / 'gtk' / 'style.css' try: with path.open("r") as file: css = file.read() except Exception as exc: log.error('Error loading css: %s', exc) return try: provider = Gtk.CssProvider() provider.load_from_data(bytes(css.encode('utf-8'))) Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider, 610) except Exception: log.exception('Error loading application css') def signed_in(self, event): """ Method called on SignIn Parameters ---------- event : SignedInEvent """ account = event.conn.name if account == 'Local': return if account in self.disabled_accounts: return if account not in self.connections: self.connections[account] = OMEMOConnection(account, self) self.connections[account].signed_in(event) def activate(self): """ Method called when the Plugin is activated in the PluginManager """ for account in app.connections: if account == 'Local': continue if account in self.disabled_accounts: continue self.connections[account] = OMEMOConnection(account, self) self.connections[account].activate() def deactivate(self): """ Method called when the Plugin is deactivated in the PluginManager """ for account in self.connections: if account == 'Local': continue self.connections[account].deactivate() def _update_caps(self, account): if account == 'Local': return if account not in self.connections: self.connections[account] = OMEMOConnection(account, self) self.connections[account].update_caps(account) def activate_encryption(self, chat_control): if isinstance(chat_control, GroupchatControl): omemo_con = self.connections[chat_control.account] if chat_control.room_jid not in omemo_con.groupchat: dialogs.ErrorDialog( _('Bad Configuration'), _('To use OMEMO in a Groupchat, the Groupchat should be' ' non-anonymous and members-only.')) return False return True def _message_received(self, conn, obj, callback): if conn.name == 'Local': return self.connections[conn.name].message_received(conn, obj, callback) def _gc_encrypt_message(self, conn, obj, callback): if conn.name == 'Local': return self.connections[conn.name].gc_encrypt_message(conn, obj, callback) def _encrypt_message(self, conn, obj, callback): if conn.name == 'Local': return self.connections[conn.name].encrypt_message(conn, obj, callback) def _file_decryption(self, url, kind, instance, window): file_crypto.FileDecryption(self).hyperlink_handler( url, kind, instance, window) def encrypt_file(self, file, account, callback): thread = threading.Thread(target=self._encrypt_file_thread, args=(file, callback)) thread.daemon = True thread.start() @staticmethod def _encrypt_file_thread(file, callback, *args, **kwargs): encrypted_data, key, iv = file_crypto.encrypt_file( file.get_data(full=True)) file.encrypted = True file.size = len(encrypted_data) file.user_data = binascii.hexlify(iv + key).decode('utf-8') file.data = encrypted_data if file.event.isSet(): return GLib.idle_add(callback, file) @staticmethod def encryption_state(chat_control, state): state['visible'] = True state['authenticated'] = True def on_encryption_button_clicked(self, chat_control): self.show_fingerprint_window(chat_control) def get_omemo(self, account): return self.connections[account].omemo def before_sendmessage(self, chat_control): account = chat_control.account if account == 'Local': return contact = chat_control.contact con = self.connections[account] self.new_fingerprints_available(chat_control) if isinstance(chat_control, GroupchatControl): room = chat_control.room_jid missing = True for nick in con.groupchat[room]: real_jid = con.groupchat[room][nick] if not con.are_keys_missing(real_jid): missing = False if missing: log.info('%s => No Trusted Fingerprints for %s', account, room) self.print_message(chat_control, UserMessages.NO_FINGERPRINTS) else: # check if we have devices for the contact if not self.get_omemo(account).device_list_for(contact.jid): con.query_devicelist(contact.jid, True) self.print_message(chat_control, UserMessages.QUERY_DEVICES) chat_control.sendmessage = False return # check if bundles are missing for some devices if con.are_keys_missing(contact.jid): log.info('%s => No Trusted Fingerprints for %s', account, contact.jid) self.print_message(chat_control, UserMessages.NO_FINGERPRINTS) chat_control.sendmessage = False else: log.debug('%s => Sending Message to %s', account, contact.jid) def new_fingerprints_available(self, chat_control): jid = chat_control.contact.jid account = chat_control.account con = self.connections[account] omemo = self.get_omemo(account) if isinstance(chat_control, GroupchatControl): room_jid = chat_control.room_jid if room_jid in con.groupchat: for nick in con.groupchat[room_jid]: real_jid = con.groupchat[room_jid][nick] fingerprints = omemo.store. \ getNewFingerprints(real_jid) if fingerprints: self.show_fingerprint_window( chat_control, fingerprints) elif not isinstance(chat_control, GroupchatControl): fingerprints = omemo.store.getNewFingerprints(jid) if fingerprints: self.show_fingerprint_window( chat_control, fingerprints) def show_fingerprint_window(self, chat_control, fingerprints=None): contact = chat_control.contact account = chat_control.account omemo = self.get_omemo(account) transient = chat_control.parent_win.window if 'dialog' not in self.windowinstances: is_groupchat = isinstance(chat_control, GroupchatControl) self.windowinstances['dialog'] = \ KeyDialog(self, contact, transient, self.windowinstances, groupchat=is_groupchat) if fingerprints: log.debug('%s => Showing Fingerprint Prompt for %s', account, contact.jid) omemo.store.setShownFingerprints(fingerprints) else: self.windowinstances['dialog'].present() self.windowinstances['dialog'].update() if fingerprints: omemo.store.setShownFingerprints(fingerprints) @staticmethod def print_message(chat_control, kind): msg = None if kind == UserMessages.QUERY_DEVICES: msg = _('No devices found. Query in progress...') elif kind == UserMessages.NO_FINGERPRINTS: msg = _('To send an encrypted message, you have to ' 'first trust the fingerprint of your contact!') if msg is None: return chat_control.print_conversation_line(msg, 'status', '', None) omemo/file_crypto.py0000644000175500017550000002157013623023766014632 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2017 Philipp Hörist # # 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 . # import os import hashlib import logging import socket import threading import platform import subprocess import binascii import ssl from urllib.request import urlopen from urllib.error import URLError from urllib.parse import urlparse, urldefrag from io import BufferedWriter, FileIO, BytesIO from gi.repository import GLib from gajim.common import app from gajim.common import configpaths from gajim.plugins.plugins_i18n import _ from gajim.gtk.dialogs import ErrorDialog, YesNoDialog from omemo.gtk.progress import ProgressWindow if os.name == 'nt': import certifi log = logging.getLogger('gajim.plugin_system.omemo.filedecryption') ERROR = False try: from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers.modes import GCM from cryptography.hazmat.backends import default_backend from omemo.omemo.aes_gcm_native import aes_encrypt except ImportError: log.exception('ImportError') ERROR = True DIRECTORY = os.path.join(configpaths.get('MY_DATA'), 'downloads') try: if not os.path.exists(DIRECTORY): os.makedirs(DIRECTORY) except Exception: ERROR = True log.exception('Error') def encrypt_file(data): key = os.urandom(32) iv = os.urandom(12) payload, tag = aes_encrypt(key, iv, data) encrypted_data = payload + tag return (encrypted_data, key, iv) class File: def __init__(self, url, account): self.account = account self.url, self.fragment = urldefrag(url) self.key = None self.iv = None self.filepath = None self.filename = None class FileDecryption: def __init__(self, plugin): self.plugin = plugin self.window = None def hyperlink_handler(self, url, kind, instance, window): if ERROR or kind != 'url': return self.window = window urlparts = urlparse(url) file = File(urlparts.geturl(), instance.account) if urlparts.scheme not in ['https', 'aesgcm'] or not urlparts.netloc: log.info("Not accepting URL for decryption: %s", url) return if urlparts.scheme == 'aesgcm': log.debug('aesgcm scheme detected') file.url = 'https://' + file.url[9:] if not self.is_encrypted(file): log.info('Url not encrypted: %s', url) return self.create_paths(file) if os.path.exists(file.filepath): instance.plugin_modified = True self.finished(file) return event = threading.Event() progressbar = ProgressWindow(self.plugin, self.window, event) thread = threading.Thread(target=Download, args=(file, progressbar, self.window, event, self)) thread.daemon = True thread.start() instance.plugin_modified = True def is_encrypted(self, file): if file.fragment: try: fragment = binascii.unhexlify(file.fragment) file.key = fragment[16:] file.iv = fragment[:16] if len(file.key) == 32 and len(file.iv) == 16: return True file.key = fragment[12:] file.iv = fragment[:12] if len(file.key) == 32 and len(file.iv) == 12: return True except: return False return False def create_paths(self, file): file.filename = os.path.basename(file.url) ext = os.path.splitext(file.filename)[1] name = os.path.splitext(file.filename)[0] urlhash = hashlib.sha1(file.url.encode('utf-8')).hexdigest() newfilename = name + '_' + urlhash[:10] + ext file.filepath = os.path.join(DIRECTORY, newfilename) def finished(self, file): question = _('Do you want to open %s') % file.filename YesNoDialog(_('Open File'), question, transient_for=self.window, on_response_yes=(self.open_file, file.filepath)) return False def open_file(self, checked, path): if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.Popen(["open", path]) else: subprocess.Popen(["xdg-open", path]) class Download: def __init__(self, file, progressbar, window, event, base): self.file = file self.progressbar = progressbar self.window = window self.event = event self.base = base self.download() def download(self): GLib.idle_add(self.progressbar.set_text, _('Downloading...')) data = self.load_url() if isinstance(data, str): GLib.idle_add(self.progressbar.close_dialog) GLib.idle_add(self.error, data) return GLib.idle_add(self.progressbar.set_text, _('Decrypting...')) decrypted_data = self.aes_decrypt(data) GLib.idle_add( self.progressbar.set_text, _('Writing file to harddisk...')) self.write_file(decrypted_data) GLib.idle_add(self.progressbar.close_dialog) GLib.idle_add(self.base.finished, self.file) def load_url(self): try: stream = BytesIO() if not app.config.get_per('accounts', self.file.account, 'httpupload_verify'): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE log.warning('CERT Verification disabled') get_request = urlopen(self.file.url, timeout=30, context=context) else: if os.name == 'nt': get_request = urlopen( self.file.url, cafile=certifi.where(), timeout=30) else: get_request = urlopen(self.file.url, timeout=30) size = get_request.info()['Content-Length'] if not size: errormsg = 'Content-Length not found in header' log.error(errormsg) return errormsg while True: try: if self.event.isSet(): raise DownloadAbortedException temp = get_request.read(10000) GLib.idle_add( self.progressbar.update_progress, len(temp), size) except socket.timeout: errormsg = 'Request timeout' log.error(errormsg) return errormsg if temp: stream.write(temp) else: return stream except DownloadAbortedException as error: log.info('Download Aborted') errormsg = error except URLError as error: log.exception('URLError') errormsg = error.reason except Exception as error: log.exception('Error') errormsg = error stream.close() return str(errormsg) def aes_decrypt(self, payload): # Use AES128 GCM with the given key and iv to decrypt the payload. payload = payload.getvalue() data = payload[:-16] tag = payload[-16:] decryptor = Cipher( algorithms.AES(self.file.key), GCM(self.file.iv, tag=tag), backend=default_backend()).decryptor() return decryptor.update(data) + decryptor.finalize() def write_file(self, data): log.info('Writing data to %s', self.file.filepath) try: with BufferedWriter(FileIO(self.file.filepath, "wb")) as output: output.write(data) output.close() except Exception: log.exception('Failed to write file') def error(self, error): ErrorDialog(_('Error'), error, transient_for=self.window) return False class DownloadAbortedException(Exception): def __str__(self): return _('Download Aborted') omemo/omemo.png0000644000175500017550000000470413623023766013563 0ustar debacledebaclePNG  IHDR00W IDATxXx&hm۶m6m۶m;k{خׯ*Tt0 0a0: CO,Lɬx7دX< lfƏB,)",'̥ѧt(lUK7tF|nۀVV&6VoƍJj]+0b^wc;R'3J-%54ʕ+ީ ߈@O0d6 ]>݋}zm,R||&"O2&|%N/]AZ e{(oܬEy{{;yr/Ω38۾bb .Ჰk۸aLW/KaOB4йizrߦeq Cy>?C< u'k9^ \JnӋϟ>fbDFμ0̑W5dL,Nq@P1f.ܽv.BxŰ(hPO˹G#aSOQxbJ5.̄5S`'c%QFR5iΌUyTEz[V7p2'N=d>4<;@q%KqjSpB"d͖=Slzl˹^[VGpL8YlT~ MZNl Nh ϝ?}R#CLy>~wu*Z{C:=1YqȀ YҥK4hPNT5GZ(T!` \'#R>'/RK=o;"فƸVΥ%On/Cx $Y2> 𕓉Mspwp@j۶oxȑW\ٶm{M|"FAo VͭD -BM | 逴;O_9eⷧuP#%yt>/ΝJ/Vz{.ƔbQ sne\7xb,qȤܲxcd6Ww=5g2Deސ Ô Hc~ ϛV&suۣ:2F(* ݜ *6c1[ [ҽGίC뻨7Iߥj_st6€1@ >_NcK={b{ .6|Y`uyp‰|lvYdOOpd0 '{]:Fɸϝ@^mX>??8FGj!V+GOAU0cDo H3p Ep{$7f:]>zG </]} eSs˶ehh(]R4*4AvR7JÝ=AiĴBx$iwp|_x}^Mn߰B Z~Tew{i*Y=kkkq͛9{΅.uFQ!jI)'#*sCl_\ٹkFi˦,\<3`6p4ֹi(S/7;x?Ԑ]00ƵD\3*'5E䤾'Qv ؛7u(3v3Ke >(w[«'vqטRYLEtҋfOߔ<|`CB8ݲGQB,5:ǽ0"I p=M(L󚺼% vvnM$ ;S I-WC'OR;]Qx`j- ?[E p|cH\6o-Z 4åvuJhبIK!PNosuT;nPiWL) as9Za+nO*Sli-L@'g|4cVHң?5x"na VN.:k GHf.-H9ZG-!dPB>u$a%)]!MY]22^J+;X5vJ}Wx?b˒55( # # 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 . # from axolotl.invalidkeyidexception import InvalidKeyIdException from axolotl.state.signedprekeyrecord import SignedPreKeyRecord from axolotl.state.signedprekeystore import SignedPreKeyStore from axolotl.util.medium import Medium class LiteSignedPreKeyStore(SignedPreKeyStore): def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn def loadSignedPreKey(self, signedPreKeyId): q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (signedPreKeyId, )) result = cursor.fetchone() if not result: raise InvalidKeyIdException("No such signedprekeyrecord! %s " % signedPreKeyId) return SignedPreKeyRecord(serialized=result[0]) def loadSignedPreKeys(self): q = "SELECT record FROM signed_prekeys" cursor = self.dbConn.cursor() cursor.execute(q, ) result = cursor.fetchall() results = [] for row in result: results.append(SignedPreKeyRecord(serialized=row[0])) return results def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord): q = "INSERT INTO signed_prekeys (prekey_id, record) VALUES(?,?)" cursor = self.dbConn.cursor() cursor.execute(q, (signedPreKeyId, signedPreKeyRecord.serialize())) self.dbConn.commit() def containsSignedPreKey(self, signedPreKeyId): q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (signedPreKeyId, )) return cursor.fetchone() is not None def removeSignedPreKey(self, signedPreKeyId): q = "DELETE FROM signed_prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (signedPreKeyId, )) self.dbConn.commit() def getNextSignedPreKeyId(self): result = self.getCurrentSignedPreKeyId() if not result: return 1 # StartId if no SignedPreKeys exist else: return (result % (Medium.MAX_VALUE - 1)) + 1 def getCurrentSignedPreKeyId(self): q = "SELECT MAX(prekey_id) FROM signed_prekeys" cursor = self.dbConn.cursor() cursor.execute(q) result = cursor.fetchone() if not result: return None else: return result[0] def getSignedPreKeyTimestamp(self, signedPreKeyId): q = "SELECT strftime('%s', timestamp) FROM " \ "signed_prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (signedPreKeyId, )) result = cursor.fetchone() if not result: raise InvalidKeyIdException("No such signedprekeyrecord! %s " % signedPreKeyId) return result[0] def removeOldSignedPreKeys(self, timestamp): q = "DELETE FROM signed_prekeys " \ "WHERE timestamp < datetime(?, 'unixepoch')" cursor = self.dbConn.cursor() cursor.execute(q, (timestamp, )) self.dbConn.commit() omemo/omemo/liteprekeystore.py0000644000175500017550000000566513623023766016670 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Tarek Galal # # 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 . # from axolotl.state.prekeyrecord import PreKeyRecord from axolotl.state.prekeystore import PreKeyStore from axolotl.util.keyhelper import KeyHelper class LitePreKeyStore(PreKeyStore): def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn def loadPreKey(self, preKeyId): q = "SELECT record FROM prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (preKeyId, )) result = cursor.fetchone() if not result: raise Exception("No such prekeyRecord!") return PreKeyRecord(serialized=result[0]) def loadPendingPreKeys(self): q = "SELECT record FROM prekeys" cursor = self.dbConn.cursor() cursor.execute(q) result = cursor.fetchall() return [PreKeyRecord(serialized=r[0]) for r in result] def storePreKey(self, preKeyId, preKeyRecord): q = "INSERT INTO prekeys (prekey_id, record) VALUES(?,?)" cursor = self.dbConn.cursor() cursor.execute(q, (preKeyId, preKeyRecord.serialize())) self.dbConn.commit() def containsPreKey(self, preKeyId): q = "SELECT record FROM prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (preKeyId, )) return cursor.fetchone() is not None def removePreKey(self, preKeyId): q = "DELETE FROM prekeys WHERE prekey_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (preKeyId, )) self.dbConn.commit() def getCurrentPreKeyId(self): q = "SELECT MAX(prekey_id) FROM prekeys" cursor = self.dbConn.cursor() cursor.execute(q) return cursor.fetchone()[0] def getPreKeyCount(self): q = "SELECT COUNT(prekey_id) FROM prekeys" cursor = self.dbConn.cursor() cursor.execute(q) return cursor.fetchone()[0] def generateNewPreKeys(self, count): prekey_id = self.getCurrentPreKeyId() if prekey_id is None: prekey_id = 0 preKeys = KeyHelper.generatePreKeys(prekey_id + 1, count) for preKey in preKeys: self.storePreKey(preKey.getId(), preKey) omemo/omemo/sql.py0000644000175500017550000001377613623023766014237 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Tarek Galal # # 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 . # from .db_helpers import user_version class SQLDatabase(): """ SQL Database """ def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn self.createDb() self.migrateDb() c = self.dbConn.cursor() c.execute("PRAGMA synchronous=NORMAL;") c.execute("PRAGMA journal_mode;") mode = c.fetchone()[0] # WAL is a persistent DB mode, dont override it if user has set it if mode != 'wal': c.execute("PRAGMA journal_mode=MEMORY;") self.dbConn.commit() def createDb(self): if user_version(self.dbConn) == 0: # Creates # IdentityKeyStore # PreKeyStore # SignedPreKeyStore # SessionStore # EncryptionStore create_tables = ''' CREATE TABLE IF NOT EXISTS identities ( _id INTEGER PRIMARY KEY AUTOINCREMENT, recipient_id TEXT, registration_id INTEGER, public_key BLOB, private_key BLOB, next_prekey_id INTEGER, timestamp INTEGER, trust INTEGER, shown INTEGER DEFAULT 0); CREATE UNIQUE INDEX IF NOT EXISTS public_key_index ON identities (public_key, recipient_id); CREATE TABLE IF NOT EXISTS prekeys( _id INTEGER PRIMARY KEY AUTOINCREMENT, prekey_id INTEGER UNIQUE, sent_to_server BOOLEAN, record BLOB); CREATE TABLE IF NOT EXISTS signed_prekeys ( _id INTEGER PRIMARY KEY AUTOINCREMENT, prekey_id INTEGER UNIQUE, timestamp NUMERIC DEFAULT CURRENT_TIMESTAMP, record BLOB); CREATE TABLE IF NOT EXISTS sessions ( _id INTEGER PRIMARY KEY AUTOINCREMENT, recipient_id TEXT, device_id INTEGER, record BLOB, timestamp INTEGER, active INTEGER DEFAULT 1, UNIQUE(recipient_id, device_id)); CREATE TABLE IF NOT EXISTS encryption_state ( id INTEGER PRIMARY KEY AUTOINCREMENT, jid TEXT UNIQUE, encryption INTEGER ); ''' create_db_sql = """ BEGIN TRANSACTION; %s PRAGMA user_version=5; END TRANSACTION; """ % (create_tables) self.dbConn.executescript(create_db_sql) def migrateDb(self): """ Migrates the DB """ # Find all double entrys and delete them if user_version(self.dbConn) < 2: delete_dupes = """ DELETE FROM identities WHERE _id not in ( SELECT MIN(_id) FROM identities GROUP BY recipient_id, public_key ); """ self.dbConn.executescript(""" BEGIN TRANSACTION; %s PRAGMA user_version=2; END TRANSACTION; """ % (delete_dupes)) if user_version(self.dbConn) < 3: # Create a UNIQUE INDEX so every public key/recipient_id tuple # can only be once in the db add_index = """ CREATE UNIQUE INDEX IF NOT EXISTS public_key_index ON identities (public_key, recipient_id); """ self.dbConn.executescript(""" BEGIN TRANSACTION; %s PRAGMA user_version=3; END TRANSACTION; """ % (add_index)) if user_version(self.dbConn) < 4: # Adds column "active" to the sessions table add_active = """ ALTER TABLE sessions ADD COLUMN active INTEGER DEFAULT 1; """ self.dbConn.executescript(""" BEGIN TRANSACTION; %s PRAGMA user_version=4; END TRANSACTION; """ % (add_active)) if user_version(self.dbConn) < 5: # Adds DEFAULT Timestamp add_timestamp = """ DROP TABLE signed_prekeys; CREATE TABLE IF NOT EXISTS signed_prekeys ( _id INTEGER PRIMARY KEY AUTOINCREMENT, prekey_id INTEGER UNIQUE, timestamp NUMERIC DEFAULT CURRENT_TIMESTAMP, record BLOB); ALTER TABLE identities ADD COLUMN shown INTEGER DEFAULT 0; UPDATE identities SET shown = 1; """ self.dbConn.executescript(""" BEGIN TRANSACTION; %s PRAGMA user_version=5; END TRANSACTION; """ % (add_timestamp)) omemo/omemo/aes_gcm.py0000644000175500017550000000223313623023766015020 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Bahtiar `kalkin-` Gadimov # # This file is part of python-omemo library. # # The python-omemo library 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. # # python-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 python-omemo library. If not, see . # import sys import logging from .aes_gcm_native import aes_decrypt from .aes_gcm_native import aes_encrypt log = logging.getLogger('gajim.plugin_system.omemo') def encrypt(key, iv, plaintext): return aes_encrypt(key, iv, plaintext) def decrypt(key, iv, ciphertext): return aes_decrypt(key, iv, ciphertext).decode('utf-8') class NoValidSessions(Exception): pass omemo/omemo/state.py0000644000175500017550000004574013623023766014554 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Bahtiar `kalkin-` Gadimov # # 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 . # import logging import time import os from base64 import b64encode from axolotl.ecc.djbec import DjbECPublicKey from axolotl.identitykey import IdentityKey from axolotl.duplicatemessagexception import DuplicateMessageException from axolotl.invalidmessageexception import InvalidMessageException from axolotl.invalidversionexception import InvalidVersionException from axolotl.untrustedidentityexception import UntrustedIdentityException from axolotl.nosessionexception import NoSessionException from axolotl.protocol.prekeywhispermessage import PreKeyWhisperMessage from axolotl.protocol.whispermessage import WhisperMessage from axolotl.sessionbuilder import SessionBuilder from axolotl.sessioncipher import SessionCipher from axolotl.state.prekeybundle import PreKeyBundle from axolotl.util.keyhelper import KeyHelper from .aes_gcm import NoValidSessions, decrypt, encrypt from .liteaxolotlstore import (LiteAxolotlStore, DEFAULT_PREKEY_AMOUNT, MIN_PREKEY_AMOUNT, SPK_CYCLE_TIME, SPK_ARCHIVE_TIME) log = logging.getLogger('gajim.plugin_system.omemo') logAxolotl = logging.getLogger('axolotl') UNTRUSTED = 0 TRUSTED = 1 UNDECIDED = 2 class OmemoState: def __init__(self, own_jid, db_con, account, xmpp_con): """ Instantiates an OmemoState object. :param connection: an :py:class:`sqlite3.Connection` """ self.account = account self.xmpp_con = xmpp_con self.session_ciphers = {} self.own_jid = own_jid self.device_ids = {} self.own_devices = [] self.store = LiteAxolotlStore(db_con) self.encryption = self.store.encryptionStore for jid, device_id in self.store.getActiveDeviceTuples(): if jid != own_jid: self.add_device(jid, device_id) else: self.add_own_device(device_id) log.info(self.account + ' => Roster devices after boot:' + str(self.device_ids)) log.info(self.account + ' => Own devices after boot:' + str(self.own_devices)) log.debug(self.account + ' => ' + str(self.store.preKeyStore.getPreKeyCount()) + ' PreKeys available') 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) def set_devices(self, name, devices): """ Return a an. Parameters ---------- jid : string The contacts jid devices: [int] A list of devices """ self.device_ids[name] = devices log.info(self.account + ' => Saved devices for ' + name) def add_device(self, name, device_id): if name not in self.device_ids: self.device_ids[name] = [device_id] elif device_id not in self.device_ids[name]: self.device_ids[name].append(device_id) def set_own_devices(self, devices): """ Overwrite the current :py:attribute:`OmemoState.own_devices` with the given devices. Parameters ---------- devices : [int] A list of device_ids """ self.own_devices = devices log.info(self.account + ' => Saved own devices') def add_own_device(self, device_id): if device_id not in self.own_devices: self.own_devices.append(device_id) @property def own_device_id(self): reg_id = self.store.getLocalRegistrationId() assert reg_id is not None, \ "Requested device_id but there is no generated" return ((reg_id % 2147483646) + 1) def own_device_id_published(self): """ Return `True` only if own device id was added via :py:method:`OmemoState.set_own_devices()`. """ return self.own_device_id in self.own_devices @property def bundle(self): self.checkPreKeyAmount() prekeys = [ (k.getId(), b64encode(k.getKeyPair().getPublicKey().serialize())) for k in self.store.loadPreKeys() ] identityKeyPair = self.store.getIdentityKeyPair() self.cycleSignedPreKey(identityKeyPair) signedPreKey = self.store.loadSignedPreKey( self.store.getCurrentSignedPreKeyId()) result = { 'signedPreKeyId': signedPreKey.getId(), 'signedPreKeyPublic': b64encode(signedPreKey.getKeyPair().getPublicKey().serialize()), 'signedPreKeySignature': b64encode(signedPreKey.getSignature()), 'identityKey': b64encode(identityKeyPair.getPublicKey().serialize()), 'prekeys': prekeys } return result def decrypt_msg(self, msg_dict): own_id = self.own_device_id if msg_dict['sid'] == own_id: log.info('Received previously sent message by us') return if own_id not in msg_dict['keys']: log.warning('OMEMO message does not contain our device key') return iv = msg_dict['iv'] sid = msg_dict['sid'] sender_jid = msg_dict['sender_jid'] payload = msg_dict['payload'] encrypted_key = msg_dict['keys'][own_id] try: key = self.handlePreKeyWhisperMessage(sender_jid, sid, encrypted_key) except (InvalidVersionException, InvalidMessageException): try: key = self.handleWhisperMessage(sender_jid, sid, encrypted_key) except (NoSessionException, InvalidMessageException) as e: log.warning(e) log.warning('sender_jid => ' + str(sender_jid) + ' sid =>' + str(sid)) return except (DuplicateMessageException) as e: log.warning('Duplicate message found ' + str(e.args)) return except (DuplicateMessageException) as e: log.warning('Duplicate message found ' + str(e.args)) return if payload is None: result = None log.debug("Decrypted Key Exchange Message") else: result = decrypt(key, iv, payload) log.debug("Decrypted Message => " + result) return result def create_msg(self, from_jid, jid, plaintext): key = os.urandom(16) iv = os.urandom(12) encrypted_keys = {} devices_list = self.device_list_for(jid) if len(devices_list) == 0: log.error('No known devices') return payload, tag = encrypt(key, iv, plaintext) key += tag # Encrypt the message key with for each of receivers devices for device in devices_list: try: if self.isTrusted(jid, device) == TRUSTED: cipher = self.get_session_cipher(jid, device) cipher_key = cipher.encrypt(key) prekey = isinstance(cipher_key, PreKeyWhisperMessage) encrypted_keys[device] = (cipher_key.serialize(), prekey) else: log.debug('Skipped Device because Trust is: ' + str(self.isTrusted(jid, device))) except: log.warning('Failed to find key for device ' + str(device)) if len(encrypted_keys) == 0: log.error('Encrypted keys empty') raise NoValidSessions('Encrypted keys empty') my_other_devices = set(self.own_devices) - set({self.own_device_id}) # Encrypt the message key with for each of our own devices for device in my_other_devices: try: if self.isTrusted(from_jid, device) == TRUSTED: cipher = self.get_session_cipher(from_jid, device) cipher_key = cipher.encrypt(key) prekey = isinstance(cipher_key, PreKeyWhisperMessage) encrypted_keys[device] = (cipher_key.serialize(), prekey) else: log.debug('Skipped own Device because Trust is: ' + str(self.isTrusted(from_jid, device))) except: log.warning('Failed to find key for device ' + str(device)) result = {'sid': self.own_device_id, 'keys': encrypted_keys, 'jid': jid, 'iv': iv, 'payload': payload} log.debug('Finished encrypting message') return result def create_gc_msg(self, from_jid, jid, plaintext): key = os.urandom(16) iv = os.urandom(12) encrypted_keys = {} room = jid encrypted_jids = [] devices_list = self.device_list_for(jid, True) payload, tag = encrypt(key, iv, plaintext) key += tag for tup in devices_list: self.get_session_cipher(tup[0], tup[1]) # Encrypt the message key with for each of receivers devices for nick in self.xmpp_con.groupchat[room]: jid_to = self.xmpp_con.groupchat[room][nick] if jid_to == self.own_jid: continue if jid_to in encrypted_jids: # We already encrypted to this JID continue if jid_to not in self.session_ciphers: continue for rid, cipher in self.session_ciphers[jid_to].items(): try: if self.isTrusted(jid_to, rid) == TRUSTED: cipher_key = cipher.encrypt(key) prekey = isinstance(cipher_key, PreKeyWhisperMessage) encrypted_keys[rid] = (cipher_key.serialize(), prekey) else: log.debug('Skipped Device because Trust is: ' + str(self.isTrusted(jid_to, rid))) except: log.exception('ERROR:') log.warning('Failed to find key for device ' + str(rid)) encrypted_jids.append(jid_to) my_other_devices = set(self.own_devices) - set({self.own_device_id}) # Encrypt the message key with for each of our own devices for dev in my_other_devices: try: cipher = self.get_session_cipher(from_jid, dev) if self.isTrusted(from_jid, dev) == TRUSTED: cipher_key = cipher.encrypt(key) prekey = isinstance(cipher_key, PreKeyWhisperMessage) encrypted_keys[dev] = (cipher_key.serialize(), prekey) else: log.debug('Skipped own Device because Trust is: ' + str(self.isTrusted(from_jid, dev))) except: log.exception('ERROR:') log.warning('Failed to find key for device ' + str(dev)) if not encrypted_keys: log.error('Encrypted keys empty') raise NoValidSessions('Encrypted keys empty') result = {'sid': self.own_device_id, 'keys': encrypted_keys, 'jid': jid, 'iv': iv, 'payload': payload} log.debug('Finished encrypting message') return result def device_list_for(self, jid, gc=False): """ Return a list of known device ids for the specified jid. Parameters ---------- jid : string The contacts jid gc : bool Groupchat Message """ if gc: room = jid devicelist = [] for nick in self.xmpp_con.groupchat[room]: jid_to = self.xmpp_con.groupchat[room][nick] if jid_to == self.own_jid: continue try: for device in self.device_ids[jid_to]: devicelist.append((jid_to, device)) except KeyError: log.warning('no device ids found for %s', jid_to) continue return devicelist if jid == self.own_jid: return set(self.own_devices) - set({self.own_device_id}) if jid not in self.device_ids: return set() return set(self.device_ids[jid]) def isTrusted(self, recipient_id, device_id): record = self.store.loadSession(recipient_id, device_id) identity_key = record.getSessionState().getRemoteIdentityKey() return self.store.isTrustedIdentity(recipient_id, identity_key) def getTrustedFingerprints(self, recipient_id): inactive = self.store.getInactiveSessionsKeys(recipient_id) trusted = self.store.getTrustedFingerprints(recipient_id) trusted = set(trusted) - set(inactive) return trusted def getUndecidedFingerprints(self, recipient_id): inactive = self.store.getInactiveSessionsKeys(recipient_id) undecided = self.store.getUndecidedFingerprints(recipient_id) undecided = set(undecided) - set(inactive) return undecided def devices_without_sessions(self, jid): """ List device_ids for the given jid which have no axolotl session. Parameters ---------- jid : string The contacts jid Returns ------- [int] A list of device_ids """ known_devices = self.device_list_for(jid) missing_devices = [dev for dev in known_devices if not self.store.containsSession(jid, dev)] if missing_devices: log.info(self.account + ' => Missing device sessions for ' + jid + ': ' + str(missing_devices)) return missing_devices def get_session_cipher(self, jid, device_id): if jid not in self.session_ciphers: self.session_ciphers[jid] = {} if device_id not in self.session_ciphers[jid]: cipher = SessionCipher(self.store, self.store, self.store, self.store, jid, device_id) self.session_ciphers[jid][device_id] = cipher return self.session_ciphers[jid][device_id] def handlePreKeyWhisperMessage(self, recipient_id, device_id, key): preKeyWhisperMessage = PreKeyWhisperMessage(serialized=key) if not preKeyWhisperMessage.getPreKeyId(): raise Exception("Received PreKeyWhisperMessage without PreKey =>" + recipient_id) sessionCipher = self.get_session_cipher(recipient_id, device_id) try: log.debug(self.account + " => Received PreKeyWhisperMessage from " + recipient_id) key = sessionCipher.decryptPkmsg(preKeyWhisperMessage) # Publish new bundle after PreKey has been used # for building a new Session self.xmpp_con.publish_bundle() self.add_device(recipient_id, device_id) return key except UntrustedIdentityException as e: log.info(self.account + " => Received WhisperMessage " + "from Untrusted Fingerprint! => " + e.getName()) def handleWhisperMessage(self, recipient_id, device_id, key): whisperMessage = WhisperMessage(serialized=key) log.debug(self.account + " => Received WhisperMessage from " + recipient_id) if self.isTrusted(recipient_id, device_id): sessionCipher = self.get_session_cipher(recipient_id, device_id) key = sessionCipher.decryptMsg(whisperMessage, textMsg=False) self.add_device(recipient_id, device_id) return key else: raise Exception("Received WhisperMessage " "from Untrusted Fingerprint! => " + recipient_id) def checkPreKeyAmount(self): # Check if enough PreKeys are available preKeyCount = self.store.preKeyStore.getPreKeyCount() if preKeyCount < MIN_PREKEY_AMOUNT: newKeys = DEFAULT_PREKEY_AMOUNT - preKeyCount self.store.preKeyStore.generateNewPreKeys(newKeys) log.info(self.account + ' => ' + str(newKeys) + ' PreKeys created') def cycleSignedPreKey(self, identityKeyPair): # Publish every SPK_CYCLE_TIME a new SignedPreKey # Delete all exsiting SignedPreKeys that are older # then SPK_ARCHIVE_TIME # Check if SignedPreKey exist and create if not if not self.store.getCurrentSignedPreKeyId(): signedPreKey = KeyHelper.generateSignedPreKey( identityKeyPair, self.store.getNextSignedPreKeyId()) self.store.storeSignedPreKey(signedPreKey.getId(), signedPreKey) log.debug(self.account + ' => New SignedPreKey created, because none existed') # if SPK_CYCLE_TIME is reached, generate a new SignedPreKey now = int(time.time()) timestamp = self.store.getSignedPreKeyTimestamp( self.store.getCurrentSignedPreKeyId()) if int(timestamp) < now - SPK_CYCLE_TIME: signedPreKey = KeyHelper.generateSignedPreKey( identityKeyPair, self.store.getNextSignedPreKeyId()) self.store.storeSignedPreKey(signedPreKey.getId(), signedPreKey) log.debug(self.account + ' => Cycled SignedPreKey') # Delete all SignedPreKeys that are older than SPK_ARCHIVE_TIME timestamp = now - SPK_ARCHIVE_TIME self.store.removeOldSignedPreKeys(timestamp) omemo/omemo/aes_gcm_native.py0000644000175500017550000000464513623023766016377 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Bahtiar `kalkin-` Gadimov # # This file is part of python-omemo library. # # The python-omemo library 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. # # python-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 python-omemo library. If not, see . # import os import logging from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers.modes import GCM # On Windows we have to import a specific backend because the # default_backend() mechanism doesnt work in Gajim for Windows. # Its because of how Gajim is build with cx_freeze if os.name == 'nt': from cryptography.hazmat.backends.openssl import backend else: from cryptography.hazmat.backends import default_backend log = logging.getLogger('gajim.plugin_system.omemo') def aes_decrypt(_key, iv, payload): """ Use AES128 GCM with the given key and iv to decrypt the payload. """ if len(_key) >= 32: # XEP-0384 log.debug('XEP Compliant Key/Tag') data = payload key = _key[:16] tag = _key[16:] else: # Legacy log.debug('Legacy Key/Tag') data = payload[:-16] key = _key tag = payload[-16:] if os.name == 'nt': _backend = backend else: _backend = default_backend() decryptor = Cipher( algorithms.AES(key), GCM(iv, tag=tag), backend=_backend).decryptor() return decryptor.update(data) + decryptor.finalize() def aes_encrypt(key, iv, plaintext): """ Use AES128 GCM with the given key and iv to encrypt the plaintext. """ if os.name == 'nt': _backend = backend else: _backend = default_backend() encryptor = Cipher( algorithms.AES(key), GCM(iv), backend=_backend).encryptor() return encryptor.update(plaintext) + encryptor.finalize(), encryptor.tag omemo/omemo/encryption.py0000644000175500017550000000403113623023766015612 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Bahtiar `kalkin-` Gadimov # Copyright 2015 Daniel Gultsch # # 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 . # class EncryptionState(): """ Used to store if OMEMO is enabled or not between gajim restarts """ def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn def activate(self, jid): q = """INSERT OR REPLACE INTO encryption_state (jid, encryption) VALUES (?, 1) """ c = self.dbConn.cursor() c.execute(q, (jid, )) self.dbConn.commit() def deactivate(self, jid): q = """INSERT OR REPLACE INTO encryption_state (jid, encryption) VALUES (?, 0)""" c = self.dbConn.cursor() c.execute(q, (jid, )) self.dbConn.commit() def is_active(self, jid): q = 'SELECT encryption FROM encryption_state where jid = ?;' c = self.dbConn.cursor() c.execute(q, (jid, )) result = c.fetchone() if result is None: return False return result[0] def exist(self, jid): q = 'SELECT encryption FROM encryption_state where jid = ?;' c = self.dbConn.cursor() c.execute(q, (jid, )) result = c.fetchone() if result is None: return False else: return True omemo/omemo/liteaxolotlstore.py0000644000175500017550000001563613623023766017052 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Tarek Galal # # 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 . # import logging from axolotl.state.axolotlstore import AxolotlStore from axolotl.util.keyhelper import KeyHelper from .liteidentitykeystore import LiteIdentityKeyStore from .liteprekeystore import LitePreKeyStore from .litesessionstore import LiteSessionStore from .litesignedprekeystore import LiteSignedPreKeyStore from .encryption import EncryptionState from .sql import SQLDatabase log = logging.getLogger('gajim.plugin_system.omemo') DEFAULT_PREKEY_AMOUNT = 100 MIN_PREKEY_AMOUNT = 80 SPK_ARCHIVE_TIME = 86400 * 15 # 15 Days SPK_CYCLE_TIME = 86400 # 24 Hours class LiteAxolotlStore(AxolotlStore): def __init__(self, connection): try: connection.text_factory = bytes except(AttributeError): raise AssertionError('Expected a sqlite3.Connection got ' + str(connection)) self.sql = SQLDatabase(connection) self.identityKeyStore = LiteIdentityKeyStore(connection) self.preKeyStore = LitePreKeyStore(connection) self.signedPreKeyStore = LiteSignedPreKeyStore(connection) self.sessionStore = LiteSessionStore(connection) self.encryptionStore = EncryptionState(connection) if not self.getLocalRegistrationId(): log.info("Generating Axolotl keys") self._generate_axolotl_keys() def _generate_axolotl_keys(self): identityKeyPair = KeyHelper.generateIdentityKeyPair() registrationId = KeyHelper.generateRegistrationId() preKeys = KeyHelper.generatePreKeys(KeyHelper.getRandomSequence(4294967296), DEFAULT_PREKEY_AMOUNT) self.storeLocalData(registrationId, identityKeyPair) signedPreKey = KeyHelper.generateSignedPreKey( identityKeyPair, KeyHelper.getRandomSequence(65536)) self.storeSignedPreKey(signedPreKey.getId(), signedPreKey) for preKey in preKeys: self.storePreKey(preKey.getId(), preKey) def getIdentityKeyPair(self): return self.identityKeyStore.getIdentityKeyPair() def storeLocalData(self, registrationId, identityKeyPair): self.identityKeyStore.storeLocalData(registrationId, identityKeyPair) def getLocalRegistrationId(self): return self.identityKeyStore.getLocalRegistrationId() def saveIdentity(self, recepientId, identityKey): self.identityKeyStore.saveIdentity(recepientId, identityKey) def deleteIdentity(self, recipientId, identityKey): self.identityKeyStore.deleteIdentity(recipientId, identityKey) def isTrustedIdentity(self, recepientId, identityKey): return self.identityKeyStore.isTrustedIdentity(recepientId, identityKey) def setTrust(self, identityKey, trust): return self.identityKeyStore.setTrust(identityKey, trust) def getTrustedFingerprints(self, jid): return self.identityKeyStore.getTrustedFingerprints(jid) def getUndecidedFingerprints(self, jid): return self.identityKeyStore.getUndecidedFingerprints(jid) def setShownFingerprints(self, jid): return self.identityKeyStore.setShownFingerprints(jid) def getNewFingerprints(self, jid): return self.identityKeyStore.getNewFingerprints(jid) def loadPreKey(self, preKeyId): return self.preKeyStore.loadPreKey(preKeyId) def loadPreKeys(self): return self.preKeyStore.loadPendingPreKeys() def storePreKey(self, preKeyId, preKeyRecord): self.preKeyStore.storePreKey(preKeyId, preKeyRecord) def containsPreKey(self, preKeyId): return self.preKeyStore.containsPreKey(preKeyId) def removePreKey(self, preKeyId): self.preKeyStore.removePreKey(preKeyId) def loadSession(self, recepientId, deviceId): return self.sessionStore.loadSession(recepientId, deviceId) def getActiveDeviceTuples(self): return self.sessionStore.getActiveDeviceTuples() def getInactiveSessionsKeys(self, recipientId): return self.sessionStore.getInactiveSessionsKeys(recipientId) def getSubDeviceSessions(self, recepientId): # TODO Reuse this return self.sessionStore.getSubDeviceSessions(recepientId) def getJidFromDevice(self, device_id): return self.sessionStore.getJidFromDevice(device_id) def storeSession(self, recepientId, deviceId, sessionRecord): self.sessionStore.storeSession(recepientId, deviceId, sessionRecord) def containsSession(self, recepientId, deviceId): return self.sessionStore.containsSession(recepientId, deviceId) def deleteSession(self, recepientId, deviceId): self.sessionStore.deleteSession(recepientId, deviceId) def deleteAllSessions(self, recepientId): self.sessionStore.deleteAllSessions(recepientId) def getSessionsFromJid(self, recipientId): return self.sessionStore.getSessionsFromJid(recipientId) def getSessionsFromJids(self, recipientId): return self.sessionStore.getSessionsFromJids(recipientId) def getAllSessions(self): return self.sessionStore.getAllSessions() def loadSignedPreKey(self, signedPreKeyId): return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId) def loadSignedPreKeys(self): return self.signedPreKeyStore.loadSignedPreKeys() def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord): self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId, signedPreKeyRecord) def containsSignedPreKey(self, signedPreKeyId): return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId) def removeSignedPreKey(self, signedPreKeyId): self.signedPreKeyStore.removeSignedPreKey(signedPreKeyId) def getNextSignedPreKeyId(self): return self.signedPreKeyStore.getNextSignedPreKeyId() def getCurrentSignedPreKeyId(self): return self.signedPreKeyStore.getCurrentSignedPreKeyId() def getSignedPreKeyTimestamp(self, signedPreKeyId): return self.signedPreKeyStore.getSignedPreKeyTimestamp(signedPreKeyId) def removeOldSignedPreKeys(self, timestamp): self.signedPreKeyStore.removeOldSignedPreKeys(timestamp) omemo/omemo/__init__.py0000644000175500017550000000002613623023766015157 0ustar debacledebacle__version__ = "0.1.0" omemo/omemo/db_helpers.py0000644000175500017550000000065013623023766015532 0ustar debacledebacle''' Database helper functions ''' def table_exists(db, name): """ Check if the specified table exists in the db. """ query = """ SELECT name FROM sqlite_master WHERE type='table' AND name=?; """ return db.execute(query, (name, )).fetchone() is not None def user_version(db): """ Return the value of PRAGMA user_version. """ return db.execute('PRAGMA user_version').fetchone()[0] omemo/omemo/liteidentitykeystore.py0000644000175500017550000001352113623023766017721 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Tarek Galal # # 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 . # from axolotl.ecc.djbec import DjbECPrivateKey, DjbECPublicKey from axolotl.identitykey import IdentityKey from axolotl.identitykeypair import IdentityKeyPair from axolotl.state.identitykeystore import IdentityKeyStore UNDECIDED = 2 TRUSTED = 1 UNTRUSTED = 0 class LiteIdentityKeyStore(IdentityKeyStore): def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn def getIdentityKeyPair(self): q = "SELECT public_key, private_key FROM identities " + \ "WHERE recipient_id = -1" c = self.dbConn.cursor() c.execute(q) result = c.fetchone() publicKey, privateKey = result return IdentityKeyPair( IdentityKey(DjbECPublicKey(publicKey[1:])), DjbECPrivateKey(privateKey)) def getLocalRegistrationId(self): q = "SELECT registration_id FROM identities WHERE recipient_id = -1" c = self.dbConn.cursor() c.execute(q) result = c.fetchone() return result[0] if result else None def storeLocalData(self, registrationId, identityKeyPair): q = "INSERT INTO identities( " + \ "recipient_id, registration_id, public_key, private_key) " + \ "VALUES(-1, ?, ?, ?)" c = self.dbConn.cursor() c.execute(q, (registrationId, identityKeyPair.getPublicKey().getPublicKey().serialize(), identityKeyPair.getPrivateKey().serialize())) self.dbConn.commit() def saveIdentity(self, recipientId, identityKey): q = "INSERT INTO identities (recipient_id, public_key, trust) " \ "VALUES(?, ?, ?)" c = self.dbConn.cursor() if not self.getIdentity(recipientId, identityKey): c.execute(q, (recipientId, identityKey.getPublicKey().serialize(), UNDECIDED)) self.dbConn.commit() def getIdentity(self, recipientId, identityKey): q = "SELECT * FROM identities WHERE recipient_id = ? " \ "AND public_key = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, identityKey.getPublicKey().serialize())) result = c.fetchone() return result is not None def deleteIdentity(self, recipientId, identityKey): q = "DELETE FROM identities WHERE recipient_id = ? AND public_key = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, identityKey.getPublicKey().serialize())) self.dbConn.commit() def isTrustedIdentity(self, recipientId, identityKey): q = "SELECT trust FROM identities WHERE recipient_id = ? " \ "AND public_key = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, identityKey.getPublicKey().serialize())) result = c.fetchone() states = [UNTRUSTED, TRUSTED, UNDECIDED] if result and result[0] in states: return result[0] else: return True def getAllFingerprints(self): q = "SELECT _id, recipient_id, public_key, trust FROM identities " \ "WHERE recipient_id != -1 ORDER BY recipient_id ASC" c = self.dbConn.cursor() result = [] for row in c.execute(q): result.append((row[0], row[1], row[2], row[3])) return result def getFingerprints(self, jid): q = "SELECT _id, recipient_id, public_key, trust FROM identities " \ "WHERE recipient_id =? ORDER BY trust ASC" c = self.dbConn.cursor() result = [] c.execute(q, (jid,)) rows = c.fetchall() for row in rows: result.append((row[0], row[1], row[2], row[3])) return result def getTrustedFingerprints(self, jid): q = "SELECT public_key FROM identities WHERE recipient_id = ? AND trust = ?" c = self.dbConn.cursor() result = [] c.execute(q, (jid, TRUSTED)) rows = c.fetchall() for row in rows: result.append(row[0]) return result def getUndecidedFingerprints(self, jid): q = "SELECT trust FROM identities WHERE recipient_id = ? AND trust = ?" c = self.dbConn.cursor() result = [] c.execute(q, (jid, UNDECIDED)) result = c.fetchall() return result def getNewFingerprints(self, jid): q = "SELECT _id FROM identities WHERE shown = 0 AND " \ "recipient_id = ?" c = self.dbConn.cursor() result = [] for row in c.execute(q, (jid,)): result.append(row[0]) return result def setShownFingerprints(self, fingerprints): q = "UPDATE identities SET shown = 1 WHERE _id IN ({})" \ .format(', '.join(['?'] * len(fingerprints))) c = self.dbConn.cursor() c.execute(q, fingerprints) self.dbConn.commit() def setTrust(self, identityKey, trust): q = "UPDATE identities SET trust = ? WHERE public_key = ?" c = self.dbConn.cursor() c.execute(q, (trust, identityKey.getPublicKey().serialize())) self.dbConn.commit() omemo/omemo/litesessionstore.py0000644000175500017550000001244613623023766017047 0ustar debacledebacle# -*- coding: utf-8 -*- # # Copyright 2015 Tarek Galal # # 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 . # from axolotl.state.sessionrecord import SessionRecord from axolotl.state.sessionstore import SessionStore class LiteSessionStore(SessionStore): def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn def loadSession(self, recipientId, deviceId): q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, deviceId)) result = c.fetchone() if result: return SessionRecord(serialized=result[0]) else: return SessionRecord() def getSubDeviceSessions(self, recipientId): q = "SELECT device_id from sessions WHERE recipient_id = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, )) result = c.fetchall() deviceIds = [r[0] for r in result] return deviceIds def getJidFromDevice(self, device_id): q = "SELECT recipient_id from sessions WHERE device_id = ?" c = self.dbConn.cursor() c.execute(q, (device_id, )) result = c.fetchone() return result[0].decode('utf-8') if result else None def getActiveDeviceTuples(self): q = "SELECT recipient_id, device_id FROM sessions WHERE active = 1" c = self.dbConn.cursor() result = [] for row in c.execute(q): result.append((row[0].decode('utf-8'), row[1])) return result def storeSession(self, recipientId, deviceId, sessionRecord): self.deleteSession(recipientId, deviceId) q = "INSERT INTO sessions(recipient_id, device_id, record) VALUES(?,?,?)" c = self.dbConn.cursor() c.execute(q, (recipientId, deviceId, sessionRecord.serialize())) self.dbConn.commit() def containsSession(self, recipientId, deviceId): q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?" c = self.dbConn.cursor() c.execute(q, (recipientId, deviceId)) result = c.fetchone() return result is not None def deleteSession(self, recipientId, deviceId): q = "DELETE FROM sessions WHERE recipient_id = ? AND device_id = ?" self.dbConn.cursor().execute(q, (recipientId, deviceId)) self.dbConn.commit() def deleteAllSessions(self, recipientId): q = "DELETE FROM sessions WHERE recipient_id = ?" self.dbConn.cursor().execute(q, (recipientId, )) self.dbConn.commit() def getAllSessions(self): q = "SELECT _id, recipient_id, device_id, record, active from sessions" c = self.dbConn.cursor() result = [] for row in c.execute(q): result.append((row[0], row[1].decode('utf-8'), row[2], row[3], row[4])) return result def getSessionsFromJid(self, recipientId): q = "SELECT _id, recipient_id, device_id, record, active from sessions" \ " WHERE recipient_id = ?" c = self.dbConn.cursor() result = [] for row in c.execute(q, (recipientId,)): result.append((row[0], row[1].decode('utf-8'), row[2], row[3], row[4])) return result def getSessionsFromJids(self, recipientId): q = "SELECT _id, recipient_id, device_id, record, active from sessions" \ " WHERE recipient_id IN ({})" \ .format(', '.join(['?'] * len(recipientId))) c = self.dbConn.cursor() result = [] for row in c.execute(q, recipientId): result.append((row[0], row[1].decode('utf-8'), row[2], row[3], row[4])) return result def setActiveState(self, deviceList, jid): c = self.dbConn.cursor() q = "UPDATE sessions SET active = {} " \ "WHERE recipient_id = '{}' AND device_id IN ({})" \ .format(1, jid, ', '.join(['?'] * len(deviceList))) c.execute(q, deviceList) q = "UPDATE sessions SET active = {} " \ "WHERE recipient_id = '{}' AND device_id NOT IN ({})" \ .format(0, jid, ', '.join(['?'] * len(deviceList))) c.execute(q, deviceList) self.dbConn.commit() def getInactiveSessionsKeys(self, recipientId): q = "SELECT record FROM sessions WHERE active = 0 AND recipient_id = ?" c = self.dbConn.cursor() result = [] for row in c.execute(q, (recipientId,)): public_key = (SessionRecord(serialized=row[0]). getSessionState().getRemoteIdentityKey(). getPublicKey()) result.append(public_key.serialize()) return result omemo/COPYING0000644000175500017550000010451313623023766012773 0ustar debacledebacle GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program 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. This program 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 this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . omemo/__init__.py0000644000175500017550000000004513623023766014044 0ustar debacledebaclefrom .omemoplugin import OmemoPlugin omemo/manifest.ini0000644000175500017550000000104313623023766014241 0ustar debacledebacle[info] name: OMEMO short_name: omemo version: 2.6.30 description: OMEMO is an XMPP Extension Protocol (XEP) for secure multi-client end-to-end encryption based on Axolotl and PEP. You need to install some dependencies, you can find install instructions for your system in the Github Wiki. authors: Bahtiar `kalkin-` Gadimov Daniel Gultsch Philipp Hörist homepage: https://dev.gajim.org/gajim/gajim-plugins/wikis/OmemoGajimPlugin min_gajim_version: 1.0.99 max_gajim_version: 1.1.90 omemo/omemo16x16.png0000644000175500017550000000126013623023766014263 0ustar debacledebaclePNG  IHDRawIDATxKzFm۶m۶m۶mNζ9[ffcoɾ.VV/$h >+eeyTerVgqe:!k˻;m/n&M'=(1kr opK]㏬p7pxW"kdx`n1sIH\+Ƚ9ۉeQx.W&#/!';rc5%)U2#LUqHz7i(ŗ~IENDB`omemo/omemo_connection.py0000644000175500017550000007615113623023766015653 0ustar debacledebacleimport os import time import logging import sqlite3 import nbxmpp from nbxmpp.simplexml import Node from nbxmpp import JID from gajim.common import app from gajim.common import ged from gajim.common import helpers from gajim.common import configpaths from gajim.common.connection_handlers_events import MessageNotSentEvent from gajim.plugins.plugins_i18n import _ from omemo.xmpp import ( NS_NOTIFY, NS_OMEMO, NS_EME, NS_HINTS, NS_BUNDLES, BundleInformationQuery, DevicelistQuery, make_bundle, OmemoMessage, successful, unpack_device_bundle, unpack_device_list_update, unpack_encrypted, NS_DEVICE_LIST) from omemo.omemo.state import OmemoState ALLOWED_TAGS = [('request', nbxmpp.NS_RECEIPTS), ('active', nbxmpp.NS_CHATSTATES), ('gone', nbxmpp.NS_CHATSTATES), ('inactive', nbxmpp.NS_CHATSTATES), ('paused', nbxmpp.NS_CHATSTATES), ('composing', nbxmpp.NS_CHATSTATES), ('no-store', nbxmpp.NS_MSG_HINTS), ('store', nbxmpp.NS_MSG_HINTS), ('no-copy', nbxmpp.NS_MSG_HINTS), ('no-permanent-store', nbxmpp.NS_MSG_HINTS), ('replace', nbxmpp.NS_CORRECT), ('thread', None), ('origin-id', nbxmpp.NS_SID), ] log = logging.getLogger('gajim.plugin_system.omemo') class OMEMOConnection: def __init__(self, account, plugin): self.account = account self.plugin = plugin self.own_jid = self.get_own_jid(stripped=True) self.omemo = self.__get_omemo() self.groupchat = {} self.temp_groupchat = {} self.gc_message = {} self.query_for_bundles = [] self.query_for_devicelists = [] app.ged.register_event_handler('pep-received', ged.PRECORE, self.handle_device_list_update) app.ged.register_event_handler('signed-in', ged.PRECORE, self.signed_in) app.ged.register_event_handler('gc-presence-received', ged.PRECORE, self.gc_presence_received) app.ged.register_event_handler('gc-config-changed-received', ged.PRECORE, self.gc_config_changed_received) def get_con(self): return app.connections[self.account] def send_with_callback(self, stanza, callback, data=None): if data is None: self.get_con().connection.SendAndCallForResponse(stanza, callback) else: self.get_con().connection.SendAndCallForResponse( stanza, callback, data) def get_own_jid(self, stripped=False): if stripped: return self.get_con().get_own_jid().getStripped() return self.get_con().get_own_jid() def __get_omemo(self): """ Returns the the OmemoState for the specified account. Creates the OmemoState if it does not exist yet. Parameters ---------- account : str the account name Returns ------- OmemoState """ data_dir = configpaths.get('MY_DATA') db_path = os.path.join(data_dir, 'omemo_' + self.own_jid + '.db') conn = sqlite3.connect(db_path, check_same_thread=False) conn.execute("PRAGMA secure_delete=1") return OmemoState(self.own_jid, conn, self.account, self) def signed_in(self, event): """ Method called on SignIn Parameters ---------- event : SignedInEvent """ if event.conn.name != self.account: return log.info('%s => Announce Support after Sign In', self.account) self.query_for_bundles = [] self.publish_bundle() self.query_devicelist() def activate(self): """ Method called when the Plugin is activated in the PluginManager """ if app.caps_hash[self.account] != '': # Gajim has already a caps hash calculated, update it helpers.update_optional_features(self.account) if app.account_is_connected(self.account): log.info('%s => Announce Support after Plugin Activation', self.account) self.query_for_bundles = [] self.publish_bundle() self.query_devicelist() def deactivate(self): """ Method called when the Plugin is deactivated in the PluginManager """ self.query_for_bundles = [] @staticmethod def update_caps(account): if NS_NOTIFY not in app.gajim_optional_features[account]: app.gajim_optional_features[account].append(NS_NOTIFY) def message_received(self, conn, obj, callback): if obj.encrypted: return if obj.name == 'message-received': self._message_received(obj) elif obj.name == 'mam-message-received': self._mam_message_received(obj) elif obj.name == 'mam-gc-message-received': self._mam_gc_message_received(obj) if obj.encrypted == 'OMEMO': callback(obj) def _mam_gc_message_received(self, event): """ Handles an incoming GC MAM message Payload is decrypted and the plaintext is written into the event object. Afterwards the event is passed on further to Gajim. Parameters ---------- event : MamGcMessageReceivedEvent Returns ------- Return means that the Event is passed on to Gajim """ if event.conn.name != self.account: return # Compatibility for Gajim 1.0.3 if hasattr(event, 'message'): message = event.message else: message = event.msg_ omemo = message.getTag('encrypted', namespace=NS_OMEMO) if omemo is None: return if event.real_jid is None: log.error('%s => Received Groupchat Message without real jid', self.account) return log.info('%s => Groupchat Message received', self.account) msg_dict = unpack_encrypted(omemo) msg_dict['sender_jid'] = JID(event.real_jid).getStripped() plaintext = self.omemo.decrypt_msg(msg_dict) if not plaintext: event.encrypted = 'drop' return self.print_msg_to_log(message) event.msgtxt = plaintext event.encrypted = self.plugin.encryption_name self.add_additional_data(event.additional_data) def _mam_message_received(self, event): """ Handles an incoming MAM message Payload is decrypted and the plaintext is written into the event object. Afterwards the event is passed on further to Gajim. Parameters ---------- event : MamMessageReceivedEvent Returns ------- Return means that the Event is passed on to Gajim """ if event.conn.name != self.account: return # Compatibility for Gajim 1.0.3 if hasattr(event, 'message'): message = event.message else: message = event.msg_ omemo_encrypted_tag = message.getTag('encrypted', namespace=NS_OMEMO) if omemo_encrypted_tag: log.debug('%s => OMEMO MAM msg received', self.account) msg_dict = unpack_encrypted(omemo_encrypted_tag) if msg_dict is None: log.error('Invalid omemo message received:\n%s', message) event.encrypted = 'drop' return msg_dict['sender_jid'] = message.getFrom().getStripped() plaintext = self.omemo.decrypt_msg(msg_dict) if not plaintext: event.encrypted = 'drop' return self.print_msg_to_log(message) event.msgtxt = plaintext event.encrypted = self.plugin.encryption_name self.add_additional_data(event.additional_data) return def _message_received(self, msg): """ Handles an incoming message Payload is decrypted and the plaintext is written into the event object. Afterwards the event is passed on further to Gajim. Parameters ---------- msg : MessageReceivedEvent Returns ------- Return means that the Event is passed on to Gajim """ if msg.conn.name != self.account: return if msg.stanza.getTag('encrypted', namespace=NS_OMEMO): log.debug('%s => OMEMO msg received', self.account) if msg.forwarded and msg.sent: from_jid = str(msg.stanza.getTo()) # why gajim? why? log.debug('message was forwarded doing magic') else: from_jid = str(msg.stanza.getFrom()) self.print_msg_to_log(msg.stanza) msg_dict = unpack_encrypted(msg.stanza.getTag ('encrypted', namespace=NS_OMEMO)) if msg.mtype == 'groupchat': address_tag = msg.stanza.getTag('addresses', namespace=nbxmpp.NS_ADDRESS) if address_tag: # History Message from MUC from_jid = address_tag.getTag( 'address', attrs={'type': 'ofrom'}).getAttr('jid') else: try: from_jid = self.groupchat[msg.jid][msg.resource] except KeyError: log.debug('Groupchat: Last resort trying to ' 'find SID in DB') from_jid = self.omemo.store. \ getJidFromDevice(msg_dict['sid']) if not from_jid: log.error('%s => Cant decrypt GroupChat Message ' 'from %s', self.account, msg.resource) msg.encrypted = 'drop' return self.groupchat[msg.jid][msg.resource] = from_jid log.debug('GroupChat Message from: %s', from_jid) plaintext = '' if msg_dict['sid'] == self.omemo.own_device_id: if msg_dict['payload'] in self.gc_message: plaintext = self.gc_message[msg_dict['payload']] del self.gc_message[msg_dict['payload']] else: log.error('%s => Cant decrypt own GroupChat Message', self.account) msg.encrypted = 'drop' return else: msg_dict['sender_jid'] = app. \ get_jid_without_resource(from_jid) plaintext = self.omemo.decrypt_msg(msg_dict) if not plaintext: msg.encrypted = 'drop' return msg.msgtxt = plaintext # Gajim bug: there must be a body or the message # gets dropped from history msg.stanza.setBody(plaintext) msg.encrypted = self.plugin.encryption_name self.add_additional_data(msg.additional_data) def room_memberlist_received(self, stanza): if not nbxmpp.isResultNode(stanza): log.error('Room %s Memberlist received: %s', stanza.getFrom(), stanza.getError()) return room_jid = stanza.getFrom().getStripped() log.info('Room %s Memberlist received', room_jid) if room_jid not in self.groupchat: self.groupchat[room_jid] = {} def jid_known(jid): for nick in self.groupchat[room_jid]: if self.groupchat[room_jid][nick] == jid: return True return False items = stanza.getTag( 'query', namespace=nbxmpp.NS_MUC_ADMIN).getTags('item') for item in items: if not item.has_attr('jid'): continue try: jid = helpers.parse_jid(item.getAttr('jid')) except helpers.InvalidFormat: log.warning( 'Invalid JID: %s, ignoring it', item.getAttr('jid')) continue if not jid_known(jid): # Add JID with JID because we have no Nick yet self.groupchat[room_jid][jid] = jid log.info('JID Added: %s', jid) if not self.is_contact_in_roster(jid): # Query Devicelists from JIDs not in our Roster log.info('%s not in Roster, query devicelist...', jid) self.query_devicelist(jid) def is_contact_in_roster(self, jid): if jid == self.own_jid: return True contact = app.contacts.get_first_contact_from_jid(self.account, jid) if contact is None: return False return contact.sub == 'both' def gc_presence_received(self, event): if event.conn.name != self.account: return if not hasattr(event, 'real_jid') or not event.real_jid: return room = event.room_jid jid = app.get_jid_without_resource(event.real_jid) nick = event.nick if '303' in event.status_code: # Nick Changed if room in self.groupchat: if nick in self.groupchat[room]: del self.groupchat[room][nick] self.groupchat[room][event.new_nick] = jid log.debug('Nick Change: old: %s, new: %s, jid: %s ', nick, event.new_nick, jid) log.debug('Members after Change: %s', self.groupchat[room]) else: if nick in self.temp_groupchat[room]: del self.temp_groupchat[room][nick] self.temp_groupchat[room][event.new_nick] = jid return if room not in self.groupchat: if room not in self.temp_groupchat: self.temp_groupchat[room] = {} if nick not in self.temp_groupchat[room]: self.temp_groupchat[room][nick] = jid else: # Check if we received JID over Memberlist if jid in self.groupchat[room]: del self.groupchat[room][jid] # Add JID with Nick if nick not in self.groupchat[room]: self.groupchat[room][nick] = jid log.debug('JID Added: %s', jid) if not self.is_contact_in_roster(jid): # Query Devicelists from JIDs not in our Roster log.info('%s not in Roster, query devicelist...', jid) self.query_devicelist(jid) if '100' in event.status_code: # non-anonymous Room (Full JID) if room not in self.groupchat: self.groupchat[room] = self.temp_groupchat[room] log.info('OMEMO capable Room found: %s', room) self.get_affiliation_list(room, 'owner') self.get_affiliation_list(room, 'admin') self.get_affiliation_list(room, 'member') def get_affiliation_list(self, room_jid, affiliation): iq = nbxmpp.Iq(typ='get', to=room_jid, queryNS=nbxmpp.NS_MUC_ADMIN) item = iq.setQuery().setTag('item') item.setAttr('affiliation', affiliation) self.get_con().connection.SendAndCallForResponse( iq, self.room_memberlist_received) def gc_config_changed_received(self, event): if event.conn.name != self.account: return room = event.room_jid if '172' in event.status_code: if room not in self.groupchat: self.groupchat[room] = self.temp_groupchat[room] log.debug('CONFIG CHANGE') log.debug(event.room_jid) log.debug(event.status_code) def gc_encrypt_message(self, conn, event, callback): """ Manipulates the outgoing groupchat stanza The body is getting encrypted Parameters ---------- conn : nbxmpp.NonBlockingClient event : GcStanzaMessageOutgoingEvent callback: func The callback. Its only called if the stanza was encrypted. This prevents any accidental sending of unencrypted messages. """ if event.conn.name != self.account: return try: self.cleanup_stanza(event) if not event.message: callback(event) return to_jid = app.get_jid_without_resource(event.jid) msg_dict = self.omemo.create_gc_msg( self.own_jid, to_jid, event.message.encode('utf8')) if not msg_dict: raise OMEMOError('Error while encrypting') except OMEMOError as error: log.error(error) app.nec.push_incoming_event( MessageNotSentEvent( None, conn=conn, jid=event.jid, message=event.message, error=error, time_=time.time(), session=None)) return self.gc_message[msg_dict['payload']] = event.message encrypted_node = OmemoMessage(msg_dict) event.msg_iq.addChild(node=encrypted_node) # XEP-0380: Explicit Message Encryption eme_node = Node('encryption', attrs={'xmlns': NS_EME, 'name': 'OMEMO', 'namespace': NS_OMEMO}) event.msg_iq.addChild(node=eme_node) # Add Message for devices that dont support OMEMO support_msg = _('You received a message encrypted with ' \ 'OMEMO but your client doesnt support OMEMO.') event.msg_iq.setBody(support_msg) # Store Hint for MAM store = Node('store', attrs={'xmlns': NS_HINTS}) event.msg_iq.addChild(node=store) self.print_msg_to_log(event.msg_iq) callback(event) def encrypt_message(self, conn, event, callback): """ Manipulates the outgoing stanza Encrypt the body Parameters ---------- conn : nbxmpp.NonBlockingClient event : StanzaMessageOutgoingEvent callback: func The callback. Its only called if the stanza was encrypted. This prevents any accidental sending of unencrypted messages. """ if event.conn.name != self.account: return try: self.cleanup_stanza(event) if not event.message: callback(event) return to_jid = app.get_jid_without_resource(event.jid) plaintext = event.message.encode('utf8') msg_dict = self.omemo.create_msg(self.own_jid, to_jid, plaintext) if not msg_dict: raise OMEMOError('Error while encrypting') except OMEMOError as error: log.error(error) app.nec.push_incoming_event( MessageNotSentEvent( None, conn=conn, jid=event.jid, message=event.message, error=error, time_=time.time(), session=event.session)) return encrypted_node = OmemoMessage(msg_dict) event.msg_iq.addChild(node=encrypted_node) # XEP-0380: Explicit Message Encryption eme_node = Node('encryption', attrs={'xmlns': NS_EME, 'name': 'OMEMO', 'namespace': NS_OMEMO}) event.msg_iq.addChild(node=eme_node) # Add Message for devices that don't support OMEMO support_msg = _("You received a message encrypted with " \ "OMEMO but your client doesn't support OMEMO.") event.msg_iq.setBody(support_msg) # Store Hint for MAM store = Node('store', attrs={'xmlns': NS_HINTS}) event.msg_iq.addChild(node=store) self.print_msg_to_log(event.msg_iq) event.xhtml = None event.encrypted = self.plugin.encryption_name self.add_additional_data(event.additional_data) callback(event) @staticmethod def cleanup_stanza(obj): ''' We make sure only allowed tags are in the stanza ''' stanza = nbxmpp.Message( to=obj.msg_iq.getTo(), typ=obj.msg_iq.getType()) stanza.setID(obj.stanza_id) for tag, ns in ALLOWED_TAGS: node = obj.msg_iq.getTag(tag, namespace=ns) if node: stanza.addChild(node=node) obj.msg_iq = stanza def handle_device_list_update(self, event): """ Check if the passed event is a device list update and store the new device ids. Parameters ---------- event : PEPReceivedEvent Returns ------- bool True if the given event was a valid device list update event """ if event.conn.name != self.account: return if event.pep_type != 'omemo-devicelist': return self._handle_device_list_update(None, event.stanza) # Dont propagate event further return True def _handle_device_list_update(self, conn, stanza, fetch_bundle=False): """ Check if the passed event is a device list update and store the new device ids. Parameters ---------- conn : nbxmpp.NonBlockingClient stanza: nbxmpp.Iq fetch_bundle: If True, bundles are fetched for the device ids """ devices_list = list(set(unpack_device_list_update(stanza, self.account))) contact_jid = stanza.getFrom().getStripped() if not devices_list: log.error('%s => Received empty or invalid Devicelist from: %s', self.account, contact_jid) return False if self.get_own_jid().bareMatch(contact_jid): log.info('%s => Received own device list: %s', self.account, devices_list) self.omemo.set_own_devices(devices_list) self.omemo.store.sessionStore.setActiveState( devices_list, self.own_jid) # remove contact from list, so on send button pressed # we query for bundle and build a session if contact_jid in self.query_for_bundles: self.query_for_bundles.remove(contact_jid) if not self.omemo.own_device_id_published(): # Our own device_id is not in the list, it could be # overwritten by some other client self.publish_own_devices_list() else: log.info('%s => Received device list for %s: %s', self.account, contact_jid, devices_list) self.omemo.set_devices(contact_jid, devices_list) self.omemo.store.sessionStore.setActiveState( devices_list, contact_jid) # remove contact from list, so on send button pressed # we query for bundle and build a session if contact_jid in self.query_for_bundles: self.query_for_bundles.remove(contact_jid) if fetch_bundle: self.are_keys_missing(contact_jid) # Enable Encryption on receiving first Device List # TODO def publish_own_devices_list(self, new=False): """ Get all currently known own active device ids and publish them Parameters ---------- new : bool if True, a devicelist with only one (the current id of this instance) device id is pushed """ if new: devices_list = [self.omemo.own_device_id] else: devices_list = self.omemo.own_devices devices_list.append(self.omemo.own_device_id) devices_list = list(set(devices_list)) self.omemo.set_own_devices(devices_list) list_node = Node('list', attrs={'xmlns': NS_OMEMO}) for device in devices_list: list_node.addChild('device').setAttr('id', device) con = app.connections[self.account] con.get_module('PubSub').send_pb_publish( '', NS_DEVICE_LIST, list_node, 'current', cb=self.device_list_publish_result) log.info('%s => Publishing own Devices: %s', self.account, devices_list) def device_list_publish_result(self, _con, stanza): if not nbxmpp.isResultNode(stanza): log.error('%s => Publishing devicelist failed: %s', self.account, stanza.getError()) def are_keys_missing(self, contact_jid): """ Checks if devicekeys are missing and querys the bundles Parameters ---------- contact_jid : str bare jid of the contact Returns ------- bool Returns True if there are no trusted Fingerprints """ # Fetch Bundles of own other Devices if self.own_jid not in self.query_for_bundles: devices_without_session = self.omemo \ .devices_without_sessions(self.own_jid) self.query_for_bundles.append(self.own_jid) if devices_without_session: for device_id in devices_without_session: self.fetch_device_bundle_information(self.own_jid, device_id) # Fetch Bundles of contacts devices if contact_jid not in self.query_for_bundles: devices_without_session = self.omemo \ .devices_without_sessions(contact_jid) self.query_for_bundles.append(contact_jid) if devices_without_session: for device_id in devices_without_session: self.fetch_device_bundle_information(contact_jid, device_id) if self.omemo.getTrustedFingerprints(contact_jid): return False return True def fetch_device_bundle_information(self, jid, device_id): """ Fetch bundle information for specified jid, key, and create axolotl session on success. Parameters ---------- jid : str The jid to query for bundle information device_id : int The device id for which we want the bundle """ log.info('%s => Fetch bundle device %s#%s', self.account, device_id, jid) bundle_query = BundleInformationQuery(jid, device_id) self.send_with_callback(bundle_query, self.session_from_prekey_bundle, {'jid': jid, 'device_id': device_id}) def session_from_prekey_bundle(self, conn, stanza, jid, device_id): """ Starts a session from a PreKey bundle. This method tries to build an axolotl session when a PreKey bundle is fetched. If a session can not be build it will fail silently but log the a warning. Parameters ---------- conn : nbxmpp.NonBlockingClient stanza : nbxmpp.Iq The stanza jid : str Jid of the contact device_id : int The device id """ bundle_dict = unpack_device_bundle(stanza, device_id) if not bundle_dict: log.warning('Failed to build Session with %s', jid) return if self.omemo.build_session(jid, device_id, bundle_dict): log.info('%s => session created for: %s', self.account, jid) # Trigger dialog to trust new Fingerprints if # the Chat Window is Open ctrl = app.interface.msg_win_mgr.get_control( jid, self.account) if ctrl: self.plugin.new_fingerprints_available(ctrl) def query_devicelist(self, jid=None, fetch_bundle=False): """ Query own devicelist from the server """ if jid in self.query_for_devicelists: return if jid is None: device_query = DevicelistQuery(self.own_jid) log.info('%s => Querry own devicelist ...', self.account) self.send_with_callback(device_query, self.handle_devicelist_result) else: device_query = DevicelistQuery(jid) log.info('%s => Querry devicelist from %s', self.account, jid) self.send_with_callback(device_query, self._handle_device_list_update, data={'fetch_bundle': fetch_bundle}) self.query_for_devicelists.append(jid) def publish_bundle(self): """ Publish our bundle information to the PEP node """ bundle = make_bundle(self.omemo.bundle) node = '%s%s' % (NS_BUNDLES, self.omemo.own_device_id) log.info('%s => Publishing bundle ...', self.account) con = app.connections[self.account] con.get_module('PubSub').send_pb_publish( '', node, bundle, 'current', cb=self.handle_publish_result) def handle_publish_result(self, _con, stanza): """ Log if publishing our bundle was successful Parameters ---------- stanza : nbxmpp.Iq The stanza """ if successful(stanza): log.info('%s => Publishing bundle was successful', self.account) else: log.error('%s => Publishing bundle was NOT successful', self.account) def handle_devicelist_result(self, stanza): """ If query was successful add own device to the list. Parameters ---------- stanza : nbxmpp.Iq The stanza """ if successful(stanza): devices_list = list(set(unpack_device_list_update(stanza, self.account))) if not devices_list: self.publish_own_devices_list(new=True) return self.omemo.set_own_devices(devices_list) self.omemo.store.sessionStore.setActiveState( devices_list, self.own_jid) log.info('%s => Devicelistquery was successful', self.account) if not self.omemo.own_device_id_published(): # Our own device_id is not in the list, it could be # overwritten by some other client self.publish_own_devices_list() else: log.error('%s => Devicelistquery was NOT successful: %s', self.account, stanza.getError()) self.publish_own_devices_list(new=True) @staticmethod def print_msg_to_log(stanza): """ Prints a stanza in a fancy way to the log """ log.debug('-'*15) stanzastr = '\n' + stanza.__str__(fancy=True) stanzastr = stanzastr[0:-1] log.debug(stanzastr) log.debug('-'*15) def add_additional_data(self, data): data['encrypted'] = {'name': self.plugin.encryption_name} class OMEMOError(Exception): pass omemo/CHANGELOG0000644000175500017550000000560213623023766013151 0ustar debacledebacle2.6.30 / 2020-02-14 - Switch to 12 byte IV 2.6.29 / 2019-05-21 - Keep compatibility with python-axolotl 2.6.28 / 2019-03-16 - Fix loading style with python 3.5 2.6.27 / 2019-02-23 - Bug fix 2.6.26 / 2019-01-05 - Fix label color - Dont add additional thread node - Add fallback body 2.6.25 / 2018-12-15 - Better handle key exchange messages 2.6.24 / 2018-11-20 - Use "current" as pubsub node id 2.6.23 / 2018-10-17 - Bug fix 2.6.22 / 2018-10-13 - Bug fix 2.6.21 / 2018-10-12 - GUI adjustments - Use new fingerprints dialog - Refactor some UI code 2.6.1 / 2018-08-08 - Save encryption details to the database - Bugfixes 2.6.0 / 2018-08-08 - FingerprintDialog: show all fingerprints in one list 2.5.14 / 2018-07-15 - Make preparations for future Gajim versions - Allow writing encrypted messages in groupchats if there are no other participants 2.5.14 / 2018-07-15 - Make preparations for future Gajim versions - Allow writing encrypted messages in groupchats if there are no other participants 2.5.13 / 2018-05-21 - Bug fix 2.5.12 / 2018-05-20 - Bug fix 2.5.11 / 2018-04-25 - Bug fix 2.5.10 / 2018-04-09 - Bug fix 2.5.9 / 2018-04-08 - Remove pycrypo dependency 2.5.8 / 2018-03-31 - Bug fix 2.5.7 / 2018-02-26 - Big fix 2.5.6 / 2018-01-26 - Fix decrypting MAM MUC messages 2.5.5 / 2017-12-17 - Bug fix 2.5.4 / 2017-12-16 - Bug fix 2.5.3 / 2017-12-10 - Bug fix 2.5.2 / 2017-12-10 - Small refactoring 2.5.1 / 2017-11-21 - Bug fix 2.5.0 / 2017-11-20 - Add MAM for MUC decryption 2.4.3 / 2017-11-15 - Use Gajim API to announce caps 2.4.2 / 2017-11-15 - Query devicelists for contacts where we have none, this makes us a bit more independent from PEP - Fix encrypting in Groupchats - Improve error messages 2.4.1 / 2017-11-12 - Bug fix 2.4.0 / 2017-11-10 - Refactoring 2.3.8 / 2017-10-07 - Bug Fixes 2.3.7 / 2017-08-26 - Query only the most recent PEP items 2.3.6 / 2017-08-21 - Adapt to Gaim beeing now a Package 2.3.5 / 2017-08-07 - Support 12bit IVs on httpupload files 2.3.4 / 2017-06-10 - Bugfixes - Some Refactoring 2.3.3 / 2017-06-09 - Move encryption logic for files from the HTTPUploadPlugin to the OMEMOPlugin 2.3.2 / 2017-06-02 - Adapt to patches regarding LMC in Gajim 2.3.1 / 2017-05-23 - Bugfixes 2.3.0 / 2017-05-07 - Make plugin compatible with Gajims encryption API 2.2.1 / 2017-04-15 - Recognize aesgcm uri scheme 2.2.0 / 2017-04-06 - Add auth tag to key instead of payload - Support decryption of aesgcm:// uri scheme - Make python-cryptography mandatory - small bugfixes 2.1.0 / 2017-03-26 - Add file decryption 2.0.4 / 2017-03-01 - Use correct tag name for EME 2.0.3 / 2017-02-28 - Set an inactive device active again after receiving a message from it 2.0.2 / 2017-02-28 - Fix a bug when publishing devices - Fix copying fingerprint - Fix layout issue - Dont handle type 'normal' messages 2.0.1 / 2017-01-14 - Better XEP Compliance - Bugfixes 2.0.0 / 2016-12-04 - Port Plugin from GTK2