You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

466 lines
15 KiB

4 years ago
  1. """
  2. SSL with SNI_-support for Python 2. Follow these instructions if you would
  3. like to verify SSL certificates in Python 2. Note, the default libraries do
  4. *not* do certificate checking; you need to do additional work to validate
  5. certificates yourself.
  6. This needs the following packages installed:
  7. * pyOpenSSL (tested with 16.0.0)
  8. * cryptography (minimum 1.3.4, from pyopenssl)
  9. * idna (minimum 2.0, from cryptography)
  10. However, pyopenssl depends on cryptography, which depends on idna, so while we
  11. use all three directly here we end up having relatively few packages required.
  12. You can install them with the following command:
  13. pip install pyopenssl cryptography idna
  14. To activate certificate checking, call
  15. :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
  16. before you begin making HTTP requests. This can be done in a ``sitecustomize``
  17. module, or at any other time before your application begins using ``urllib3``,
  18. like this::
  19. try:
  20. import urllib3.contrib.pyopenssl
  21. urllib3.contrib.pyopenssl.inject_into_urllib3()
  22. except ImportError:
  23. pass
  24. Now you can use :mod:`urllib3` as you normally would, and it will support SNI
  25. when the required modules are installed.
  26. Activating this module also has the positive side effect of disabling SSL/TLS
  27. compression in Python 2 (see `CRIME attack`_).
  28. If you want to configure the default list of supported cipher suites, you can
  29. set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.
  30. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication
  31. .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)
  32. """
  33. from __future__ import absolute_import
  34. import OpenSSL.SSL
  35. from cryptography import x509
  36. from cryptography.hazmat.backends.openssl import backend as openssl_backend
  37. from cryptography.hazmat.backends.openssl.x509 import _Certificate
  38. try:
  39. from cryptography.x509 import UnsupportedExtension
  40. except ImportError:
  41. # UnsupportedExtension is gone in cryptography >= 2.1.0
  42. class UnsupportedExtension(Exception):
  43. pass
  44. from socket import timeout, error as SocketError
  45. from io import BytesIO
  46. try: # Platform-specific: Python 2
  47. from socket import _fileobject
  48. except ImportError: # Platform-specific: Python 3
  49. _fileobject = None
  50. from ..packages.backports.makefile import backport_makefile
  51. import logging
  52. import ssl
  53. from ..packages import six
  54. import sys
  55. from .. import util
  56. __all__ = ['inject_into_urllib3', 'extract_from_urllib3']
  57. # SNI always works.
  58. HAS_SNI = True
  59. # Map from urllib3 to PyOpenSSL compatible parameter-values.
  60. _openssl_versions = {
  61. ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
  62. ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
  63. }
  64. if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):
  65. _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
  66. if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):
  67. _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
  68. try:
  69. _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})
  70. except AttributeError:
  71. pass
  72. _stdlib_to_openssl_verify = {
  73. ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
  74. ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
  75. ssl.CERT_REQUIRED:
  76. OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
  77. }
  78. _openssl_to_stdlib_verify = dict(
  79. (v, k) for k, v in _stdlib_to_openssl_verify.items()
  80. )
  81. # OpenSSL will only write 16K at a time
  82. SSL_WRITE_BLOCKSIZE = 16384
  83. orig_util_HAS_SNI = util.HAS_SNI
  84. orig_util_SSLContext = util.ssl_.SSLContext
  85. log = logging.getLogger(__name__)
  86. def inject_into_urllib3():
  87. 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
  88. _validate_dependencies_met()
  89. util.ssl_.SSLContext = PyOpenSSLContext
  90. util.HAS_SNI = HAS_SNI
  91. util.ssl_.HAS_SNI = HAS_SNI
  92. util.IS_PYOPENSSL = True
  93. util.ssl_.IS_PYOPENSSL = True
  94. def extract_from_urllib3():
  95. 'Undo monkey-patching by :func:`inject_into_urllib3`.'
  96. util.ssl_.SSLContext = orig_util_SSLContext
  97. util.HAS_SNI = orig_util_HAS_SNI
  98. util.ssl_.HAS_SNI = orig_util_HAS_SNI
  99. util.IS_PYOPENSSL = False
  100. util.ssl_.IS_PYOPENSSL = False
  101. def _validate_dependencies_met():
  102. """
  103. Verifies that PyOpenSSL's package-level dependencies have been met.
  104. Throws `ImportError` if they are not met.
  105. """
  106. # Method added in `cryptography==1.1`; not available in older versions
  107. from cryptography.x509.extensions import Extensions
  108. if getattr(Extensions, "get_extension_for_class", None) is None:
  109. raise ImportError("'cryptography' module missing required functionality. "
  110. "Try upgrading to v1.3.4 or newer.")
  111. # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
  112. # attribute is only present on those versions.
  113. from OpenSSL.crypto import X509
  114. x509 = X509()
  115. if getattr(x509, "_x509", None) is None:
  116. raise ImportError("'pyOpenSSL' module missing required functionality. "
  117. "Try upgrading to v0.14 or newer.")
  118. def _dnsname_to_stdlib(name):
  119. """
  120. Converts a dNSName SubjectAlternativeName field to the form used by the
  121. standard library on the given Python version.
  122. Cryptography produces a dNSName as a unicode string that was idna-decoded
  123. from ASCII bytes. We need to idna-encode that string to get it back, and
  124. then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
  125. uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
  126. If the name cannot be idna-encoded then we return None signalling that
  127. the name given should be skipped.
  128. """
  129. def idna_encode(name):
  130. """
  131. Borrowed wholesale from the Python Cryptography Project. It turns out
  132. that we can't just safely call `idna.encode`: it can explode for
  133. wildcard names. This avoids that problem.
  134. """
  135. import idna
  136. try:
  137. for prefix in [u'*.', u'.']:
  138. if name.startswith(prefix):
  139. name = name[len(prefix):]
  140. return prefix.encode('ascii') + idna.encode(name)
  141. return idna.encode(name)
  142. except idna.core.IDNAError:
  143. return None
  144. name = idna_encode(name)
  145. if name is None:
  146. return None
  147. elif sys.version_info >= (3, 0):
  148. name = name.decode('utf-8')
  149. return name
  150. def get_subj_alt_name(peer_cert):
  151. """
  152. Given an PyOpenSSL certificate, provides all the subject alternative names.
  153. """
  154. # Pass the cert to cryptography, which has much better APIs for this.
  155. if hasattr(peer_cert, "to_cryptography"):
  156. cert = peer_cert.to_cryptography()
  157. else:
  158. # This is technically using private APIs, but should work across all
  159. # relevant versions before PyOpenSSL got a proper API for this.
  160. cert = _Certificate(openssl_backend, peer_cert._x509)
  161. # We want to find the SAN extension. Ask Cryptography to locate it (it's
  162. # faster than looping in Python)
  163. try:
  164. ext = cert.extensions.get_extension_for_class(
  165. x509.SubjectAlternativeName
  166. ).value
  167. except x509.ExtensionNotFound:
  168. # No such extension, return the empty list.
  169. return []
  170. except (x509.DuplicateExtension, UnsupportedExtension,
  171. x509.UnsupportedGeneralNameType, UnicodeError) as e:
  172. # A problem has been found with the quality of the certificate. Assume
  173. # no SAN field is present.
  174. log.warning(
  175. "A problem was encountered with the certificate that prevented "
  176. "urllib3 from finding the SubjectAlternativeName field. This can "
  177. "affect certificate validation. The error was %s",
  178. e,
  179. )
  180. return []
  181. # We want to return dNSName and iPAddress fields. We need to cast the IPs
  182. # back to strings because the match_hostname function wants them as
  183. # strings.
  184. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
  185. # decoded. This is pretty frustrating, but that's what the standard library
  186. # does with certificates, and so we need to attempt to do the same.
  187. # We also want to skip over names which cannot be idna encoded.
  188. names = [
  189. ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
  190. if name is not None
  191. ]
  192. names.extend(
  193. ('IP Address', str(name))
  194. for name in ext.get_values_for_type(x509.IPAddress)
  195. )
  196. return names
  197. class WrappedSocket(object):
  198. '''API-compatibility wrapper for Python OpenSSL's Connection-class.
  199. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
  200. collector of pypy.
  201. '''
  202. def __init__(self, connection, socket, suppress_ragged_eofs=True):
  203. self.connection = connection
  204. self.socket = socket
  205. self.suppress_ragged_eofs = suppress_ragged_eofs
  206. self._makefile_refs = 0
  207. self._closed = False
  208. def fileno(self):
  209. return self.socket.fileno()
  210. # Copy-pasted from Python 3.5 source code
  211. def _decref_socketios(self):
  212. if self._makefile_refs > 0:
  213. self._makefile_refs -= 1
  214. if self._closed:
  215. self.close()
  216. def recv(self, *args, **kwargs):
  217. try:
  218. data = self.connection.recv(*args, **kwargs)
  219. except OpenSSL.SSL.SysCallError as e:
  220. if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
  221. return b''
  222. else:
  223. raise SocketError(str(e))
  224. except OpenSSL.SSL.ZeroReturnError as e:
  225. if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
  226. return b''
  227. else:
  228. raise
  229. except OpenSSL.SSL.WantReadError:
  230. if not util.wait_for_read(self.socket, self.socket.gettimeout()):
  231. raise timeout('The read operation timed out')
  232. else:
  233. return self.recv(*args, **kwargs)
  234. else:
  235. return data
  236. def recv_into(self, *args, **kwargs):
  237. try:
  238. return self.connection.recv_into(*args, **kwargs)
  239. except OpenSSL.SSL.SysCallError as e:
  240. if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
  241. return 0
  242. else:
  243. raise SocketError(str(e))
  244. except OpenSSL.SSL.ZeroReturnError as e:
  245. if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
  246. return 0
  247. else:
  248. raise
  249. except OpenSSL.SSL.WantReadError:
  250. if not util.wait_for_read(self.socket, self.socket.gettimeout()):
  251. raise timeout('The read operation timed out')
  252. else:
  253. return self.recv_into(*args, **kwargs)
  254. def settimeout(self, timeout):
  255. return self.socket.settimeout(timeout)
  256. def _send_until_done(self, data):
  257. while True:
  258. try:
  259. return self.connection.send(data)
  260. except OpenSSL.SSL.WantWriteError:
  261. if not util.wait_for_write(self.socket, self.socket.gettimeout()):
  262. raise timeout()
  263. continue
  264. except OpenSSL.SSL.SysCallError as e:
  265. raise SocketError(str(e))
  266. def sendall(self, data):
  267. total_sent = 0
  268. while total_sent < len(data):
  269. sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
  270. total_sent += sent
  271. def shutdown(self):
  272. # FIXME rethrow compatible exceptions should we ever use this
  273. self.connection.shutdown()
  274. def close(self):
  275. if self._makefile_refs < 1:
  276. try:
  277. self._closed = True
  278. return self.connection.close()
  279. except OpenSSL.SSL.Error:
  280. return
  281. else:
  282. self._makefile_refs -= 1
  283. def getpeercert(self, binary_form=False):
  284. x509 = self.connection.get_peer_certificate()
  285. if not x509:
  286. return x509
  287. if binary_form:
  288. return OpenSSL.crypto.dump_certificate(
  289. OpenSSL.crypto.FILETYPE_ASN1,
  290. x509)
  291. return {
  292. 'subject': (
  293. (('commonName', x509.get_subject().CN),),
  294. ),
  295. 'subjectAltName': get_subj_alt_name(x509)
  296. }
  297. def _reuse(self):
  298. self._makefile_refs += 1
  299. def _drop(self):
  300. if self._makefile_refs < 1:
  301. self.close()
  302. else:
  303. self._makefile_refs -= 1
  304. if _fileobject: # Platform-specific: Python 2
  305. def makefile(self, mode, bufsize=-1):
  306. self._makefile_refs += 1
  307. return _fileobject(self, mode, bufsize, close=True)
  308. else: # Platform-specific: Python 3
  309. makefile = backport_makefile
  310. WrappedSocket.makefile = makefile
  311. class PyOpenSSLContext(object):
  312. """
  313. I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
  314. for translating the interface of the standard library ``SSLContext`` object
  315. to calls into PyOpenSSL.
  316. """
  317. def __init__(self, protocol):
  318. self.protocol = _openssl_versions[protocol]
  319. self._ctx = OpenSSL.SSL.Context(self.protocol)
  320. self._options = 0
  321. self.check_hostname = False
  322. @property
  323. def options(self):
  324. return self._options
  325. @options.setter
  326. def options(self, value):
  327. self._options = value
  328. self._ctx.set_options(value)
  329. @property
  330. def verify_mode(self):
  331. return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
  332. @verify_mode.setter
  333. def verify_mode(self, value):
  334. self._ctx.set_verify(
  335. _stdlib_to_openssl_verify[value],
  336. _verify_callback
  337. )
  338. def set_default_verify_paths(self):
  339. self._ctx.set_default_verify_paths()
  340. def set_ciphers(self, ciphers):
  341. if isinstance(ciphers, six.text_type):
  342. ciphers = ciphers.encode('utf-8')
  343. self._ctx.set_cipher_list(ciphers)
  344. def load_verify_locations(self, cafile=None, capath=None, cadata=None):
  345. if cafile is not None:
  346. cafile = cafile.encode('utf-8')
  347. if capath is not None:
  348. capath = capath.encode('utf-8')
  349. self._ctx.load_verify_locations(cafile, capath)
  350. if cadata is not None:
  351. self._ctx.load_verify_locations(BytesIO(cadata))
  352. def load_cert_chain(self, certfile, keyfile=None, password=None):
  353. self._ctx.use_certificate_chain_file(certfile)
  354. if password is not None:
  355. self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password)
  356. self._ctx.use_privatekey_file(keyfile or certfile)
  357. def wrap_socket(self, sock, server_side=False,
  358. do_handshake_on_connect=True, suppress_ragged_eofs=True,
  359. server_hostname=None):
  360. cnx = OpenSSL.SSL.Connection(self._ctx, sock)
  361. if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3
  362. server_hostname = server_hostname.encode('utf-8')
  363. if server_hostname is not None:
  364. cnx.set_tlsext_host_name(server_hostname)
  365. cnx.set_connect_state()
  366. while True:
  367. try:
  368. cnx.do_handshake()
  369. except OpenSSL.SSL.WantReadError:
  370. if not util.wait_for_read(sock, sock.gettimeout()):
  371. raise timeout('select timed out')
  372. continue
  373. except OpenSSL.SSL.Error as e:
  374. raise ssl.SSLError('bad handshake: %r' % e)
  375. break
  376. return WrappedSocket(cnx, sock)
  377. def _verify_callback(cnx, x509, err_no, err_depth, return_code):
  378. return err_no == 0