summaryrefslogtreecommitdiff
path: root/src/leap/services/eip/providerbootstrapper.py
blob: f1a917f0a1995139273b4b28eefd275b277672c1 (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
# -*- coding: utf-8 -*-
# providerbootstrapper.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/>.

"""
Provider bootstrapping
"""

import requests
import logging
import socket
import os
import errno

from OpenSSL import crypto
from PySide import QtGui, QtCore

from leap.config.providerconfig import ProviderConfig
from leap.util.check import leap_assert, leap_assert_type
from leap.util.checkerthread import CheckerThread
from leap.util.files import check_and_fix_urw_only, get_mtime

logger = logging.getLogger(__name__)


class ProviderBootstrapper(QtCore.QObject):
    """
    Given a provider URL performs a series of checks and emits signals
    after they are passed.
    If a check fails, the subsequent checks are not executed
    """

    PASSED_KEY = "passed"
    ERROR_KEY = "error"

    IDLE_SLEEP_INTERVAL = 100

    # All dicts returned are of the form
    # {"passed": bool, "error": str}
    name_resolution = QtCore.Signal(dict)
    https_connection = QtCore.Signal(dict)
    download_provider_info = QtCore.Signal(dict)

    download_ca_cert = QtCore.Signal(dict)
    check_ca_fingerprint = QtCore.Signal(dict)
    check_api_certificate = QtCore.Signal(dict)

    def __init__(self):
        QtCore.QObject.__init__(self)

        # **************************************************** #
        # Dependency injection helpers, override this for more
        # granular testing
        self._fetcher = requests
        # **************************************************** #

        self._session = self._fetcher.session()
        self._domain = None
        self._provider_config = None
        self._download_if_needed = False

    def _check_name_resolution(self):
        """
        Checks that the name resolution for the provider name works

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """

        leap_assert(self._domain, "Cannot check DNS without a domain")

        logger.debug("Checking name resolution for %s" % (self._domain))

        name_resolution_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        # We don't skip this check, since it's basic for the whole
        # system to work
        try:
            socket.gethostbyname(self._domain)
            name_resolution_data[self.PASSED_KEY] = True
        except socket.gaierror as e:
            name_resolution_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting name_resolution %s" % (name_resolution_data,))
        self.name_resolution.emit(name_resolution_data)

        return name_resolution_data[self.PASSED_KEY]

    def _check_https(self):
        """
        Checks that https is working and that the provided certificate
        checks out

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """

        leap_assert(self._domain, "Cannot check HTTPS without a domain")

        logger.debug("Checking https for %s" % (self._domain))

        https_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        # We don't skip this check, since it's basic for the whole
        # system to work

        try:
            res = self._session.get("https://%s" % (self._domain,))
            res.raise_for_status()
            https_data[self.PASSED_KEY] = True
        except Exception as e:
            https_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting https_connection %s" % (https_data,))
        self.https_connection.emit(https_data)

        return https_data[self.PASSED_KEY]

    def _download_provider_info(self):
        """
        Downloads the provider.json defition

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """
        leap_assert(self._domain,
                    "Cannot download provider info without a domain")

        logger.debug("Downloading provider info for %s" % (self._domain))

        download_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        try:
            headers = {}
            mtime = get_mtime(os.path.join(ProviderConfig()
                                           .get_path_prefix(),
                                           "leap",
                                           "providers",
                                           self._domain,
                                           "provider.json"))
            if self._download_if_needed and mtime:
                headers['if-modified-since'] = mtime

            res = self._session.get("https://%s/%s" % (self._domain,
                                                       "provider.json"),
                                    headers=headers)
            res.raise_for_status()

            # Not modified
            if res.status_code == 304:
                logger.debug("Provider definition has not been modified")
            else:
                provider_definition = res.content

                provider_config = ProviderConfig()
                provider_config.load(data=provider_definition)
                provider_config.save(["leap",
                                      "providers",
                                      self._domain,
                                      "provider.json"])

            download_data[self.PASSED_KEY] = True
        except Exception as e:
            download_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting download_provider_info %s" % (download_data,))
        self.download_provider_info.emit(download_data)

        return download_data[self.PASSED_KEY]

    def run_provider_select_checks(self, checker,
                                   domain, download_if_needed=False):
        """
        Populates the check queue

        @param domain: domain to check
        @type domain: str
        @param download_if_needed: if True, makes the checks do not
        overwrite already downloaded data
        @type download_if_needed: bool

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """
        leap_assert(domain and len(domain) > 0, "We need a domain!")

        self._domain = domain
        self._download_if_needed = download_if_needed

        checker.add_checks([
            self._check_name_resolution,
            self._check_https,
            self._download_provider_info
        ])

    def _should_proceed_cert(self):
        """
        Returns False if the certificate already exists for the given
        provider. True otherwise

        @rtype: bool
        """
        leap_assert(self._provider_config, "We need a provider config!")

        if not self._download_if_needed:
            return True

        return not os.path.exists(self._provider_config
                                  .get_ca_cert_path(about_to_download=True))

    def _download_ca_cert(self):
        """
        Downloads the CA cert that is going to be used for the api URL

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """

        leap_assert(self._provider_config, "Cannot download the ca cert "
                    "without a provider config!")

        logger.debug("Downloading ca cert for %s at %s" %
                     (self._domain, self._provider_config.get_ca_cert_uri()))

        download_ca_cert_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        if not self._should_proceed_cert():
            try:
                check_and_fix_urw_only(
                    self._provider_config
                    .get_ca_cert_path(about_to_download=True))
                download_ca_cert_data[self.PASSED_KEY] = True
            except Exception as e:
                download_ca_cert_data[self.PASSED_KEY] = False
                download_ca_cert_data[self.ERROR_KEY] = "%s" % (e,)
            self.download_ca_cert.emit(download_ca_cert_data)
            return download_ca_cert_data[self.PASSED_KEY]

        try:
            res = self._session.get(self._provider_config.get_ca_cert_uri())
            res.raise_for_status()

            cert_path = self._provider_config.get_ca_cert_path(
                about_to_download=True)

            cert_dir = os.path.dirname(cert_path)

            try:
                os.makedirs(cert_dir)
            except OSError as e:
                if e.errno == errno.EEXIST and os.path.isdir(cert_dir):
                    pass
                else:
                    raise

            with open(cert_path, "w") as f:
                f.write(res.content)

            check_and_fix_urw_only(cert_path)

            download_ca_cert_data[self.PASSED_KEY] = True
        except Exception as e:
            download_ca_cert_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting download_ca_cert %s" % (download_ca_cert_data,))
        self.download_ca_cert.emit(download_ca_cert_data)

        return download_ca_cert_data[self.PASSED_KEY]

    def _check_ca_fingerprint(self):
        """
        Checks the CA cert fingerprint against the one provided in the
        json definition

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """
        leap_assert(self._provider_config, "Cannot check the ca cert "
                    "without a provider config!")

        logger.debug("Checking ca fingerprint for %s and cert %s" %
                     (self._domain,
                      self._provider_config.get_ca_cert_path()))

        check_ca_fingerprint_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        if not self._should_proceed_cert():
            check_ca_fingerprint_data[self.PASSED_KEY] = True
            self.check_ca_fingerprint.emit(check_ca_fingerprint_data)
            return True

        try:
            parts = self._provider_config.get_ca_cert_fingerprint().split(":")
            leap_assert(len(parts) == 2, "Wrong fingerprint format")

            method = parts[0].strip()
            fingerprint = parts[1].strip()
            cert_data = None
            with open(self._provider_config.get_ca_cert_path()) as f:
                cert_data = f.read()

            leap_assert(len(cert_data) > 0, "Could not read certificate data")

            x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
            digest = x509.digest(method).replace(":", "").lower()

            leap_assert(digest == fingerprint,
                        "Downloaded certificate has a different fingerprint!")

            check_ca_fingerprint_data[self.PASSED_KEY] = True
        except Exception as e:
            check_ca_fingerprint_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting check_ca_fingerprint %s" %
                     (check_ca_fingerprint_data,))
        self.check_ca_fingerprint.emit(check_ca_fingerprint_data)

        return check_ca_fingerprint_data[self.PASSED_KEY]

    def _check_api_certificate(self):
        """
        Tries to make an API call with the downloaded cert and checks
        if it validates against it

        @return: True if the checks passed, False otherwise
        @rtype: bool
        """
        leap_assert(self._provider_config, "Cannot check the ca cert "
                    "without a provider config!")

        logger.debug("Checking api certificate for %s and cert %s" %
                     (self._provider_config.get_api_uri(),
                      self._provider_config.get_ca_cert_path()))

        check_api_certificate_data = {
            self.PASSED_KEY: False,
            self.ERROR_KEY: ""
        }

        if not self._should_proceed_cert():
            check_api_certificate_data[self.PASSED_KEY] = True
            self.check_api_certificate.emit(check_api_certificate_data)
            return True

        try:
            test_uri = "%s/%s/cert" % (self._provider_config.get_api_uri(),
                                       self._provider_config.get_api_version())
            res = self._session.get(test_uri,
                                    verify=self._provider_config
                                    .get_ca_cert_path())
            res.raise_for_status()
            check_api_certificate_data[self.PASSED_KEY] = True
        except Exception as e:
            check_api_certificate_data[self.ERROR_KEY] = "%s" % (e,)

        logger.debug("Emitting check_api_certificate %s" %
                     (check_api_certificate_data,))
        self.check_api_certificate.emit(check_api_certificate_data)

        return check_api_certificate_data[self.PASSED_KEY]

    def run_provider_setup_checks(self, checker,
                                  provider_config,
                                  download_if_needed=False):
        """
        Starts the checks needed for a new provider setup

        @param provider_config: Provider configuration
        @type provider_config: ProviderConfig
        @param download_if_needed: if True, makes the checks do not
        overwrite already downloaded data
        @type download_if_needed: bool
        """
        leap_assert(provider_config, "We need a provider config!")
        leap_assert_type(provider_config, ProviderConfig)

        self._provider_config = provider_config
        self._download_if_needed = download_if_needed

        checker.add_checks([
            self._download_ca_cert,
            self._check_ca_fingerprint,
            self._check_api_certificate
        ])

