File: connector.py

package info (click to toggle)
python-aioxmpp 0.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,152 kB
  • sloc: python: 96,969; xml: 215; makefile: 155; sh: 72
file content (382 lines) | stat: -rw-r--r-- 12,042 bytes parent folder | download | duplicates (2)
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
########################################################################
# File name: connector.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
"""
:mod:`~aioxmpp.connector` --- Ways to establish XML streams
###########################################################

This module provides classes to establish XML streams. Currently, there are two
different ways to establish XML streams: normal TCP connection which is then
upgraded using STARTTLS, and directly using TLS.

.. versionadded:: 0.6

   The whole module was added in version 0.6.

Abstract base class
===================

The connectors share a common abstract base class, :class:`BaseConnector`:

.. autoclass:: BaseConnector

Specific connectors
===================

.. autoclass:: STARTTLSConnector

.. autoclass:: XMPPOverTLSConnector

"""

import abc
import asyncio
import logging

from datetime import timedelta

import aioxmpp.errors as errors
import aioxmpp.nonza as nonza
import aioxmpp.protocol as protocol
import aioxmpp.ssl_transport as ssl_transport


def to_ascii(s):
    return s.encode("idna").decode("ascii")


class BaseConnector(metaclass=abc.ABCMeta):
    """
    This is the base class for connectors. It defines the public interface of
    all connectors.

    .. autoattribute:: tls_supported

    .. automethod:: connect

    Existing connectors:

    .. autosummary::

       STARTTLSConnector
       XMPPOverTLSConnector

    """

    @abc.abstractproperty
    def tls_supported(self):
        """
        Boolean which indicates whether TLS is supported by this connector.
        """

    @abc.abstractproperty
    def dane_supported(self):
        """
        Boolean which indicates whether DANE is supported by this connector.
        """

    @abc.abstractmethod
    async def connect(self, loop, metadata, domain, host, port,
                      negotiation_timeout,
                      base_logger=None):
        """
        Establish a :class:`.protocol.XMLStream` for `domain` with the given
        `host` at the given TCP `port`.

        `metadata` must be a :class:`.security_layer.SecurityLayer` instance to
        use for the connection. `loop` must be a :class:`asyncio.BaseEventLoop`
        to use.

        `negotiation_timeout` must be the maximum time in seconds to wait for
        the server to reply in each negotiation step. The `negotiation_timeout`
        is used as value for
        :attr:`~aioxmpp.protocol.XMLStream.deadtime_hard_limit` in the returned
        stream.

        Return a triple consisting of the :class:`asyncio.Transport`, the
        :class:`.protocol.XMLStream` and the
        :class:`aioxmpp.nonza.StreamFeatures` of the stream.

        To detect the use of TLS on the stream, check whether
        :meth:`asyncio.Transport.get_extra_info` returns a non-:data:`None`
        value for ``"ssl_object"``.

        `base_logger` is passed to :class:`aioxmpp.protocol.XMLStream`.

        .. versionchanged:: 0.10

            Assignment of
            :attr:`~aioxmpp.protocol.XMLStream.deadtime_hard_limit` was added.
        """


