jellyfin-kodi/resources/lib/libraries/requests/packages/urllib3/util/ssl_.py
angelblue05 bab67ddf9b
Version 4.0.0 (#182)
* Adjust refresh behavior

* Fix favorites

* Add option to mask info

* Fix keymap delete

* Fix empty show

* Version bump 3.1.14

* Reset rescan flag

* Fix subtitles encoding

* Fix path verification

* Fix update library

Plug in remove library percentage

* Fix unauthorized behavior

Reprompt user with login

* Fix series pooling

* Version bump 3.1.15

* Fix for additional users

Return all users, not just public users

* Fix http potential errors

Prevent from going further if {server} or {userid} is requested but not filled to avoid 401 errors

* Fix extra fanart

* Fix patch

make a case insensitive search

* Version bump 3.1.16

Additional logging, fix kodi source.

* Fix library tags on update

* Version bump 3.1.17

* Fix season artwork

* Fix season artwork

* Fix logging

* Fix blank files sources

* Add backup option

* Fix userdata song

* Transfer data.txt to data.json

Use default port for webserver caching

* Fix mixed content shortcut

* Fix path encoding for patch

Hopefully this works...

* Fix source nonetype error

Just incase, wrap in a try/except because it's not important.

* Base fast sync on server time

Try to fix music video refresh to prevent cursor from moving up.

* Prep subfolders for dynamic

Support homevideos for now

* Fix empty artist, missing Title

* Version bump 3.1.18a

* Version bump for objects

171076013

* Notify user of large updates

Give option to back out if the user wants to manually update the libraries

* Fix sources.xml verification

* Prevent error in monitor

Put in place try/except in case data is None

* Remember sync position for manual triggers

Allow to resume sync on restart for manual user triggers (update, repair). Automatically refresh boxsets if movie library is selected.

use waitForAbort and emby_should_stop prop to terminate threads

* Update string for sync later

* Add subfolders for dynamic movies

* Small fixes

* Version bump 3.1.19

* Fix fast sync

try/except, default back to previous behavior.

* Fix artwork

* Change settings name

To ensure it takes default value instead of previous value set in 3.0.34

* Fix transcode

flac and live tv

* Fix episodes for series pooling

* Add live tv support

* Version bump 3.1.20

* Revert "Small fixes"

This reverts commit 9ec1fa3585.

* Version bump 3.1.21

* Fix playback starting server connection instance

* Fix show update

* Fix boxsets

* Fix lastplayed

* Patch to support pre 3.6 libraries

* Fix slowness

* Plug in settings for threading

* Plug in settings for threading

* Adjust sleep behavior

* Version bump 3.1.22

* Fix server detection in monitor

* Version bump 3.1.23

* Fix potential error with checksum

* Fix missing new artists

* Fix library sync

Adjust lock, re-add screensaver deactivated during sync, prep compare sync, stop library updates from being processed before startup sync is completed

* Version bump 3.1.25

* Fix local trailers

* Adjust lock modification

* Check db version

* Prevent error from creating nodes

The addon automatically creates nodes at startup with prefilled information. Prevent errors in the event something goes wrong. It will fix itself down the line, after user has logged in.

* Version bump 3.1.26

* Revert "Version bump 3.1.26"

This reverts commit c583a69a4b.

* Fix screensaver toggle

* Fix source selection for direct stream

* Version bump 3.1.26

* Add progress for updates

* Revise progress bar

Fix typos and subsetting

* content notification

* Remove content with update library

Now remove irrelevant content as well

* Fix slowness

* Version bump 3.1.27

* Stop trying to get items if server offline

* Fix content type for dynamic music

* Fix resume sync

Now save progress, unless exited due to path validation

* Fix artwork for shortcuts on profile switch

* Add force transcode settings

* Fix audiobooks back to video type

Add shortcuts. Audiobook can't be music type otherwise it break resume behavior and it won't play the right item. Has to be video type.

* Update general info

To finish, download and installation

* Update README.md

* Move welcome message to service

* Prevent patch loop

Try once, then let it go, to avoid locking user in a restart loop

* Review library threads

* Prep for audiobook transcode

Still need to implement universal for audio transcode

* Version bump 3.1.28

* Fix emby database locked

* Fix regression to welcome message

* Version bump 3.1.29

* Adjust playback

Allow direct play for http streams

* Ensure all threads are terminated correctly

* Fix empty results due to error 500

* Fix boxset refresh

* Fix resume sync behavior

Allow to complete the startup sync in the event user backs out of resume sync

* Version bump 3.1.30

* Update patch

Move patch from cache to addon_data. No longer need to restart Kodi to apply the first patch.

* Fix inital sync leading to fast sync

* Fix user settings

Due to api change in 3.6.0.55

* krypton update

* Adjust for resume settings

With .55 the resume setting is set per library. Instead query server to see if the item is played to offer delete

* Restart service upon check for updates

To reload the new objects module.

* Fix update library

Only do the compare when user selects update library, also add a restart service option in the add-on settings > advanced

* Version bump 3.1.31

* Update dependencies

* Update FR translation

* Update DE translation

* Add translation

* Support up next

* Small service adjustment

* Krypton update to support upnext

* Add a verification onwake

Somehow, Kodi can trigger OnWake without first trigger OnSleep.

* Fix loading if special char in path

* Add logging and small fixes

Prepare userdata by date modified

* Version bump 3.1.32

* Change default behavior of startup dialog

In case it is forced closed by Kodi, allow the sync to proceed

* Ensure deliveryurl is an actual url

* Update README.md

* Fix nextup

* Fix dynamic widgets

* Detect coreelect, etc

* Fix progress report

Silent RefreshProgress in websocket

* Follow emby settings for subtitles

* Version bump 3.1.33

* Add Italian translation

* Fix playback for server 3.6.0.61

* Version bump 3.1.34a

* Add silent catch for errors

* Adjust playback progress monitor

Only track progress report if the item is an emby item

* Fix subtitles not following server settings

* Add remove libraries, fix mixed libraries

* Fix live tv

For now, use transcode since direct play returns a 127.0.0.1 unusable address as the path.

* Allow live tv to direct stream

* Fix LiveTV

* Add setting to sync during playback

* Fix updates

* Fix encoding error

* Add optional rotten tomatoes option

* Version bump 3.1.35

* Fix emby connect auth string

Was preventing proper device detection when using emby connect, play to, etc.

* Add setup RT

* Fix audio/sub change

Only for addon playback

* Add developer mode

* Update patch

Check for updates + dev = forced grab from github

* Fix RT string

* Fix patch

Allow dev mode to redownload zip

* Fix patch

ugh sleep!!

* Verify patch connection

* Version bump 3.1.36

* Fix libraries being wiped

Catch errors to prevent false positive

* Add dateutil library

* Prep convert to local time

* Fix string

* Prep for multi db version support

* Fix service restart

* Add shortcut restart addon

Add notification

* Add database discovery

* Ensure previous playback terminated

* Update translation

New: Polish, Dutch Updated: German, French, Italian

* Version bump 3.1.37

* Quick fix for new library dateutil

* Catch error for dateutil

In the event the server has some weird date that can't be converted

* Version bump 3.1.38

* Fix dateutil import

* Fix db discovery

Ignore emby.db

* Version bump 3.1.39

* Add a delay if setup not completed

Avoid crash from everything loading at once.

* Fix database discovery

Add table verification + date modified verification

* Container optional playutils

* Version bump 3.1.40

* Adjust database discovery

Compare loaded vs discovered to avoid loading old databases by accident.

* Version bump 3.1.41

* Fix discovery toggle

* Version bump 3.1.42

* Add webservice for playback prep

* Fix service restart

* Version bump 3.1.43

* Update default sync indicator

Based on overall feedback

* Fix check update

* Fix if server is selected but unavailable

* Support songs without albums

* Fix encode and params

* Increase retry timeout

* Fix update generating duplicates

* Add manage libraries

Too many entries

* Fix database discovery

* Fixed transcode via context menu

* Fix context transcode

* Quiet webservice

* Update Krypton objects

* Fix database discovery prompt

* fixed video listitem issues for krypton

* load all item details for playlists

* Fix playlist

* Version bump 3.1.44

* Fix force hi10p transcoding behavior

Fixes the "Force Hi10p transcoding" option to only apply to h264 video codecs

* Clear playlist on player.onstop

* Don't clear playlist if busy spinner is active

* Fix case sensitive issue at calling the log function

* fix db stuff (#164)

* Reload objects upon initial setup

* Fix database discovery

ignore db-journal

* Update translation

German, Italian

* Use LastConnectionMode for server test

* Fix compare sync

* Version bump 3.1.45

* Ensure widgets get updated

Container.Refresh alone doesn't seem to work

* Update database discovery

* Re-add texture to database discovery

* Add option to enable/disable service

* Remove unused strings

* Fix object reload upon restart service

* Update Krypton objects

* Update translation

Dutch, Polish

* Version bump 3.1.46

* Adjust client api

* Adjust subtitles behavior

* Fix string typo

* Only run one full sync instance

Prevent user from launching multiple syncs and freezing the add-on.

* added "playlists" to wnodes

* Disable Audiobooks

Server doesn't have a set structure yet. This feature is broken atm.

* Version bump 4.0.0

* License GPL v3

* Update readme
2019-01-24 07:04:48 -06:00

317 lines
11 KiB
Python

from __future__ import absolute_import
import errno
import warnings
import hmac
from binascii import hexlify, unhexlify
from hashlib import md5, sha1, sha256
from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning
SSLContext = None
HAS_SNI = False
create_default_context = None
# Maps the length of a digest to a possible hash function producing this digest
HASHFUNC_MAP = {
32: md5,
40: sha1,
64: sha256,
}
def _const_compare_digest_backport(a, b):
"""
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
"""
result = abs(len(a) - len(b))
for l, r in zip(bytearray(a), bytearray(b)):
result |= l ^ r
return result == 0
_const_compare_digest = getattr(hmac, 'compare_digest',
_const_compare_digest_backport)
try: # Test for SSL features
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import HAS_SNI # Has SNI?
except ImportError:
pass
try:
from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION
except ImportError:
OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
OP_NO_COMPRESSION = 0x20000
# A secure default.
# Sources for more information on TLS ciphers:
#
# - https://wiki.mozilla.org/Security/Server_Side_TLS
# - https://www.ssllabs.com/projects/best-practices/index.html
# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
#
# The general intent is:
# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
# - prefer ECDHE over DHE for better performance,
# - prefer any AES-GCM over any AES-CBC for better performance and security,
# - use 3DES as fallback which is secure but slow,
# - disable NULL authentication, MD5 MACs and DSS for security reasons.
DEFAULT_CIPHERS = (
'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
'!eNULL:!MD5'
)
try:
from ssl import SSLContext # Modern SSL?
except ImportError:
import sys
class SSLContext(object): # Platform-specific: Python 2 & 3.1
supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or
(3, 2) <= sys.version_info)
def __init__(self, protocol_version):
self.protocol = protocol_version
# Use default values from a real SSLContext
self.check_hostname = False
self.verify_mode = ssl.CERT_NONE
self.ca_certs = None
self.options = 0
self.certfile = None
self.keyfile = None
self.ciphers = None
def load_cert_chain(self, certfile, keyfile):
self.certfile = certfile
self.keyfile = keyfile
def load_verify_locations(self, cafile=None, capath=None):
self.ca_certs = cafile
if capath is not None:
raise SSLError("CA directories not supported in older Pythons")
def set_ciphers(self, cipher_suite):
if not self.supports_set_ciphers:
raise TypeError(
'Your version of Python does not support setting '
'a custom cipher suite. Please upgrade to Python '
'2.7, 3.2, or later if you need this functionality.'
)
self.ciphers = cipher_suite
def wrap_socket(self, socket, server_hostname=None):
warnings.warn(
'A true SSLContext object is not available. This prevents '
'urllib3 from configuring SSL appropriately and may cause '
'certain SSL connections to fail. For more information, see '
'https://urllib3.readthedocs.org/en/latest/security.html'
'#insecureplatformwarning.',
InsecurePlatformWarning
)
kwargs = {
'keyfile': self.keyfile,
'certfile': self.certfile,
'ca_certs': self.ca_certs,
'cert_reqs': self.verify_mode,
'ssl_version': self.protocol,
}
if self.supports_set_ciphers: # Platform-specific: Python 2.7+
return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
else: # Platform-specific: Python 2.6
return wrap_socket(socket, **kwargs)
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
fingerprint = fingerprint.replace(':', '').lower()
digest_length = len(fingerprint)
hashfunc = HASHFUNC_MAP.get(digest_length)
if not hashfunc:
raise SSLError(
'Fingerprint of invalid length: {0}'.format(fingerprint))
# We need encode() here for py32; works on py2 and p33.
fingerprint_bytes = unhexlify(fingerprint.encode())
cert_digest = hashfunc(cert).digest()
if not _const_compare_digest(cert_digest, fingerprint_bytes):
raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
.format(fingerprint, hexlify(cert_digest)))
def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbrevation.
(So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
If it's neither `None` nor a string we assume it is already the numeric
constant which can directly be passed to wrap_socket.
"""
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
return candidate
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
def create_urllib3_context(ssl_version=None, cert_reqs=None,
options=None, ciphers=None):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do::
from urllib3.util import ssl_
context = ssl_.create_urllib3_context()
context.options &= ~ssl_.OP_NO_SSLv3
You can do the same to enable compression (substituting ``COMPRESSION``
for ``SSLv3`` in the last line above).
:param ssl_version:
The desired protocol version to use. This will default to
PROTOCOL_SSLv23 which will negotiate the highest protocol that both
the server and your installation of OpenSSL support.
:param cert_reqs:
Whether to require the certificate verification. This defaults to
``ssl.CERT_REQUIRED``.
:param options:
Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
:param ciphers:
Which cipher suites to allow the server to select.
:returns:
Constructed SSLContext object with specified options
:rtype: SSLContext
"""
context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
# Setting the default here, as we may have no ssl module on import
cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
if options is None:
options = 0
# SSLv2 is easily broken and is considered harmful and dangerous
options |= OP_NO_SSLv2
# SSLv3 has several problems and is now dangerous
options |= OP_NO_SSLv3
# Disable compression to prevent CRIME attacks for OpenSSL 1.0+
# (issue #309)
options |= OP_NO_COMPRESSION
context.options |= options
if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6
context.set_ciphers(ciphers or DEFAULT_CIPHERS)
context.verify_mode = cert_reqs
if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
# We do our own verification, including fingerprints and alternative
# hostnames. So disable it here
context.check_hostname = False
return context
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
"""
All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support. This is not
supported on Python 2.6 as the ssl module does not support it.
:param ca_cert_dir:
A directory containing CA certificates in multiple separate files, as
supported by OpenSSL's -CApath flag or the capath argument to
SSLContext.load_verify_locations().
"""
context = ssl_context
if context is None:
context = create_urllib3_context(ssl_version, cert_reqs,
ciphers=ciphers)
if ca_certs or ca_cert_dir:
try:
context.load_verify_locations(ca_certs, ca_cert_dir)
except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2
raise SSLError(e)
# Py33 raises FileNotFoundError which subclasses OSError
# These are not equivalent unless we check the errno attribute
except OSError as e: # Platform-specific: Python 3.3 and beyond
if e.errno == errno.ENOENT:
raise SSLError(e)
raise
if certfile:
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
warnings.warn(
'An HTTPS request has been made, but the SNI (Subject Name '
'Indication) extension to TLS is not available on this platform. '
'This may cause the server to present an incorrect TLS '
'certificate, which can cause validation failures. For more '
'information, see '
'https://urllib3.readthedocs.org/en/latest/security.html'
'#snimissingwarning.',
SNIMissingWarning
)
return context.wrap_socket(sock)