pgpplugin.py 12.6 KB
Newer Older
Philipp Hörist's avatar
Philipp Hörist committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# -*- coding: utf-8 -*-

'''
Copyright 2017 Philipp Hörist <philipp@hoerist.com>

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 <http://www.gnu.org/licenses/>.
'''

import os
import logging
import time
import threading
import queue

import nbxmpp
from gi.repository import GLib

30
from gajim.common import app
31
from gajim.common.connection_handlers_events import MessageNotSentEvent
32
from gajim.plugins import GajimPlugin
Philipp Hörist's avatar
Philipp Hörist committed
33
from gajim.plugins.plugins_i18n import _
Philipp Hörist's avatar
Philipp Hörist committed
34

Philipp Hörist's avatar
Philipp Hörist committed
35 36 37 38
from gajim.gtk.dialogs import ErrorDialog
from gajim.gtk.dialogs import InformationDialog
from gajim.gtk.dialogs import YesNoDialog

Philipp Hörist's avatar
Philipp Hörist committed
39 40 41
log = logging.getLogger('gajim.plugin_system.oldpgp')

ERROR_MSG = ''
42
if not app.is_installed('GPG'):
43 44 45 46
    if os.name == 'nt':
        ERROR_MSG = _('Please install GnuPG / Gpg4win')
    else:
        ERROR_MSG = _('Please install python-gnupg and PGP')
Philipp Hörist's avatar
Philipp Hörist committed
47 48 49 50 51 52 53 54 55 56 57

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),
58 59 60
                ('replace', nbxmpp.NS_CORRECT),
                ('origin-id', nbxmpp.NS_SID),
                ]
Philipp Hörist's avatar
Philipp Hörist committed
61 62 63 64 65


class OldPGPPlugin(GajimPlugin):

    def init(self):
66
        self.description = _('PGP encryption as per XEP-0027')
Philipp Hörist's avatar
Philipp Hörist committed
67 68 69 70 71 72
        if ERROR_MSG:
            self.activatable = False
            self.available_text = ERROR_MSG
            return
        self.config_dialog = None
        self.encryption_name = 'PGP'
73
        self.allow_zeroconf = True
Philipp Hörist's avatar
Philipp Hörist committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87
        self.gui_extension_points = {
            'encrypt' + self.encryption_name: (self._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)}

        self.decrypt_queue = queue.Queue()
        self.thread = None

    def get_gpg(self, account):
88
        return app.connections[account].gpg
Philipp Hörist's avatar
Philipp Hörist committed
89 90

    def activate(self):
91
        pass
Philipp Hörist's avatar
Philipp Hörist committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

    def deactivate(self):
        pass

    @staticmethod
    def activate_encryption(chat_control):
        return True

    @staticmethod
    def encryption_state(chat_control, state):
        key_id = chat_control.contact.keyID
        account = chat_control.account
        authenticated, _ = check_state(key_id, account)
        state['visible'] = True
        state['authenticated'] = authenticated

    @staticmethod
    def on_encryption_button_clicked(chat_control):
        account = chat_control.account
        key_id = chat_control.contact.keyID
        transient = chat_control.parent_win.window
        authenticated, info = check_state(key_id, account)
Philipp Hörist's avatar
Philipp Hörist committed
114
        InformationDialog(authenticated, info, transient)
Philipp Hörist's avatar
Philipp Hörist committed
115 116 117 118 119

    @staticmethod
    def _before_sendmessage(chat_control):
        account = chat_control.account
        if not chat_control.contact.keyID:
Philipp Hörist's avatar
Philipp Hörist committed
120
            ErrorDialog(
Philipp Hörist's avatar
Philipp Hörist committed
121 122 123 124
                _('No OpenPGP key assigned'),
                _('No OpenPGP key is assigned to this contact. So you cannot '
                  'encrypt messages with OpenPGP.'))
            chat_control.sendmessage = False
125
        elif not app.config.get_per('accounts', account, 'keyid'):
Philipp Hörist's avatar
Philipp Hörist committed
126
            ErrorDialog(
Philipp Hörist's avatar
Philipp Hörist committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
                _('No OpenPGP key assigned'),
                _('No OpenPGP key is assigned to your account. So you cannot '
                  'encrypt messages with OpenPGP.'))
            chat_control.sendmessage = False

    @staticmethod
    def _get_info_message():
        msg = '[This message is *encrypted* (See :XEP:`27`]'
        lang = os.getenv('LANG')
        if lang is not None and not lang.startswith('en'):
            # we're not english: one in locale and one en
            msg = _('[This message is *encrypted* (See :XEP:`27`]') + \
                    ' (' + msg + ')'
        return msg

    def _message_received(self, conn, obj, callback):
        if obj.encrypted:
            # Another Plugin already decrypted the message
            return
        account = conn.name