if __name__ == "__main__":
    import sys
    from functools import partial
    app = QtGui.QApplication(sys.argv)

    import signal

    def sigint_handler(*args, **kwargs):
        logger.debug('SIGINT catched. shutting down...')
        bootstrapper_checks = args[0]
        bootstrapper_checks.set_should_quit()
        QtGui.QApplication.quit()

    def signal_tester(d):
        print d

    logger = logging.getLogger(name='leap')
    logger.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s '
        '- %(name)s - %(levelname)s - %(message)s')
    console.setFormatter(formatter)
    logger.addHandler(console)

    bootstrapper_checks = ProviderBootstrapper()

    checker = CheckerThread()
    checker.start()

    sigint = partial(sigint_handler, checker)
    signal.signal(signal.SIGINT, sigint)

    timer = QtCore.QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None)
    app.connect(app, QtCore.SIGNAL("aboutToQuit()"),
                checker.set_should_quit)
    w = QtGui.QWidget()
    w.resize(100, 100)
    w.show()

    bootstrapper_checks.run_provider_select_checks(checker,
                                                   "bitmask.net")

    provider_config = ProviderConfig()
    if provider_config.load(os.path.join("leap",
                                         "providers",
                                         "bitmask.net",
                                         "provider.json")):
        bootstrapper_checks.run_provider_setup_checks(checker,
                                                      provider_config)

    sys.exit(app.exec_())