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