147
        if obj.name == 'message-received':
Philipp Hörist's avatar
Philipp Hörist committed
148
            enc_tag = obj.stanza.getTag('x', namespace=nbxmpp.NS_ENCRYPTED)
149 150 151 152 153 154 155
        elif obj.name == 'mam-message-received':
            # Compatibility for Gajim 1.0.3
            if hasattr(obj, 'message'):
                message = obj.message
            else:
                message = obj.msg_
            enc_tag = message.getTag('x', namespace=nbxmpp.NS_ENCRYPTED)
156 157
        else:
            return
Philipp Hörist's avatar
Philipp Hörist committed
158 159
        if enc_tag:
            encmsg = enc_tag.getData()
160
            key_id = app.config.get_per('accounts', account, 'keyid')
Philipp Hörist's avatar
Philipp Hörist committed
161
            if key_id:
162
                obj.encrypted = self.encryption_name
163
                self.add_additional_data(obj.additional_data)
Philipp Hörist's avatar
Philipp Hörist committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
                self.decrypt_queue.put([encmsg, key_id, obj, conn, callback])
                if not self.thread:
                    self.thread = threading.Thread(target=self.worker)
                    self.thread.start()
                return

    def worker(self):
        while True:
            try:
                item = self.decrypt_queue.get(block=False)
                encmsg, key_id, obj, conn, callback = item
                account = conn.name
                decmsg = self.get_gpg(account).decrypt(encmsg, key_id)
                decmsg = conn.connection.Dispatcher. \
                    replace_non_character(decmsg)
                # \x00 chars are not allowed in C (so in GTK)
                msg = decmsg.replace('\x00', '')
                obj.msgtxt = msg
                GLib.idle_add(callback, obj)
            except queue.Empty:
                self.thread = None
                break

    def _encrypt_message(self, conn, obj, callback):
        account = conn.name
        if not obj.message:
            # We only encrypt the actual message
            self._finished_encrypt(obj, callback=callback)
            return

        if obj.keyID == 'UNKNOWN':
            error = _('Neither the remote presence is signed, nor a key was '
                      'assigned.')
        elif obj.keyID.endswith('MISMATCH'):
            error = _('The contact\'s key (%s) does not match the key assigned '
                      'in Gajim.' % obj.keyID[:8])
        else:
201
            my_key_id = app.config.get_per('accounts', account, 'keyid')
Philipp Hörist's avatar
Philipp Hörist committed
202 203 204 205 206 207 208 209
            key_list = [obj.keyID, my_key_id]

            def _on_encrypted(output):
                msgenc, error = output
                if error.startswith('NOT_TRUSTED'):
                    def on_yes(checked):
                        if checked:
                            obj.conn.gpg.always_trust.append(obj.keyID)
210
                        app.thread_interface(
Philipp Hörist's avatar
Philipp Hörist committed
211 212 213 214 215 216 217 218
                            self.get_gpg(account).encrypt,
                            [obj.message, key_list, True],
                            _on_encrypted, [])

                    def on_no():
                        self._finished_encrypt(
                            obj, msgenc=msgenc, error=error, conn=conn)

Philipp Hörist's avatar
Philipp Hörist committed
219
                    YesNoDialog(
Philipp Hörist's avatar
Philipp Hörist committed
220 221 222 223 224 225 226 227 228 229 230
                        _('Untrusted OpenPGP key'),
                        _('The OpenPGP key used to encrypt this chat is not '
                          'trusted. Do you really want to encrypt this '
                          'message?'),
                        checktext=_('_Do not ask me again'),
                        on_response_yes=on_yes,
                        on_response_no=on_no)
                else:
                    self._finished_encrypt(
                        obj, msgenc=msgenc, error=error, conn=conn,
                        callback=callback)
231
            app.thread_interface(
Philipp Hörist's avatar
Philipp Hörist committed
232 233 234 235 236 237 238 239 240 241
                self.get_gpg(account).encrypt,
                [obj.message, key_list, False],
                _on_encrypted, [])
            return
        self._finished_encrypt(conn, obj, error=error)

    def _finished_encrypt(self, obj, msgenc=None, error=None,
                          conn=None, callback=None):
        if error:
            log.error('python-gnupg error: %s', error)
