summaryrefslogtreecommitdiff
path: root/src/leap/mail/imap/fetch.py
blob: 38612e1e76416ef2e8446407fd2b504611de0ac5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# -*- coding: utf-8 -*-
# fetch.py
# Copyright (C) 2013 LEAP
#
# 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 <http://www.gnu.org/licenses/>.
"""
Incoming mail fetcher.
"""
import logging
import json
import ssl
import threading
import time
import copy
from StringIO import StringIO

from email.parser import Parser
from email.generator import Generator
from email.utils import parseaddr

from twisted.python import log
from twisted.internet.task import LoopingCall
from twisted.internet.threads import deferToThread
from zope.proxy import sameProxiedObjects

from leap.common import events as leap_events
from leap.common.check import leap_assert, leap_assert_type
from leap.common.events.events_pb2 import IMAP_FETCHED_INCOMING
from leap.common.events.events_pb2 import IMAP_MSG_PROCESSING
from leap.common.events.events_pb2 import IMAP_MSG_DECRYPTED
from leap.common.events.events_pb2 import IMAP_MSG_SAVED_LOCALLY
from leap.common.events.events_pb2 import IMAP_MSG_DELETED_INCOMING
from leap.common.events.events_pb2 import IMAP_UNREAD_MAIL
from leap.common.mail import get_email_charset
from leap.keymanager import errors as keymanager_errors
from leap.keymanager.openpgp import OpenPGPKey
from leap.soledad.client import Soledad
from leap.soledad.common.crypto import ENC_SCHEME_KEY, ENC_JSON_KEY


logger = logging.getLogger(__name__)


class MalformedMessage(Exception):
    """
    Raised when a given message is not well formed.
    """
    pass


