pyopenssl.py 15 KB

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