summaryrefslogtreecommitdiff
path: root/src/leap/common/http.py
blob: f6a7f7e88195b7fb124da65dd821b2df1bc82cd0 (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
# -*- coding: utf-8 -*-
# http.py
# Copyright (C) 2015 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/>.
"""
Twisted HTTP/HTTPS client.
This module will be deprecated and slowly migrated to use treq instead.
"""

import os
import re


try:
    import twisted
    assert twisted
except ImportError:
    print "*******"
    print "Twisted is needed to use leap.common.http module"
    print ""
    print "Install the extra requirement of the package:"
    print "$ pip install leap.common[http]"
    import sys
    sys.exit(1)

from leap.common import ca_bundle


from OpenSSL.crypto import X509StoreContext
from OpenSSL.crypto import X509StoreContextError
from OpenSSL.SSL import Context
from OpenSSL.SSL import TLSv1_METHOD

from twisted.internet import reactor
from twisted.internet import defer
from twisted.internet.ssl import Certificate, trustRootFromCertificates
from twisted.internet.ssl import ClientContextFactory
from twisted.logger import Logger
from twisted.python import failure
from twisted.python.filepath import FilePath

from twisted.web.client import Agent
from twisted.web.client import BrowserLikePolicyForHTTPS
from twisted.web.client import HTTPConnectionPool
from twisted.web.client import _HTTP11ClientFactory as HTTP11ClientFactory
from twisted.web.client import readBody
from twisted.web.http_headers import Headers
from twisted.web.iweb import IBodyProducer
from twisted.web._newclient import HTTP11ClientProtocol

from zope.interface import implements

__all__ = ["HTTPClient"]


log = Logger()


# A default HTTP timeout is used for 2 distinct purposes:
#   1. as HTTP connection timeout, prior to connection estabilshment.
#   2. as data reception timeout, after the connection has been established.

DEFAULT_HTTP_TIMEOUT = 30  # seconds

SKIP_SSL_CHECK = os.environ.get('SKIP_TWISTED_SSL_CHECK', False)


def certsFromBundle(path, x509=False):
    PEM_RE = re.compile(
        "-----BEGIN CERTIFICATE-----\r?.+?\r?"
        "-----END CERTIFICATE-----\r?\n?""",
        re.DOTALL)
    if not os.path.isfile(path):
        log.warn("Attempted to load non-existent certificate bundle path %s"
                 % path)
        return []

    pems = FilePath(path).getContent()
    cstr = [match.group(0) for match in PEM_RE.finditer(pems)]
    certs = [Certificate.loadPEM(cert) for cert in cstr]
    if x509:
        certs = [cert.original for cert in certs]
    return certs


def hasUsablePlatformTrust():

    _knownchain = certsFromBundle(ca_bundle.where('EFFchain.pem'), x509=True)
    _knowncert = _knownchain[0]
    _knowninterm = _knownchain[1:]

    def _verify_test_cert(store, cert):
        store_ctx = X509StoreContext(store, cert)
        try:
            assert store_ctx.verify_certificate() is None
        except (X509StoreContextError, AssertionError):
            return False
        else:
            return True

    def _add_intermediates(store, intermediates):
        for _cert in intermediates:
            store.add_cert(_cert)

    ctx = Context(TLSv1_METHOD)
    ctx.set_default_verify_paths()
    store = ctx.get_cert_store()
    _add_intermediates(store, _knowninterm)

    return _verify_test_cert(store, _knowncert)


def getCertifiTrustRoot():
    try:
        import certifi
        bundle = certifi.where()
    except ImportError:
        log.warn("certifi was not found. Using leap.common bundle")
        bundle = ca_bundle.where()
    if bundle is None:
        log.error("Cannot find an usable cacert bundle. "
                  "Certificate verification will fail")
        return None
    cacerts = certsFromBundle(bundle)
    return trustRootFromCertificates(cacerts)


class _HTTP11ClientFactory(HTTP11ClientFactory):
    """
    A timeout-able HTTP 1.1 client protocol factory.
    """

    def __init__(self, quiescentCallback, timeout):
        """
        :param quiescentCallback: The quiescent callback to be passed to
                                  protocol instances, used to return them to
                                  the connection pool.
        :type quiescentCallback: callable(Protocol)
        :param timeout: The timeout, in seconds, for requests made by
                        protocols created by this factory.
        :type timeout: float
        """
        HTTP11ClientFactory.__init__(self, quiescentCallback)
        self._timeout = timeout

    def buildProtocol(self, _):
        """
        Build the HTTP 1.1 client protocol.
        """
        return _HTTP11ClientProtocol(self._quiescentCallback, self._timeout)


class _HTTPConnectionPool(HTTPConnectionPool):
    """
    A timeout-able HTTP connection pool.
    """

    _factory = _HTTP11ClientFactory

    def __init__(self, reactor, persistent, timeout, maxPersistentPerHost=10):
        HTTPConnectionPool.__init__(self, reactor, persistent=persistent)
        self.maxPersistentPerHost = maxPersistentPerHost
        self._timeout = timeout

    def _newConnection(self, key, endpoint):
        def quiescentCallback(protocol):
            self._putConnection(key, protocol)
        factory = self._factory(quiescentCallback, timeout=self._timeout)
        return endpoint.connect(factory)


# TODO deprecate this in favor of treq.
# We need treq to have support for:

# [ ] timeout
# [ ] retries
# [ ] download/upload pool.


def getPolicyForHTTPS(trustRoot=None):

    if SKIP_SSL_CHECK:
        log.info("---------------------------------------")
        log.info("SKIPPING SSL CERT VERIFICATION!!!")
        log.info("I assume you know WHAT YOU ARE DOING...")
        log.info("---------------------------------------")

        class WebClientContextFactory(ClientContextFactory):
            """
            A web context factory which ignores the hostname and port and does
            no certificate verification.
            """
            def getContext(self, hostname, port):
                return ClientContextFactory.getContext(self)

        contextFactory = WebClientContextFactory()
        return contextFactory

    if isinstance(trustRoot, str):
        trustRoot = Certificate.loadPEM(FilePath(trustRoot).getContent())

    return BrowserLikePolicyForHTTPS(trustRoot)


class HTTPClient(object):
    """
    HTTP client done the twisted way, with a main focus on pinning the SSL
    certificate.

    By default, it uses a shared connection pool. If you want a dedicated
    one, create and pass on __init__ pool parameter.
    Please note that this client will limit the maximum amount of connections
    by using a DeferredSemaphore.
    This limit is equal to the maxPersistentPerHost used on pool and is needed
    in order to avoid resource abuse on huge requests batches.
    """

    _pool = _HTTPConnectionPool(
        reactor,
        persistent=True,
        timeout=DEFAULT_HTTP_TIMEOUT,
        maxPersistentPerHost=10
    )

    def __init__(self, cert_path=None,
                 timeout=DEFAULT_HTTP_TIMEOUT, pool=None):
        """
        Init the HTTP client

        :param cert_file: The path to the ca certificate file to verify
                          certificates, if None given the system's CAs will be
                          used.
        :type cert_file: str
        :param timeout: The amount of time that this Agent will wait for the
                        peer to accept a connection and for each request to be
                        finished. If a pool is passed, then this argument is
                        ignored.
        :type timeout: float
        """

        self._timeout = timeout
        self._pool = pool if pool is not None else self._pool

        if cert_path is None:
            if hasUsablePlatformTrust():
                # Twisted Knows What To Do
                trustRoot = None
            else:
                trustRoot = getCertifiTrustRoot()
        else:
            trustRoot = cert_path

        self._agent = Agent(
            reactor,
            contextFactory=getPolicyForHTTPS(trustRoot),
            pool=self._pool,
            connectTimeout=self._timeout)
        self._semaphore = defer.DeferredSemaphore(
            self._pool.maxPersistentPerHost)

    def _createPool(self, maxPersistentPerHost=10, persistent=True):
        pool = _HTTPConnectionPool(reactor, persistent, self._timeout)
        pool.maxPersistentPerHost = maxPersistentPerHost
        return pool

    def _request(self, url, method, body, headers, callback):
        """
        Perform an HTTP request.

        :param url: The URL for the request.
        :type url: str
        :param method: The HTTP method of the request.
        :type method: str
        :param body: The body of the request, if any.
        :type body: str
        :param headers: The headers of the request.
        :type headers: dict
        :param callback: A callback to be added to the request's deferred
                         callback chain.
        :type callback: callable

        :return: A deferred that fires with the body of the request.
        :rtype: twisted.internet.defer.Deferred
        """
        if body:
            body = _StringBodyProducer(body)
        d = self._agent.request(
            method, url, headers=Headers(headers), bodyProducer=body)
        d.addCallback(callback)
        return d

    def request(self, url, method='GET', body=None, headers={},
                callback=readBody):
        """
        Perform an HTTP request, but limit the maximum amount of concurrent
        connections.

        May be passed a callback to be added to the request's deferred
        callback chain. The callback is expected to receive the response of
        the request and may do whatever it wants with the response. By
        default, if no callback is passed, we will use a simple body reader
        which returns a deferred that is fired with the body of the response.

        :param url: The URL for the request.
        :type url: str
        :param method: The HTTP method of the request.
        :type method: str
        :param body: The body of the request, if any.
        :type body: str
        :param headers: The headers of the request.
        :type headers: dict
        :param callback: A callback to be added to the request's deferred
                         callback chain.
        :type callback: callable

        :return: A deferred that fires with the body of the request.
        :rtype: twisted.internet.defer.Deferred
        """
        assert callable(callback), "The callback parameter should be a callable!"
        return self._semaphore.run(self._request, url, method, body, headers,
                                   callback)

    def close(self):
        """
        Close any cached connections.
        """
        self._pool.closeCachedConnections()


#
# An IBodyProducer to write the body of an HTTP request as a string.
#


class _StringBodyProducer(object):
    """
    A producer that writes the body of a request to a consumer.
    """

    implements(IBodyProducer)

    def __init__(self, body):
        """
        Initialize the string produer.

        :param body: The body of the request.
        :type body: str
        """
        self.body = body
        self.length = len(body)

    def startProducing(self, consumer):
        """
        Write the body to the consumer.

        :param consumer: Any IConsumer provider.
        :type consumer: twisted.internet.interfaces.IConsumer

        :return: A successful deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        consumer.write(self.body)
        return defer.succeed(None)

    def pauseProducing(self):
        pass

    def stopProducing(self):
        pass


#
# Patched twisted.web classes
#

class _HTTP11ClientProtocol(HTTP11ClientProtocol):
    """
    A timeout-able HTTP 1.1 client protocol, that is instantiated by the
    _HTTP11ClientFactory below.
    """

    def __init__(self, quiescentCallback, timeout):
        """
        Initialize the protocol.

        :param quiescentCallback:
        :type quiescentCallback: callable
        :param timeout: A timeout, in seconds, for requests made by this
                        protocol.
        :type timeout: float
        """
        HTTP11ClientProtocol.__init__(self, quiescentCallback)
        self._timeout = timeout
        self._timeoutCall = None

    def request(self, request):
        """
        Issue request over self.transport and return a Deferred which
        will fire with a Response instance or an error.

        :param request: The object defining the parameters of the request to
                        issue.
        :type request: twisted.web._newclient.Request

        :return: A deferred which fires after the request has finished.
        :rtype: Deferred
        """
        d = HTTP11ClientProtocol.request(self, request)
        if self._timeout:
            self._last_buffer_len = 0
            timeoutCall = reactor.callLater(
                self._timeout, self._doTimeout, request)
            self._timeoutCall = timeoutCall
        return d

    def _doTimeout(self, request):
        """
        Give up the request because of a timeout.

        :param request: The object defining the parameters of the request to
                        issue.
        :type request: twisted.web._newclient.Request
        """
        self._giveUp(
            failure.Failure(
                defer.TimeoutError(
                    "Getting %s took longer than %s seconds."
                    % (request.absoluteURI, self._timeout))))

    def _cancelTimeout(self):
        """
        Cancel the request timeout, when it's finished.
        """
        if self._timeoutCall and self._timeoutCall.active():
            self._timeoutCall.cancel()
            self._timeoutCall = None

    def _finishResponse(self, rest):
        """
        Cancel the timeout when finished receiving the response.
        """
        self._cancelTimeout()
        HTTP11ClientProtocol._finishResponse(self, rest)

    def dataReceived(self, bytes):
        """
        Receive some data and extend the timeout period of this request.

        :param bytes: A string of indeterminate length.
        :type bytes: str
        """
        HTTP11ClientProtocol.dataReceived(self, bytes)
        if self._timeoutCall and self._timeoutCall.active():
            self._timeoutCall.reset(self._timeout)

    def connectionLost(self, reason):
        self._cancelTimeout()
        return HTTP11ClientProtocol.connectionLost(self, reason)