summaryrefslogtreecommitdiff
path: root/client/src/leap/soledad/client/crypto.py
blob: 950576ecf3f4f2d234f7d7666b727198740bb218 (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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# -*- coding: utf-8 -*-
# crypto.py
# Copyright (C) 2013, 2014 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/>.
"""
Cryptographic utilities for Soledad.
"""
import os
import binascii
import hmac
import hashlib
import json
import logging
import multiprocessing
import threading

from pycryptopp.cipher.aes import AES
from pycryptopp.cipher.xsalsa20 import XSalsa20
from zope.proxy import sameProxiedObjects

from leap.soledad.common import soledad_assert
from leap.soledad.common import soledad_assert_type
from leap.soledad.common import crypto
from leap.soledad.common.document import SoledadDocument


logger = logging.getLogger(__name__)


MAC_KEY_LENGTH = 64


def _assert_known_encryption_method(method):
    """
    Assert that we can encrypt/decrypt the given C{method}

    :param method: The encryption method to assert.
    :type method: str

    :raise UnknownEncryptionMethodError: Raised when C{method} is unknown.
    """
    valid_methods = [
        crypto.EncryptionMethods.AES_256_CTR,
        crypto.EncryptionMethods.XSALSA20,
    ]
    try:
        soledad_assert(method in valid_methods)
    except AssertionError:
        raise crypto.UnknownEncryptionMethodError


def encrypt_sym(data, key, method):
    """
    Encrypt C{data} using a {password}.

    Currently, the only encryption methods supported are AES-256 in CTR
    mode and XSalsa20.

    :param data: The data to be encrypted.
    :type data: str
    :param key: The key used to encrypt C{data} (must be 256 bits long).
    :type key: str
    :param method: The encryption method to use.
    :type method: str

    :return: A tuple with the initial value and the encrypted data.
    :rtype: (long, str)

    :raise AssertionError: Raised if C{method} is unknown.
    """
    soledad_assert_type(key, str)
    soledad_assert(
        len(key) == 32,  # 32 x 8 = 256 bits.
        'Wrong key size: %s bits (must be 256 bits long).' %
        (len(key) * 8))
    _assert_known_encryption_method(method)

    iv = None
    # AES-256 in CTR mode
    if method == crypto.EncryptionMethods.AES_256_CTR:
        iv = os.urandom(16)
        ciphertext = AES(key=key, iv=iv).process(data)
    # XSalsa20
    elif method == crypto.EncryptionMethods.XSALSA20:
        iv = os.urandom(24)
        ciphertext = XSalsa20(key=key, iv=iv).process(data)

    return binascii.b2a_base64(iv), ciphertext


def decrypt_sym(data, key, method, **kwargs):
    """
    Decrypt data using symmetric secret.

    Currently, the only encryption method supported is AES-256 CTR mode.

    :param data: The data to be decrypted.
    :type data: str
    :param key: The key used to decrypt C{data} (must be 256 bits long).
    :type key: str
    :param method: The encryption method to use.
    :type method: str
    :param kwargs: Other parameters specific to each encryption method.
    :type kwargs: dict

    :return: The decrypted data.
    :rtype: str

    :raise UnknownEncryptionMethodError: Raised when C{method} is unknown.
    """
    soledad_assert_type(key, str)
    # assert params
    soledad_assert(
        len(key) == 32,  # 32 x 8 = 256 bits.
        'Wrong key size: %s (must be 256 bits long).' % len(key))
    soledad_assert(
        'iv' in kwargs,
        '%s needs an initial value.' % method)
    _assert_known_encryption_method(method)
    # AES-256 in CTR mode
    if method == crypto.EncryptionMethods.AES_256_CTR:
        return AES(
            key=key, iv=binascii.a2b_base64(kwargs['iv'])).process(data)
    elif method == crypto.EncryptionMethods.XSALSA20:
        return XSalsa20(
            key=key, iv=binascii.a2b_base64(kwargs['iv'])).process(data)


def doc_mac_key(doc_id, secret):
    """
    Generate a key for calculating a MAC for a document whose id is
    C{doc_id}.

    The key is derived using HMAC having sha256 as underlying hash
    function. The key used for HMAC is the first MAC_KEY_LENGTH characters
    of Soledad's storage secret. The HMAC message is C{doc_id}.

    :param doc_id: The id of the document.
    :type doc_id: str

    :param secret: The Soledad storage secret
    :type secret: str

    :return: The key.
    :rtype: str
    """
    soledad_assert(secret is not None)
    return hmac.new(
        secret[:MAC_KEY_LENGTH],
        doc_id,
        hashlib.sha256).digest()


class SoledadCrypto(object):
    """
    General cryptographic functionality encapsulated in a
    object that can be passed along.
    """
    def __init__(self, soledad):
        """
        Initialize the crypto object.

        :param soledad: A Soledad instance for key lookup.
        :type soledad: leap.soledad.Soledad
        """
        self._soledad = soledad

    def encrypt_sym(self, data, key,
                    method=crypto.EncryptionMethods.AES_256_CTR):
        return encrypt_sym(data, key, method)

    def decrypt_sym(self, data, key,
                    method=crypto.EncryptionMethods.AES_256_CTR, **kwargs):
        return decrypt_sym(data, key, method, **kwargs)

    def doc_mac_key(self, doc_id, secret):
        return doc_mac_key(doc_id, self.secret)

    def doc_passphrase(self, doc_id):
        """
        Generate a passphrase for symmetric encryption of document's contents.

        The password is derived using HMAC having sha256 as underlying hash
        function. The key used for HMAC are the first
        C{soledad.REMOTE_STORAGE_SECRET_LENGTH} bytes of Soledad's storage
        secret stripped from the first MAC_KEY_LENGTH characters. The HMAC
        message is C{doc_id}.

        :param doc_id: The id of the document that will be encrypted using
            this passphrase.
        :type doc_id: str

        :return: The passphrase.
        :rtype: str
        """
        soledad_assert(self.secret is not None)
        return hmac.new(
            self.secret[MAC_KEY_LENGTH:],
            doc_id,
            hashlib.sha256).digest()

    #
    # secret setters/getters
    #

    def _get_secret(self):
        return self._soledad.secrets.remote_storage_secret

    secret = property(
        _get_secret, doc='The secret used for symmetric encryption')


#
# Crypto utilities for a SoledadDocument.
#

def mac_doc(doc_id, doc_rev, ciphertext, enc_scheme, enc_method, enc_iv,
        mac_method, secret):
    """
    Calculate a MAC for C{doc} using C{ciphertext}.

    Current MAC method used is HMAC, with the following parameters:

        * key: sha256(storage_secret, doc_id)
        * msg: doc_id + doc_rev + ciphertext
        * digestmod: sha256

    :param doc_id: The id of the document.
    :type doc_id: str
    :param doc_rev: The revision of the document.
    :type doc_rev: str
    :param ciphertext: The content of the document.
    :type ciphertext: str
    :param enc_scheme: The encryption scheme.
    :type enc_scheme: str
    :param enc_method: The encryption method.
    :type enc_method: str
    :param enc_iv: The encryption initialization vector.
    :type enc_iv: str
    :param mac_method: The MAC method to use.
    :type mac_method: str
    :param secret: The Soledad storage secret
    :type secret: str

    :return: The calculated MAC.
    :rtype: str

    :raise crypto.UnknownMacMethodError: Raised when C{mac_method} is unknown.
    """
    try:
        soledad_assert(mac_method == crypto.MacMethods.HMAC)
    except AssertionError:
        raise crypto.UnknownMacMethodError
    template = "{doc_id}{doc_rev}{ciphertext}{enc_scheme}{enc_method}{enc_iv}"
    content = template.format(
        doc_id=doc_id,
        doc_rev=doc_rev,
        ciphertext=ciphertext,
        enc_scheme=enc_scheme,
        enc_method=enc_method,
        enc_iv=enc_iv)
    return hmac.new(
        doc_mac_key(doc_id, secret),
        content,
        hashlib.sha256).digest()


def encrypt_doc(crypto, doc):
    """
    Wrapper around encrypt_docstr that accepts a crypto object and the document
    as arguments.

    :param crypto: a soledad crypto object.
    :type crypto: SoledadCrypto
    :param doc: the document.
    :type doc: SoledadDocument
    """
    key = crypto.doc_passphrase(doc.doc_id)
    secret = crypto.secret

    return encrypt_docstr(
        doc.get_json(), doc.doc_id, doc.rev, key, secret)


def encrypt_docstr(docstr, doc_id, doc_rev, key, secret):
    """
    Encrypt C{doc}'s content.

    Encrypt doc's contents using AES-256 CTR mode and return a valid JSON
    string representing the following:

        {
            crypto.ENC_JSON_KEY: '<encrypted doc JSON string>',
            crypto.ENC_SCHEME_KEY: 'symkey',
            crypto.ENC_METHOD_KEY: crypto.EncryptionMethods.AES_256_CTR,
            crypto.ENC_IV_KEY: '<the initial value used to encrypt>',
            MAC_KEY: '<mac>'
            crypto.MAC_METHOD_KEY: 'hmac'
        }

    :param docstr: A representation of the document to be encrypted.
    :type docstr: str or unicode.

    :param doc_id: The document id.
    :type doc_id: str

    :param doc_rev: The document revision.
    :type doc_rev: str

    :param key: The key used to encrypt ``data`` (must be 256 bits long).
    :type key: str

    :param secret: The Soledad storage secret (used for MAC auth).
    :type secret: str

    :return: The JSON serialization of the dict representing the encrypted
             content.
    :rtype: str
    """
    enc_scheme = crypto.EncryptionSchemes.SYMKEY
    enc_method = crypto.EncryptionMethods.AES_256_CTR
    mac_method = crypto.MacMethods.HMAC
    enc_iv, ciphertext = encrypt_sym(
        str(docstr),  # encryption/decryption routines expect str
        key, method=enc_method)
    mac = binascii.b2a_hex(  # store the mac as hex.
        mac_doc(
            doc_id,
            doc_rev,
            ciphertext,
            enc_scheme,
            enc_method,
            enc_iv,
            mac_method,
            secret))
    # Return a representation for the encrypted content. In the following, we
    # convert binary data to hexadecimal representation so the JSON
    # serialization does not complain about what it tries to serialize.
    hex_ciphertext = binascii.b2a_hex(ciphertext)
    return json.dumps({
        crypto.ENC_JSON_KEY: hex_ciphertext,
        crypto.ENC_SCHEME_KEY: enc_scheme,
        crypto.ENC_METHOD_KEY: enc_method,
        crypto.ENC_IV_KEY: enc_iv,
        crypto.MAC_KEY: mac,
        crypto.MAC_METHOD_KEY: mac_method,
    })


def decrypt_doc(crypto, doc):
    """
    Wrapper around decrypt_doc_dict that accepts a crypto object and the
    document as arguments.

    :param crypto: a soledad crypto object.
    :type crypto: SoledadCrypto
    :param doc: the document.
    :type doc: SoledadDocument

    :return: json string with the decrypted document
    :rtype: str
    """
    key = crypto.doc_passphrase(doc.doc_id)
    secret = crypto.secret
    return decrypt_doc_dict(doc.content, doc.doc_id, doc.rev, key, secret)


def _verify_doc_mac(doc_id, doc_rev, ciphertext, enc_scheme, enc_method,
        enc_iv, mac_method, secret, doc_mac):
    """
    Verify that C{doc_mac} is a correct MAC for the given document.

    :param doc_id: The id of the document.
    :type doc_id: str
    :param doc_rev: The revision of the document.
    :type doc_rev: str
    :param ciphertext: The content of the document.
    :type ciphertext: str
    :param enc_scheme: The encryption scheme.
    :type enc_scheme: str
    :param enc_method: The encryption method.
    :type enc_method: str
    :param enc_iv: The encryption initialization vector.
    :type enc_iv: str
    :param mac_method: The MAC method to use.
    :type mac_method: str
    :param secret: The Soledad storage secret
    :type secret: str
    :param doc_mac: The MAC to be verified against.
    :type doc_mac: str

    :raise crypto.UnknownMacMethodError: Raised when C{mac_method} is unknown.
    :raise crypto.WrongMacError: Raised when MAC could not be verified.
    """
    calculated_mac = mac_doc(
        doc_id,
        doc_rev,
        ciphertext,
        enc_scheme,
        enc_method,
        enc_iv,
        mac_method,
        secret)
    # we compare mac's hashes to avoid possible timing attacks that might
    # exploit python's builtin comparison operator behaviour, which fails
    # immediatelly when non-matching bytes are found.
    doc_mac_hash = hashlib.sha256(
        binascii.a2b_hex(  # the mac is stored as hex
            doc_mac)).digest()
    calculated_mac_hash = hashlib.sha256(calculated_mac).digest()

    if doc_mac_hash != calculated_mac_hash:
        logger.warning("Wrong MAC while decrypting doc...")
        raise crypto.WrongMacError("Could not authenticate document's "
                                   "contents.")


def decrypt_doc_dict(doc_dict, doc_id, doc_rev, key, secret):
    """
    Decrypt a symmetrically encrypted C{doc}'s content.

    Return the JSON string representation of the document's decrypted content.

    The passed doc_dict argument should have the following structure:

        {
            crypto.ENC_JSON_KEY: '<enc_blob>',
            crypto.ENC_SCHEME_KEY: '<enc_scheme>',
            crypto.ENC_METHOD_KEY: '<enc_method>',
            crypto.ENC_IV_KEY: '<initial value used to encrypt>',  # (optional)
            MAC_KEY: '<mac>'
            crypto.MAC_METHOD_KEY: 'hmac'
        }

    C{enc_blob} is the encryption of the JSON serialization of the document's
    content. For now Soledad just deals with documents whose C{enc_scheme} is
    crypto.EncryptionSchemes.SYMKEY and C{enc_method} is
    crypto.EncryptionMethods.AES_256_CTR.

    :param doc_dict: The content of the document to be decrypted.
    :type doc_dict: dict

    :param doc_id: The document id.
    :type doc_id: str

    :param doc_rev: The document revision.
    :type doc_rev: str

    :param key: The key used to encrypt ``data`` (must be 256 bits long).
    :type key: str

    :param secret:
    :type secret:

    :return: The JSON serialization of the decrypted content.
    :rtype: str

    :raise UnknownEncryptionMethodError: Raised when trying to decrypt from an
        unknown encryption method.
    """
    # assert document dictionary structure
    expected_keys = set([
        crypto.ENC_JSON_KEY,
        crypto.ENC_SCHEME_KEY,
        crypto.ENC_METHOD_KEY,
        crypto.ENC_IV_KEY,
        crypto.MAC_KEY,
        crypto.MAC_METHOD_KEY,
    ])
    soledad_assert(expected_keys.issubset(set(doc_dict.keys())))

    ciphertext = binascii.a2b_hex(doc_dict[crypto.ENC_JSON_KEY])
    enc_scheme = doc_dict[crypto.ENC_SCHEME_KEY]
    enc_method = doc_dict[crypto.ENC_METHOD_KEY]
    enc_iv = doc_dict[crypto.ENC_IV_KEY]
    doc_mac = doc_dict[crypto.MAC_KEY]
    mac_method = doc_dict[crypto.MAC_METHOD_KEY]

    soledad_assert(enc_scheme == crypto.EncryptionSchemes.SYMKEY)

    _verify_doc_mac(
        doc_id, doc_rev, ciphertext, enc_scheme, enc_method,
        enc_iv, mac_method, secret, doc_mac)

    return decrypt_sym(ciphertext, key, method=enc_method, iv=enc_iv)


def is_symmetrically_encrypted(doc):
    """
    Return True if the document was symmetrically encrypted.

    :param doc: The document to check.
    :type doc: SoledadDocument

    :rtype: bool
    """
    if doc.content and crypto.ENC_SCHEME_KEY in doc.content:
        if doc.content[crypto.ENC_SCHEME_KEY] \
                == crypto.EncryptionSchemes.SYMKEY:
            return True
    return False


#
# Encrypt/decrypt pools of workers
#

class SyncEncryptDecryptPool(object):
    """
    Base class for encrypter/decrypter pools.
    """
    WORKERS = multiprocessing.cpu_count()

    def __init__(self, crypto, sync_db, write_lock):
        """
        Initialize the pool of encryption-workers.

        :param crypto: A SoledadCryto instance to perform the encryption.
        :type crypto: leap.soledad.crypto.SoledadCrypto

        :param sync_db: A database connection handle
        :type sync_db: pysqlcipher.dbapi2.Connection

        :param write_lock: a write lock for controlling concurrent access
                           to the sync_db
        :type write_lock: threading.Lock
        """
        self._pool = multiprocessing.Pool(self.WORKERS)
        self._crypto = crypto
        self._sync_db = sync_db
        self._sync_db_write_lock = write_lock

    def close(self):
        """
        Cleanly close the pool of workers.
        """
        logger.debug("Closing %s" % (self.__class__.__name__,))
        self._pool.close()
        try:
            self._pool.join()
        except Exception:
            pass

    def terminate(self):
        """
        Terminate the pool of workers.
        """
        logger.debug("Terminating %s" % (self.__class__.__name__,))
        self._pool.terminate()


def encrypt_doc_task(doc_id, doc_rev, content, key, secret):
    """
    Encrypt the content of the given document.

    :param doc_id: The document id.
    :type doc_id: str
    :param doc_rev: The document revision.
    :type doc_rev: str
    :param content: The serialized content of the document.
    :type content: str
    :param key: The encryption key.
    :type key: str
    :param secret: The Soledad storage secret (used for MAC auth).
    :type secret: str

    :return: A tuple containing the doc id, revision and encrypted content.
    :rtype: tuple(str, str, str)
    """
    encrypted_content = encrypt_docstr(
        content, doc_id, doc_rev, key, secret)
    return doc_id, doc_rev, encrypted_content


class SyncEncrypterPool(SyncEncryptDecryptPool):
    """
    Pool of workers that spawn subprocesses to execute the symmetric encryption
    of documents to be synced.
    """
    # TODO implement throttling to reduce cpu usage??
    WORKERS = multiprocessing.cpu_count()
    TABLE_NAME = "docs_tosync"
    FIELD_NAMES = "doc_id, rev, content"

    def encrypt_doc(self, doc, workers=True):
        """
        Symmetrically encrypt a document.

        :param doc: The document with contents to be encrypted.
        :type doc: SoledadDocument

        :param workers: Whether to defer the decryption to the multiprocess
                        pool of workers. Useful for debugging purposes.
        :type workers: bool
        """
        soledad_assert(self._crypto is not None, "need a crypto object")
        docstr = doc.get_json()
        key = self._crypto.doc_passphrase(doc.doc_id)
        secret = self._crypto.secret
        args = doc.doc_id, doc.rev, docstr, key, secret

        try:
            if workers:
                res = self._pool.apply_async(
                    encrypt_doc_task, args,
                    callback=self.encrypt_doc_cb)
            else:
                # encrypt inline
                res = encrypt_doc_task(*args)
                self.encrypt_doc_cb(res)

        except Exception as exc:
            logger.exception(exc)

    def encrypt_doc_cb(self, result):
        """
        Insert results of encryption routine into the local sync database.

        :param result: A tuple containing the doc id, revision and encrypted
                       content.
        :type result: tuple(str, str, str)
        """
        doc_id, doc_rev, content = result
        self.insert_encrypted_local_doc(doc_id, doc_rev, content)

    def insert_encrypted_local_doc(self, doc_id, doc_rev, content):
        """
        Insert the contents of the encrypted doc into the local sync
        database.

        :param doc_id: The document id.
        :type doc_id: str
        :param doc_rev: The document revision.
        :type doc_rev: str
        :param content: The serialized content of the document.
        :type content: str
        :param content: The encrypted document.
        :type content: str
        """
        # FIXME --- callback should complete immediately since otherwise the
        # thread which handles the results will get blocked
        # Right now we're blocking the dispatcher with the writes to sqlite.
        sql_del = "DELETE FROM '%s' WHERE doc_id=?" % (self.TABLE_NAME,)
        sql_ins = "INSERT INTO '%s' VALUES (?, ?, ?)" % (self.TABLE_NAME,)

        con = self._sync_db
        with self._sync_db_write_lock:
            con.execute(sql_del, (doc_id, ))
            con.execute(sql_ins, (doc_id, doc_rev, content))


def decrypt_doc_task(doc_id, doc_rev, content, gen, trans_id, key, secret):
    """
    Decrypt the content of the given document.

    :param doc_id: The document id.
    :type doc_id: str
    :param doc_rev: The document revision.
    :type doc_rev: str
    :param content: The encrypted content of the document.
    :type content: str
    :param gen: The generation corresponding to the modification of that
                document.
    :type gen: int
    :param trans_id: The transaction id corresponding to the modification of
                     that document.
    :type trans_id: str
    :param key: The encryption key.
    :type key: str
    :param secret: The Soledad storage secret (used for MAC auth).
    :type secret: str

    :return: A tuple containing the doc id, revision and encrypted content.
    :rtype: tuple(str, str, str)
    """
    decrypted_content = decrypt_doc_dict(
        content, doc_id, doc_rev, key, secret)
    return doc_id, doc_rev, decrypted_content, gen, trans_id


class SyncDecrypterPool(SyncEncryptDecryptPool):
    """
    Pool of workers that spawn subprocesses to execute the symmetric decryption
    of documents that were received.

    The decryption of the received documents is done in two steps:

        1. All the encrypted docs are collected, together with their generation
           and transaction-id
        2. The docs are enqueued for decryption. When completed, they are
           inserted following the generation order.
    """
    # TODO implement throttling to reduce cpu usage??
    TABLE_NAME = "docs_received"
    FIELD_NAMES = "doc_id, rev, content, gen, trans_id, encrypted"

    write_encrypted_lock = threading.Lock()

    def __init__(self, *args, **kwargs):
        """
        Initialize the decrypter pool, and setup a dict for putting the
        results of the decrypted docs until they are picked by the insert
        routine that gets them in order.

        :param insert_doc_cb: A callback for inserting received documents from
                              target. If not overriden, this will call u1db
                              insert_doc_from_target in synchronizer, which
                              implements the TAKE OTHER semantics.
        :type insert_doc_cb: function
        :param last_known_generation: Target's last known generation.
        :type last_known_generation: int
        """
        self._insert_doc_cb = kwargs.pop("insert_doc_cb")
        SyncEncryptDecryptPool.__init__(self, *args, **kwargs)
        self.source_replica_uid = None

    def set_source_replica_uid(self, source_replica_uid):
        """
        Set the source replica uid for this decrypter pool instance.

        :param source_replica_uid: The uid of the source replica.
        :type source_replica_uid: str
        """
        self.source_replica_uid = source_replica_uid

    def insert_encrypted_received_doc(self, doc_id, doc_rev, content,
                                      gen, trans_id):
        """
        Insert a received message with encrypted content, to be decrypted later
        on.

        :param doc_id: The Document ID.
        :type doc_id: str
        :param doc_rev: The Document Revision
        :param doc_rev: str
        :param content: the Content of the document
        :type content: str
        :param gen: the Document Generation
        :type gen: int
        :param trans_id: Transaction ID
        :type trans_id: str
        """
        docstr = json.dumps(content)
        sql_del = "DELETE FROM '%s' WHERE doc_id=?" % (self.TABLE_NAME,)
        sql_ins = "INSERT INTO '%s' VALUES (?, ?, ?, ?, ?, ?)" % (
            self.TABLE_NAME,)

        con = self._sync_db
        with self._sync_db_write_lock:
            con.execute(sql_del, (doc_id, ))
            con.execute(
                sql_ins,
                (doc_id, doc_rev, docstr, gen, trans_id, 1))

    def insert_received_doc(self, doc_id, doc_rev, content, gen, trans_id):
        """
        Insert a document that is not symmetrically encrypted.
        We store it in the staging area (the decrypted_docs dictionary) to be
        picked up in order as the preceding documents are decrypted.

        :param doc_id: The Document ID.
        :type doc_id: str
        :param doc_rev: The Document Revision
        :param doc_rev: str
        :param content: the Content of the document
        :type content: str
        :param gen: the Document Generation
        :type gen: int
        :param trans_id: Transaction ID
        :type trans_id: str
        """
        if not isinstance(content, str):
            content = json.dumps(content)
        sql_del = "DELETE FROM '%s' WHERE doc_id=?" % (
            self.TABLE_NAME,)
        sql_ins = "INSERT INTO '%s' VALUES (?, ?, ?, ?, ?, ?)" % (
            self.TABLE_NAME,)
        con = self._sync_db
        with self._sync_db_write_lock:
            con.execute(sql_del, (doc_id,))
            con.execute(
                sql_ins,
                (doc_id, doc_rev, content, gen, trans_id, 0))

    def delete_received_doc(self, doc_id, doc_rev):
        """
        Delete a received doc after it was inserted into the local db.

        :param doc_id: Document ID.
        :type doc_id: str
        :param doc_rev: Document revision.
        :type doc_rev: str
        """
        sql_del = "DELETE FROM '%s' WHERE doc_id=? AND rev=?" % (
            self.TABLE_NAME,)
        con = self._sync_db
        with self._sync_db_write_lock:
            con.execute(sql_del, (doc_id, doc_rev))

    def decrypt_doc(self, doc_id, rev, content, gen, trans_id,
                    source_replica_uid, workers=True):
        """
        Symmetrically decrypt a document.

        :param doc_id: The ID for the document with contents to be encrypted.
        :type doc: str
        :param rev: The revision of the document.
        :type rev: str
        :param content: The serialized content of the document.
        :type content: str
        :param gen: The generation corresponding to the modification of that
                    document.
        :type gen: int
        :param trans_id: The transaction id corresponding to the modification
                         of that document.
        :type trans_id: str
        :param source_replica_uid:
        :type source_replica_uid: str

        :param workers: Whether to defer the decryption to the multiprocess
                        pool of workers. Useful for debugging purposes.
        :type workers: bool
        """
        self.source_replica_uid = source_replica_uid

        # insert_doc_cb is a proxy object that gets updated with the right
        # insert function only when the sync_target invokes the sync_exchange
        # method. so, if we don't still have a non-empty callback, we refuse
        # to proceed.
        if sameProxiedObjects(self._insert_doc_cb.get(source_replica_uid),
                              None):
            logger.debug("Sync decrypter pool: no insert_doc_cb() yet.")
            return

        soledad_assert(self._crypto is not None, "need a crypto object")

        if len(content) == 0:
            # not encrypted payload
            return

        try:
            content = json.loads(content)
        except TypeError:
            logger.warning("Wrong type while decoding json: %s"
                           % repr(content))
            return

        key = self._crypto.doc_passphrase(doc_id)
        secret = self._crypto.secret
        args = doc_id, rev, content, gen, trans_id, key, secret

        try:
            if workers:
                # Ouch. This is sent to the workers asynchronously, so
                # we have no way of logging errors. We'd have to inspect
                # lingering results by querying successful / get() over them...
                # Or move the heck out of it to twisted.
                res = self._pool.apply_async(
                    decrypt_doc_task, args,
                    callback=self.decrypt_doc_cb)
            else:
                # decrypt inline
                res = decrypt_doc_task(*args)
                self.decrypt_doc_cb(res)

        except Exception as exc:
            logger.exception(exc)

    def decrypt_doc_cb(self, result):
        """
        Store the decryption result in the sync db from where it will later be
        picked by process_decrypted.

        :param result: A tuple containing the doc id, revision and encrypted
        content.
        :type result: tuple(str, str, str)
        """
        doc_id, rev, content, gen, trans_id = result
        logger.debug("Sync decrypter pool: decrypted doc %s: %s %s %s"
                     % (doc_id, rev, gen, trans_id))
        self.insert_received_doc(doc_id, rev, content, gen, trans_id)

    def get_docs_by_generation(self, encrypted=None):
        """
        Get all documents in the received table from the sync db,
        ordered by generation.

        :param encrypted: If not None, only return documents with encrypted
                          field equal to given parameter.
        :type encrypted: bool or None

        :return: list of doc_id, rev, generation, gen, trans_id
        :rtype: list
        """
        sql = "SELECT doc_id, rev, content, gen, trans_id, encrypted FROM %s" \
              % self.TABLE_NAME
        if encrypted is not None:
            sql += " WHERE encrypted = %d" % int(encrypted)
        sql += " ORDER BY gen ASC"
        return self._fetchall(sql)

    def get_insertable_docs_by_gen(self):
        """
        Return a list of non-encrypted documents ready to be inserted.
        """
        # here, we compare the list of all available docs with the list of
        # decrypted docs and find the longest common prefix between these two
        # lists. Note that the order of lists fetch matters: if instead we
        # first fetch the list of decrypted docs and then the list of all
        # docs, then some document might have been decrypted between these two
        # calls, and if it is just the right doc then it might not be caught
        # by the next loop.
        all_docs = self.get_docs_by_generation()
        decrypted_docs = self.get_docs_by_generation(encrypted=False)
        insertable = []
        for doc_id, rev, _, gen, trans_id, encrypted in all_docs:
            for next_doc_id, _, next_content, _, _, _ in decrypted_docs:
                if doc_id == next_doc_id:
                    content = next_content
                    insertable.append((doc_id, rev, content, gen, trans_id))
                else:
                    break
        return insertable

    def count_docs_in_sync_db(self, encrypted=None):
        """
        Count how many documents we have in the table for received docs.

        :param encrypted: If not None, return count of documents with
                          encrypted field equal to given parameter.
        :type encrypted: bool or None

        :return: The count of documents.
        :rtype: int
        """
        if self._sync_db is None:
            logger.warning("cannot return count with null sync_db")
            return
        sql = "SELECT COUNT(*) FROM %s" % (self.TABLE_NAME,)
        if encrypted is not None:
            sql += " WHERE encrypted = %d" % int(encrypted)
        res = self._fetchall(sql)
        if res:
            val = res.pop()
            return val[0]
        else:
            return 0

    def decrypt_received_docs(self):
        """
        Get all the encrypted documents from the sync database and dispatch a
        decrypt worker to decrypt each one of them.
        """
        docs_by_generation = self.get_docs_by_generation(encrypted=True)
        for doc_id, rev, content, gen, trans_id, _ \
                in filter(None, docs_by_generation):
            self.decrypt_doc(
                doc_id, rev, content, gen, trans_id, self.source_replica_uid)

    def process_decrypted(self):
        """
        Process the already decrypted documents, and insert as many documents
        as can be taken from the expected order without finding a gap.

        :return: Whether we have processed all the pending docs.
        :rtype: bool
        """
        # Acquire the lock to avoid processing while we're still
        # getting data from the syncing stream, to avoid InvalidGeneration
        # problems.
        with self.write_encrypted_lock:
            for doc_fields in self.get_insertable_docs_by_gen():
                self.insert_decrypted_local_doc(*doc_fields)
        remaining = self.count_docs_in_sync_db()
        return remaining == 0

    def insert_decrypted_local_doc(self, doc_id, doc_rev, content,
                                   gen, trans_id):
        """
        Insert the decrypted document into the local sqlcipher database.
        Makes use of the passed callback `return_doc_cb` passed to the caller
        by u1db sync.

        :param doc_id: The document id.
        :type doc_id: str
        :param doc_rev: The document revision.
        :type doc_rev: str
        :param content: The serialized content of the document.
        :type content: str
        :param gen: The generation corresponding to the modification of that
                    document.
        :type gen: int
        :param trans_id: The transaction id corresponding to the modification
                         of that document.
        :type trans_id: str
        """
        # could pass source_replica in params for callback chain
        insert_fun = self._insert_doc_cb[self.source_replica_uid]
        logger.debug("Sync decrypter pool: inserting doc in local db: "
                     "%s:%s %s" % (doc_id, doc_rev, gen))
        try:
            # convert deleted documents to avoid error on document creation
            if content == 'null':
                content = None
            doc = SoledadDocument(doc_id, doc_rev, content)
            gen = int(gen)
            insert_fun(doc, gen, trans_id)
        except Exception as exc:
            logger.error("Sync decrypter pool: error while inserting "
                         "decrypted doc into local db.")
            logger.exception(exc)

        else:
            # If no errors found, remove it from the received database.
            self.delete_received_doc(doc_id, doc_rev)

    def empty(self):
        """
        Empty the received docs table of the sync database.
        """
        sql = "DELETE FROM %s WHERE 1" % (self.TABLE_NAME,)
        self._sync_db.execute(sql)

    def _fetchall(self, *args, **kwargs):
        with self._sync_db:
            c = self._sync_db.cursor()
            c.execute(*args, **kwargs)
            return c.fetchall()