Skip to content
Myr

Merge pull request #2556 from sigmavirus24/release/2.6.1

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

Prepare v2.6.1

authored by Ian Cordasco · committed by Ian Cordasco · parents 1f0e577, ae7c28e · Browse files · 11 files+172 added−169 removed
This commit

State

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

Diff stats

11 files+172 added−169 removed

  • other:+172 added−169 removed

11 files+172 added−169 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+4 added-2 removed
2 unmodified lines
3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = '1.10.2'7__version__ = '1.10.3'8910from .connectionpool import (11 HTTPConnectionPool,
42 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
modified:requests/packages/__init__.py+1 added-105 removed
1"""2Copyright (c) Donald Stufft, pip, and individual contributors34Permission is hereby granted, free of charge, to any person obtaining5a copy of this software and associated documentation files (the6"Software"), to deal in the Software without restriction, including7without limitation the rights to use, copy, modify, merge, publish,8distribute, sublicense, and/or sell copies of the Software, and to9permit persons to whom the Software is furnished to do so, subject to10the following conditions:1112The above copyright notice and this permission notice shall be13included in all copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE19LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION20OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION21WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.22"""1from __future__ import absolute_import225import sys262728class VendorAlias(object):2930 def __init__(self, package_names):31 self._package_names = package_names32 self._vendor_name = __name__33 self._vendor_pkg = self._vendor_name + "."34 self._vendor_pkgs = [35 self._vendor_pkg + name for name in self._package_names36 ]3738 def find_module(self, fullname, path=None):39 if fullname.startswith(self._vendor_pkg):40 return self4142 def load_module(self, name):43 # Ensure that this only works for the vendored name44 if not name.startswith(self._vendor_pkg):45 raise ImportError(46 "Cannot import %s, must be a subpackage of '%s'." % (47 name, self._vendor_name,48 )49 )5051 if not (name == self._vendor_name or52 any(name.startswith(pkg) for pkg in self._vendor_pkgs)):53 raise ImportError(54 "Cannot import %s, must be one of %s." % (55 name, self._vendor_pkgs56 )57 )5859 # Check to see if we already have this item in sys.modules, if we do60 # then simply return that.61 if name in sys.modules:62 return sys.modules[name]6364 # Check to see if we can import the vendor name65 try:66 # We do this dance here because we want to try and import this67 # module without hitting a recursion error because of a bunch of68 # VendorAlias instances on sys.meta_path69 real_meta_path = sys.meta_path[:]70 try:71 sys.meta_path = [72 m for m in sys.meta_path73 if not isinstance(m, VendorAlias)74 ]75 __import__(name)76 module = sys.modules[name]77 finally:78 # Re-add any additions to sys.meta_path that were made while79 # during the import we just did, otherwise things like80 # requests.packages.urllib3.poolmanager will fail.81 for m in sys.meta_path:82 if m not in real_meta_path:83 real_meta_path.append(m)8485 # Restore sys.meta_path with any new items.86 sys.meta_path = real_meta_path87 except ImportError:88 # We can't import the vendor name, so we'll try to import the89 # "real" name.90 real_name = name[len(self._vendor_pkg):]91 try:92 __import__(real_name)93 module = sys.modules[real_name]94 except ImportError:95 raise ImportError("No module named '%s'" % (name,))9697 # If we've gotten here we've found the module we're looking for, either98 # as part of our vendored package, or as the real name, so we'll add99 # it to sys.modules as the vendored name so that we don't have to do100 # the lookup again.101 sys.modules[name] = module102103 # Finally, return the loaded module104 return module105106107sys.meta_path.insert(0, VendorAlias(["urllib3", "chardet"]))3from . import urllib3
modified:requests/__init__.py+2 added-2 removed
40 unmodified lines
4142"""4344__title__ = 'requests'45__version__ = '2.6.0'46__build__ = 0x02060045__version__ = '2.6.1'46__build__ = 0x02060147__author__ = 'Kenneth Reitz'48__license__ = 'Apache 2.0'49__copyright__ = 'Copyright 2015 Kenneth Reitz'50
27 unmodified lines
modified:HISTORY.rst+22 added
1 unmodified line
23Release History4---------------562.6.1 (2015-04-22)7++++++++++++++++++89**Bugfixes**1011- Remove VendorAlias import machinery introduced in v2.5.2.1213- Simplify the PreparedRequest.prepare API: We no longer require the user to14 pass an empty list to the hooks keyword argument. (c.f. #2552)1516- Resolve redirects now receives and forwards all of the original arguments to17 the adapter. (#2503)1819- Handle UnicodeDecodeErrors when trying to deal with a unicode URL that20 cannot be encoded in ASCII. (#2540)2122- Populate the parsed path of the URI field when performing Digest23 Authentication. (#2426)2425- Copy a PreparedRequest's CookieJar more reliably when it is not an instance26 of RequestsCookieJar. (#2527)27282.6.0 (2015-03-14)29++++++++++++++++++3031**Bugfixes**
980 unmodified lines