242
            app.nec.push_incoming_event(
Philipp Hörist's avatar
Philipp Hörist committed
243 244 245 246
                MessageNotSentEvent(
                    None, conn=conn, jid=obj.jid, message=obj.message,
                    error=error, time_=time.time(), session=obj.session))
            return
247

Philipp Hörist's avatar
Philipp Hörist committed
248 249 250 251 252 253 254 255 256 257 258
        self.cleanup_stanza(obj)

        if msgenc:
            obj.msg_iq.setBody(self._get_info_message())
            obj.msg_iq.setTag(
                'x', namespace=nbxmpp.NS_ENCRYPTED).setData(msgenc)
            eme_node = nbxmpp.Node('encryption',
                                   attrs={'xmlns': nbxmpp.NS_EME,
                                          'namespace': nbxmpp.NS_ENCRYPTED})
            obj.msg_iq.addChild(node=eme_node)

259 260 261
            # Set xhtml to None so it doesnt get logged
            obj.xhtml = None
            obj.encrypted = self.encryption_name
262
            self.add_additional_data(obj.additional_data)
263 264
            print_msg_to_log(obj.msg_iq)

Philipp Hörist's avatar
Philipp Hörist committed
265 266
        callback(obj)

267 268 269 270 271 272 273
    def encrypt_file(self, file, account, callback):
        thread = threading.Thread(target=self._encrypt_file_thread,
                                  args=(file, account, callback))
        thread.daemon = True
        thread.start()

    def _encrypt_file_thread(self, file, account, callback):
274
        my_key_id = app.config.get_per('accounts', account, 'keyid')
Philipp Hörist's avatar
Philipp Hörist committed
275
        key_list = [file.contact.keyID, my_key_id]
276 277 278 279 280 281 282 283 284 285 286 287 288 289

        encrypted = self.get_gpg(account).encrypt_file(file.get_data(), key_list)
        if not encrypted:
            GLib.idle_add(self._on_file_encryption_error, file, encrypted.status)
            return

        file.encrypted = True
        file.size = len(encrypted.data)
        file.path += '.pgp'
        file.data = encrypted.data
        if file.event.isSet():
            return
        GLib.idle_add(callback, file)

290
    @staticmethod
291
    def _on_file_encryption_error(file, error):
Philipp Hörist's avatar
Philipp Hörist committed
292
        ErrorDialog(_('Error'), error)
293

Philipp Hörist's avatar
Philipp Hörist committed
294 295 296 297 298 299
    @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())
300
        stanza.setID(obj.stanza_id)
Philipp Hörist's avatar
Philipp Hörist committed
301 302 303 304 305 306 307
        stanza.setThread(obj.msg_iq.getThread())
        for tag, ns in ALLOWED_TAGS:
            node = obj.msg_iq.getTag(tag, namespace=ns)
            if node:
                stanza.addChild(node=node)
        obj.msg_iq = stanza

308 309 310
    def add_additional_data(self, data):
        data['encrypted'] = {'name': self.encryption_name}

Philipp Hörist's avatar
Philipp Hörist committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

def print_msg_to_log(stanza):
    """ Prints a stanza in a fancy way to the log """
    stanzastr = '\n' + stanza.__str__(fancy=True) + '\n'
    stanzastr = stanzastr[0:-1]
    log.debug('\n' + '-'*15 + stanzastr + '-'*15)


def check_state(key_id, account):
    error = None
    if key_id.endswith('MISMATCH'):
        verification_status = _('''Contact's identity NOT verified''')
        info = _('The contact\'s key (%s) <b>does not match</b> the key '
                 'assigned in Gajim.') % key_id[:8]
    elif not key_id:
        # No key assigned nor a key is used by remote contact
        verification_status = _('No OpenPGP key assigned')
        info = _('No OpenPGP key is assigned to this contact. So you cannot'
                 ' encrypt messages.')
    else:
331
        error = app.connections[account].gpg.encrypt('test', [key_id])[1]
Philipp Hörist's avatar
Philipp Hörist committed
332 333 334 335 336 337 338 339 340 341
        if error:
            verification_status = _('''Contact's identity NOT verified''')
            info = _('OpenPGP key is assigned to this contact, but <b>you '
                     'do not trust their key</b>, so message <b>cannot</b> be '
                     'encrypted. Use your OpenPGP client to trust their key.')
        else:
            verification_status = _('''Contact's identity verified''')
            info = _('OpenPGP Key is assigned to this contact, and you '
                     'trust their key, so messages will be encrypted.')
    return (verification_status, info)