churchyard / rpms / python38

Forked from rpms/python38 5 years ago
Clone
f7bd058
f7bd058
# HG changeset patch
f7bd058
# User Christian Heimes <christian@python.org>
f7bd058
# Date 1473110345 -7200
f7bd058
# Node ID 5c75b315152b714f7c84258ea511b461e2c06154
f7bd058
# Parent  82467d0dbaea31a7971d1429ca5f4a251a995f33
f7bd058
Issue #26470: Port ssl and hashlib module to OpenSSL 1.1.0.
f7bd058
f7bd058
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
f7bd058
--- a/Doc/library/ssl.rst
f7bd058
+++ b/Doc/library/ssl.rst
f7bd058
@@ -178,7 +178,7 @@ instead.
38b026e
    use.  Typically, the server chooses a particular protocol version, and the
38b026e
    client must adapt to the server's choice.  Most of the versions are not
38b026e
    interoperable with the other versions.  If not specified, the default is
38b026e
-   :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
38b026e
+   :data:`PROTOCOL_TLS`; it provides the most compatibility with other
38b026e
    versions.
38b026e
 
38b026e
    Here's a table showing which versions in a client (down the side) can connect
f7bd058
@@ -187,11 +187,11 @@ instead.
38b026e
      .. table::
38b026e
 
38b026e
        ========================  =========  =========  ==========  =========  ===========  ===========
38b026e
-        *client* / **server**    **SSLv2**  **SSLv3**  **SSLv23**  **TLSv1**  **TLSv1.1**  **TLSv1.2**
38b026e
+        *client* / **server**    **SSLv2**  **SSLv3**  **TLS**     **TLSv1**  **TLSv1.1**  **TLSv1.2**
38b026e
        ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
38b026e
         *SSLv2*                    yes        no         yes         no         no         no
38b026e
         *SSLv3*                    no         yes        yes         no         no         no
38b026e
-        *SSLv23*                   no         yes        yes         yes        yes        yes
38b026e
+        *TLS* (*SSLv23*)           no         yes        yes         yes        yes        yes
38b026e
         *TLSv1*                    no         no         yes         yes        no         no
38b026e
         *TLSv1.1*                  no         no         yes         no         yes        no
38b026e
         *TLSv1.2*                  no         no         yes         no         no         yes
f7bd058
@@ -244,7 +244,7 @@ purposes.
38b026e
    :const:`None`, this function can choose to trust the system's default
38b026e
    CA certificates instead.
38b026e
 
38b026e
-   The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
38b026e
+   The settings are: :data:`PROTOCOL_TLS`, :data:`OP_NO_SSLv2`, and
38b026e
    :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
38b026e
    without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
38b026e
    as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
f7bd058
@@ -316,6 +316,11 @@ Random generation
38b026e
 
38b026e
    .. versionadded:: 3.3
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
38b026e
+      :func:`ssl.RAND_bytes` instead.
38b026e
+
38b026e
 .. function:: RAND_status()
38b026e
 
38b026e
    Return ``True`` if the SSL pseudo-random number generator has been seeded
f7bd058
@@ -334,7 +339,7 @@ Random generation
38b026e
    See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
38b026e
    of entropy-gathering daemons.
38b026e
 
38b026e
-   Availability: not available with LibreSSL.
38b026e
+   Availability: not available with LibreSSL and OpenSSL > 1.1.0
38b026e
 
38b026e
 .. function:: RAND_add(bytes, entropy)
38b026e
 
f7bd058
@@ -409,7 +414,7 @@ Certificate handling
38b026e
       previously. Return an integer (no fractions of a second in the
38b026e
       input format)
38b026e
 
38b026e
-.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)
38b026e
+.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None)
38b026e
 
38b026e
    Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
38b026e
    *port-number*) pair, fetches the server's certificate, and returns it as a
f7bd058
@@ -425,7 +430,7 @@ Certificate handling
38b026e
 
38b026e
    .. versionchanged:: 3.5
38b026e
       The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to
38b026e
-      :data:`PROTOCOL_SSLv23` for maximum compatibility with modern servers.
38b026e
+      :data:`PROTOCOL_TLS` for maximum compatibility with modern servers.
38b026e
 
38b026e
 .. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
38b026e
 
f7bd058
@@ -451,6 +456,9 @@ Certificate handling
38b026e
    * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
38b026e
    * :attr:`openssl_capath` - hard coded path to a capath directory
38b026e
 
