Development of an internal social media platform with personalised dashboards for students
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.

pyopenssl.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. """
  127. def idna_encode(name):
  128. """
  129. Borrowed wholesale from the Python Cryptography Project. It turns out
  130. that we can't just safely call `idna.encode`: it can explode for
  131. wildcard names. This avoids that problem.
  132. """
  133. from pip._vendor import idna
  134. for prefix in [u'*.', u'.']:
  135. if name.startswith(prefix):
  136. name = name[len(prefix):]
  137. return prefix.encode('ascii') + idna.encode(name)
  138. return idna.encode(name)
  139. name = idna_encode(name)
  140. if sys.version_info >= (3, 0):
  141. name = name.decode('utf-8')
  142. return name
  143. def get_subj_alt_name(peer_cert):
  144. """
  145. Given an PyOpenSSL certificate, provides all the subject alternative names.
  146. """
  147. # Pass the cert to cryptography, which has much better APIs for this.
  148. if hasattr(peer_cert, "to_cryptography"):
  149. cert = peer_cert.to_cryptography()
  150. else:
  151. # This is technically using private APIs, but should work across all
  152. # relevant versions before PyOpenSSL got a proper API for this.
  153. cert = _Certificate(openssl_backend, peer_cert._x509)
  154. # We want to find the SAN extension. Ask Cryptography to locate it (it's
  155. # faster than looping in Python)
  156. try:
  157. ext = cert.extensions.get_extension_for_class(
  158. x509.SubjectAlternativeName
  159. ).value
  160. except x509.ExtensionNotFound:
  161. # No such extension, return the empty list.
  162. return []
  163. except (x509.DuplicateExtension, UnsupportedExtension,
  164. x509.UnsupportedGeneralNameType, UnicodeError) as e:
  165. # A problem has been found with the quality of the certificate. Assume
  166. # no SAN field is present.
  167. log.warning(
  168. "A problem was encountered with the certificate that prevented "
  169. "urllib3 from finding the SubjectAlternativeName field. This can "
  170. "affect certificate validation. The error was %s",
  171. e,
  172. )
  173. return []
  174. # We want to return dNSName and iPAddress fields. We need to cast the IPs
  175. # back to strings because the match_hostname function wants them as
  176. # strings.
  177. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
  178. # decoded. This is pretty frustrating, but that's what the standard library
  179. # does with certificates, and so we need to attempt to do the same.
  180. names = [
  181. ('DNS', _dnsname_to_stdlib(name))
  182. for name in ext.get_values_for_type(x509.DNSName)
  183. ]
  184. names.extend(
  185. ('IP Address', str(name))
  186. for name in ext.get_values_for_type(x509.IPAddress)
  187. )
  188. return names
  189. class WrappedSocket(object):
  190. '''API-compatibility wrapper for Python OpenSSL's Connection-class.
  191. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
  192. collector of pypy.
  193. '''
  194. def __init__(self, connection, socket, suppress_ragged_eofs=True):
  195. self.connection = connection
  196. self.socket = socket
  197. self.suppress_ragged_eofs = suppress_ragged_eofs
  198. self._makefile_refs = 0
  199. self._closed = False
  200. def fileno(self):
  201. return self.socket.fileno()
  202. # Copy-pasted from Python 3.5 source code
  203. def _decref_socketios(self):
  204. if self._makefile_refs > 0:
  205. self._makefile_refs -= 1
  206. if self._closed:
  207. self.close()
  208. def recv(self, *args, **kwargs):
  209. try:
  210. data = self.connection.recv(*args, **kwargs)
  211. except OpenSSL.SSL.SysCallError as e:
  212. if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
  213. return b''
  214. else:
  215. raise SocketError(str(e))
  216. except OpenSSL.SSL.ZeroReturnError as e:
  217. if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
  218. return b''
  219. else:
  220. raise
  221. except OpenSSL.SSL.WantReadError:
  222. if not util.wait_for_read(self.socket, self.socket.gettimeout()):
  223. raise timeout('The read operation timed out')
  224. else:
  225. return self.recv(*args, **kwargs)
  226. else:
  227. return data
  228. def recv_into(self, *args, **kwargs):
  229. try:
  230. return self.connection.recv_into(*args, **kwargs)
  231. except OpenSSL.SSL.SysCallError as e:
  232. if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
  233. return 0
  234. else:
  235. raise SocketError(str(e))
  236. except OpenSSL.SSL.ZeroReturnError as e:
  237. if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
  238. return 0
  239. else:
  240. raise
  241. except OpenSSL.SSL.WantReadError:
  242. if not util.wait_for_read(self.socket, self.socket.gettimeout()):
  243. raise timeout('The read operation timed out')
  244. else:
  245. return self.recv_into(*args, **kwargs)
  246. def settimeout(self, timeout):
  247. return self.socket.settimeout(timeout)
  248. def _send_until_done(self, data):
  249. while True:
  250. try:
  251. return self.connection.send(data)
  252. except OpenSSL.SSL.WantWriteError:
  253. if not util.wait_for_write(self.socket, self.socket.gettimeout()):
  254. raise timeout()
  255. continue
  256. except OpenSSL.SSL.SysCallError as e:
  257. raise SocketError(str(e))
  258. def sendall(self, data):
  259. total_sent = 0
  260. while total_sent < len(data):
  261. sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
  262. total_sent += sent
  263. def shutdown(self):
  264. # FIXME rethrow compatible exceptions should we ever use this
  265. self.connection.shutdown()
  266. def close(self):
  267. if self._makefile_refs < 1:
  268. try:
  269. self._closed = True
  270. return self.connection.close()
  271. except OpenSSL.SSL.Error:
  272. return
  273. else:
  274. self._makefile_refs -= 1
  275. def getpeercert(self, binary_form=False):
  276. x509 = self.connection.get_peer_certificate()
  277. if not x509:
  278. return x509
  279. if binary_form:
  280. return OpenSSL.crypto.dump_certificate(
  281. OpenSSL.crypto.FILETYPE_ASN1,
  282. x509)
  283. return {
  284. 'subject': (
  285. (('commonName', x509.get_subject().CN),),
  286. ),
  287. 'subjectAltName': get_subj_alt_name(x509)
  288. }
  289. def _reuse(self):
  290. self._makefile_refs += 1
  291. def _drop(self):
  292. if self._makefile_refs < 1:
  293. self.close()
  294. else:
  295. self._makefile_refs -= 1
  296. if _fileobject: # Platform-specific: Python 2
  297. def makefile(self, mode, bufsize=-1):
  298. self._makefile_refs += 1
  299. return _fileobject(self, mode, bufsize, close=True)
  300. else: # Platform-specific: Python 3
  301. makefile = backport_makefile
  302. WrappedSocket.makefile = makefile
  303. class PyOpenSSLContext(object):
  304. """
  305. I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
  306. for translating the interface of the standard library ``SSLContext`` object
  307. to calls into PyOpenSSL.
  308. """
  309. def __init__(self, protocol):
  310. self.protocol = _openssl_versions[protocol]
  311. self._ctx = OpenSSL.SSL.Context(self.protocol)
  312. self._options = 0
  313. self.check_hostname = False
  314. @property
  315. def options(self):
  316. return self._options
  317. @options.setter
  318. def options(self, value):
  319. self._options = value
  320. self._ctx.set_options(value)
  321. @property
  322. def verify_mode(self):
  323. return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
  324. @verify_mode.setter
  325. def verify_mode(self, value):
  326. self._ctx.set_verify(
  327. _stdlib_to_openssl_verify[value],
  328. _verify_callback
  329. )
  330. def set_default_verify_paths(self):
  331. self._ctx.set_default_verify_paths()
  332. def set_ciphers(self, ciphers):
  333. if isinstance(ciphers, six.text_type):
  334. ciphers = ciphers.encode('utf-8')
  335. self._ctx.set_cipher_list(ciphers)
  336. def load_verify_locations(self, cafile=None, capath=None, cadata=None):
  337. if cafile is not None:
  338. cafile = cafile.encode('utf-8')
  339. if capath is not None:
  340. capath = capath.encode('utf-8')
  341. self._ctx.load_verify_locations(cafile, capath)
  342. if cadata is not None:
  343. self._ctx.load_verify_locations(BytesIO(cadata))
  344. def load_cert_chain(self, certfile, keyfile=None, password=None):
  345. self._ctx.use_certificate_chain_file(certfile)
  346. if password is not None:
  347. self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password)
  348. self._ctx.use_privatekey_file(keyfile or certfile)
  349. def wrap_socket(self, sock, server_side=False,
  350. do_handshake_on_connect=True, suppress_ragged_eofs=True,
  351. server_hostname=None):
  352. cnx = OpenSSL.SSL.Connection(self._ctx, sock)
  353. if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3
  354. server_hostname = server_hostname.encode('utf-8')
  355. if server_hostname is not None:
  356. cnx.set_tlsext_host_name(server_hostname)
  357. cnx.set_connect_state()
  358. while True:
  359. try:
  360. cnx.do_handshake()
  361. except OpenSSL.SSL.WantReadError:
  362. if not util.wait_for_read(sock, sock.gettimeout()):
  363. raise timeout('select timed out')
  364. continue
  365. except OpenSSL.SSL.Error as e:
  366. raise ssl.SSLError('bad handshake: %r' % e)
  367. break
  368. return WrappedSocket(cnx, sock)
  369. def _verify_callback(cnx, x509, err_no, err_depth, return_code):
  370. return err_no == 0