Plex plugin to to play various online streams (mostly Latvian).

ssl_.py 11KB

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