summaryrefslogtreecommitdiff
path: root/src/leap/common/keymanager/__init__.py
blob: 8db3b3cb9535023c9bdb6011d02cc3ff96c74512 (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
# -*- 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 httplib
import requests


from leap.common.check import leap_assert
from leap.common.keymanager.errors import (
    KeyNotFound,
    KeyAlreadyExists,
)
from leap.common.keymanager.keys import (
    build_key_from_dict,
)
from leap.common.keymanager.openpgp import (
    OpenPGPKey,
    OpenPGPScheme,
    encrypt_sym,
)


TAGS_INDEX = 'by-tags'
TAGS_AND_PRIVATE_INDEX = 'by-tags-and-private'
INDEXES = {
    TAGS_INDEX: ['tags'],
    TAGS_AND_PRIVATE_INDEX: ['tags', 'bool(private)'],
}


class KeyManager(object):

    def __init__(self, address, nickserver_url, soledad):
        """
        Initialize a Key Manager for user's C{address} with provider's
        nickserver reachable in C{url}.

        @param address: The address of the user of this Key Manager.
        @type address: str
        @param url: The URL of the nickserver.
        @type url: str
        @param soledad: A Soledad instance for local storage of keys.
        @type soledad: leap.soledad.Soledad
        """
        self._address = address
        self._nickserver_url = nickserver_url
        self._soledad = soledad
        self._wrapper_map = {
            OpenPGPKey: OpenPGPScheme(soledad),
            # other types of key will be added to this mapper.
        }
        self._init_indexes()

    #
    # utilities
    #

    def _key_class_from_type(self, ktype):
        """
        Return key class from string representation of key type.
        """
        return filter(
            lambda klass: str(klass) == ktype,
            self._wrapper_map).pop()

    def _init_indexes(self):
        """
        Initialize the database indexes.
        """
        # Ask the database for currently existing indexes.
        db_indexes = dict(self._soledad.list_indexes())
        # Loop through the indexes we expect to find.
        for name, expression in INDEXES.items():
            if name not in db_indexes:
                # The index does not yet exist.
                self._soledad.create_index(name, *expression)
                continue
            if expression == db_indexes[name]:
                # The index exists and is up to date.
                continue
            # The index exists but the definition is not what expected, so we
            # delete it and add the proper index expression.
            self._soledad.delete_index(name)
            self._soledad.create_index(name, *expression)

    def _get_dict_from_http_json(self, path):
        """
        Make a GET HTTP request and return a dictionary containing the
        response.
        """
        response = requests.get(self._nickserver_url+path)
        leap_assert(r.status_code == 200, 'Invalid response.')
        leap_assert(
            response.headers['content-type'].startswith('application/json')
                is True,
            'Content-type is not JSON.')
        return r.json()

    #
    # key management
    #

    def send_key(self, ktype, send_private=False, password=None):
        """
        Send user's key of type C{ktype} to provider.

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

        If C{send_private} is True, then the private key is encrypted with
        C{password} and sent to server in the same request, together with a
        hash string of user's address and password. The encrypted private key
        will be saved in the server in a way it is publicly retrievable
        through the hash string.

        @param address: The address bound to the key.
        @type address: str
        @param ktype: The type of the key.
        @type ktype: KeyType

        @raise httplib.HTTPException:
        @raise KeyNotFound: If the key was not found both locally and in
            keyserver.
        """
        # prepare the public key bound to address
        data = {
            'address': self._address,
            'keys': [
                json.loads(
                    self.get_key(
                        self._address, ktype, private=False).get_json()),
            ]
        }
        # prepare the private key bound to address
        if send_private:
            privkey = json.loads(
                self.get_key(self._address, ktype, private=True).get_json())
            privkey.key_data = encrypt_sym(data, passphrase)
            data['keys'].append(privkey)
        requests.put(
            self._nickserver_url + '/key/' + address,
            data=data,
            auth=(self._address, None))  # TODO: replace for token-based auth.

    def get_key(self, address, ktype, private=False, fetch_remote=True):
        """
        Return a key of type C{ktype} bound to C{address}.

        First, search for the key in local storage. If it is not available,
        then try to fetch from nickserver.

        @param address: The address bound to the key.
        @type address: str
        @param ktype: The type of the key.
        @type ktype: KeyType
        @param private: Look for a private key instead of a public one?
        @type private: bool

        @return: A key of type C{ktype} bound to C{address}.
        @rtype: EncryptionKey
        @raise KeyNotFound: If the key was not found both locally and in
            keyserver.
        """
        leap_assert(
            ktype in self._wrapper_map,
            'Unkown key type: %s.' % str(ktype))
        try:
            return self._wrapper_map[ktype].get_key(address, private=private)
        except KeyNotFound:
            if fetch_remote is False:
                raise
            # fetch keys from server and discard unwanted types.
            keys = filter(lambda k: isinstance(k, ktype),
                          self.fetch_keys_from_server(address))
            if len(keys) is 0:
                raise KeyNotFound()
            leap_assert(
                len(keys) == 1,
                'Got more than one key of type %s for %s.' %
                (str(ktype), address))
            self._wrapper_map[ktype].put_key(keys[0])
            return key

    def fetch_keys_from_server(self, address):
        """
        Fetch keys bound to C{address} from nickserver.

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

        @return: A list of keys bound to C{address}.
        @rtype: list of EncryptionKey
        @raise KeyNotFound: If the key was not found on nickserver.
        @raise httplib.HTTPException:
        """
        keydata = self._get_dict_from_http_json('/key/%s' % address)
        leap_assert(
            keydata['address'] == address,
            "Fetched key for wrong address.")
        keys = []
        for key in keydata['keys']:
            keys.append(
                build_key_from_dict(
                    self._key_class_from_type(key['type']),
                    address,
                    key))
        return keys

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

        @return: A list with all keys in local db.
        @rtype: list
        """
        return map(
            lambda doc: build_key_from_dict(
                self._key_class_from_type(doc.content['type']),
                doc.content['address'],
                doc.content),
            self._soledad.get_from_index(
                TAGS_AND_PRIVATE_INDEX,
                'keymanager-key',
                '1' if private else '0'))

    def refresh_keys(self):
        """
        Fetch keys from nickserver and update them locally.
        """
        addresses = set(map(
            lambda doc: doc.address,
            self.get_all_keys_in_local_db(False)))
        for address in addresses:
            for key in self.fetch_keys_from_server(address):
                self._wrapper_map[key.__class__].put_key(key)

    def gen_key(self, ktype):
        """
        Generate a key of type C{ktype} bound to the user's address.

        @param ktype: The type of the key.
        @type ktype: KeyType

        @return: The generated key.
        @rtype: EncryptionKey
        """
        return self._wrapper_map[ktype].gen_key(self._address)