We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
SSL cert digest check uses non-constant-time comparison
This is the problematic line:
https://github.com/shazow/urllib3/blob/master/urllib3/util/ssl_.py#L137

The digests being compared are strings, and `==` is not constant-time, which could potentially allow a timing attack. While it may not immediately be obvious whether an adversary could gain any advantage by successfully timing this line, I am a firm believer in "better safe than sorry."

The best way to fix this is to use a constant-time digest comparison function, such as the built-in `hmac.compare_digest`. However, this function was only introduced in Python 2.7.7, while this library supports Python 2.6+. The next best solution would be to use something like the `constant_time_compare` function from the following package:
https://github.com/mitsuhiko/itsdangerous

Using a constant-time comparison is semantically equivalent to using `==`, and the performance impact is negligible and comes along with improved security. I believe this is a good tradeoff.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `urllib3/util/ssl_.py`
Content:
```
1 from binascii import hexlify, unhexlify
2 from hashlib import md5, sha1, sha256
3 
4 from ..exceptions import SSLError, InsecurePlatformWarning
5 
6 
7 SSLContext = None
8 HAS_SNI = False
9 create_default_context = None
10 
11 # Maps the length of a digest to a possible hash function producing this digest
12 HASHFUNC_MAP = {
13     32: md5,
14     40: sha1,
15     64: sha256,
16 }
17 
18 import errno
19 import warnings
20 
21 try:  # Test for SSL features
22     import ssl
23     from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
24     from ssl import HAS_SNI  # Has SNI?
25 except ImportError:
26     pass
27 
28 
29 try:
30     from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION
31 except ImportError:
32     OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
33     OP_NO_COMPRESSION = 0x20000
34 
35 # A secure default.
36 # Sources for more information on TLS ciphers:
37 #
38 # - https://wiki.mozilla.org/Security/Server_Side_TLS
39 # - https://www.ssllabs.com/projects/best-practices/index.html
40 # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
41 #
42 # The general intent is:
43 # - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
44 # - prefer ECDHE over DHE for better performance,
45 # - prefer any AES-GCM over any AES-CBC for better performance and security,
46 # - use 3DES as fallback which is secure but slow,
47 # - disable NULL authentication, MD5 MACs and DSS for security reasons.
48 DEFAULT_CIPHERS = (
49     'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
50     'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
51     '!eNULL:!MD5'
52 )
53 
54 try:
55     from ssl import SSLContext  # Modern SSL?
56 except ImportError:
57     import sys
58 
59     class SSLContext(object):  # Platform-specific: Python 2 & 3.1
60         supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or
61                                 (3, 2) <= sys.version_info)
62 
63         def __init__(self, protocol_version):
64             self.protocol = protocol_version
65             # Use default values from a real SSLContext
66             self.check_hostname = False
67             self.verify_mode = ssl.CERT_NONE
68             self.ca_certs = None
69             self.options = 0
70             self.certfile = None
71             self.keyfile = None
72             self.ciphers = None
73 
74         def load_cert_chain(self, certfile, keyfile):
75             self.certfile = certfile
76             self.keyfile = keyfile
77 
78         def load_verify_locations(self, cafile=None, capath=None):
79             self.ca_certs = cafile
80 
81             if capath is not None:
82                 raise SSLError("CA directories not supported in older Pythons")
83 
84         def set_ciphers(self, cipher_suite):
85             if not self.supports_set_ciphers:
86                 raise TypeError(
87                     'Your version of Python does not support setting '
88                     'a custom cipher suite. Please upgrade to Python '
89                     '2.7, 3.2, or later if you need this functionality.'
90                 )
91             self.ciphers = cipher_suite
92 
93         def wrap_socket(self, socket, server_hostname=None):
94             warnings.warn(
95                 'A true SSLContext object is not available. This prevents '
96                 'urllib3 from configuring SSL appropriately and may cause '
97                 'certain SSL connections to fail. For more information, see '
98                 'https://urllib3.readthedocs.org/en/latest/security.html'
99                 '#insecureplatformwarning.',
100                 InsecurePlatformWarning
101             )
102             kwargs = {
103                 'keyfile': self.keyfile,
104                 'certfile': self.certfile,
105                 'ca_certs': self.ca_certs,
106                 'cert_reqs': self.verify_mode,
107                 'ssl_version': self.protocol,
108             }
109             if self.supports_set_ciphers:  # Platform-specific: Python 2.7+
110                 return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
111             else:  # Platform-specific: Python 2.6
112                 return wrap_socket(socket, **kwargs)
113 
114 
115 def assert_fingerprint(cert, fingerprint):
116     """
117     Checks if given fingerprint matches the supplied certificate.
118 
119     :param cert:
120         Certificate as bytes object.
121     :param fingerprint:
122         Fingerprint as string of hexdigits, can be interspersed by colons.
123     """
124 
125     fingerprint = fingerprint.replace(':', '').lower()
126     digest_length = len(fingerprint)
127     hashfunc = HASHFUNC_MAP.get(digest_length)
128     if not hashfunc:
129         raise SSLError(
130             'Fingerprint of invalid length: {0}'.format(fingerprint))
131 
132     # We need encode() here for py32; works on py2 and p33.
133     fingerprint_bytes = unhexlify(fingerprint.encode())
134 
135     cert_digest = hashfunc(cert).digest()
136 
137     if cert_digest != fingerprint_bytes:
138         raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
139                        .format(fingerprint, hexlify(cert_digest)))
140 
141 
142 def resolve_cert_reqs(candidate):
143     """
144     Resolves the argument to a numeric constant, which can be passed to
145     the wrap_socket function/method from the ssl module.
146     Defaults to :data:`ssl.CERT_NONE`.
147     If given a string it is assumed to be the name of the constant in the
148     :mod:`ssl` module or its abbrevation.
149     (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
150     If it's neither `None` nor a string we assume it is already the numeric
151     constant which can directly be passed to wrap_socket.
152     """
153     if candidate is None:
154         return CERT_NONE
155 
156     if isinstance(candidate, str):
157         res = getattr(ssl, candidate, None)
158         if res is None:
159             res = getattr(ssl, 'CERT_' + candidate)
160         return res
161 
162     return candidate
163 
164 
165 def resolve_ssl_version(candidate):
166     """
167     like resolve_cert_reqs
168     """
169     if candidate is None:
170         return PROTOCOL_SSLv23
171 
172     if isinstance(candidate, str):
173         res = getattr(ssl, candidate, None)
174         if res is None:
175             res = getattr(ssl, 'PROTOCOL_' + candidate)
176         return res
177 
178     return candidate
179 
180 
181 def create_urllib3_context(ssl_version=None, cert_reqs=None,
182                            options=None, ciphers=None):
183     """All arguments have the same meaning as ``ssl_wrap_socket``.
184 
185     By default, this function does a lot of the same work that
186     ``ssl.create_default_context`` does on Python 3.4+. It:
187 
188     - Disables SSLv2, SSLv3, and compression
189     - Sets a restricted set of server ciphers
190 
191     If you wish to enable SSLv3, you can do::
192 
193         from urllib3.util import ssl_
194         context = ssl_.create_urllib3_context()
195         context.options &= ~ssl_.OP_NO_SSLv3
196 
197     You can do the same to enable compression (substituting ``COMPRESSION``
198     for ``SSLv3`` in the last line above).
199 
200     :param ssl_version:
201         The desired protocol version to use. This will default to
202         PROTOCOL_SSLv23 which will negotiate the highest protocol that both
203         the server and your installation of OpenSSL support.
204     :param cert_reqs:
205         Whether to require the certificate verification. This defaults to
206         ``ssl.CERT_REQUIRED``.
207     :param options:
208         Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
209         ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
210     :param ciphers:
211         Which cipher suites to allow the server to select.
212     :returns:
213         Constructed SSLContext object with specified options
214     :rtype: SSLContext
215     """
216     context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
217 
218     # Setting the default here, as we may have no ssl module on import
219     cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
220 
221     if options is None:
222         options = 0
223         # SSLv2 is easily broken and is considered harmful and dangerous
224         options |= OP_NO_SSLv2
225         # SSLv3 has several problems and is now dangerous
226         options |= OP_NO_SSLv3
227         # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
228         # (issue #309)
229         options |= OP_NO_COMPRESSION
230 
231     context.options |= options
232 
233     if getattr(context, 'supports_set_ciphers', True):  # Platform-specific: Python 2.6
234         context.set_ciphers(ciphers or DEFAULT_CIPHERS)
235 
236     context.verify_mode = cert_reqs
237     if getattr(context, 'check_hostname', None) is not None:  # Platform-specific: Python 3.2
238         # We do our own verification, including fingerprints and alternative
239         # hostnames. So disable it here
240         context.check_hostname = False
241     return context
242 
243 
244 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
245                     ca_certs=None, server_hostname=None,
246                     ssl_version=None, ciphers=None, ssl_context=None,
247                     ca_cert_dir=None):
248     """
249     All arguments except for server_hostname, ssl_context, and ca_cert_dir have
250     the same meaning as they do when using :func:`ssl.wrap_socket`.
251 
252     :param server_hostname:
253         When SNI is supported, the expected hostname of the certificate
254     :param ssl_context:
255         A pre-made :class:`SSLContext` object. If none is provided, one will
256         be created using :func:`create_urllib3_context`.
257     :param ciphers:
258         A string of ciphers we wish the client to support. This is not
259         supported on Python 2.6 as the ssl module does not support it.
260     :param ca_cert_dir:
261         A directory containing CA certificates in multiple separate files, as
262         supported by OpenSSL's -CApath flag or the capath argument to
263         SSLContext.load_verify_locations().
264     """
265     context = ssl_context
266     if context is None:
267         context = create_urllib3_context(ssl_version, cert_reqs,
268                                          ciphers=ciphers)
269 
270     if ca_certs or ca_cert_dir:
271         try:
272             context.load_verify_locations(ca_certs, ca_cert_dir)
273         except IOError as e:  # Platform-specific: Python 2.6, 2.7, 3.2
274             raise SSLError(e)
275         # Py33 raises FileNotFoundError which subclasses OSError
276         # These are not equivalent unless we check the errno attribute
277         except OSError as e:  # Platform-specific: Python 3.3 and beyond
278             if e.errno == errno.ENOENT:
279                 raise SSLError(e)
280             raise
281 
282     if certfile:
283         context.load_cert_chain(certfile, keyfile)
284     if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
285         return context.wrap_socket(sock, server_hostname=server_hostname)
286     return context.wrap_socket(sock)
287
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/urllib3/util/ssl_.py b/urllib3/util/ssl_.py
--- a/urllib3/util/ssl_.py
+++ b/urllib3/util/ssl_.py
@@ -17,6 +17,25 @@
 
 import errno
 import warnings
+import hmac
+
+
+def _const_compare_digest_backport(a, b):
+    """
+    Compare two digests of equal length in constant time.
+
+    The digests must be of type str/bytes.
+    Returns True if the digests match, and False otherwise.
+    """
+    result = abs(len(a) - len(b))
+    for l, r in zip(bytearray(a), bytearray(b)):
+        result |= l ^ r
+    return result == 0
+
+
+_const_compare_digest = getattr(hmac, 'compare_digest',
+                                _const_compare_digest_backport)
+
 
 try:  # Test for SSL features
     import ssl
@@ -134,7 +153,7 @@
 
     cert_digest = hashfunc(cert).digest()
 
-    if cert_digest != fingerprint_bytes:
+    if not _const_compare_digest(cert_digest, fingerprint_bytes):
         raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
                        .format(fingerprint, hexlify(cert_digest)))

{"golden_diff": "diff --git a/urllib3/util/ssl_.py b/urllib3/util/ssl_.py\n--- a/urllib3/util/ssl_.py\n+++ b/urllib3/util/ssl_.py\n@@ -17,6 +17,25 @@\n \n import errno\n import warnings\n+import hmac\n+\n+\n+def _const_compare_digest_backport(a, b):\n+    \"\"\"\n+    Compare two digests of equal length in constant time.\n+\n+    The digests must be of type str/bytes.\n+    Returns True if the digests match, and False otherwise.\n+    \"\"\"\n+    result = abs(len(a) - len(b))\n+    for l, r in zip(bytearray(a), bytearray(b)):\n+        result |= l ^ r\n+    return result == 0\n+\n+\n+_const_compare_digest = getattr(hmac, 'compare_digest',\n+                                _const_compare_digest_backport)\n+\n \n try:  # Test for SSL features\n     import ssl\n@@ -134,7 +153,7 @@\n \n     cert_digest = hashfunc(cert).digest()\n \n-    if cert_digest != fingerprint_bytes:\n+    if not _const_compare_digest(cert_digest, fingerprint_bytes):\n         raise SSLError('Fingerprints did not match. Expected \"{0}\", got \"{1}\".'\n                        .format(fingerprint, hexlify(cert_digest)))\n", "issue": "SSL cert digest check uses non-constant-time comparison\nThis is the problematic line:\nhttps://github.com/shazow/urllib3/blob/master/urllib3/util/ssl_.py#L137\n\nThe digests being compared are strings, and `==` is not constant-time, which could potentially allow a timing attack. While it may not immediately be obvious whether an adversary could gain any advantage by successfully timing this line, I am a firm believer in \"better safe than sorry.\"\n\nThe best way to fix this is to use a constant-time digest comparison function, such as the built-in `hmac.compare_digest`. However, this function was only introduced in Python 2.7.7, while this library supports Python 2.6+. The next best solution would be to use something like the `constant_time_compare` function from the following package:\nhttps://github.com/mitsuhiko/itsdangerous\n\nUsing a constant-time comparison is semantically equivalent to using `==`, and the performance impact is negligible and comes along with improved security. I believe this is a good tradeoff.\n\n", "before_files": [{"content": "from binascii import hexlify, unhexlify\nfrom hashlib import md5, sha1, sha256\n\nfrom ..exceptions import SSLError, InsecurePlatformWarning\n\n\nSSLContext = None\nHAS_SNI = False\ncreate_default_context = None\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {\n    32: md5,\n    40: sha1,\n    64: sha256,\n}\n\nimport errno\nimport warnings\n\ntry:  # Test for SSL features\n    import ssl\n    from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23\n    from ssl import HAS_SNI  # Has SNI?\nexcept ImportError:\n    pass\n\n\ntry:\n    from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION\nexcept ImportError:\n    OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000\n    OP_NO_COMPRESSION = 0x20000\n\n# A secure default.\n# Sources for more information on TLS ciphers:\n#\n# - https://wiki.mozilla.org/Security/Server_Side_TLS\n# - https://www.ssllabs.com/projects/best-practices/index.html\n# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/\n#\n# The general intent is:\n# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),\n# - prefer ECDHE over DHE for better performance,\n# - prefer any AES-GCM over any AES-CBC for better performance and security,\n# - use 3DES as fallback which is secure but slow,\n# - disable NULL authentication, MD5 MACs and DSS for security reasons.\nDEFAULT_CIPHERS = (\n    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'\n    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'\n    '!eNULL:!MD5'\n)\n\ntry:\n    from ssl import SSLContext  # Modern SSL?\nexcept ImportError:\n    import sys\n\n    class SSLContext(object):  # Platform-specific: Python 2 & 3.1\n        supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or\n                                (3, 2) <= sys.version_info)\n\n        def __init__(self, protocol_version):\n            self.protocol = protocol_version\n            # Use default values from a real SSLContext\n            self.check_hostname = False\n            self.verify_mode = ssl.CERT_NONE\n            self.ca_certs = None\n            self.options = 0\n            self.certfile = None\n            self.keyfile = None\n            self.ciphers = None\n\n        def load_cert_chain(self, certfile, keyfile):\n            self.certfile = certfile\n            self.keyfile = keyfile\n\n        def load_verify_locations(self, cafile=None, capath=None):\n            self.ca_certs = cafile\n\n            if capath is not None:\n                raise SSLError(\"CA directories not supported in older Pythons\")\n\n        def set_ciphers(self, cipher_suite):\n            if not self.supports_set_ciphers:\n                raise TypeError(\n                    'Your version of Python does not support setting '\n                    'a custom cipher suite. Please upgrade to Python '\n                    '2.7, 3.2, or later if you need this functionality.'\n                )\n            self.ciphers = cipher_suite\n\n        def wrap_socket(self, socket, server_hostname=None):\n            warnings.warn(\n                'A true SSLContext object is not available. This prevents '\n                'urllib3 from configuring SSL appropriately and may cause '\n                'certain SSL connections to fail. For more information, see '\n                'https://urllib3.readthedocs.org/en/latest/security.html'\n                '#insecureplatformwarning.',\n                InsecurePlatformWarning\n            )\n            kwargs = {\n                'keyfile': self.keyfile,\n                'certfile': self.certfile,\n                'ca_certs': self.ca_certs,\n                'cert_reqs': self.verify_mode,\n                'ssl_version': self.protocol,\n            }\n            if self.supports_set_ciphers:  # Platform-specific: Python 2.7+\n                return wrap_socket(socket, ciphers=self.ciphers, **kwargs)\n            else:  # Platform-specific: Python 2.6\n                return wrap_socket(socket, **kwargs)\n\n\ndef assert_fingerprint(cert, fingerprint):\n    \"\"\"\n    Checks if given fingerprint matches the supplied certificate.\n\n    :param cert:\n        Certificate as bytes object.\n    :param fingerprint:\n        Fingerprint as string of hexdigits, can be interspersed by colons.\n    \"\"\"\n\n    fingerprint = fingerprint.replace(':', '').lower()\n    digest_length = len(fingerprint)\n    hashfunc = HASHFUNC_MAP.get(digest_length)\n    if not hashfunc:\n        raise SSLError(\n            'Fingerprint of invalid length: {0}'.format(fingerprint))\n\n    # We need encode() here for py32; works on py2 and p33.\n    fingerprint_bytes = unhexlify(fingerprint.encode())\n\n    cert_digest = hashfunc(cert).digest()\n\n    if cert_digest != fingerprint_bytes:\n        raise SSLError('Fingerprints did not match. Expected \"{0}\", got \"{1}\".'\n                       .format(fingerprint, hexlify(cert_digest)))\n\n\ndef resolve_cert_reqs(candidate):\n    \"\"\"\n    Resolves the argument to a numeric constant, which can be passed to\n    the wrap_socket function/method from the ssl module.\n    Defaults to :data:`ssl.CERT_NONE`.\n    If given a string it is assumed to be the name of the constant in the\n    :mod:`ssl` module or its abbrevation.\n    (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n    If it's neither `None` nor a string we assume it is already the numeric\n    constant which can directly be passed to wrap_socket.\n    \"\"\"\n    if candidate is None:\n        return CERT_NONE\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, 'CERT_' + candidate)\n        return res\n\n    return candidate\n\n\ndef resolve_ssl_version(candidate):\n    \"\"\"\n    like resolve_cert_reqs\n    \"\"\"\n    if candidate is None:\n        return PROTOCOL_SSLv23\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, 'PROTOCOL_' + candidate)\n        return res\n\n    return candidate\n\n\ndef create_urllib3_context(ssl_version=None, cert_reqs=None,\n                           options=None, ciphers=None):\n    \"\"\"All arguments have the same meaning as ``ssl_wrap_socket``.\n\n    By default, this function does a lot of the same work that\n    ``ssl.create_default_context`` does on Python 3.4+. It:\n\n    - Disables SSLv2, SSLv3, and compression\n    - Sets a restricted set of server ciphers\n\n    If you wish to enable SSLv3, you can do::\n\n        from urllib3.util import ssl_\n        context = ssl_.create_urllib3_context()\n        context.options &= ~ssl_.OP_NO_SSLv3\n\n    You can do the same to enable compression (substituting ``COMPRESSION``\n    for ``SSLv3`` in the last line above).\n\n    :param ssl_version:\n        The desired protocol version to use. This will default to\n        PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n        the server and your installation of OpenSSL support.\n    :param cert_reqs:\n        Whether to require the certificate verification. This defaults to\n        ``ssl.CERT_REQUIRED``.\n    :param options:\n        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.\n    :param ciphers:\n        Which cipher suites to allow the server to select.\n    :returns:\n        Constructed SSLContext object with specified options\n    :rtype: SSLContext\n    \"\"\"\n    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)\n\n    # Setting the default here, as we may have no ssl module on import\n    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n    if options is None:\n        options = 0\n        # SSLv2 is easily broken and is considered harmful and dangerous\n        options |= OP_NO_SSLv2\n        # SSLv3 has several problems and is now dangerous\n        options |= OP_NO_SSLv3\n        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n        # (issue #309)\n        options |= OP_NO_COMPRESSION\n\n    context.options |= options\n\n    if getattr(context, 'supports_set_ciphers', True):  # Platform-specific: Python 2.6\n        context.set_ciphers(ciphers or DEFAULT_CIPHERS)\n\n    context.verify_mode = cert_reqs\n    if getattr(context, 'check_hostname', None) is not None:  # Platform-specific: Python 3.2\n        # We do our own verification, including fingerprints and alternative\n        # hostnames. So disable it here\n        context.check_hostname = False\n    return context\n\n\ndef ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,\n                    ca_certs=None, server_hostname=None,\n                    ssl_version=None, ciphers=None, ssl_context=None,\n                    ca_cert_dir=None):\n    \"\"\"\n    All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n    the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n    :param server_hostname:\n        When SNI is supported, the expected hostname of the certificate\n    :param ssl_context:\n        A pre-made :class:`SSLContext` object. If none is provided, one will\n        be created using :func:`create_urllib3_context`.\n    :param ciphers:\n        A string of ciphers we wish the client to support. This is not\n        supported on Python 2.6 as the ssl module does not support it.\n    :param ca_cert_dir:\n        A directory containing CA certificates in multiple separate files, as\n        supported by OpenSSL's -CApath flag or the capath argument to\n        SSLContext.load_verify_locations().\n    \"\"\"\n    context = ssl_context\n    if context is None:\n        context = create_urllib3_context(ssl_version, cert_reqs,\n                                         ciphers=ciphers)\n\n    if ca_certs or ca_cert_dir:\n        try:\n            context.load_verify_locations(ca_certs, ca_cert_dir)\n        except IOError as e:  # Platform-specific: Python 2.6, 2.7, 3.2\n            raise SSLError(e)\n        # Py33 raises FileNotFoundError which subclasses OSError\n        # These are not equivalent unless we check the errno attribute\n        except OSError as e:  # Platform-specific: Python 3.3 and beyond\n            if e.errno == errno.ENOENT:\n                raise SSLError(e)\n            raise\n\n    if certfile:\n        context.load_cert_chain(certfile, keyfile)\n    if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI\n        return context.wrap_socket(sock, server_hostname=server_hostname)\n    return context.wrap_socket(sock)\n", "path": "urllib3/util/ssl_.py"}], "after_files": [{"content": "from binascii import hexlify, unhexlify\nfrom hashlib import md5, sha1, sha256\n\nfrom ..exceptions import SSLError, InsecurePlatformWarning\n\n\nSSLContext = None\nHAS_SNI = False\ncreate_default_context = None\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {\n    32: md5,\n    40: sha1,\n    64: sha256,\n}\n\nimport errno\nimport warnings\nimport hmac\n\n\ndef _const_compare_digest_backport(a, b):\n    \"\"\"\n    Compare two digests of equal length in constant time.\n\n    The digests must be of type str/bytes.\n    Returns True if the digests match, and False otherwise.\n    \"\"\"\n    result = abs(len(a) - len(b))\n    for l, r in zip(bytearray(a), bytearray(b)):\n        result |= l ^ r\n    return result == 0\n\n\n_const_compare_digest = getattr(hmac, 'compare_digest',\n                                _const_compare_digest_backport)\n\n\ntry:  # Test for SSL features\n    import ssl\n    from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23\n    from ssl import HAS_SNI  # Has SNI?\nexcept ImportError:\n    pass\n\n\ntry:\n    from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION\nexcept ImportError:\n    OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000\n    OP_NO_COMPRESSION = 0x20000\n\n# A secure default.\n# Sources for more information on TLS ciphers:\n#\n# - https://wiki.mozilla.org/Security/Server_Side_TLS\n# - https://www.ssllabs.com/projects/best-practices/index.html\n# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/\n#\n# The general intent is:\n# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),\n# - prefer ECDHE over DHE for better performance,\n# - prefer any AES-GCM over any AES-CBC for better performance and security,\n# - use 3DES as fallback which is secure but slow,\n# - disable NULL authentication, MD5 MACs and DSS for security reasons.\nDEFAULT_CIPHERS = (\n    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'\n    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'\n    '!eNULL:!MD5'\n)\n\ntry:\n    from ssl import SSLContext  # Modern SSL?\nexcept ImportError:\n    import sys\n\n    class SSLContext(object):  # Platform-specific: Python 2 & 3.1\n        supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or\n                                (3, 2) <= sys.version_info)\n\n        def __init__(self, protocol_version):\n            self.protocol = protocol_version\n            # Use default values from a real SSLContext\n            self.check_hostname = False\n            self.verify_mode = ssl.CERT_NONE\n            self.ca_certs = None\n            self.options = 0\n            self.certfile = None\n            self.keyfile = None\n            self.ciphers = None\n\n        def load_cert_chain(self, certfile, keyfile):\n            self.certfile = certfile\n            self.keyfile = keyfile\n\n        def load_verify_locations(self, cafile=None, capath=None):\n            self.ca_certs = cafile\n\n            if capath is not None:\n                raise SSLError(\"CA directories not supported in older Pythons\")\n\n        def set_ciphers(self, cipher_suite):\n            if not self.supports_set_ciphers:\n                raise TypeError(\n                    'Your version of Python does not support setting '\n                    'a custom cipher suite. Please upgrade to Python '\n                    '2.7, 3.2, or later if you need this functionality.'\n                )\n            self.ciphers = cipher_suite\n\n        def wrap_socket(self, socket, server_hostname=None):\n            warnings.warn(\n                'A true SSLContext object is not available. This prevents '\n                'urllib3 from configuring SSL appropriately and may cause '\n                'certain SSL connections to fail. For more information, see '\n                'https://urllib3.readthedocs.org/en/latest/security.html'\n                '#insecureplatformwarning.',\n                InsecurePlatformWarning\n            )\n            kwargs = {\n                'keyfile': self.keyfile,\n                'certfile': self.certfile,\n                'ca_certs': self.ca_certs,\n                'cert_reqs': self.verify_mode,\n                'ssl_version': self.protocol,\n            }\n            if self.supports_set_ciphers:  # Platform-specific: Python 2.7+\n                return wrap_socket(socket, ciphers=self.ciphers, **kwargs)\n            else:  # Platform-specific: Python 2.6\n                return wrap_socket(socket, **kwargs)\n\n\ndef assert_fingerprint(cert, fingerprint):\n    \"\"\"\n    Checks if given fingerprint matches the supplied certificate.\n\n    :param cert:\n        Certificate as bytes object.\n    :param fingerprint:\n        Fingerprint as string of hexdigits, can be interspersed by colons.\n    \"\"\"\n\n    fingerprint = fingerprint.replace(':', '').lower()\n    digest_length = len(fingerprint)\n    hashfunc = HASHFUNC_MAP.get(digest_length)\n    if not hashfunc:\n        raise SSLError(\n            'Fingerprint of invalid length: {0}'.format(fingerprint))\n\n    # We need encode() here for py32; works on py2 and p33.\n    fingerprint_bytes = unhexlify(fingerprint.encode())\n\n    cert_digest = hashfunc(cert).digest()\n\n    if not _const_compare_digest(cert_digest, fingerprint_bytes):\n        raise SSLError('Fingerprints did not match. Expected \"{0}\", got \"{1}\".'\n                       .format(fingerprint, hexlify(cert_digest)))\n\n\ndef resolve_cert_reqs(candidate):\n    \"\"\"\n    Resolves the argument to a numeric constant, which can be passed to\n    the wrap_socket function/method from the ssl module.\n    Defaults to :data:`ssl.CERT_NONE`.\n    If given a string it is assumed to be the name of the constant in the\n    :mod:`ssl` module or its abbrevation.\n    (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n    If it's neither `None` nor a string we assume it is already the numeric\n    constant which can directly be passed to wrap_socket.\n    \"\"\"\n    if candidate is None:\n        return CERT_NONE\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, 'CERT_' + candidate)\n        return res\n\n    return candidate\n\n\ndef resolve_ssl_version(candidate):\n    \"\"\"\n    like resolve_cert_reqs\n    \"\"\"\n    if candidate is None:\n        return PROTOCOL_SSLv23\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, 'PROTOCOL_' + candidate)\n        return res\n\n    return candidate\n\n\ndef create_urllib3_context(ssl_version=None, cert_reqs=None,\n                           options=None, ciphers=None):\n    \"\"\"All arguments have the same meaning as ``ssl_wrap_socket``.\n\n    By default, this function does a lot of the same work that\n    ``ssl.create_default_context`` does on Python 3.4+. It:\n\n    - Disables SSLv2, SSLv3, and compression\n    - Sets a restricted set of server ciphers\n\n    If you wish to enable SSLv3, you can do::\n\n        from urllib3.util import ssl_\n        context = ssl_.create_urllib3_context()\n        context.options &= ~ssl_.OP_NO_SSLv3\n\n    You can do the same to enable compression (substituting ``COMPRESSION``\n    for ``SSLv3`` in the last line above).\n\n    :param ssl_version:\n        The desired protocol version to use. This will default to\n        PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n        the server and your installation of OpenSSL support.\n    :param cert_reqs:\n        Whether to require the certificate verification. This defaults to\n        ``ssl.CERT_REQUIRED``.\n    :param options:\n        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.\n    :param ciphers:\n        Which cipher suites to allow the server to select.\n    :returns:\n        Constructed SSLContext object with specified options\n    :rtype: SSLContext\n    \"\"\"\n    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)\n\n    # Setting the default here, as we may have no ssl module on import\n    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n    if options is None:\n        options = 0\n        # SSLv2 is easily broken and is considered harmful and dangerous\n        options |= OP_NO_SSLv2\n        # SSLv3 has several problems and is now dangerous\n        options |= OP_NO_SSLv3\n        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n        # (issue #309)\n        options |= OP_NO_COMPRESSION\n\n    context.options |= options\n\n    if getattr(context, 'supports_set_ciphers', True):  # Platform-specific: Python 2.6\n        context.set_ciphers(ciphers or DEFAULT_CIPHERS)\n\n    context.verify_mode = cert_reqs\n    if getattr(context, 'check_hostname', None) is not None:  # Platform-specific: Python 3.2\n        # We do our own verification, including fingerprints and alternative\n        # hostnames. So disable it here\n        context.check_hostname = False\n    return context\n\n\ndef ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,\n                    ca_certs=None, server_hostname=None,\n                    ssl_version=None, ciphers=None, ssl_context=None,\n                    ca_cert_dir=None):\n    \"\"\"\n    All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n    the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n    :param server_hostname:\n        When SNI is supported, the expected hostname of the certificate\n    :param ssl_context:\n        A pre-made :class:`SSLContext` object. If none is provided, one will\n        be created using :func:`create_urllib3_context`.\n    :param ciphers:\n        A string of ciphers we wish the client to support. This is not\n        supported on Python 2.6 as the ssl module does not support it.\n    :param ca_cert_dir:\n        A directory containing CA certificates in multiple separate files, as\n        supported by OpenSSL's -CApath flag or the capath argument to\n        SSLContext.load_verify_locations().\n    \"\"\"\n    context = ssl_context\n    if context is None:\n        context = create_urllib3_context(ssl_version, cert_reqs,\n                                         ciphers=ciphers)\n\n    if ca_certs or ca_cert_dir:\n        try:\n            context.load_verify_locations(ca_certs, ca_cert_dir)\n        except IOError as e:  # Platform-specific: Python 2.6, 2.7, 3.2\n            raise SSLError(e)\n        # Py33 raises FileNotFoundError which subclasses OSError\n        # These are not equivalent unless we check the errno attribute\n        except OSError as e:  # Platform-specific: Python 3.3 and beyond\n            if e.errno == errno.ENOENT:\n                raise SSLError(e)\n            raise\n\n    if certfile:\n        context.load_cert_chain(certfile, keyfile)\n    if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI\n        return context.wrap_socket(sock, server_hostname=server_hostname)\n    return context.wrap_socket(sock)\n", "path": "urllib3/util/ssl_.py"}]}