pyopenssl.py 17 KB

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