class STARTTLSConnector(BaseConnector):
    """
    Establish an XML stream using STARTTLS.

    .. automethod:: connect
    """

    @property
    def tls_supported(self):
        return True

    @property
    def dane_supported(self):
        return False

    async def connect(self, loop, metadata, domain: str, host, port,
                      negotiation_timeout, base_logger=None):
        """
        .. seealso::

           :meth:`BaseConnector.connect`
              For general information on the :meth:`connect` method.

        Connect to `host` at TCP port number `port`. The
        :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used
        to determine the parameters of the TLS connection.

        First, a normal TCP connection is opened and the stream header is sent.
        The stream features are waited for, and then STARTTLS is negotiated if
        possible.

        :attr:`~.security_layer.SecurityLayer.tls_required` is honoured: if it
        is true and TLS negotiation fails, :class:`~.errors.TLSUnavailable` is
        raised. TLS negotiation is always attempted if
        :attr:`~.security_layer.SecurityLayer.tls_required` is true, even if
        the server does not advertise a STARTTLS stream feature. This might
        help to prevent trivial downgrade attacks, and we don’t have anything
        to lose at this point anymore anyways.

        :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and
        :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are
        used to configure the TLS connection.

        .. versionchanged:: 0.10

            The `negotiation_timeout` is set as
            :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
        """

        features_future = asyncio.Future(loop=loop)

        stream = protocol.XMLStream(
            to=domain,
            features_future=features_future,
            base_logger=base_logger,
        )
        if base_logger is not None:
            logger = base_logger.getChild(type(self).__name__)
        else:
            logger = logging.getLogger(".".join([
                __name__, type(self).__qualname__,
            ]))

        try:
            transport, _ = await ssl_transport.create_starttls_connection(
                loop,
                lambda: stream,
                host=host,
                port=port,
                peer_hostname=host,
                server_hostname=to_ascii(domain),
                use_starttls=True,
            )
        except:  # NOQA
            stream.abort()
            raise

        stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout)

        features = await features_future

        try:
            features[nonza.StartTLSFeature]
        except KeyError:
            if not metadata.tls_required:
                return transport, stream, await features_future
            logger.debug(
                "attempting STARTTLS despite not announced since it is"
                " required")

        try:
            response = await protocol.send_and_wait_for(
                stream,
                [
                    nonza.StartTLS(),
                ],
                [
                    nonza.StartTLSFailure,
                    nonza.StartTLSProceed,
                ]
            )
        except errors.StreamError:
            raise errors.TLSUnavailable(
                "STARTTLS not supported by server, but required by client"
            )

        if not isinstance(response, nonza.StartTLSProceed):
            if metadata.tls_required:
                message = (
                    "server failed to STARTTLS"
                )

                protocol.send_stream_error_and_close(
                    stream,
                    condition=errors.StreamErrorCondition.POLICY_VIOLATION,
                    text=message,
                )

                raise errors.TLSUnavailable(message)
            return transport, stream, await features_future

        verifier = metadata.certificate_verifier_factory()
        await verifier.pre_handshake(
            domain,
            host,
            port,
            metadata,
        )

        ssl_context = metadata.ssl_context_factory()
        verifier.setup_context(ssl_context, transport)

        await stream.starttls(
            ssl_context=ssl_context,
            post_handshake_callback=verifier.post_handshake,
        )

        features = await protocol.reset_stream_and_get_features(
            stream,
            timeout=negotiation_timeout,
        )

        return transport, stream, features


class XMPPOverTLSConnector(BaseConnector):
    """
    Establish an XML stream using XMPP-over-TLS, as per :xep:`368`.

    .. automethod:: connect
    """

    @property
    def dane_supported(self):
        return False

    @property
    def tls_supported(self):
        return True

    def _context_factory_factory(self, logger, metadata, verifier):
        def context_factory(transport):
            ssl_context = metadata.ssl_context_factory()

            if hasattr(ssl_context, "set_alpn_protos"):
                try:
                    ssl_context.set_alpn_protos([b'xmpp-client'])
                except NotImplementedError:
                    logger.warning(
                        "the underlying OpenSSL library does not support ALPN"
                    )
            else:
                logger.warning(
                    "OpenSSL.SSL.Context lacks set_alpn_protos - "
                    "please update pyOpenSSL to a recent version"
                )

            verifier.setup_context(ssl_context, transport)
            return ssl_context
        return context_factory

    async def connect(self, loop, metadata, domain, host, port,
                      negotiation_timeout, base_logger=None):
        """
        .. seealso::

           :meth:`BaseConnector.connect`
              For general information on the :meth:`connect` method.

        Connect to `host` at TCP port number `port`. The
        :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used
        to determine the parameters of the TLS connection.

        The connector connects to the server by directly establishing TLS; no
        XML stream is started before TLS negotiation, in accordance to
        :xep:`368` and how legacy SSL was handled in the past.

        :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and
        :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are
        used to configure the TLS connection.

        .. versionchanged:: 0.10

            The `negotiation_timeout` is set as
            :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
        """

        features_future = asyncio.Future(loop=loop)

        stream = protocol.XMLStream(
            to=domain,
            features_future=features_future,
            base_logger=base_logger,
        )

        if base_logger is not None:
            logger = base_logger.getChild(type(self).__name__)
        else:
            logger = logging.getLogger(".".join([
                __name__, type(self).__qualname__,
            ]))

        verifier = metadata.certificate_verifier_factory()
        await verifier.pre_handshake(
            domain,
            host,
            port,
            metadata,
        )

        context_factory = self._context_factory_factory(logger, metadata,
                                                        verifier)

        try:
            transport, _ = await ssl_transport.create_starttls_connection(
                loop,
                lambda: stream,
                host=host,
                port=port,
                peer_hostname=host,
                server_hostname=to_ascii(domain),
                post_handshake_callback=verifier.post_handshake,
                ssl_context_factory=context_factory,
                use_starttls=False,
            )
        except:  # NOQA
            stream.abort()
            raise

        stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout)

        return transport, stream, await features_future