38b026e
+   Availability: LibreSSL ignores the environment vars
38b026e
+   :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`
38b026e
+
38b026e
    .. versionadded:: 3.4
38b026e
 
38b026e
 .. function:: enum_certificates(store_name)
f7bd058
@@ -568,11 +576,21 @@ Constants
38b026e
 
38b026e
    .. versionadded:: 3.4.4
38b026e
 
38b026e
-.. data:: PROTOCOL_SSLv23
38b026e
+.. data:: PROTOCOL_TLS
38b026e
 
38b026e
    Selects the highest protocol version that both the client and server support.
38b026e
    Despite the name, this option can select "TLS" protocols as well as "SSL".
38b026e
 
f7bd058
+   .. versionadded:: 3.5.3
38b026e
+
38b026e
+.. data:: PROTOCOL_SSLv23
38b026e
+
38b026e
+   Alias for data:`PROTOCOL_TLS`.
38b026e
+
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      Use data:`PROTOCOL_TLS` instead.
38b026e
+
38b026e
 .. data:: PROTOCOL_SSLv2
38b026e
 
38b026e
    Selects SSL version 2 as the channel encryption protocol.
f7bd058
@@ -584,6 +602,10 @@ Constants
38b026e
 
38b026e
       SSL version 2 is insecure.  Its use is highly discouraged.
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has removed support for SSLv2.
38b026e
+
38b026e
 .. data:: PROTOCOL_SSLv3
38b026e
 
38b026e
    Selects SSL version 3 as the channel encryption protocol.
f7bd058
@@ -595,10 +617,20 @@ Constants
38b026e
 
38b026e
       SSL version 3 is insecure.  Its use is highly discouraged.
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has deprecated all version specific protocols. Use the default
38b026e
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
38b026e
+
38b026e
 .. data:: PROTOCOL_TLSv1
38b026e
 
38b026e
    Selects TLS version 1.0 as the channel encryption protocol.
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has deprecated all version specific protocols. Use the default
38b026e
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
38b026e
+
38b026e
 .. data:: PROTOCOL_TLSv1_1
38b026e
 
38b026e
    Selects TLS version 1.1 as the channel encryption protocol.
f7bd058
@@ -606,6 +638,11 @@ Constants
38b026e
 
38b026e
    .. versionadded:: 3.4
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has deprecated all version specific protocols. Use the default
38b026e
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
38b026e
+
38b026e
 .. data:: PROTOCOL_TLSv1_2
38b026e
 
38b026e
    Selects TLS version 1.2 as the channel encryption protocol. This is the
f7bd058
@@ -614,6 +651,11 @@ Constants
38b026e
 
38b026e
    .. versionadded:: 3.4
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      OpenSSL has deprecated all version specific protocols. Use the default
38b026e
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
38b026e
+
38b026e
 .. data:: OP_ALL
38b026e
 
38b026e
    Enables workarounds for various bugs present in other SSL implementations.
f7bd058
@@ -625,23 +667,32 @@ Constants
38b026e
 .. data:: OP_NO_SSLv2
38b026e
 
38b026e
    Prevents an SSLv2 connection.  This option is only applicable in
38b026e
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
38b026e
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
38b026e
    choosing SSLv2 as the protocol version.
38b026e
 
38b026e
    .. versionadded:: 3.2
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      SSLv2 is deprecated
38b026e
+
38b026e
+
38b026e
 .. data:: OP_NO_SSLv3
38b026e
 
38b026e
    Prevents an SSLv3 connection.  This option is only applicable in
38b026e
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
38b026e
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
38b026e
    choosing SSLv3 as the protocol version.
38b026e
 
38b026e
    .. versionadded:: 3.2
38b026e
 
f7bd058
+   .. deprecated:: 3.5.3
38b026e
+
38b026e
+      SSLv3 is deprecated
38b026e
+
38b026e
 .. data:: OP_NO_TLSv1
38b026e
 
38b026e
    Prevents a TLSv1 connection.  This option is only applicable in
38b026e
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
38b026e
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
38b026e
    choosing TLSv1 as the protocol version.
38b026e
 
38b026e
    .. versionadded:: 3.2
f7bd058
@@ -649,7 +700,7 @@ Constants
38b026e
 .. data:: OP_NO_TLSv1_1
38b026e
 
38b026e
    Prevents a TLSv1.1 connection. This option is only applicable in conjunction
38b026e
-   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
38b026e
+   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as
38b026e
    the protocol version. Available only with openssl version 1.0.1+.
38b026e
 
38b026e
    .. versionadded:: 3.4
f7bd058
@@ -657,7 +708,7 @@ Constants
38b026e
 .. data:: OP_NO_TLSv1_2
38b026e
 
38b026e
    Prevents a TLSv1.2 connection. This option is only applicable in conjunction
38b026e
-   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
38b026e
+   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as
38b026e
    the protocol version. Available only with openssl version 1.0.1+.
38b026e
 
38b026e
    .. versionadded:: 3.4
f7bd058
@@ -1081,17 +1132,21 @@ such as SSL configuration options, certi
38b026e
 It also manages a cache of SSL sessions for server-side sockets, in order
38b026e
 to speed up repeated connections from the same clients.
38b026e
 
38b026e
-.. class:: SSLContext(protocol)
f7bd058
-
38b026e
-   Create a new SSL context.  You must pass *protocol* which must be one
f7bd058
+.. class:: SSLContext(protocol=PROTOCOL_TLS)
f7bd058
+
38b026e
+   Create a new SSL context.  You may pass *protocol* which must be one
38b026e
    of the ``PROTOCOL_*`` constants defined in this module.
38b026e
-   :data:`PROTOCOL_SSLv23` is currently recommended for maximum
38b026e
-   interoperability.
38b026e
+   :data:`PROTOCOL_TLS` is currently recommended for maximum
38b026e
+   interoperability and default value.
38b026e
 
38b026e
    .. seealso::
38b026e
       :func:`create_default_context` lets the :mod:`ssl` module choose
38b026e
       security settings for a given purpose.
38b026e
 
f7bd058
+   .. versionchanged:: 3.5.3
38b026e
+
38b026e
+      :data:`PROTOCOL_TLS` is the default value.
38b026e
+
38b026e
 
38b026e
 :class:`SSLContext` objects have the following methods and attributes:
38b026e
 
f7bd058
@@ -1232,6 +1287,9 @@ to speed up repeated connections from th
38b026e
    This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
38b026e
    False.
38b026e
 
38b026e
+   OpenSSL 1.1.0+ will abort the handshake and raise :exc:`SSLError` when
38b026e
+   both sides support ALPN but cannot agree on a protocol.
38b026e
+
38b026e
    .. versionadded:: 3.5
38b026e
 
38b026e
 .. method:: SSLContext.set_npn_protocols(protocols)
f7bd058
@@ -1598,7 +1656,7 @@ If you prefer to tune security settings 
38b026e
 a context from scratch (but beware that you might not get the settings
38b026e
 right)::
38b026e
 
38b026e
-   >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
38b026e
+   >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS)
38b026e
    >>> context.verify_mode = ssl.CERT_REQUIRED
38b026e
    >>> context.check_hostname = True
38b026e
    >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
f7bd058
@@ -1999,15 +2057,17 @@ Protocol versions
38b026e
 
38b026e
 SSL versions 2 and 3 are considered insecure and are therefore dangerous to
38b026e
 use.  If you want maximum compatibility between clients and servers, it is
38b026e
-recommended to use :const:`PROTOCOL_SSLv23` as the protocol version and then
38b026e
+recommended to use :const:`PROTOCOL_TLS` as the protocol version and then
38b026e
 disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
38b026e
 attribute::
38b026e
 
38b026e
-   context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
38b026e
+   context = ssl.SSLContext(ssl.PROTOCOL_TLS)
38b026e
    context.options |= ssl.OP_NO_SSLv2
38b026e
    context.options |= ssl.OP_NO_SSLv3
f7bd058
-
f7bd058
-The SSL context created above will only allow TLSv1 and later (if
38b026e
+   context.options |= ssl.OP_NO_TLSv1
38b026e
+   context.options |= ssl.OP_NO_TLSv1_1
f7bd058
+
38b026e
+The SSL context created above will only allow TLSv1.2 and later (if
38b026e
 supported by your system) connections.
38b026e
 
38b026e
 Cipher selection
f7bd058
diff --git a/Lib/ssl.py b/Lib/ssl.py
f7bd058
--- a/Lib/ssl.py
f7bd058
+++ b/Lib/ssl.py
38b026e
@@ -51,6 +51,7 @@ The following constants identify various
38b026e
 PROTOCOL_SSLv2
38b026e
 PROTOCOL_SSLv3
38b026e
 PROTOCOL_SSLv23
38b026e
+PROTOCOL_TLS
38b026e
 PROTOCOL_TLSv1
38b026e
 PROTOCOL_TLSv1_1
38b026e
 PROTOCOL_TLSv1_2
38b026e
@@ -128,9 +129,10 @@ from _ssl import _OPENSSL_API_VERSION
38b026e
 
38b026e
 _IntEnum._convert(
38b026e
         '_SSLMethod', __name__,
38b026e
-        lambda name: name.startswith('PROTOCOL_'),
38b026e
+        lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
38b026e
         source=_ssl)
38b026e
 
38b026e
+PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
38b026e
 _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
38b026e
 
38b026e
 try:
38b026e
@@ -357,13 +359,13 @@ class SSLContext(_SSLContext):
38b026e
     __slots__ = ('protocol', '__weakref__')
38b026e
     _windows_cert_stores = ("CA", "ROOT")
38b026e
 
38b026e
-    def __new__(cls, protocol, *args, **kwargs):
38b026e
+    def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
38b026e
         self = _SSLContext.__new__(cls, protocol)
38b026e
         if protocol != _SSLv2_IF_EXISTS:
38b026e
             self.set_ciphers(_DEFAULT_CIPHERS)
38b026e
         return self
38b026e
 
38b026e
-    def __init__(self, protocol):
38b026e
+    def __init__(self, protocol=PROTOCOL_TLS):
38b026e
         self.protocol = protocol
38b026e
 
38b026e
     def wrap_socket(self, sock, server_side=False,
38b026e
@@ -438,7 +440,7 @@ def create_default_context(purpose=Purpo
38b026e
     if not isinstance(purpose, _ASN1Object):
38b026e
         raise TypeError(purpose)
38b026e
 
38b026e
-    context = SSLContext(PROTOCOL_SSLv23)
38b026e
+    context = SSLContext(PROTOCOL_TLS)
38b026e
 
38b026e
     # SSLv2 considered harmful.
38b026e
     context.options |= OP_NO_SSLv2
38b026e
@@ -475,7 +477,7 @@ def create_default_context(purpose=Purpo
38b026e
         context.load_default_certs(purpose)
38b026e
     return context
38b026e
 
38b026e
-def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
38b026e
+def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
38b026e
                            check_hostname=False, purpose=Purpose.SERVER_AUTH,
38b026e
                            certfile=None, keyfile=None,
38b026e
                            cafile=None, capath=None, cadata=None):
38b026e
@@ -666,7 +668,7 @@ class SSLSocket(socket):
38b026e
 
38b026e
     def __init__(self, sock=None, keyfile=None, certfile=None,
38b026e
                  server_side=False, cert_reqs=CERT_NONE,
38b026e
-                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
38b026e
+                 ssl_version=PROTOCOL_TLS, ca_certs=None,
38b026e
                  do_handshake_on_connect=True,
38b026e
                  family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
38b026e
                  suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
38b026e
@@ -1056,7 +1058,7 @@ class SSLSocket(socket):
38b026e
 
38b026e
 def wrap_socket(sock, keyfile=None, certfile=None,
38b026e
                 server_side=False, cert_reqs=CERT_NONE,
38b026e
-                ssl_version=PROTOCOL_SSLv23, ca_certs=None,
38b026e
+                ssl_version=PROTOCOL_TLS, ca_certs=None,
38b026e
                 do_handshake_on_connect=True,
38b026e
                 suppress_ragged_eofs=True,
38b026e
                 ciphers=None):
38b026e
@@ -1125,7 +1127,7 @@ def PEM_cert_to_DER_cert(pem_cert_string
38b026e
     d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
38b026e
     return base64.decodebytes(d.encode('ASCII', 'strict'))
38b026e
 
38b026e
-def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
38b026e
+def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
38b026e
     """Retrieve the certificate from the server at the specified address,
38b026e
     and return it as a PEM-encoded string.
38b026e
     If 'ca_certs' is specified, validate the server cert against it.
f7bd058
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
f7bd058
--- a/Lib/test/test_ssl.py
f7bd058
+++ b/Lib/test/test_ssl.py
38b026e
@@ -23,6 +23,9 @@ ssl = support.import_module("ssl")
38b026e
 
38b026e
 PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
38b026e
 HOST = support.HOST
38b026e
+IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL')
38b026e
+IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0)
38b026e
+
38b026e
 
38b026e
 def data_file(*name):
38b026e
     return os.path.join(os.path.dirname(__file__), *name)
38b026e
@@ -143,8 +146,8 @@ class BasicSocketTests(unittest.TestCase
38b026e
     def test_str_for_enums(self):
38b026e
         # Make sure that the PROTOCOL_* constants have enum-like string
38b026e
         # reprs.
38b026e
-        proto = ssl.PROTOCOL_SSLv23
38b026e
-        self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_SSLv23')
38b026e
+        proto = ssl.PROTOCOL_TLS
38b026e
+        self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS')
38b026e
         ctx = ssl.SSLContext(proto)
38b026e
         self.assertIs(ctx.protocol, proto)
38b026e
 
38b026e
@@ -312,8 +315,8 @@ class BasicSocketTests(unittest.TestCase
38b026e
         self.assertGreaterEqual(status, 0)
38b026e
         self.assertLessEqual(status, 15)
38b026e
         # Version string as returned by {Open,Libre}SSL, the format might change
38b026e
-        if "LibreSSL" in s:
38b026e
-            self.assertTrue(s.startswith("LibreSSL {:d}.{:d}".format(major, minor)),
38b026e
+        if IS_LIBRESSL:
38b026e
+            self.assertTrue(s.startswith("LibreSSL {:d}".format(major)),
38b026e
                             (s, t, hex(n)))
38b026e
         else:
38b026e
             self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
38b026e
@@ -790,7 +793,8 @@ class ContextTests(unittest.TestCase):
38b026e
     def test_constructor(self):
38b026e
         for protocol in PROTOCOLS:
38b026e
             ssl.SSLContext(protocol)
38b026e
-        self.assertRaises(TypeError, ssl.SSLContext)
38b026e
+        ctx = ssl.SSLContext()
38b026e
+        self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
38b026e
         self.assertRaises(ValueError, ssl.SSLContext, -1)
38b026e
         self.assertRaises(ValueError, ssl.SSLContext, 42)
38b026e
 
38b026e
@@ -811,15 +815,15 @@ class ContextTests(unittest.TestCase):
38b026e
     def test_options(self):
38b026e
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
38b026e
         # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
38b026e
-        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3,
38b026e
-                         ctx.options)
38b026e
+        default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
38b026e
+        if not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0):
38b026e
+            default |= ssl.OP_NO_COMPRESSION
38b026e
+        self.assertEqual(default, ctx.options)
38b026e
         ctx.options |= ssl.OP_NO_TLSv1
38b026e
-        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1,
38b026e
-                         ctx.options)
38b026e
+        self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options)
38b026e
         if can_clear_options():
38b026e
-            ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1
38b026e
-            self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3,
38b026e
-                             ctx.options)
38b026e
+            ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1)
38b026e
+            self.assertEqual(default, ctx.options)
38b026e
             ctx.options = 0
38b026e
             # Ubuntu has OP_NO_SSLv3 forced on by default
38b026e
             self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
38b026e
@@ -1155,6 +1159,7 @@ class ContextTests(unittest.TestCase):
38b026e
         self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
38b026e
 
38b026e
     @unittest.skipIf(sys.platform == "win32", "not-Windows specific")
38b026e
+    @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars")
38b026e
     def test_load_default_certs_env(self):
38b026e
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
38b026e
         with support.EnvironmentVarGuard() as env:
38b026e
@@ -1750,13 +1755,13 @@ class NetworkedBIOTests(unittest.TestCas
38b026e
             sslobj = ctx.wrap_bio(incoming, outgoing, False, REMOTE_HOST)
38b026e
             self.assertIs(sslobj._sslobj.owner, sslobj)
38b026e
             self.assertIsNone(sslobj.cipher())
38b026e
-            self.assertIsNone(sslobj.shared_ciphers())
38b026e
+            self.assertIsNotNone(sslobj.shared_ciphers())
38b026e
             self.assertRaises(ValueError, sslobj.getpeercert)
38b026e
             if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
38b026e
                 self.assertIsNone(sslobj.get_channel_binding('tls-unique'))
38b026e
             self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
38b026e
             self.assertTrue(sslobj.cipher())
38b026e
-            self.assertIsNone(sslobj.shared_ciphers())
38b026e
+            self.assertIsNotNone(sslobj.shared_ciphers())
38b026e
             self.assertTrue(sslobj.getpeercert())
38b026e
             if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
38b026e
                 self.assertTrue(sslobj.get_channel_binding('tls-unique'))
f7bd058
@@ -2993,7 +2998,7 @@ else:
38b026e
                 with context.wrap_socket(socket.socket()) as s:
38b026e
                     self.assertIs(s.version(), None)
38b026e
                     s.connect((HOST, server.port))
38b026e
-                    self.assertEqual(s.version(), "TLSv1")
38b026e
+                    self.assertEqual(s.version(), 'TLSv1')
38b026e
                 self.assertIs(s.version(), None)
38b026e
 
38b026e
         @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL")
f7bd058
@@ -3135,24 +3140,36 @@ else:
38b026e
                 (['http/3.0', 'http/4.0'], None)
38b026e
             ]
38b026e
             for client_protocols, expected in protocol_tests:
38b026e
-                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
38b026e
+                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
38b026e
                 server_context.load_cert_chain(CERTFILE)
38b026e
                 server_context.set_alpn_protocols(server_protocols)
38b026e
-                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
38b026e
+                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
38b026e
                 client_context.load_cert_chain(CERTFILE)
38b026e
                 client_context.set_alpn_protocols(client_protocols)
38b026e
-                stats = server_params_test(client_context, server_context,
38b026e
-                                           chatty=True, connectionchatty=True)
f7bd058
-
38b026e
-                msg = "failed trying %s (s) and %s (c).\n" \
38b026e
-                      "was expecting %s, but got %%s from the %%s" \
38b026e
-                          % (str(server_protocols), str(client_protocols),
38b026e
-                             str(expected))
38b026e
-                client_result = stats['client_alpn_protocol']
38b026e
-                self.assertEqual(client_result, expected, msg % (client_result, "client"))
38b026e
-                server_result = stats['server_alpn_protocols'][-1] \
38b026e
-                    if len(stats['server_alpn_protocols']) else 'nothing'
38b026e
-                self.assertEqual(server_result, expected, msg % (server_result, "server"))
f7bd058
+
38b026e
+                try:
38b026e
+                    stats = server_params_test(client_context,
38b026e
+                                               server_context,
38b026e
+                                               chatty=True,
38b026e
+                                               connectionchatty=True)
38b026e
+                except ssl.SSLError as e:
38b026e
+                    stats = e
38b026e
+
38b026e
+                if expected is None and IS_OPENSSL_1_1:
38b026e
+                    # OpenSSL 1.1.0 raises handshake error
38b026e
+                    self.assertIsInstance(stats, ssl.SSLError)
38b026e
+                else:
38b026e
+                    msg = "failed trying %s (s) and %s (c).\n" \
38b026e
+                        "was expecting %s, but got %%s from the %%s" \
38b026e
+                            % (str(server_protocols), str(client_protocols),
38b026e
+                                str(expected))
38b026e
+                    client_result = stats['client_alpn_protocol']
38b026e
+                    self.assertEqual(client_result, expected,
38b026e
+                                     msg % (client_result, "client"))
38b026e
+                    server_result = stats['server_alpn_protocols'][-1] \
38b026e
+                        if len(stats['server_alpn_protocols']) else 'nothing'
38b026e
+                    self.assertEqual(server_result, expected,
38b026e
+                                     msg % (server_result, "server"))
38b026e
 
38b026e
         def test_selected_npn_protocol(self):
38b026e
             # selected_npn_protocol() is None unless NPN is used
f7bd058
@@ -3300,13 +3317,23 @@ else:
38b026e
             client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
38b026e
             client_context.verify_mode = ssl.CERT_REQUIRED
38b026e
             client_context.load_verify_locations(SIGNING_CA)
38b026e
-            client_context.set_ciphers("RC4")
38b026e
-            server_context.set_ciphers("AES:RC4")
38b026e
+            if ssl.OPENSSL_VERSION_INFO >= (1, 0, 2):
38b026e
+                client_context.set_ciphers("AES128:AES256")
38b026e
+                server_context.set_ciphers("AES256")
38b026e
+                alg1 = "AES256"
38b026e
+                alg2 = "AES-256"
38b026e
+            else:
38b026e
+                client_context.set_ciphers("AES:3DES")
38b026e
+                server_context.set_ciphers("3DES")
38b026e
+                alg1 = "3DES"
38b026e
+                alg2 = "DES-CBC3"
38b026e
+
38b026e
             stats = server_params_test(client_context, server_context)
38b026e
             ciphers = stats['server_shared_ciphers'][0]
38b026e
             self.assertGreater(len(ciphers), 0)
38b026e
             for name, tls_version, bits in ciphers:
38b026e
-                self.assertIn("RC4", name.split("-"))
38b026e
+                if not alg1 in name.split("-") and alg2 not in name:
38b026e
+                    self.fail(name)
38b026e
 
38b026e
         def test_read_write_after_close_raises_valuerror(self):
38b026e
             context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
f7bd058
f7bd058
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
f7bd058
--- a/Modules/_hashopenssl.c
f7bd058
+++ b/Modules/_hashopenssl.c
f7bd058
@@ -21,7 +21,6 @@
f7bd058
 
f7bd058
 /* EVP is the preferred interface to hashing in OpenSSL */
38b026e
 #include <openssl/evp.h>
38b026e
-#include <openssl/hmac.h>
38b026e
 /* We use the object interface to discover what hashes OpenSSL supports. */
38b026e
 #include <openssl/objects.h>
38b026e
 #include "openssl/err.h"
f7bd058
@@ -32,11 +31,22 @@
38b026e
 #define HASH_OBJ_CONSTRUCTOR 0
38b026e
 #endif
38b026e
 
38b026e
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
38b026e
+/* OpenSSL < 1.1.0 */
38b026e
+#define EVP_MD_CTX_new EVP_MD_CTX_create
38b026e
+#define EVP_MD_CTX_free EVP_MD_CTX_destroy
38b026e
+#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
38b026e
+#include <openssl/hmac.h>
38b026e
+#else
38b026e
+/* OpenSSL >= 1.1.0 */
38b026e
+#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
38b026e
+#endif
38b026e
+
38b026e
 
38b026e
 typedef struct {
38b026e
     PyObject_HEAD
38b026e
     PyObject            *name;  /* name of this hash algorithm */
38b026e
-    EVP_MD_CTX           ctx;   /* OpenSSL message digest context */
38b026e
+    EVP_MD_CTX          *ctx;   /* OpenSSL message digest context */
38b026e
 #ifdef WITH_THREAD
38b026e
     PyThread_type_lock   lock;  /* OpenSSL context lock */
38b026e
 #endif
f7bd058
@@ -48,7 +58,6 @@ static PyTypeObject EVPtype;
f7bd058
 
f7bd058
 #define DEFINE_CONSTS_FOR_NEW(Name)  \
f7bd058
     static PyObject *CONST_ ## Name ## _name_obj = NULL; \
f7bd058
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
f7bd058
     static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
f7bd058
 
f7bd058
 DEFINE_CONSTS_FOR_NEW(md5)
f7bd058
@@ -59,19 +68,57 @@ DEFINE_CONSTS_FOR_NEW(sha384)
38b026e
 DEFINE_CONSTS_FOR_NEW(sha512)
38b026e
 
38b026e
 
38b026e
+/* LCOV_EXCL_START */
38b026e
+static PyObject *
38b026e
+_setException(PyObject *exc)
38b026e
+{
38b026e
+    unsigned long errcode;
38b026e
+    const char *lib, *func, *reason;
38b026e
+
38b026e
+    errcode = ERR_peek_last_error();
38b026e
+    if (!errcode) {
38b026e
+        PyErr_SetString(exc, "unknown reasons");
38b026e
+        return NULL;
38b026e
+    }
38b026e
+    ERR_clear_error();
38b026e
+
38b026e
+    lib = ERR_lib_error_string(errcode);
38b026e
+    func = ERR_func_error_string(errcode);
38b026e
+    reason = ERR_reason_error_string(errcode);
38b026e
+
38b026e
+    if (lib && func) {
38b026e
+        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
38b026e
+    }
38b026e
+    else if (lib) {
38b026e
+        PyErr_Format(exc, "[%s] %s", lib, reason);
38b026e
+    }
38b026e
+    else {
38b026e
+        PyErr_SetString(exc, reason);
38b026e
+    }
38b026e
+    return NULL;
38b026e
+}
38b026e
+/* LCOV_EXCL_STOP */
38b026e
+
38b026e
 static EVPobject *
38b026e
 newEVPobject(PyObject *name)
38b026e
 {
38b026e
     EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
38b026e
+    if (retval == NULL) {
38b026e
+        return NULL;
38b026e
+    }
38b026e
+
38b026e
+    retval->ctx = EVP_MD_CTX_new();
38b026e
+    if (retval->ctx == NULL) {
38b026e
+        PyErr_NoMemory();
38b026e
+        return NULL;
38b026e
+    }
38b026e
 
38b026e
     /* save the name for .name to return */
38b026e
-    if (retval != NULL) {
38b026e
-        Py_INCREF(name);
38b026e
-        retval->name = name;
38b026e
+    Py_INCREF(name);
38b026e
+    retval->name = name;
38b026e
 #ifdef WITH_THREAD
38b026e
-        retval->lock = NULL;
38b026e
+    retval->lock = NULL;
38b026e
 #endif
38b026e
-    }
38b026e
 
38b026e
     return retval;
38b026e
 }
f7bd058
@@ -86,7 +133,7 @@ EVP_hash(EVPobject *self, const void *vp
38b026e
             process = MUNCH_SIZE;
38b026e
         else
38b026e
             process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
38b026e
-        EVP_DigestUpdate(&self->ctx, (const void*)cp, process);
38b026e
+        EVP_DigestUpdate(self->ctx, (const void*)cp, process);
38b026e
         len -= process;
38b026e
         cp += process;
38b026e
     }
f7bd058
@@ -101,16 +148,19 @@ EVP_dealloc(EVPobject *self)
38b026e
     if (self->lock != NULL)
38b026e
         PyThread_free_lock(self->lock);
38b026e
 #endif
38b026e
-    EVP_MD_CTX_cleanup(&self->ctx);
38b026e
+    EVP_MD_CTX_free(self->ctx);
38b026e
     Py_XDECREF(self->name);
38b026e
     PyObject_Del(self);
38b026e
 }
38b026e
 
38b026e
-static void locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
38b026e
+static int
38b026e
+locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
38b026e
 {
38b026e
+    int result;
38b026e
     ENTER_HASHLIB(self);
38b026e
-    EVP_MD_CTX_copy(new_ctx_p, &self->ctx);
38b026e
+    result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
38b026e
     LEAVE_HASHLIB(self);
38b026e
+    return result;
38b026e
 }
38b026e
 
38b026e
 /* External methods for a hash object */
f7bd058
@@ -126,7 +176,9 @@ EVP_copy(EVPobject *self, PyObject *unus
38b026e
     if ( (newobj = newEVPobject(self->name))==NULL)
38b026e
         return NULL;
38b026e
 
38b026e
-    locked_EVP_MD_CTX_copy(&newobj->ctx, self);
38b026e
+    if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
38b026e
+        return _setException(PyExc_ValueError);
38b026e
+    }
38b026e
     return (PyObject *)newobj;
38b026e
 }
38b026e
 
f7bd058
@@ -137,16 +189,24 @@ static PyObject *
38b026e
 EVP_digest(EVPobject *self, PyObject *unused)
38b026e
 {
38b026e
     unsigned char digest[EVP_MAX_MD_SIZE];
38b026e
-    EVP_MD_CTX temp_ctx;
38b026e
+    EVP_MD_CTX *temp_ctx;
38b026e
     PyObject *retval;
38b026e
     unsigned int digest_size;
38b026e
 
38b026e
-    locked_EVP_MD_CTX_copy(&temp_ctx, self);
38b026e
-    digest_size = EVP_MD_CTX_size(&temp_ctx);
38b026e
-    EVP_DigestFinal(&temp_ctx, digest, NULL);
38b026e
+    temp_ctx = EVP_MD_CTX_new();
38b026e
+    if (temp_ctx == NULL) {
38b026e
+        PyErr_NoMemory();
38b026e
+        return NULL;
38b026e
+    }
38b026e
+
38b026e
+    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
38b026e
+        return _setException(PyExc_ValueError);
38b026e
+    }
38b026e
+    digest_size = EVP_MD_CTX_size(temp_ctx);
38b026e
+    EVP_DigestFinal(temp_ctx, digest, NULL);
38b026e
 
38b026e
     retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
38b026e
-    EVP_MD_CTX_cleanup(&temp_ctx);
38b026e
+    EVP_MD_CTX_free(temp_ctx);
38b026e
     return retval;
38b026e
 }
38b026e
 
f7bd058
@@ -157,15 +217,23 @@ static PyObject *
38b026e
 EVP_hexdigest(EVPobject *self, PyObject *unused)
38b026e
 {
38b026e
     unsigned char digest[EVP_MAX_MD_SIZE];
38b026e
-    EVP_MD_CTX temp_ctx;
38b026e
+    EVP_MD_CTX *temp_ctx;
38b026e
     unsigned int digest_size;
38b026e
 
38b026e
+    temp_ctx = EVP_MD_CTX_new();
38b026e
+    if (temp_ctx == NULL) {
38b026e
+        PyErr_NoMemory();
38b026e
+        return NULL;
38b026e
+    }
38b026e
+
38b026e
     /* Get the raw (binary) digest value */
38b026e
-    locked_EVP_MD_CTX_copy(&temp_ctx, self);
38b026e
-    digest_size = EVP_MD_CTX_size(&temp_ctx);
38b026e
-    EVP_DigestFinal(&temp_ctx, digest, NULL);
38b026e
+    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
38b026e
+        return _setException(PyExc_ValueError);
38b026e
+    }
38b026e
+    digest_size = EVP_MD_CTX_size(temp_ctx);
38b026e
+    EVP_DigestFinal(temp_ctx, digest, NULL);
38b026e
 
38b026e
-    EVP_MD_CTX_cleanup(&temp_ctx);
38b026e
+    EVP_MD_CTX_free(temp_ctx);
38b026e
 
38b026e
     return _Py_strhex((const char *)digest, digest_size);
38b026e
 }
f7bd058
@@ -219,7 +287,7 @@ static PyObject *
38b026e
 EVP_get_block_size(EVPobject *self, void *closure)
38b026e
 {
38b026e
     long block_size;
38b026e
-    block_size = EVP_MD_CTX_block_size(&self->ctx);
38b026e
+    block_size = EVP_MD_CTX_block_size(self->ctx);
38b026e
     return PyLong_FromLong(block_size);
38b026e
 }
38b026e
 
f7bd058
@@ -227,7 +295,7 @@ static PyObject *
38b026e
 EVP_get_digest_size(EVPobject *self, void *closure)
38b026e
 {
38b026e
     long size;
38b026e
-    size = EVP_MD_CTX_size(&self->ctx);
38b026e
+    size = EVP_MD_CTX_size(self->ctx);
38b026e
     return PyLong_FromLong(size);
38b026e
 }
38b026e
 
f7bd058
@@ -288,7 +356,7 @@ EVP_tp_init(EVPobject *self, PyObject *a
38b026e
             PyBuffer_Release(&view);
38b026e
         return -1;
38b026e
     }
f7bd058
-    EVP_DigestInit(&self->ctx, digest);
f7bd058
+    EVP_DigestInit(self->ctx, digest);
f7bd058
 
f7bd058
     self->name = name_obj;
f7bd058
     Py_INCREF(self->name);
f7bd058
@@ -385,9 +453,9 @@ EVPnew(PyObject *name_obj,
38b026e
         return NULL;
38b026e
 
38b026e
     if (initial_ctx) {
38b026e
-        EVP_MD_CTX_copy(&self->ctx, initial_ctx);
38b026e
+        EVP_MD_CTX_copy(self->ctx, initial_ctx);
38b026e
     } else {
f7bd058
-        EVP_DigestInit(&self->ctx, digest);
f7bd058
+        EVP_DigestInit(self->ctx, digest);
f7bd058
     }
f7bd058
 
f7bd058
     if (cp && len) {
f7bd058
@@ -453,6 +521,7 @@ EVP_new(PyObject *self, PyObject *args, 
38b026e
 
38b026e
 #define PY_PBKDF2_HMAC 1
38b026e
 
38b026e
+#if !HAS_FAST_PKCS5_PBKDF2_HMAC
38b026e
 /* Improved implementation of PKCS5_PBKDF2_HMAC()
38b026e
  *
38b026e
  * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
f7bd058
@@ -534,37 +603,8 @@ PKCS5_PBKDF2_HMAC_fast(const char *pass,
38b026e
     HMAC_CTX_cleanup(&hctx_tpl);
38b026e
     return 1;
38b026e
 }
38b026e
+#endif
38b026e
 
38b026e
-/* LCOV_EXCL_START */
38b026e
-static PyObject *
38b026e
-_setException(PyObject *exc)
38b026e
-{
38b026e
-    unsigned long errcode;
38b026e
-    const char *lib, *func, *reason;
38b026e
-
38b026e
-    errcode = ERR_peek_last_error();
38b026e
-    if (!errcode) {
38b026e
-        PyErr_SetString(exc, "unknown reasons");
38b026e
-        return NULL;
38b026e
-    }
38b026e
-    ERR_clear_error();
38b026e
-
38b026e
-    lib = ERR_lib_error_string(errcode);
38b026e
-    func = ERR_func_error_string(errcode);
38b026e
-    reason = ERR_reason_error_string(errcode);
38b026e
-
38b026e
-    if (lib && func) {
38b026e
-        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
38b026e
-    }
38b026e
-    else if (lib) {
38b026e
-        PyErr_Format(exc, "[%s] %s", lib, reason);
38b026e
-    }
38b026e
-    else {
38b026e
-        PyErr_SetString(exc, reason);
38b026e
-    }
38b026e
-    return NULL;
38b026e
-}
38b026e
-/* LCOV_EXCL_STOP */
38b026e
 
38b026e
 PyDoc_STRVAR(pbkdf2_hmac__doc__,
38b026e
 "pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
f7bd058
@@ -646,10 +686,17 @@ pbkdf2_hmac(PyObject *self, PyObject *ar
38b026e
     key = PyBytes_AS_STRING(key_obj);
38b026e
 
38b026e
     Py_BEGIN_ALLOW_THREADS
38b026e
+#if HAS_FAST_PKCS5_PBKDF2_HMAC
38b026e
+    retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
38b026e
+                               (unsigned char *)salt.buf, (int)salt.len,
38b026e
+                               iterations, digest, dklen,
38b026e
+                               (unsigned char *)key);
38b026e
+#else
38b026e
     retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
38b026e
                                     (unsigned char *)salt.buf, (int)salt.len,
38b026e
                                     iterations, digest, dklen,
38b026e
                                     (unsigned char *)key);
38b026e
+#endif
38b026e
     Py_END_ALLOW_THREADS
38b026e
 
38b026e
     if (!retval) {
f7bd058
@@ -768,7 +815,7 @@ generate_hash_name_list(void)
f7bd058
     if (CONST_ ## NAME ## _name_obj == NULL) { \
f7bd058
         CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
f7bd058
         if (EVP_get_digestbyname(#NAME)) { \
f7bd058
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
f7bd058
+            CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
f7bd058
             EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
f7bd058
         } \
f7bd058
     } \
f7bd058
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
f7bd058
--- a/Modules/_ssl.c
f7bd058
+++ b/Modules/_ssl.c
38b026e
@@ -55,6 +55,14 @@ static PySocketModule_APIObject PySocket
38b026e
 #include <sys/poll.h>
38b026e
 #endif
38b026e
 
38b026e
+/* Don't warn about deprecated functions */
38b026e
+#ifdef __GNUC__
38b026e
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
38b026e
+#endif
38b026e
+#ifdef __clang__
38b026e
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
38b026e
+#endif
38b026e
+
38b026e
 /* Include OpenSSL header files */
38b026e
 #include "openssl/rsa.h"
38b026e
 #include "openssl/crypto.h"
38b026e
@@ -91,6 +99,10 @@ struct py_ssl_library_code {
38b026e
 /* Include generated data (error codes) */
38b026e
 #include "_ssl_data.h"
38b026e
 
38b026e
+#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
38b026e
+#  define OPENSSL_VERSION_1_1 1
38b026e
+#endif
38b026e
+
38b026e
 /* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
38b026e
     http://www.openssl.org/news/changelog.html
38b026e
  */
f7bd058
@@ -117,6 +129,72 @@ struct py_ssl_library_code {
38b026e
 # define HAVE_ALPN
38b026e
 #endif
38b026e
 
38b026e
+#ifdef OPENSSL_VERSION_1_1
38b026e
+/* OpenSSL 1.1.0+ */
38b026e
+#ifndef OPENSSL_NO_SSL2
38b026e
+#define OPENSSL_NO_SSL2
38b026e
+#endif
38b026e
+#else /* OpenSSL < 1.1.0 */
38b026e
+#if defined(WITH_THREAD)
38b026e
+#define HAVE_OPENSSL_CRYPTO_LOCK
38b026e
+#endif
38b026e
+
38b026e
+#define TLS_method SSLv23_method
38b026e
+
38b026e
+static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
38b026e
+{
38b026e
+    return ne->set;
38b026e
+}
38b026e
+
38b026e
+#ifndef OPENSSL_NO_COMP
38b026e
+static int COMP_get_type(const COMP_METHOD *meth)
38b026e
+{
38b026e
+    return meth->type;
38b026e
+}
38b026e
+
38b026e
+static const char *COMP_get_name(const COMP_METHOD *meth)
38b026e
+{
38b026e
+    return meth->name;
38b026e
+}
38b026e
+#endif
38b026e
+
38b026e
+static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
38b026e
+{
38b026e
+    return ctx->default_passwd_callback;
38b026e
+}
38b026e
+
38b026e
+static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
38b026e
+{
38b026e
+    return ctx->default_passwd_callback_userdata;
38b026e
+}
38b026e
+
38b026e
+static int X509_OBJECT_get_type(X509_OBJECT *x)
38b026e
+{
38b026e
+    return x->type;
38b026e
+}
38b026e
+
38b026e
+static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
38b026e
+{
38b026e
+    return x->data.x509;
38b026e
+}
38b026e
+
38b026e
+static int BIO_up_ref(BIO *b)
38b026e
+{
38b026e
+    CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
38b026e
+    return 1;
38b026e
+}
38b026e
+
38b026e
+static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
38b026e
+    return store->objs;
38b026e
+}
38b026e
+
38b026e
+static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
38b026e
+{
38b026e
+    return store->param;
38b026e
+}
38b026e
+#endif /* OpenSSL < 1.1.0 or LibreSSL */
38b026e
+
38b026e
+
38b026e
 enum py_ssl_error {
38b026e
     /* these mirror ssl.h */
38b026e
     PY_SSL_ERROR_NONE,
f7bd058
@@ -147,7 +225,7 @@ enum py_ssl_cert_requirements {
38b026e
 enum py_ssl_version {
38b026e
     PY_SSL_VERSION_SSL2,
38b026e
     PY_SSL_VERSION_SSL3=1,
38b026e
-    PY_SSL_VERSION_SSL23,
38b026e
+    PY_SSL_VERSION_TLS,
38b026e
 #if HAVE_TLSv1_2
38b026e
     PY_SSL_VERSION_TLS1,
38b026e
     PY_SSL_VERSION_TLS1_1,
f7bd058
@@ -527,8 +605,8 @@ newPySSLSocket(PySSLContext *sslctx, PyS
38b026e
         /* BIOs are reference counted and SSL_set_bio borrows our reference.
38b026e
          * To prevent a double free in memory_bio_dealloc() we need to take an
38b026e
          * extra reference here. */
38b026e
-        CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
38b026e
-        CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
38b026e
+        BIO_up_ref(inbio->bio);
38b026e
+        BIO_up_ref(outbio->bio);
38b026e
         SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
38b026e
     }
38b026e
     mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
f7bd058
@@ -738,7 +816,7 @@ static PyObject *
38b026e
 
38b026e
         /* check to see if we've gotten to a new RDN */
38b026e
         if (rdn_level >= 0) {
38b026e
-            if (rdn_level != entry->set) {
38b026e
+            if (rdn_level != X509_NAME_ENTRY_set(entry)) {
38b026e
                 /* yes, new RDN */
38b026e
                 /* add old RDN to DN */
38b026e
                 rdnt = PyList_AsTuple(rdn);
f7bd058
@@ -755,7 +833,7 @@ static PyObject *
38b026e
                     goto fail0;
38b026e
             }
38b026e
         }
38b026e
-        rdn_level = entry->set;
38b026e
+        rdn_level = X509_NAME_ENTRY_set(entry);
38b026e
 
38b026e
         /* now add this attribute to the current RDN */
38b026e
         name = X509_NAME_ENTRY_get_object(entry);
f7bd058
@@ -853,18 +931,18 @@ static PyObject *
38b026e
             goto fail;
38b026e
         }
38b026e
 
38b026e
-        p = ext->value->data;
38b026e
+        p = X509_EXTENSION_get_data(ext)->data;
38b026e
         if (method->it)
38b026e
             names = (GENERAL_NAMES*)
38b026e
               (ASN1_item_d2i(NULL,
38b026e
                              &p,
38b026e
-                             ext->value->length,
38b026e
+                             X509_EXTENSION_get_data(ext)->length,
38b026e
                              ASN1_ITEM_ptr(method->it)));
38b026e
         else
38b026e
             names = (GENERAL_NAMES*)
38b026e
               (method->d2i(NULL,
38b026e
                            &p,
38b026e
-                           ext->value->length));
38b026e
+                           X509_EXTENSION_get_data(ext)->length));
38b026e
 
38b026e
         for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
38b026e
             /* get a rendering of each name in the set of names */
f7bd058
@@ -1075,13 +1153,11 @@ static PyObject *
38b026e
     int i, j;
38b026e
     PyObject *lst, *res = NULL;
38b026e
 
38b026e
-#if OPENSSL_VERSION_NUMBER < 0x10001000L
38b026e
-    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
38b026e
-#else
38b026e
+#if OPENSSL_VERSION_NUMBER >= 0x10001000L
38b026e
     /* Calls x509v3_cache_extensions and sets up crldp */
38b026e
     X509_check_ca(certificate);
38b026e
-    dps = certificate->crldp;
38b026e
 #endif
38b026e
+    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
38b026e
 
38b026e
     if (dps == NULL)
38b026e
         return Py_None;
f7bd058
@@ -1451,14 +1527,13 @@ static PyObject *
38b026e
 _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
38b026e
 /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
38b026e
 {
38b026e
-    SSL_SESSION *sess = SSL_get_session(self->ssl);
38b026e
     STACK_OF(SSL_CIPHER) *ciphers;
38b026e
     int i;
38b026e
     PyObject *res;
38b026e
 
38b026e
-    if (!sess || !sess->ciphers)
38b026e
+    ciphers = SSL_get_ciphers(self->ssl);
38b026e
+    if (!ciphers)
38b026e
         Py_RETURN_NONE;
38b026e
-    ciphers = sess->ciphers;
38b026e
     res = PyList_New(sk_SSL_CIPHER_num(ciphers));
38b026e
     if (!res)
38b026e
         return NULL;
f7bd058
@@ -1567,9 +1642,9 @@ static PyObject *
38b026e
     if (self->ssl == NULL)
38b026e
         Py_RETURN_NONE;
38b026e
     comp_method = SSL_get_current_compression(self->ssl);
38b026e
-    if (comp_method == NULL || comp_method->type == NID_undef)
38b026e
+    if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
38b026e
         Py_RETURN_NONE;
38b026e
-    short_name = OBJ_nid2sn(comp_method->type);
38b026e
+    short_name = COMP_get_name(comp_method);
38b026e
     if (short_name == NULL)
38b026e
         Py_RETURN_NONE;
38b026e
     return PyUnicode_DecodeFSDefault(short_name);
f7bd058
@@ -2255,8 +2330,8 @@ static PyObject *
38b026e
     else if (proto_version == PY_SSL_VERSION_SSL2)
38b026e
         ctx = SSL_CTX_new(SSLv2_method());
38b026e
 #endif
38b026e
-    else if (proto_version == PY_SSL_VERSION_SSL23)
38b026e
-        ctx = SSL_CTX_new(SSLv23_method());
38b026e
+    else if (proto_version == PY_SSL_VERSION_TLS)
38b026e
+        ctx = SSL_CTX_new(TLS_method());
38b026e
     else
38b026e
         proto_version = -1;
38b026e
     PySSL_END_ALLOW_THREADS
f7bd058
@@ -2318,8 +2393,9 @@ static PyObject *
38b026e
 #ifndef OPENSSL_NO_ECDH
38b026e
     /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
38b026e
        prime256v1 by default.  This is Apache mod_ssl's initialization
38b026e
-       policy, so we should be safe. */
38b026e
-#if defined(SSL_CTX_set_ecdh_auto)
38b026e
+       policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
38b026e
+     */
38b026e
+#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
38b026e
     SSL_CTX_set_ecdh_auto(self->ctx, 1);
38b026e
 #else
38b026e
     {
f7bd058
@@ -2586,10 +2662,12 @@ static PyObject *
38b026e
 get_verify_flags(PySSLContext *self, void *c)
38b026e
 {
38b026e
     X509_STORE *store;
38b026e
+    X509_VERIFY_PARAM *param;
38b026e
     unsigned long flags;
38b026e
 
38b026e
     store = SSL_CTX_get_cert_store(self->ctx);
38b026e
-    flags = X509_VERIFY_PARAM_get_flags(store->param);
38b026e
+    param = X509_STORE_get0_param(store);
38b026e
+    flags = X509_VERIFY_PARAM_get_flags(param);
38b026e
     return PyLong_FromUnsignedLong(flags);
38b026e
 }
38b026e
 
f7bd058
@@ -2597,22 +2675,24 @@ static int
38b026e
 set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
38b026e
 {
38b026e
     X509_STORE *store;
38b026e
+    X509_VERIFY_PARAM *param;
38b026e
     unsigned long new_flags, flags, set, clear;
38b026e
 
38b026e
     if (!PyArg_Parse(arg, "k", &new_flags))
38b026e
         return -1;
38b026e
     store = SSL_CTX_get_cert_store(self->ctx);
38b026e
-    flags = X509_VERIFY_PARAM_get_flags(store->param);
38b026e
+    param = X509_STORE_get0_param(store);
38b026e
+    flags = X509_VERIFY_PARAM_get_flags(param);
38b026e
     clear = flags & ~new_flags;
38b026e
     set = ~flags & new_flags;
38b026e
     if (clear) {
38b026e
-        if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
38b026e
+        if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
38b026e
             _setSSLError(NULL, 0, __FILE__, __LINE__);
38b026e
             return -1;
38b026e
         }
38b026e
     }
38b026e
     if (set) {
38b026e
-        if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
38b026e
+        if (!X509_VERIFY_PARAM_set_flags(param, set)) {
38b026e
             _setSSLError(NULL, 0, __FILE__, __LINE__);
38b026e
             return -1;
38b026e
         }
f7bd058
@@ -2789,8 +2869,8 @@ static PyObject *
38b026e
 /*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
38b026e
 {
38b026e
     PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
38b026e
-    pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
38b026e
-    void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
38b026e
+    pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
38b026e
+    void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
38b026e
     _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
38b026e
     int r;
38b026e
 
f7bd058
@@ -2917,8 +2997,9 @@ static int
38b026e
             cert = d2i_X509_bio(biobuf, NULL);
38b026e
         } else {
38b026e
             cert = PEM_read_bio_X509(biobuf, NULL,
38b026e
-                                     self->ctx->default_passwd_callback,
38b026e
-                                     self->ctx->default_passwd_callback_userdata);
38b026e
+                                     SSL_CTX_get_default_passwd_cb(self->ctx),
38b026e
+                                     SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
38b026e
+                                    );
38b026e
         }
38b026e
         if (cert == NULL) {
38b026e
             break;
f7bd058
@@ -3444,25 +3525,24 @@ static PyObject *
38b026e
 /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
38b026e
 {
38b026e
     X509_STORE *store;
38b026e
+    STACK_OF(X509_OBJECT) *objs;
38b026e
     X509_OBJECT *obj;
38b026e
-    int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
38b026e
+    int x509 = 0, crl = 0, ca = 0, i;
38b026e
 
38b026e
     store = SSL_CTX_get_cert_store(self->ctx);
38b026e
-    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
38b026e
-        obj = sk_X509_OBJECT_value(store->objs, i);
38b026e
-        switch (obj->type) {
38b026e
+    objs = X509_STORE_get0_objects(store);
38b026e
+    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
38b026e
+        obj = sk_X509_OBJECT_value(objs, i);
38b026e
+        switch (X509_OBJECT_get_type(obj)) {
38b026e
             case X509_LU_X509:
38b026e
                 x509++;
38b026e
-                if (X509_check_ca(obj->data.x509)) {
38b026e
+                if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
38b026e
                     ca++;
38b026e
                 }
38b026e
                 break;
38b026e
             case X509_LU_CRL:
38b026e
                 crl++;
38b026e
                 break;
38b026e
-            case X509_LU_PKEY:
38b026e
-                pkey++;
38b026e
-                break;
38b026e
             default:
38b026e
                 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
38b026e
                  * As far as I can tell they are internal states and never
f7bd058
@@ -3492,6 +3572,7 @@ static PyObject *
38b026e
 /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
38b026e
 {
38b026e
     X509_STORE *store;
38b026e
+    STACK_OF(X509_OBJECT) *objs;
38b026e
     PyObject *ci = NULL, *rlist = NULL;
38b026e
     int i;
38b026e
 
f7bd058
@@ -3500,17 +3581,18 @@ static PyObject *
38b026e
     }
38b026e
 
38b026e
     store = SSL_CTX_get_cert_store(self->ctx);
38b026e
-    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
38b026e
+    objs = X509_STORE_get0_objects(store);
38b026e
+    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
38b026e
         X509_OBJECT *obj;
38b026e
         X509 *cert;
38b026e
 
38b026e
-        obj = sk_X509_OBJECT_value(store->objs, i);
38b026e
-        if (obj->type != X509_LU_X509) {
38b026e
+        obj = sk_X509_OBJECT_value(objs, i);
38b026e
+        if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
38b026e
             /* not a x509 cert */
38b026e
             continue;
38b026e
         }
38b026e
         /* CA for any purpose */
38b026e
-        cert = obj->data.x509;
38b026e
+        cert = X509_OBJECT_get0_X509(obj);
38b026e
         if (!X509_check_ca(cert)) {
38b026e
             continue;
38b026e
         }
f7bd058
@@ -4374,10 +4456,12 @@ static PyMethodDef PySSL_methods[] = {
38b026e
 };
38b026e
 
38b026e
 
38b026e
-#ifdef WITH_THREAD
38b026e
+#ifdef HAVE_OPENSSL_CRYPTO_LOCK
38b026e
 
38b026e
 /* an implementation of OpenSSL threading operations in terms
38b026e
-   of the Python C thread library */
38b026e
+ * of the Python C thread library
38b026e
+ * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
38b026e
+ */
38b026e
 
38b026e
 static PyThread_type_lock *_ssl_locks = NULL;
38b026e
 
f7bd058
@@ -4458,7 +4542,7 @@ static int _setup_ssl_threads(void) {
38b026e
     return 1;
38b026e
 }
38b026e
 
38b026e
-#endif  /* def HAVE_THREAD */
38b026e
+#endif  /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
38b026e
 
38b026e
 PyDoc_STRVAR(module_doc,
38b026e
 "Implementation module for SSL socket operations.  See the socket module\n\
f7bd058
@@ -4527,11 +4611,16 @@ PyInit__ssl(void)
38b026e
     SSL_load_error_strings();
38b026e
     SSL_library_init();
38b026e
 #ifdef WITH_THREAD
38b026e
+#ifdef HAVE_OPENSSL_CRYPTO_LOCK
38b026e
     /* note that this will start threading if not already started */
38b026e
     if (!_setup_ssl_threads()) {
38b026e
         return NULL;
38b026e
     }
38b026e
+#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
38b026e
+    /* OpenSSL 1.1.0 builtin thread support is enabled */
38b026e
+    _ssl_locks_count++;
38b026e
 #endif
38b026e
+#endif  /* WITH_THREAD */
38b026e
     OpenSSL_add_all_algorithms();
38b026e
 
38b026e
     /* Add symbols to module dict */
f7bd058
@@ -4678,7 +4767,9 @@ PyInit__ssl(void)
38b026e
                             PY_SSL_VERSION_SSL3);
38b026e
 #endif
38b026e
     PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
38b026e
-                            PY_SSL_VERSION_SSL23);
38b026e
+                            PY_SSL_VERSION_TLS);
38b026e
+    PyModule_AddIntConstant(m, "PROTOCOL_TLS",
38b026e
+                            PY_SSL_VERSION_TLS);
38b026e
     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
38b026e
                             PY_SSL_VERSION_TLS1);
38b026e
 #if HAVE_TLSv1_2
f7bd058
f7bd058
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
f7bd058
--- a/Modules/_ssl.c
f7bd058
+++ b/Modules/_ssl.c
f7bd058
@@ -151,11 +151,6 @@ static int COMP_get_type(const COMP_METH
f7bd058
 {
f7bd058
     return meth->type;
f7bd058
 }
f7bd058
-
f7bd058
-static const char *COMP_get_name(const COMP_METHOD *meth)
f7bd058
-{
f7bd058
-    return meth->name;
f7bd058
-}
f7bd058
 #endif
f7bd058
 
f7bd058
 static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
f7bd058
@@ -1644,7 +1639,7 @@ static PyObject *
f7bd058
     comp_method = SSL_get_current_compression(self->ssl);
f7bd058
     if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
f7bd058
         Py_RETURN_NONE;
f7bd058
-    short_name = COMP_get_name(comp_method);
f7bd058
+    short_name = OBJ_nid2sn(COMP_get_type(comp_method));
f7bd058
     if (short_name == NULL)
f7bd058
         Py_RETURN_NONE;
f7bd058
     return PyUnicode_DecodeFSDefault(short_name);