• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import os
2import socket
3from sys import platform
4from functools import wraps, partial
5from itertools import count, chain
6from weakref import WeakValueDictionary
7from errno import errorcode
8
9from six import integer_types, int2byte, indexbytes
10
11from OpenSSL._util import (
12    UNSPECIFIED as _UNSPECIFIED,
13    exception_from_error_queue as _exception_from_error_queue,
14    ffi as _ffi,
15    from_buffer as _from_buffer,
16    lib as _lib,
17    make_assert as _make_assert,
18    native as _native,
19    path_string as _path_string,
20    text_to_bytes_and_warn as _text_to_bytes_and_warn,
21    no_zero_allocator as _no_zero_allocator,
22)
23
24from OpenSSL.crypto import (
25    FILETYPE_PEM,
26    _PassphraseHelper,
27    PKey,
28    X509Name,
29    X509,
30    X509Store,
31)
32
33__all__ = [
34    "OPENSSL_VERSION_NUMBER",
35    "SSLEAY_VERSION",
36    "SSLEAY_CFLAGS",
37    "SSLEAY_PLATFORM",
38    "SSLEAY_DIR",
39    "SSLEAY_BUILT_ON",
40    "SENT_SHUTDOWN",
41    "RECEIVED_SHUTDOWN",
42    "SSLv2_METHOD",
43    "SSLv3_METHOD",
44    "SSLv23_METHOD",
45    "TLSv1_METHOD",
46    "TLSv1_1_METHOD",
47    "TLSv1_2_METHOD",
48    "OP_NO_SSLv2",
49    "OP_NO_SSLv3",
50    "OP_NO_TLSv1",
51    "OP_NO_TLSv1_1",
52    "OP_NO_TLSv1_2",
53    "OP_NO_TLSv1_3",
54    "MODE_RELEASE_BUFFERS",
55    "OP_SINGLE_DH_USE",
56    "OP_SINGLE_ECDH_USE",
57    "OP_EPHEMERAL_RSA",
58    "OP_MICROSOFT_SESS_ID_BUG",
59    "OP_NETSCAPE_CHALLENGE_BUG",
60    "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
61    "OP_SSLREF2_REUSE_CERT_TYPE_BUG",
62    "OP_MICROSOFT_BIG_SSLV3_BUFFER",
63    "OP_MSIE_SSLV2_RSA_PADDING",
64    "OP_SSLEAY_080_CLIENT_DH_BUG",
65    "OP_TLS_D5_BUG",
66    "OP_TLS_BLOCK_PADDING_BUG",
67    "OP_DONT_INSERT_EMPTY_FRAGMENTS",
68    "OP_CIPHER_SERVER_PREFERENCE",
69    "OP_TLS_ROLLBACK_BUG",
70    "OP_PKCS1_CHECK_1",
71    "OP_PKCS1_CHECK_2",
72    "OP_NETSCAPE_CA_DN_BUG",
73    "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
74    "OP_NO_COMPRESSION",
75    "OP_NO_QUERY_MTU",
76    "OP_COOKIE_EXCHANGE",
77    "OP_NO_TICKET",
78    "OP_ALL",
79    "VERIFY_PEER",
80    "VERIFY_FAIL_IF_NO_PEER_CERT",
81    "VERIFY_CLIENT_ONCE",
82    "VERIFY_NONE",
83    "SESS_CACHE_OFF",
84    "SESS_CACHE_CLIENT",
85    "SESS_CACHE_SERVER",
86    "SESS_CACHE_BOTH",
87    "SESS_CACHE_NO_AUTO_CLEAR",
88    "SESS_CACHE_NO_INTERNAL_LOOKUP",
89    "SESS_CACHE_NO_INTERNAL_STORE",
90    "SESS_CACHE_NO_INTERNAL",
91    "SSL_ST_CONNECT",
92    "SSL_ST_ACCEPT",
93    "SSL_ST_MASK",
94    "SSL_CB_LOOP",
95    "SSL_CB_EXIT",
96    "SSL_CB_READ",
97    "SSL_CB_WRITE",
98    "SSL_CB_ALERT",
99    "SSL_CB_READ_ALERT",
100    "SSL_CB_WRITE_ALERT",
101    "SSL_CB_ACCEPT_LOOP",
102    "SSL_CB_ACCEPT_EXIT",
103    "SSL_CB_CONNECT_LOOP",
104    "SSL_CB_CONNECT_EXIT",
105    "SSL_CB_HANDSHAKE_START",
106    "SSL_CB_HANDSHAKE_DONE",
107    "Error",
108    "WantReadError",
109    "WantWriteError",
110    "WantX509LookupError",
111    "ZeroReturnError",
112    "SysCallError",
113    "SSLeay_version",
114    "Session",
115    "Context",
116    "Connection",
117]
118
119try:
120    _buffer = buffer
121except NameError:
122
123    class _buffer(object):
124        pass
125
126
127OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
128SSLEAY_VERSION = _lib.SSLEAY_VERSION
129SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
130SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
131SSLEAY_DIR = _lib.SSLEAY_DIR
132SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
133
134SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
135RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
136
137SSLv2_METHOD = 1
138SSLv3_METHOD = 2
139SSLv23_METHOD = 3
140TLSv1_METHOD = 4
141TLSv1_1_METHOD = 5
142TLSv1_2_METHOD = 6
143
144OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
145OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
146OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
147OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
148OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
149try:
150    OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
151except AttributeError:
152    pass
153
154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
155
156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162    _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177    _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
180
181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
184
185OP_ALL = _lib.SSL_OP_ALL
186
187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
191
192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
200
201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
204
205SSL_CB_LOOP = _lib.SSL_CB_LOOP
206SSL_CB_EXIT = _lib.SSL_CB_EXIT
207SSL_CB_READ = _lib.SSL_CB_READ
208SSL_CB_WRITE = _lib.SSL_CB_WRITE
209SSL_CB_ALERT = _lib.SSL_CB_ALERT
210SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
211SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
212SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
213SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
214SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
215SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
216SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
217SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
218
219# Taken from https://golang.org/src/crypto/x509/root_linux.go
220_CERTIFICATE_FILE_LOCATIONS = [
221    "/etc/ssl/certs/ca-certificates.crt",  # Debian/Ubuntu/Gentoo etc.
222    "/etc/pki/tls/certs/ca-bundle.crt",  # Fedora/RHEL 6
223    "/etc/ssl/ca-bundle.pem",  # OpenSUSE
224    "/etc/pki/tls/cacert.pem",  # OpenELEC
225    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",  # CentOS/RHEL 7
226]
227
228_CERTIFICATE_PATH_LOCATIONS = [
229    "/etc/ssl/certs",  # SLES10/SLES11
230]
231
232# These values are compared to output from cffi's ffi.string so they must be
233# byte strings.
234_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
235_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
236
237
238class Error(Exception):
239    """
240    An error occurred in an `OpenSSL.SSL` API.
241    """
242
243
244_raise_current_error = partial(_exception_from_error_queue, Error)
245_openssl_assert = _make_assert(Error)
246
247
248class WantReadError(Error):
249    pass
250
251
252class WantWriteError(Error):
253    pass
254
255
256class WantX509LookupError(Error):
257    pass
258
259
260class ZeroReturnError(Error):
261    pass
262
263
264class SysCallError(Error):
265    pass
266
267
268class _CallbackExceptionHelper(object):
269    """
270    A base class for wrapper classes that allow for intelligent exception
271    handling in OpenSSL callbacks.
272
273    :ivar list _problems: Any exceptions that occurred while executing in a
274        context where they could not be raised in the normal way.  Typically
275        this is because OpenSSL has called into some Python code and requires a
276        return value.  The exceptions are saved to be raised later when it is
277        possible to do so.
278    """
279
280    def __init__(self):
281        self._problems = []
282
283    def raise_if_problem(self):
284        """
285        Raise an exception from the OpenSSL error queue or that was previously
286        captured whe running a callback.
287        """
288        if self._problems:
289            try:
290                _raise_current_error()
291            except Error:
292                pass
293            raise self._problems.pop(0)
294
295
296class _VerifyHelper(_CallbackExceptionHelper):
297    """
298    Wrap a callback such that it can be used as a certificate verification
299    callback.
300    """
301
302    def __init__(self, callback):
303        _CallbackExceptionHelper.__init__(self)
304
305        @wraps(callback)
306        def wrapper(ok, store_ctx):
307            x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
308            _lib.X509_up_ref(x509)
309            cert = X509._from_raw_x509_ptr(x509)
310            error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
311            error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
312
313            index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
314            ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
315            connection = Connection._reverse_mapping[ssl]
316
317            try:
318                result = callback(
319                    connection, cert, error_number, error_depth, ok
320                )
321            except Exception as e:
322                self._problems.append(e)
323                return 0
324            else:
325                if result:
326                    _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
327                    return 1
328                else:
329                    return 0
330
331        self.callback = _ffi.callback(
332            "int (*)(int, X509_STORE_CTX *)", wrapper
333        )
334
335
336NO_OVERLAPPING_PROTOCOLS = object()
337
338
339class _ALPNSelectHelper(_CallbackExceptionHelper):
340    """
341    Wrap a callback such that it can be used as an ALPN selection callback.
342    """
343
344    def __init__(self, callback):
345        _CallbackExceptionHelper.__init__(self)
346
347        @wraps(callback)
348        def wrapper(ssl, out, outlen, in_, inlen, arg):
349            try:
350                conn = Connection._reverse_mapping[ssl]
351
352                # The string passed to us is made up of multiple
353                # length-prefixed bytestrings. We need to split that into a
354                # list.
355                instr = _ffi.buffer(in_, inlen)[:]
356                protolist = []
357                while instr:
358                    encoded_len = indexbytes(instr, 0)
359                    proto = instr[1 : encoded_len + 1]
360                    protolist.append(proto)
361                    instr = instr[encoded_len + 1 :]
362
363                # Call the callback
364                outbytes = callback(conn, protolist)
365                any_accepted = True
366                if outbytes is NO_OVERLAPPING_PROTOCOLS:
367                    outbytes = b""
368                    any_accepted = False
369                elif not isinstance(outbytes, bytes):
370                    raise TypeError(
371                        "ALPN callback must return a bytestring or the "
372                        "special NO_OVERLAPPING_PROTOCOLS sentinel value."
373                    )
374
375                # Save our callback arguments on the connection object to make
376                # sure that they don't get freed before OpenSSL can use them.
377                # Then, return them in the appropriate output parameters.
378                conn._alpn_select_callback_args = [
379                    _ffi.new("unsigned char *", len(outbytes)),
380                    _ffi.new("unsigned char[]", outbytes),
381                ]
382                outlen[0] = conn._alpn_select_callback_args[0][0]
383                out[0] = conn._alpn_select_callback_args[1]
384                if not any_accepted:
385                    return _lib.SSL_TLSEXT_ERR_NOACK
386                return _lib.SSL_TLSEXT_ERR_OK
387            except Exception as e:
388                self._problems.append(e)
389                return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
390
391        self.callback = _ffi.callback(
392            (
393                "int (*)(SSL *, unsigned char **, unsigned char *, "
394                "const unsigned char *, unsigned int, void *)"
395            ),
396            wrapper,
397        )
398
399
400class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
401    """
402    Wrap a callback such that it can be used as an OCSP callback for the server
403    side.
404
405    Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
406    ways. For servers, that callback is expected to retrieve some OCSP data and
407    hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
408    SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
409    is expected to check the OCSP data, and returns a negative value on error,
410    0 if the response is not acceptable, or positive if it is. These are
411    mutually exclusive return code behaviours, and they mean that we need two
412    helpers so that we always return an appropriate error code if the user's
413    code throws an exception.
414
415    Given that we have to have two helpers anyway, these helpers are a bit more
416    helpery than most: specifically, they hide a few more of the OpenSSL
417    functions so that the user has an easier time writing these callbacks.
418
419    This helper implements the server side.
420    """
421
422    def __init__(self, callback):
423        _CallbackExceptionHelper.__init__(self)
424
425        @wraps(callback)
426        def wrapper(ssl, cdata):
427            try:
428                conn = Connection._reverse_mapping[ssl]
429
430                # Extract the data if any was provided.
431                if cdata != _ffi.NULL:
432                    data = _ffi.from_handle(cdata)
433                else:
434                    data = None
435
436                # Call the callback.
437                ocsp_data = callback(conn, data)
438
439                if not isinstance(ocsp_data, bytes):
440                    raise TypeError("OCSP callback must return a bytestring.")
441
442                # If the OCSP data was provided, we will pass it to OpenSSL.
443                # However, we have an early exit here: if no OCSP data was
444                # provided we will just exit out and tell OpenSSL that there
445                # is nothing to do.
446                if not ocsp_data:
447                    return 3  # SSL_TLSEXT_ERR_NOACK
448
449                # OpenSSL takes ownership of this data and expects it to have
450                # been allocated by OPENSSL_malloc.
451                ocsp_data_length = len(ocsp_data)
452                data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
453                _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
454
455                _lib.SSL_set_tlsext_status_ocsp_resp(
456                    ssl, data_ptr, ocsp_data_length
457                )
458
459                return 0
460            except Exception as e:
461                self._problems.append(e)
462                return 2  # SSL_TLSEXT_ERR_ALERT_FATAL
463
464        self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
465
466
467class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
468    """
469    Wrap a callback such that it can be used as an OCSP callback for the client
470    side.
471
472    Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
473    ways. For servers, that callback is expected to retrieve some OCSP data and
474    hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
475    SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
476    is expected to check the OCSP data, and returns a negative value on error,
477    0 if the response is not acceptable, or positive if it is. These are
478    mutually exclusive return code behaviours, and they mean that we need two
479    helpers so that we always return an appropriate error code if the user's
480    code throws an exception.
481
482    Given that we have to have two helpers anyway, these helpers are a bit more
483    helpery than most: specifically, they hide a few more of the OpenSSL
484    functions so that the user has an easier time writing these callbacks.
485
486    This helper implements the client side.
487    """
488
489    def __init__(self, callback):
490        _CallbackExceptionHelper.__init__(self)
491
492        @wraps(callback)
493        def wrapper(ssl, cdata):
494            try:
495                conn = Connection._reverse_mapping[ssl]
496
497                # Extract the data if any was provided.
498                if cdata != _ffi.NULL:
499                    data = _ffi.from_handle(cdata)
500                else:
501                    data = None
502
503                # Get the OCSP data.
504                ocsp_ptr = _ffi.new("unsigned char **")
505                ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
506                if ocsp_len < 0:
507                    # No OCSP data.
508                    ocsp_data = b""
509                else:
510                    # Copy the OCSP data, then pass it to the callback.
511                    ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
512
513                valid = callback(conn, ocsp_data, data)
514
515                # Return 1 on success or 0 on error.
516                return int(bool(valid))
517
518            except Exception as e:
519                self._problems.append(e)
520                # Return negative value if an exception is hit.
521                return -1
522
523        self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
524
525
526def _asFileDescriptor(obj):
527    fd = None
528    if not isinstance(obj, integer_types):
529        meth = getattr(obj, "fileno", None)
530        if meth is not None:
531            obj = meth()
532
533    if isinstance(obj, integer_types):
534        fd = obj
535
536    if not isinstance(fd, integer_types):
537        raise TypeError("argument must be an int, or have a fileno() method.")
538    elif fd < 0:
539        raise ValueError(
540            "file descriptor cannot be a negative integer (%i)" % (fd,)
541        )
542
543    return fd
544
545
546def SSLeay_version(type):
547    """
548    Return a string describing the version of OpenSSL in use.
549
550    :param type: One of the :const:`SSLEAY_` constants defined in this module.
551    """
552    return _ffi.string(_lib.SSLeay_version(type))
553
554
555def _make_requires(flag, error):
556    """
557    Builds a decorator that ensures that functions that rely on OpenSSL
558    functions that are not present in this build raise NotImplementedError,
559    rather than AttributeError coming out of cryptography.
560
561    :param flag: A cryptography flag that guards the functions, e.g.
562        ``Cryptography_HAS_NEXTPROTONEG``.
563    :param error: The string to be used in the exception if the flag is false.
564    """
565
566    def _requires_decorator(func):
567        if not flag:
568
569            @wraps(func)
570            def explode(*args, **kwargs):
571                raise NotImplementedError(error)
572
573            return explode
574        else:
575            return func
576
577    return _requires_decorator
578
579
580_requires_alpn = _make_requires(
581    _lib.Cryptography_HAS_ALPN, "ALPN not available"
582)
583
584
585_requires_keylog = _make_requires(
586    getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
587)
588
589
590class Session(object):
591    """
592    A class representing an SSL session.  A session defines certain connection
593    parameters which may be re-used to speed up the setup of subsequent
594    connections.
595
596    .. versionadded:: 0.14
597    """
598
599    pass
600
601
602class Context(object):
603    """
604    :class:`OpenSSL.SSL.Context` instances define the parameters for setting
605    up new SSL connections.
606
607    :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
608        TLSv1_METHOD.
609    """
610
611    _methods = {
612        SSLv2_METHOD: "SSLv2_method",
613        SSLv3_METHOD: "SSLv3_method",
614        SSLv23_METHOD: "SSLv23_method",
615        TLSv1_METHOD: "TLSv1_method",
616        TLSv1_1_METHOD: "TLSv1_1_method",
617        TLSv1_2_METHOD: "TLSv1_2_method",
618    }
619    _methods = dict(
620        (identifier, getattr(_lib, name))
621        for (identifier, name) in _methods.items()
622        if getattr(_lib, name, None) is not None
623    )
624
625    def __init__(self, method):
626        if not isinstance(method, integer_types):
627            raise TypeError("method must be an integer")
628
629        try:
630            method_func = self._methods[method]
631        except KeyError:
632            raise ValueError("No such protocol")
633
634        method_obj = method_func()
635        _openssl_assert(method_obj != _ffi.NULL)
636
637        context = _lib.SSL_CTX_new(method_obj)
638        _openssl_assert(context != _ffi.NULL)
639        context = _ffi.gc(context, _lib.SSL_CTX_free)
640
641        # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
642        # auto-selected. This function was added in 1.0.2 and made a noop in
643        # 1.1.0+ (where it is set automatically).
644        res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
645        _openssl_assert(res == 1)
646
647        self._context = context
648        self._passphrase_helper = None
649        self._passphrase_callback = None
650        self._passphrase_userdata = None
651        self._verify_helper = None
652        self._verify_callback = None
653        self._info_callback = None
654        self._keylog_callback = None
655        self._tlsext_servername_callback = None
656        self._app_data = None
657        self._alpn_select_helper = None
658        self._alpn_select_callback = None
659        self._ocsp_helper = None
660        self._ocsp_callback = None
661        self._ocsp_data = None
662
663        self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
664
665    def load_verify_locations(self, cafile, capath=None):
666        """
667        Let SSL know where we can find trusted certificates for the certificate
668        chain.  Note that the certificates have to be in PEM format.
669
670        If capath is passed, it must be a directory prepared using the
671        ``c_rehash`` tool included with OpenSSL.  Either, but not both, of
672        *pemfile* or *capath* may be :data:`None`.
673
674        :param cafile: In which file we can find the certificates (``bytes`` or
675            ``unicode``).
676        :param capath: In which directory we can find the certificates
677            (``bytes`` or ``unicode``).
678
679        :return: None
680        """
681        if cafile is None:
682            cafile = _ffi.NULL
683        else:
684            cafile = _path_string(cafile)
685
686        if capath is None:
687            capath = _ffi.NULL
688        else:
689            capath = _path_string(capath)
690
691        load_result = _lib.SSL_CTX_load_verify_locations(
692            self._context, cafile, capath
693        )
694        if not load_result:
695            _raise_current_error()
696
697    def _wrap_callback(self, callback):
698        @wraps(callback)
699        def wrapper(size, verify, userdata):
700            return callback(size, verify, self._passphrase_userdata)
701
702        return _PassphraseHelper(
703            FILETYPE_PEM, wrapper, more_args=True, truncate=True
704        )
705
706    def set_passwd_cb(self, callback, userdata=None):
707        """
708        Set the passphrase callback.  This function will be called
709        when a private key with a passphrase is loaded.
710
711        :param callback: The Python callback to use.  This must accept three
712            positional arguments.  First, an integer giving the maximum length
713            of the passphrase it may return.  If the returned passphrase is
714            longer than this, it will be truncated.  Second, a boolean value
715            which will be true if the user should be prompted for the
716            passphrase twice and the callback should verify that the two values
717            supplied are equal. Third, the value given as the *userdata*
718            parameter to :meth:`set_passwd_cb`.  The *callback* must return
719            a byte string. If an error occurs, *callback* should return a false
720            value (e.g. an empty string).
721        :param userdata: (optional) A Python object which will be given as
722                         argument to the callback
723        :return: None
724        """
725        if not callable(callback):
726            raise TypeError("callback must be callable")
727
728        self._passphrase_helper = self._wrap_callback(callback)
729        self._passphrase_callback = self._passphrase_helper.callback
730        _lib.SSL_CTX_set_default_passwd_cb(
731            self._context, self._passphrase_callback
732        )
733        self._passphrase_userdata = userdata
734
735    def set_default_verify_paths(self):
736        """
737        Specify that the platform provided CA certificates are to be used for
738        verification purposes. This method has some caveats related to the
739        binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
740
741        *   macOS will only load certificates using this method if the user has
742            the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
743            in the default location.
744        *   Windows will not work.
745        *   manylinux1 cryptography wheels will work on most common Linux
746            distributions in pyOpenSSL 17.1.0 and above.  pyOpenSSL detects the
747            manylinux1 wheel and attempts to load roots via a fallback path.
748
749        :return: None
750        """
751        # SSL_CTX_set_default_verify_paths will attempt to load certs from
752        # both a cafile and capath that are set at compile time. However,
753        # it will first check environment variables and, if present, load
754        # those paths instead
755        set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
756        _openssl_assert(set_result == 1)
757        # After attempting to set default_verify_paths we need to know whether
758        # to go down the fallback path.
759        # First we'll check to see if any env vars have been set. If so,
760        # we won't try to do anything else because the user has set the path
761        # themselves.
762        dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
763            "ascii"
764        )
765        file_env_var = _ffi.string(
766            _lib.X509_get_default_cert_file_env()
767        ).decode("ascii")
768        if not self._check_env_vars_set(dir_env_var, file_env_var):
769            default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
770            default_file = _ffi.string(_lib.X509_get_default_cert_file())
771            # Now we check to see if the default_dir and default_file are set
772            # to the exact values we use in our manylinux1 builds. If they are
773            # then we know to load the fallbacks
774            if (
775                default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
776                and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
777            ):
778                # This is manylinux1, let's load our fallback paths
779                self._fallback_default_verify_paths(
780                    _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
781                )
782
783    def _check_env_vars_set(self, dir_env_var, file_env_var):
784        """
785        Check to see if the default cert dir/file environment vars are present.
786
787        :return: bool
788        """
789        return (
790            os.environ.get(file_env_var) is not None
791            or os.environ.get(dir_env_var) is not None
792        )
793
794    def _fallback_default_verify_paths(self, file_path, dir_path):
795        """
796        Default verify paths are based on the compiled version of OpenSSL.
797        However, when pyca/cryptography is compiled as a manylinux1 wheel
798        that compiled location can potentially be wrong. So, like Go, we
799        will try a predefined set of paths and attempt to load roots
800        from there.
801
802        :return: None
803        """
804        for cafile in file_path:
805            if os.path.isfile(cafile):
806                self.load_verify_locations(cafile)
807                break
808
809        for capath in dir_path:
810            if os.path.isdir(capath):
811                self.load_verify_locations(None, capath)
812                break
813
814    def use_certificate_chain_file(self, certfile):
815        """
816        Load a certificate chain from a file.
817
818        :param certfile: The name of the certificate chain file (``bytes`` or
819            ``unicode``).  Must be PEM encoded.
820
821        :return: None
822        """
823        certfile = _path_string(certfile)
824
825        result = _lib.SSL_CTX_use_certificate_chain_file(
826            self._context, certfile
827        )
828        if not result:
829            _raise_current_error()
830
831    def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
832        """
833        Load a certificate from a file
834
835        :param certfile: The name of the certificate file (``bytes`` or
836            ``unicode``).
837        :param filetype: (optional) The encoding of the file, which is either
838            :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
839            :const:`FILETYPE_PEM`.
840
841        :return: None
842        """
843        certfile = _path_string(certfile)
844        if not isinstance(filetype, integer_types):
845            raise TypeError("filetype must be an integer")
846
847        use_result = _lib.SSL_CTX_use_certificate_file(
848            self._context, certfile, filetype
849        )
850        if not use_result:
851            _raise_current_error()
852
853    def use_certificate(self, cert):
854        """
855        Load a certificate from a X509 object
856
857        :param cert: The X509 object
858        :return: None
859        """
860        if not isinstance(cert, X509):
861            raise TypeError("cert must be an X509 instance")
862
863        use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
864        if not use_result:
865            _raise_current_error()
866
867    def add_extra_chain_cert(self, certobj):
868        """
869        Add certificate to chain
870
871        :param certobj: The X509 certificate object to add to the chain
872        :return: None
873        """
874        if not isinstance(certobj, X509):
875            raise TypeError("certobj must be an X509 instance")
876
877        copy = _lib.X509_dup(certobj._x509)
878        add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
879        if not add_result:
880            # TODO: This is untested.
881            _lib.X509_free(copy)
882            _raise_current_error()
883
884    def _raise_passphrase_exception(self):
885        if self._passphrase_helper is not None:
886            self._passphrase_helper.raise_if_problem(Error)
887
888        _raise_current_error()
889
890    def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
891        """
892        Load a private key from a file
893
894        :param keyfile: The name of the key file (``bytes`` or ``unicode``)
895        :param filetype: (optional) The encoding of the file, which is either
896            :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
897            :const:`FILETYPE_PEM`.
898
899        :return: None
900        """
901        keyfile = _path_string(keyfile)
902
903        if filetype is _UNSPECIFIED:
904            filetype = FILETYPE_PEM
905        elif not isinstance(filetype, integer_types):
906            raise TypeError("filetype must be an integer")
907
908        use_result = _lib.SSL_CTX_use_PrivateKey_file(
909            self._context, keyfile, filetype
910        )
911        if not use_result:
912            self._raise_passphrase_exception()
913
914    def use_privatekey(self, pkey):
915        """
916        Load a private key from a PKey object
917
918        :param pkey: The PKey object
919        :return: None
920        """
921        if not isinstance(pkey, PKey):
922            raise TypeError("pkey must be a PKey instance")
923
924        use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
925        if not use_result:
926            self._raise_passphrase_exception()
927
928    def check_privatekey(self):
929        """
930        Check if the private key (loaded with :meth:`use_privatekey`) matches
931        the certificate (loaded with :meth:`use_certificate`)
932
933        :return: :data:`None` (raises :exc:`Error` if something's wrong)
934        """
935        if not _lib.SSL_CTX_check_private_key(self._context):
936            _raise_current_error()
937
938    def load_client_ca(self, cafile):
939        """
940        Load the trusted certificates that will be sent to the client.  Does
941        not actually imply any of the certificates are trusted; that must be
942        configured separately.
943
944        :param bytes cafile: The path to a certificates file in PEM format.
945        :return: None
946        """
947        ca_list = _lib.SSL_load_client_CA_file(
948            _text_to_bytes_and_warn("cafile", cafile)
949        )
950        _openssl_assert(ca_list != _ffi.NULL)
951        _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
952
953    def set_session_id(self, buf):
954        """
955        Set the session id to *buf* within which a session can be reused for
956        this Context object.  This is needed when doing session resumption,
957        because there is no way for a stored session to know which Context
958        object it is associated with.
959
960        :param bytes buf: The session id.
961
962        :returns: None
963        """
964        buf = _text_to_bytes_and_warn("buf", buf)
965        _openssl_assert(
966            _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf))
967            == 1
968        )
969
970    def set_session_cache_mode(self, mode):
971        """
972        Set the behavior of the session cache used by all connections using
973        this Context.  The previously set mode is returned.  See
974        :const:`SESS_CACHE_*` for details about particular modes.
975
976        :param mode: One or more of the SESS_CACHE_* flags (combine using
977            bitwise or)
978        :returns: The previously set caching mode.
979
980        .. versionadded:: 0.14
981        """
982        if not isinstance(mode, integer_types):
983            raise TypeError("mode must be an integer")
984
985        return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
986
987    def get_session_cache_mode(self):
988        """
989        Get the current session cache mode.
990
991        :returns: The currently used cache mode.
992
993        .. versionadded:: 0.14
994        """
995        return _lib.SSL_CTX_get_session_cache_mode(self._context)
996
997    def set_verify(self, mode, callback=None):
998        """
999        Set the verification flags for this Context object to *mode* and
1000        specify that *callback* should be used for verification callbacks.
1001
1002        :param mode: The verify mode, this should be one of
1003            :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1004            :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1005            :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1006            :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1007        :param callback: The optional Python verification callback to use.
1008            This should take five arguments: A Connection object, an X509
1009            object, and three integer variables, which are in turn potential
1010            error number, error depth and return code. *callback* should
1011            return True if verification passes and False otherwise.
1012            If omitted, OpenSSL's default verification is used.
1013        :return: None
1014
1015        See SSL_CTX_set_verify(3SSL) for further details.
1016        """
1017        if not isinstance(mode, integer_types):
1018            raise TypeError("mode must be an integer")
1019
1020        if callback is None:
1021            self._verify_helper = None
1022            self._verify_callback = None
1023            _lib.SSL_CTX_set_verify(self._context, mode, _ffi.NULL)
1024        else:
1025            if not callable(callback):
1026                raise TypeError("callback must be callable")
1027
1028            self._verify_helper = _VerifyHelper(callback)
1029            self._verify_callback = self._verify_helper.callback
1030            _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
1031
1032    def set_verify_depth(self, depth):
1033        """
1034        Set the maximum depth for the certificate chain verification that shall
1035        be allowed for this Context object.
1036
1037        :param depth: An integer specifying the verify depth
1038        :return: None
1039        """
1040        if not isinstance(depth, integer_types):
1041            raise TypeError("depth must be an integer")
1042
1043        _lib.SSL_CTX_set_verify_depth(self._context, depth)
1044
1045    def get_verify_mode(self):
1046        """
1047        Retrieve the Context object's verify mode, as set by
1048        :meth:`set_verify`.
1049
1050        :return: The verify mode
1051        """
1052        return _lib.SSL_CTX_get_verify_mode(self._context)
1053
1054    def get_verify_depth(self):
1055        """
1056        Retrieve the Context object's verify depth, as set by
1057        :meth:`set_verify_depth`.
1058
1059        :return: The verify depth
1060        """
1061        return _lib.SSL_CTX_get_verify_depth(self._context)
1062
1063    def load_tmp_dh(self, dhfile):
1064        """
1065        Load parameters for Ephemeral Diffie-Hellman
1066
1067        :param dhfile: The file to load EDH parameters from (``bytes`` or
1068            ``unicode``).
1069
1070        :return: None
1071        """
1072        dhfile = _path_string(dhfile)
1073
1074        bio = _lib.BIO_new_file(dhfile, b"r")
1075        if bio == _ffi.NULL:
1076            _raise_current_error()
1077        bio = _ffi.gc(bio, _lib.BIO_free)
1078
1079        dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1080        dh = _ffi.gc(dh, _lib.DH_free)
1081        res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1082        _openssl_assert(res == 1)
1083
1084    def set_tmp_ecdh(self, curve):
1085        """
1086        Select a curve to use for ECDHE key exchange.
1087
1088        :param curve: A curve object to use as returned by either
1089            :meth:`OpenSSL.crypto.get_elliptic_curve` or
1090            :meth:`OpenSSL.crypto.get_elliptic_curves`.
1091
1092        :return: None
1093        """
1094        _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
1095
1096    def set_cipher_list(self, cipher_list):
1097        """
1098        Set the list of ciphers to be used in this context.
1099
1100        See the OpenSSL manual for more information (e.g.
1101        :manpage:`ciphers(1)`).
1102
1103        :param bytes cipher_list: An OpenSSL cipher string.
1104        :return: None
1105        """
1106        cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
1107
1108        if not isinstance(cipher_list, bytes):
1109            raise TypeError("cipher_list must be a byte string.")
1110
1111        _openssl_assert(
1112            _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
1113        )
1114        # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1115        # ciphers even if you pass an invalid cipher. Applications (like
1116        # Twisted) have tests that depend on an error being raised if an
1117        # invalid cipher string is passed, but without the following check
1118        # for the TLS 1.3 specific cipher suites it would never error.
1119        tmpconn = Connection(self, None)
1120        if tmpconn.get_cipher_list() == [
1121            "TLS_AES_256_GCM_SHA384",
1122            "TLS_CHACHA20_POLY1305_SHA256",
1123            "TLS_AES_128_GCM_SHA256",
1124        ]:
1125            raise Error(
1126                [
1127                    (
1128                        "SSL routines",
1129                        "SSL_CTX_set_cipher_list",
1130                        "no cipher match",
1131                    ),
1132                ],
1133            )
1134
1135    def set_client_ca_list(self, certificate_authorities):
1136        """
1137        Set the list of preferred client certificate signers for this server
1138        context.
1139
1140        This list of certificate authorities will be sent to the client when
1141        the server requests a client certificate.
1142
1143        :param certificate_authorities: a sequence of X509Names.
1144        :return: None
1145
1146        .. versionadded:: 0.10
1147        """
1148        name_stack = _lib.sk_X509_NAME_new_null()
1149        _openssl_assert(name_stack != _ffi.NULL)
1150
1151        try:
1152            for ca_name in certificate_authorities:
1153                if not isinstance(ca_name, X509Name):
1154                    raise TypeError(
1155                        "client CAs must be X509Name objects, not %s "
1156                        "objects" % (type(ca_name).__name__,)
1157                    )
1158                copy = _lib.X509_NAME_dup(ca_name._name)
1159                _openssl_assert(copy != _ffi.NULL)
1160                push_result = _lib.sk_X509_NAME_push(name_stack, copy)
1161                if not push_result:
1162                    _lib.X509_NAME_free(copy)
1163                    _raise_current_error()
1164        except Exception:
1165            _lib.sk_X509_NAME_free(name_stack)
1166            raise
1167
1168        _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
1169
1170    def add_client_ca(self, certificate_authority):
1171        """
1172        Add the CA certificate to the list of preferred signers for this
1173        context.
1174
1175        The list of certificate authorities will be sent to the client when the
1176        server requests a client certificate.
1177
1178        :param certificate_authority: certificate authority's X509 certificate.
1179        :return: None
1180
1181        .. versionadded:: 0.10
1182        """
1183        if not isinstance(certificate_authority, X509):
1184            raise TypeError("certificate_authority must be an X509 instance")
1185
1186        add_result = _lib.SSL_CTX_add_client_CA(
1187            self._context, certificate_authority._x509
1188        )
1189        _openssl_assert(add_result == 1)
1190
1191    def set_timeout(self, timeout):
1192        """
1193        Set the timeout for newly created sessions for this Context object to
1194        *timeout*.  The default value is 300 seconds. See the OpenSSL manual
1195        for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
1196
1197        :param timeout: The timeout in (whole) seconds
1198        :return: The previous session timeout
1199        """
1200        if not isinstance(timeout, integer_types):
1201            raise TypeError("timeout must be an integer")
1202
1203        return _lib.SSL_CTX_set_timeout(self._context, timeout)
1204
1205    def get_timeout(self):
1206        """
1207        Retrieve session timeout, as set by :meth:`set_timeout`. The default
1208        is 300 seconds.
1209
1210        :return: The session timeout
1211        """
1212        return _lib.SSL_CTX_get_timeout(self._context)
1213
1214    def set_info_callback(self, callback):
1215        """
1216        Set the information callback to *callback*. This function will be
1217        called from time to time during SSL handshakes.
1218
1219        :param callback: The Python callback to use.  This should take three
1220            arguments: a Connection object and two integers.  The first integer
1221            specifies where in the SSL handshake the function was called, and
1222            the other the return code from a (possibly failed) internal
1223            function call.
1224        :return: None
1225        """
1226
1227        @wraps(callback)
1228        def wrapper(ssl, where, return_code):
1229            callback(Connection._reverse_mapping[ssl], where, return_code)
1230
1231        self._info_callback = _ffi.callback(
1232            "void (*)(const SSL *, int, int)", wrapper
1233        )
1234        _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
1235
1236    @_requires_keylog
1237    def set_keylog_callback(self, callback):
1238        """
1239        Set the TLS key logging callback to *callback*. This function will be
1240        called whenever TLS key material is generated or received, in order
1241        to allow applications to store this keying material for debugging
1242        purposes.
1243
1244        :param callback: The Python callback to use.  This should take two
1245            arguments: a Connection object and a bytestring that contains
1246            the key material in the format used by NSS for its SSLKEYLOGFILE
1247            debugging output.
1248        :return: None
1249        """
1250
1251        @wraps(callback)
1252        def wrapper(ssl, line):
1253            line = _ffi.string(line)
1254            callback(Connection._reverse_mapping[ssl], line)
1255
1256        self._keylog_callback = _ffi.callback(
1257            "void (*)(const SSL *, const char *)", wrapper
1258        )
1259        _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1260
1261    def get_app_data(self):
1262        """
1263        Get the application data (supplied via :meth:`set_app_data()`)
1264
1265        :return: The application data
1266        """
1267        return self._app_data
1268
1269    def set_app_data(self, data):
1270        """
1271        Set the application data (will be returned from get_app_data())
1272
1273        :param data: Any Python object
1274        :return: None
1275        """
1276        self._app_data = data
1277
1278    def get_cert_store(self):
1279        """
1280        Get the certificate store for the context.  This can be used to add
1281        "trusted" certificates without using the
1282        :meth:`load_verify_locations` method.
1283
1284        :return: A X509Store object or None if it does not have one.
1285        """
1286        store = _lib.SSL_CTX_get_cert_store(self._context)
1287        if store == _ffi.NULL:
1288            # TODO: This is untested.
1289            return None
1290
1291        pystore = X509Store.__new__(X509Store)
1292        pystore._store = store
1293        return pystore
1294
1295    def set_options(self, options):
1296        """
1297        Add options. Options set before are not cleared!
1298        This method should be used with the :const:`OP_*` constants.
1299
1300        :param options: The options to add.
1301        :return: The new option bitmask.
1302        """
1303        if not isinstance(options, integer_types):
1304            raise TypeError("options must be an integer")
1305
1306        return _lib.SSL_CTX_set_options(self._context, options)
1307
1308    def set_mode(self, mode):
1309        """
1310        Add modes via bitmask. Modes set before are not cleared!  This method
1311        should be used with the :const:`MODE_*` constants.
1312
1313        :param mode: The mode to add.
1314        :return: The new mode bitmask.
1315        """
1316        if not isinstance(mode, integer_types):
1317            raise TypeError("mode must be an integer")
1318
1319        return _lib.SSL_CTX_set_mode(self._context, mode)
1320
1321    def set_tlsext_servername_callback(self, callback):
1322        """
1323        Specify a callback function to be called when clients specify a server
1324        name.
1325
1326        :param callback: The callback function.  It will be invoked with one
1327            argument, the Connection instance.
1328
1329        .. versionadded:: 0.13
1330        """
1331
1332        @wraps(callback)
1333        def wrapper(ssl, alert, arg):
1334            callback(Connection._reverse_mapping[ssl])
1335            return 0
1336
1337        self._tlsext_servername_callback = _ffi.callback(
1338            "int (*)(SSL *, int *, void *)", wrapper
1339        )
1340        _lib.SSL_CTX_set_tlsext_servername_callback(
1341            self._context, self._tlsext_servername_callback
1342        )
1343
1344    def set_tlsext_use_srtp(self, profiles):
1345        """
1346        Enable support for negotiating SRTP keying material.
1347
1348        :param bytes profiles: A colon delimited list of protection profile
1349            names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1350        :return: None
1351        """
1352        if not isinstance(profiles, bytes):
1353            raise TypeError("profiles must be a byte string.")
1354
1355        _openssl_assert(
1356            _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1357        )
1358
1359    @_requires_alpn
1360    def set_alpn_protos(self, protos):
1361        """
1362        Specify the protocols that the client is prepared to speak after the
1363        TLS connection has been negotiated using Application Layer Protocol
1364        Negotiation.
1365
1366        :param protos: A list of the protocols to be offered to the server.
1367            This list should be a Python list of bytestrings representing the
1368            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1369        """
1370        # Take the list of protocols and join them together, prefixing them
1371        # with their lengths.
1372        protostr = b"".join(
1373            chain.from_iterable((int2byte(len(p)), p) for p in protos)
1374        )
1375
1376        # Build a C string from the list. We don't need to save this off
1377        # because OpenSSL immediately copies the data out.
1378        input_str = _ffi.new("unsigned char[]", protostr)
1379        _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
1380
1381    @_requires_alpn
1382    def set_alpn_select_callback(self, callback):
1383        """
1384        Specify a callback function that will be called on the server when a
1385        client offers protocols using ALPN.
1386
1387        :param callback: The callback function.  It will be invoked with two
1388            arguments: the Connection, and a list of offered protocols as
1389            bytestrings, e.g ``[b'http/1.1', b'spdy/2']``.  It can return
1390            one of those bytestrings to indicate the chosen protocol, the
1391            empty bytestring to terminate the TLS connection, or the
1392            :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1393            protocol was selected, but that the connection should not be
1394            aborted.
1395        """
1396        self._alpn_select_helper = _ALPNSelectHelper(callback)
1397        self._alpn_select_callback = self._alpn_select_helper.callback
1398        _lib.SSL_CTX_set_alpn_select_cb(
1399            self._context, self._alpn_select_callback, _ffi.NULL
1400        )
1401
1402    def _set_ocsp_callback(self, helper, data):
1403        """
1404        This internal helper does the common work for
1405        ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1406        almost all of it.
1407        """
1408        self._ocsp_helper = helper
1409        self._ocsp_callback = helper.callback
1410        if data is None:
1411            self._ocsp_data = _ffi.NULL
1412        else:
1413            self._ocsp_data = _ffi.new_handle(data)
1414
1415        rc = _lib.SSL_CTX_set_tlsext_status_cb(
1416            self._context, self._ocsp_callback
1417        )
1418        _openssl_assert(rc == 1)
1419        rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1420        _openssl_assert(rc == 1)
1421
1422    def set_ocsp_server_callback(self, callback, data=None):
1423        """
1424        Set a callback to provide OCSP data to be stapled to the TLS handshake
1425        on the server side.
1426
1427        :param callback: The callback function. It will be invoked with two
1428            arguments: the Connection, and the optional arbitrary data you have
1429            provided. The callback must return a bytestring that contains the
1430            OCSP data to staple to the handshake. If no OCSP data is available
1431            for this connection, return the empty bytestring.
1432        :param data: Some opaque data that will be passed into the callback
1433            function when called. This can be used to avoid needing to do
1434            complex data lookups or to keep track of what context is being
1435            used. This parameter is optional.
1436        """
1437        helper = _OCSPServerCallbackHelper(callback)
1438        self._set_ocsp_callback(helper, data)
1439
1440    def set_ocsp_client_callback(self, callback, data=None):
1441        """
1442        Set a callback to validate OCSP data stapled to the TLS handshake on
1443        the client side.
1444
1445        :param callback: The callback function. It will be invoked with three
1446            arguments: the Connection, a bytestring containing the stapled OCSP
1447            assertion, and the optional arbitrary data you have provided. The
1448            callback must return a boolean that indicates the result of
1449            validating the OCSP data: ``True`` if the OCSP data is valid and
1450            the certificate can be trusted, or ``False`` if either the OCSP
1451            data is invalid or the certificate has been revoked.
1452        :param data: Some opaque data that will be passed into the callback
1453            function when called. This can be used to avoid needing to do
1454            complex data lookups or to keep track of what context is being
1455            used. This parameter is optional.
1456        """
1457        helper = _OCSPClientCallbackHelper(callback)
1458        self._set_ocsp_callback(helper, data)
1459
1460
1461class Connection(object):
1462    _reverse_mapping = WeakValueDictionary()
1463
1464    def __init__(self, context, socket=None):
1465        """
1466        Create a new Connection object, using the given OpenSSL.SSL.Context
1467        instance and socket.
1468
1469        :param context: An SSL Context to use for this connection
1470        :param socket: The socket to use for transport layer
1471        """
1472        if not isinstance(context, Context):
1473            raise TypeError("context must be a Context instance")
1474
1475        ssl = _lib.SSL_new(context._context)
1476        self._ssl = _ffi.gc(ssl, _lib.SSL_free)
1477        # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1478        # an SSL_ERROR_WANT_READ when processing a non-application data packet
1479        # even though there is still data on the underlying transport.
1480        # See https://github.com/openssl/openssl/issues/6234 for more details.
1481        _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
1482        self._context = context
1483        self._app_data = None
1484
1485        # References to strings used for Application Layer Protocol
1486        # Negotiation. These strings get copied at some point but it's well
1487        # after the callback returns, so we have to hang them somewhere to
1488        # avoid them getting freed.
1489        self._alpn_select_callback_args = None
1490
1491        # Reference the verify_callback of the Context. This ensures that if
1492        # set_verify is called again after the SSL object has been created we
1493        # do not point to a dangling reference
1494        self._verify_helper = context._verify_helper
1495        self._verify_callback = context._verify_callback
1496
1497        self._reverse_mapping[self._ssl] = self
1498
1499        if socket is None:
1500            self._socket = None
1501            # Don't set up any gc for these, SSL_free will take care of them.
1502            self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1503            _openssl_assert(self._into_ssl != _ffi.NULL)
1504
1505            self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1506            _openssl_assert(self._from_ssl != _ffi.NULL)
1507
1508            _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
1509        else:
1510            self._into_ssl = None
1511            self._from_ssl = None
1512            self._socket = socket
1513            set_result = _lib.SSL_set_fd(
1514                self._ssl, _asFileDescriptor(self._socket)
1515            )
1516            _openssl_assert(set_result == 1)
1517
1518    def __getattr__(self, name):
1519        """
1520        Look up attributes on the wrapped socket object if they are not found
1521        on the Connection object.
1522        """
1523        if self._socket is None:
1524            raise AttributeError(
1525                "'%s' object has no attribute '%s'"
1526                % (self.__class__.__name__, name)
1527            )
1528        else:
1529            return getattr(self._socket, name)
1530
1531    def _raise_ssl_error(self, ssl, result):
1532        if self._context._verify_helper is not None:
1533            self._context._verify_helper.raise_if_problem()
1534        if self._context._alpn_select_helper is not None:
1535            self._context._alpn_select_helper.raise_if_problem()
1536        if self._context._ocsp_helper is not None:
1537            self._context._ocsp_helper.raise_if_problem()
1538
1539        error = _lib.SSL_get_error(ssl, result)
1540        if error == _lib.SSL_ERROR_WANT_READ:
1541            raise WantReadError()
1542        elif error == _lib.SSL_ERROR_WANT_WRITE:
1543            raise WantWriteError()
1544        elif error == _lib.SSL_ERROR_ZERO_RETURN:
1545            raise ZeroReturnError()
1546        elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
1547            # TODO: This is untested.
1548            raise WantX509LookupError()
1549        elif error == _lib.SSL_ERROR_SYSCALL:
1550            if _lib.ERR_peek_error() == 0:
1551                if result < 0:
1552                    if platform == "win32":
1553                        errno = _ffi.getwinerror()[0]
1554                    else:
1555                        errno = _ffi.errno
1556
1557                    if errno != 0:
1558                        raise SysCallError(errno, errorcode.get(errno))
1559                raise SysCallError(-1, "Unexpected EOF")
1560            else:
1561                # TODO: This is untested.
1562                _raise_current_error()
1563        elif error == _lib.SSL_ERROR_NONE:
1564            pass
1565        else:
1566            _raise_current_error()
1567
1568    def get_context(self):
1569        """
1570        Retrieve the :class:`Context` object associated with this
1571        :class:`Connection`.
1572        """
1573        return self._context
1574
1575    def set_context(self, context):
1576        """
1577        Switch this connection to a new session context.
1578
1579        :param context: A :class:`Context` instance giving the new session
1580            context to use.
1581        """
1582        if not isinstance(context, Context):
1583            raise TypeError("context must be a Context instance")
1584
1585        _lib.SSL_set_SSL_CTX(self._ssl, context._context)
1586        self._context = context
1587
1588    def get_servername(self):
1589        """
1590        Retrieve the servername extension value if provided in the client hello
1591        message, or None if there wasn't one.
1592
1593        :return: A byte string giving the server name or :data:`None`.
1594
1595        .. versionadded:: 0.13
1596        """
1597        name = _lib.SSL_get_servername(
1598            self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1599        )
1600        if name == _ffi.NULL:
1601            return None
1602
1603        return _ffi.string(name)
1604
1605    def set_tlsext_host_name(self, name):
1606        """
1607        Set the value of the servername extension to send in the client hello.
1608
1609        :param name: A byte string giving the name.
1610
1611        .. versionadded:: 0.13
1612        """
1613        if not isinstance(name, bytes):
1614            raise TypeError("name must be a byte string")
1615        elif b"\0" in name:
1616            raise TypeError("name must not contain NUL byte")
1617
1618        # XXX I guess this can fail sometimes?
1619        _lib.SSL_set_tlsext_host_name(self._ssl, name)
1620
1621    def pending(self):
1622        """
1623        Get the number of bytes that can be safely read from the SSL buffer
1624        (**not** the underlying transport buffer).
1625
1626        :return: The number of bytes available in the receive buffer.
1627        """
1628        return _lib.SSL_pending(self._ssl)
1629
1630    def send(self, buf, flags=0):
1631        """
1632        Send data on the connection. NOTE: If you get one of the WantRead,
1633        WantWrite or WantX509Lookup exceptions on this, you have to call the
1634        method again with the SAME buffer.
1635
1636        :param buf: The string, buffer or memoryview to send
1637        :param flags: (optional) Included for compatibility with the socket
1638                      API, the value is ignored
1639        :return: The number of bytes written
1640        """
1641        # Backward compatibility
1642        buf = _text_to_bytes_and_warn("buf", buf)
1643
1644        with _from_buffer(buf) as data:
1645            # check len(buf) instead of len(data) for testability
1646            if len(buf) > 2147483647:
1647                raise ValueError(
1648                    "Cannot send more than 2**31-1 bytes at once."
1649                )
1650
1651            result = _lib.SSL_write(self._ssl, data, len(data))
1652            self._raise_ssl_error(self._ssl, result)
1653
1654            return result
1655
1656    write = send
1657
1658    def sendall(self, buf, flags=0):
1659        """
1660        Send "all" data on the connection. This calls send() repeatedly until
1661        all data is sent. If an error occurs, it's impossible to tell how much
1662        data has been sent.
1663
1664        :param buf: The string, buffer or memoryview to send
1665        :param flags: (optional) Included for compatibility with the socket
1666                      API, the value is ignored
1667        :return: The number of bytes written
1668        """
1669        buf = _text_to_bytes_and_warn("buf", buf)
1670
1671        with _from_buffer(buf) as data:
1672
1673            left_to_send = len(buf)
1674            total_sent = 0
1675
1676            while left_to_send:
1677                # SSL_write's num arg is an int,
1678                # so we cannot send more than 2**31-1 bytes at once.
1679                result = _lib.SSL_write(
1680                    self._ssl, data + total_sent, min(left_to_send, 2147483647)
1681                )
1682                self._raise_ssl_error(self._ssl, result)
1683                total_sent += result
1684                left_to_send -= result
1685
1686            return total_sent
1687
1688    def recv(self, bufsiz, flags=None):
1689        """
1690        Receive data on the connection.
1691
1692        :param bufsiz: The maximum number of bytes to read
1693        :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1694            all other flags are ignored.
1695        :return: The string read from the Connection
1696        """
1697        buf = _no_zero_allocator("char[]", bufsiz)
1698        if flags is not None and flags & socket.MSG_PEEK:
1699            result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1700        else:
1701            result = _lib.SSL_read(self._ssl, buf, bufsiz)
1702        self._raise_ssl_error(self._ssl, result)
1703        return _ffi.buffer(buf, result)[:]
1704
1705    read = recv
1706
1707    def recv_into(self, buffer, nbytes=None, flags=None):
1708        """
1709        Receive data on the connection and copy it directly into the provided
1710        buffer, rather than creating a new string.
1711
1712        :param buffer: The buffer to copy into.
1713        :param nbytes: (optional) The maximum number of bytes to read into the
1714            buffer. If not present, defaults to the size of the buffer. If
1715            larger than the size of the buffer, is reduced to the size of the
1716            buffer.
1717        :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1718            all other flags are ignored.
1719        :return: The number of bytes read into the buffer.
1720        """
1721        if nbytes is None:
1722            nbytes = len(buffer)
1723        else:
1724            nbytes = min(nbytes, len(buffer))
1725
1726        # We need to create a temporary buffer. This is annoying, it would be
1727        # better if we could pass memoryviews straight into the SSL_read call,
1728        # but right now we can't. Revisit this if CFFI gets that ability.
1729        buf = _no_zero_allocator("char[]", nbytes)
1730        if flags is not None and flags & socket.MSG_PEEK:
1731            result = _lib.SSL_peek(self._ssl, buf, nbytes)
1732        else:
1733            result = _lib.SSL_read(self._ssl, buf, nbytes)
1734        self._raise_ssl_error(self._ssl, result)
1735
1736        # This strange line is all to avoid a memory copy. The buffer protocol
1737        # should allow us to assign a CFFI buffer to the LHS of this line, but
1738        # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1739        # wrap it in a memoryview.
1740        buffer[:result] = memoryview(_ffi.buffer(buf, result))
1741
1742        return result
1743
1744    def _handle_bio_errors(self, bio, result):
1745        if _lib.BIO_should_retry(bio):
1746            if _lib.BIO_should_read(bio):
1747                raise WantReadError()
1748            elif _lib.BIO_should_write(bio):
1749                # TODO: This is untested.
1750                raise WantWriteError()
1751            elif _lib.BIO_should_io_special(bio):
1752                # TODO: This is untested.  I think io_special means the socket
1753                # BIO has a not-yet connected socket.
1754                raise ValueError("BIO_should_io_special")
1755            else:
1756                # TODO: This is untested.
1757                raise ValueError("unknown bio failure")
1758        else:
1759            # TODO: This is untested.
1760            _raise_current_error()
1761
1762    def bio_read(self, bufsiz):
1763        """
1764        If the Connection was created with a memory BIO, this method can be
1765        used to read bytes from the write end of that memory BIO.  Many
1766        Connection methods will add bytes which must be read in this manner or
1767        the buffer will eventually fill up and the Connection will be able to
1768        take no further actions.
1769
1770        :param bufsiz: The maximum number of bytes to read
1771        :return: The string read.
1772        """
1773        if self._from_ssl is None:
1774            raise TypeError("Connection sock was not None")
1775
1776        if not isinstance(bufsiz, integer_types):
1777            raise TypeError("bufsiz must be an integer")
1778
1779        buf = _no_zero_allocator("char[]", bufsiz)
1780        result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
1781        if result <= 0:
1782            self._handle_bio_errors(self._from_ssl, result)
1783
1784        return _ffi.buffer(buf, result)[:]
1785
1786    def bio_write(self, buf):
1787        """
1788        If the Connection was created with a memory BIO, this method can be
1789        used to add bytes to the read end of that memory BIO.  The Connection
1790        can then read the bytes (for example, in response to a call to
1791        :meth:`recv`).
1792
1793        :param buf: The string to put into the memory BIO.
1794        :return: The number of bytes written
1795        """
1796        buf = _text_to_bytes_and_warn("buf", buf)
1797
1798        if self._into_ssl is None:
1799            raise TypeError("Connection sock was not None")
1800
1801        with _from_buffer(buf) as data:
1802            result = _lib.BIO_write(self._into_ssl, data, len(data))
1803            if result <= 0:
1804                self._handle_bio_errors(self._into_ssl, result)
1805            return result
1806
1807    def renegotiate(self):
1808        """
1809        Renegotiate the session.
1810
1811        :return: True if the renegotiation can be started, False otherwise
1812        :rtype: bool
1813        """
1814        if not self.renegotiate_pending():
1815            _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1816            return True
1817        return False
1818
1819    def do_handshake(self):
1820        """
1821        Perform an SSL handshake (usually called after :meth:`renegotiate` or
1822        one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
1823        raise the same exceptions as :meth:`send` and :meth:`recv`.
1824
1825        :return: None.
1826        """
1827        result = _lib.SSL_do_handshake(self._ssl)
1828        self._raise_ssl_error(self._ssl, result)
1829
1830    def renegotiate_pending(self):
1831        """
1832        Check if there's a renegotiation in progress, it will return False once
1833        a renegotiation is finished.
1834
1835        :return: Whether there's a renegotiation in progress
1836        :rtype: bool
1837        """
1838        return _lib.SSL_renegotiate_pending(self._ssl) == 1
1839
1840    def total_renegotiations(self):
1841        """
1842        Find out the total number of renegotiations.
1843
1844        :return: The number of renegotiations.
1845        :rtype: int
1846        """
1847        return _lib.SSL_total_renegotiations(self._ssl)
1848
1849    def connect(self, addr):
1850        """
1851        Call the :meth:`connect` method of the underlying socket and set up SSL
1852        on the socket, using the :class:`Context` object supplied to this
1853        :class:`Connection` object at creation.
1854
1855        :param addr: A remote address
1856        :return: What the socket's connect method returns
1857        """
1858        _lib.SSL_set_connect_state(self._ssl)
1859        return self._socket.connect(addr)
1860
1861    def connect_ex(self, addr):
1862        """
1863        Call the :meth:`connect_ex` method of the underlying socket and set up
1864        SSL on the socket, using the Context object supplied to this Connection
1865        object at creation. Note that if the :meth:`connect_ex` method of the
1866        socket doesn't return 0, SSL won't be initialized.
1867
1868        :param addr: A remove address
1869        :return: What the socket's connect_ex method returns
1870        """
1871        connect_ex = self._socket.connect_ex
1872        self.set_connect_state()
1873        return connect_ex(addr)
1874
1875    def accept(self):
1876        """
1877        Call the :meth:`accept` method of the underlying socket and set up SSL
1878        on the returned socket, using the Context object supplied to this
1879        :class:`Connection` object at creation.
1880
1881        :return: A *(conn, addr)* pair where *conn* is the new
1882            :class:`Connection` object created, and *address* is as returned by
1883            the socket's :meth:`accept`.
1884        """
1885        client, addr = self._socket.accept()
1886        conn = Connection(self._context, client)
1887        conn.set_accept_state()
1888        return (conn, addr)
1889
1890    def bio_shutdown(self):
1891        """
1892        If the Connection was created with a memory BIO, this method can be
1893        used to indicate that *end of file* has been reached on the read end of
1894        that memory BIO.
1895
1896        :return: None
1897        """
1898        if self._from_ssl is None:
1899            raise TypeError("Connection sock was not None")
1900
1901        _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
1902
1903    def shutdown(self):
1904        """
1905        Send the shutdown message to the Connection.
1906
1907        :return: True if the shutdown completed successfully (i.e. both sides
1908                 have sent closure alerts), False otherwise (in which case you
1909                 call :meth:`recv` or :meth:`send` when the connection becomes
1910                 readable/writeable).
1911        """
1912        result = _lib.SSL_shutdown(self._ssl)
1913        if result < 0:
1914            self._raise_ssl_error(self._ssl, result)
1915        elif result > 0:
1916            return True
1917        else:
1918            return False
1919
1920    def get_cipher_list(self):
1921        """
1922        Retrieve the list of ciphers used by the Connection object.
1923
1924        :return: A list of native cipher strings.
1925        """
1926        ciphers = []
1927        for i in count():
1928            result = _lib.SSL_get_cipher_list(self._ssl, i)
1929            if result == _ffi.NULL:
1930                break
1931            ciphers.append(_native(_ffi.string(result)))
1932        return ciphers
1933
1934    def get_client_ca_list(self):
1935        """
1936        Get CAs whose certificates are suggested for client authentication.
1937
1938        :return: If this is a server connection, the list of certificate
1939            authorities that will be sent or has been sent to the client, as
1940            controlled by this :class:`Connection`'s :class:`Context`.
1941
1942            If this is a client connection, the list will be empty until the
1943            connection with the server is established.
1944
1945        .. versionadded:: 0.10
1946        """
1947        ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1948        if ca_names == _ffi.NULL:
1949            # TODO: This is untested.
1950            return []
1951
1952        result = []
1953        for i in range(_lib.sk_X509_NAME_num(ca_names)):
1954            name = _lib.sk_X509_NAME_value(ca_names, i)
1955            copy = _lib.X509_NAME_dup(name)
1956            _openssl_assert(copy != _ffi.NULL)
1957
1958            pyname = X509Name.__new__(X509Name)
1959            pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
1960            result.append(pyname)
1961        return result
1962
1963    def makefile(self, *args, **kwargs):
1964        """
1965        The makefile() method is not implemented, since there is no dup
1966        semantics for SSL connections
1967
1968        :raise: NotImplementedError
1969        """
1970        raise NotImplementedError(
1971            "Cannot make file object of OpenSSL.SSL.Connection"
1972        )
1973
1974    def get_app_data(self):
1975        """
1976        Retrieve application data as set by :meth:`set_app_data`.
1977
1978        :return: The application data
1979        """
1980        return self._app_data
1981
1982    def set_app_data(self, data):
1983        """
1984        Set application data
1985
1986        :param data: The application data
1987        :return: None
1988        """
1989        self._app_data = data
1990
1991    def get_shutdown(self):
1992        """
1993        Get the shutdown state of the Connection.
1994
1995        :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1996            RECEIVED_SHUTDOWN.
1997        """
1998        return _lib.SSL_get_shutdown(self._ssl)
1999
2000    def set_shutdown(self, state):
2001        """
2002        Set the shutdown state of the Connection.
2003
2004        :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
2005        :return: None
2006        """
2007        if not isinstance(state, integer_types):
2008            raise TypeError("state must be an integer")
2009
2010        _lib.SSL_set_shutdown(self._ssl, state)
2011
2012    def get_state_string(self):
2013        """
2014        Retrieve a verbose string detailing the state of the Connection.
2015
2016        :return: A string representing the state
2017        :rtype: bytes
2018        """
2019        return _ffi.string(_lib.SSL_state_string_long(self._ssl))
2020
2021    def server_random(self):
2022        """
2023        Retrieve the random value used with the server hello message.
2024
2025        :return: A string representing the state
2026        """
2027        session = _lib.SSL_get_session(self._ssl)
2028        if session == _ffi.NULL:
2029            return None
2030        length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2031        _openssl_assert(length > 0)
2032        outp = _no_zero_allocator("unsigned char[]", length)
2033        _lib.SSL_get_server_random(self._ssl, outp, length)
2034        return _ffi.buffer(outp, length)[:]
2035
2036    def client_random(self):
2037        """
2038        Retrieve the random value used with the client hello message.
2039
2040        :return: A string representing the state
2041        """
2042        session = _lib.SSL_get_session(self._ssl)
2043        if session == _ffi.NULL:
2044            return None
2045
2046        length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2047        _openssl_assert(length > 0)
2048        outp = _no_zero_allocator("unsigned char[]", length)
2049        _lib.SSL_get_client_random(self._ssl, outp, length)
2050        return _ffi.buffer(outp, length)[:]
2051
2052    def master_key(self):
2053        """
2054        Retrieve the value of the master key for this session.
2055
2056        :return: A string representing the state
2057        """
2058        session = _lib.SSL_get_session(self._ssl)
2059        if session == _ffi.NULL:
2060            return None
2061
2062        length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2063        _openssl_assert(length > 0)
2064        outp = _no_zero_allocator("unsigned char[]", length)
2065        _lib.SSL_SESSION_get_master_key(session, outp, length)
2066        return _ffi.buffer(outp, length)[:]
2067
2068    def export_keying_material(self, label, olen, context=None):
2069        """
2070        Obtain keying material for application use.
2071
2072        :param: label - a disambiguating label string as described in RFC 5705
2073        :param: olen - the length of the exported key material in bytes
2074        :param: context - a per-association context value
2075        :return: the exported key material bytes or None
2076        """
2077        outp = _no_zero_allocator("unsigned char[]", olen)
2078        context_buf = _ffi.NULL
2079        context_len = 0
2080        use_context = 0
2081        if context is not None:
2082            context_buf = context
2083            context_len = len(context)
2084            use_context = 1
2085        success = _lib.SSL_export_keying_material(
2086            self._ssl,
2087            outp,
2088            olen,
2089            label,
2090            len(label),
2091            context_buf,
2092            context_len,
2093            use_context,
2094        )
2095        _openssl_assert(success == 1)
2096        return _ffi.buffer(outp, olen)[:]
2097
2098    def sock_shutdown(self, *args, **kwargs):
2099        """
2100        Call the :meth:`shutdown` method of the underlying socket.
2101        See :manpage:`shutdown(2)`.
2102
2103        :return: What the socket's shutdown() method returns
2104        """
2105        return self._socket.shutdown(*args, **kwargs)
2106
2107    def get_certificate(self):
2108        """
2109        Retrieve the local certificate (if any)
2110
2111        :return: The local certificate
2112        """
2113        cert = _lib.SSL_get_certificate(self._ssl)
2114        if cert != _ffi.NULL:
2115            _lib.X509_up_ref(cert)
2116            return X509._from_raw_x509_ptr(cert)
2117        return None
2118
2119    def get_peer_certificate(self):
2120        """
2121        Retrieve the other side's certificate (if any)
2122
2123        :return: The peer's certificate
2124        """
2125        cert = _lib.SSL_get_peer_certificate(self._ssl)
2126        if cert != _ffi.NULL:
2127            return X509._from_raw_x509_ptr(cert)
2128        return None
2129
2130    @staticmethod
2131    def _cert_stack_to_list(cert_stack):
2132        """
2133        Internal helper to convert a STACK_OF(X509) to a list of X509
2134        instances.
2135        """
2136        result = []
2137        for i in range(_lib.sk_X509_num(cert_stack)):
2138            cert = _lib.sk_X509_value(cert_stack, i)
2139            _openssl_assert(cert != _ffi.NULL)
2140            res = _lib.X509_up_ref(cert)
2141            _openssl_assert(res >= 1)
2142            pycert = X509._from_raw_x509_ptr(cert)
2143            result.append(pycert)
2144        return result
2145
2146    def get_peer_cert_chain(self):
2147        """
2148        Retrieve the other side's certificate (if any)
2149
2150        :return: A list of X509 instances giving the peer's certificate chain,
2151                 or None if it does not have one.
2152        """
2153        cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2154        if cert_stack == _ffi.NULL:
2155            return None
2156
2157        return self._cert_stack_to_list(cert_stack)
2158
2159    def get_verified_chain(self):
2160        """
2161        Retrieve the verified certificate chain of the peer including the
2162        peer's end entity certificate. It must be called after a session has
2163        been successfully established. If peer verification was not successful
2164        the chain may be incomplete, invalid, or None.
2165
2166        :return: A list of X509 instances giving the peer's verified
2167                 certificate chain, or None if it does not have one.
2168
2169        .. versionadded:: 20.0
2170        """
2171        # OpenSSL 1.1+
2172        cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2173        if cert_stack == _ffi.NULL:
2174            return None
2175
2176        return self._cert_stack_to_list(cert_stack)
2177
2178    def want_read(self):
2179        """
2180        Checks if more data has to be read from the transport layer to complete
2181        an operation.
2182
2183        :return: True iff more data has to be read
2184        """
2185        return _lib.SSL_want_read(self._ssl)
2186
2187    def want_write(self):
2188        """
2189        Checks if there is data to write to the transport layer to complete an
2190        operation.
2191
2192        :return: True iff there is data to write
2193        """
2194        return _lib.SSL_want_write(self._ssl)
2195
2196    def set_accept_state(self):
2197        """
2198        Set the connection to work in server mode. The handshake will be
2199        handled automatically by read/write.
2200
2201        :return: None
2202        """
2203        _lib.SSL_set_accept_state(self._ssl)
2204
2205    def set_connect_state(self):
2206        """
2207        Set the connection to work in client mode. The handshake will be
2208        handled automatically by read/write.
2209
2210        :return: None
2211        """
2212        _lib.SSL_set_connect_state(self._ssl)
2213
2214    def get_session(self):
2215        """
2216        Returns the Session currently used.
2217
2218        :return: An instance of :class:`OpenSSL.SSL.Session` or
2219            :obj:`None` if no session exists.
2220
2221        .. versionadded:: 0.14
2222        """
2223        session = _lib.SSL_get1_session(self._ssl)
2224        if session == _ffi.NULL:
2225            return None
2226
2227        pysession = Session.__new__(Session)
2228        pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
2229        return pysession
2230
2231    def set_session(self, session):
2232        """
2233        Set the session to be used when the TLS/SSL connection is established.
2234
2235        :param session: A Session instance representing the session to use.
2236        :returns: None
2237
2238        .. versionadded:: 0.14
2239        """
2240        if not isinstance(session, Session):
2241            raise TypeError("session must be a Session instance")
2242
2243        result = _lib.SSL_set_session(self._ssl, session._session)
2244        _openssl_assert(result == 1)
2245
2246    def _get_finished_message(self, function):
2247        """
2248        Helper to implement :meth:`get_finished` and
2249        :meth:`get_peer_finished`.
2250
2251        :param function: Either :data:`SSL_get_finished`: or
2252            :data:`SSL_get_peer_finished`.
2253
2254        :return: :data:`None` if the desired message has not yet been
2255            received, otherwise the contents of the message.
2256        :rtype: :class:`bytes` or :class:`NoneType`
2257        """
2258        # The OpenSSL documentation says nothing about what might happen if the
2259        # count argument given is zero.  Specifically, it doesn't say whether
2260        # the output buffer may be NULL in that case or not.  Inspection of the
2261        # implementation reveals that it calls memcpy() unconditionally.
2262        # Section 7.1.4, paragraph 1 of the C standard suggests that
2263        # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2264        # alone desirable) behavior (though it probably does on just about
2265        # every implementation...)
2266        #
2267        # Allocate a tiny buffer to pass in (instead of just passing NULL as
2268        # one might expect) for the initial call so as to be safe against this
2269        # potentially undefined behavior.
2270        empty = _ffi.new("char[]", 0)
2271        size = function(self._ssl, empty, 0)
2272        if size == 0:
2273            # No Finished message so far.
2274            return None
2275
2276        buf = _no_zero_allocator("char[]", size)
2277        function(self._ssl, buf, size)
2278        return _ffi.buffer(buf, size)[:]
2279
2280    def get_finished(self):
2281        """
2282        Obtain the latest TLS Finished message that we sent.
2283
2284        :return: The contents of the message or :obj:`None` if the TLS
2285            handshake has not yet completed.
2286        :rtype: :class:`bytes` or :class:`NoneType`
2287
2288        .. versionadded:: 0.15
2289        """
2290        return self._get_finished_message(_lib.SSL_get_finished)
2291
2292    def get_peer_finished(self):
2293        """
2294        Obtain the latest TLS Finished message that we received from the peer.
2295
2296        :return: The contents of the message or :obj:`None` if the TLS
2297            handshake has not yet completed.
2298        :rtype: :class:`bytes` or :class:`NoneType`
2299
2300        .. versionadded:: 0.15
2301        """
2302        return self._get_finished_message(_lib.SSL_get_peer_finished)
2303
2304    def get_cipher_name(self):
2305        """
2306        Obtain the name of the currently used cipher.
2307
2308        :returns: The name of the currently used cipher or :obj:`None`
2309            if no connection has been established.
2310        :rtype: :class:`unicode` or :class:`NoneType`
2311
2312        .. versionadded:: 0.15
2313        """
2314        cipher = _lib.SSL_get_current_cipher(self._ssl)
2315        if cipher == _ffi.NULL:
2316            return None
2317        else:
2318            name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2319            return name.decode("utf-8")
2320
2321    def get_cipher_bits(self):
2322        """
2323        Obtain the number of secret bits of the currently used cipher.
2324
2325        :returns: The number of secret bits of the currently used cipher
2326            or :obj:`None` if no connection has been established.
2327        :rtype: :class:`int` or :class:`NoneType`
2328
2329        .. versionadded:: 0.15
2330        """
2331        cipher = _lib.SSL_get_current_cipher(self._ssl)
2332        if cipher == _ffi.NULL:
2333            return None
2334        else:
2335            return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2336
2337    def get_cipher_version(self):
2338        """
2339        Obtain the protocol version of the currently used cipher.
2340
2341        :returns: The protocol name of the currently used cipher
2342            or :obj:`None` if no connection has been established.
2343        :rtype: :class:`unicode` or :class:`NoneType`
2344
2345        .. versionadded:: 0.15
2346        """
2347        cipher = _lib.SSL_get_current_cipher(self._ssl)
2348        if cipher == _ffi.NULL:
2349            return None
2350        else:
2351            version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
2352            return version.decode("utf-8")
2353
2354    def get_protocol_version_name(self):
2355        """
2356        Retrieve the protocol version of the current connection.
2357
2358        :returns: The TLS version of the current connection, for example
2359            the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
2360            for connections that were not successfully established.
2361        :rtype: :class:`unicode`
2362        """
2363        version = _ffi.string(_lib.SSL_get_version(self._ssl))
2364        return version.decode("utf-8")
2365
2366    def get_protocol_version(self):
2367        """
2368        Retrieve the SSL or TLS protocol version of the current connection.
2369
2370        :returns: The TLS version of the current connection.  For example,
2371            it will return ``0x769`` for connections made over TLS version 1.
2372        :rtype: :class:`int`
2373        """
2374        version = _lib.SSL_version(self._ssl)
2375        return version
2376
2377    @_requires_alpn
2378    def set_alpn_protos(self, protos):
2379        """
2380        Specify the client's ALPN protocol list.
2381
2382        These protocols are offered to the server during protocol negotiation.
2383
2384        :param protos: A list of the protocols to be offered to the server.
2385            This list should be a Python list of bytestrings representing the
2386            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2387        """
2388        # Take the list of protocols and join them together, prefixing them
2389        # with their lengths.
2390        protostr = b"".join(
2391            chain.from_iterable((int2byte(len(p)), p) for p in protos)
2392        )
2393
2394        # Build a C string from the list. We don't need to save this off
2395        # because OpenSSL immediately copies the data out.
2396        input_str = _ffi.new("unsigned char[]", protostr)
2397        _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
2398
2399    @_requires_alpn
2400    def get_alpn_proto_negotiated(self):
2401        """
2402        Get the protocol that was negotiated by ALPN.
2403
2404        :returns: A bytestring of the protocol name.  If no protocol has been
2405            negotiated yet, returns an empty string.
2406        """
2407        data = _ffi.new("unsigned char **")
2408        data_len = _ffi.new("unsigned int *")
2409
2410        _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2411
2412        if not data_len:
2413            return b""
2414
2415        return _ffi.buffer(data[0], data_len[0])[:]
2416
2417    def request_ocsp(self):
2418        """
2419        Called to request that the server sends stapled OCSP data, if
2420        available. If this is not called on the client side then the server
2421        will not send OCSP data. Should be used in conjunction with
2422        :meth:`Context.set_ocsp_client_callback`.
2423        """
2424        rc = _lib.SSL_set_tlsext_status_type(
2425            self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2426        )
2427        _openssl_assert(rc == 1)
2428
2429
2430# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2431# but is exercised mostly by the Context initializer.
2432_lib.SSL_library_init()
2433