summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/keymanager/__init__.py
blob: b2cf1c991439423bcb12743347c85675e93492a5 (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
# -*- coding: utf-8 -*-
# __init__.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/>.
"""
Key Manager is a Nicknym agent for LEAP client.
"""
import fileinput
import tempfile

from urlparse import urlparse

from twisted.logger import Logger
from twisted.internet import defer, task, reactor

from leap.common import ca_bundle
from leap.common.http import HTTPClient
from leap.common.events import emit_async, catalog

from leap.bitmask.keymanager import errors as keymanager_errors
from leap.bitmask.keymanager.errors import KeyNotFound
from leap.bitmask.keymanager.nicknym import Nicknym
from leap.bitmask.keymanager.refresher import RandomRefreshPublicKey
from leap.bitmask.keymanager.validation import ValidationLevels, can_upgrade
from leap.bitmask.keymanager.openpgp import OpenPGPScheme


class KeyManager(object):
    #
    # server's key storage constants
    #

    log = Logger()

    def __init__(self, address, nickserver_uri, soledad, token=None,
                 ca_cert_path=None, api_uri=None, api_version=None, uid=None,
                 gpgbinary=None, combined_ca_bundle=None):
        """
        Initialize a Key Manager for user's C{address} with provider's
        nickserver reachable in C{nickserver_uri}.

        :param address: The email address of the user of this Key Manager.
        :type address: str
        :param nickserver_uri: The URI of the nickserver.
        :type nickserver_uri: str
        :param soledad: A Soledad instance for local storage of keys.
        :type soledad: leap.soledad.Soledad
        :param token: The token for interacting with the webapp API.
        :type token: str
        :param ca_cert_path: The path to the CA certificate.
        :type ca_cert_path: str
        :param api_uri: The URI of the webapp API.
        :type api_uri: str
        :param api_version: The version of the webapp API.
        :type api_version: str
        :param uid: The user's UID.
        :type uid: str
        :param gpgbinary: Name for GnuPG binary executable.
        :type gpgbinary: C{str}
        """
        self._address = address
        self._nickserver_uri = nickserver_uri
        self._soledad = soledad
        self._token = token
        self.ca_cert_path = ca_cert_path
        self.api_uri = api_uri
        self.api_version = api_version
        self.uid = uid
        create = self._create_combined_bundle_file
        try:
            self._combined_ca_bundle = combined_ca_bundle or create()
        except Exception:
            self.log.warn('Error while creating combined ca bundle')
            self._combined_ca_bundle = ''

        self._async_client = HTTPClient(self._combined_ca_bundle)
        self._nicknym = Nicknym(self._nickserver_uri,
                                self._ca_cert_path, self._token)
        self.refresher = None
        self._init_gpg(soledad, gpgbinary)

    #
    # utilities
    #

    def _init_gpg(self, soledad, gpgbinary):
        self._openpgp = OpenPGPScheme(soledad, gpgbinary=gpgbinary)

    def start_refresher(self):
        self.refresher = RandomRefreshPublicKey(self._openpgp, self)
        self.refresher.start()

    def stop_refresher(self):
        self.refresher.stop()

    def _create_combined_bundle_file(self):
        leap_ca_bundle = ca_bundle.where()

        if self._ca_cert_path == leap_ca_bundle:
            return self._ca_cert_path  # don't merge file with itself
        elif not self._ca_cert_path:
            return leap_ca_bundle

        tmp_file = tempfile.NamedTemporaryFile(delete=False)

        with open(tmp_file.name, 'w') as fout:
            fin = fileinput.input(files=(leap_ca_bundle, self._ca_cert_path))
            for line in fin:
                fout.write(line)
            fin.close()

        return tmp_file.name

    @defer.inlineCallbacks
    def _get_with_combined_ca_bundle(self, uri, data=None):
        """
        Send a GET request to C{uri} containing C{data}.

        Instead of using the ca_cert provided on construction time, this
        version also uses the default certificates shipped with leap.common

        :param uri: The URI of the request.
        :type uri: str
        :param data: The body of the request.
        :type data: dict, str or file

        :return: A deferred that will be fired with the GET response
        :rtype: Deferred
        """
        try:
            content = yield self._async_client.request(str(uri), 'GET')
        except Exception as e:
            self.log.warn("There was a problem fetching key: %s" % (e,))
            raise keymanager_errors.KeyNotFound(uri)
        if not content:
            raise keymanager_errors.KeyNotFound(uri)
        defer.returnValue(content)

    #
    # key management
    #

    @defer.inlineCallbacks
    def send_key(self):
        """
        Send user's key to provider.

        Public key bound to user's is sent to provider, which will
        replace any prior keys for the same address in its database.

        :return: A Deferred which fires when the key is sent, or which fails
                 with KeyNotFound if the key was not found in local database.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        if not self.token:
            self.log.debug(
                'Token not available, scheduling '
                'a new key sending attempt...')
            yield task.deferLater(reactor, 5, self.send_key)

        self.log.info('Sending public key to server')
        key = yield self.get_key(self._address, fetch_remote=False)
        yield self._nicknym.put_key(self.uid, key.key_data,
                                    self._api_uri, self._api_version)
        emit_async(catalog.KEYMANAGER_DONE_UPLOADING_KEYS,
                   self._address)
        self.log.info('Key sent to server')
        defer.returnValue(key)

    @defer.inlineCallbacks
    def _fetch_keys_from_server_and_store_local(self, address):
        """
        Fetch keys  from nickserver and insert them in locale database.

        :param address: The address bound to the keys.
        :type address: str

        :return: A Deferred which fires when the key is in the storage,
                     or which fails with KeyNotFound if the key was not
                     found on nickserver.
        :rtype: Deferred

        """
        raw_key = yield self._nicknym.fetch_key_with_address(address)

        # nicknym server is authoritative for its own domain,
        # for other domains the key might come from key servers.
        validation_level = ValidationLevels.Weak_Chain
        _, domain = _split_email(address)
        if (domain == _get_domain(self._nickserver_uri)):
            validation_level = ValidationLevels.Provider_Trust

        yield self.put_raw_key(
            raw_key, address=address, validation=validation_level)

    @defer.inlineCallbacks
    def get_inactive_private_keys(self):
        """
        Return all inactive private keys bound to address, that are
        stored locally.
        This can be used to attempt decryption from multiple keys.

        :return: A Deferred which fires the list of inactive keys sorted
                 according to their expiry dates.
        :rtype: Deferred
        """
        all_keys = yield self.get_all_keys(private=True)
        inactive_keys = filter(lambda _key: not _key.is_active(), all_keys)

        inactive_keys = \
            sorted(inactive_keys, key=lambda _key: _key.expiry_date)
        defer.returnValue(inactive_keys)

    def get_key(self, address, private=False, fetch_remote=True):
        """
        Return a key bound to address.

        First, search for the key in local storage. When it is available
        locally but is expired or when it is not available locally,
        then a fetch from nickserver is tried.

        :param address: The address bound to the key.
        :type address: str
        :param private: Look for a private key instead of a public one?
        :type private: bool
        :param fetch_remote: If key not found in local storage try to fetch
                             from nickserver
        :type fetch_remote: bool

        :return: A Deferred which fires with an EncryptionKey bound to address,
                 or which fails with KeyNotFound if no key was found neither
                 locally or in keyserver or fail with KeyVersionError if the
                 key has a format not supported by this version of KeyManager
                 or KeyNotValidUpgrade if the key is renewed remotely but fails
                 the validation rule
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        self.log.debug('Getting key for %s' % (address,))
        emit_async(catalog.KEYMANAGER_LOOKING_FOR_KEY, address)

        def key_found(key):
            emit_async(catalog.KEYMANAGER_KEY_FOUND, address)
            return key

        def ensure_valid(key):
            if key.is_expired():
                logger.info('Found expired key for %s.' % self._address)
                return _fetch_remotely(key)
            key_found(key)
            return key

        def key_not_found(failure):
            if not failure.check(keymanager_errors.KeyNotFound):
                return failure

            emit_async(catalog.KEYMANAGER_KEY_NOT_FOUND, address)
            return _fetch_remotely(failure)

        def _fetch_remotely(passthru):
            # we will only try to fetch a key from nickserver if fetch_remote
            # is True and the key is not private.
            if fetch_remote is False or private is True:
                return passthru

            logger.debug('Fetching remotely key for %s.' % self._address)
            emit_async(catalog.KEYMANAGER_LOOKING_FOR_KEY, address)
            d = self._fetch_keys_from_server_and_store_local(address)
            d.addCallback(
                lambda _: self._openpgp.get_key(address, private=False))
            d.addCallback(key_found)
            return d

        # return key if it exists in local database
        d = self._openpgp.get_key(address, private=private)
        d.addCallbacks(ensure_valid, key_not_found)
        return d

    @defer.inlineCallbacks
    def fetch_key_fingerprint(self, address, fingerprint):
        """
        Fetch a key from the key servers by fingerprint.

        It will replace any key assigned to the address in the keyring and have
        validation level Fingerprint.

        :param address: The address bound to the key.
        :type address: str
        :param fingerprint: The fingerprint of the key to fetch.
        :type fingerprint: str

        :return: A Deferred which fires with an EncryptionKey fetched,
                 or which fails with KeyNotFound if no key was found in the
                 keyserver for this fingerprint.
        :rtype: Deferred
        """
        key_data = yield self._nicknym.fetch_key_with_fingerprint(fingerprint)
        key, _ = self._openpgp.parse_key(key_data, address)
        key.validation = ValidationLevels.Fingerprint

        if key.fingerprint != fingerprint:
            raise keymanager_errors.KeyNotFound("Got wrong fingerprint")

        try:
            old_key = yield self._openpgp.get_key(address)
            if old_key.fingerprint == key.fingerprint:
                key.last_audited_at = old_key.last_audited_at
                key.encr_used = old_key.encr_used
                key.sign_used = old_key.sign_used
        except keymanager_errors.KeyNotFound:
            pass

        yield self._openpgp.put_key(key)
        defer.returnValue(key)

    def get_all_keys(self, private=False):
        """
        Return all keys stored in local database.

        :param private: Include private keys
        :type private: bool

        :return: A Deferred which fires with a list of all keys in local db.
        :rtype: Deferred
        """
        return self._openpgp.get_all_keys(private)

    def gen_key(self):
        """
        Generate a key bound to the user's address.

        :return: A Deferred which fires with the generated EncryptionKey.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        def signal_finished(key):
            self.log.info('Key generated for %s' % self._address)
            emit_async(
                catalog.KEYMANAGER_FINISHED_KEY_GENERATION, self._address)
            return key

        emit_async(catalog.KEYMANAGER_STARTED_KEY_GENERATION, self._address)

        d = self._openpgp.gen_key(self._address)
        d.addCallback(signal_finished)
        return d

    @defer.inlineCallbacks
    def regenerate_key(self):
        """
        Regenerate a key bound to the user's address.

        :return: A Deferred which fires with the generated EncryptionKey.
        :rtype: Deferred
        """

        self.log.info('Regenerating key for %s.' % self._address)

        new_key = yield self._openpgp.regenerate_key(self._address)
        yield self._openpgp.reset_all_keys_sign_used()

        defer.returnValue(new_key)

    #
    # Setters/getters
    #

    def _get_token(self):
        return self._token

    def _set_token(self, token):
        self._token = token
        self._nicknym.token = token

    token = property(
        _get_token, _set_token, doc='The session token.')

    def _get_ca_cert_path(self):
        return self._ca_cert_path

    def _set_ca_cert_path(self, ca_cert_path):
        self._ca_cert_path = ca_cert_path

    ca_cert_path = property(
        _get_ca_cert_path, _set_ca_cert_path,
        doc='The path to the CA certificate.')

    def _get_api_uri(self):
        return self._api_uri

    def _set_api_uri(self, api_uri):
        self._api_uri = api_uri

    api_uri = property(
        _get_api_uri, _set_api_uri, doc='The webapp API URI.')

    def _get_api_version(self):
        return self._api_version

    def _set_api_version(self, api_version):
        self._api_version = api_version

    api_version = property(
        _get_api_version, _set_api_version, doc='The webapp API version.')

    def _get_uid(self):
        return self._uid

    def _set_uid(self, uid):
        self._uid = uid

    uid = property(
        _get_uid, _set_uid, doc='The uid of the user.')

    #
    # encrypt/decrypt and sign/verify API
    #

    def encrypt(self, data, address, passphrase=None, sign=None,
                cipher_algo='AES256', fetch_remote=True):
        """
        Encrypt data with the public key bound to address and sign with with
        the private key bound to sign address.

        :param data: The data to be encrypted.
        :type data: str
        :param address: The address to encrypt it for.
        :type address: str
        :param passphrase: The passphrase for the secret key used for the
                           signature.
        :type passphrase: str
        :param sign: The address to be used for signature.
        :type sign: str
        :param cipher_algo: The cipher algorithm to use.
        :type cipher_algo: str
        :param fetch_remote: If key is not found in local storage try to fetch
                             from nickserver
        :type fetch_remote: bool

        :return: A Deferred which fires with the encrypted data as str, or
                 which fails with KeyNotFound if no keys were found neither
                 locally or in keyserver or fails with KeyVersionError if the
                 key format is not supported or fails with EncryptError if
                 failed encrypting for some reason.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        @defer.inlineCallbacks
        def encrypt(keys):
            pubkey, signkey = keys
            encrypted = yield self._openpgp.encrypt(
                data, pubkey, passphrase, sign=signkey,
                cipher_algo=cipher_algo)
            if not pubkey.encr_used:
                pubkey.encr_used = True
                yield self._openpgp.put_key(pubkey)
            defer.returnValue(encrypted)

        dpub = self.get_key(address, private=False,
                            fetch_remote=fetch_remote)
        dpriv = defer.succeed(None)
        if sign is not None:
            dpriv = self.get_key(sign, private=True)
        d = defer.gatherResults([dpub, dpriv], consumeErrors=True)
        d.addCallbacks(encrypt, self._extract_first_error)
        return d

    def decrypt(self, data, address, passphrase=None, verify=None,
                fetch_remote=True):
        """
        Decrypt data using private key from address and verify with public key
        bound to verify address. If the decryption using the active private
        key fails, then decryption with inactive keys, if any, is recursively
        tried.

        :param data: The data to be decrypted.
        :type data: str
        :param address: The address to whom data was encrypted.
        :type address: str
        :param passphrase: The passphrase for the secret key used for
                           decryption.
        :type passphrase: str
        :param verify: The address to be used for signature.
        :type verify: str
        :param fetch_remote: If key for verify not found in local storage try
                             to fetch from nickserver
        :type fetch_remote: bool

        :return: A Deferred which fires with:
            * (decripted str, signing key) if validation works
            * (decripted str, KeyNotFound) if signing key not found
            * (decripted str, InvalidSignature) if signature is invalid
            * KeyNotFound failure if private key not found
            * DecryptError failure if decription failed
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """

        @defer.inlineCallbacks
        def _decrypt(keys):
            pubkey, privkey = keys
            decrypted, signed = yield self._openpgp.decrypt(
                data, privkey, passphrase=passphrase, verify=pubkey)
            if pubkey is None:
                signature = keymanager_errors.KeyNotFound(verify)
            elif signed:
                signature = pubkey
                if not pubkey.sign_used:
                    pubkey.sign_used = True
                    yield self._openpgp.put_key(pubkey)
                    defer.returnValue((decrypted, signature))
            else:
                signature = keymanager_errors.InvalidSignature(
                    'Failed to verify signature with key %s' %
                    (pubkey.fingerprint,))
            defer.returnValue((decrypted, signature))

        @defer.inlineCallbacks
        def decrypt_with_inactive_keys(inactive_keys, verify_key,
                                       original_decrypt_err):
            if not inactive_keys:
                # when there are no more keys to go through
                raise original_decrypt_err

            try:
                inactive_key = inactive_keys.pop()
                result = yield _decrypt([verify_key, inactive_key])
            except keymanager_errors.DecryptError:
                result = yield decrypt_with_inactive_keys(inactive_keys,
                                                          verify_key,
                                                          original_decrypt_err)
            defer.returnValue(result)

        @defer.inlineCallbacks
        def decrypt(keys):
            try:
                result = yield _decrypt(keys)
            except keymanager_errors.DecryptError as e:
                verify_key, active_key = keys
                inactive_keys = yield self.get_inactive_private_keys()
                result = yield decrypt_with_inactive_keys(inactive_keys,
                                                          verify_key, e)
            defer.returnValue(result)

        dpriv = self.get_key(address, private=True)
        dpub = defer.succeed(None)
        if verify is not None:
            dpub = self.get_key(verify, private=False,
                                fetch_remote=fetch_remote)
            dpub.addErrback(lambda f: None if f.check(
                keymanager_errors.KeyNotFound) else f)
        d = defer.gatherResults([dpub, dpriv], consumeErrors=True)
        d.addCallbacks(decrypt, self._extract_first_error)
        return d

    def _extract_first_error(self, failure):
        return failure.value.subFailure

    def sign(self, data, address, digest_algo='SHA512', clearsign=False,
             detach=True, binary=False):
        """
        Sign data with private key bound to address.

        :param data: The data to be signed.
        :type data: str
        :param address: The address to be used to sign.
        :type address: EncryptionKey
        :param digest_algo: The hash digest to use.
        :type digest_algo: str
        :param clearsign: If True, create a cleartext signature.
        :type clearsign: bool
        :param detach: If True, create a detached signature.
        :type detach: bool
        :param binary: If True, do not ascii armour the output.
        :type binary: bool

        :return: A Deferred which fires with the signed data as str or fails
                 with KeyNotFound if no key was found neither locally or in
                 keyserver or fails with SignFailed if there was any error
                 signing.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """

        def sign(privkey):
            return self._openpgp.sign(
                data, privkey, digest_algo=digest_algo, clearsign=clearsign,
                detach=detach, binary=binary)

        d = self.get_key(address, private=True)
        d.addCallback(sign)
        return d

    def verify(self, data, address, detached_sig=None,
               fetch_remote=True):
        """
        Verify signed data with private key bound to address, eventually using
        detached_sig.

        :param data: The data to be verified.
        :type data: str
        :param address: The address to be used to verify.
        :type address: EncryptionKey
        :param detached_sig: A detached signature. If given, C{data} is
                             verified using this detached signature.
        :type detached_sig: str
        :param fetch_remote: If key for verify not found in local storage try
                             to fetch from nickserver
        :type fetch_remote: bool

        :return: A Deferred which fires with the signing EncryptionKey if
                 signature verifies, or which fails with InvalidSignature if
                 signature don't verifies or fails with KeyNotFound if no key
                 was found neither locally or in keyserver.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        def verify(pubkey):
            signed = self._openpgp.verify(
                data, pubkey, detached_sig=detached_sig)
            if signed:
                if not pubkey.sign_used:
                    pubkey.sign_used = True
                    d = self._openpgp.put_key(pubkey)
                    d.addCallback(lambda _: pubkey)
                    return d
                return pubkey
            else:
                raise keymanager_errors.InvalidSignature(
                    'Failed to verify signature with key %s' %
                    (pubkey.fingerprint,))

        d = self.get_key(address, private=False,
                         fetch_remote=fetch_remote)
        d.addCallback(verify)
        return d

    def delete_key(self, key):
        """
        Remove key from storage.

        :param key: The key to be removed.
        :type key: EncryptionKey

        :return: A Deferred which fires when the key is deleted, or which fails
                 KeyNotFound if the key was not found on local storage.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        return self._openpgp.delete_key(key)

    def put_key(self, key):
        """
        Put key bound to address in local storage.

        :param key: The key to be stored
        :type key: EncryptionKey

        :return: A Deferred which fires when the key is in the storage, or
                 which fails with KeyNotValidUpdate if a key with the same
                 uid exists and the new one is not a valid update for it.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        def old_key_not_found(failure):
            if failure.check(keymanager_errors.KeyNotFound):
                return None
            else:
                return failure

        def check_upgrade(old_key):
            if key.private or can_upgrade(key, old_key):
                return self._openpgp.put_key(key)
            else:
                raise keymanager_errors.KeyNotValidUpgrade(
                    "Key %s can not be upgraded by new key %s"
                    % (old_key.fingerprint, key.fingerprint))

        d = self._openpgp.get_key(key.address, private=key.private)
        d.addErrback(old_key_not_found)
        d.addCallback(check_upgrade)
        return d

    @defer.inlineCallbacks
    def put_raw_key(self, key, address,
                    validation=ValidationLevels.Weak_Chain):
        """
        Put raw key bound to address in local storage.

        :param key: The key to be stored
        :type key: str
        :param address: address for which this key will be active
        :type address: str
        :param validation: validation level for this key
                           (default: 'Weak_Chain')
        :type validation: ValidationLevels

        :return: A Deferred which fires when the key is in the storage, or
                 which fails with KeyAddressMismatch if address doesn't match
                 any uid on the key or fails with KeyNotFound if no OpenPGP
                 material was found in key or fails with KeyNotValidUpdate if a
                 key with the same uid exists and the new one is not a valid
                 update for it.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """
        pubkey, privkey = self._openpgp.parse_key(key, address)

        if pubkey is None:
            raise keymanager_errors.KeyNotFound(key)

        if address == self._address and not privkey:
            try:
                existing = yield self.get_key(address, fetch_remote=False)
            except KeyNotFound:
                existing = None
            if (existing is None or
                    pubkey.fingerprint != existing.fingerprint):
                raise keymanager_errors.KeyNotValidUpgrade(
                    "Cannot update your %s key without the private part"
                    % (address,))

        pubkey.validation = validation
        yield self.put_key(pubkey)
        if privkey is not None:
            yield self.put_key(privkey)

        if address == self._address:
            yield self.send_key()

    @defer.inlineCallbacks
    def fetch_key(self, address, uri, validation=ValidationLevels.Weak_Chain):
        """
        Fetch a public key bound to address from the network and put it in
        local storage.

        :param address: The email address of the key.
        :type address: str
        :param uri: The URI of the key.
        :type uri: str
        :param validation: validation level for this key
                           (default: 'Weak_Chain')
        :type validation: ValidationLevels

        :return: A Deferred which fires when the key is in the storage, or
                 which fails with KeyNotFound: if not valid key on uri or fails
                 with KeyAddressMismatch if address doesn't match any uid on
                 the key or fails with KeyNotValidUpdate if a key with the same
                 uid exists and the new one is not a valid update for it.
        :rtype: Deferred

        :raise UnsupportedKeyTypeError: if invalid key type
        """

        self.log.info('Fetch key for %s from %s' % (address, uri))
        key_content = yield self._get_with_combined_ca_bundle(uri)

        # XXX parse binary keys
        pubkey, _ = self._openpgp.parse_key(key_content, address)
        if pubkey is None:
            raise keymanager_errors.KeyNotFound(uri)

        pubkey.validation = validation
        yield self.put_key(pubkey)

    @defer.inlineCallbacks
    def extend_key_expiration(self, validity='1y', passphrase=None):
        """
        extend the expiration date of the key pair bound to the user's address
        by the validity period, from the key's creation date.

        :param validity: new validity from creation date 'n','nw','nm' or 'ny'
                        where n is a number
        :type validity: str

        :return: The updated secret key, with new expiry date
        :rtype: OpenPGPKey

        :raise KeyExpiryExtensionError: if invalid validity period
        """
        my_secret_key = yield self.get_key(self._address, private=True)
        renewed_key = yield self._openpgp.extend_key(my_secret_key, validity,
                                                     passphrase)
        yield self._openpgp.reset_all_keys_sign_used()
        defer.returnValue(renewed_key)


def _split_email(address):
    """
    Split username and domain from an email address

    :param address: an email address
    :type address: str

    :return: username and domain from the email address
    :rtype: (str, str)
    """
    if address.count("@") != 1:
        return None
    return address.split("@")


def _get_domain(url):
    """
    Get the domain from an url

    :param url: an url
    :type url: str

    :return: the domain part of the url
    :rtype: str
    """
    return urlparse(url).hostname