class LeapIncomingMail(object):
    """
    Fetches mail from the incoming queue.
    """

    RECENT_FLAG = "\\Recent"

    INCOMING_KEY = "incoming"
    CONTENT_KEY = "content"

    LEAP_SIGNATURE_HEADER = 'X-Leap-Signature'
    """
    Header added to messages when they are decrypted by the IMAP fetcher,
    which states the validity of an eventual signature that might be included
    in the encrypted blob.
    """
    LEAP_SIGNATURE_VALID = 'valid'
    LEAP_SIGNATURE_INVALID = 'invalid'
    LEAP_SIGNATURE_COULD_NOT_VERIFY = 'could not verify'

    fetching_lock = threading.Lock()

    def __init__(self, keymanager, soledad, imap_account,
                 check_period, userid):

        """
        Initialize LeapIMAP.

        :param keymanager: a keymanager instance
        :type keymanager: keymanager.KeyManager

        :param soledad: a soledad instance
        :type soledad: Soledad

        :param imap_account: the account to fetch periodically
        :type imap_account: SoledadBackedAccount

        :param check_period: the period to fetch new mail, in seconds.
        :type check_period: int
        """

        leap_assert(keymanager, "need a keymanager to initialize")
        leap_assert_type(soledad, Soledad)
        leap_assert(check_period, "need a period to check incoming mail")
        leap_assert_type(check_period, int)
        leap_assert(userid, "need a userid to initialize")

        self._keymanager = keymanager
        self._soledad = soledad
        self.imapAccount = imap_account
        self._inbox = self.imapAccount.getMailbox('inbox')
        self._userid = userid

        self._loop = None
        self._check_period = check_period

        self._create_soledad_indexes()

    def _create_soledad_indexes(self):
        """
        Create needed indexes on soledad.
        """
        self._soledad.create_index("just-mail", "incoming")

    @property
    def _pkey(self):
        if sameProxiedObjects(self._keymanager, None):
            logger.warning('tried to get key, but null keymanager found')
            return None
        return self._keymanager.get_key(self._userid, OpenPGPKey, private=True)

    #
    # Public API: fetch, start_loop, stop.
    #

    def fetch(self):
        """
        Fetch incoming mail, to be called periodically.

        Calls a deferred that will execute the fetch callback
        in a separate thread
        """
        logger.debug("fetching mail for: %s %s" % (
            self._soledad.uuid, self._userid))
        if not self.fetching_lock.locked():
            d = deferToThread(self._sync_soledad)
            d.addCallbacks(self._signal_fetch_to_ui, self._sync_soledad_error)
            d.addCallbacks(self._process_doclist, self._sync_soledad_error)
            return d
        else:
            logger.debug("Already fetching mail.")

    def start_loop(self):
        """
        Starts a loop to fetch mail.
        """
        if self._loop is None:
            self._loop = LoopingCall(self.fetch)
            self._loop.start(self._check_period)
        else:
            logger.warning("Tried to start an already running fetching loop.")

    def stop(self):
        """
        Stops the loop that fetches mail.
        """
        if self._loop and self._loop.running is True:
            self._loop.stop()
            self._loop = None

    #
    # Private methods.
    #

    # synchronize incoming mail

    def _sync_soledad(self):
        """
        Synchronizes with remote soledad.

        :returns: a list of LeapDocuments, or None.
        :rtype: iterable or None
        """
        with self.fetching_lock:
            log.msg('syncing soledad...')
            self._soledad.sync()
            doclist = self._soledad.get_from_index("just-mail", "*")
        return doclist

    def _signal_unread_to_ui(self):
        """
        Sends unread event to ui.
        """
        leap_events.signal(
            IMAP_UNREAD_MAIL, str(self._inbox.getUnseenCount()))

    def _signal_fetch_to_ui(self, doclist):
        """
        Sends leap events to ui.

        :param doclist: iterable with msg documents.
        :type doclist: iterable.
        :returns: doclist
        :rtype: iterable
        """
        fetched_ts = time.mktime(time.gmtime())
        num_mails = len(doclist)
        log.msg("there are %s mails" % (num_mails,))
        leap_events.signal(
            IMAP_FETCHED_INCOMING, str(num_mails), str(fetched_ts))
        self._signal_unread_to_ui()
        return doclist

    def _sync_soledad_error(self, failure):
        """
        Errback for sync errors.
        """
        # XXX should signal unrecoverable maybe.
        err = failure.value
        logger.error("error syncing soledad: %s" % (err,))
        if failure.check(ssl.SSLError):
            logger.warning('SSL Error while '
                           'syncing soledad: %r' % (err,))
        elif failure.check(Exception):
            logger.warning('Unknown error while '
                           'syncing soledad: %r' % (err,))

    def _log_err(self, failure):
        """
        Generic errback
        """
        err = failure.value
        logger.exception("error!: %r" % (err,))

    def _decryption_error(self, failure):
        """
        Errback for decryption errors.
        """
        # XXX should signal unrecoverable maybe.
        err = failure.value
        logger.error("error decrypting msg: %s" % (err,))

    def _saving_error(self, failure):
        """
        Errback for local save errors.
        """
        # XXX should signal unrecoverable maybe.
        err = failure.value
        logger.error("error saving msg locally: %s" % (err,))

    def _process_doclist(self, doclist):
        """
        Iterates through the doclist, checks if each doc
        looks like a message, and yields a deferred that will decrypt and
        process the message.

        :param doclist: iterable with msg documents.
        :type doclist: iterable.
        :returns: a list of deferreds for individual messages.
        """
        log.msg('processing doclist')
        if not doclist:
            logger.debug("no docs found")
            return
        num_mails = len(doclist)

        docs_cb = []
        for index, doc in enumerate(doclist):
            logger.debug("processing doc %d of %d" % (index, num_mails))
            leap_events.signal(
                IMAP_MSG_PROCESSING, str(index), str(num_mails))
            keys = doc.content.keys()
            if self._is_msg(keys):
                # Ok, this looks like a legit msg.
                # Let's process it!
                # Deferred chain for individual messages
                d = deferToThread(self._decrypt_doc, doc)
                d.addCallback(self._process_decrypted_doc)
                d.addErrback(self._log_err)
                d.addCallback(self._add_message_locally)
                d.addErrback(self._log_err)
                # XXX check this, add_locally should not get called if we
                # get an error in process
                #d.addCallbacks(self._process_decrypted, self._decryption_error)
                #d.addCallbacks(self._add_message_locally, self._saving_error)
                docs_cb.append(d)
            else:
                # Ooops, this does not.
                logger.debug('This does not look like a proper msg.')
        return docs_cb

    #
    # operations on individual messages
    #

    def _is_msg(self, keys):
        """
        Checks if the keys of a dictionary match the signature
        of the document type we use for messages.

        :param keys: iterable containing the strings to match.
        :type keys: iterable of strings.
        :rtype: bool
        """
        return ENC_SCHEME_KEY in keys and ENC_JSON_KEY in keys

    def _decrypt_doc(self, doc):
        """
        Decrypt the contents of a document.

        :param doc: A document containing an encrypted message.
        :type doc: SoledadDocument

        :return: A tuple containing the document and the decrypted message.
        :rtype: (SoledadDocument, str)
        """
        log.msg('decrypting msg')
        success = False
        try:
            decrdata = self._keymanager.decrypt(
                doc.content[ENC_JSON_KEY],
                self._pkey)
            success = True
        except Exception as exc:
            # XXX move this to errback !!!
            logger.warning("Error while decrypting msg: %r" % (exc,))
            decrdata = ""
        leap_events.signal(IMAP_MSG_DECRYPTED, "1" if success else "0")
        return doc, decrdata

    def _process_decrypted_doc(self, msgtuple):
        """
        Process a document containing a succesfully decrypted message.

        :param msgtuple: a tuple consisting of a SoledadDocument
                         instance containing the incoming message
                         and data, the json-encoded, decrypted content of the
                         incoming message
        :type msgtuple: (SoledadDocument, str)
        :return: a SoledadDocument and the processed data.
        :rtype: (doc, data)
        """
        doc, data = msgtuple
        msg = json.loads(data)
        if not isinstance(msg, dict):
            return False
        if not msg.get(self.INCOMING_KEY, False):
            return False

        # ok, this is an incoming message
        rawmsg = msg.get(self.CONTENT_KEY, None)
        if not rawmsg:
            return False
        try:
            data = self._maybe_decrypt_msg(rawmsg)
            return doc, data
        except keymanager_errors.EncryptionDecryptionFailed as exc:
            logger.error(exc)
            raise

    def _maybe_decrypt_msg(self, data):
        """
        Tries to decrypt a gpg message if data looks like one.

        :param data: the text to be decrypted.
        :type data: unicode
        :return: data, possibly descrypted.
        :rtype: str
        """
        leap_assert_type(data, unicode)

        # parse the original message
        parser = Parser()
        encoding = get_email_charset(data)
        data = data.encode(encoding)
        msg = parser.parsestr(data)

        # try to obtain sender public key
        senderPubkey = None
        fromHeader = msg.get('from', None)
        if fromHeader is not None:
            _, senderAddress = parseaddr(fromHeader)
            try:
                senderPubkey = self._keymanager.get_key(
                    senderAddress, OpenPGPKey)
            except keymanager_errors.KeyNotFound:
                pass

        valid_sig = False  # we will add a header saying if sig is valid
        decrdata = ''
        if msg.get_content_type() == 'multipart/encrypted':
            decrmsg, valid_sig = self._decrypt_multipart_encrypted_msg(
                msg, encoding, senderPubkey)
        else:
            decrmsg, valid_sig = self._maybe_decrypt_inline_encrypted_msg(
                msg, encoding, senderPubkey)

        # add x-leap-signature header
        if senderPubkey is None:
            decrmsg.add_header(
                self.LEAP_SIGNATURE_HEADER,
                self.LEAP_SIGNATURE_COULD_NOT_VERIFY)
        else:
            decrmsg.add_header(
                self.LEAP_SIGNATURE_HEADER,
                self.LEAP_SIGNATURE_VALID if valid_sig else \
                self.LEAP_SIGNATURE_INVALID,
                pubkey=senderPubkey.key_id)

        return decrmsg.as_string()

    def _decrypt_multipart_encrypted_msg(self, msg, encoding, senderPubkey):
        """
        Decrypt a message with content-type 'multipart/encrypted'.

        :param msg: The original encrypted message.
        :type msg: Message
        :param encoding: The encoding of the email message.
        :type encoding: str
        :param senderPubkey: The key of the sender of the message.
        :type senderPubkey: OpenPGPKey

        :return: A unitary tuple containing a decrypted message.
        :rtype: (Message)
        """
        msg = copy.deepcopy(msg)
        # sanity check
        payload = msg.get_payload()
        if len(payload) != 2:
            raise MalformedMessage(
                'Multipart/encrypted messages should have exactly 2 body '
                'parts (instead of %d).' % len(payload))
        if payload[0].get_content_type() != 'application/pgp-encrypted':
            raise MalformedMessage(
                "Multipart/encrypted messages' first body part should "
                "have content type equal to 'application/pgp-encrypted' "
                "(instead of %s)." % payload[0].get_content_type())
        if payload[1].get_content_type() != 'application/octet-stream':
            raise MalformedMessage(
                "Multipart/encrypted messages' second body part should "
                "have content type equal to 'octet-stream' (instead of "
                "%s)." % payload[1].get_content_type())
        # parse message and get encrypted content
        pgpencmsg = msg.get_payload()[1]
        encdata = pgpencmsg.get_payload()
        # decrypt and parse decrypted message
        decrdata, valid_sig = self._decrypt_and_verify_data(
            encdata, senderPubkey)
        try:
            decrdata = decrdata.encode(encoding)
        except (UnicodeEncodeError, UnicodeDecodeError) as e:
            logger.error("Unicode error {0}".format(e))
            decrdata = decrdata.encode(encoding, 'replace')
        parser = Parser()
        decrmsg = parser.parsestr(decrdata)
        # remove original message's multipart/encrypted content-type
        del(msg['content-type'])
        # replace headers back in original message
        for hkey, hval in decrmsg.items():
            try:
                # this will raise KeyError if header is not present
                msg.replace_header(hkey, hval)
            except KeyError:
                msg[hkey] = hval
        # replace payload by unencrypted payload
        msg.set_payload(decrmsg.get_payload())
        return msg, valid_sig

    def _maybe_decrypt_inline_encrypted_msg(self, origmsg, encoding,
                                                senderPubkey):
        """
        Possibly decrypt an inline OpenPGP encrypted message.

        :param origmsg: The original, possibly encrypted message.
        :type origmsg: Message
        :param encoding: The encoding of the email message.
        :type encoding: str
        :param senderPubkey: The key of the sender of the message.
        :type senderPubkey: OpenPGPKey

        :return: A unitary tuple containing a decrypted message.
        :rtype: (Message)
        """
        # serialize the original message
        buf = StringIO()
        g = Generator(buf)
        g.flatten(origmsg)
        data = buf.getvalue()
        # handle exactly one inline PGP message
        PGP_BEGIN = "-----BEGIN PGP MESSAGE-----"
        PGP_END = "-----END PGP MESSAGE-----"
        valid_sig = False
        if PGP_BEGIN in data:
            begin = data.find(PGP_BEGIN)
            end = data.find(PGP_END)
            pgp_message = data[begin:end+len(PGP_END)]
            decrdata, valid_sig = self._decrypt_and_verify_data(
                pgp_message, senderPubkey)
            # replace encrypted by decrypted content
            data = data.replace(pgp_message, decrdata)
        # if message is not encrypted, return raw data
        if isinstance(data, unicode):
            data = data.encode(encoding, 'replace')
        parser = Parser()
        return parser.parsestr(data), valid_sig

    def _decrypt_and_verify_data(self, data, senderPubkey):
        """
        Decrypt C{data} using our private key and attempt to verify a
        signature using C{senderPubkey}.

        :param data: The text to be decrypted.
        :type data: unicode
        :param senderPubkey: The public key of the sender of the message.
        :type senderPubkey: OpenPGPKey

        :return: The decrypted data and a boolean stating whether the
                 signature could be verified.
        :rtype: (str, bool)
        """
        valid_sig = False
        try:
            decrdata = self._keymanager.decrypt(
                data, self._pkey,
                verify=senderPubkey)
            if senderPubkey is not None:
                valid_sig = True
        except keymanager_errors.InvalidSignature:
            decrdata = self._keymanager.decrypt(
                data, self._pkey)
        return decrdata, valid_sig

    def _add_message_locally(self, msgtuple):
        """
        Adds a message to local inbox and delete it from the incoming db
        in soledad.

        :param msgtuple: a tuple consisting of a SoledadDocument
                         instance containing the incoming message
                         and data, the json-encoded, decrypted content of the
                         incoming message
        :type msgtuple: (SoledadDocument, str)
        """
        doc, data = msgtuple
        self._inbox.addMessage(data, (self.RECENT_FLAG,))
        leap_events.signal(IMAP_MSG_SAVED_LOCALLY)
        doc_id = doc.doc_id
        self._soledad.delete_doc(doc)
        log.msg("deleted doc %s from incoming" % doc_id)
        leap_events.signal(IMAP_MSG_DELETED_INCOMING)
        self._signal_unread_to_ui()