Skip to content
Myr

Update urllib3 to 10b7a0fefa6596f47a9a6afc80f1f4d1ae950b66

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Ian Cordasco · committed by Ian Cordasco · parent 1f0e577 · Browse files · 8 files+146 added−61 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+146 added−61 removed

  • other:+146 added−61 removed

8 files+146 added−61 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-19 removed
36 unmodified lines
37Module Variables38----------------3940:var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.41 Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:42 ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``4142.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44
37 unmodified lines
82 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,84}8588# A secure default.89# Sources for more information on TLS ciphers:90#91# - https://wiki.mozilla.org/Security/Server_Side_TLS92# - https://www.ssllabs.com/projects/best-practices/index.html93# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/94#95# The general intent is:96# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),97# - prefer ECDHE over DHE for better performance,98# - prefer any AES-GCM over any AES-CBC for better performance and security,99# - use 3DES as fallback which is secure but slow,100# - disable NULL authentication, MD5 MACs and DSS for security reasons.101DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \102 "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \103 "!aNULL:!MD5:!DSS"86DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS878889orig_util_HAS_SNI = util.HAS_SNI90orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket
190 unmodified lines
281 while True:282 try:283 cnx.do_handshake()284 except OpenSSL.SSL.WantReadError:302 select.select([sock], [], [])285 rd, _, _ = select.select([sock], [], [], sock.gettimeout())286 if not rd:287 raise timeout('select timed out')288 continue289 except OpenSSL.SSL.Error as e:290 raise ssl.SSLError('bad handshake', e)291 break
2 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+26 added-12 removed
7 unmodified lines
8HAS_SNI = False9create_default_context = None1011import errno12import ssl12import warnings1314try: # Test for SSL features15 import ssl16 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2317 from ssl import HAS_SNI # Has SNI?18except ImportError:19 pass
4 unmodified lines
24except ImportError:25 OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000026 OP_NO_COMPRESSION = 0x200002728# A secure default.29# Sources for more information on TLS ciphers:30#31# - https://wiki.mozilla.org/Security/Server_Side_TLS32# - https://www.ssllabs.com/projects/best-practices/index.html33# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/34#35# The general intent is:36# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),37# - prefer ECDHE over DHE for better performance,28try:29 from ssl import _DEFAULT_CIPHERS30except ImportError:31 _DEFAULT_CIPHERS = (32 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'33 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'34 '!eNULL:!MD5'35 )38# - prefer any AES-GCM over any AES-CBC for better performance and security,39# - use 3DES as fallback which is secure but slow,40# - disable NULL authentication, MD5 MACs and DSS for security reasons.41DEFAULT_CIPHERS = (42 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'43 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'44 '!eNULL:!MD5'45)4647try:48 from ssl import SSLContext # Modern SSL?49except ImportError:50 import sys5152 class SSLContext(object): # Platform-specific: Python 2 & 3.143 supports_set_ciphers = sys.version_info >= (2, 7)53 supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or54 (3, 2) <= sys.version_info)5556 def __init__(self, protocol_version):57 self.protocol = protocol_version58 # Use default values from a real SSLContext
118 unmodified lines
177178 return candidate179180170def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,181def create_urllib3_context(ssl_version=None, cert_reqs=None,182 options=None, ciphers=None):183 """All arguments have the same meaning as ``ssl_wrap_socket``.184185 By default, this function does a lot of the same work that
28 unmodified lines
214 :rtype: SSLContext215 """216 context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)217218 # Setting the default here, as we may have no ssl module on import219 cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs220221 if options is None:222 options = 0223 # SSLv2 is easily broken and is considered harmful and dangerous224 options |= OP_NO_SSLv2
5 unmodified lines
230231 context.options |= options232233 if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6220 context.set_ciphers(ciphers or _DEFAULT_CIPHERS)234 context.set_ciphers(ciphers or DEFAULT_CIPHERS)235236 context.verify_mode = cert_reqs237 if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2238 # We do our own verification, including fingerprints and alternative
42 unmodified lines
modified:requests/packages/urllib3/__init__.py+3 added-1 removed
53 unmodified lines
54# ... Clean up.55del NullHandler565758# Set security warning to always go off by default.58import warnings59# SecurityWarning's always go off by default.60warnings.simplefilter('always', exceptions.SecurityWarning)61# InsecurePlatformWarning's don't vary between requests, so we keep it default.62warnings.simplefilter('default', exceptions.InsecurePlatformWarning)6364def disable_warnings(category=exceptions.HTTPWarning):65 """66 Helper for quickly disabling all urllib3 warnings.
2 unmodified lines
modified:requests/packages/urllib3/_collections.py+24 added-21 removed
225 unmodified lines
226 # vals should be a tuple then, i.e. only one item so far227 # Need to convert the tuple to list for further extension228 _dict_setitem(self, key_lower, [vals[0], vals[1], val])229230 def extend(*args, **kwargs):230 def extend(self, *args, **kwargs):231 """Generic import function for any type of header-like object.232 Adapted version of MutableMapping.update in order to insert items233 with self.add instead of self.__setitem__234 """235 if len(args) > 2:236 raise TypeError("update() takes at most 2 positional "235 if len(args) > 1:236 raise TypeError("extend() takes at most 1 positional "237 "arguments ({} given)".format(len(args)))238 elif not args:239 raise TypeError("update() takes at least 1 argument (0 given)")240 self = args[0]241 other = args[1] if len(args) >= 2 else ()238 other = args[0] if len(args) >= 1 else ()239 243 if isinstance(other, Mapping):240 if isinstance(other, HTTPHeaderDict):241 for key, val in other.iteritems():242 self.add(key, val)243 elif isinstance(other, Mapping):244 for key in other:245 self.add(key, other[key])246 elif hasattr(other, "keys"):247 for key in other.keys():
55 unmodified lines
303 def items(self):304 return list(self.iteritems())305306 @classmethod307 def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2307 def from_httplib(cls, message): # Python 2308 """Read headers from a Python 2 httplib message object."""309 ret = cls(message.items())310 # ret now contains only the last header line for each duplicate.311 # Importing with all duplicates would be nice, but this would312 # mean to repeat most of the raw parsing already done, when the313 # message object was created. Extracting only the headers of interest 314 # separately, the cookies, should be faster and requires less315 # extra code.316 for key in duplicates:317 ret.discard(key)318 for val in message.getheaders(key):319 ret.add(key, val)320 return ret309 # python2.7 does not expose a proper API for exporting multiheaders310 # efficiently. This function re-reads raw lines from the message 311 # object and extracts the multiheaders properly.312 headers = []313 314 for line in message.headers:315 if line.startswith((' ', '\t')):316 key, value = headers[-1]317 headers[-1] = (key, value + '\r\n' + line.rstrip())318 continue319 320 key, value = line.split(':', 1)321 headers.append((key, value.strip()))322323 return cls(headers)
modified:requests/packages/urllib3/connection.py+2 added
258 unmodified lines
259if ssl:260 # Make a copy for testing.261 UnverifiedHTTPSConnection = HTTPSConnection262 HTTPSConnection = VerifiedHTTPSConnection263else:264 HTTPSConnection = DummyConnection
modified:requests/packages/urllib3/connectionpool.py-1 removed
733 unmodified lines
734 log.info("Starting new HTTPS connection (%d): %s"735 % (self.num_connections, self.host))736737 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:738 # Platform-specific: Python without ssl738 raise SSLError("Can't connect to HTTPS URL because the SSL "739 "module is not available.")740741 actual_host = self.host
54 unmodified lines
modified:requests/packages/urllib3/exceptions.py+5 added
160 unmodified lines
161162class InsecurePlatformWarning(SecurityWarning):163 "Warned when certain SSL configuration is not available on a platform."164 pass165166167class ResponseNotChunked(ProtocolError, ValueError):168 "Response needs to be chunked in order to read it as chunks."169 pass
modified:requests/packages/urllib3/response.py+82 added-7 removed
1try:2 import http.client as httplib3except ImportError:4 import httplib5import zlib6import io7from socket import timeout as SocketTimeout89from ._collections import HTTPHeaderDict6from .exceptions import ProtocolError, DecodeError, ReadTimeoutError10from .exceptions import (11 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked12)13from .packages.six import string_types as basestring, binary_type, PY314from .connection import HTTPException, BaseSSLError15from .util.response import is_fp_closed16
105 unmodified lines
122123 if hasattr(body, 'read'):124 self._fp = body125120 if preload_content and not self._body:121 self._body = self.read(decode_content=decode_content)126 # Are we using the chunked-style of transfer encoding?127 self.chunked = False128 self.chunk_left = None129 tr_enc = self.headers.get('transfer-encoding', '')130 if tr_enc.lower() == "chunked":131 self.chunked = True132133 # We certainly don't want to preload content when the response is chunked.134 if not self.chunked:135 if preload_content and not self._body:136 self._body = self.read(decode_content=decode_content)137138 def get_redirect_location(self):139 """140 Should we redirect and where to?141
141 unmodified lines
283 :param decode_content:284 If True, will attempt to decode the body based on the285 'content-encoding' header.286 """287 if self.chunked:288 for line in self.read_chunked(amt):289 yield line290 else:272 while not is_fp_closed(self._fp):273 data = self.read(amt=amt, decode_content=decode_content)291 while not is_fp_closed(self._fp):292 data = self.read(amt=amt, decode_content=decode_content)293275 if data:276 yield data294 if data:295 yield data296297 @classmethod298 def from_httplib(ResponseCls, r, **response_kw):299 """
69 unmodified lines
369 return 0370 else:371 b[:len(temp)] = temp372 return len(temp)373374 def read_chunked(self, amt=None):375 # FIXME: Rewrite this method and make it a class with376 # a better structured logic.377 if not self.chunked:378 raise ResponseNotChunked("Response is not chunked. "379 "Header 'transfer-encoding: chunked' is missing.")380 while True:381 # First, we'll figure out length of a chunk and then382 # we'll try to read it from socket.383 if self.chunk_left is None:384 line = self._fp.fp.readline()385 line = line.decode()386 # See RFC 7230: Chunked Transfer Coding.387 i = line.find(';')388 if i >= 0:389 line = line[:i] # Strip chunk-extensions.390 try:391 self.chunk_left = int(line, 16)392 except ValueError:393 # Invalid chunked protocol response, abort.394 self.close()395 raise httplib.IncompleteRead(''.join(line))396 if self.chunk_left == 0:397 break398 if amt is None:399 chunk = self._fp._safe_read(self.chunk_left)400 yield chunk401 self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.402 self.chunk_left = None403 elif amt < self.chunk_left:404 value = self._fp._safe_read(amt)405 self.chunk_left = self.chunk_left - amt406 yield value407 elif amt == self.chunk_left:408 value = self._fp._safe_read(amt)409 self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.410 self.chunk_left = None411 yield value412 else: # amt > self.chunk_left413 yield self._fp._safe_read(self.chunk_left)414 self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.415 self.chunk_left = None416417 # Chunk content ends with \r\n: discard it.418 while True:419 line = self._fp.fp.readline()420 if not line:421 # Some sites may not end with '\r\n'.422 break423 if line == b'\r\n':424 break425426 # We read everything; close the "file".427 self.release_conn()428